Course contents 09 / 27

09 / 27 · Language Models as Agents

The language model as a policy

How a pretrained, instruction-tuned language model becomes the policy of an agent: tokens, turns and actions as a POMDP over text, the prompt as conditioning, temperature as a behavioural knob, why the pretrained prior makes acting possible, and what it still lacks.

On this page 7

The reinforcement-learning section ended with agents that learn a model of their world and plan inside it (previous note). Every agent in that section, from tabular Q-learning to Dreamer, starts from a policy that knows nothing about its task and improves it from rewards, over thousands or millions of episodes. A language model arrives with something none of them had: a policy that has already been trained, on a large share of what people have written, to produce a plausible next move in almost any situation that can be described in text. This note writes the language-model agent in the vocabulary of the first two sections. It defines what the state, the action and the policy are when everything is text, how the prompt and the temperature change the policy without any training, why the pretrained model is a good starting policy, and what it still lacks before it can act well.

Notation. A vocabulary VV of tokens ww. The model gives πθ(w∣w<j)\pi_\theta(w \mid w_{<j}), the probability of the next token after a prefix, through logits z∈R∣V∣z \in \mathbb R^{|V|} and a softmax with temperature τ\tau, as in the GPT note. At environment step tt the environment is in a hidden state sts_t and emits an observation oto_t, a string. The context ctc_t is the token sequence the model reads at that step: the instructions, then o1,a1,…,at−1,oto_1, a_1, \dots, a_{t-1}, o_t, rendered by the chat template. An action is a string y=(w1,…,wm)y = (w_1, \dots, w_m) that ends with an end-of-turn token; a parser ϕ\phi maps it to an element of the environment’s action set A\mathcal A or to invalid. The reward R(s,a,s′)R(s, a, s'), the discount γ\gamma and the belief bb are those of the Markov decision processes note; btb_t is the belief at step tt.

Baseline: a policy that starts from nothing#

The agents of the reinforcement-learning section begin with a uniform or random policy and explore: ε\varepsilon-greedy action choice, an entropy bonus, random initial weights. Exploration works because their action sets are small. A grid world has four actions; an Atari game has at most eighteen. Random actions find a reward sooner or later, and learning takes over from there.

Text is a different action space. Worked example. With the GPT-2 vocabulary of 50,257 tokens, the number of strings of 8 tokens is

50,2578≈4.07×1037.50{,}257^{8} \approx 4.07 \times 10^{37}.

A uniformly random policy emits one particular 8-token action, such as search[Dunmore] followed by the end of the turn, with probability 2.5×10−382.5 \times 10^{-38}. Even if a million different strings were all acceptable actions, a random string would be one of them with probability 2.5×10−322.5 \times 10^{-32}. An agent that had to discover by trial and error that search[ opens a call would never see its first reward. A policy over text has to start with most of its probability on sensible strings, or reinforcement learning has nothing to work with.

Tokens, turns and actions#

The model generates one token at a time, but the environment sees only whole actions. Two levels of description are therefore useful, and the course uses both.

The turn level is the agent of the first note. The environment has a hidden state sts_t, a transition P(st+1∣st,at)P(s_{t+1} \mid s_t, a_t) and an observation oto_t that shows only part of sts_t: a partially observable MDP, or POMDP (Kaelbling, Littman and Cassandra, 1998). The agent receives oto_t and emits ata_t. The policy is a distribution over strings, the product of the token probabilities,

πθ(y∣ct)=∏j=1mπθ(wj∣ct,w<j),\pi_\theta(y \mid c_t) = \prod_{j=1}^{m} \pi_\theta(w_j \mid c_t, w_{<j}),

and the environment receives only what the parser makes of the string. The policy over the environment’s actions adds up every string that parses to the same action:

π(a∣ct)=∑y : ϕ(y)=aπθ(y∣ct),π(invalid∣ct)=∑y : ϕ(y)=invalidπθ(y∣ct).\boxed{ \begin{aligned} \pi(a \mid c_t) &= \sum_{y\,:\,\phi(y) = a} \pi_\theta(y \mid c_t), \\ \pi(\textit{invalid} \mid c_t) &= \sum_{y\,:\,\phi(y) = \textit{invalid}} \pi_\theta(y \mid c_t). \end{aligned} }

The invalid mass is a property of the model, the prompt and the parser together. A strict parser that accepts only Suck makes suck and Suck. invalid; a lenient one maps them to Suck and moves that probability to a valid action.

The token level is the view used when a language model is trained with reinforcement learning. The state is the prefix (ct,w<j)(c_t, w_{<j}), the action is the next token, the transition is deterministic (append the token), and the reward arrives only when a whole response has been judged. This MDP has ∣V∣|V| actions in every state and episodes as long as the response; Reinforcement learning for language models works in it.

Between the two levels lies the question of what the agent conditions on. In a POMDP the information available at step tt is the history ht=(o1,a1,…,at−1,ot)h_t = (o_1, a_1, \dots, a_{t-1}, o_t), and an optimal policy can be written as a function of the belief bt(s)=P(st=s∣ht)b_t(s) = P(s_t = s \mid h_t), which summarizes the history (Markov decision processes). A language-model agent never computes a belief. Its context is the history itself, written as text, ct=template(instructions,ht)c_t = \text{template}(\text{instructions}, h_t), and whatever the model infers about the hidden state stays implicit in its activations. This is the most general form of a POMDP policy, a function of the whole history, with one practical limit: the context window. When the history no longer fits, the runtime drops or summarizes part of it, and the policy then conditions on less than hth_t. Context and memory is about that limit.

MDP or POMDPlanguage-model agent
hidden state sts_twhat the agent cannot see: files, a web page it has not opened, a database
observation oto_ttext returned by the environment: a tool result, an error, a user message
history hth_t or belief btb_tthe context ctc_t: the history written into the chat template
action at∈Aa_t \in \mathcal Aa generated string, parsed into a tool call, a command or a final answer
policy π(a∣s)\pi(a \mid s)π(a∣ct)\pi(a \mid c_t): token probabilities, then the parser
transition P(s′∣s,a)P(s' \mid s, a)the runtime and the world: tools, programs, people
reward R(s,a,s′)R(s, a, s')usually zero until the end, then task success: tests pass, the answer is right
episodeone task, ended by a final answer or a budget
discount γ\gammausually 11, in an episode bounded by a step budget

Worked example: the vacuum world as text. The two-square world of the first note becomes a text environment once its percepts are written as sentences and its actions read from strings. The runtime renders the observation as You are in square A. Square A is dirty.; the model generates Suck and the end-of-turn token; the parser maps the string to the action Suck. One environment step is one turn of the conversation and, here, two generated tokens. A coding agent’s turn may be several hundred tokens of reasoning followed by a command; the turn level stays the same and only the token level grows.

Figure

The language model as a policy: one step of the agent

The language model as a policy: one step of the agentOn the left the agent program: a context column of three rows (instructions; o_1, a_1, …, a_{t−1}; o_t), a model box that produces next-token logits, a sampling box softmax(z / τ) with an arrow back to the model that repeats until the end of the turn, and a parse box that maps the string y to an action or to invalid. On the right the environment, with its hidden state and tools, receives the action a_t. Along the bottom an arrow returns the observation o_{t+1} to the context.agent programcontext ctinstructionso1, a1, …, at-1ot1model πθnext-token logits2samplesoftmax(z / τ)until end of turn3yparseaction or invalid4atenvironmenthidden state, toolsot+1 appended to the history5The language model as a policy: one step of the agentOn the left the agent program: a context column of three rows (instructions; o_1, a_1, …, a_{t−1}; o_t), a model box that produces next-token logits, a sampling box softmax(z / τ) with an arrow back to the model that repeats until the end of the turn, and a parse box that maps the string y to an action or to invalid. On the right the environment, with its hidden state and tools, receives the action a_t. Along the bottom an arrow returns the observation o_{t+1} to the context.context ctinstructionso1, a1, …, at-1ot1model πθnext-token logits2token by tokensamplesoftmax(z / τ)3parseaction or invalid4atenvironmenthidden state, toolsot+1 appended to the history5
The model runs only in steps 2 and 3: it gives a distribution over the next token, a token is drawn, and this repeats until the end of the turn. The template, the parser and the loop belong to the agent program, written by people. The environment sees only the parsed action; a string the parser rejects becomes an invalid action. The context is the history written as text, and it is all the model has to go on about the hidden state of the environment.
  1. Render. The chat template writes the system prompt, the earlier turns and the new observation into the context ctc_t.
  2. Score. The model reads ctc_t and the tokens generated so far in this turn, and produces logits zz for the next token.
  3. Sample. A token is drawn from the softmax of z/τz / \tau; steps 2 and 3 repeat until the end-of-turn token, giving the string yy.
  4. Parse. The parser maps yy to an action at∈Aa_t \in \mathcal A, or reports it as invalid.
  5. Act and observe. The environment executes ata_t, moves to st+1s_{t+1} and returns ot+1o_{t+1}; the turn is appended to the history, and the loop starts again at step 1.

The model runs only in steps 2 and 3. The template, the parser and the loop belong to the agent program around it, written by people, and they decide as much about the agent’s behaviour as the weights do.

Prompting as conditioning#

The policy is πθ(⋅∣c)\pi_\theta(\cdot \mid c), and cc includes text that the designer writes. Changing that text changes the policy without changing θ\theta. Three parts of the context do most of the work.

The system prompt states the task, the role, the rules and the available actions. It is the cheapest lever on behaviour and the most fragile: it is only more tokens in the context, and the model follows it to the extent that training taught it to follow such text.

Demonstrations, or few-shot examples, show the model whole solved cases, here whole trajectories of observations and actions. This is the in-context learning of GPT-3, described in the GPT note. Two findings tell what the examples contribute. Xie et al. (2022) model a prompt as evidence about a latent task: if the pretraining text is a mixture of documents generated under different latent tasks kk, the model’s prediction behaves like

πθ(y∣c)≈∑kP(k∣c) π(y∣c,k),\pi_\theta(y \mid c) \approx \sum_{k} P(k \mid c)\, \pi(y \mid c, k),

and each example sharpens the posterior P(k∣c)P(k \mid c). Worked example. Two candidate tasks start at P(k1)=P(k2)=0.5P(k_1) = P(k_2) = 0.5, and each example is 4 times as likely under k1k_1 as under k2k_2. After one, two and three examples, Bayes’ rule gives

P(k1∣c)=11+4−n=0.8,    0.941,    0.985(n=1,2,3),P(k_1 \mid c) = \frac{1}{1 + 4^{-n}} = 0.8, \;\; 0.941, \;\; 0.985 \qquad (n = 1, 2, 3),

so a few examples settle which behaviour is wanted. The second finding is empirical. In classification and multiple-choice tasks, replacing the labels of the examples by random labels barely hurt accuracy, across 12 models including GPT-3; the format, the set of possible labels and the kind of inputs mattered more (Min et al., 2022). Demonstrations tell the policy what kind of action is expected more than they teach it the mapping.

The chat template marks who said what. The instruction-tuning note shows the template of one model family; for an agent, the context is a sequence of roles. Written with simplified role tags, the context of the vacuum agent after one step reads

<system> You control a vacuum cleaner in squares A and B. Reply with one action: Suck, Left, Right or NoOp.
<user> You are in square A. Square A is dirty.
<assistant> Suck
<user> You are in square A. Square A is clean.
<assistant>

and the model continues after the last tag. Real templates use special tokens and often a separate tool role for observations. The role tokens are the only thing that separates the designer’s instructions from the text that the environment returns. Both condition the same policy, so an observation that contains instructions can steer the agent as well as the system prompt can: the root of the prompt injection of Agent security and prompt injection.

Worked example: an instruction becomes a different agent program. The Code section runs the vacuum world with a scripted stand-in model. With the plain system prompt and τ=0.3\tau = 0.3 it behaves like the reflex agent of the first note: 1.495 points per step at p=0.05p = 0.05 with moves costing 0.50.5, against the reflex agent’s exact 1.494. Adding one sentence, Moving costs energy: wait when the square is clean, and check the other square every few steps, makes the same model wait four steps before it moves, reading the count from the turns in its context. It scores 1.760, the waiting agent’s 1.759. The context served as the agent’s memory, and the prompt selected the program. Whether the new program is better is decided by the environment’s performance measure, not by the prompt: the same instruction would lower the score if moves were free.

Sampling: temperature and behaviour#

The temperature divides the logits before the softmax, Pτ(w)∝exp⁡(zw/τ)P_\tau(w) \propto \exp(z_w / \tau), as in the GPT note: τ→0\tau \to 0 approaches greedy decoding, τ=1\tau = 1 is the model’s own distribution, and τ>1\tau > 1 flattens it. For an agent, the question is what it does to the distribution over actions. For an action of one token, followed by the end of the turn, the answer is exact: its probability is proportional to π(a)1/τ\pi(a)^{1/\tau}, so low temperatures sharpen the policy towards its mode and high temperatures move mass from the head to the tail. For actions of several tokens the sharpening happens token by token, which is not the same as raising πθ(y∣c)\pi_\theta(y \mid c) to the power 1/τ1/\tau.

Worked example: the tail is large. In square A, clean, a model gives the first token of its reply the logits Right 3.03.0, NoOp 1.51.5, Suck 1.01.0 and Left 0.50.5; each of 1,000 other tokens, which would make the reply invalid, gets −8-8. At τ=1\tau = 1, the normalizer is

Z=e3+e1.5+e1+e0.5+1000 e−8=20.086+4.482+2.718+1.649+0.335=29.27,Z = e^{3} + e^{1.5} + e^{1} + e^{0.5} + 1000\,e^{-8} = 20.086 + 4.482 + 2.718 + 1.649 + 0.335 = 29.27,

so Right has probability 0.6860.686 and the invalid tail 0.335/29.27=0.0110.335 / 29.27 = 0.011. At τ=2\tau = 2 every logit is halved, the tail becomes 1000 e−4=18.31000\, e^{-4} = 18.3, and

πτ=2(invalid)=18.34.482+2.117+1.649+1.284+18.3=0.658.\pi_{\tau = 2}(\textit{invalid}) = \frac{18.3}{4.482 + 2.117 + 1.649 + 1.284 + 18.3} = 0.658 .

One token with probability e−8e^{-8} is negligible; a thousand of them are not, once the temperature lifts them. At τ=0.5\tau = 0.5 Right has 0.9300.930 and the tail is below 10−410^{-4}.

Figure

The distribution of the first token of the reply, against temperature

The distribution of the first token of the reply, against temperatureFive probability curves against temperature from 0.1 to 2.5. Right falls from almost 1 at small τ to 0.686 at τ = 1 and 0.161 at τ = 2. NoOp, Suck and Left first rise and then fall; NoOp peaks at 0.168 near τ = 1.23. The probability of an invalid reply, one of the 1,000 unsuitable tokens, is close to zero up to τ ≈ 0.8, is 0.011 at τ = 1, and rises to 0.658 at τ = 2 and 0.839 at τ = 2.5. The curves of Right and of invalid cross near τ = 1.59.0.00.20.40.60.81.00.51.01.52.02.50temperature τprobabilityRightNoOpSuckLeftinvalid (1,000 tokens)The distribution of the first token of the reply, against temperatureFive probability curves against temperature from 0.1 to 2.5. Right falls from almost 1 at small τ to 0.686 at τ = 1 and 0.161 at τ = 2. NoOp, Suck and Left first rise and then fall; NoOp peaks at 0.168 near τ = 1.23. The probability of an invalid reply, one of the 1,000 unsuitable tokens, is close to zero up to τ ≈ 0.8, is 0.011 at τ = 1, and rises to 0.658 at τ = 2 and 0.839 at τ = 2.5. The curves of Right and of invalid cross near τ = 1.59.0.00.20.40.60.81.00.51.01.52.02.50temperature τprobabilityRightNoOpSuckLeftinvalid (1,000 tokens)
The same context and the same logits; only the temperature changes. Logits: Right 3, NoOp 1.5, Suck 1, Left 0.5, and −8 for each of 1,000 tokens after which the reply cannot be parsed. At τ = 0.5 the policy is nearly deterministic (Right 0.930); at τ = 1 it is the model's own distribution; at τ = 2 the tail of a thousand unlikely tokens gathers 0.658, and most replies become invalid. The dotted lines mark τ = 0.5, 1 and 2.

The three regimes matter for agents in different ways.

  • Low temperature gives a nearly deterministic policy. Runs are reproducible and invalid actions rare, but the policy has no exploration, and in an unchanged context it repeats the same action: an agent that failed once with greedy decoding tends to fail the same way again. The ReAct authors trace one of their failure modes, repeating the same thought and action, to greedy decoding (Yao et al., 2023, footnote on repetitive loops).
  • Temperature around 1 samples the model’s own policy. Methods that need several different attempts at the same problem, such as self-consistency in the next note and the reinforcement learning of the training section, sample here, because their signal comes from the differences between samples.
  • High temperature mostly breaks the format. In the Code section, the plain-prompt agent scores 1.495 points per step at τ=0.3\tau = 0.3, 1.570 at τ=1\tau = 1 and 1.055 at τ=2\tau = 2, where 81 % of its replies are invalid. The gain at τ=1\tau = 1 is an accident: random NoOps sometimes make the agent wait, which happens to pay when moves cost something. Temperature changes behaviour in ways that have nothing to do with the task, and its value should be chosen with the environment’s measure, like any other parameter of the agent.

Temperature 00 does not make a served model deterministic either. Floating-point addition is not associative, and the order of the reductions inside a GPU kernel can depend on how many requests share a batch. Asked the same prompt 1,000 times at temperature 0, Qwen3-235B-A22B-Instruct-2507 gave 80 different completions, the first difference at the 103rd token; with kernels rewritten to be independent of the batch size, all 1,000 were identical (He and Thinking Machines Lab, 2025).

Why pretraining and instruction tuning give a usable prior#

Pretraining maximizes the likelihood of human-written text, ∑jlog⁡πθ(wj∣w<j)\sum_j \log \pi_\theta(w_j \mid w_{<j}) over a corpus (Maximum likelihood). Read as reinforcement learning, this is behaviour cloning: imitation of the policy that produced the data, a mixture of millions of writers. The text includes descriptions of procedures, dialogues, questions followed by answers, code followed by its output and logs of commands. The cloned policy therefore already maps situations described in words to the moves people made in them. Instruction tuning continues the imitation on curated demonstrations of an assistant, including demonstrations of tool calls (Instruction tuning and alignment); preference optimization and reinforcement learning with verifiable rewards then improve the policy while a KL penalty keeps it near what it imitated.

In the terms of the reinforcement-learning section, these stages provide a prior policy π0\pi_0 with good coverage. A sample from it is a sensible action with high probability, so exploration reduces to sampling, and later training reweights actions the prior already proposes. The KL-regularized objective of RLHF makes this exact: its optimum is

π⋆(a∣c)∝π0(a∣c) exp⁡(r(c,a)/β),\pi^\star(a \mid c) \propto \pi_0(a \mid c)\, \exp\big(r(c, a) / \beta\big),

a reweighting of the prior by the exponentiated reward, as derived in the DPO section of the instruction-tuning note. Worked example. Three actions with π0=(0.6,0.3,0.1)\pi_0 = (0.6, 0.3, 0.1), rewards (0,1,0)(0, 1, 0) and β=0.5\beta = 0.5 give the weights 0.60.6, 0.3 e2=2.2170.3\,e^{2} = 2.217 and 0.10.1, so π⋆=(0.206,0.760,0.034)\pi^\star = (0.206, 0.760, 0.034). The second action wins because the prior gave it enough probability to start with. An action to which the prior gives zero probability stays at zero, whatever its reward: the prior decides which behaviours are reachable at all.

The prior is not a grounded policy, though. Huang et al. (2022) asked GPT-3 175B to write step-by-step plans for household tasks in the VirtualHome simulator. The free-form plans read well, but only 7.79 % of them were executable in the simulator, because their steps did not name actions the simulator had. Mapping each generated step to the most similar admissible action, with a better choice of example and step-by-step correction, raised executability to 73.05 % (Codex 12B: from 18.07 % to 78.57 %). The model knew what to do; it did not know which actions existed.

What is still missing#

A language model wrapped in a loop is a policy. Three things separate it from a good agent, and the following notes add them.

Grounding. The actions must be ones the environment accepts, and they must refer to its actual state. The parser of the Code section accepts four strings and rejects everything else. Two remedies keep the model’s knowledge and add the environment’s constraints. One maps or restricts generated text to admissible actions, as Huang et al. did and as tool schemas and constrained decoding do in Tool use and function calling. The other scores each admissible action with the model and multiplies the score by what the environment allows. SayCan (Ahn et al., 2022) chooses a robot’s next skill by maximizing πθ(a∣ct)⋅P(success∣st,a)\pi_\theta(a \mid c_t) \cdot P(\text{success} \mid s_t, a): the language model says what would help, a learned value function says what can succeed from where the robot stands.

Feedback. A plan written in one pass is open loop. The agent improves only if observations of the results come back into the context, as in ReAct and the agent loop, or if outcomes are turned into rewards and used for training, as in Training agents with reinforcement learning. Feedback in the context changes behaviour within one episode and is forgotten after it; feedback in the weights persists.

Memory. The context is the agent’s only state. It is finite, every token in it is read again at every step, and what is dropped from it no longer exists for the model. The Code section keeps the last 12 turns; real agents keep files, notes and retrieval indexes, the subject of Context and memory.

One more ingredient sits inside the policy rather than around it. The model computes each token with a fixed number of layers, so an action that needs several steps of reasoning has to fit inside the forward passes of a few tokens. Letting the model write those steps out is the subject of the next note.

What changed#

a policy learned from scratcha language-model policy
starting pointrandom or uniforma pretrained, instruction-tuned prior
what it conditions onthe state sts_t, or a beliefthe context: the history written as text
action spacea small fixed setany string, read by a parser
how it is changedgradient steps on rewardsthe prompt, without training; or fine-tuning
explorationε\varepsilon-greedy, entropy bonusthe sampling temperature
groundingbuilt in: its actions are the environment’sadded by the program: parser, schemas, admissible actions
memorya state or belief updatethe context window, plus whatever the program stores

Limitations#

  • Likelihood is not value. The prior proposes what a writer would plausibly do next, not what maximizes the performance measure. Text over-represents confident statements and successful outcomes, and the policy inherits both.
  • The agent reads its own actions as evidence. A model trained to imitate experts who knew things it cannot see may treat its own earlier actions as information about the hidden state, and so confirm its own guesses. Ortega et al. (2021) call this an auto-suggestive delusion and argue that actions must be treated as interventions, not observations.
  • Invalid actions and brittle parsing. Every free-text action can fail to parse, and a lenient parser may map a string to an action the model did not mean.
  • Prompt sensitivity. Small changes in wording, in the order of examples or in the model version change the policy, often in ways no one predicted. Every prompt is a parameter that has to be evaluated.
  • The context is expensive memory. It is re-read at every step, and it is bounded.
  • Temperature is a crude knob. It reshapes every token distribution at once: the choice between two actions and the spelling of their arguments.

What you should remember#

  • A language-model agent is a POMDP agent whose policy is π(a∣ct)\pi(a \mid c_t): the probabilities of the generated tokens, summed over the strings that the parser maps to each action, with an invalid remainder.
  • The context is the history written as text. It replaces the belief state, up to the length of the window.
  • The token level, with one token per action and a reward at the end, is the MDP used for training; the turn level is the one the environment sees.
  • The prompt conditions the policy: the system prompt states the task, demonstrations select the kind of behaviour, the chat template separates roles. Instructions and observations condition the same policy.
  • Temperature sharpens or flattens the policy. Low temperature repeats itself; temperature near 1 is for methods that need diverse samples; high temperature mostly produces invalid actions. Temperature 0 is not bitwise deterministic on a shared server.
  • Pretraining is behaviour cloning of human writers and instruction tuning is behaviour cloning of an assistant. Together they give a prior with good coverage, which later reward training can only reweight.
  • Missing: grounding in the actual actions and state, feedback from results, and memory beyond the window.

Code#

The vacuum world of the first note, with its Vacuum class unchanged, driven by a scripted stand-in for a language model: next-token logits over a toy vocabulary of four action words, an end-of-turn token and 1,000 junk tokens, computed by rules from the rendered context. The chat template, sampling with temperature until the end of the turn, the parser and the agent program are written out. With a real model only toy_logits changes, to a forward pass of a transformer over the rendered tokens; the template, the sampling, the parser and the loop stay as they are. Seeds are fixed; exact numbers can differ slightly across platforms and library versions. The script runs in about six seconds.

import re
import numpy as np

# 1. the environment of the first note: two squares A = 0 and B = 1; the agent sees only its own square
class Vacuum:
    def __init__(self, p, move_cost, rng):
        self.p, self.c, self.rng = p, move_cost, rng
        self.loc, self.dirt = 0, [1, 1]
    def percept(self):
        return self.loc, self.dirt[self.loc]
    def step(self, action):
        if action == 'Suck': self.dirt[self.loc] = 0
        elif action in ('Left', 'Right'): self.loc = 0 if action == 'Left' else 1
        score = (2 - sum(self.dirt)) - (self.c if action in ('Left', 'Right') else 0)
        for j in (0, 1):
            if not self.dirt[j] and self.rng.random() < self.p: self.dirt[j] = 1
        return score

# 2. a scripted stand-in for a language model: next-token logits over a toy vocabulary, given the context
ACTIONS = ['Suck', 'Left', 'Right', 'NoOp']
VOCAB = ACTIONS + ['<eot>'] + [f'w{i:03d}' for i in range(1000)]     # 1,000 tokens that make no valid action
EOT, JUNK = 4, slice(5, None)

def steps_since_move(context):
    acts = re.findall(r'<assistant> (\S+)', context)
    k = 0
    for a in reversed(acts):
        if a in ('Left', 'Right'): break
        k += 1
    return k

def toy_logits(context, generated):
    z = np.full(len(VOCAB), -8.0)                  # the long tail: implausible tokens
    if generated:                                   # after one word: end the turn if the word is an action
        z[EOT] = 6.0 if generated[-1] in ACTIONS else 0.0
        return z
    last = context[context.rfind('<user>'):]        # the newest observation
    here = 'A' if 'in square A' in last else 'B'
    if 'is dirty' in last:
        z[:4] = [4.0, 0.5, 0.5, 1.0]                # Suck, Left, Right, NoOp
    else:
        go = 'Right' if here == 'A' else 'Left'
        z[:4] = [1.0, 0.5, 0.5, 1.5]
        z[ACTIONS.index(go)] = 3.0
        if 'wait when the square is clean' in context and steps_since_move(context) < 4:
            z[3] += 2.5                             # the instruction shifts mass to NoOp ...
            z[ACTIONS.index(go)] -= 2.5             # ... away from moving, until four steps have passed
    return z

# 3. the chat template, sampling with temperature until <eot>, and the parser
def render(system, turns):
    return f'<system> {system}\n' + ''.join(f'<user> {o}\n<assistant> {a}\n' for o, a in turns[:-1]) + f'<user> {turns[-1][0]}\n<assistant>'

def softmax(z, tau):
    e = np.exp((z - z.max()) / tau)
    return e / e.sum()

def sample_action(context, tau, rng, max_tokens=3):
    out = []
    for _ in range(max_tokens):
        w = VOCAB[rng.choice(len(VOCAB), p=softmax(toy_logits(context, out), tau))]
        if w == '<eot>': break
        out.append(w)
    return ' '.join(out)

def parse(text):
    return text if text in ACTIONS else None        # anything else is an invalid action

# 4. the language model wrapped as an agent program: percept in, action out, the context as its state
def lm_agent(system, tau, rng, window=12):
    def program(percept, turns):
        loc, dirty = percept
        obs = f'You are in square {"AB"[loc]}. Square {"AB"[loc]} is {"dirty" if dirty else "clean"}.'
        turns = (turns + [(obs, None)])[-window:]                # the context keeps the last 12 turns
        text = sample_action(render(system, turns), tau, rng)
        action = parse(text)
        turns[-1] = (obs, text)
        return (action or 'NoOp'), turns, action is None        # an invalid action does nothing
    return program

def run(program, p=0.05, c=0.5, steps=20_000, seed=0):
    env, state, total, invalid = Vacuum(p, c, np.random.default_rng(seed)), [], 0.0, 0
    for _ in range(steps):
        action, state, bad = program(env.percept(), state)
        total += env.step(action); invalid += bad
    return total / steps, invalid / steps

SYS = 'You control a vacuum cleaner in squares A and B. Reply with one action: Suck, Left, Right or NoOp.'
WAIT = SYS + ' Moving costs energy: wait when the square is clean, and check the other square every few steps.'
for name, system in (('plain', SYS), ('wait', WAIT)):
    for tau in (0.3, 1.0, 2.0):
        score, bad = run(lm_agent(system, tau, np.random.default_rng(1)))
        print(name, tau, round(score, 3), round(bad, 3))
# plain 0.3 1.495 0.0
# plain 1.0 1.57 0.011
# plain 2.0 1.055 0.81
# wait 0.3 1.76 0.0
# wait 1.0 1.704 0.008
# wait 2.0 0.995 0.806
#   (prompt; temperature; points per step at p = 0.05 with moves costing 0.5; share of invalid replies)

# 5. the action distribution at the first token, square A clean, plain prompt, against temperature
ctx = render(SYS, [('You are in square A. Square A is clean.', None)])
for tau in (0.5, 1.0, 2.0):
    q = softmax(toy_logits(ctx, []), tau)
    print(tau, ' '.join(f'{a}={q[i]:.3f}' for i, a in enumerate(ACTIONS)), f'invalid={q[EOT:].sum():.3f}')
# 0.5 Suck=0.017 Left=0.006 Right=0.930 NoOp=0.046 invalid=0.000
# 1.0 Suck=0.093 Left=0.056 Right=0.686 NoOp=0.153 invalid=0.011
# 2.0 Suck=0.059 Left=0.046 Right=0.161 NoOp=0.076 invalid=0.658

# 6. why reinforcement learning from scratch cannot find an action in text
print(f'{50_257 ** 8:.2e}', f'{1 / 50_257 ** 8:.1e}')         # 8-token strings over the GPT-2 vocabulary
# 4.07e+37 2.5e-38

# 7. few-shot examples as evidence about a latent task: two tasks, each example 4 times likelier under task 1
post = [1 / (1 + 4.0 ** -k) for k in range(4)]
print([round(x, 3) for x in post])
# [0.5, 0.8, 0.941, 0.985]

Next#

The policy of this note maps its context to an action in a single pass of a few tokens. For a question whose answer takes several steps of computation, such as a word problem or a chain of facts, that leaves the model a fixed number of layers to do all of the work before the first token of the answer. The next note lets the model write the intermediate steps first: chain-of-thought prompting, why the extra tokens add serial computation, self-consistency as a vote over reasoning paths, and what is known about whether the written reasoning is the reasoning the model actually did.

References#