Module contents
Lesson 37 of 37Research 100 min

Frontier: in-context RL, generalist agents, scaling and RL for language models

Map active research using the module's tools: meta-RL and in-context RL, generalist agents and interactive world models, scaling deep RL, RL in language-model reasoning, and open-ended learning. Learn to read claims critically, replicate at small scale, and choose problems.

After this lesson you can

  • Explain in-context RL and reproduce Algorithm Distillation on a small scale.
  • Analyze RL with verifiable rewards for language models through credit assignment, exploration, and overoptimization.
  • Summarize evidence on scaling networks and compute in deep RL.
  • Critically assess recent claims and design a local-scale replication.
  • Place open-ended learning and generalist agents in the context of the module.

Before you start

A map, not a list of records

The RL frontier is not one race. There are agents learning to adapt within context, models simulating possible futures, algorithms extracting policies from logs, agent teams, and systems optimizing language-model answers. Module concepts invite the same questions in each line: what the agent observes, what actions it controls, what reward it receives, what data it learns from, and how behavior is measured outside training.

InteractiveFrontier questions
In-context RLWorld modelsOffline RLMulti-agentRL for LLMsPlanning and self-play
In-context RL

Does in-context learning generalize to truly new tasks?

Paper: Algorithm Distillation

Read this session0 / 6
Module foundationsPOMDPs and memory
Explore six lines, their papers, and prerequisites. Reading status is retained during this widget session.

A citation does not establish that a method is always superior. Read the protocol alongside the figure: tasks, seeds, environment steps, compute, and tuning rules. A larger model may use the same interactions and much more compute, or the same compute and fewer interactions. Both comparisons are useful but answer different questions.

Learn within context

In in-context RL, weights remain fixed while adapting to a new task. What changes is received history or the recurrent state summarizing it. In an unknown bandit, history includes previous actions and rewards; a policy with memory can explore arms and then prefer those appearing better. Resetting memory between episodes erases evidence enabling adaptation.

RL² slowly trains a recurrent network over a task distribution while retaining state between episodes of the same task. The network receives observations, actions, rewards, and termination signals. Fast learning occurs in activations, not a weight gradient step on the test task. Fine-tuning instead changes parameters; both can use new experience but have different costs and internal states.

Consider two bandits with the same initial observation but different rewards. Before acting, the agent does not know which it received; after trying an arm and observing reward, recurrent state can encode evidence about that task. From outside the problem is partially observable even if each bandit has fixed rules. A reactive policy receiving only current observation cannot distinguish histories ending in the same observation. A policy with memory can act differently, but only if training taught it to use that information.

Retaining memory does not prove learning an algorithm. The model may use episode position, memorize frequent actions, or exploit accidental task-set regularities. A stronger test changes arm probabilities, permutes identities, and measures the effect of erasing, changing, or permuting past rewards. It should separate task-generation and model-training seeds. Testing one network initialization means task variation does not substitute for variation across training runs.

Algorithm Distillation generates complete learning histories from a source algorithm and trains a causal transformer to predict actions from what happened before. If data contain only expert trajectories, imitating actions need not teach improvement during interaction. Learning histories retain initial exploration and later adaptation. At deployment the model’s own actions and rewards enter context, not the source agent’s. The history distribution may change and degrade imitation.

AdA studies adaptation across a broad 3D task space using memory and automatic curriculum. Results belong to its distribution and training budget; “human-timescale adaptation” does not mean every task outside that distribution is solved. To check generalization, separate test tasks by parameters, topologies, or rules and compare with a baseline unable to use history. Longer context also does not guarantee improvement if irrelevant or beyond training length.

Local lab: distill histories

We build two history classes. In four-arm bandits, a UCB teacher receives a new Bernoulli probability vector per task; each action is an episode and the teacher retains counts. In 4 × 4 grids, Q-learning explores toward an unobserved goal and retains its table across episodes. Test goals lie in the right column, excluded from training-goal distribution. Grid observation includes current position; a task identifier distinguishes problem types.

Each input step groups current observation, previous action and reward, previous end signal, and task type; the label is the teacher’s current action. The transformer uses a causal mask, two 64-component layers, and context up to 64 steps. It generates 400 histories per type and trains 5000 batches of 32 sequences on GPU. Grid histories use eleven possible goal positions repeated with different seeds, not 400 distinct grid configurations. Weights, optimizer, and random states are saved atomically every 500 updates; the process can resume from checkpoint. Evaluation freezes weights and compares context 64 with context 1 on 32 new-seed instances per type, plus random actions and UCB for bandits. Grid selects among four held-out goal positions repeated across those 32 instances.

[ ]Causal transformer and UCB and Q-learning teachersLocal GPU
"""Destilación de algoritmos en bandits y grids, con tareas separadas para evaluación."""
import json,random,os
from pathlib import Path
import numpy as np
import torch
from torch import nn

torch.set_num_threads(1)
K=4;L=64;START=4
MOVES=np.array([[0,-1],[1,0],[0,1],[-1,0]])

def bandit_history(seed,length=128):
 rng=np.random.default_rng(seed);p=rng.uniform(.1,.9,K);counts=np.zeros(K);totals=np.zeros(K);rows=[];pa=START;pr=0;done=1
 for t in range(length):
  score=np.divide(totals,counts,out=np.zeros(K),where=counts>0)+np.sqrt(2*np.log(t+1)/np.maximum(counts,1));score[counts==0]=np.inf
  candidates=np.flatnonzero(score==score.max());a=int(rng.choice(candidates));reward=int(rng.random()<p[a]);rows.append((0,pa,pr,done,0,a));counts[a]+=1;totals[a]+=reward;pa,pr,done=a,reward,1
 return np.array(rows,dtype=np.int64)

def grid_history(seed,episodes=20,horizon=20):
 rng=np.random.default_rng(seed);goal=int(rng.choice([1,2,4,5,6,8,9,10,12,13,14]));q=np.zeros((16,4));rows=[];pa=START;pr=0;done=1
 for episode in range(episodes):
  state=0
  for t in range(horizon):
   a=int(rng.integers(4)) if rng.random()<.2 else int(rng.choice(np.flatnonzero(q[state]==q[state].max())))
   x,y=state%4,state//4;dx,dy=MOVES[a];nxt=int(np.clip(y+dy,0,3)*4+np.clip(x+dx,0,3));r=int(nxt==goal);terminal=bool(r or t==horizon-1)
   rows.append((state,pa,pr,done,1,a));q[state,a]+=.2*(r+(.95*q[nxt].max() if not terminal else 0.)-q[state,a]);state=nxt;pa,pr,done=a,r,int(terminal)
   if terminal:break
 return np.array(rows,dtype=np.int64)

class Distiller(nn.Module):
 def __init__(self):
  super().__init__();d=64
  self.obs=nn.Embedding(16,d);self.action=nn.Embedding(5,d);self.reward=nn.Embedding(2,d);self.done=nn.Embedding(2,d);self.task=nn.Embedding(2,d);self.pos=nn.Embedding(L,d)
  layer=nn.TransformerEncoderLayer(d_model=d,nhead=4,dim_feedforward=128,batch_first=True,dropout=0.)
  self.blocks=nn.TransformerEncoder(layer,num_layers=2,enable_nested_tensor=False);self.head=nn.Linear(d,4)
 def forward(self,x):
  T=x.shape[1];h=self.obs(x[:,:,0])+self.action(x[:,:,1])+self.reward(x[:,:,2])+self.done(x[:,:,3])+self.task(x[:,:,4])+self.pos(torch.arange(T,device=x.device))[None]
  mask=torch.triu(torch.ones(T,T,device=x.device,dtype=torch.bool),diagonal=1)
  return self.head(self.blocks(h,mask=mask))

def make_data(tasks,seed):
 return [bandit_history(seed+i) for i in range(tasks)]+[grid_history(seed+100000+i) for i in range(tasks)]

def train(updates=5000,tasks=400,seed=11,device='cuda',save_path='ad-model.pt'):
 torch.manual_seed(seed);np.random.seed(seed);random.seed(seed);rng=np.random.default_rng(seed);data=make_data(tasks,seed*1000);net=Distiller().to(device);optimizer=torch.optim.AdamW(net.parameters(),lr=3e-4)
 start_step=0
 if Path(save_path).exists():
  checkpoint=torch.load(save_path,map_location=device,weights_only=False)
  assert checkpoint['tasks_per_type']==tasks and checkpoint['seed']==seed
  net.load_state_dict(checkpoint['state']);optimizer.load_state_dict(checkpoint['optimizer']);rng.bit_generator.state=checkpoint['rng_state'];torch.set_rng_state(checkpoint['torch_rng'].cpu());start_step=checkpoint['updates']
  if device.startswith('cuda'):torch.cuda.set_rng_state_all([v.cpu() for v in checkpoint['cuda_rng']])
 for step in range(start_step,updates):
  batches=[]
  for _ in range(32):
   row=data[int(rng.integers(len(data)))];start=int(rng.integers(max(1,len(row)-L+1)));window=row[start:start+L]
   if len(window)<L:
    pad=np.zeros((L-len(window),6),dtype=np.int64);pad[:,5]=-100;window=np.concatenate((window,pad))
   batches.append(window)
  batch=torch.tensor(np.stack(batches),device=device);logits=net(batch[:,:,:5]);loss=nn.functional.cross_entropy(logits.reshape(-1,4),batch[:,:,5].reshape(-1))
  optimizer.zero_grad();loss.backward();nn.utils.clip_grad_norm_(net.parameters(),1.);optimizer.step()
  if (step+1)%500==0 or step+1==updates:
   print('update',step+1,'loss',float(loss.detach()),flush=True)
   snapshot={'state':net.state_dict(),'optimizer':optimizer.state_dict(),'updates':step+1,'tasks_per_type':tasks,'seed':seed,'rng_state':rng.bit_generator.state,'torch_rng':torch.get_rng_state(),'cuda_rng':torch.cuda.get_rng_state_all() if device.startswith('cuda') else []}
   temp=str(save_path)+'.tmp';torch.save(snapshot,temp);os.replace(temp,save_path)
 return net

def evaluate(net,task,context,seed,episodes=40,baseline='model'):
 rng=np.random.default_rng(seed);choices=np.random.default_rng(seed+9999);p=rng.uniform(.1,.9,K);goal=int(rng.choice([3,7,11,15]));state=0;history=[];pa=START;pr=0;done=1;rewards=[];actions=[];counts=np.zeros(K);totals=np.zeros(K)
 horizon=1 if task==0 else 20;device=next(net.parameters()).device
 for episode in range(episodes):
  score=0;state=0
  for t in range(horizon):
   history.append([state if task else 0,pa,pr,done,task]);x=torch.tensor([history[-context:]],device=device)
   if baseline=='random':a=int(choices.integers(4))
   elif baseline=='ucb' and task==0:
    scores=np.divide(totals,counts,out=np.zeros(K),where=counts>0)+np.sqrt(2*np.log(episode+1)/np.maximum(counts,1));scores[counts==0]=np.inf;a=int(choices.choice(np.flatnonzero(scores==scores.max())))
   else:
    with torch.no_grad():a=int(net(x)[0,-1].argmax().item())
   if task==0:r=int(rng.random()<p[a]);terminal=True
   else:
    dx,dy=MOVES[a];x0,y0=state%4,state//4;state=int(np.clip(y0+dy,0,3)*4+np.clip(x0+dx,0,3));r=int(state==goal);terminal=bool(r or t==horizon-1)
   score+=r;actions.append(a);counts[a]+=1;totals[a]+=r;pa,pr,done=a,r,int(terminal)
   if terminal:break
  rewards.append(score)
 return {'seed':seed,'task':'bandit' if task==0 else 'grid','context':context,'baseline':baseline,'rewards':rewards,'actions':actions,'goal':goal if task else None,'probabilities':p.tolist() if task==0 else None}
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Train and evaluate on new tasksLocal GPU
assert torch.cuda.is_available(), "Este experimento requiere una GPU CUDA para el presupuesto indicado"
model=train(5000,400,device="cuda",save_path="ad-model.pt");model.eval()
rows=[evaluate(model,task,context,200000+i) for task in (0,1) for context in (1,64) for i in range(32)]
rows += [evaluate(model,task,1,200000+i,baseline="random") for task in (0,1) for i in range(32)]
rows += [evaluate(model,0,1,200000+i,baseline="ucb") for i in range(32)]
Path("ad-model.pt.results.json").write_text(json.dumps(rows,indent=2),encoding="utf8")
for task in ("bandit","grid"):
    for method,context in (("model",1),("model",64),("random",1),("ucb",1)):
        group=[r for r in rows if r["task"]==task and r["baseline"]==method and r["context"]==context]
        if group:
            values=np.array([r["rewards"] for r in group]);print(task,method,context,"primeros 10",float(values[:,:10].mean()),"últimos 10",float(values[:,-10:].mean()))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The previous episode’s end signal is retained in the first input of the next, so the model can know when reset occurred without losing task history. Short episodes are padded only to form batches and padding positions do not contribute to loss. In grid, a goal held out by position requires extrapolation beyond seen goals; memorizing a training trajectory is insufficient. Still, this small experiment does not reproduce the paper’s environments or scale.

InteractiveDistilled model trajectories
Chosen action: arm 2
True probabilities, hidden from the agent: 0.86 / 0.22 / 0.68 / 0.15
A held-out task is shown; each reward is a Bernoulli sample.

Bars: reward per episode. Improvements are not guaranteed in every trajectory or when averaging tasks.

Task
Context
1
Episode reward0
Mean episodes 1 to 100.60
Mean episodes 31 to 400.80
Weightsfijos
Data from 32 evaluations per type and context; grid has four held-out goals repeated across instances. Choose evaluation and episode; weights remained frozen.

In our RTX 3060 run, mean per-episode return across 32 held-out bandits was 0.669 with context 64, 0.532 with context 1, 0.596 with UCB, and 0.517 with random actions. In grid, context 64 scored 0.297 and random actions 0.295; context 1 scored 0.156. These average 40 episodes per instance and one transformer training seed; four grid goals repeat, so there are not 32 independent grid types. This is not a robust general advantage estimate. Full context beats truncated context in this run, but the contrast does not itself identify whether the model uses rewards, positions, or sequence correlations.

The last ten episodes’ mean did not improve over the first ten: with context 64 it changed from 0.672 to 0.653 in bandits and 0.344 to 0.281 in grid. Thus this test does not demonstrate temporal policy improvement within the task, although individual trajectories vary. An ablation permuting past rewards and multiple training seeds would help investigate mechanism. The figure explores 32 held-out evaluations; it does not generate or train a new model in the browser.

Generalist agents and interactive worlds

Generalist agents share parameters across tasks or modalities. Gato represents data and actions from domains ranging from text to control in one sequence. Sharing a network does not demonstrate transfer to every task or superiority to a specialist on each. Record which tasks, demonstrations, and modalities were included in training and which were truly held out.

Genie studies interactive environments generated from video without action labels. A world model useful for imagining interactions can produce convincing images while misrepresenting physics, object persistence, or action consequences. Evaluating an agent trained in a generated simulator requires external tests and sensitivity measurements. A generator sharing benchmark data may favor apparent generalization that fails in an independent environment.

Generalist-agent evaluation should declare whether weights may adapt, many samples may be searched, or in-context demonstrations used for each task. Comparing many attempts per problem against one measures more than policy quality. In robotics, control time and action safety matter; in games, episodes per map may matter. Aggregate means should accompany per-family results and failures where the agent does not even complete the protocol.

Scale, compute, and plasticity

Deep RL scaling has several axes: parameters, environment steps, updates per transition, memory, and task count. Increasing one may change cost or overfitting regime of others. Bigger, Better, Faster studies large networks and sample efficiency on Atari 100K; the benchmark name indicates a specific budget, not a universal law for robotics or medicine.

A value function can train by classification over bins instead of scalar regression. If a target lies between adjacent centers, a two-hot representation splits mass between them; expected value is recovered by weighting centers by predicted probabilities. Farebrother and colleagues investigate classification for scaling value estimators. Support, scale transformation, and out-of-range targets matter: classification does not automatically remove bias or bootstrap error.

Plasticity is the ability to keep learning when distribution changes. An agent with good final return may have lost the ability to adapt to new tasks or use more data. Test resets, task changes, and curves across training, not just a final number. A trend in one experimental family is not a transferable scaling law without checking its limits.

In supervised learning, scaling data can mean processing more fixed examples. In RL, the policy changes the observation distribution it will collect next; a larger agent may generate different data and an old buffer become less representative. Increasing network size, update frequency, and experience simultaneously does not identify which caused improvement. One useful ablation fixes interactions while varying compute; another fixes approximate compute while varying interactions. Also count simulation, training, and evaluation when comparing total cost.

A categorical value distribution has support bounds. Projecting returns outside the interval to the edge may saturate predictions; widening it excessively can lose bin resolution where values concentrate. Specify scale transformation and interpolation alongside loss. Do not attribute all improvement to “classification” if the variant also changed normalization, architecture, or budget.

Tokens, final reward, and group signal

In RL for language-model reasoning, one useful formulation takes instruction and emitted prefix as state, next token as action, and complete answer as episode. A verifier can assign reward at the end. This recovers temporal credit assignment: many tokens receive signal derived from one result, and a correct answer may contain useless or incorrect steps that did not affect the verdict.

One objective family uses multiple responses to one instruction, computes reward mean and dispersion, and normalizes advantages within the group. A PPO-style objective uses the new-to-old policy probability ratio and clips part of the incentive for large changes; a KL penalty can limit departure from a reference. Group normalization, clipping, and KL are separate decisions. REINFORCE explains reward-weighted policy gradients; comparisons between answers resemble a baseline; PPO contributes a clipped objective. There is no single implementation of all these pieces.

InteractiveFrom an answer to group advantage
State: instruction + previous prefix
Action: Compute
Group: 1100
Reward: verifier at the end of the response

The penalty uses a hypothetical KL of 0.1, not a model measurement. If standard deviation is zero, this illustration sets advantage to zero.

2
Generation step
1.00
0.10
Group mean and standard deviation0.50 / 0.50
Advantage of a correct response1.000
Clipped PPO term1.000
Illustrative penalty0.010
Numerical example of four binary rewards and hypothetical KL; these are not language-model measurements.

If all four rewards are equal, group standard deviation is zero: here advantage is defined as zero. With two correct and two incorrect answers, mean and population deviation are 0.50.5, and a correct answer has advantage 11. Terminal reward does not identify which token contributed to success. The figure’s KL coefficient multiplies a hypothetical value of 0.1; no divergence was measured. DeepSeek-R1 describes RL and reasoning experiments, but extrapolation requires controlling base model, data, verifiers, compute, and evaluation.

An incomplete verifier can be exploited. An answer passing a weak test does not always solve the task, and repeated optimization against one set can overfit it. For mathematical or code problems separate examples, evaluators, and hidden tests; measure length, cost, and out-of-distribution failures as well as success rate. A stochastic or manipulable verifier outputs an imperfect observation of desired quality.

As a credit-assignment example, if an answer contains ten steps and the verifier checks only the final answer, success signal does not identify which step was necessary. Repeating that advantage for every token yields a gradient estimator, not a local correctness label for each reasoning step. A step evaluator can provide denser signal but introduces another model or rules that can also be wrong. The reasoning and preference modules develop these decisions; here the connection is horizon, reward, and exploration distribution.

Small average KL does not prevent a particular answer changing greatly or the model learning to exploit a verifier exception. Conversely, a higher-KL policy can be useful if it improves on held-out tasks and cost is justified. Compare variants with fixed initial model, instructions, answers per group, and total token budget. If a variant uses more evaluation or selection samples, declare it rather than attributing the whole difference to the algorithm.

Open-ended learning and evaluation

Open-ended search seeks diverse tasks and solutions instead of fixing one curriculum in advance. POET proposes generating environments and transferring agents among them. Diversity depends on generator, selection, and metrics; a growing task set alone does not prove unlimited progress. The era of experience thesis proposes greater emphasis on interaction and outcomes, but is a research position, not an empirical guarantee that every interaction yields useful data.

An automatic curriculum can choose tasks not yet mastered where the agent makes some progress. Selecting only impossible tasks can eliminate reward signal; selecting only solved tasks adds little information. In an open-ended system, retention of old solutions, policy transfer, and whether new tasks differ under a generator-independent metric matter too. Counting syntactically different instances does not prove functional diversity.

A good research question first defines the failure to detect. For example: does an agent apparently adapting to a bandit use past rewards or merely favor the most frequent training arm? Design a test distribution with permuted arm labels, keep budget and architecture identical, and compare intact history, permuted reward history, and erased memory. The hypothesis may be false: a negative replication with reproducible data and code also reduces uncertainty.

When replicating, state what stays fixed and what changes. If a paper uses a hard environment and local replication uses a smaller world, the latter may test a mechanism without reproducing scale or main result. Separate training seeds from test tasks, save configurations, and compare budgets. An interquartile mean reduces sensitivity to extremes when aggregating, but cannot compensate for an irrelevant benchmark or replace uncertainty intervals. With few seeds, even a narrow interval may result from unvaried data.

A bounded RND replication

The original Random Network Distillation work studies exploration using a fixed random network and predictor, including hard-exploration Atari games. The earlier in-house implementation compares PPO and PPO+RND on MiniGrid Empty with 102,400 steps per combination, three seeds, and 50 evaluation episodes. It retains distillation and comparison to a no-bonus policy but radically changes environment and budget: it does not reproduce Atari or its main results.

Each entry below is mean evaluation return for a seed actually run in that lesson, not an individual episode. The interquartile mean (IQM) integrates quantiles from 25% to 75%, with fractional endpoint weights. State the convention for such a small empirical distribution. Bootstrap resamples seed pairs; seeds have nominally common conditions, but that does not guarantee paired trajectories between algorithms. The interval describes only this operation and these three seeds.

[ ]IQM and bootstrap for a small replicationBrowser
import numpy as np
ppo=np.array([.961328125,.961328125,.961328125])
rnd=np.array([.961328125,.961328125,.961328125])
def iqm(values):
    x=np.sort(np.asarray(values,float));n=len(x);lo=.25*n;hi=.75*n
    weights=np.array([max(0.,min(i+1,hi)-max(i,lo)) for i in range(n)])
    return float(weights@x/weights.sum())
rng=np.random.default_rng(71);differences=[]
for _ in range(5000):
    ids=rng.integers(len(ppo),size=len(ppo));differences.append(iqm(rnd[ids])-iqm(ppo[ids]))
print('IQM PPO',iqm(ppo),'IQM RND',iqm(rnd),'diferencia',iqm(rnd)-iqm(ppo))
print('intervalo bootstrap 95 %',np.quantile(differences,[.025,.975]))

Both variants have IQM 0.961328125 and difference zero; all resamples also give zero because the three saved values match exactly. A degenerate interval does not prove identical policy performance on other tasks or zero real uncertainty. The ablation removes RND while holding the rest fixed; this easy-environment result does not separate methods. The decisive limitation is changed benchmark and scale: the observation supports a local code check, not conclusive paper replication.

When expanding the study, do not turn each variant’s 150 episodes into 150 independent trainings: they belong to only three trained policies. An alternative resamples training seeds first and then episodes within each seed, if individual returns were retained. When comparing tasks, normalize or present per-task results before aggregation so one reward scale does not dominate the summary. Here only per-seed means were retained, so code does not invent an episode-level interval.

The next experiment need not seek victory at any cost. It could fix a harder exploration task, record coverage and external return, run more seeds, and compare an agent without bonus normalization. Before training, state what would support and weaken the hypothesis. If agents reach the environment ceiling too soon, the experiment cannot distinguish them; changing task and measuring again is more informative than interpreting a tie as universal equivalence.

Exercises

NumericDoes the history fit?
A history has 50 episodes of 20 steps. Each step uses three tokens (observation, action, reward), each episode adds a separator, and the full sequence starts with one initial token. How many tokens does it occupy?
QuizContext or gradients
What distinguishes RL² in-context adaptation from gradient fine-tuning?
QuizWhat evidence to request
A report claims an RL method improves reasoning for any model and never exploits its verifier. What observation would best evaluate the claim?
CodeUCB learning history
Implement history(probs, steps, seed). For a Bernoulli bandit with probabilities probs, use np.random.default_rng(seed). At each step randomly choose an unvisited arm if available; otherwise maximize empirical mean + sqrt(2 log(t+1)/N), with t starting at zero and random tie-breaking. Sample Bernoulli reward using the same generator. Return a list of tuples (accion_anterior, recompensa_anterior, accion_actual) (previous action, previous reward, current action); before the first action use len(probs) as the start symbol and previous reward 0. Do not modify probs.
import numpy as np
def history(probs, steps, seed):
  pass
Shift+Enter to run