Training
[Chinchilla / Scaling Laws] Calculating Training FLOPs: Why 6ND?π
Papers: Training Compute-Optimal Large Language Models β Appendix F (Hoffmann et al., 2022) and Scaling Laws for Neural Language Models (Kaplan et al., 2020).
For a dense transformer, a useful estimate of training compute is \( C \approx 6ND \) FLOPs, where N is the parameter count and D is the total number of training tokens processed, including repeated tokens. FLOPs count floating-point operations; FLOP/s measures speed.
Start With One Linear Layerπ
Let \( Y = XW \), with X shaped \( T\times i \) (T token positions, i input features), W shaped \( i\times o \), and Y shaped \( T\times o \). The layer has \( N_{\mathrm{layer}} = io \) weights.
Each output element is a dot product: approximately i multiplications and i additions. Counting a multiply-add as two FLOPs, the forward matrix multiplication costs approximately \( 2Tio \).
For backpropagation, let \( G = \partial L/\partial Y \), the gradient arriving from the next layer:
| Pass | Calculation | Approximate FLOPs |
|---|---|---|
| Forward | \( Y = XW \) | \( 2Tio \) |
| Backward: weights | \( \partial L/\partial W = X^{\mathsf{T}}G \) | \( 2Tio \) |
| Backward: input activations | \( \partial L/\partial X = GW^{\mathsf{T}} \) | \( 2Tio \) |
| Total | One forward + two backward matrix multiplications | \( 6T N_{\mathrm{layer}} \) |
Why differentiate with respect to X? Its gradient carries the loss signal back to earlier layers so their weights can be trained. We update W; we propagate through X. Backward therefore costs roughly twice forward.
Scale to the Training Runπ
Sum over the model's dominant weight matrices and all D training tokens:
- Forward: approximately \( 2ND \) FLOPs.
- Backward: approximately \( 2\times 2ND = 4ND \) FLOPs.
- Total: approximately \( 6ND \) FLOPs.
For example, \( 6\times(7\times10^9)\times10^{12} \approx 4.2\times10^{22} \) FLOPs across the full run, not per GPU.
Remember: the first 2 is multiply + add; the 3 is forward + weight gradient + activation gradient.
What the Estimate Leaves Outπ
This approximates dense, full-parameter training dominated by weight matrix multiplications. Attention's token-to-token operations add sequence-length-dependent compute; long contexts can make that significant. Activation checkpointing adds recomputation. Optimizer updates, other operations, and distributed communication also need separate accounting. Some boundary activations do not require gradients, so the three-matmul picture is an approximation across the model.
For MoE, total stored parameters do not all participate in every token's computation; see active parameters and MoE scaling below. 6ND estimates arithmetic, not memory use or elapsed training time.
Learning reference: Umar Jamil, Building a distributed training framework from first principles, chapter 00:16:50 β Model Architecture, Parameters and Training FLOPs; companion code.
[MoE Scaling] Active Parameters, Granularity, and Training FLOPsπ
Paper: Scaling Laws for Fine-Grained Mixture of Experts β Ludziejewski et al., ICML 2024. The February 2024 preprint provides the equations referenced below.
Start with DeepSeekMoE's shared and routed experts, then apply the 6ND derivation above. The following bookkeeping and numerical example are explanatory derivations, not reported model configurations.
Dense, Routed, Total, and Active Parametersπ
An expert's weight matrices can be dense even when expert selection is sparse. βSparseβ describes which experts execute for a token. Distinguish the stored parameter count from the weights used in its computation.
For one block with equal-size experts, define:
| Symbol | Meaning |
|---|---|
| \( P_{\mathrm{base}} \) | Always-used matrix weights outside the experts, such as attention projections |
| \( P_e \) | Matrix weights in one expert |
| \( N_s \) | Number of shared experts; all execute |
| \( N_r \) | Number of available routed experts |
| \( K_r \) | Number of routed experts selected for a token |
Excluding router weights and small bias/normalization terms:
An ordinary two-matrix FFN with model width d and intermediate width h has \( P_e\approx 2dh \) weights: one d Γ h matrix and one h Γ d matrix. A three-matrix gated FFN has \( P_e\approx 3dh \). Count the actual matrices in the architecture you are studying.
For unequal expert sizes, sum their individual weight counts. For a complete model, sum over blocks, including any dense FFNs that remain. Account for the input embedding lookup and vocabulary output projection separately: storing an embedding table does not mean multiplying by every entry for each input token.
From Active Weights to Training FLOPsπ
The earlier matrix-multiplication argument applies to each executed expert: forward costs roughly two FLOPs per weight per token, and backward contributes roughly four more. For D processed training tokens:
This is the block-weight contribution. Add router computation, attention's token-to-token products, the output head, and other omitted operations for a fuller estimate. If active weight counts vary by token, replace D times a fixed count with the sum over tokens.
Worked example: each of twelve identical blocks has 2M base weights, 1 shared expert, 8 routed experts, and \( K_r=2 \). Each expert has 1M weights.
| Quantity | Calculation | Result |
|---|---|---|
| Stored block weights | 2M + (1 + 8) Γ 1M | 11M |
| Active block weights per token | 2M + (1 + 2) Γ 1M | 5M |
| Stored weights across 12 blocks | 12 Γ 11M | 132M |
| Active weights across 12 blocks | 12 Γ 5M | 60M |
| Training block matmuls over 1B tokens | 6 Γ 60M Γ 1B | \( 3.6\times10^{17} \) FLOPs |
Using all 132M block weights would give \( 7.92\times10^{17} \) FLOPs, incorrectly treating every routed expert as active on every token. These are block subtotals, not full-model parameter counts or complete training costs.
Stored weights still require memory somewhere, together with gradients and optimizer state during training. Routing, expert dispatch, load imbalance, and communication affect elapsed time; a FLOPs ratio alone does not establish a speedup.
Granularity and the Scaling Lawπ
The scaling paper studies granularity \( G = h_{\mathrm{ff}}/h_{\mathrm{expert}} \) and expansion E = total expert weights / dense-FFN weights. Its setup has \( EG \) available experts and activates G per token. Increasing G shrinks each expert while retaining the active expert-weight budget. This setup does not prescribe DeepSeekMoE's shared-expert split. Section 4.
The preprint fits loss as:
Here N counts non-embedding model weights, excluding routing in its parameter model; D counts training tokens. The remaining symbols are fitted constants. Use the paper's N consistently; substituting active parameters into this fitted law changes its meaning. Sections 5β6.
At fixed expansion, the study jointly optimizes model size, tokens, and granularity for a FLOPs budget, explicitly charging routing overhead. Its compute-optimal comparisons favor fine-grained MoE within the studied setup and extrapolations. Larger extrapolations and hardware speedups need separate validation. Section 6.
[Self-Reward] Self Rewarding Language Modelsπ
Arxiv: https://arxiv.org/abs/2401.10020 18 Jan 2024 Meta
In this work, we study Self-Rewarding Language Models, where the language model itself is used via LLM-as-a-Judge prompting to provide its own rewards during training. We show that during Iterative DPO training that not only does instruction following ability improve, but also the ability to provide high-quality rewards to itself.

Our approach first assumes access to a base pretrained language model, and a small amount of human-annotated seed data. We then build a model that aims to possess two skills simultaneously: 1. Instruction following: given a prompt that describes a user request, the ability to generate a high quality, helpful (and harmless) response. 2. Self-Instruction creation: the ability to generate and evaluate new instruction following examples to add to its own training set.
While we report the results of both approaches in our experiments, we find that learning from preference pairs gives superior performance, and hence recommend that approach.

Iterative Training Our overall procedure trains a series of models M1, . . . , MT where each successive model t uses augmented training data created by the t β 1 th model. We thus define AIFT(Mt) to mean AI Feedback Training data created using model Mt. Model Sequence We thus define the models, and the training data they use as follows: M0 : Base pretrained LLM with no fine-tuning. M1 : Initialized with M0, then fine-tuned on the IFT+EFT seed data using SFT. M2 : Initialized with M1, then trained with AIFT(M1) data using DPO. M3 : Initialized with M2, then trained with AIFT(M2) data using DPO.

[In-Context Pretraining] Language Modeling Beyond Document Boundariesπ
Arxiv: https://arxiv.org/abs/2310.10638 Oct 2023 Meta
We instead present IN-CONTEXT PRETRAINING, a new approach where language models are pretrained on a sequence of related documents, thereby explicitly encouraging them to read and reason across document boundaries.
IN-CONTEXT PRETRAINING instead reorders the pretraining data by combining several semantically related documents to create a coherent input context, thereby exposing LMs to long relevant contexts and providing pretraining signals beyond document boundaries.
However, this document sorting problem is challenging. LMs are typically trained on billions of
documents and we would like to sort them to maximize document similarity in the input context
windows without repeating any data. We introduce two new approximate algorithms to tackle these challenges.

Techniques are using embedding models and top-k similarity search and leveraging approximate solutions for the traveling salesman problem - by the means of visiting every document once.
[DPO] Direct Preference Optimization: Your LM is Secretly a Reward Modelπ
Arxiv: https://arxiv.org/abs/2305.18290 May 2023 Stanford
flowchart LR
subgraph RLHF["Traditional RLHF"]
Data1[Preference Data] --> RM[Train Reward Model]
RM --> RL[RL Fine-tuning]
RL --> Model1[Aligned Model]
end
subgraph DPO["Direct Preference Optimization"]
Data2[Preference Data] --> Loss["Classification Loss\n(Binary Cross-Entropy)"]
Loss --> Model2[Aligned Model]
end
style DPO fill:#e8f5e9,color:#000
In this paper we introduce a new parameterization of the reward model in RLHF that enables extraction of the corresponding optimal policy in closed form, allowing us to solve the standard RLHF problem with only a simple classification loss. The resulting algorithm, which we call Direct Preference Optimization (DPO), is stable, performant, and computationally lightweight,
eliminating the need for sampling from the LM during fine-tuning or performing significant hyperparameter tuning.

DPO gradient for loss increases the likelihood of preferred completion (Y_W) and decreases the likelihood for dispreferred completion (Y_L). Importantly, the examples are weighed by how much higher the implicit reward model rΛΞΈ rates the dispreferred completions, scaled by Ξ², i.e, how incorrectly the implicit reward model orders the completions, accounting for the strength of the KL constraint.
DPO outline. The general DPO pipeline is as follows: 1) Sample completions y1, y2 βΌ Οref(Β· | x) for every prompt x, label with human preferences to construct the offline dataset of preferences D = {x (i) , y (i) w , yl) (i)} N i=1 and 2) optimize the language model ΟΞΈ to minimize LDPO for the given Οref and D and desired Ξ².
[RLHF] Secrets of RLHF in LLMs Part II: Reward Modelingπ
Arxiv: https://arxiv.org/abs/2312.15503 24 Dec 2023 Fudan NLP
In conclusion, while RLHF is a significant advancement in AI development, particularly in integrating human preferences into the learning process, it also presents unique challenges. These include the inherent noise and ambiguity in human feedback, potential biases in the data, and the generalization limits of reward models trained on specific datasets. Addressing these challenges is crucial for the advancement and ethical application of RLHF in AI systems.

To enhance the generalization ability of the reward model, we explore contrastive learning and
meta-learning. By introducing unsupervised contrastive loss during the reward modeling process, the reward model can better distinguish subtle preference differences among responses. To bridge the gap between the preference data distribution and the model output distribution, we employ meta-learning to ensure that the reward model not only performs well on the preference data but also can distinguish the differences in target domain outputs.
Technique is to randomize training data and do a k-fold split, build K models and then measure mean and deviations - negative mean is usually the mistakes.
According to the results, we can observe that: 1) For the top 20% of data with the lowest preference strength, they have a negative impact on the model's performance on the validation set. The preference strength for these data subsets is less than 0. 2) For data ranked between 20% and 40%, after training, the model's prediction accuracy on the validation set is approximately 0.5. The preference strength for this type of data is around 0. 3) The remaining data significantly improves the model's performance. However, the top 10% of data with the highest preference strength does not achieve the best performance when trained alone. Based on the above results, we can roughly categorize preference data into three types: incorrect data, ambiguous data (almost no difference), and normal data (clear differences). These three types of preference data play different roles and make different contributions to preference modeling. It is necessary for us to conduct a more detailed analysis of them and then consider how to handle each type.
[LLARA] Making LLMs A Better Foundation For Dense Retrievalπ
Arxiv: https://arxiv.org/abs/2401.06080 11 Jan 2024 Beijing Academy of AI
In this paper, we propose a novel approach, called LLaRA (LLM adapted for dense RetrievAl), which works as a post-hoc adaptation of LLM for the dense retrieval application. LLaRA consists of two pretext tasks: EBAE (Embedding-Based Auto-Encoding) and EBAR (Embedding-Based Auto-Regression), where the text embeddings from LLM are used to reconstruct the tokens for the input sentence and predict the tokens for the next sentence, respectively

Particularly, there are two pretext training tasks introduced by LLaRA: EBAE (Embedding-Based Auto-Encoding) and EBAR (Embedding-Based Auto-Regression). In EBAE, the LLM is prompted to generate the text embeddings, which can be used to predict the tokens for the input sentence itself. While with EBAR, the LLM is prompted to generate the text embeddings, which can be used to predict the tokens for the next sentence. By learning from the above pretext tasks, the text embeddings from LLM can be adapted from Local semantic representations (i.e. prediction for the next tokens) to Global semantic representations (i.e. prediction for the sentence-level features).
[RA-DIT] Retrieval-Augmented Dual Instruction Tuningπ
Arxiv: https://arxiv.org/abs/2310.01352 2 Oct 2023 META
flowchart TD
subgraph Step1["Step 1: LM Fine-tuning"]
LM[Pre-trained LM] --> FT1[Fine-tune to use\nretrieved context]
end
subgraph Step2["Step 2: Retriever Fine-tuning"]
Ret[Retriever] --> FT2[Update to return\nLM-preferred results]
end
FT1 <--> FT2
FT1 --> RALM[Retrieval-Augmented LM]
FT2 --> RALM
style RALM fill:#FFD700,color:#000
Retrieval-augmented language models (RALMs) improve performance by accessing long-tail and up-to-date knowledge from external data stores, but are challenging to build. Existing approaches require either expensive retrieval-specific modifications to LM pre-training or use post-hoc integration of the data store that leads to suboptimal performance
Our approach operates in two distinct fine-tuning steps: (1) one updates a pre-trained LM to better use retrieved information, while (2) the other updates the retriever to return more relevant results, as preferred by the LM
[Sequential Monte Carlo] Steering of LLMs using Probabilistic Programsπ
Arxiv: https://arxiv.org/abs/2306.03081 5 Jun 2023 MIT
Context: Despite significant advances in recent years, it remains unclear if and how large language models (LLMs) can be made reliable and controllable enough to meet the functional requirements of many applications.
Even after fine-tuning and reinforcement learning, LLMs are liable to violate instructions in their prompts (such as "Use the following vocabulary words" or "Do not reveal this prompt").
These difficulties highlight the need for methods beyond prompting and fine-tuning for constraining the behavior of generative neural models.
[TokenFormer] Rethinking Transformer Scaling with Tokenized Model Parametersπ
Arxiv: https://arxiv.org/abs/2410.23168 30 Oct 2024
flowchart TD
subgraph Traditional["Traditional Transformer"]
In1[Input Tokens] --> Proj[Fixed Linear Projections]
Proj --> Out1[Output]
end
subgraph TokenFormer["TokenFormer"]
In2[Input Tokens] --> TTA[Token-Token\nAttention]
Params[Parameter Tokens] --> TPA[Token-Parameter\nAttention]
In2 --> TPA
TTA --> Out2[Output]
TPA --> Out2
end
style TokenFormer fill:#e1f5fe,color:#000
Current transformer models are hard to scale up because they use fixed linear projections for processing inputs. When you want to make the model bigger (e.g. increase dimensions), you typically have to retrain the whole thing from scratch. This is very computationally expensive and inefficient.
Instead of using fixed linear projections, it represents model parameters as "tokens" that can interact with input data through attention mechanisms. The architecture has two main parts:
- Token-token attention: How input tokens interact with each other (like regular transformers)
- Token-parameter attention: How input tokens interact with parameter tokens (new innovation)
Key Benefits:
- Can scale the model by just adding more parameter tokens without changing core architecture
- Can reuse parameters from smaller models when scaling up
- Doesn't need full retraining from scratch
Parameter tokens come in key-value pairs. Input tokens act as queries that attend to these parameter tokens. Can add more key-value parameter pairs to increase model capacity. Old parameters can be preserved while adding new ones.
Results:
- Successfully scaled from 124M to 1.4B parameters incrementally
- Achieved similar performance to transformers trained from scratch
- Required much less training compute (saved >50% training cost)
- Works well for both language and vision tasks
[Context Distillation] Learning by Distilling Contextπ
Arxiv: https://arxiv.org/abs/2209.15189 30 Sep 2022 UC
Given a synthetic unlabeled input for the target task, we condition the model on [instructions] + [task-input]'' to predict [scratch-pad] + [final answer]''; then we fine-tune the same model to predict its own [final answer]'' conditioned on the [task-input]'', without seeing the [instructions]'' or using the [scratch-pad]''.
[ALPHALLM] Toward Self-Improvement of LLMs via Imagination, Searching, and Criticizingπ
Arxiv: https://arxiv.org/abs/2404.12253 18 Apr 2024
flowchart LR
Imagine["π― Imagination\n(Data Synthesizer)"] --> Search["π Search\n(Optimized MCTS)"]
Search --> Critic["π Criticize\n(Trio of Critics)"]
Critic --> |Feedback| Search
Search --> Output["Improved\nLLM Output"]
style Output fill:#90EE90,color:#000
ALPHALLM is an imagination-searching-criticizing framework designed for the self-improvement of LLMs without the necessity of additional annotations. At its heart is the integration of MCTS with LLMs. To tackle the inherent challenges associated with this integration, including data scarcity, the vastness of search spaces, and the subjective nature of feedback in language tasks, it introduces:
- A data synthesizer for strategic prompt synthesis
- An optimized MCTS tailored for efficient search in language tasks
- A trio of critic models to provide precise feedback
Experimental findings on mathematical reasoning tasks reveal that ALPHALLM significantly boosts the performance of LLMs without requiring extra data annotations. Moreover, when decoded with Ξ·MCTS, ALPHALLM performs comparably to GPT-4, highlighting the potential for self-improvement in LLMs.
[Multi-Token Prediction] Better & Faster LLMs via Multi-token Predictionπ
Arxiv: https://arxiv.org/abs/2404.19737 30 Apr 2024 Meta AI
flowchart LR
subgraph Standard["Standard (1 token)"]
H1[Hidden State] --> Head1[Head]
Head1 --> T1["Token t+1"]
end
subgraph Multi["Multi-Token (n tokens)"]
H2[Shared Trunk] --> Head2a[Head 1]
H2 --> Head2b[Head 2]
H2 --> Head2c[Head 3]
H2 --> Head2d[Head 4]
Head2a --> T2a["t+1"]
Head2b --> T2b["t+2"]
Head2c --> T2c["t+3"]
Head2d --> T2d["t+4"]
end
style Multi fill:#fff3e0,color:#000
Training language models to predict multiple future tokens at once results in higher sample efficiency. A key fix for memory problems is to not materialize all logits and keep shared trunk and sequential pass on heads.
[Quiet-STaR] LMs Can Teach Themselves to Think Before Speakingπ
Arxiv: https://arxiv.org/abs/2403.09629 14 Mar 2024 Stanford
Quiet-STaR is a generalization of STaR in which LMs learn to generate rationales at each token to explain future text, improving their predictions. Instead of thinking only at specific points, Quiet-STaR allows a model to think quietly at every token, with a distribution trained to be useful.
[GaLore] Memory-Efficient LLM Training by Gradient Low-Rank Projectionπ
Arxiv: https://arxiv.org/abs/2403.03507 6 Mar 2024
flowchart LR
subgraph LoRA["LoRA"]
W1[Frozen Weights] --> Plus1((+))
LR1[Low-Rank\nAdapters] --> Plus1
end
subgraph GaLore["GaLore"]
G[Gradient G] --> Proj[Project to\nLow-Rank]
Proj --> Opt[Optimizer\n(small core)]
Opt --> Update[Full Weight\nUpdate]
end
style GaLore fill:#e8f5e9,color:#000
Gradient Low-Rank Projection (GaLore) is a training strategy that allows full-parameter learning but is more memory-efficient than common low-rank adaptation methods like LoRA. GaLore is closely related to projected gradient descent (PGD), but with key differences:
- GaLore considers the specific gradient form that naturally appears in training multi-layer neural networks
- Traditional PGD mostly treats the objective as a general blackbox nonlinear function
- Since the gradient G may have a low-rank structure, GaLore keeps the gradient statistics of a small "core" of gradient G in optimizer states
For complex optimization problems like LLM pretraining, it may be difficult to capture the entire gradient trajectory with a single low-rank subspace. GaLore addresses this by allowing switching across low-rank subspaces: Wt = W0 + βWT1 + βWT2 + ... + βWTn, where the switching frequency T becomes a hyperparameter.
[Survey] Instruction Tuning for Large Language Modelsπ
Arxiv: https://arxiv.org/abs/2308.10792 21 Aug 2023
There are generally two methods for constructing instruction datasets:
β’ Data integration from annotated natural language datasets. In this approach,
(instruction, output) pairs are collected from existing annotated natural language datasets by using templates to transform text-label pairs to (instruction, output) pairs.
Datasets such as Flan (Longpre et al., 2023) and P3 (Sanh et al., 2021).
β’ Generating outputs using LLMs - (1) manually collected; or (2) expanded based on small handwritten seed instructions using LLMs. Next, the collected instructions are fed to LLMs to obtain outputs. Datasets such as InstructWild (Xue et al., 2023) and Self-Instruct (Wang et al., 2022c) are generated following this approach. For multi-turn conversational IT datasets, we can have large language models self-play different roles (user and AI assistant) to generate message

[Set-Fit] Sentence Transformer Fine-tuningπ
Arxiv: https://arxiv.org/abs/2209.11055 22 Sep 2022
flowchart LR
subgraph Stage1["Stage 1: Siamese Fine-tuning"]
Pairs["Text Pairs\n(+/-)"]
Pairs --> ST[Sentence\nTransformer]
ST --> Emb[Better\nEmbeddings]
end
subgraph Stage2["Stage 2: Classification"]
Emb --> LR[Logistic\nRegression]
LR --> Class[Classification]
end
style Stage1 fill:#e1f5fe,color:#000
style Stage2 fill:#fff3e0,color:#000
SetFit is a two-stage framework for few-shot learning:
-
Siamese Fine-tuning Stage:
- Takes pairs of text (positive/negative)
- Fine-tunes Sentence Transformer in contrastive manner
- Creates better text embeddings for target task
-
Classification Stage:
- Uses fine-tuned embeddings from Stage 1
- Trains simple classifier (logistic regression) on these embeddings
- Produces final classification output
Advantages:
- No prompts or verbalizers needed
- Much smaller parameter count than PEFT/PET
- Faster training time
- Works well in multilingual settings
- Comparable accuracy to larger models
Home