Reasoning Models, Contextual Retrieval, and Continual Learning: Building LLMs That Improve Over Time
Primary references:
- Build Your Own Reasoning Model: A Full Video Course
- Introducing Contextual Retrieval
- The sleep framework: A new way for LLMs to retain knowledge in continual learning
Modern LLM systems need three related capabilities:
- Reasoning: solve difficult problems through better inference and post-training.
- Retrieval: ground responses in external, current, and domain-specific knowledge.
- Continual learning: retain new knowledge without forgetting old capabilities.
These capabilities address different failure modes. A reasoning model improves problem-solving; contextual retrieval improves factual grounding; continual learning reduces the gap between a model’s training cutoff and the present.
This document covers the mechanisms behind each capability, their trade-offs, and how they fit into a production AI system.
A source-coverage note: the LinkedIn post, Headroom repository, arXiv papers, Spotify A/B-testing post, KronLSTM repository, and Kaggle competition links could not be fully verified from their primary pages in this pass. They are listed as further reading rather than treated as verified technical claims.
Part 1: Foundations
Conventional LLMs, reasoning models, and agents
A conventional large language model (LLM) is trained to predict the next token given preceding tokens. A reasoning model is an LLM additionally improved through post-training—often reinforcement learning with verifiable rewards—and optionally inference-time scaling techniques, so it can solve more challenging problems. magazine.sebastianraschka
An agent is a system that uses an LLM or reasoning model as its core engine, surrounded by an agent harness: the software framework that provides context management, tools, memory, control flow, and task-specific logic. magazine.sebastianraschka
+--------------------------------------------+
| Agent harness |
| |
| Context management + tools + memory |
| Control flow + skills + evaluation |
+---------------------+----------------------+
|
v
+------------------+
| Reasoning model |
| or LLM engine |
+------------------+
Raschka uses an engine analogy: the model is the engine, while the agent harness adds the machinery that lets it perform useful work beyond a simple chat interface. An agent can use either a conventional LLM or a reasoning model, though reasoning models are typically more capable. magazine.sebastianraschka
Key terminology
| Term | Meaning |
|---|---|
| Token | A unit of text used by a model, often a word piece or subword |
| Logits | Raw, unnormalized model scores for each possible next token |
| Probability | A normalized score obtained from logits, usually through softmax |
| KV cache | Stored attention keys and values that allow efficient autoregressive generation |
| Inference-time scaling | Improving answers by using more compute at inference, such as sampling multiple responses |
| RLVR | Reinforcement Learning with Verifiable Rewards |
| GRPO | Group Relative Policy Optimization |
| Distillation | Training a smaller student model to imitate a stronger teacher model |
| RAG | Retrieval-Augmented Generation |
| Catastrophic forgetting | Loss of previously learned capability after learning new tasks |
Part 2: Building Reasoning Models
The reasoning-model recipe
Raschka’s course starts with a pretrained Qwen3 0.6B model and implements reasoning methods in Python and PyTorch. The focus is not pretraining from scratch; it is evaluation, inference-time scaling, reinforcement learning, and distillation. magazine.sebastianraschka
Pretrained base model
|
v
+---------------------+
| Evaluation |
| Verifier on MATH-500|
+----------+----------+
|
+--> Inference-time scaling
|
+--> Reinforcement learning
|
+--> Distillation
|
v
Improved reasoning model
The course uses MATH-500 as its main evaluation benchmark and builds a verifier that extracts final answers, normalizes them, and checks mathematical equivalence. The same verifier later supplies the reward signal for reinforcement learning with verifiable rewards. magazine.sebastianraschka
Base-model inference
Before adding reasoning methods, the course implements a baseline generation pipeline:
- Encode text into tokens.
- Load pretrained Qwen3 weights.
- Compute logits for the next token.
- Generate text using greedy decoding or sampling.
- Handle end-of-sequence tokens.
- Add a KV cache.
- Combine KV caching with
torch.compile. magazine.sebastianraschka
KV caching stores previously computed attention keys and values so that each newly generated token does not require recomputation over the entire prior context.
Prompt: [t1 t2 t3 t4]
Prefill:
Compute K/V for t1..t4 and store in cache.
Generate t5:
Use cached K/V for t1..t4.
Compute K/V for t5 and append to cache.
This is the baseline efficiency mechanism on which later reasoning and inference-scaling methods build. magazine.sebastianraschka
Verifiers and RLVR
A verifier determines whether a model’s answer is correct. For math, it typically:
- Extracts the final answer from the generated response.
- Normalizes formatting.
- Checks mathematical equivalence.
- Returns a binary or graded reward. magazine.sebastianraschka
Reinforcement Learning with Verifiable Rewards, or RLVR, uses this verifier signal to improve the model. Unlike Reinforcement Learning with Human Feedback (RLHF), which relies on human preference labels, RLVR uses programmatically checkable correctness. magazine.sebastianraschka
Prompt
|
v
Generate group of responses
|
v
Verifier scores each response
|
v
Compute relative advantages
|
v
Update policy with GRPO
GRPO
Group Relative Policy Optimization, or GRPO, generates a group of responses for each prompt, scores them with a verifier, and uses relative rewards within the group to update the policy. magazine.sebastianraschka
For a group of $G$ responses to one prompt, let $r_i$ be the verifier reward for response $i$. A simplified relative advantage is:
\[A_i = r_i - \frac{1}{G}\sum_{j=1}^{G} r_j\]where:
- $A_i$ is the advantage for response $i$.
- $r_i$ is the reward for response $i$.
- $G$ is the group size.
Responses better than the group average receive positive advantage; worse-than-average responses receive negative advantage.
The course implements a simplified GRPO loss, then adds training diagnostics including entropy, advantage statistics, clipped policy ratios, KL loss terms, and formatted rewards. magazine.sebastianraschka
Inference-time scaling
Inference-time scaling improves answers without changing model weights. The course covers three main techniques:
| Technique | Mechanism | Trade-off |
|---|---|---|
| Chain-of-thought prompting | Encourage intermediate reasoning before the final answer | More output tokens and latency |
| Self-consistency | Sample multiple answers and vote on the final answer | Higher compute cost |
| Self-refinement | Critique an answer and revise it | Additional generation passes |
The course implements temperature scaling, multinomial sampling, top-$p$ filtering, self-consistency, scoring functions, and self-refinement loops. It also evaluates the trade-off between MATH-500 accuracy and additional inference compute. magazine.sebastianraschka
A simple self-consistency procedure is:
For k samples:
Generate answer with temperature > 0
Extract final answer
Return majority-voted answer
More samples can improve accuracy, but they increase latency, token cost, and infrastructure load.
Distillation
Distillation trains a smaller student model to learn from a stronger teacher. Raschka’s course distinguishes soft and hard distillation, as well as on-policy and off-policy distillation. magazine.sebastianraschka
Strong teacher model
|
v
Teacher-generated reasoning traces
|
v
Filtered and formatted dataset
|
v
Student model supervised training
|
v
Smaller reasoning model
The course creates teacher-generated answers for the MATH dataset using DeepSeek R1, prepares tokenized training, validation, and test splits, computes answer-token log probabilities, and trains the student with cross-entropy loss. magazine.sebastianraschka
For a teacher-generated target token sequence $y_1, \ldots, y_T$, the student’s supervised loss is:
\[\mathcal{L} = -\sum_{t=1}^{T} \log p_{\theta}(y_t \mid y_{<t}, x)\]where:
- $x$ is the prompt.
- $y_t$ is the teacher-generated token at position $t$.
- $p_{\theta}$ is the student model’s probability distribution.
Distillation is often cheaper and more stable than reinforcement learning, but its ceiling is limited by the quality and diversity of the teacher-generated data. magazine.sebastianraschka
Part 3: Contextual Retrieval
The RAG context problem
Retrieval-Augmented Generation (RAG) retrieves relevant information from a knowledge base and appends it to the user’s prompt. It is the standard approach when a knowledge base is too large to fit in the model context window. anthropic
Traditional RAG has a weakness: documents are split into chunks, and each chunk may lose the context needed to interpret it.
Anthropic gives this example:
Original chunk:
"The company's revenue grew by 3% over the previous quarter."
Without context, the system does not know which company or time period the sentence describes. A query such as “What was the revenue growth for ACME Corp in Q2 2023?” may fail to retrieve this chunk. anthropic
Contextual Retrieval
Contextual Retrieval solves this by prepending chunk-specific explanatory context before embedding and before building the BM25 index. anthropic
Original chunk:
"The company's revenue grew by 3% over the previous quarter."
Contextualized chunk:
"This chunk is from an SEC filing on ACME corp's performance in Q2 2023;
the previous quarter's revenue was $314 million.
The company's revenue grew by 3% over the previous quarter."
The contextual text is typically 50 to 100 tokens and is generated by an LLM using the whole document plus the chunk. anthropic
Hybrid retrieval
Contextual Retrieval combines two retrieval mechanisms:
| Mechanism | Strength | Weakness |
|---|---|---|
| Contextual embeddings | Semantic similarity | May miss exact identifiers |
| Contextual BM25 | Exact lexical matching | May miss paraphrases |
BM25 is a lexical ranking function based on TF-IDF concepts. It is particularly useful for exact identifiers, error codes, product SKUs, and technical terms. anthropic
User query
|
+--> Contextual embeddings --> semantic candidates
|
+--> Contextual BM25 ------> lexical candidates
|
v
Rank fusion and deduplication
|
v
Top-K chunks
|
v
LLM response generation
Anthropic’s results
Anthropic evaluated Contextual Retrieval across codebases, fiction, ArXiv papers, and scientific papers, using top-20 retrieval and $1 - \text{recall}@20$ as the failure metric. anthropic
| Configuration | Top-20 retrieval failure rate | Reduction |
|---|---|---|
| Standard retrieval baseline | 5.7% | — |
| Contextual Embeddings | 3.7% | 35% |
| Contextual Embeddings plus Contextual BM25 | 2.9% | 49% |
| Contextual Embeddings plus Contextual BM25 plus reranking | 1.9% | 67% |
These results come from Anthropic’s evaluated domains, embedding configuration, and top-20 retrieval setting. They demonstrate that context, lexical retrieval, and reranking provide complementary benefits. anthropic
Reranking
Reranking improves precision by scoring retrieved candidates against the query and selecting only the most relevant ones.
Anthropic’s pipeline retrieves the top 150 chunks, reranks them, and passes the top 20 to the model. anthropic
Initial retrieval: top 150 chunks
|
v
Reranker scores each chunk
|
v
Select top 20 chunks
|
v
LLM generates final response
Reranking improves response quality and can reduce cost and latency because the generator processes less context. However, it adds a runtime step, so systems must balance reranking more chunks for quality against reranking fewer chunks for lower latency and cost. anthropic
Implementation considerations
Anthropic recommends attention to:
- Chunk size, boundaries, and overlap.
- Embedding-model choice.
- Domain-specific contextualizer prompts.
- Number of chunks passed to the generator.
- Separate evaluation of retrieval and response generation. anthropic
For knowledge bases smaller than 200,000 tokens, Anthropic notes that simply placing the entire knowledge base in the prompt may be preferable to RAG. Prompt caching can make this approach faster and cheaper. anthropic
Part 4: Continual Learning and the Sleep Framework
The static-model problem
Most deployed LLMs are static after training. They have a knowledge cutoff and cannot naturally acquire long-term facts or adapt to new information after deployment. research
Two common approaches have limitations:
| Approach | Strength | Limitation |
|---|---|---|
| Continue parameter training | Can add new knowledge | Can cause catastrophic forgetting |
| In-context learning | Fast adaptation without weight updates | Knowledge disappears when context ends |
Catastrophic forgetting occurs when learning new tasks severely degrades performance on previously learned tasks. In-context learning, by contrast, retains information only within the current context window. research
The sleep paradigm
Google Research’s sleep framework introduces a periodic lifecycle with two states: research
- Active or wake phase: the model processes inputs and stores temporary information in short-term memory.
- Sleep phase: the model pauses new input processing and consolidates short-term memory into long-term parameters.
Active phase
|
v
Short-term memory
|
v
Sleep phase
|
+--> Memory consolidation
|
+--> Dreaming / self-improvement
|
v
Updated long-term parametric memory
The framework operates within a fixed model architecture and human-defined training rules. During the offline sleep phase, the model unlocks preallocated Mixture-of-Experts memory blocks and updates weights using self-generated practice examples. research
Memory consolidation
Memory consolidation transfers fragile short-term context into stable long-term parameters. It uses: research
- Parameter expansion through newly unlocked low-rank experts.
- A continuum memory hierarchy.
- Knowledge seeding through upward distillation.
- On-policy distillation.
- Learning to imitate using semantic and Levenshtein-distance rewards.
- Synaptic pruning after consolidation.
The goal is not to copy every short-term detail into parameters. Google describes it as structured, low-rank compression: identify compact directions that preserve on-policy behavior and semantically useful information. research
Dreaming
The dreaming stage generates synthetic training examples, or “dreams,” and uses them for self-improvement. research
Short-term memory
|
v
Random expert activation
|
v
Generate synthetic samples
|
v
Gradient-based sample selection
|
v
Reinforcement-learning refinement
|
v
Improved model capability
Random expert selection forces the model to mix knowledge from different domains. Gradient-based filtering prioritizes synthetic samples with the highest potential to improve overall capability. research
Reported results
Google reports the following results for its sleep framework: research
| Evaluation | Reported result |
|---|---|
| Continual translation in unseen languages | Near-zero performance drop across multi-stage evaluation |
| Long-context understanding on BABILong | Near-perfect scaling up to 10M tokens |
| Factual knowledge incorporation on SQuAD | 48.9% |
| Continued pre-training evaluation | 46.2% |
| AIME 24/25 | 79.2% |
| HMMT 25 | 46.1% |
The framework is reported to outperform baselines including in-context learning, supervised fine-tuning, Cartridges, GPT-4, Titans, SEAL, GRPO, and on-policy self-distillation in the respective evaluations. These results are specific to Google’s benchmarks, models, and experimental setup. research
Part 5: How the Pieces Fit Together
A production AI system
User request
|
v
+---------------------------+
| Query understanding |
+-------------+-------------+
|
v
+---------------------------+
| Contextual retrieval |
| - contextual embeddings |
| - contextual BM25 |
| - reranking |
+-------------+-------------+
|
v
+---------------------------+
| Reasoning model / agent |
| - tools |
| - memory |
| - control flow |
+-------------+-------------+
|
v
+---------------------------+
| Grounded response |
+-------------+-------------+
|
v
+---------------------------+
| Feedback and sleep phase |
| - consolidate new facts |
| - generate practice data |
| - update long-term memory |
+---------------------------+
This is a conceptual architecture combining the three source patterns. It is not a claim that any single production system implements all of them exactly in this form.
Division of responsibility
| Capability | Best mechanism | Main limitation |
|---|---|---|
| Answer a hard reasoning problem | Reasoning model, inference scaling, RLVR | Higher latency and token cost |
| Use current private knowledge | Contextual retrieval | Retrieval quality depends on chunking and indexing |
| Use exact identifiers | BM25 or hybrid retrieval | Lexical match alone may miss paraphrases |
| Avoid out-of-context answers | Retrieval plus grounding | Retrieval can fail or return irrelevant evidence |
| Learn new facts after deployment | Continual learning or sleep-phase consolidation | Risk of forgetting, cost, and evaluation complexity |
| Adapt within one session | In-context learning | Knowledge is lost after the session |
Part 6: Comparisons and Trade-Offs
Reasoning versus retrieval versus continual learning
| Dimension | Reasoning model | Contextual retrieval | Continual learning |
|---|---|---|---|
| Primary goal | Solve harder problems | Ground answers in external knowledge | Retain knowledge over time |
| Weight updates | Often yes, through RLVR or distillation | Usually no | Yes, periodically |
| Latency impact | Can be high | Moderate | Usually offline |
| Cost impact | Higher inference cost | Retrieval and reranking cost | Training and infrastructure cost |
| Failure mode | Wrong reasoning or reward hacking | Bad chunks or failed retrieval | Catastrophic forgetting |
| Best for | Math, code, planning, complex analysis | Private, changing, or large knowledge bases | Long-lived assistants and evolving domains |
Inference scaling versus post-training
| Approach | When weights change | Cost profile | Best use |
|---|---|---|---|
| Chain-of-thought prompting | No | More output tokens | Quick improvement without training |
| Self-consistency | No | Multiple samples per query | High-value tasks where latency is acceptable |
| Self-refinement | No | Multiple generation passes | Tasks where critique improves quality |
| RLVR / GRPO | Yes | Expensive training | Verifiable domains such as math and code |
| Distillation | Yes | Teacher-generation plus student training | Deploying smaller reasoning models |
Raschka’s course treats these as complementary paths: inference-time scaling improves a fixed model, while RLVR and distillation change the model itself. magazine.sebastianraschka
Part 7: Limitations and Open Questions
Reasoning models
- Verifiers can be wrong, incomplete, or gameable.
- Reward hacking can produce responses that satisfy the verifier without solving the task.
- More inference-time compute does not always improve accuracy.
- Distillation is bounded by teacher quality and data diversity.
- RL training can be unstable and memory-intensive.
Raschka’s course explicitly examines reward hacking, KL terms, clipped policy ratios, and the limitations of simplified KL formulations. magazine.sebastianraschka
Contextual retrieval
- LLM-generated chunk context adds preprocessing cost.
- Poor chunk boundaries can still harm retrieval.
- Reranking adds runtime latency.
- More retrieved chunks can distract the generator.
- Retrieval evaluation must be separated from response-generation evaluation.
Anthropic found that passing 20 chunks was more effective than 5 or 10 in its experiments, but recommends experimenting per use case because additional context can also distract the model. anthropic
Continual learning
- Continual parameter updates remain risky.
- Synthetic self-generated data can reinforce model errors.
- Memory expansion increases model size and infrastructure complexity.
- Long-context consolidation must preserve both new and old knowledge.
- Benchmarks may not reflect real production distribution shift.
Google’s sleep framework addresses forgetting through parameter expansion, low-rank memory blocks, distillation, and pruning, but these mechanisms add substantial system complexity. research
Part 8: Practical Design Checklist
- Start with a strong evaluation harness before changing the model.
- Use verifiable rewards where the task has checkable correctness.
- Use inference-time scaling when model weights must remain fixed.
- Use distillation when a smaller, cheaper reasoning model is needed.
- Use hybrid retrieval when both semantic similarity and exact matching matter.
- Add chunk-specific context before embedding and indexing.
- Use reranking when retrieval precision matters more than minimal latency.
- Keep retrieval evaluation separate from response evaluation.
- Use in-context learning for session-local adaptation.
- Use continual learning only with strong forgetting, cost, and safety controls.
- Monitor factual accuracy, retrieval failure rate, reasoning quality, latency, and cost.
Resources
- Build Your Own Reasoning Model — eight-video, 11-hour course covering evaluation, inference-time scaling, GRPO-based RLVR, and distillation in Python and PyTorch.
- Introducing Contextual Retrieval — Anthropic’s method for contextual embeddings, contextual BM25, and reranking.
- The sleep framework — Google Research’s continual-learning framework using wake and sleep phases.
- Headroom — further reading on retrieval and context management.
- Why Spotify is not using Bayesian A/B testing — further reading on experimentation methodology.
- KronLSTM — further reading on recurrent sequence-model architectures.
- Gemma 4 Developer Agent Paper competition — further reading on agent benchmarking.
Final Technical Takeaways
- Central mechanism: Reasoning models improve problem-solving through verifiable rewards, inference-time scaling, and distillation; retrieval systems ground responses in external knowledge; continual learning systems retain new knowledge over time.
- Main architectural insight: Separate the model engine from the agent harness. The harness manages context, tools, memory, and control flow; the model performs reasoning and generation. magazine.sebastianraschka
- Important retrieval insight: Embeddings and BM25 solve different retrieval failures. Adding chunk-specific context before embedding and indexing, then reranking, reduced Anthropic’s top-20 retrieval failure rate from 5.7% to 1.9%. anthropic
- Important continual-learning insight: Alternate active interaction with offline consolidation so short-term context can become stable parametric memory without relying solely on a fixed context window. research
- Key trade-off: More reasoning, more retrieved context, and more training can improve capability, but each increases latency, cost, complexity, or forgetting risk.
- Main limitation: A stronger model does not automatically produce a better system. Verifiers, retrieval quality, context management, and evaluation discipline often determine real-world performance. magazine.sebastianraschka
- Broader engineering implication: Build LLM systems as closed loops: reason, retrieve, act, measure, consolidate useful experience, and improve—while keeping forgetting, hallucination, and cost under explicit control. magazine.sebastianraschka