AI Logic

Architectures

TinyLlama

Updated:

TinyLlama architecture and training. Left: the overall flow (a token sequence from the same tokenizer as Llama 2, token embeddings without position embeddings, 22 decoder layers, a final RMSNorm, and next-token prediction), plus a schematic of GQA in which 32 query heads are grouped by 8 to share K and V. Upper right: inside a decoder layer (GQA self-attention with RoPE and a SwiGLU feed-forward, each with RMSNorm on the input side). Lower right: the three-stage pretraining of v1.1 (basic pretraining on SlimPajama only, branching into three continual pretraining tracks for general, code and math, and Chinese, each followed by a cooldown)

Background and overview

TinyLlama is a small open language model that scales the architecture and tokenizer of Llama 2 down to 1.1 billion (1.1B) parameters and trains it on up to 3 trillion tokens. Peiyuan Zhang and colleagues at the Singapore University of Technology and Design introduced it in 2024 in the paper "TinyLlama: An Open-Source Small Language Model," releasing everything: the training code, intermediate checkpoints, and the data processing pipeline.

There are two schools of thought on how to train large language models:

  • Optimize for training compute: The Chinchilla study found that, for a fixed compute budget, model size and the amount of training data should be scaled up in equal proportion.
  • Optimize for inference compute: LLaMA trained small models on far more tokens than Chinchilla recommends, in order to lower the cost of using them.

TinyLlama explores what happens when the latter approach is pushed to an extreme with an even smaller model. The paper states that, to the authors' knowledge, this is the first attempt to train a 1.1B-parameter model on as many as 3 trillion tokens. That amounts to reading about 2,700 times as many tokens as the model has parameters.

As a result, TinyLlama outperformed open models of similar size (OPT-1.3B, Pythia-1.0B and 1.4B) on average across seven commonsense reasoning tasks. Because the model is small, it can run on devices such as smartphones and serve as a platform for quickly testing new ideas in language modeling.

Architecture: Llama 2's components, scaled down

TinyLlama's architecture is the same Transformer decoder as Llama 2. Its components are also the same as Llama 2's; Section 2.2 of the paper lists the following four. The left of the figure at the top of the article shows the overall flow, and the upper right shows the inside of one decoder layer.

  1. RoPE for positional information: Rotates the attention queries and keys according to their positions.
  2. RMSNorm on the input side: Normalizes the input of each sublayer (the Pre-LN arrangement), to stabilize training and reduce computation.
  3. SwiGLU feed-forward: A gate passed through SiLU (Swish) scales the other branch's output element-wise.
  4. Grouped-query attention (GQA): The 32 query heads are split into 4 groups, and each group shares one key and value.

GQA (item 4) was used only in the 34B and 70B Llama 2 models. TinyLlama uses it even at 1.1B, reducing the amount of memory read and written during inference to improve speed. Since key and value heads drop from 32 to 4, the KV cache, which stores the keys and values of past tokens, shrinks to one eighth.

The architecture's dimensions are as follows (Table 1 of the paper):

ItemValue
Hidden size dd2,048
Feed-forward intermediate size5,632
Number of layers22
Number of query heads32
Number of key/value heads4
Context length2,048
Vocabulary32,000 (same tokenizer as Llama 2)

Because the architecture and tokenizer match Llama 2, much of the inference software and many quantization and fine-tuning tools built for Llama 2 can be used with TinyLlama as is. The official weights are also distributed in a form that loads with the Llama classes in Hugging Face transformers.

Training: data and speedups

The training data is a mix of natural language and code (Section 2.1 of the paper).

DataContentsPreprocessing
SlimPajamaA further filtered version of RedPajama (over 1.2 trillion tokens), a reproduction of LLaMA's training dataRemoves low-quality and duplicate data, keeping only 50% of the original; excludes the GitHub portion
StarCoder training dataCode in 86 programming languages, GitHub issues, and natural language–code pairsOnly code-related data is used

Together they total about 950 billion tokens, mixed at a ratio of roughly 7:3 SlimPajama to StarCoder. The first version (v1.0) went through this about 3 times, training on 3 trillion tokens in total.

The optimization settings (Section 2.4 of the paper) follow Llama 2:

  • Optimizer: AdamW (β1=0.9\beta_1 = 0.9, β2=0.95\beta_2 = 0.95), with weight decay of 0.1
  • Learning rate: After 2,000 steps of warmup, decays from 4.0×10−44.0 \times 10^{-4} to 4.0×10−54.0 \times 10^{-5} following a cosine schedule
  • Batch size: 2 million tokens
  • Gradients: Clipped to a norm of 1.0
  • Hardware: 16 A100 GPUs (40 GB)

Training speedups (Section 2.3 of the paper) are why 3 trillion tokens could be trained on modest hardware.

  • FSDP: Shards model parameters and other state across GPUs to train efficiently across multiple GPUs and nodes.
  • FlashAttention-2: Reduces memory reads and writes in the attention computation. In addition, fused implementations of normalization, cross-entropy, and RoPE are used.
  • SwiGLU from xFormers: Replaces SwiGLU with a fused implementation.

With these, throughput reached 24,000 tokens per second per A100. The GPU hours needed to train on 300 billion tokens are 3,456 for TinyLlama, compared with 4,830 for Pythia-1.0B and 7,920 for MPT-1.3B (Table 2 of the paper).

v1.1: three-stage pretraining

While the first version was being trained and released, bugs were found in the learning rate schedule handling and in data loading. The paper therefore fixed the bugs, retrained the model from scratch, and released it as TinyLlama v1.1 (Section 2.5 of the paper). The main changes are these three:

  • To reduce communication, FSDP parameter sharding was limited to within a single node (16 nodes of 4 A100s each, with a batch of about 1.8 million tokens).
  • The number of training tokens was reduced from 3 trillion to 2 trillion. Downstream task performance still improved slightly.
  • Pretraining was split into three stages.

The three stages are shown in the lower right of the figure at the top of the article.

  1. Basic pretraining: Trains on 1.5 trillion tokens of SlimPajama only, building the foundation for commonsense reasoning.
  2. Domain-specific continual pretraining: Branches into three datasets, each trained on 350 billion tokens. The general version uses SlimPajama only; Math&Code mixes in Python and Jupyter from StarCoder plus Proof Pile 2 (math); Chinese mixes in the Chinese Skypile corpus. The proportion of domain data is increased gradually (linearly) over the first 6 billion tokens to make the transition smooth.
  3. Cooldown: For the last 150 billion tokens, the batch is increased from 1.8 million to 7.2 million tokens.

A typical cooldown lowers the learning rate at the end of training to let the model converge (as in the final decay of WSD, for example). TinyLlama uses a cosine schedule, so its learning rate is already small near the end; it increases the batch size instead. In general, a larger batch reduces the variance of the gradient estimate, so it is thought to dampen fluctuations in the updates, much as lowering the learning rate does.

The result is three models: a general one (v1.1), v1.1 Math&Code, which is stronger at math and code, and v1.1 Chinese, which is stronger at Chinese.

When building domain-specific models, sharing the first 1.5 trillion tokens means only the 500 billion tokens after the branch point need to be trained separately for each domain. It is like sharing the prep work in cooking and changing only the final seasoning to make three dishes, which keeps total compute down.

Why train a small model on so many tokens

The question TinyLlama asks is whether a small model's performance keeps improving if it keeps reading more data.

Under the Chinchilla view, the optimal amount of training data for a 1.1B-parameter model is far smaller. Training beyond that, the argument goes, is worse than spending the same compute on a larger model. However, the cost of using a model (inference) is determined by its size, so if a small model's performance can be improved even a little, it is worth spending more compute on training.

The paper also cites earlier discussions suggesting that predictions based on the Chinchilla view may not be accurate when small models are trained for a long time. TinyLlama is an example of actually testing this regime.

That said, the TinyLlama paper does not systematically compare performance across different numbers of training tokens. In v1.1, performance improved slightly even though the token count was reduced from 3 trillion to 2 trillion, but the bug fixes and the three-stage training were introduced at the same time, so the effect of the token count alone cannot be isolated.

Training a small model for longer does not increase the model's capacity itself. TinyLlama stays at around 25–27% on MMLU (5-shot), close to the 25% chance accuracy for four-choice questions. On tasks that probe broad knowledge, the gap with larger models cannot be closed by more training.

Experimental results

Commonsense reasoning (Zero-shot accuracy, %. Table 3 of the paper. Evaluated with the Language Model Evaluation Harness.)

ModelHellaSwagOBQAWinoGrandeARC-cARC-eBoolQPIQAAverage
OPT-1.3B53.6533.4059.5929.4450.8060.8372.3651.44
Pythia-1.0B47.1631.4053.4327.0548.9957.8369.2148.30
Pythia-1.4B52.0133.2057.3828.5054.0063.2770.9551.33
TinyLlama v1.059.2036.0059.1230.1255.2557.8373.2952.99
TinyLlama v1.161.4736.8059.4332.6855.4755.9973.5653.63
TinyLlama v1.1 Math&Code60.8036.4060.2233.8755.2057.0972.6953.75
TinyLlama v1.1 Chinese58.2335.2059.2731.4055.3561.4173.0153.41

All four TinyLlama models outperformed the other models on average. On BoolQ, however, they fell below Pythia-1.4B and OPT-1.3B, so they do not win on every task. The Chinese version, continually pretrained with 50% Chinese data, also largely retains its performance on English tasks.

Problem-solving tasks (InstructEval benchmark. Table 4 of the paper.)

ModelMMLU (5-shot)BBH (3-shot)HumanEval (zero-shot)DROP (3-shot)Average
OPT-1.3B24.9028.570.0014.3216.95
Pythia-1.4B25.4129.014.2712.2717.72
TinyLlama v1.025.3429.659.1515.3419.87
TinyLlama v1.126.5829.276.7115.2119.44
TinyLlama v1.1 Math&Code24.6026.3515.2418.5421.18

Although the Math&Code version saw little code and math in the first 1.5 trillion tokens, continual pretraining alone raised its HumanEval score to 15.24%. This shows that domain-specific continual pretraining can boost particular capabilities with a short amount of additional training.

On Chinese understanding (zero-shot; Table 5 of the paper), the Chinese version scored the highest average across four tasks at 58.37, far above the general v1.1 (47.46). The paper attributes the relatively good Chinese scores of v1.0 and the Math&Code version to Chinese text contained in the code data (about 3.5% of the Python data and about 4% of the Jupyter data).

Practical considerations

Keep the following in mind when using TinyLlama:

  • Context is limited to 2,048 tokens: Handling long documents requires splitting them or extending the context with methods such as position interpolation.
  • Weak at knowledge-intensive tasks: MMLU is around 25–27%, close to chance accuracy. It is not suited to uses that require specialized knowledge.
  • It is a base model: The paper's models are trained only on next-token prediction. To use them for dialogue or instruction following, fine-tuning on instruction data or similar is needed.
  • Differences between v1.0 and v1.1: v1.0 is the model in which bugs were found during training. For new uses, choose the v1.1 family, which was retrained after the fixes, and pick the general, Math&Code, or Chinese version depending on the use case.

The paper's evaluation is limited to commonsense reasoning and problem-solving tasks; no evaluation of harmful outputs or bias is reported. When deploying it for people, verify the safety of its outputs for your own use case.

Comparison with other models

Comparing approaches to small language models from the same perspectives gives the following (based on each paper or report):

ModelParametersTraining tokensTokens per parameterMain lever for performance
LLaMA 7B6.7 billion1 trillionAbout 150×Trains on public data beyond what Chinchilla recommends
TinyLlama (v1.0)1.1 billion3 trillionAbout 2,700×Shrinks the same architecture and trains on even more tokens
phi-11.3 billionAbout 50 billion (about 8 passes over 7 billion)About 40×Selects textbook-quality data and adds synthetic data
Phi-3-mini3.8 billion3.3 trillionAbout 870×Uses heavily filtered web and synthetic data to devote capacity to reasoning
Gemma 2B2.5 billion3 trillionAbout 1,200×Brings Gemini's architecture and data to a small model

TinyLlama's distinguishing features are an extreme amount of data and full openness. Rather than engineering data quality as the Phi family does, it uses large amounts of public data (SlimPajama and StarCoder) as is, so anyone can reproduce the same conditions.

Rough guidelines for choosing:

  • Researching or reproducing language model training on modest hardware: TinyLlama is a good fit, since its training code, intermediate checkpoints, and data processing are all public, and it can be trained on 16 A100s.
  • A small on-device model with strong reasoning or math: Phi-3-mini and Gemma 2B, which engineer data quality, score higher on MMLU and similar benchmarks.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
A compact example of TinyLlama's decoder layers, following Section 2.2 and Table 1 of the paper and the official config (tiny_LLaMA_1b in jzhang38/TinyLlama)
  - Same components as Llama 2: RMSNorm on the input side, RoPE on Q and K, SwiGLU feed-forward, no biases
  - GQA: 32 query heads, 4 key/value heads (each shared by a group of 8 query heads)
  - d = 2048, intermediate 5632, 22 layers, context 2048, vocab 32,000
No dropout is used, so model.train() and model.eval() compute the same thing
"""

class RMSNorm(nn.Module):
  def __init__(self, dim, eps=1e-5):
    super().__init__()
    self.eps = eps
    self.weight = nn.Parameter(torch.ones(dim))

  def forward(self, x):
    return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight


def rope_angles(head_dim, max_len, theta=10000.0):
  freqs = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
  angles = torch.outer(torch.arange(max_len).float(), freqs)
  angles = torch.cat((angles, angles), dim=-1)
  return torch.cos(angles), torch.sin(angles)


def apply_rope(x, cos, sin):
  x1, x2 = x.chunk(2, dim=-1)
  return x * cos + torch.cat((-x2, x1), dim=-1) * sin


class GQAttention(nn.Module):
  def __init__(self, dim=2048, n_heads=32, n_kv_heads=4):
    super().__init__()
    self.n_heads, self.n_kv_heads, self.head_dim = n_heads, n_kv_heads, dim // n_heads
    self.wq = nn.Linear(dim, n_heads * self.head_dim, bias=False)
    self.wk = nn.Linear(dim, n_kv_heads * self.head_dim, bias=False)   # Only 4 heads for K and V
    self.wv = nn.Linear(dim, n_kv_heads * self.head_dim, bias=False)
    self.wo = nn.Linear(dim, dim, bias=False)

  def forward(self, x, cos, sin):
    b, n, _ = x.shape
    q = self.wq(x).view(b, n, self.n_heads, self.head_dim).transpose(1, 2)
    k = self.wk(x).view(b, n, self.n_kv_heads, self.head_dim).transpose(1, 2)
    v = self.wv(x).view(b, n, self.n_kv_heads, self.head_dim).transpose(1, 2)
    q, k = apply_rope(q, cos[:n], sin[:n]), apply_rope(k, cos[:n], sin[:n])
    rep = self.n_heads // self.n_kv_heads                          # 8 query heads use the same K and V
    k, v = k.repeat_interleave(rep, dim=1), v.repeat_interleave(rep, dim=1)
    out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
    return self.wo(out.transpose(1, 2).reshape(b, n, -1))


class SwiGLU(nn.Module):
  def __init__(self, dim=2048, hidden=5632):
    super().__init__()
    self.w1 = nn.Linear(dim, hidden, bias=False)                   # Gate branch (passed through SiLU)
    self.w3 = nn.Linear(dim, hidden, bias=False)
    self.w2 = nn.Linear(hidden, dim, bias=False)

  def forward(self, x):
    return self.w2(F.silu(self.w1(x)) * self.w3(x))


class DecoderLayer(nn.Module):
  def __init__(self, dim, n_heads, n_kv_heads, hidden):
    super().__init__()
    self.attn_norm, self.attn = RMSNorm(dim), GQAttention(dim, n_heads, n_kv_heads)
    self.ffn_norm, self.ffn = RMSNorm(dim), SwiGLU(dim, hidden)

  def forward(self, x, cos, sin):
    x = x + self.attn(self.attn_norm(x), cos, sin)
    return x + self.ffn(self.ffn_norm(x))


class TinyLlama(nn.Module):
  def __init__(self, vocab=32000, dim=2048, n_layers=22, n_heads=32, n_kv_heads=4, hidden=5632, max_len=2048):
    super().__init__()
    self.embed = nn.Embedding(vocab, dim)
    self.layers = nn.ModuleList(DecoderLayer(dim, n_heads, n_kv_heads, hidden) for _ in range(n_layers))
    self.norm = RMSNorm(dim)
    self.lm_head = nn.Linear(dim, vocab, bias=False)
    cos, sin = rope_angles(dim // n_heads, max_len)
    self.register_buffer("cos", cos, persistent=False)
    self.register_buffer("sin", sin, persistent=False)

  def forward(self, tokens):
    x = self.embed(tokens)
    for layer in self.layers:
      x = layer(x, self.cos, self.sin)
    return self.lm_head(self.norm(x))


# Sanity check (small config)
model = TinyLlama(vocab=1000, dim=128, n_layers=2, n_heads=8, n_kv_heads=2, hidden=352, max_len=64).eval()
with torch.no_grad():
  print(model(torch.randint(0, 1000, (2, 16))).shape)              # torch.Size([2, 16, 1000])

# The released weights load with the Llama classes in Hugging Face transformers
# from transformers import AutoModelForCausalLM
# model = AutoModelForCausalLM.from_pretrained("TinyLlama/TinyLlama_v1.1")

FAQ

Q. How does TinyLlama differ from Llama 2?
A.

The architectural components (RMSNorm, SwiGLU, RoPE) and the tokenizer are the same as Llama 2. The difference is size: it is scaled down to 1.1 billion parameters with 22 layers and d=2048d = 2048. It also uses GQA, which in Llama 2 was used only by the larger models, even in the 1.1B model.

Q. Isn't 3 trillion tokens too many for 1.1 billion parameters?
A.

Under the Chinchilla view, it is too many relative to training compute. However, since the cost of using a model is determined by its size, improving a small model's performance even slightly is worthwhile. TinyLlama pushes this "train a small model for longer" direction to an extreme, and it outperformed similarly sized OPT and Pythia models on average across commonsense reasoning tasks.

Q. Should I use v1.0 or v1.1?
A.

v1.1. v1.0 is the model in which bugs in the learning rate schedule and data loading were found during training; v1.1 was retrained after fixing them. v1.1 comes in three variants (general, Math&Code for math and code, and Chinese for Chinese), so you can choose by use case.

References

  1. Zhang, P., Zeng, G., Wang, T., & Lu, W. (2024). TinyLlama: An Open-Source Small Language Model. arXiv:2401.02385.
  2. jzhang38/TinyLlama (official repository) lit_gpt/config.py.
  3. Touvron, H., Martin, L., Stone, K., et al. (2023). Llama 2: Open Foundation and Fine-Tuned Chat Models. arXiv:2307.09288.
  4. Ainslie, J., Lee-Thorp, J., de Jong, M., et al. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. arXiv:2305.13245.