A straightforward method for training your LLM, from downloading data to generating text.
perf(rollout): PPO and GRPO rollouts use the modern model's KV cache
FareedKhan-dev9d2d50bbed2d
diff --git a/src/post_training/rollout.py b/src/post_training/rollout.pyindex 779a2c4..dc1984c 100644--- a/src/post_training/rollout.py+++ b/src/post_training/rollout.py@@ -26,7 +26,9 @@ from dataclasses import dataclassimport torchimport torch.nn.functional as F+from src.checkpoint import unwrap_modelfrom src.inference.sampling import filter_logits+from src.models.modern import ModernTransformerfrom src.post_training.chat_template import EOT_ID__all__ = [@@ -84,6 +86,7 @@ def generate_with_logprobs(stop_tokens: tuple[int, ...] = (EOT_ID,),pad_id: int = EOT_ID,context_length: int | None = None,+ use_cache: bool = True,) -> RolloutBatch:"""Autoregressively sample a completion for each prompt and record per-token log-probs.@@ -92,8 +95,9 @@ def generate_with_logprobs(Rows stop individually once they emit any ``stop_tokens``; subsequent positions arefilled with ``pad_id`` and excluded from ``response_mask``.- No KV cache (kept for clarity): each step re-runs the prefix, which is fine for the- short sequences here on an H100.+ The modern model decodes with its KV cache: the prompts are processed once and every+ later step feeds only the newest token. The classic model has no cache, so each step+ re-runs the prefix (``use_cache=False`` does the same for the modern model)."""model.eval()device = prompt_ids.device@@ -110,10 +114,19 @@ def generate_with_logprobs(gen_logprobs = torch.zeros(B, max_new_tokens, device=device)gen_mask = torch.zeros(B, max_new_tokens, dtype=torch.bool, device=device)finished = torch.zeros(B, dtype=torch.bool, device=device)+ # prompt + generation fits in the context (checked above), so the cache never overflows+ plain = unwrap_model(model)+ backbone = unwrap_model(getattr(plain, "transformer", plain)) # the policy behind a value head+ cache = backbone.new_cache(B) if use_cache and isinstance(backbone, ModernTransformer) else Nonefor t in range(max_new_tokens):- idx_cond = sequences[:, -cap:]- logits = _logits_from(model, idx_cond)[:, -1, :] # (B, vocab)+ if cache is None:+ idx_cond = sequences[:, -cap:]+ logits = _logits_from(model, idx_cond)[:, -1, :] # (B, vocab)+ else: # prefill the prompts once, then decode one token per step+ assert isinstance(backbone, ModernTransformer)+ new_tokens = sequences if t == 0 else sequences[:, -1:]+ logits = backbone.lm_head(backbone.forward_hidden(new_tokens, cache)[:, -1, :])# Full-distribution log-prob at the sampling temperature (matches recompute).full_logprobs = F.log_softmax(logits.float() / max(temperature, 1e-6), dim=-1)diff --git a/tests/test_modern_model.py b/tests/test_modern_model.pyindex f7fcda0..011a49b 100644--- a/tests/test_modern_model.py+++ b/tests/test_modern_model.py@@ -260,3 +260,22 @@ def test_post_training_wrappers_accept_the_modern_model() -> None:rb = generate_with_logprobs(model, idx[:, :4], max_new_tokens=6)lp, mask = compute_logprobs(model, rb.sequences, rb.response_mask, requires_grad=False)assert torch.allclose(rb.gen_logprobs[rb.response_mask[:, 4:]], lp[mask], atol=1e-4)+++def test_rl_rollouts_use_the_kv_cache_and_sample_the_same_tokens() -> None:+ from src.post_training.rollout import generate_with_logprobs+ from src.post_training.value_head import TransformerWithValueHead++ model = _model(VARIANTS["gqa"])+ prompts = torch.randint(0, BASE.vocab_size, (3, 5))+ runs = []+ for use_cache in (True, False):+ torch.manual_seed(0)+ runs.append(generate_with_logprobs(model, prompts, 12, temperature=0.9, use_cache=use_cache))+ cached, plain = runs+ assert torch.equal(cached.sequences, plain.sequences)+ assert torch.allclose(cached.gen_logprobs, plain.gen_logprobs, atol=1e-5)+ # the PPO actor wraps the policy in a value head; its rollouts take the cached path too+ actor = TransformerWithValueHead(model) # built before seeding: its init draws random numbers+ torch.manual_seed(0)+ assert torch.equal(generate_with_logprobs(actor, prompts, 12, temperature=0.9).sequences, cached.sequences)