nanochat-d24

A 0.73B-parameter base language model (24 layers × 1,536), trained from scratch with 8-bit (FP8 E4M3) matrix products in hand-written CUDA/C++ kernels (llm.c style, no cuBLAS, no PyTorch in the training loop), on 5.46 billion tokens of NVIDIA ClimbMix, using 8× H100 SXM for about 1.6 hours.

Code: github.com/ducbachsong/nanochat: the CUDA kernels, the trainer (train_8bit.cu), the data and tokenizer scripts, and the export to this folder (data/export_safetensors.py).

It is a base model: it continues text and has not been fine-tuned for chat or instructions.

Parameters 733,105,152
Final validation loss 2.846 (nats per token, ClimbMix val split)
Training tokens 5,463,080,960 (10,420 steps × 524,288 tokens, one pass over the train files)
Training compute 2.62 × 10¹⁹ FLOPs, 1.58 hours on 8× H100 SXM, MFU 53.8%
Context 2,048 tokens
Vocabulary 32,768 (nanochat's tokenizer, rustbpe, GPT-4 split pattern)
Weights model.safetensors, bfloat16, 1.47 GB

Architecture

GPT-2-style decoder, with nanochat's d24 size and a few of its changes:

Layers / width / heads 24 / 1,536 / 12 heads of 128
Position learned position embeddings (wpe) added to the token embeddings (wte)
Normalization pre-LayerNorm (weight and bias, eps 1e-5) before attention, before the MLP, and at the end (ln_f)
Attention causal; sliding window of 512 on 3 of every 4 layers (layers 0-2, 4-6, ...), full context on every 4th layer and on the last
QK-norm each query and key head row scaled to RMS 1, times 1.2, no weight: q = 1.2 · q / sqrt(mean(q²) + 1e-6) (the same for k)
MLP 1,536 → 6,144 → 1,536, GELU (tanh form)
Linear biases none (the LayerNorms keep theirs)
Head tied to wte: logits = ln_f(x) @ wte.weightᵀ, no bias
Logit softcap logits = 15 · tanh(logits / 15)

config.json lists all of these values.

Training

Data NVIDIA ClimbMix, tokenized with this tokenizer; <|bos|> (id 32,759) between documents
Batch 524,288 tokens a step: 8 GPUs × 32 rows × 2,048 tokens
Optimizer AdamW (β 0.9 / 0.95, eps 1e-8, weight decay 0.1 on the matrices), gradients clipped to norm 1. Its moments m and √v are kept in 8 bits (E4M3, one scale per 128 values)
Learning rate 3e-4, 700 warm-up steps, cosine down to 0
Precision every matrix product (the 4 linears of each layer, attention's q·kᵀ, the head) runs in FP8 E4M3 with one scale per tensor (delayed scaling, as NVIDIA Transformer Engine does); the activations, gradients and residual stream are bfloat16; the master weights are float32
Hardware 8× NVIDIA H100 80GB SXM (NVLink), 960,317 tokens/s on average
FLOPs a token 4.795 × 10⁹: 6 × 733,105,152 params + 12 × 1,536 × the keys a token sees in each layer (2,048 on the 6 full layers, 512 on the 18 windowed ones), as nanochat counts them
MFU 53.8% on average: tokens/s × FLOPs a token / (8 × 1,070 TFLOPS, the H100 SXM's bfloat16 tensor-core peak at 1,980 MHz). The products run in FP8, whose peak is twice that

Validation loss

Step 1,000 2,000 3,000 4,000 5,000 6,000 7,000 8,000 9,000 10,420
Val loss 4.065 3.430 3.213 3.119 3.016 2.967 2.911 2.877 2.855 2.846

Training charts

The training loss (mean of 50 steps) and the val loss (every 250 steps) lie on top of each other the whole way: one pass over the data, no overfitting.

Loss over the training steps

Val loss against training compute (FLOPs, log scale)

Val loss against training time

The step time stayed the same from the first step to the last: MFU held at about 54% throughout.

MFU over the training steps

Using it

The layout is this model's own, so transformers' GPT-2 classes cannot load it. The forward pass is short in plain PyTorch:

# pip install torch safetensors tiktoken huggingface_hub
import json, pickle, torch, torch.nn.functional as F
from safetensors.torch import load_file
from huggingface_hub import snapshot_download

folder = snapshot_download("ducbachsong/nanochat-d24")  # config.json, model.safetensors, tokenizer.pkl
config = json.load(open(f"{folder}/config.json"))
w = {k: v.float().cuda() for k, v in load_file(f"{folder}/model.safetensors").items()}
enc = pickle.load(open(f"{folder}/tokenizer.pkl", "rb"))  # a tiktoken Encoding; a pickle runs code when
                                                          # loaded: load only files you trust

def ln(x, name):
    return F.layer_norm(x, (x.shape[-1],), w[f"{name}.weight"], w[f"{name}.bias"], config["layer_norm_epsilon"])

def rms(x):                                             # QK-norm
    return config["qk_norm_gain"] * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + config["qk_norm_epsilon"])

@torch.no_grad()
def logits_of(ids):                                     # ids: {B, T}
    B, T = ids.shape
    D, NH, HS = config["n_embd"], config["n_head"], config["head_size"]
    x = w["wte.weight"][ids] + w["wpe.weight"][:T]
    distance = torch.arange(T, device=ids.device)[:, None] - torch.arange(T, device=ids.device)[None, :]
    for l in range(config["n_layer"]):
        q, k, v = (F.linear(ln(x, f"h.{l}.ln_1"), w[f"h.{l}.attn.qkv.weight"]).split(D, -1))
        q, k, v = (t.view(B, T, NH, HS).transpose(1, 2) for t in (q, k, v))
        q, k = rms(q), rms(k)
        window = 0 if (l % 4 == 3 or l == config["n_layer"] - 1) else config["attention_window"]
        mask = (distance >= 0) & ((distance <= window) if window else True)
        y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
        x = x + F.linear(y.transpose(1, 2).reshape(B, T, D), w[f"h.{l}.attn.proj.weight"])
        h = F.gelu(F.linear(ln(x, f"h.{l}.ln_2"), w[f"h.{l}.mlp.up.weight"]), approximate="tanh")
        x = x + F.linear(h, w[f"h.{l}.mlp.down.weight"])
    logits = ln(x, "ln_f") @ w["wte.weight"].T
    return config["logit_softcap"] * torch.tanh(logits / config["logit_softcap"])

bos = enc.encode_single_token("<|bos|>")
ids = torch.tensor([[bos] + enc.encode_ordinary("The capital of France is")], device="cuda")
for _ in range(30):                                     # greedy, no KV cache: simple, not fast
    next_id = logits_of(ids)[0, -1].argmax()
    ids = torch.cat([ids, next_id.view(1, 1)], dim=1)
print(enc.decode(ids[0, 1:].tolist()))

Weight names: wte.weight {32768, 1536}, wpe.weight {2048, 1536}, and for each layer h.<l>.ln_1.{weight,bias}, h.<l>.attn.qkv.weight {4608, 1536} (rows: q, then k, then v), h.<l>.attn.proj.weight, h.<l>.ln_2.{weight,bias}, h.<l>.mlp.up.weight {6144, 1536}, h.<l>.mlp.down.weight {1536, 6144}; then ln_f.{weight,bias}. Every matrix is in torch.nn.Linear's {out, in} layout.

Limitations

  • A small base model trained on 5.5B tokens: it writes fluent-looking text but gets facts wrong, repeats itself, and follows no instructions.
  • Not evaluated on downstream benchmarks; the validation loss above is its only measure.
  • Trained with FP8 products and exported to bfloat16 from the float32 master weights. The PyTorch forward above runs in float32/bfloat16, so its loss may differ slightly from the trainer's 2.846.
  • No safety tuning; it can reproduce whatever its web training data contains.
Downloads last month
53
Safetensors
Model size
0.7B params
Tensor type
BF16
·
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Model tree for ducbachsong/nanochat-d24

Finetunes
1 model