# One Training Step and Its Data *What a training step of a large language model computes and stores, and how Megatron turns tokenized text into the batches that feed it* If you have trained a small model in PyTorch, you have written a training loop like this one: ```python for batch in loader: logits = model(batch["input_ids"]) loss = F.cross_entropy(logits.flatten(0, 1), batch["labels"].flatten()) loss.backward() optimizer.step() optimizer.zero_grad() ``` It takes a batch of examples, runs the model forward, computes the loss, calls backward, and lets the optimizer update the weights. The whole thing fits on one screen. Large language models are trained with the same loop. However, the numbers around it are very different. When Meta trained Llama 3 405B, each step of that loop processed 16 million tokens, the model was far too big for a single GPU, and the training data was about 15 trillion tokens of text. Most of a training framework exists to make that one loop run at this scale. Before we can talk about how the loop is spread over thousands of GPUs, we need a clear picture of the loop itself. So, what does one training step of a large model actually compute, how much memory does it need, and how does the data get to it? This is the first article in a series on training engineering, and I will answer these questions with Megatron Core, NVIDIA's library for training large transformers, as the running example (at commit 54f18cd21, from October 2026). For the concrete numbers, I will use Llama 3 70B as the reference model, together with the batch-size and learning-rate schedules that were published for Llama 3 405B and DeepSeek-V3, and what their 2026 successors, DeepSeek-V4 and Kimi K3, changed. Parallelism, low-precision number formats, mixture-of-experts internals and fine-tuning data each need more room than I can give them here, so I will leave them for later articles. Along the way, I will show each mechanism as a short piece of PyTorch code. The snippets assume the usual imports (`torch`, `torch.nn.functional as F`, `torch.distributed as dist`, `math` and `numpy as np`), and every one of them was run before publishing. ## 1. One Training Step Let's start with the step itself and what it costs, first in compute and then in memory. After that, we will look at how a step's batch is split up and how the loss and the learning rate are handled. ### 1.1 Forward, Backward and the Optimizer Step Most of the computation in a transformer happens in linear layers. A linear layer multiplies its input X, which has one row per token, by a weight matrix W. This is a GEMM, short for general matrix multiplication, which is the operation that GPUs are built to do fast. To count the cost of a GEMM, we count floating-point operations (FLOPs). Every weight in W is multiplied with one input value per token, and the product is added to a running sum, which is 2 FLOPs per weight per token. For example, the first matrix of an MLP block in Llama 3 70B has 8,192 x 28,672, or about 235 million, weights. Pushing one token through it costs about 470 million FLOPs. So, the forward pass costs 2 FLOPs per parameter per token. The backward pass is where training differs from inference. For every linear layer, it computes two gradients. The first is the gradient with respect to the layer's input, dX = dY W^T, which we need to keep backpropagation going into the layer before it. The second is the gradient with respect to the weights, dW = X^T dY, which is what the optimizer needs to update W. Both are GEMMs of the same size as the forward one, as illustrated in Figure 1 below. ![The three GEMMs of one linear layer](https://sleepy-capybara.vercel.app/training-step-and-data/figures/fig01_three_gemms.png) *Figure 1: Every weight matrix takes part in three GEMMs per training step: one in the forward pass and two in the backward pass.* As we can see in Figure 1, the backward pass does twice the work of the forward pass, since it has two GEMMs where the forward pass has one. In total, a training step costs 2 + 4 = 6 FLOPs per parameter per token. To make this concrete, we can write the three GEMMs out by hand as a PyTorch autograd function: ```python class Linear(torch.autograd.Function): @staticmethod def forward(ctx, x, w): ctx.save_for_backward(x, w) # x is needed again for dW return x @ w # GEMM 1: forward @staticmethod def backward(ctx, dy): x, w = ctx.saved_tensors dx = dy @ w.T # GEMM 2: data gradient dw = x.T @ dy # GEMM 3: weight gradient return dx, dw x = torch.randn(4, 16, requires_grad=True) # 4 tokens w = torch.randn(16, 32, requires_grad=True) # 16 x 32 weights Linear.apply(x, w).sum().backward() ``` If you run this and compare `x.grad` and `w.grad` with the result of a plain `x @ w`, they are the same, since this is exactly what PyTorch's autograd does for a matrix multiplication. Notice also the `save_for_backward` call: the weight gradient needs X, the input from the forward pass, so X has to be kept until the backward pass. We will come back to this in the next section, since keeping such tensors around is where much of the memory goes. The third part of a step, the optimizer step, updates each parameter once per step rather than once per token. Its FLOPs are therefore negligible next to the GEMMs, although it does read and write all of the training state, which we will also look at in the next section. Megatron counts FLOPs exactly this way. Its FLOP counter multiplies every GEMM by 3 for the forward pass, the weight gradient and the data gradient, and by 2 for the multiply and the add. For Llama 3 70B, the linear layers and the final output layer (which maps the hidden state to a score for every token in the vocabulary) hold 69.5 billion parameters, which gives 417 GFLOP per token. The input embedding is a table lookup rather than a matrix multiplication, so it does not add to the count. The 6-FLOP rule is also a good sanity check for published numbers. The Llama 3 paper reports that the 405B model was trained with 3.8 x 10^25 FLOPs on 15.6 trillion tokens, and 6 x 405 billion x 15.6 trillion is 3.79 x 10^25. However, there is one part of a transformer that does not follow the rule. In attention, every token compares its query with the keys of all earlier tokens, and then takes a weighted sum of their values. These two matrix products have no weights at all, and their cost per token grows with the length of the document. Megatron counts them as 6 x 8,192 x s FLOPs per token and layer for Llama 3 70B, where s is the document length. (The 8,192 is the total width of the 64 attention heads. The two matrix products double the work, and the causal mask, which only lets a token look backward, halves it again.) Put together, the whole count fits into a small function, which follows Megatron's formula for a dense model with grouped-query attention: ```python def train_flops_per_token(cfg, seq_len): h, layers = cfg["hidden"], cfg["layers"] q = cfg["heads"] * cfg["head_dim"] kv = cfg["kv_heads"] * cfg["head_dim"] attn_proj = h * (q + 2 * kv) + q * h # QKV and output projection mlp = 3 * h * cfg["ffn"] # SwiGLU has three matrices head = h * cfg["vocab"] # output layer linear = 6 * (layers * (attn_proj + mlp) + head) core_attn = 6 * q * seq_len * layers # scores and weighted values return linear, core_attn llama3_70b = dict(hidden=8192, ffn=28672, layers=80, heads=64, kv_heads=8, head_dim=128, vocab=128000) linear, attn = train_flops_per_token(llama3_70b, seq_len=8192) print(f"{linear / 1e9:.1f} + {attn / 1e9:.1f} GFLOP") # 417.0 + 32.2 GFLOP ``` Figure 2 below shows what the attention term adds at four document lengths. ![Training FLOPs per token for Llama 3 70B](https://sleepy-capybara.vercel.app/training-step-and-data/figures/fig02_flops.png) *Figure 2: Training FLOPs per token for Llama 3 70B at four document lengths, computed with Megatron's FLOP formula from the model's configuration.* As shown in Figure 2, attention is a small addition at the sequence lengths that pretraining typically uses. At 8,192 tokens, it adds 32 GFLOP per token, or about 7% of the step. At 131,072 tokens, it adds 515 GFLOP, which is more than all the linear layers together. The Llama 3 paper gives exactly this as the reason why it trained on long sequences only in the final stage of pretraining, for about 800 billion tokens: the compute in attention grows quadratically with the sequence length. The 2026 reports do the same in more steps: DeepSeek-V4 starts at 4K tokens and extends to 16K, 64K and finally 1M, and Kimi K3 starts at 8K and extends to 64K. Lastly, for mixture-of-experts (MoE) models, the rule applies to the active parameters only, since a token only passes through the experts that the router selects for it. For example, DeepSeek-V3 has 671 billion parameters, but only 37 billion are active per token, so a training step costs about 6 x 37 billion, or 222 GFLOP, per token. That is less than Llama 3 70B, even though the model is almost ten times larger. ### 1.2 Where Memory Goes Now, let's look at memory. A trained model is shipped as its weights, but training has to keep a lot more than the weights around. Megatron's memory estimate assumes bf16 training with the Adam optimizer, which is the baseline that lower-precision training and newer optimizers start from, and counts 18 bytes per parameter. To see where the 18 bytes come from, we need two number formats. fp32 is the standard 32-bit floating-point format. bf16 is a 16-bit format that keeps the range of fp32 but only two to three significant decimal digits, which makes GEMMs much faster and halves the memory. The forward and backward passes use bf16 weights (2 bytes per parameter). The gradients are accumulated in fp32 (4 bytes). The optimizer updates an fp32 copy of the weights (4 bytes), because many updates are too small to change a bf16 number, as we can check in PyTorch: ```python >>> one = torch.tensor(1.0, dtype=torch.bfloat16) >>> one + 1e-4 tensor(1., dtype=torch.bfloat16) >>> one.float() + 1e-4 tensor(1.0001) ``` Finally, Adam keeps two running averages per parameter, one of the gradient and one of the squared gradient (4 bytes each). Figure 3 below shows these five parts. ![Training state per parameter](https://sleepy-capybara.vercel.app/training-step-and-data/figures/fig03_bytes.png) *Figure 3: The training state per parameter in bf16 training with Adam, as assumed by Megatron's memory estimate.* Only 2 of these 18 bytes are the weights that end up in the released model. We can also count the 18 bytes directly, by creating the same five tensors for one weight matrix in PyTorch: ```python w = torch.randn(4096, 4096, dtype=torch.bfloat16) # used in the GEMMs main_w = w.float().requires_grad_() # fp32 copy main_w.grad = torch.zeros_like(main_w) # fp32 gradient opt = torch.optim.Adam([main_w], lr=1e-4) opt.step() # creates Adam's state state = opt.state[main_w] tensors = [w, main_w, main_w.grad, state["exp_avg"], state["exp_avg_sq"]] print(sum(t.numel() * t.element_size() for t in tensors) / w.numel()) # 18.0 ``` For Llama 3 70B, the 18 bytes add up to 1.27 TB. Even a B300, the GPU that the code in this article was run on, has only 288 GB of memory, so the training state alone needs five of them, before a single token has been processed. The 18 bytes are a baseline, and current runs move away from it in three ways: - **Lower-precision weights.** DeepSeek-V3 already ran most of its GEMMs in FP8, which I will cover in a later article on number formats. - **A different optimizer.** DeepSeek-V4 and Kimi K3 train most of their weights with Muon, which keeps one running average of the gradient (its momentum) instead of Adam's two, so those weights need 4 bytes less. DeepSeek-V4 still uses AdamW for the embeddings, the output layer and the norms. - **Lower-precision optimizer state.** Megatron can store the gradients and Adam's averages in lower precision. Its minimum-memory recipe keeps bf16 gradients and FP8 averages, which brings the 18 bytes down to 10. The second part of the memory is the activations. These are the intermediate results of the forward pass that the backward pass needs, such as the input X in Figure 1. Unlike the training state, activations grow with the number of tokens in flight. Megatron estimates them as s x b x h x (18 + 4 x ffn/h) bytes per layer, where s is the sequence length, b is the number of sequences, h is the hidden size and ffn is the width of the MLP. For one sequence of 8,192 tokens, that is 2.15 GB per layer of Llama 3 70B, or 172 GB for all 80 layers. Where does a formula like this come from? Korthikanti et al. went through a transformer layer and added up every tensor that the backward pass reads. At 2 bytes per value, most of the attention block is the input of the query, key and value projection, the queries, keys and values themselves, and the input of the output projection. In the MLP, the input of the second linear layer and the input of the activation function are as wide as the MLP itself, which is several times the hidden size, so the MLP holds the largest tensors. That is why the MLP width shows up in the formula: Megatron's estimate is their count with the MLP width of the actual model plugged in. The point to take away is that every one of these tensors has one row per token, so the activations grow linearly with the number of tokens that are in flight. This estimate assumes that the attention scores are never stored. That is what FlashAttention-style kernels do: they compute the scores in small tiles, never write the full matrix to memory, and compute them again in the backward pass. Without such a kernel, the attention scores and the softmax have to be kept, and Korthikanti et al. count 5 x a x s^2 x b bytes per layer for them, where a is the number of heads. We can see the difference in PyTorch with a hook that is called for every tensor that autograd keeps for the backward pass. Below, the same attention call runs once with PyTorch's plain math backend, which stores the scores, and once with its FlashAttention backend: ```python from torch.nn.attention import SDPBackend, sdpa_kernel def saved_bytes(fn, *args): sizes = [] def pack(t): # called for every tensor kept for the backward pass sizes.append(t.numel() * t.element_size()) return t with torch.autograd.graph.saved_tensors_hooks(pack, lambda t: t): fn(*args) return sum(sizes) def attention(q, k, v): return F.scaled_dot_product_attention(q, k, v, is_causal=True) q, k, v = (torch.randn(1, 16, 4096, 128, device="cuda", dtype=torch.bfloat16, requires_grad=True) for _ in range(3)) with sdpa_kernel(SDPBackend.MATH): # keeps the scores print(saved_bytes(attention, q, k, v) / 2**20) # 2144.0 MiB with sdpa_kernel(SDPBackend.FLASH_ATTENTION): # recomputes them print(saved_bytes(attention, q, k, v) / 2**20) # 64.25 MiB ``` On one of our GPUs, the math backend keeps 2,144 MiB for a single attention call with 16 heads and 4,096 tokens, while the FlashAttention backend keeps 64 MiB, which is just the queries, keys, values and output. Doubling the sequence length to 8,192 roughly quadruples the first number (8,384 MiB) and only doubles the second (128.5 MiB). Figure 4 below compares the two cases for a full layer of Llama 3 70B. ![Activations per layer](https://sleepy-capybara.vercel.app/training-step-and-data/figures/fig04_activations.png) *Figure 4: Activation memory per layer for one 8,192-token sequence of Llama 3 70B, with the attention matrix stored (left) and with a FlashAttention-style kernel (right).* As shown in Figure 4, storing the attention matrix would add 21.5 GB per layer, ten times more than everything else in the layer. So, FlashAttention-style kernels matter for memory as much as for speed, since without them a single long sequence would hardly fit into a GPU at all. To summarize this section, the training state of Llama 3 70B is 1.27 TB, and the activations of a single 8,192-token sequence are another 172 GB. Both are far beyond one GPU, and the later articles in this series are largely about the remedies: sharding the training state across GPUs, recomputing activations instead of storing them, and splitting long sequences. ### 1.3 Micro-Batches and the Global Batch So far, we looked at one sequence at a time. However, a step of Llama 3 405B used 16 million tokens, or 2,048 sequences of 8,192 tokens, while one GPU can hold the activations of only one or a few sequences at a time. So, how does a step process 2,048 sequences? The batch is split in two ways. First, it is split across data-parallel ranks. A rank is one training process, usually one GPU, and in data parallelism every rank holds a copy of the model, processes different sequences and averages its gradients with the other ranks, so that all copies take the same optimizer step. (I will cover data parallelism properly in the next article.) Second, each rank splits its share over time into micro-batches. It runs the forward and backward pass for one micro-batch, adds the gradients to a buffer, moves on to the next micro-batch, and only steps the optimizer after the last one. This is called gradient accumulation, and it is shown in Figure 5 below. ![Micro-batches and the global batch](https://sleepy-capybara.vercel.app/training-step-and-data/figures/fig05_microbatches.png) *Figure 5: Four data-parallel ranks, each running three micro-batches of two sequences, make a global batch of 24 sequences.* In PyTorch, with the model wrapped in `DistributedDataParallel` (DDP), gradient accumulation looks like this: ```python from contextlib import nullcontext for i, mb in enumerate(micro_batches): last = i == len(micro_batches) - 1 # skip the gradient all-reduce for all but the last micro-batch with nullcontext() if last else model.no_sync(): loss = loss_fn(model(mb["x"]), mb["y"]) (loss / len(micro_batches)).backward() optimizer.step() optimizer.zero_grad() ``` The `no_sync` context tells DDP not to average the gradients across ranks after every backward pass. They are only averaged once, after the last micro-batch, when the buffer holds the sum of all of them. As illustrated in Figure 5, the global batch is the micro-batch size times the number of data-parallel ranks times the number of micro-batches per rank. Megatron derives the number of micro-batches from the global batch, the micro-batch size and the number of ranks, and requires the division to come out even. For a real example, the Llama 3 405B run on 16,384 GPUs had 128 data-parallel replicas of the model, each of which processed 16 of the 2,048 sequences per step. (Each replica was itself spread over 128 GPUs, for reasons we will get to in later articles.) Since gradients add up, accumulating over three micro-batches gives the same result as one big batch, as long as the loss is averaged correctly, which is the topic of the next section. Interestingly, many large runs do not keep the global batch fixed. Llama 3 405B started with 4 million tokens per step at a sequence length of 4,096, doubled to 8 million tokens at a sequence length of 8,192 after 252 million tokens, and doubled again to 16 million after 2.87 trillion tokens. According to the paper, the smaller batch early on was for training stability and the larger batch later on for efficiency. DeepSeek-V3 also grew its batch, from 3,072 to 15,360 sequences of 4K tokens over the first 469 billion tokens, and DeepSeek-V4 kept the same strategy in 2026, growing to 75.5 million tokens per step (94.4 million for the larger V4-Pro). Figure 6 below shows both schedules. ![Batch-size schedules](https://sleepy-capybara.vercel.app/training-step-and-data/figures/fig06_batch_schedules.png) *Figure 6: The batch-size schedules of Llama 3 405B and DeepSeek-V3, in millions of tokens per step, over the number of training tokens seen so far (on a log scale).* As we can see in Figure 6, both runs reached their final batch size early, within the first 20% of their training tokens. (The DeepSeek-V3 paper only says that the batch grew gradually, so the dashed line simply connects the two ends.) Megatron supports such schedules as a list of token counts at which the batch size changes. The example in its code starts at 768 sequences and doubles at 250, 500 and 750 billion tokens. It used to offer a smooth linear ramp of the batch size as well, but that option is now deprecated in favor of the step schedule. Either way, a larger global batch means more micro-batches per step, while the micro-batch size stays the same. ### 1.4 Loss Normalization The training loss is the average cross-entropy over all the tokens that the model has to predict. With micro-batches and data-parallel ranks, though, there are two ways to compute that average, and they do not always agree. By default, Megatron divides the summed loss of each micro-batch by that micro-batch's own number of tokens, and then by the number of micro-batches. The gradient reduction across data-parallel ranks then averages over the ranks. This gives every micro-batch the same weight, no matter how many tokens it had. In pretraining, that is perfectly fine, since every sample is a full sequence and every micro-batch has the same number of tokens. However, in fine-tuning, the prompt tokens are usually masked out of the loss, so the number of tokens that count toward the loss differs from one micro-batch to the next. Then a token in a micro-batch with few such tokens gets a larger weight than a token in a micro-batch with many. Figure 7 below shows a small example with two micro-batches. ![Two ways to average the loss](https://sleepy-capybara.vercel.app/training-step-and-data/figures/fig07_loss_norm.png) *Figure 7: Averaging per micro-batch (left) and per token (right) for two micro-batches with 2 and 8 tokens that count toward the loss.* As shown in Figure 7, averaging per micro-batch gives each of the 2 tokens in the first micro-batch a weight of 1/4 and each of the 8 tokens in the second micro-batch a weight of 1/16. In other words, one token in the short micro-batch counts as much as four tokens in the long one. To fix this, we need the number of loss tokens in the whole global batch before we divide. In plain PyTorch, the simplest way is to count them first, since the masks are known as soon as the batch is loaded: ```python # count the loss tokens of the whole global batch first n = sum(mb["mask"].sum() for mb in micro_batches) dist.all_reduce(n) # add up the counts of all data-parallel ranks for mb in micro_batches: logits = model(mb["x"]) ce = F.cross_entropy(logits.flatten(0, 1), mb["y"].flatten(), reduction="none") loss = (ce * mb["mask"].flatten()).sum() / n (loss * dist.get_world_size()).backward() # DDP averages ``` (The last line multiplies by the number of ranks because DDP averages the gradients over the ranks, and we want a sum over all of them divided by the global token count. For brevity, I left out the `no_sync` context from the previous section.) Megatron does the same thing in a different order. With per-token normalization turned on, the micro-batches return their summed loss without dividing it, and after the backward pass Megatron counts the tokens over the whole global batch and divides all gradients by that total once. Below is that step, cut down from [`finalize_model_grads.py`](https://github.com/NVIDIA/Megatron-LM/blob/54f18cd21/megatron/core/distributed/finalize_model_grads.py): ```python # the number of tokens is only present on the last stage, # so broadcast it to the other ranks in the pipeline. torch.distributed.broadcast(num_tokens, src=last_rank, group=pp_group) # all-reduce across DP ranks. torch.distributed.all_reduce(num_tokens, group=dp_cp_group) scaling = 1.0 / torch.clamp(num_tokens, min=1) for model_chunk in model: model_chunk.scale_gradients(scaling) ``` The count is all-reduced across the data-parallel ranks, so it covers the whole global batch, and the gradients are scaled once, after the backward pass and before the optimizer step. (The broadcast is there because, with pipeline parallelism, only the last stage of the model computes the loss, which we will get to in a later article.) Every token in the global batch then gets the same weight, which is 1/10 in the example of Figure 7. Megatron applies the same choice to the auxiliary losses that some models add, such as the load-balancing loss of a mixture-of-experts model, so that they stay on the same scale as the main loss. Its newest packing path, added in August 2026, makes the choice for you: when it packs variable-length samples into micro-batches, it refuses to run without per-token normalization, since the packed micro-batches carry different numbers of tokens. ### 1.5 Learning-Rate Schedules The last part of the step is the learning rate, which says how far the optimizer moves the weights at each step. It is almost never constant over a run. Nearly every run starts with a warmup, which increases the learning rate linearly from close to zero to its peak over the first few thousand steps. Llama 3 405B warmed up over 8,000 steps and DeepSeek-V3 over 2,000 steps. The usual explanation is that this keeps the first updates small while the weights are still random and Adam's running averages are based on very few steps. After the warmup, two shapes are common. A cosine schedule starts decaying right away and follows half a cosine curve down to a minimum. Llama 3 405B used one, decaying from 8 x 10^-5 to 8 x 10^-7 over 1.2 million steps. A warmup-stable-decay (WSD) schedule instead holds the peak for most of the run and decays only at the end. DeepSeek-V3's schedule has this shape: it stayed at the peak until 10 trillion of its 14.8 trillion tokens, decayed along a cosine over the next 4.3 trillion, and finished with two short constant phases. Figure 8 below shows both schedules over their full length. ![Learning-rate schedules](https://sleepy-capybara.vercel.app/training-step-and-data/figures/fig08_lr.png) *Figure 8: The learning-rate schedules of Llama 3 405B and DeepSeek-V3, as a fraction of the peak learning rate, over the length of each schedule.* The two schedules spend most of the run at very different learning rates, as Figure 8 shows. Halfway through its schedule, Llama 3 405B was at about half of its peak, while DeepSeek-V3 was still at the full peak. In PyTorch, a WSD schedule is a small function that returns a factor for the base learning rate at every step, which `LambdaLR` then applies: ```python def wsd(step, warmup=2_000, total=100_000, decay=20_000, floor=0.1): if step < warmup: return step / warmup if step < total - decay: return 1.0 r = (step - (total - decay)) / decay return floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * r)) scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, wsd) ``` The stable phase is simply a factor of 1.0 until the last `decay` steps, and the shape of the decay only matters after that point. Megatron implements the same shapes in its [`optimizer_param_scheduler.py`](https://github.com/NVIDIA/Megatron-LM/blob/54f18cd21/megatron/core/optimizer_param_scheduler.py): warmup together with constant, linear, cosine, inverse-square-root and WSD decay, where WSD can anneal linearly, along a cosine, exponentially, or as one minus a square root. An important detail is that Megatron counts the schedule in samples rather than in steps: the warmup and decay lengths are converted to iterations times the global batch size. So, when the batch size grows, as in Figure 6, the schedule still follows the amount of data the model has seen. In 2026, both shapes are still in use. DeepSeek-V4 holds its peak learning rate for most of the run and decays along a cosine near the end, while Kimi K3 uses a plain cosine schedule with a warmup over the first 1% of training. So, which one is better? The Kimi K3 report has the most careful comparison I know of. Its authors found that the two schedules have quite different optimal peak learning rates and batch sizes, so comparing them with one shared set of hyperparameters favors whichever schedule those hyperparameters happen to suit. When they tuned each schedule separately, cosine consistently reached a lower final loss. On the other hand, the long stable phase of WSD does not depend on when training will end, so a run can be extended, or a checkpoint from the middle of the stable phase branched off into its own decay, without restarting the schedule. I would guess that this flexibility is part of why DeepSeek still uses it. ## 2. Data Now that we know what a step does with a batch, let's look at where the batch comes from. I think this is the part of a training framework that is explained the least, since most of it only exists in the code. We will follow the data from the raw text on disk to the samples in a batch, and then look at what changes at the scale of thousands of GPUs. ### 2.1 Tokenized Datasets on Disk A model does not read text, it reads token ids, the integers that a tokenizer maps pieces of text to. Tokenizing terabytes of text is slow, so Megatron does it once, ahead of training. Its preprocessing tool reads a JSONL file, which has one document per line, tokenizes every document, optionally appends an end-of-document token, and writes the result into two files. The .bin file holds all token ids one after the other, and the .idx file says where each document starts and how long it is, as shown in Figure 9 below. ![A tokenized dataset on disk](https://sleepy-capybara.vercel.app/training-step-and-data/figures/fig09_bin_idx.png) *Figure 9: The .bin file is one stream of token ids. The .idx file holds a short header, the length of every document and its byte offset in the .bin file.* As we can see in Figure 9, the .idx file starts with a 34-byte header, which holds a magic string, a version number, a code for the type of the token ids, and the number of sequences and documents. After the header come three arrays: the length of each sequence, its byte offset in the .bin file, and the boundaries of the documents. (A document can consist of several sequences, for example sentences, although for pretraining each document is usually one sequence.) Since the format is this simple, we can read it back with a few lines of NumPy: ```python import struct import numpy as np def open_dataset(prefix): with open(prefix + ".idx", "rb") as f: assert f.read(9) == b"MMIDIDX\x00\x00" version, code = struct.unpack("= kv_idx) S = len(tokens) block_mask = create_block_mask(document_causal, None, None, S, S) out = torch.compile(flex_attention)(q, k, v, block_mask=block_mask) ``` FlexAttention turns the mask into a list of blocks that need computing, and the compiled kernel skips the others, so it never builds the full S x S matrix. Megatron's own path passes the document boundaries (`cu_seqlens`) to the attention kernel instead, which has the same effect. Per-document masks also save work. In Figure 12, only the triangles on the diagonal remain, so the attention cost is proportional to the sum of the squared document lengths rather than the square of the sample length. For example, eight documents of 1,024 tokens in a sample of 8,192 tokens need only one eighth of the attention FLOPs. Megatron's FLOP counter accounts for this by using the actual document lengths in packed batches. ### 2.5 Data Loading at Scale You might expect data loading to become a bandwidth problem at scale, but it rarely does. One sample of 8,193 tokens at 4 bytes each is 32 KiB, while a training step takes seconds. (For Llama 3 405B on 16,384 GPUs, dividing the FLOPs of one step by the 400 TFLOPS per GPU that the paper reports gives about six seconds.) The problems at scale are about startup and file metadata instead. Megatron's guide on data loading describes two such problems at 256 nodes and more. The first is the barrier from section 2.2: while rank 0 builds the indices, every other rank waits, which on a 512-node job means that 4,095 GPUs sit idle. The second comes right after the barrier, when all ranks memory-map the same large index files at the same time and cause a burst of page faults and I/O. Figure 13 below shows both on a timeline. ![Startup at 512 nodes](https://sleepy-capybara.vercel.app/training-step-and-data/figures/fig13_startup.png) *Figure 13: Building the indices when the job starts (left) and building them ahead of time (right).* As illustrated in Figure 13, the fix is to take the index building out of the training job. The guide recommends four things. First, consolidate the data into large files, since thousands of 100 MB files perform much worse than tens of files of 10 GB or more. Second, build the index cache in a separate step before training starts. Third, let the training job trust that cache instead of checking that every file exists, and memory-map each index only when a sample from it is first requested, which spreads the page faults out over the first steps instead of concentrating them at the barrier. A related option precomputes the number of sequences in every dataset, so that the job does not have to open thousands of .idx files at startup just to read their headers. Fourth, before tuning any of this, measure the ceiling with synthetic data that bypasses the data pipeline completely, so that you know how much the loader actually costs. When the data lives in object storage such as S3 rather than on a shared filesystem, memory mapping does not apply. In that case, Megatron caches the small .idx files on local disk and streams the .bin files in chunks of 256 MB. ## 3. Summary To wrap up, let's go over the two halves once more. A training step of a dense model costs about 6 FLOPs per parameter per token, 2 in the forward pass and 4 in the backward pass, plus an attention term that grows with the document length. It keeps 18 bytes of training state per parameter in bf16 training with Adam, plus activations that grow with the number of tokens in flight. The global batch is the micro-batch size times the data-parallel ranks times the micro-batches per rank, and it often grows in steps early in a run. The loss should be normalized per token whenever micro-batches have different numbers of tokens, and the learning rate follows a warmup and then a cosine or warmup-stable-decay schedule (Kimi K3 found cosine better when each is tuned on its own), which Megatron counts in samples. On the data side, text is tokenized once into a .bin file of token ids and an .idx file of offsets. Three index arrays turn shuffled documents into fixed-length samples, blending follows a deterministic rule that keeps every prefix on target, and packing either lets attention cross document boundaries or masks it per document. At the scale of thousands of GPUs, the hard part of data loading is startup rather than bandwidth. All of this assumed that one GPU can hold the whole model, which, as we saw in section 1.2, is far from true. In the next article, I will start spreading the step over many GPUs, beginning with data parallelism and the distributed optimizer, which splits most of those 18 bytes per parameter across the data-parallel ranks. ## Sources - [Megatron-LM at commit 54f18cd21](https://github.com/NVIDIA/Megatron-LM/tree/54f18cd21) - [Megatron Core: Data Loading at Scale](https://github.com/NVIDIA/Megatron-LM/blob/54f18cd21/docs/user-guide/data-loading.md) - [Megatron Core: Distributed Optimizer](https://github.com/NVIDIA/Megatron-LM/blob/54f18cd21/docs/user-guide/features/dist_optimizer.md) - [The Llama 3 Herd of Models](https://arxiv.org/abs/2407.21783) - [DeepSeek-V3 Technical Report](https://arxiv.org/abs/2412.19437) - [DeepSeek-V4 Technical Report](https://arxiv.org/abs/2606.19348) - [Kimi K3 Technical Report](https://arxiv.org/abs/2607.24653) - [Fewer Truncations Improve Language Modeling](https://arxiv.org/abs/2404.10830) (Ding et al.) - [Megatron Core: Low-Precision Training Guide](https://github.com/NVIDIA/Megatron-LM/blob/54f18cd21/docs/user-guide/features/low_precision_training.md) - [Reducing Activation Recomputation in Large Transformer Models](https://arxiv.org/abs/2205.05198) (Korthikanti et al.) - [FlashAttention](https://arxiv.org/abs/2205.14135)