<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Brayan Njoroge on Medium]]></title>
        <description><![CDATA[Stories by Brayan Njoroge on Medium]]></description>
        <link>https://medium.com/@brayannjoroge259?source=rss-12e238a35936------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*e5OMgi8C8VQwVMj8</url>
            <title>Stories by Brayan Njoroge on Medium</title>
            <link>https://medium.com/@brayannjoroge259?source=rss-12e238a35936------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:18:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brayannjoroge259/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a GPT from Scratch in JAX/Flax]]></title>
            <link>https://medium.com/@brayannjoroge259/building-a-gpt-from-scratch-in-jax-flax-ce7d442627ed?source=rss-12e238a35936------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce7d442627ed</guid>
            <dc:creator><![CDATA[Brayan Njoroge]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 09:52:05 GMT</pubDate>
            <atom:updated>2026-03-26T09:52:05.251Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a GPT from Scratch in JAX/Flax</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*Flvg0Wl6tTmN3L2GT6clvg.png" /></figure><p>An account of building a transformer language model using JAX, Flax NNX, and the TinyStories dataset — including every wall I hit along the way.</p><p>Why JAX?</p><p>Most transformer tutorials start with PyTorch. It’s intuitive, well-documented, and the ecosystem is enormous. So why would anyone choose JAX for a from-scratch GPT implementation?</p><p>Three reasons:</p><p>1. XLA compilation. JAX compiles your code down to XLA (Accelerated Linear Algebra), which means the same code runs on CPU, GPU, and TPU without modification. You decorate a function with <a href="http://twitter.com/jax">@jax</a>.jit and JAX handles the rest.</p><p>2. Functional purity. JAX forces you to write pure functions — no hidden state, no in-place mutations. This is uncomfortable at first, but it makes your model logic explicit and easier to reason about.</p><p>3. vmap. JAX’s vmap lets you write code for a single example and automatically vectorize it across a batch. This isn’t just a convenience — it changes how you think about batching entirely.</p><p>That said, JAX has a steeper learning curve than PyTorch. This post is an honest account of what that looks like in practice.</p><p>The Architecture</p><p>The model is a decoder-only transformer — the same family as GPT — trained to predict the next token in a sequence. Here’s the full picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*E1tGv5LnII0VHgJcLwSkGQ.png" /></figure><p>Hyperparameters:</p><p>Transformer blocks: 6<br>Embedding dimension: 192<br>Attention heads: 6<br>Feed-forward dimension: 512<br>Max sequence length: 128<br>Vocabulary: GPT-2 tokenizer (50,257 tokens)<br>The transformer architecture — our model uses the decoder side (right) only.</p><p>Small by modern standards, but trainable on a single GPU and expressive enough to learn story structure.</p><p>Part 1: Embeddings</p><p>The first layer combines token embeddings (what is this word?) with positional embeddings (where is it in the sequence?):</p><p>class TokenAndPositionEmbedding(nnx.Module):<br> def __init__(self, maxlen, vocab_size, embed_dim, *, rngs):<br> self.token_emb = nnx.Embed(vocab_size, embed_dim, rngs=rngs)<br> self.pos_emb = nnx.Embed(maxlen, embed_dim, rngs=rngs)</p><p>def __call__(self, x):<br> seq_len = x.shape[1]<br> positions = jnp.arange(seq_len)[None, :] # shape: (1, seq_len)<br> return self.token_emb(x) + self.pos_emb(positions)</p><p>The key line is jnp.arange(seq_len)[None, :] — the [None, :] adds a batch dimension so positions broadcast correctly across the batch. This is a pattern used constantly in JAX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ayeut2GAKwin_2FRh7_InA.jpeg" /></figure><p>Token embeddings encode meaning; positional embeddings encode order. Both are summed before entering the transformer.</p><p>Part 2: Causal Attention</p><p>The attention block uses Flax NNX’s built-in MultiHeadAttention, but the critical piece is the causal mask — without it, the model can look into the future when predicting the next token, which is cheating.</p><p>class MiniGPT(nnx.Module):</p><p>def causal_attention_mask(self, seq_len):<br> # Lower triangular matrix — token i can only attend to tokens 0..i<br> return jnp.tril(jnp.ones((seq_len, seq_len)))</p><p>def __call__(self, token_ids):<br> seq_len = token_ids.shape[1]<br> mask = self.causal_attention_mask(seq_len)</p><p>x = self.embedding(token_ids)</p><p>for block in self.transformer_blocks:<br> x = block(x, mask=mask)</p><p>return self.output_layer(x)</p><p>jnp.tril produces a lower-triangular matrix of ones. Position (i, j) is 1 if j ≤ i, meaning token i is allowed to attend to token j. This single matrix enforces the autoregressive property of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*WNz_svgPcPGpjBoljaE9wQ.png" /></figure><p>The causal mask — each token (row) can only attend to itself and previous tokens (columns). Future positions are masked out.</p><p>Part 3: The Flax NNX Learning Curve</p><p>Flax has two APIs: the older linen API and the newer nnx API. This project uses NNX, which is more Pythonic — modules hold their own state rather than requiring external parameter trees.</p><p>The gotcha that cost me real time:</p><p>Flax 0.11.0 changed the Optimizer and update signatures without much fanfare:</p><p># Flax &lt; 0.11.0<br>optimizer = nnx.Optimizer(model, optax.adamw(…))<br>optimizer.update(grads)</p><p># Flax &gt;= 0.11.0 — both arguments now required<br>optimizer = nnx.Optimizer(model, optax.adamw(…), wrt=nnx.Param)<br>optimizer.update(model, grads)</p><p>The error message (Missing required argument ‘wrt’) points you in the right direction, but if you’re following a tutorial written before 0.11.0 you’ll hit this immediately. Always check your Flax version against the tutorial’s requirements.</p><p>Part 4: Data Loading with Grain</p><p>Rather than writing a custom DataLoader, this project uses Google’s grain library — a JAX-native data loading library built for performance.</p><p>dataset = StoryDataset(stories, maxlen, tokenizer)</p><p>sampler = pygrain.IndexSampler(<br> num_records=len(dataset),<br> shuffle=True,<br> seed=42,<br> shard_options=pygrain.NoSharding(),<br> num_epochs=num_epochs,<br>)</p><p>dataloader = pygrain.DataLoader(<br> data_source=dataset,<br> sampler=sampler,<br> operations=[pygrain.Batch(batch_size=batch_size, drop_remainder=True)]<br>)</p><p>Each story is tokenized and right-padded to maxlen=128 with zeros. The target sequence is simply the input shifted one position to the right:</p><p># Input: [Once, upon, a, time, …]<br># Target: [upon, a, time, …, &lt;pad&gt;]</p><p>prep_target_batch = jax.vmap(<br> lambda tokens: jnp.concatenate((tokens[1:], jnp.array([0])))<br>)</p><p>This is where vmap shines — write the transformation for a single sequence, apply it across the entire batch automatically.</p><p>Part 5: Training Loop</p><p>The training loop uses nnx.value_and_grad to compute loss and gradients in a single pass:</p><p><a href="http://twitter.com/nnx">@nnx</a>.jit<br>def train_step(model, optimizer, metrics, batch):<br> input_ids, target_ids = batch</p><p>def loss_fn(model):<br> logits = model(input_ids)<br> loss = optax.softmax_cross_entropy_with_integer_labels(<br> logits.reshape(-1, vocab_size),<br> target_ids.reshape(-1)<br> ).mean()<br> return loss, logits</p><p>(loss, logits), grads = nnx.value_and_grad(loss_fn, has_aux=True)(model)<br> optimizer.update(model, grads)<br> metrics.update(loss=loss, logits=logits, labels=target_ids)</p><p>The <a href="http://twitter.com/nnx">@nnx</a>.jit decorator compiles the entire train step — forward pass, loss computation, gradient calculation, and weight update — into a single XLA kernel. The first call is slow (compilation), every subsequent call is fast.</p><p>How <a href="http://twitter.com/jax">@jax</a>.jit works — Python traces your function once, XLA compiles it, then every subsequent call skips Python entirely.</p><p>A subtle bug to watch for in the training loop:</p><p># WRONG — step only increments once per epoch<br>for batch in dataloader:<br> train_step(…)<br>step += 1 # ← outside the for loop</p><p># CORRECT — step increments every batch<br>for batch in dataloader:<br> train_step(…)<br> step += 1 # ← inside the for loop</p><p>Python indentation bugs are silent in training loops.</p><p>Part 6: Checkpointing with Orbax</p><p>Orbax is JAX’s native checkpointing library. Saving and restoring model state:</p><p># Save<br>checkpointer = orbax.checkpoint.PyTreeCheckpointer()<br>checkpointer.save(checkpoint_path, nnx.state(model))</p><p># Restore<br>restored_state = checkpointer.restore(<br> checkpoint_path,<br> item=nnx.state(model),<br> restore_args=restore_args<br>)<br>nnx.update(model, restored_state)</p><p>nnx.state(model) extracts the parameter pytree from the model. nnx.update(model, restored_state) writes it back in. The model architecture must match exactly — if you change embed_dim from 192 to 256, the checkpoint will fail to load because the weight shapes no longer match.</p><p>This also means you can load someone else’s checkpoint on your machine, instantly inheriting their training without running a single training step. This is how the 20M-token checkpoint used in this project was loaded and run on a fresh Colab session.</p><p>Part 7: Text Generation</p><p>Generation uses greedy decoding (argmax) with temperature scaling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gHzzN5c2lpauKM0_ePUsw.png" /></figure><p>Autoregressive generation — the model predicts one token at a time, appending each prediction back to the input for the next step.</p><p>def generate_text(model, start_tokens, max_new_tokens=50, temperature=1.0):<br> tokens = list(start_tokens)</p><p>for _ in range(max_new_tokens):<br> context = tokens[-model.maxlen:]<br> actual_len = len(context)</p><p># Right-pad to maxlen to match training<br> if actual_len &lt; model.maxlen:<br> context = context + [0] * (model.maxlen — actual_len)</p><p>context_array = jnp.array(context)[None, :]<br> logits = model(context_array)</p><p># Sample from the position of the LAST real token, not position 0<br> next_token_logits = logits[0, actual_len — 1, :] / temperature<br> next_token = int(jnp.argmax(next_token_logits))</p><p>if next_token == END_TOKEN_ID:<br> break</p><p>tokens.append(next_token)</p><p>return tokenizer.decode(tokens)</p><p>The line logits[0, actual_len — 1, :] is easy to get wrong. You want the logits at the position of the last real token — not position 0, and not the last padded position. Getting this wrong results in the model repeating the prompt with no new tokens generated.</p><p>Temperature controls how peaked the probability distribution is:<br>- temperature=0.2 → conservative, repetitive output<br>- temperature=1.0 → balanced<br>- temperature=1.5 → creative, sometimes incoherent</p><p>Results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IrUxBDkmzMjwbtnnE_K8gQ.png" /></figure><p>Trained on the TinyStories dataset with a 20M-token checkpoint, the model generates coherent short stories:</p><p>Prompt: “Once upon a time a big bear”<br>Output: “Once upon a time a big bear lived in the forest.<br> He liked to walk and find berries. One day he<br> met a little rabbit who was lost…”</p><p>The model learned basic story structure, character introduction, and simple cause-and-effect narrative — all from a 6-layer, 192-dimensional transformer.</p><p>What’s Next</p><p>- Add layer normalisation to the transformer blocks (currently missing)<br>- Replace greedy decoding with top-k or nucleus sampling for more varied output<br>- Scale up: larger embed_dim, more blocks, more training data<br>- Experiment with RoPE positional embeddings instead of learned positions</p><p>Try It Yourself</p><p>The full code is on GitHub: MinGPT-Implementation-with-Jax<br><a href="https://github.com/Brayanbrayan/MinGPT-Implementation-with-Jax">https://github.com/Brayanbrayan/MinGPT-Implementation-with-Jax</a></p><p>A Colab notebook is included — mount your Drive, run the cells, and you can load the pretrained checkpoint and start generating stories in under a minute.</p><p>Built with JAX, Flax NNX, Optax, Orbax, Grain, and tiktoken.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce7d442627ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Direct Preference Optimization (DPO)]]></title>
            <link>https://medium.com/@brayannjoroge259/implementing-direct-preference-optimization-dpo-149360bd2e9b?source=rss-12e238a35936------2</link>
            <guid isPermaLink="false">https://medium.com/p/149360bd2e9b</guid>
            <dc:creator><![CDATA[Brayan Njoroge]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 09:13:57 GMT</pubDate>
            <atom:updated>2026-03-26T09:17:16.574Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementing Direct Preference Optimization (DPO)</p><p>A ground-up implementation of DPO from the Rafailov et al. 2023 paper, trained on tatsu-lab/alpaca as part of a multi-stage RLHF project</p><p>Series: Multi-Stage RLHF from Scratch · Part 10 of 10 · Algorithm: DPO</p><p>1. Context and motivation</p><p>This write-up documents Part 10 of a multi-stage project implementing reinforcement learning from human feedback (RLHF) from scratch. The full project covers: Supervised Fine-Tuning (SFT), a Reward Model, Proximal Policy Optimisation (PPO), Group Relative Policy Optimisation (GRPO), and finally Direct Preference Optimisation (DPO). Each algorithm is implemented from first principles against the same model architecture, tokenizer, and evaluation suite, enabling a direct side-by-side comparison of approaches.</p><p>DPO is chosen as the final stage because it represents the most elegant solution to the preference alignment problem. Where PPO requires a live reward model, a value function, rollout collection, and a clipped policy gradient update, DPO collapses the entire pipeline into a single classification loss. The goal of implementing it in this project is not just to obtain good scores, but to understand precisely what it does differently, where it succeeds, and where it falls short at small model scale.</p><p>2. What the DPO paper says</p><p>2.1 The core problem</p><p>Standard RLHF (as used in PPO and InstructGPT) has two stages after SFT: first train a reward model on human preference data, then use reinforcement learning to maximise the learned reward subject to a KL constraint from the reference policy. The optimisation objective is:</p><p>max 𝔼[r_φ(x,y)] − β · KL[ π_θ(y|x) ‖ π_ref(y|x) ]<br> π_θ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dN00uMUDaVueFUTKu9U7QA.png" /></figure><p>[TIP FOR MEDIUM: paste the chart image “chart_training.png” here or use an equation image]</p><p>This is expensive: it requires sampling from the LM during training, maintaining a separate reward model and critic, and careful hyperparameter tuning of the KL coefficient. The paper’s central insight is that this objective has a closed-form optimal solution:</p><p>π*(y|x) = (1 / Z(x)) · π_ref(y|x) · exp( r(x,y) / β )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9AQ8jC0ZiCcinI0x0pI4A.png" /></figure><p>Rearranging this to express the reward in terms of the policy gives:</p><p>r(x,y) = β · log[ π_θ(y|x) / π_ref(y|x) ] + β · log Z(x)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJvlJjaaxsBZAu9nWeAHZQ.png" /></figure><p>The key observation is that when this reparameterisation is substituted into the Bradley-Terry preference model, the intractable partition function Z(x) cancels out entirely. This allows the preference probability to be expressed purely in terms of the policy and the reference — no reward model required.</p><p>2.2 The DPO loss</p><p>Substituting the reparameterised reward into the Bradley-Terry preference model and framing it as a maximum likelihood objective over preference pairs (x, y_w, y_l) yields the DPO loss:</p><p>L_DPO = −𝔼[ log σ( β · log(π_θ(y_w|x) / π_ref(y_w|x))<br> − β · log(π_θ(y_l|x) / π_ref(y_l|x)) ) ]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGPwWJWbna6inZ2Z9n21UQ.png" /></figure><p>Where y_w is the chosen (preferred) response, y_l is the rejected (dispreferred) response, and β controls how tightly the policy stays near the reference. This is a binary cross-entropy loss — the model learns to assign higher implicit reward to chosen over rejected, with the gradient automatically weighting harder examples more heavily.</p><p>2.3 What the gradient does</p><p>The paper provides an explicit gradient analysis. Increasing the DPO loss parameters θ increases the log-probability of y_w and decreases the log-probability of y_l. Crucially, the weight applied to each example is σ(r̂_θ(x, y_l) − r̂_θ(x, y_w)) — proportional to how much the current model incorrectly ranks the rejected response over the chosen one. This dynamic weighting prevents trivial updates on already-solved pairs and concentrates learning on the hardest examples.</p><p>2.4 Experimental setup in the paper</p><p>The paper evaluates DPO on three tasks. In controlled sentiment generation on IMDb, it uses GPT-2-large SFT’d on movie reviews, with preference pairs generated synthetically using a pre-trained sentiment classifier. In TL;DR summarisation, it uses a GPT-J SFT model with human preference labels from Stiennon et al. In single-turn dialogue on the Anthropic HH dataset, it uses Pythia-2.8B fine-tuned on preferred completions. Evaluation uses the frontier of reward vs KL divergence (sentiment task, where the ground-truth reward function is known) and GPT-4 win rates against reference completions (summarisation and dialogue).</p><p>Crucially, all three experiments use pre-collected preference datasets. The paper never generates rejected responses on-the-fly during training — it works from a static offline dataset of (x, y_w, y_l) triplets. This distinction is central to understanding how this implementation differs.</p><p>3. This implementation</p><p>3.1 Architecture</p><p>The policy uses the PolicyWithValue class introduced in Part 8 (PPO). It wraps a GPTModern language model (a small transformer with RMSNorm, SwiGLU activations, and RoPE positional embeddings) and adds a linear value head over the logit space. In DPO, the value head is not trained — it is frozen and retained only for checkpoint compatibility with the earlier PPO and GRPO phases. Only the LM parameters receive gradient updates.</p><p>The reference model is an identical frozen copy of the SFT checkpoint. Its weights are fixed throughout training. All reference log-probabilities are computed inside torch.no_grad() blocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5V25okmqRgn18ba6PGnGA.png" /></figure><p>Figure 3 — DPO pipeline: the frozen reference model and the trainable policy both receive the preference pair and output log-probabilities that feed the DPO loss. Gradients flow only to the trainable policy.</p><p>3.2 The dataset challenge</p><p>KEY DEPARTURE FROM THE PAPER</p><p>The original DPO paper uses datasets that already contain (prompt,<br> chosen, rejected) triplets — the Anthropic HH dataset, TL;DR with<br> Stiennon et al. preferences, or synthetically generated pairs.<br> tatsu-lab/alpaca only provides (instruction, output) pairs with no<br> rejected response. This requires constructing rejected responses<br> on-the-fly during training, which is a meaningful departure from<br> the pure offline DPO setup.</p><p>After filtering rows with empty outputs, the Alpaca dataset provides 51,974 instruction-response pairs. For each training step:</p><p>• The dataset’s human-written output becomes the chosen response y_w.<br> • A rejected response y_l is generated on-the-fly from the frozen reference model using temperature=0.9 and top_k=50.<br> • The assumption ‘human output is always better than a high-temperature model generation’ is treated as valid without reward model verification.</p><p>This assumption is defensible and is consistent with the spirit of the paper’s approach, but it introduces noise: there will be cases where the generated response is actually acceptable, making the preference signal weak. The high temperature and diverse sampling are intended to maximise the probability that the rejected response is genuinely inferior.</p><p>The closest analogue in the paper is the IMDb sentiment task, where preference pairs are also constructed automatically rather than from human annotation — though there the classification is done with a ground-truth reward function, whereas here we rely on the quality gap between human text and a random generation.</p><p>3.3 The get_logps function</p><p>A central implementation detail is the correct computation of per-sequence log-probabilities over the response tokens only. The function must respect the same token-shift logic used throughout the codebase:</p><p>[Paste as a code block in Medium using the “&lt;/&gt;” button]</p><p>def get_logps(model, input_ids, response_mask):<br> # Forward pass<br> logits, _, _ = model.lm(input_ids, None) # (B, T, V)</p><p># Shift: logits[:-1] predict tokens[1:]<br> shift_logits = logits[:, :-1, :] # (B, T-1, V)<br> shift_labels = input_ids[:, 1:] # (B, T-1)</p><p># Shift mask by 1 to align with shifted labels<br> shift_mask = response_mask[:, 1:] # (B, T-1)</p><p># Per-token log-probs, zeroed on prompt tokens<br> log_probs = torch.log_softmax(shift_logits, dim=-1)<br> token_logps = log_probs.gather(-1, shift_labels.unsqueeze(-1)).squeeze(-1)<br> token_logps = token_logps * shift_mask.float()</p><p>return token_logps.sum(dim=-1) # (B,) — one value per sequence</p><p>The mask is shifted by one position to match the shifted labels. This ensures that only response tokens contribute to the log-probability sum, leaving prompt tokens at zero weight — which is the correct behaviour since we want to measure how well the model assigns probability to the response, not the prompt.</p><p>3.4 The DPO loss</p><p>[Paste as a code block in Medium using the “&lt;/&gt;” button]</p><p>def dpo_loss(policy_chosen_logps, policy_rejected_logps,<br> ref_chosen_logps, ref_rejected_logps, beta=0.1):</p><p>chosen_log_ratios = policy_chosen_logps — ref_chosen_logps<br> rejected_log_ratios = policy_rejected_logps — ref_rejected_logps</p><p># DPO margin: β * (log-ratio_chosen — log-ratio_rejected)<br> logits = beta * (chosen_log_ratios — rejected_log_ratios)</p><p>loss = -F.logsigmoid(logits).mean()<br> reward_margin = (chosen_log_ratios — rejected_log_ratios).detach().mean()<br> accuracy = (logits.detach() &gt; 0).float().mean()</p><p>return DPOLossOutput(loss=loss,<br> reward_margin=reward_margin,<br> accuracy=accuracy)</p><p>3.5 Training configuration</p><p>Training ran for 200 steps on CPU using a single example per step (batch size 1). The key hyperparameters:</p><p>• β = 0.1 (DPO temperature, same as paper default)<br> • Learning rate = 1e-5 with AdamW, betas (0.9, 0.999)<br> • Gradient clipping at 1.0<br> • Response generation: temperature 0.9, top_k 50, max 64 new tokens<br> • Block size: 256 tokens<br> • Model: 2-layer, 2-head, 128-dim transformer (same as PPO phase)</p><p>The small model size (2 layers, 128-dim) is consistent across all phases of the project. This is intentional — the project is about algorithm implementation and comparison, not about maximising absolute scores.</p><p>4. Training dynamics</p><p>4.1 Loss behaviour</p><p>The loss curve tells a clear story. At step 10, loss = 0.641 and accuracy = 1.0 — the model is already preferring chosen over rejected, but with moderate confidence. At step 20, loss = 0.693 (exactly log(2)), accuracy = 0.0, margin = 0.0. This is the degenerate case predicted by theory: when the policy exactly mirrors the reference, all log-ratios are zero, the DPO margin is zero, and the loss equals −log(σ(0)) = log(2) ≈ 0.693. The model assigns equal probability to chosen and rejected.</p><p>From step 30 onward, loss collapses toward zero and stays there for the remainder of training, reaching exactly 0.0 at steps 70, 80, 110, 130, 150, 160, 170, 190, and 200. Accuracy locks at 1.0. This rapid convergence is consistent with what the paper describes as the efficiency of DPO — but the speed here is a warning sign, not a success signal.</p><p>4.2 Reward margin explosion</p><p>The most important metric to examine is the reward margin — the mean gap between chosen and rejected log-ratios. A margin of 1–10 is healthy and indicates the model has learned a meaningful preference signal while staying close to the reference. The values observed here are qualitatively different:</p><p>• Step 30: 56.9<br> • Step 70: 240.7<br> • Step 80: 295.8<br> • Step 150: 599.2<br> • Step 200: 329.7</p><p>Margins of this magnitude indicate that the policy has drifted very far from the reference distribution. The loss reaching zero and staying there is not evidence of good generalisation — it is evidence that the model has memorised the preference signal on each individual pair to the point where it assigns near-zero probability mass to the rejected response. This is reward hacking in the DPO sense: the policy has exploited the training signal rather than learning a generalisable preference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klzWCA3dtisjrPIaEYmbZg.png" /></figure><p>Figure 1 — DPO training dynamics over 200 steps. Blue: loss (left axis). Red dashed: reward margin (right axis). Note the margin explosion after step 30, reaching 599 at step 150.</p><p>ROOT CAUSE</p><p>The primary driver is the batch size of 1 combined with a small<br> model and a strong quality gap between human text and<br> high-temperature generations. With a single example per step,<br> there is no averaging across a batch to stabilise gradients. Each<br> update can overfit completely to one (chosen, rejected) pair before<br> moving to the next. A batch size of 16–64 with gradient<br> accumulation would stabilise this significantly.</p><p>5. Evaluation results</p><p>5.1 Summary</p><p>Post-training evaluation was run on 16 standard prompts using the Part 7 reward model. Average reward: 2.40. Average KL divergence from the SFT base: 3.31.</p><p>Prompt | Reward | Avg KL<br> — — — — — — — — — — — — — — — — — — — — — — — — — — | — — — — -| — — — -<br>Give three tips for staying healthy. | 5.44 | 3.45<br>What are the three primary colors? | 6.93 | 2.54<br>Describe the structure of an atom. | -6.63 | 1.21<br>How can we reduce air pollution? | -7.75 | 4.45<br>Describe a time when you had to make a difficult | 0.25 | 2.06<br> decision. | |<br>Identify the odd one out. Twitter, Instagram, | 3.94 | 2.87<br> Telegram | |<br>Explain why 4/16 is equivalent to 1/4 | 6.14 | 3.02<br>Write a short story about a career decision. | 1.67 | 8.70<br>Render a 3D model of a house | 2.97 | 2.35<br>Evaluate this sentence for spelling/grammar | 6.99 | 5.91<br> mistakes | |<br>How did Julius Caesar die? | 7.13 | 2.88<br>What is the capital of France? | 4.91 | 3.51<br>Generate a list of ten items for a camping trip | -4.28 | 1.65<br>Discuss the causes of the Great Depression | -4.91 | 1.41<br>Classify: Oak tree, copper ore, elephant | 7.84 | 2.59<br>Explain the use of word embeddings in NLP | 7.82 | 4.27</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Xv_m4zmFhLWsJjwt96Yjg.png" /></figure><p>Figure 2 — Per-prompt reward scores for 16 evaluation prompts. Blue bars = positive reward; red bars = negative reward. Average: 2.40.</p><p>5.2 Response quality</p><p>The responses are incoherent. Representative examples:</p><p>• Prompt: ‘Describe the structure of an atom.’<br> Response: ‘An atom is ways make inform of a severe glic acid.’</p><p>• Prompt: ‘How can we reduce air pollution?’<br> Response: ‘There are reducing made up16 is made up of a risular of 13’</p><p>• Prompt: ‘What is the capital of France?’<br> Response: ‘The capital of France is made up of Water Exercise ore of<br> comm of at 1973on Bret, make amends.’</p><p>These outputs are syntactically broken and semantically meaningless. The model has learned to shift its distribution away from the reference but has not learned coherent language — it has simply collapsed into a different incoherent distribution that happens to score positively under the reward model.</p><p>5.3 Reward model limitations</p><p>The high variance in reward scores (range: −7.75 to +7.84) and the presence of very high rewards on clearly nonsensical responses points to a known limitation: the reward model was trained at this same small scale (2-layer, 256-dim) and has limited ability to discriminate response quality on prompts far outside its training distribution. A response like ‘Julius Caur G conflict, forces, had just graphelling’ receives a reward of 7.13. This is reward model overfitting — the RM has learned surface patterns that map to high scores without capturing semantic quality.</p><p>This is not a failure unique to DPO. It is a general property of small-scale RLHF: the reward model and the policy are jointly limited by model capacity, and the policy can find reward-maximising outputs that fool the RM without producing genuinely good text.</p><p>6. How this compares to the paper</p><p>6.1 What was faithfully implemented</p><p>• The DPO loss equation from the paper (Equation 7) is implemented exactly, including the beta temperature and the log-sigmoid objective.<br> • The frozen reference model pattern is correct: π_ref is initialised from the SFT checkpoint and receives no gradient updates throughout training.<br> • The val_head is preserved in the architecture for checkpoint compatibility, as required by the multi-stage project structure.<br> • The get_logps masking correctly supervises only response tokens, consistent with the paper’s per-sequence log-probability formulation.<br> • The reward model is absent from the training loop entirely, consistent with DPO’s RL-free design.<br> • β = 0.1 matches the paper’s default hyperparameter.</p><p>6.2 Where this differs from the paper</p><p>• Dataset: The paper uses pre-collected (x, y_w, y_l) triplets. This implementation constructs rejected responses on-the-fly from the reference model because tatsu-lab/alpaca contains no rejected responses.<br> • Batch size: The paper uses batch size 64 with RMSprop. This implementation uses batch size 1 with AdamW, which destabilises training and contributes to margin explosion.<br> • Model scale: The paper evaluates models up to 6B parameters. This implementation uses a ~1M parameter model. At this scale, the learned representations are too weak to produce coherent responses even after successful preference alignment.<br> • Evaluation: The paper uses GPT-4 win rates for realistic tasks and a ground-truth sentiment classifier for the controlled task. This implementation uses a small trained reward model, which has its own limitations at small scale.<br> • Training steps: The paper trains to convergence (thousands of steps). This run trained for 200 steps, which is sufficient to observe the training dynamics but not to assess long-run behaviour.</p><p>6.3 On the RM-free design</p><p>The absence of the reward model from the DPO training loop is architecturally correct and theoretically motivated. In standard RLHF, the RM appears twice: once during reward model training (Part 7), and again inside the PPO training loop as the reward signal for each rollout. DPO eliminates the second appearance entirely. The implicit reward is instead encoded in the preference pairs themselves — the policy learns to assign higher implicit reward to chosen responses purely by shifting log-ratios, with no RM forward pass at training time.</p><p>In this project, the RM reappears only at evaluation time (dpo_logger.py and eval_dpo.py), where it serves as a consistent scoring function to allow comparison with PPO results. This is the correct separation: RM as evaluator, not as training signal.</p><p>7. What the results tell us and what to try next</p><p>The training dynamics are informative even though the final outputs are incoherent. The loss and accuracy curves are behaving as expected theoretically — rapid convergence is a known property of DPO on easy preference pairs. The reward margin explosion is the clear pathology, and its cause is well-understood: a batch size of 1 gives the optimiser no averaging, each step overfits the current pair, and the margin grows without bound.</p><p>To obtain coherent outputs at this model scale, the most impactful changes in order of priority would be:</p><p>1. Increase batch size to 16–64 using gradient accumulation. This is the single most important change.<br> 2. Add a margin cap: clip the reward margin at a threshold (e.g., 10.0) to prevent saturation, or use a length-normalised version of the log-probability sum instead of the raw sum.<br> 3. Reduce β to 0.05. A smaller beta tightens the KL constraint and keeps the policy closer to the reference, reducing the risk of degenerate drift.<br> 4. Train for more steps with early stopping on a held-out reward score. 200 steps on a 51k dataset barely scratches the surface.<br> 5. Upgrade the model. The 2-layer 128-dim architecture is the binding constraint on response quality. Even moving to 4 layers and 256-dim would substantially improve coherence.</p><p>Despite the output quality, the implementation is architecturally sound. The DPO loss, the reference model pattern, the get_logps masking, and the RM-free training loop are all correct. What is broken is the training regime, not the algorithm. This is a meaningful distinction — it means the codebase is a valid starting point for a proper run with better hyperparameters and a larger model.</p><p>8. Conclusion</p><p>DPO is a genuinely elegant algorithm. The theoretical insight — that the RLHF objective has a closed-form optimal policy, and that substituting a log-ratio reparameterisation into the Bradley-Terry model eliminates both the reward model and the RL loop — is one of the cleaner results in the alignment literature. The implementation is simpler than PPO by a significant margin: no value function, no rollout collection, no advantage estimation, no clipped ratio objective.</p><p>At small scale with a batch size of 1, the reward margin explodes and output quality degrades. This is not a failure of DPO as an algorithm — it is a failure of the training configuration relative to model capacity. The paper’s results at 6B parameters with batch size 64 are not directly comparable to a 1M parameter model trained one example at a time. What this run does confirm is the theoretical behaviour: rapid loss convergence, accuracy saturating at 1.0, and the preference signal being successfully encoded (even if over-encoded) in the policy weights.</p><p>The next step is the cross-algorithm comparison across PPO, GRPO, and DPO using the same 16 evaluation prompts and the same reward model — the comparison this entire project has been building toward.</p><p>References</p><p>Rafailov, R., Sharma, A., Mitchell, E., Ermon, S., Manning, C. D., &amp; Finn, C. (2023). Direct Preference Optimization: Your Language Model is Secretly a Reward Model. NeurIPS 2023. arXiv:2305.18290.</p><p>Schulman, J., Wolski, F., Dhariwal, P., Radford, A., &amp; Klimov, O. (2017). Proximal Policy Optimization Algorithms. arXiv:1707.06347.</p><p>Taori, R. et al. (2023). Stanford Alpaca: An Instruction-following LLaMA model. tatsu-lab/alpaca dataset.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=149360bd2e9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>