← Jagesh Maharjan (Jugs) All posts
22 October 2026nanotron · config_test_8xh100.yaml

How a Llama is spread over 8 GPUs and trained one step at a time

The model as nanotron actually builds it: a graph of pipeline blocks, each cut across tensor-parallel ranks, replicated across data-parallel replicas. Then everything that happens inside one training_step, how checkpoints are written, and how to adapt the whole thing to a new corpus.

TPTensor parallel · splits each layer's weights PPPipeline parallel · splits the layer stack DPData parallel · full copies, different batches MPModel parallel · TP × PP, one whole copy
Contents
    ModelLlama · 12 layers · H 1024
    Attention16 q-heads · 4 kv-heads · d 64
    FFN / vocabI 4096 · V 49 152
    Micro-batchB 4 × S 2048 tokens
    Parallelismdp 2 · tp 2 · pp 2 = 8 GPUs
    Per step4 micro-batches/replica · 65 536 tokens

    Every shape below is computed from this test config. File references point into nanotron/src/nanotron/.

    The 8-GPU layout

    ParallelContext (parallel/context.py:62-120) lays the 8 ranks out as a matrix with axes (ep, pp, dp, cp, tp) — expert and context parallel are 1 here — and then carves process groups out of it by slicing along one axis. Every collective in the model runs on one of these groups, so the picture below is the whole communication topology.

    pp_rank 0embedding + layers 0–7
    dp_rank 0
    rank 0pp0·dp0·tp0heads 0–7
    rank 1pp0·dp0·tp1heads 8–15
    dp_rank 1
    rank 2pp0·dp1·tp0heads 0–7
    rank 3pp0·dp1·tp1heads 8–15
    →
    P2P
    hidden_states
    [2048, 4, 1024]
    bf16
    pp_rank 1layers 8–11 + norm + lm_head + loss
    dp_rank 0
    rank 4pp1·dp0·tp0vocab 0–24 575
    rank 5pp1·dp0·tp1vocab 24 576–49 151
    dp_rank 1
    rank 6pp1·dp1·tp0vocab 0–24 575
    rank 7pp1·dp1·tp1vocab 24 576–49 151
    tp_pg{0,1} {2,3} {4,5} {6,7}. The shaded pairs.
    pp_pg{0,4} {1,5} {2,6} {3,7}. Across the arrow.
    dp_pg{0,2} {1,3} {4,6} {5,7}. Same position, other replica.
    mp_pg{0,1,4,5} {2,3,6,7}. One whole model.

    global rank = pp_rank·4 + dp_rank·2 + tp_rank

    One replica is four GPUs, not one. Numbers in the boxes are global ranks (what torchrun puts in RANK); the small line is the rank’s coordinate in the (pp, dp, tp) matrix. A data-parallel replica (dp_rank 0) is global ranks {0,1,4,5}: two pipeline stages, each a tensor-parallel pair. tp_pg carries the all-reduce / reduce-scatter inside every layer; pp_pg carries hidden states between stages; dp_pg carries the gradient all-reduce once per step. mp_pg (TP × PP for a fixed dp) is what gradient clipping reduces over.

    Concretely, when torchrun --nproc_per_node=8 starts, each process reads RANK and asks the matrix for its coordinates (get_local_ranks, context.py:151). Global rank 5 learns it is pp_rank 1, dp_rank 0, tp_rank 1: it will build layers 8–11 and the upper half of the vocabulary, consume the same batches as ranks 0, 1 and 4, and average gradients with rank 7. See the table below for all eight.

    Reading rank numbers

    Three different things are called “rank”, and the code mixes them freely:

    ranks = np.arange(8).reshape(ep=1, pp=2, dp=2, cp=1, tp=2)      # context.py:62
    global_rank = pp_rank·(dp·cp·tp) + dp_rank·(cp·tp) + cp_rank·tp + tp_rank
                = pp_rank·4 + dp_rank·2 + tp_rank                      # for this config
    
    global rank pp_rank dp_rank tp_rank tp_pg (rank in it) pp_pg (rank in it) dp_pg (rank in it) mp_pg holds
    0 0 0 0 {0,1} (0) {0,4} (0) {0,2} (0) {0,1,4,5} emb + layers 0–7 · heads 0–7 · vocab rows 0–24 575
    1 0 0 1 {0,1} (1) {1,5} (0) {1,3} (0) {0,1,4,5} emb + layers 0–7 · heads 8–15 · vocab rows 24 576–49 151
    2 0 1 0 {2,3} (0) {2,6} (0) {0,2} (1) {2,3,6,7} same as rank 0, second replica
    3 0 1 1 {2,3} (1) {3,7} (0) {1,3} (1) {2,3,6,7} same as rank 1, second replica
    4 1 0 0 {4,5} (0) {0,4} (1) {4,6} (0) {0,1,4,5} layers 8–11 + norm + lm_head cols 0–24 575 + loss
    5 1 0 1 {4,5} (1) {1,5} (1) {5,7} (0) {0,1,4,5} layers 8–11 + norm + lm_head cols 24 576–49 151 + loss
    6 1 1 0 {6,7} (0) {2,6} (1) {4,6} (1) {2,3,6,7} same as rank 4, second replica
    7 1 1 1 {6,7} (1) {3,7} (1) {5,7} (1) {2,3,6,7} same as rank 5, second replica

    What the group columns mean

    The four group columns are the process groups each rank belongs to — the sets of ranks that communicate for one purpose — and, in parentheses, that rank’s position inside the set. ParallelContext builds them by slicing the rank matrix along one axis (context.py:76-95). Reading them for global rank 5:

    column rank 5 meaning what uses it
    tp_pg {4,5} (1) Tensor-parallel group: rank 5 shares every layer’s weights with rank 4. Member #1 → it owns the second half of each sharded matrix (heads 8–15, vocab 24 576–49 151). Column/Row linear all-reduce & reduce-scatter; embedding; sharded cross-entropy
    pp_pg {1,5} (1) Pipeline group: the two stages of one pipeline. Rank 1 is stage 0 (embedding + layers 0–7), rank 5 is member #1 = stage 1 (layers 8–11 + head). Hidden states flow 1 → 5, gradients 5 → 1. PipelineBlock P2P send/recv; collator’s input_pp_rank/output_pp_rank test
    dp_pg {5,7} (0) Data-parallel group: ranks holding the same shard in different replicas. Ranks 5 and 7 average their gradients each step. Rank 5 is member #0. DDP gradient all-reduce; ZeRO-1 optimizer shard; sampler slice of the batch
    mp_pg {0,1,4,5} Model-parallel group = TP × PP: all four GPUs of one replica, i.e. one complete copy of the model. gradient clipping — the norm must span the whole model
    dp_cp_pg {5,7} DP × context-parallel. With cp = 1 it is identical to dp_pg. the lm_loss average for logging

    Why “rank in it” matters. torch.distributed numbers every group independently, 0 … size−1. The code decides roles with dist.get_rank(group), never with the global rank:

    Because nanotron slices the groups along matrix axes, the group-local rank always equals the coordinate: rank 5’s position in tp_pg is its tp_rank (1), in pp_pg its pp_rank (1), in dp_pg its dp_rank (0). That equality is what lets the code use the two interchangeably.

    tp_pg — 4 disjoint groups pp_pg — 4 disjoint groups dp_pg — 4 disjoint groups
    0 · 1 0 → 4 0 ↔ 2
    2 · 3 1 → 5 1 ↔ 3
    4 · 5 2 → 6 4 ↔ 6
    6 · 7 3 → 7 5 ↔ 7
    neighbours: same stage, same replica, different halves of every weight r and r+4: stage 0 → stage 1 of one pipeline; hidden states cross here r and r+2: same shard in the other replica; gradients averaged here

    Each family partitions all 8 ranks; a rank is in exactly one group of each kind. Two groups of different kinds meet in exactly one rank: tp_pg {4,5} ∩ dp_pg {5,7} = {5}.

    mp_pg = one tp family × one pp family = a whole replica: {0,1,4,5} and {2,3,6,7}. It is not a matrix axis — it is the set that holds one full model.

    Three ways to partition the same eight ranks. Every rank sits in one tensor group, one pipeline group and one data group; the intersections are what make a rank’s role unambiguous. mp_pg is the union that forms a complete model copy.

    Worked example, global rank 5. 5 = 1·4 + 0·2 + 1 → pp_rank 1, dp_rank 0, tp_rank 1. In every layer it computes heads 8–15 and all-reduces with rank 4 (tp_pg {4,5}). It receives hidden_states from rank 1 (pp_pg {1,5}; rank 1 is pp_rank 0 of that pair). Its loss block owns vocab ids 24 576–49 151 and exchanges the three small tensors with rank 4. After backward it averages gradients with rank 7 (dp_pg {5,7}) and, for clipping, sums squared norms with ranks 0, 1 and 4 (mp_pg). The DataCollatorForCLM on rank 5 sees dist.get_rank(pp_pg) == 1 == output_pp_rank, so it materialises label_ids/label_mask and hands out pointers for input_ids/input_mask. The sampler on rank 5 uses dist.get_rank(dp_pg) == 0, so it draws the same sample indices as ranks 0, 1 and 4 — the four GPUs of one replica must see one batch.

    Part A · The model

    A1 · The forward is two lines

    class LlamaForTraining(NanotronModel):                      # models/llama.py:1026
        def forward(self, input_ids, input_mask, label_ids, label_mask):
            sharded_logits = self.model(input_ids=input_ids, input_mask=input_mask)   # LlamaModel
            return {"loss": self.loss(sharded_logits=sharded_logits,                  # PipelineBlock(Loss)
                                      label_ids=label_ids, label_mask=label_mask)["loss"]}
    

    Nothing in this method knows about GPUs. Each of the four arguments arrives either as a real tensor (on the rank that owns it) or as a TensorPointer (everywhere else) — exactly what the collator produced. All the distributed behaviour is inside LlamaModel and the blocks it is made of.

    A2 · The model is a graph of 16 pipeline blocks

    LlamaModel.__init__ (llama.py:815-905) does not build layers. It declares a list of PipelineBlocks, each a recipe: which class to instantiate, with which kwargs, and which named tensors go in and out. forward_with_hidden_states (llama.py:914) then chains them by name.

    stage PipelineBlock module it builds tensor leaving the block what tp=2 shards
    pp_rank 0 token_position_embeddings Embedding → TensorParallelEmbedding [V, H] input_embeds [S, B, H] = [2048, 4, 1024] vocab rows: 24 576 / GPU
    pp_rank 0 decoder[0] … decoder[7] LlamaDecoderLayer ×8 (see A5) hidden_states [S, B, H] · sequence_mask [B, S] heads · FFN columns
    ↓ P2P P2P send/recv between pp_rank 0 and pp_rank 1 — the only place activations leave a GPU pair      
    pp_rank 1 decoder[8] … decoder[11] LlamaDecoderLayer ×4 hidden_states [S, B, H] heads · FFN columns
    pp_rank 1 final_layer_norm TritonRMSNorm(H) hidden_states [S, B, H] replicated
    pp_rank 1 lm_head TensorParallelColumnLinear(H → V) logits [S, B, V/tp] = [2048, 4, 24 576] bf16 output columns — never gathered
    pp_rank 1 cast_to_fp32 x.float() [2048, 4, 24 576] fp32 (0.8 GB per GPU)  
    pp_rank 1 loss (in LlamaForTraining) Loss → sharded_cross_entropy + masked_mean loss scalar fp32 3 all-reduces of [S, B]

    The block list is the model. Eight decoder blocks and the embedding live on stage 0; four decoder blocks, the norm, the LM head, the cast and the loss live on stage 1. Every block’s weights are additionally split between the two GPUs of a tensor-parallel pair (right column).

    A3 · PipelineBlock: declared everywhere, built on one rank

    parallel/pipeline_parallel/block.py. Three methods do the work:

    1. __init__(p2p, module_builder, module_kwargs, module_input_keys, module_output_keys) stores the recipe. No parameter memory is allocated, so a 70B model can be declared on every GPU for free.
    2. build_and_set_rank(pp_rank) (block.py:46) records self.rank (a pp_rank). Only if dist.get_rank(pp_pg) == pp_rank — the caller’s position within pp_pg, not its global rank — does it call module_builder(**module_kwargs) and materialise the module as self.pp_block. On the other stage it stays an empty shell that knows who owns it.
    3. forward(**kwargs) (block.py:60+) has two behaviours:
      • Not my rank → return {key: TensorPointer(group_rank=self.rank)} for every output key. Zero compute, zero memory.
      • My rank → for every input that is a TensorPointer, recv it from pointer.group_rank over pp_pg (batched through BatchTensorSendRecvState), then run self.pp_block(**inputs). During training the matching send on the owner side is queued in pipeline_state.microbatches_activations_to_send and flushed by the engine right after that micro-batch’s forward.

    This is why the collator could hand global rank 4 a TensorPointer(group_rank=0) for input_ids and a real label_ids. Note the group_rank: it is a pp_rank, a position inside pp_pg, not a global rank. On global rank 4 (pp_rank 1) the embedding block is “not my rank” and returns a pointer; the first decoder block it owns (decoder[8]) sees a pointer for hidden_states and receives it from pp_rank 0 of its own pipeline group pp_pg {0,4} — global rank 0. Rank 5 does the same with rank 1 through pp_pg {1,5}. Model code never calls send/recv; the block graph does it by following pointers.

    A4 · Assigning blocks to stages is cost-balanced, not count-balanced

    build_model (models/base.py:185-240) walks the block list with a cumulative cost and advances to the next stage when the running total passes total · (rank+1) / pp. Costs come from get_block_compute_costs() (llama.py:938):

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    lm_head
    pp_rank 0 · layers 0–7 · 8 × 16.8M = 134M
    pp_rank 1 · layers 8–11 + lm_head · 4 × 16.8M + 50.3M = 118M

    decoder layer = 4·heads·d·H + 3·I·H = 16.8M · lm_head = V·H = 50.3M · others 0. The black line is total / 2; the cut falls after the first block that crosses it (layer 7).

    model.input_pp_rank = 0, model.output_pp_rank = 1 — the two numbers the collator uses to decide who gets inputs and who gets labels.

    The LM head weighs three decoder layers, so the balanced cut is 8 / 4 layers, not 6 / 6. Set pp: 1 and the whole bar is one stage; stages are always contiguous runs of the block list.

    The materialisation happens under init_on_device_and_dtype(cuda, bfloat16), so a block that is built lands directly on the right rank’s GPU in bf16. With pp > 1, model.log_modules prints the block → rank map at startup — the first thing to read if one stage looks idle.

    A5 · Tensor parallelism inside one decoder layer

    Now zoom into one LlamaDecoderLayer on a tensor-parallel pair, say global ranks 0 and 1 (group tp_pg {0,1}; inside that group they are tp_rank 0 and tp_rank 1). The identical picture holds for {2,3}, {4,5} and {6,7}. Two primitives from parallel/tensor_parallel/nn.py do all the sharding, Megatron-style:

    Column → local op → Row means the intermediate activation is never gathered, and there is exactly one collective per sub-block.

    sub-block global rank 0 · tp_rank 0 (rank 0 inside tp_pg {0,1}) global rank 1 · tp_rank 1 (rank 1 inside tp_pg {0,1}) between the pair
    x [S,B,H] hidden_states [2048, 4, 1024] — full copy hidden_states [2048, 4, 1024] — full copy  
    RMSNorm TritonRMSNorm (weights replicated) TritonRMSNorm (weights replicated)  
    qkv_proj · Column W_qkv [768, 1024]; q heads 0–7 (512) · k heads 0–1 (128) · v (128); out [2048, 4, 768] W_qkv [768, 1024]; q heads 8–15 · k heads 2–3 · v; out [2048, 4, 768]  
    RoPE + flash-attn flash_attn_varlen_func(causal); 8 q-heads share 2 kv-heads (GQA, repeat 4) — local flash_attn_varlen_func(causal); its own 8 heads — no communication  
    o_proj · Row Σ W_o [1024, 512]; partial out [2048, 4, 1024] W_o [1024, 512]; partial out [2048, 4, 1024] all-reduce Σ (reduce-scatter in REDUCE_SCATTER mode)
    + residual · RMSNorm x = out + residual; post_attention_layernorm x = out + residual; post_attention_layernorm  
    gate_up · Column W_gate_up [4096, 1024]; gate cols 0–2047 ‖ up cols 0–2047 W_gate_up [4096, 1024]; gate cols 2048–4095 ‖ up cols 2048–4095  
    silu·up silu(gate) · up → [2048, 4, 2048] local silu(gate) · up → [2048, 4, 2048] local  
    down_proj · Row Σ W_down [1024, 2048] → partial [S,B,1024] W_down [1024, 2048] → partial [S,B,1024] all-reduce Σ

    Two collectives per layer, both on tp_pg. Column layers (qkv, gate_up) split output features so each GPU owns whole heads or whole FFN columns and computes independently; the Row layers (o_proj, down) split input features and their partial sums are all-reduced. Attention itself is local: rank 0 only ever sees heads 0–7, rank 1 heads 8–15. _core_forward is llama.py:735; the layer classes are llama.py:208-784.

    Three config knobs modify this picture:

    Guards at build time (llama.py:345-360): num_attention_heads % tp == 0 and num_key_value_heads % tp == 0 — a head is never split. recompute_layer: true wraps _core_forward in CheckpointFunction for full activation recomputation. Per GPU the parameters come to ≈ 283M / 4 ≈ 71M.

    A6 · The loss never gathers the logits

    lm_head is a ColumnLinear over the vocabulary, so on stage 1, tp_rank 0 (global ranks 4 and 6) holds logits for vocab ids 0–24 575 and tp_rank 1 (global ranks 5 and 7) for 24 576–49 151: [2048, 4, 24 576] each. Gathering them would cost S·B·V·4 B = 1.6 GB per micro-batch. Instead _ShardedCrossEntropy (tensor_parallel/functional.py:30-80) computes exact cross-entropy with three tiny collectives on [S, B] tensors:

      global rank 4 (tp_rank 0) global rank 5 (tp_rank 1)
    logits [S, B, 24 576] [S, B, 24 576]
    vocab ids 0 … 24 575 24 576 … 49 151
    exchange between the pair what it carries
    ① all-reduce MAX local max over own slice → global max, subtract
    ② all-reduce SUM logit[target] from the rank that owns that id, 0 from the other
    ③ all-reduce SUM Σ exp(logits) over own slice → global partition function

    Each exchange is [S, B] = 8 192 floats, not 50M.

    loss[s,b] = log Σexp − logit[target] → masked_mean(loss, label_mask) → scalar, identical on both GPUs.

    Exact softmax cross-entropy from half a vocabulary each. Loss.forward (llama.py:982) transposes label_ids to seq-first, calls sharded_cross_entropy(…, group=tp_pg, dtype=float), then masked_mean so the tokens masked by the collator (first token after each <|endoftext|>) drop out of numerator and denominator. LossWithZLoss adds z_loss_coef · (log Σexp)².

    A7 · After build_model: tying, init, DDP, fp32 grads

    trainer._init_model (trainer.py:1084-1160) finishes the object the step will use:

    1. Tied parameters. _mark_tied_parameters registers weights that must stay equal on several ranks. With tie_word_embeddings: true the embedding (stage 0) and lm_head (stage 1) would be tied across the pipeline boundary, adding a gradient all-reduce over pp_pg every step. The test config keeps them untied.
    2. Initialisation. init_model_randomly with StandardParametrizator (normal, std 0.02) — or SpectralMupParametrizator for µP. Seeds differ per tp_rank so the two halves of a sharded matrix are not identical; then sync_tied_weights makes tied copies equal. Alternatively load_weights from resume_checkpoint_path.
    3. DDP. If dp > 1, wrap in DistributedDataParallel(process_group=dp_pg, bucket_cap_mb=ddp_bucket_cap_mb). Its hooks are what all-reduce gradients between global ranks 0 and 2 (and 1↔3, 4↔6, 5↔7) — the four dp_pg groups.
    4. fp32 gradient accumulator. With accumulate_grad_in_fp32: true, FP32GradientAccumulator owns an fp32 buffer per parameter; bf16 grads from each micro-batch are added into it, and DDP is redirected to all-reduce those buffers asynchronously on the last micro-batch.

    Part B · One training_step

    trainer.py:604-740. The step receives the dataloader iterator and pulls n_micro_batches_per_batch = batch_accumulation_per_replica = 4 micro-batches from it. Everything below happens once per optimizer update.

    B1 · Forward and backward under the 1F1B schedule

    outputs = self.pipeline_engine.train_batch_iter(          # trainer.py:613
        model=self.model, pg=self.parallel_context.pp_pg,
        batch=(next(dataloader) for _ in range(self.n_micro_batches_per_batch)),
        nb_microbatches=self.n_micro_batches_per_batch, grad_accumulator=self.grad_accumulator)
    

    pp_engine: 1f1b selects OneForwardOneBackwardPipelineEngine.train_batch_iter (pipeline_parallel/engine.py:242). Its purpose is to keep both stages busy while bounding how many micro-batches’ activations are alive at once.

    time → (each slot ≈ one forward or one backward of one micro-batch on one stage; Fn = forward of micro-batch n, Bn = its backward)

    stage \ slot 1 2 3 4 5 6 7 8 9
    pp_rank 0 (ranks 0–3) F0 F1 B0 F2 B1 F3 B2 B3 idle
    pp_rank 1 (ranks 4–7) bubble F0 B0 F1 B1 F2 B2 F3 B3

    One forward, one backward, at most pp_size micro-batches in flight. Stage 0 does one warm-up forward so stage 1 has work, then both alternate F/B; the only idle slot is the initial bubble. Compare afab, which runs all four forwards then all four backwards and must hold four micro-batches of activations.

    Per forward (engine.py:29-62): output = model(**micro_batch), then output["loss"] /= nb_microbatches so summing four backwards equals the mean, then state.register_activation_requiring_backward(loss). Per backward: on the last stage, loss.backward(); on earlier stages, backward from the gradient received for the hidden states it sent. All P2P traffic is the PipelineBlock mechanism from A3 — the engine only decides when to flush the queued sends. Inside each forward, the four tp_pg collectives per layer (A5) and three in the loss (A6) run as usual.

    The return value outputs is a list of four dicts. On output_pp_rank = pp_rank 1 (global ranks 4–7) each contains a real loss; on pp_rank 0 (global ranks 0–3) they are TensorPointers.

    B2 · Gradient synchronisation

    B3 · Clip, average the loss, step

    1. Clip (trainer.py:660-675). clip_grad_norm(mp_pg, named_parameters, grad_accumulator, max_norm=1.0): each GPU squares and sums the norm of its own shards, all-reduces that over mp_pg = TP × PP (global ranks {0,1,4,5} for dp_rank 0, {2,3,6,7} for dp_rank 1) so the norm covers the whole model, then scales every shard by the same factor. Tied and duplicated parameters are counted once via get_named_params_with_correct_tied. The pre-clip norm is logged as grad_norm.
    2. Average the loss for logging (trainer.py:678-692). On stage 1: loss_avg = Σ outputs[i]["loss"] (already ÷ 4), then all_reduce(AVG) over dp_cp_pg, launched async and waited on at the end of the step so it overlaps the optimizer. This is lm_loss in the log line.
    3. Optimizer (trainer.py:705-716). optimizer.step(); optimizer.zero_grad(); lr_scheduler.step(). With zero_stage: 1, ZeroDistributedOptimizer gives each dp_rank the Adam moments and fp32 master copy for a 1/dp slice of every parameter; it updates that slice and all-gathers the new bf16 weights across dp_pg. Optimizer memory per GPU drops from 12 B/param to 6 B/param. torch_adam_is_fused: true uses the fused CUDA kernel. The LR follows 20 warm-up steps then cosine to min_decay_lr.
    4. Sanity checks (sanity_checks.py) bracket every phase: before_tbi → after_tbi → before_optim_step → after_optim_step. They assert tied copies are identical, gradients finite, parameters actually changed. ignore_sanity_checks: false in the test config keeps them on.

    B4 · The whole step on one page

    phase communication process group who talks
    next(dataloader) × 4 — micro-batch dicts · pointers on non-owner ranks      
    train_batch_iter (1F1B) — 4 × forward + backward · loss ÷ 4 · bf16 grads → fp32 accumulator P2P send/recv hidden_states + grads pp_pg ranks 0↔4 · 1↔5 · 2↔6 · 3↔7
    ″ 4 all-reduce / reduce-scatter per layer tp_pg 0↔1 · 2↔3 · 4↔5 · 6↔7
    ″ 3 all-reduce [S,B] in the loss tp_pg 4↔5 · 6↔7
    wait fp32 grad all-reduce — launched async in last backward all-reduce AVG of fp32 grads (0.28 GB) dp_pg 0↔2 · 1↔3 · 4↔6 · 5↔7
    sync_tied_weights_gradients all-reduce tied grads (none here) tied group  
    clip_grad_norm(max_norm=1.0) all-reduce Σ‖g‖² then scale locally mp_pg {0,1,4,5} · {2,3,6,7}
    optimizer.step · zero_grad · lr_scheduler.step — ZeRO-1: update own 1/dp slice, all-gather params all-gather updated bf16 params dp_pg  
    ″ — loss AVG all-reduce overlapped here; handle.wait() all-reduce AVG loss (scalar) dp_cp_pg 4↔6 · 5↔7 (stage 1 only)

    Then train(): consumed_train_samples += 32, consumed_tokens += 65 536, log every N steps, checkpoint every checkpoint_interval.

    Every phase maps to one process group. The heavy traffic is inside the forward/backward (TP collectives on every layer, PP activations twice per micro-batch); the once-per-step traffic is the DP gradient average and ZeRO all-gather. Clipping is the one operation that spans TP and PP together.

    Why the test model is small on purpose. 71M parameters per H100 is nothing — params + fp32 grads + ZeRO-1 Adam states total under 1 GB. The config exists to exercise every path above (both PP stages, TP collectives, DP averaging, ZeRO, clipping, checkpointing) in a few minutes. A real run raises micro_batch_size, sequence_length and the model until activations fill the 80 GB.

    Part C · Checkpointing and resume

    save_checkpoint (trainer.py:1244) runs every checkpoint_interval steps and after the last step. It writes one folder per step under checkpoints_path, then updates latest.txt. The rule for who writes what follows the process groups: anything identical across a group is written once per group; anything unique per rank is written by every rank.

    /tmp/nanotron-ckpt/test_8xh100/
    ├── latest.txt  →  "100"                          all ranks (same bytes)
    └── 100/
        ├── config.yaml · checkpoint_metadata.json    world rank 0
        │     step, consumed samples/tokens, data-stage cursors, saved tp/dp/cp
        ├── model/                                    dp_cp_rank == 0  →  ranks 0, 1, 4, 5
        │   │                                         replicas are identical; one copy is enough
        │   ├── …/decoder/0/pp_block/attn/qkv_proj/
        │   │   ├── model_weight_pp-rank-0-of-2_tp-rank-0-of-2.safetensors   rank 0  [768, 1024]
        │   │   └── model_weight_pp-rank-0-of-2_tp-rank-1-of-2.safetensors   rank 1  [768, 1024]
        │   ├── …/decoder/0/pp_block/input_layernorm/
        │   │   └── model_weight.safetensors          not sharded → no rank suffix
        │   └── …/lm_head/pp_block/model_weight_pp-rank-1-of-2_tp-rank-{0,1}-of-2.safetensors
        │                                             ranks 4, 5  [24 576, 1024]
        ├── optimizer/                                all 8 ranks (ZeRO-1: each holds a different 1/dp slice)
        │   ├── optimizer_pp-{p}-of-2_dp-{d}-of-2_tp-{t}-of-2_exp-0-of-1.pt  × 8
        │   └── optimizer_config.json                 rank 0
        ├── lr_scheduler/
        │   └── lr_scheduler_pp-…_dp-…_tp-…pt × 8     all 8 ranks
        ├── random/
        │   └── tp-{t}-of-2_dp-{d}-of-2_pp-{p}-of-2.pt × 8   all 8 ranks — RNG streams
        └── model_config.json                         all ranks (same bytes)
    

    Each safetensors header carries TensorMetadata: version, unsharded_shape, local_global_slices_pairs — which slice of the full tensor this file is.

    Filenames encode the topology; headers encode the slice. Weights are saved by one replica (ranks 0, 1, 4, 5) as one file per TP/PP shard; ZeRO-1 optimizer state is unique per rank so all eight write. For the test model a step folder is ≈ 4 GB (weights 0.57 GB + Adam 3.4 GB).

    Resume: six loads in a fixed order

    # load detail
    1 parse_ckpt_path latest.txt → 100/ · or S3 download
    2 load_weights own shard path exists? else merge+reshard
    3 load_optimizer tp/dp change: reshard · pp change: warn only
    4 load_lr_scheduler per-rank file
    5 load_meta iteration_step = 100 · sampler offset = 3200
    6 random states per-rank RNG
    changed on resume
    tp weights + optimizer re-sharded from the slice metadata (supported)
    dp ZeRO-1 optimizer shards merged and re-sliced (supported)
    pp weights load (blocks find their shards); optimizer only warns — verify, or set load_optimizer: false

    Resume is deterministic because the cursor is saved, not just the weights. checkpoint_metadata.json carries last_train_step and per-stage consumed_train_samples; the sampler restarts its index stream there, so with the same seed the data order continues exactly.

    On cloud instances with S3. Keep checkpoints_path on local NVMe (eight ranks writing hundreds of small files to an S3 FUSE mount is slow) and add an s3_upload block (it uses s5cmd) so post_save_checkpoint uploads in the background and, with remove_after_upload: true, frees the disk. To test the loop: run 200 steps, set resume_checkpoint_path to the run folder and train_steps: 300, relaunch — the first log line should show start_iteration_step: 200 and lm_loss should continue without a jump.

    Part D · What the trained artefact is: a base model

    Everything above produces one thing — a base model: a function that, given a sequence of tokens, outputs a probability distribution over the next token. It is not an assistant, a classifier, or a retriever. Everything it appears to “do” is that single operation applied repeatedly.

    ┌──► tokens so far: "The capital of France is"
    │          │
    │          ▼
    │    LlamaModel: embed → 12 layers → norm → lm_head → softmax
    │          │
    │          ▼
    │    P(next token) — 49 152 numbers, sum = 1
    │      " Paris"     0.71  ███████████████████████████████████▌
    │      " a"         0.04  ██
    │      " located"   0.03  █▌  … 49 149 more
    │          │
    └──────────┘  generation = sample/argmax one token, append it, run again —
                  there is no separate "answer" module
    

    Training signal was only this: label_ids = input_ids shifted by one (done by the collator). Everything the model knows fell out of minimising that loss.

    One operation, repeated. The whole network is a next-token estimator; the sharded logits from Part A6 are these 49 152 numbers before the softmax.

    What it learns, and why that is powerful

    To predict the next token well over trillions of tokens, the cheapest internal strategy turns out to be modelling the things that generate text. None of these were objectives; all fall out of the one loss.

    to predict… it must represent…
    "The capital of France is" → " Paris" world knowledge
    "def fibonacci(n):\n if n <" → " 2" syntax and program semantics
    "She put the keys in her bag. Later she reached into her" → " bag" coreference, physical common sense
    "Q: 17 × 3 = A:" → " 51" arithmetic procedures
    "Bonjour, comment" → " allez" languages, register, style

    What a base model is not

    Using one directly

    Because it is a completion engine, you steer it by making the desired output the most probable continuation:

    Its place in the pipeline

    pretraining — this whole page · ~T tokens
        │
        ▼
    BASE MODEL — next-token estimator · the expensive, general asset
        │
        ├──► SFT (instruction data) ──► RLHF / DPO (preferences) ──► chat model
        │
        └──► task fine-tune (classification head · code · domain)
    

    SmolLM2-135M base: ~2T tokens · Llama-3-70B: ~15T. Everything downstream is cheap by comparison and reuses the same weights; the base bounds what can be built on it.

    The base model is the asset the infrastructure exists to produce. SFT, RLHF and task heads all start from these weights, which is why data pipeline, 3D parallelism and checkpointing quality matter here and not later.

    What yours will be. Trained on dair-ai/emotion (339k tokens, ~40 epochs) it is a base model in kind and useless in degree: it has memorised 16k tweets and will reproduce them near-verbatim from any prefix — "i feel" → " so hopeless and alone right now<|endoftext|>i am…". The label column was never seen (--column text), so it cannot classify emotions. Point the same config at a FineWeb-Edu sample of a few billion tokens and the identical machinery yields a small genuine general-purpose completer in SmolLM2-135M’s class, measurable with lighteval (HellaSwag, ARC, MMLU). To get an emotion classifier from this exercise instead, re-tokenise as "Tweet: {text}\nEmotion: {label}" and keep training — still a causal LM, and nanotron runs it unchanged.

    Part E · A new corpus: fab and hardware logs

    Everything above assumed web text and a borrowed tokenizer. Semiconductor tool logs, ATE / wafer-sort results, burn-in and memory-test output, GPU telemetry are a different language: timestamps, hex registers, lot/wafer/part IDs, bin codes, floating-point measurements, key=value fields — almost no prose. That changes the first decision.

    Reuse a tokenizer, or train one?

    plan tokenizer weights when
    A continued pretraining reuse (SmolLM2 / Llama) start from the pretrained checkpoint via convert_hf_to_nanotron.py corpus is mostly natural language or code; fertility ≤ 0.3 tokens/byte
    B from scratch train your own BPE random init corpus is a genuinely different language; fertility 0.5+; little pretrained knowledge transfers — the fab-log case
    C extend vocabulary pretrained + added tokens pretrained, new embedding rows initialised from sub-token means mostly language with a domain jargon layer

    A new tokenizer means new embedding and LM-head geometry, so pretrained weights cannot load: B is expensive. Decide with a measurement, not a guess — fertility = tokens per byte on a representative sample:

    one record, 146 bytes
    ts=2026-08-30T14:02:11.334Z tool=ETCH07 lot=K7A31.00 wfr=17 step=RF_ON pwr=1487.3 W press=12.04 mT dut=0x3F2A9C bin=07 status=ERR_0x4F2A
    
    general tokenizer (SmolLM2 / Llama)
    [][][][][][][][][][][][] …
    
    domain BPE trained on the logs (digits grouped 1–3, byte-level)
    [    ][      ][   ][     ][   ][     ] …
    
    tokenizer tokens for this record fertility why
    general (SmolLM2 / Llama) ≈ 85–95 ~0.6 tokens/byte Every hex byte, digit group, “=” and unit is its own token; “0x” then “3F”, “2A”, “9C”.
    domain BPE (digits grouped 1–3, byte-level) ≈ 35–40 ~0.25 tokens/byte “tool=”, “lot=”, “bin=”, “ mT”, “ERR_0x” are single tokens; digits in groups of ≤ 3.

    Same GPU budget covers 2–2.5× more records per step; inference is 2× faster; field names get one consistent embedding.

    Measure: for tok in [SmolLM2, Llama-3, StarCoder2]: len(tok(sample).input_ids) / len(sample.encode()). English ≈ 0.25. If logs ≥ 0.5 → plan B.

    Fertility is the deciding number. The bars are illustrative token boundaries for the first fields of the record; the ratios are what general vs. domain tokenizers typically produce on structured hardware logs. Code tokenizers (StarCoder2) often land in between because of digit and symbol handling.

    Dataset design — the decisions that matter for this domain

    1. Decode binary first. STDF, vendor binary logs, SECS/GEM dumps → text via pystdf / vendor SDKs. One canonical serialisation for everything.
    2. Define a document as a process unit — one lot-step on one tool, one wafer’s test session, one DUT’s burn-in run, one GPU’s telemetry window around an event. Attention only sees inside a document, so “what preceded this failure” must be inside it. Check p99 doc length from inspect_nanoset.py against sequence_length; raise to 4096–8192 if runs routinely exceed it.
    3. Canonicalise: fixed field order, key=value, units separated from numbers by a space (1487.3 W), one record per line, documents separated by <|endoftext|>. One grammar to learn, not twelve vendors’.
    4. Numbers are the crux. Digit groups of 1–3 (Llama-3 style; measured best here) · single digits (max structure, ~20% more tokens) · fixed precision / scientific notation (compact) · bucketing for dense sensor streams · or keep raw high-rate telemetry out of the LM entirely and feed it events/summaries — an LM over 10 kHz vibration data is the wrong tool.
    5. Deduplicate hard. Heartbeats and “status OK” are >90 % of raw volume. Collapse consecutive identical records to one + <REPEAT n=240>; MinHash near-duplicate documents across the corpus. Otherwise the model becomes a heartbeat generator.
    6. Rare events are the point. Put error-containing documents in their own Nanoset folder and upweight with dataset_weights, or curriculum via data_stages (broad first, error-enriched late).
    7. Split by tool and by time (train Jan–Jun, validate Jul), never randomly by line — the same lot appears on many tools.
    8. Confidentiality. Fab data is partner-confidential: raw, tokenized and the tokenizer files (a BPE vocab leaks lot/part naming) stay in your private S3; scrub operator IDs and anything person-linked (PDPA/GDPR).

    Tokenizer recipe (plan B) — built and measured

    I implemented the whole process as a small script, build_log_tokenizer.py, with three gates,, verified end-to-end on 2026-09-02 against a 17.7 MB synthetic fab corpus (generated etch-tool runs, ATE wafer-sort, HBM burn-in with ECC counts, GPU XID telemetry).

    gate what it does next
    ① fertility tok/byte of SmolLM2 / StarCoder2 / gpt2 on your logs ≥ 0.5 → ②
    ② train byte-level BPE · digits 1–3 · “=” isolated · no normalizer → ③
    ③ verify (the gate) round-trip byte-exact · fertility · field names 1-token · digits ≤ 3 PASS → ④ · FAIL → adjust design, retrain (it caught two real defects below)
    ④ tokenize + inspect preprocess_data.py → inspect_nanoset.py  

    Measured on the synthetic fab corpus (29% of bytes are digits/hex — the entropy floor):

    tokenizer tok/byte tok/line
    SmolLM2-135M 0.635 69.2
    StarCoder2 0.620  
    gpt2 0.524  
    fablog BPE 0.475 51.7 → 25% fewer tokens than SmolLM2, every field name one token
    'press=12.04' → [p][re][ss][=][12][.][04]
    ts=2026-07-03T13:04… → [202][6][-][07][-][03][T][13][:][04]…
    

    Verify caught: (a) one-token-per-digit cost 0.581 tok/byte → switched to 1–3 grouping (0.475); (b) BPE exhausted merges at 2 929 on the templated corpus → vocab now padded with reserved tokens to a %128 size.

    Measure, train, verify — then commit the GPUs. The verify gate exists because tokenizer defects are invisible until training underperforms; both defects above were caught in seconds on CPU.

    # the three gates — all run on CPU
    python build_log_tokenizer.py fertility --data ~/data/raw/fablogs --sample-mb 8
    python build_log_tokenizer.py train     --data ~/data/raw/fablogs --out ~/data/tokenizers/fablog-16k --vocab-size 16384
    python build_log_tokenizer.py verify    --tokenizer ~/data/tokenizers/fablog-16k --data ~/data/raw/fablogs
    

    The core of the tokenizer definition:

    tok = Tokenizer(models.BPE())                                  # byte-level: every byte reachable, no <unk>, decode byte-exact
    tok.pre_tokenizer = pre_tokenizers.Sequence([
        pre_tokenizers.Split(Regex(r"\d{1,3}"), "isolated"),        # Llama-3-style digit grouping: "2026"→"202","6"
        pre_tokenizers.Split("=", "isolated"),                      # "pwr=" never fuses with its value
        pre_tokenizers.ByteLevel(add_prefix_space=False)])
    tok.decoder = decoders.ByteLevel()                              # NO normalizer — logs must round-trip exactly
    trainers.BpeTrainer(vocab_size=16384, special_tokens=["<|endoftext|>", "<|pad|>"],
                        initial_alphabet=pre_tokenizers.ByteLevel.alphabet())
    # after training: pad with <|reserved_k|> up to a multiple of 128; keep < 65 536 (uint16 Nanoset)
    PreTrainedTokenizerFast(tokenizer_object=tok, eos_token="<|endoftext|>", pad_token="<|pad|>").save_pretrained(out)
    

    Design calls, each tied to a check in verify: byte-level ⇒ round-trip test; digit grouping ⇒ “digit groups ≤ 3” test and the fertility number; no normalizer ⇒ round-trip again; = isolation and merge quality ⇒ “field names single-token” probe; vocab shape ⇒ %128 / uint16 test. Model config then follows the tokenizer: vocab_size = len(tokenizer), eos_token_id = bos_token_id = 0, tokenizer_name_or_path = the saved directory, and sequence_length: 4096 (measured doc lengths: p50 ≈ 2 049, p99 ≈ 3 810 tokens — whole process runs fit in one window).

    Two pipeline gotchas found on the way: datatrove’s --tokenizer-name-or-path needs the tokenizer.json file for a local tokenizer (a directory raises HFValidationError), and afterwards the .ds.metadata first line must be edited back to the directory, which is what nanotron’s AutoTokenizer load expects. And datatrove shards by input file: one big jsonl → one shard regardless of --n-tasks; split real corpora into many files.

    Mix, size, evaluate

    downstream use how the base model serves it metric
    anomaly / excursion detection log-probability of a record given context; low = unusual AUROC vs labelled incidents, held-out tools
    failure / bin prediction fine-tune a head on the end-of-run hidden state accuracy vs actual bin
    next-event prediction native generation top-k accuracy of next status / step
    root-cause summarisation SFT on (log window → engineer’s incident note); this is where the English mix pays off human / LLM-judge rating
    log parsing / normalisation few-shot completion field-level F1

    Honest caveat. For continuous telemetry (temperatures, ECC error rates over time) dedicated time-series and anomaly models frequently beat an LM on pure numeric streams. The LM earns its place on event/state logs and on anything that must be explained. The usual production answer is a hybrid: TS models on sensor streams, the LM on events and summaries.

    Config → mechanism

    config field value what it selects above
    parallelism.tp 2 size of tp_pg; shard factor for every Column/Row linear and the embedding/lm_head vocab (A5, A6). Must divide heads and kv-heads.
    parallelism.pp 2 number of stages build_model cuts the block list into (A4); size of pp_pg.
    parallelism.dp 2 replicas; size of dp_pg; DDP + ZeRO shard factor (A7, B2, B3).
    parallelism.pp_engine 1f1b OneForwardOneBackwardPipelineEngine (B1).
    parallelism.tp_mode REDUCE_SCATTER sequence-parallel collectives; activations ÷ tp between sub-blocks (A5).
    parallelism.tp_linear_async_communication true overlap TP collectives with matmuls (A5).
    parallelism.recompute_layer false would wrap _core_forward in checkpointing (A5).
    tokens.batch_accumulation_per_replica 4 micro-batches per step = nb_microbatches in 1F1B; must be ≥ pp − 1 (B1).
    tokens.micro_batch_size · sequence_length 4 · 2048 B and S in every shape above; 16 MB per P2P transfer.
    model.model_config.tie_word_embeddings false no cross-stage tied gradient sync (A7, B2).
    model.make_vocab_size_divisible_by 128 pads V so V % (tp·128) == 0 before the lm_head shard (A6).
    optimizer.accumulate_grad_in_fp32 true FP32GradientAccumulator; async fp32 all-reduce (A7, B2).
    optimizer.clip_grad 1.0 clip_grad_norm over mp_pg (B3).
    optimizer.zero_stage 1 ZeroDistributedOptimizer — sharded Adam states (B3).
    general.ignore_sanity_checks false run the four sanity-check hooks every step (B3).

    Sources: models/llama.py, models/base.py, parallel/context.py, parallel/pipeline_parallel/{block,engine}.py, parallel/tensor_parallel/{nn,functional}.py, trainer.py at nanotron commit 2411b022.