Module contents
Lesson 30 of 31Advanced 115 min

Learning from environment feedback: reflection, skills and multi-turn RL

Study verbal reinforcement, reusable skills, supervised fine-tuning on successful trajectories, and multi-turn reinforcement learning with turn and token credit. Compare recorded experiments against retries at explicit budgets.

After this lesson you can

  • Implement Reflexion and a skill library and compare them with independent retries under equal budgets.
  • Build a fine-tuning dataset from environment-filtered successful trajectories and fine-tune a small agent with LoRA.
  • Formulate multi-turn reinforcement learning with trajectory reward, turn credit, and a loss mask excluding environment tokens.
  • Train a small model in a multi-turn tool environment using GRPO and analyze its dynamics.
  • Design environment-based rewards from execution, tests, and state and identify how they can be exploited.

Before you start

Three scales of learning

A failed test provides information without anyone writing an ideal answer. You can use it on the next attempt, save it as a skill, or update the model weights. These are different operations: verbal memory changes the context, while supervised fine-tuning and reinforcement learning change the policy. In each case, signal quality depends on the environment and the verifier.

The signal is not necessarily free: running tests, creating environments, selecting tasks, and reviewing the verifier consume resources. An automatic test can produce millions of labels consistent with its own definition while overlooking relevant properties. Its advantage is repeatable cycles; the scientific question is what each result represents.

The verbal reinforcement of Reflexion retains a textual reflection after an attempt and incorporates it into another, without updating weights. Do not attribute improvement to reflection simply because several attempts outperform one: also compare independent retries and repair without reflection, counting the calls and tokens in every step. An incorrect memory can harm the next attempt.

In the MBPP protocol of lesson 14, the reflection variant retains previous reflections and includes them when preparing the next attempt. Every new reflection consumes a call and adds context; the log reconstructs how that memory grows. Four conditions were evaluated on 50 harmless tasks with quantized Qwen2.5-7B-Instruct on GPU: resampling, binary feedback, repair, and reflection. The held-out MBPP tests are public, although they were not shown to the generator during this protocol. The results and traces come from 200 executed conditions; the source collection has SHA-256 9d6432831dca3c7818a63d8666002e065e30c359c99e5b2a609572fdf248f363.

The budget replay follows measured calls in order, counts input and output, and discards the first call that cannot fit in full. If the remaining budget cannot cover even the prompt and one output token, it does not start that call. It selects the first complete candidate that passes the visible test, or the last complete candidate if none passes; with no complete candidate it abstains. This is a counterfactual reconstruction, not a new generation: it assumes each response prefix would remain unchanged under an online limit.

With a common available budget of 1,024 tokens, replay credits Reflexion with 28 of 50 tasks solved and resampling with 27 of 50: a difference of two percentage points, with a paired 95 % bootstrap interval of −4 to +8 points. Mean simulated spending, including interrupted calls, is 887.60 and 627.10 tokens, respectively. The allocation is equal; actual consumption differs. These data establish no conclusive advantage. Although all four conditions used the same prompt and initial seed, only 15 of the 50 tasks had four identical initial texts; the initial held-out test outcome matched in 47. The cause of the differences was not isolated and should not be attributed to a specific mechanism.

InteractiveReflection versus retries

Loading analysis…

Compare four conditions and inspect candidates and memory for the 50 tasks. Token caps use a counterfactual replay that includes the simulated cost of incomplete calls.

A skill library stores procedures an agent can retrieve and reuse. Voyager combines curriculum, library, and verification in its environment. A skill that passes a limited test set can fail beyond it; retain versions, usage conditions, and tests. Retrieving an incorrect procedure can propagate errors, while failing to retrieve one wastes previous work.

Imagine a skill that reads a table and computes a mean. Its contract must specify columns, missing values, and output type; a name and one example that happens to work are insufficient. If a later task uses it as a subroutine, also retain the version and the test that justified acceptance. A curriculum can propose tasks depending on earlier skills, but selecting only solved tasks can halt exploration. In the figure, disabling verification lets a faulty candidate enter the library, and the next one inherits the defect. This is a deliberate rule of the example, not an empirical estimate of Voyager.

The skill environment prepares another comparison using harmless arithmetic operations. A curriculum requests plans for 16 development cases; the builder takes the first verified plan from each family, generalizes its operands, and checks it on development cases. A family without a valid plan remains absent: no skill is fabricated to replace it. On 32 held-out tasks, the evaluator compares up to three independent attempts with up to three receiving a skill retrieved by lexical similarity. Each condition receives 384 output tokens and a total cap of 900 input plus output tokens; unused budget can carry forward to the next attempt. The cost of building the library is recorded separately and amortized. The allocation is common, though actual spending can differ.

The analyzer reconstructs the log and calculates the paired difference. The protocol and tasks fix the model, splits, and budgets. The held-out split is public for reproducibility and must not be used to choose the method. In a CUDA pilot with Qwen2.5-0.5B and eight development tasks, none of the 24 attempts produced a valid plan: 22 were not acceptable JSON, one had invalid structure, and one was truncated. Its trajectories and call log are available. A later diagnosis removed Markdown delimiters from the 22 complete blocks and still found no valid plan. This partial result neither evaluates held-out tasks nor compares both conditions yet; an empty library is a possible outcome, not missing data to fabricate.

In a second syntactic control, the evaluator used the same eight development tasks and retained the verifier and budgets. The grammar requires canonical JSON with fixed key order and no spaces, but permits the three operators, integers, and references without consulting the answer. Again 0/8 tasks were solved: all 24 attempts produced complete JSON, but 22 had an incorrect tool flow and two a structure rejected by the verifier. The trajectories, call log, and comparison retain both pilots. Changing the grammar changes the output distribution; this small sample does not establish a general cause or evaluate test.

Another control acquires skills through deterministic search, without calling the model. It enumerates DSL plans built with visible operands and references; for each family it accepts the first plan passing the verifier on one development case and checks it on three others. The resulting library retains three of four families after 4,942 search queries and 12 validation queries. The missing family illustrates ambiguity: in its first case two operands coincide, so a plan with the wrong operand passes there and fails on other cases. The failed skill was not replaced. The verifier knows the correct flow, making it a strong signal; the result shows generalization within this synthetic environment, not autonomous learning by Qwen. This construction cost remains separate from any later evaluation with or without memory.

The comparison uses the same syntactic mask and allocation in both arms. The adapter checks library provenance and retrieves by Jaccard similarity without a threshold, recording the selected family and score. On development it returns the corresponding family in 12 of 16 cases and another in four; all four mismatches belong to the missing family. On 32 held-out tasks the evaluator made 192 real calls to Qwen2.5-0.5B on CUDA: neither retries nor the library condition solved any task. It retrieved the corresponding family in 24 cases and another in eight. The reproducible analysis, rows, and log preserve templates, scores, and costs. Mean spending was 503.53 tokens without the library and 630.28 with it. The paired bootstrap gives a difference of zero with a degenerate [0, 0] interval because neither arm succeeded; this does not establish general equivalence. The result is limited to this model, verifier, and synthetic families.

InteractiveA library under explicit rules

Task 1 has no prerequisites; each later task requires every earlier skill. Candidates 2 and 5 are faulty by construction; a skill built on a faulty one also fails.

  1. Task 1: correct candidate; solved.
  2. Task 2: faulty candidate; unsolved.
  3. Task 3: a prior skill is missing; unsolved.
  4. Task 4: a prior skill is missing; unsolved.
  5. Task 5: a prior skill is missing; unsolved.

This simulation does not measure model quality or prove verification is always sufficient.

5
Tasks solved1 / 5
Faulty skills stored0
Toggle verification and retrieval in a deterministic curriculum. Faulty candidates follow the example's model; they are not measurements of an agent.

Fine-tuning with selected experiences

Agent trajectory fine-tuning uses examples of actions and observations to train a policy. If only successes are retained, the sample depends on the policy that produced them and the verifier. FireAct and AgentTuning study fine-tuning on agent trajectories. Evaluate by difficulty and on held-out tasks: a filter accepting only easy tasks can leave hard ones unrepresented. Mixing general examples can help investigate regressions but does not guarantee their avoidance.

For binary reward R(τ)∈{0,1}R(\tau)\in\{0,1\}, current policy pθ(τ)p_\theta(\tau), and probability of success J(θ)>0J(\theta)>0, the score identity gives

∇θJ=Eτ∼pθ[R(τ)∇θlog⁡pθ(τ)]=J Eτ∼pθ(⋅∣R=1)[∇θlog⁡pθ(τ)].\nabla_\theta J=\E_{\tau\sim p_\theta}[R(\tau)\nabla_\theta\log p_\theta(\tau)] =J\,\E_{\tau\sim p_\theta(\cdot\mid R=1)}[\nabla_\theta\log p_\theta(\tau)].

Therefore, the log-likelihood ascent gradient on newly sampled successes follows the REINFORCE direction without a baseline in expectation, apart from the positive factor 1/J1/J. Minimizing negative log-likelihood gives the opposite gradient, and gradient descent produces that ascent direction. The identity assumes that the sampling distribution and environment are not differentiated when calculating the supervised step, adequate support, and differentiation under the sum or integral. It does not imply that multiple epochs on old data, length normalization, or samples from another policy retain the same direction.

From the identity to the experiment

The identity is a claim about an expectation under the current policy. Separate successful from failed trajectories: reward is zero for the latter, so only the former remain. The probability mass of that set is JJ, and dividing by it gives the success-conditioned distribution. If J=0J=0, that distribution is undefined and there are no successful examples for this argument. A finite sample can also yield a noisy direction even when the theoretical equality is correct.

In an interactive trajectory, joint probability includes both agent actions and environment transitions. If environment dynamics are fixed and independent of policy parameters, the gradient of their logarithm contributes no action terms; it does include the logarithms of tokens produced by the agent. This separation no longer holds as written if the process generating observations also depends on those parameters. The argument also does not say every action in a successful trajectory was necessary: a sequence can reach the goal despite a useless call, and supervised fine-tuning can learn to reproduce it.

Filtering introduces a particular training distribution. If a teacher nearly always solves short sums but rarely solves long cases, retaining only successes supplies many more examples of the first group. A policy may improve in that region while receiving little signal for the other. Record proposed tasks, acceptance rate by family, and failures excluded from fine-tuning. Keep the test split out of example selection and checkpoint choice; repeatedly changing training after looking at that test turns it into development data.

Data from a teacher different from the trained policy can be useful for supervised fine-tuning, but they are not on-policy samples from that policy. In that case the identity does not directly identify the student’s reinforcement gradient. Multiple epochs on a fixed collection also change weights while the data distribution remains unchanged. Interpret the result by comparing the base model and adapter on the same held-out tasks, with documented template and budget, retaining both improvements and regressions.

Credit by turn and by token

The multi-turn environment provides an addition laboratory with JSON calls and verifiable reward; it rejects wrongly typed arguments and rewards a correct answer only if the agent called the tool with the task operands. The split avoids reusing the same operand pair even in reverse order. The mask code checks serialized prefix consistency before selecting agent turns. These components prepare the experiment; by themselves they are not training or evidence of improved capability.

The collector separates training, validation, and test and saves trajectories from a local teacher. Supervised fine-tuning filters only training successes; the group objective and GRPO loop use a small policy with LoRA and keep observation tokens in context without a direct loss term. The paired evaluator compares base model and adapter on the same held-out tasks. The comparison requires running all three processes and recording their results: code and unit tests do not establish that training improved the policy. A reward checking only addition does not establish general tool use.

The trajectory analyzer counts requests, tokens, and outcomes by split; it accepts a partial collection and states when it is complete. The collector can save an initial block and resume later without changing planned tasks. On rereading, it reconstructs episodes and checks rewards and observations, so a duplicate or altered line does not silently enter fine-tuning. The teacher name and expected hashes in the log must also be compared against files actually loaded by the server.

The collector also writes every received response to a call log before the next turn. If an interruption leaves an episode incomplete and a call must be repeated, the extra spending remains visible even when it is absent from completed episodes. A call interrupted before its response is received or saved may have a cost unknown to the client; the log cannot attribute tokens that were not observed.

The actual teacher collection used quantized Qwen2.5-7B-Instruct on CPU with 512 training tasks, 64 validation tasks, and 64 test tasks. Its SHA-256 is c57e2808bf082a3252b224ae2717fab0a448736b8bef69ce37f5a7bc0efe42b4. The call log and summary make it auditable. It completed 1,280 responses and recorded 134,969 input and output tokens; two calls interrupted before responses arrived have unknown cost. The filter accepted 132 of 512 training trajectories. For example, among pairs with both operands negative it accepted 26 of 133, and among mixed-sign pairs 71 of 269. These are descriptive counts under this strict verifier, not proof of why the teacher fails or an evaluation of the student. Failed responses remain available for examining selection bias.

Those 132 trajectories fine-tuned Qwen2.5-0.5B-Instruct with LoRA for two epochs, 264 updates, and one seed. On 64 held-out sums, greedy evaluation with up to 96 tokens per turn achieved 1/64 successes for the base model and 64/64 for the adapter: 63 tasks changed from failure to success, one was solved by both, and none changed from success to failure. The paired difference was 98.44 percentage points, with a 95 % bootstrap interval from 95.31 to 100 points over these tasks. Test operand pairs never appear in training, even reversed; both arms receive the same first prompt and tool rules, although the second-turn observation depends on each arm’s first response. This is measured improvement on a synthetic family of sums, not a measure of general agent transfer.

The same procedure with Qwen2.5-1.5B-Instruct yielded 0/64 successes for its base and 64/64 for its adapter on the same held-out sums; all 64 paired differences were positive. The [100, 100] point bootstrap interval is degenerate because all observed differences coincide, and does not measure transfer outside this sample. Both model sizes were fine-tuned on the same 132 trajectories; they are not independent replicates from a population of training runs.

The 0.5B adapter, its configuration, and report are available. Explicitly load the base at revision 7ae557604adf67be50417f59c2c2f167def9a775 before applying that adapter. The resumable evaluator saves each episode; its results, log, and audit include all 128 trajectories. For 1.5B, the adapter, configuration, report, evaluator, results, log, and audit are published; its base revision is 989aa7980e4cf806f80c7fef2b1adb7bc71aa306.

Held-out tasks are published for reproducibility: their test label denotes the split applied by the code, not secrecy from someone who downloads the file. Do not use them to select examples or tune parameters if you want to retain a held-out comparison.

If generation reaches the limit before closing a turn, the GRPO loop records a truncated trajectory and assigns zero reward. It keeps the actually generated IDs in the action mask without adding an end token the model never produced. Supervised fine-tuning excludes length-truncated teacher trajectories, and evaluation also counts an unterminated turn as failure even if its text forms valid JSON. This convention treats truncation as task failure under the selected budget; report its frequency and do not confuse it with infrastructure failure.

In multi-turn agent reinforcement learning, a trajectory alternates model actions with environment observations. The policy objective must include tokens actually generated by the agent and avoid treating a tool result as a policy action. Observations remain in context even when their direct loss term is zero. A turn-level critic can distribute credit by state and action; if inaccurate, it also introduces error. ArCHer studies hierarchical multi-turn RL, while RAGEN analyzes difficulties of training interactive agents.

InteractiveWhich tokens receive credit
System: 2 tokensweight 0.0
User: 3 tokensweight 0.0
Agent 1: 4 tokensweight 1.0
Tool: 3 tokensweight 0.0
Agent 2: 5 tokensweight 1.0

The observation remains in context even if its direct loss term is zero. Example weights for the two turns are 1.0 and 1.0.

Credit
Tokens with direct term9
Change the trajectory or turn weights and toggle the mask. Counts and advantages form an illustrative example, not a generated trajectory.

GRPO forms groups of trajectories for the same prompt, centers and scales their rewards, and applies a clipped objective. If every reward is equal, centered advantage is zero: log the fraction of groups without signal. Sequence-level and token-level reductions weight lengths differently. In real training, record mask, generated tokens, truncations, turns, successes, and length changes; growing reward may reflect an exploitable verifier rather than a more useful agent.

In the real experiment, Qwen2.5-0.5B-Instruct was trained with LoRA for 128 groups of four trajectories in the addition environment. The audit reconstructs 512 episodes: 385 successes, 30 truncated, and 67 of 128 groups with equal rewards. Means were 1.95 turns and 36.78 action tokens per episode; these are training statistics, not test statistics. Mean reward rose from 0.266 in the first 16 groups to 0.938 in the last 16, which alone does not establish generalization. Peak PyTorch reserved memory was 5,962,203,136 bytes; it excludes CUDA context and allocations outside PyTorch.

The variant finally run uses FP32 without TF32, as fixed in its protocol. Two earlier BF16 attempts stopped before updating: the first detected the newline the template adds after EOS; the second retained original IDs but detected differences between sampled and recomputed log probabilities. Tolerance was not relaxed. The FP32 loop retains actually emitted IDs, marks EOS as an action, and treats the subsequent delimiter and observations as context. In the 970 completed turns of the run, the newline after EOS was verified to have zero mask; the other 30 turns were truncated without inventing EOS. The trajectories, analyzer, adapter, and configuration are available. To reproduce evaluation, save the adapter and configuration in an adapter folder and the report in its parent.

On the same 64 held-out sums, the base solved 1 and the GRPO adapter solved 64; there were no truncations. The 0.5B SFT adapter also solved all 64: the paired comparison gives zero difference, with a degenerate [0, 0] bootstrap interval due to the observed ceiling. Both base-model runs produced identical full message sequences on all 64 tasks. Both adapters were evaluated in BF16; GRPO was trained in FP32 without TF32. The GRPO results, log, audit, evaluator, and comparator reconstruct the comparison. A single seed per method and one synthetic task do not establish general equivalence.

A multi-turn interaction can be modeled as a partially observable process: the environment has a state the agent does not fully see; each observation updates its history hth_t, and the policy selects an action from that history. An action can be a tool call, and its response forms part of the next observation. If reward is assigned only at the end, all actions in a successful trajectory initially receive the same aggregate signal, even when some were unnecessary or incorrect. A turn-level critic attempts to estimate a decision’s contribution in context; its estimate can also be wrong. ArCHer studies this hierarchical structure, while RAGEN and WebRL examine interactive-agent training under different configurations and tasks.

Comparing trajectory-level and turn-level credit requires fixing the averaging unit. A sequence mean gives long and short responses equal total weight; a token mean gives more weight to the trajectory containing more generated actions. Repeating many epochs over the same episodes changes the policy relative to the one that produced them: probability ratios and clipping limit some changes, but do not automatically turn old data into fresh samples. Save the reference policy, configuration, optimizer state, and seeds to interpret resumed training.

In a group with binary rewards [1, 0, 0, 0], centering subtracts the 0.25 mean and yields [0.75, -0.25, -0.25, -0.25] before scaling. In a group [1, 1, 1, 1], every centered advantage is zero. Dividing by a near-zero standard deviation requires an explicit numerical convention; unstable normalization must not be interpreted as a learning signal. The proportion of homogeneous groups helps distinguish lack of reward variation from an implementation issue, although it does not itself explain the cause.

The downloadable objective uses the population standard deviation within each group. For [1, 0, 0, 0] it is 3/4\sqrt{3}/4, so normalized advantages are [3,−1/3,−1/3,−1/3][\sqrt{3},-1/\sqrt{3},-1/\sqrt{3},-1/\sqrt{3}]. A group of equal rewards receives zero advantages. For each generated token, the probability ratio is calculated and its contribution compared with the clipped ratio; averaging then occurs within each episode first and across episodes second. The regularization term uses the same mask. These details matter because another reduction or normalization can produce a different gradient under the same algorithm name.

For positive advantage, the clipped objective limits the benefit of increasing the ratio too far; for negative advantage, it limits the benefit of reducing it too far. The function takes the minimum of the two contributions before changing sign to minimize loss. Lower minibatch loss does not guarantee greater reward on new tasks. Compare the checkpoint with the base model on held-out data and ensure evaluation uses the same conditions for both.

Zero advantage does not necessarily leave all parameters unchanged: other objective terms, such as regularization, can still contribute gradients. Record each component separately.

Group advantage is relative to the other trajectories for the same question. An absolute reward of one can receive zero advantage if all others also receive one; zero reward can be negative if another group trajectory succeeds. This provides a comparative signal, but does not identify why a sequence succeeded or which part was decisive. Increasing group size may reveal diverse outcomes at increased generation cost, and its effect should be measured including that cost.

In a two-turn environment, a valid action followed by an incorrect final answer and an invalid call followed by a correct final answer can both receive final reward zero if the task requires both steps. This design favors correct tool use but does not distinguish every failure cause. Retaining tool_valid, the observation, and the final answer allows stage-by-stage diagnosis without retrospectively changing the reward used in training. Changing the reward creates a different experimental condition.

The ratio between an action’s probability under the current policy and under the policy that generated the data weights change in an update. Clipping modifies the objective when the ratio leaves the chosen interval; it does not guarantee every sequence or state remains close under every measure. In a long conversation, a small change per token can accumulate in trajectory probability. Record the fraction of terms clipped, the divergence used as regularizer, action length, and mean reward.

Sampling details affect the ratio. If generation modifies the distribution through temperature, truncation, or penalties, recorded probability must correspond to the policy used in the denominator. Comparing probabilities from one transformed distribution with another without correction produces inconsistent ratios. This lesson’s loop fixes its sampling configuration and checks generated against recomputed probabilities before updating. That check detects discrepancies in the cases run; it does not itself prove successful training.

The observation mask removes a direct loss term on text the agent did not generate, but observed context can influence later action probabilities. In an addition call, the tool result is part of the history conditioning the final answer; removing it from the objective does not remove it from the input. If a turn is truncated, retain which tokens were generated and excluded. Otherwise, an apparently reasonable mask can attribute an unproduced delimiter or observation to the agent.

For a causal model, the logit at a position predicts the next token. Input, label, and mask shifting must therefore follow the implementation convention: visually marking the correct response in a string does not prove that the correct logits were multiplied. A small test can assign distinct IDs to user, tool, and assistant, calculate loss, and verify that changing an excluded token adds no direct term. It should also verify that the turn terminator follows the template convention.

A gradient check complements mask inspection. In a synthetic example, change probabilities associated with observations and verify their direct contribution remains zero while a marked action affects the objective. In a real causal network, changing observation content changes context and can alter later action logits; this is expected and consistent with zero direct loss on the observed token. Separating these claims avoids a test that appears to demand that the environment never influence the policy.

Build the mask with the specific tokenizer’s template. Some templates expose an assistant mask; otherwise, establish boundaries compatible with that template and verify them against actual IDs. The assistant-only objective also requires shifting logits and labels correctly for a causal model. The following example only accounts for a teaching sequence.

The fixed Qwen2.5-0.5B-Instruct template used in this module contains no generation blocks: requesting the automatic Transformers mask returned all zeros in a local test. Silently accepting that mask is insufficient. One alternative compares each assistant generation prefix’s IDs with those of the complete dialogue; if the template does not retain exact prefixes, the procedure must fail and be adapted rather than infer positions from characters.

There is a concrete difference between the two fine-tuning runs. The SFT mask selects the assistant’s serialized span: in this template it includes content, EOS, and the newline added by the template after EOS. Checking the 132 examples finds two supervised separators per trajectory for both sizes: 264 per epoch. That newline is not a tool observation, but neither is it a sampled model token. The GRPO mask is reconstructed from actually generated IDs and leaves that separator at zero. Thus the exercise’s prefix function bounds serialized turns in its simplified templates; a sampled policy additionally needs original IDs and an explicit separator test. Published SFT results use the first criterion, including that extra token.

[ ]Trajectory mask and advantagesBrowser
roles = ['sistema', 'usuario', 'agente', 'agente', 'herramienta', 'agente']
advantages = [0.0, 0.0, -0.2, -0.2, 0.0, 0.7]
mask = [int(role == 'agente') for role in roles]
print('máscara:', mask)
print('pesos de pérdida:', [m*a for m,a in zip(mask, advantages)])

The environment reward should measure a state or outcome the agent cannot alter in a way that makes the test cease to represent success. If it can edit tests or their output, “all pass” is an unreliable verifier. Keep tests and evaluator outside the agent’s writable space and measure outcomes on held-out cases. Code execution requires isolation; RLEF and SWE-Gym use executable feedback in their respective protocols.

A verifier can fail both by accepting incorrect solutions and rejecting valid ones. Before using it as reward, test reference implementations, deliberately wrong answers, and edge cases. In this module’s addition environment, requiring a call with the correct operands distinguishes the required flow from a correct final answer without the tool. That choice suits studying the flow, but would penalize a correct mental answer if the declared objective were merely calculating the sum. Reward should match the evaluation objective.

A learning experiment requires a complete budget and log: model and revision, data split, trajectory count, seed, generation configuration, updates, and observed memory and time. The main result is performance on held-out tasks against the baseline, with uncertainty and the conditions kept equal. A training-reward curve is a diagnostic signal; by itself it establishes neither transfer nor safety against an agent finding a verifier shortcut.

The paired comparison applies base model and adapter to the same held-out operand pairs. Beyond mean change, count tasks solved by both, only by the adapter, and only by the base model. An aggregate increase can coexist with regressions on individual cases. Because tasks come from one arithmetic environment, an interval over them does not measure performance on other tool types or open conversations. Broader testing needs other environments and independent criteria.

Choose the checkpoint on validation before inspecting the final test. Selecting the best checkpoint on that test fits the choice to the sample and makes it no longer a held-out evaluation of that choice. Retain the base model and evaluation configuration so the comparison can be repeated.

Exercises

Proof
Prove: For binary reward and positive success probability, the ascent gradient of log likelihood over successful trajectories of the current policy is proportional to the REINFORCE gradient without a baseline.
0
Assume stable support, valid interchange of gradient and expectation, and samples treated as fixed data when updating.

Step 1 of 3. How is the gradient of expected reward written?

Numeric
With independent probability 0.3 per attempt, what is the probability of at least one success in four attempts?
Numeric
The first three independent attempts succeed with probability 0.3; the fourth, conditional on prior failures, succeeds with probability r. Compare success per token: if the method costs 30 % more than four independent attempts with probability 0.3, what minimum r makes the ratio equal?
Code
Implement build_loss_mask(messages, tokenizer) for these simplified templates. apply_chat_template(messages, tokenize=True, add_generation_prompt=bool) returns an ID list or a dictionary with input_ids. For each assistant turn, compare its generation prefix and the complete dialogue through that turn against the entire conversation IDs. Mark IDs in the serialized span after the prefix through the end of the turn, including its terminator. If the prefixes do not match exactly, raise ValueError. Return (ids, mask). For a real template, separately check whether there are separators the model did not generate.
def build_loss_mask(messages, tokenizer):
  pass
Shift+Enter to run
Quiz
What makes a test-based reward exploitable?
Quiz
What complicates credit in a multi-turn trajectory?

Summary

Key idea
Experience can change context or weights. In both cases, protect the verifier, separate environment tokens, and compare against retries under an explicit budget.