Module contents
Lesson 22 of 26Advanced 110 min

Critic-free RL for LLMs: REINFORCE, RLOO and GRPO

Study sequence policy gradients, RLOO, GRPO, normalization and verifiable rewards.

After this lesson you can

  • Derive the sequence-level policy gradient and prove the leave-one-out baseline is unbiased.
  • Implement RLOO and GRPO from scratch, including clipping and the KL term using the k3 estimator.
  • Analyze GRPO biases from length and standard-deviation normalization and apply proposed corrections.
  • Design verifiable rewards for numerical answers, code tests and format, and detect how they can be exploited.
  • Train a 0.5B model with GRPO on verifiable arithmetic within 8 GB and analyze reward, length and entropy.

Before you start

Learning without a value network

A mathematical answer may have a final signal: it matches the verified solution or it does not. PPO can learn a value network to distribute that credit, but the network adds parameters, memory and training decisions. REINFORCE, RLOO and GRPO use baselines or statistics from multiple responses to avoid a learned critic. That does not show a critic contributes little in every task: the tradeoff between cost and variance reduction depends on the model, reward and experiment.

Ahmadian and colleagues studied REINFORCE-style alternatives for RLHF; DeepSeekMath introduced GRPO in its mathematical reasoning setting. In that work, the 7 billion parameter model went from 82.9% to 88.2% on GSM8K and 46.8% to 51.7% on MATH; they used 64 responses per question and a reward model. Later, DeepSeek-R1 studied reinforcement learning for reasoning. Results belong to those models, data and evaluations, and do not prove any small model learns to reason in a few updates.

A complete response as an action

Let xx be a prompt, yy a complete response sampled from πθ(⋅∣x)\pi_\theta(\cdot\mid x) and R(x,y)R(x,y) a reward fixed with respect to θ\theta given x,yx,y. The sequence-level policy gradient, under conditions allowing derivatives and expectations to be interchanged, is

∇θEy[R(x,y)]=Ey[R(x,y)∇θlog⁡πθ(y∣x)].\nabla_\theta\mathbb E_y[R(x,y)] =\mathbb E_y\left[R(x,y)\nabla_\theta\log\pi_\theta(y\mid x)\right].

The identity ∇π=π∇log⁡π\nabla\pi=\pi\nabla\log\pi yields the result. By the chain rule, log⁡π(y∣x)=∑tlog⁡π(yt∣x,y<t)\log\pi(y\mid x)=\sum_t\log\pi(y_t\mid x,y_{<t}): a final reward multiplies all response scores. This does not imply each token contributed equally to success. If reward explicitly depends on θ\theta, the corresponding direct derivative must be added.

A baseline b(x)b(x) independent of the sampled response does not change the expectation because Ey[∇log⁡π(y∣x)]=0\mathbb E_y[\nabla\log\pi(y\mid x)]=0. It can reduce or increase variance depending on its choice. A moving average from previous batches can be treated as fixed conditional on history; a mean including the current sample needs different analysis.

InteractiveBaselines and variance

Gradient estimator by number of successes K in the group.

The dashed line is the true gradient; each circle represents a success count and its size grows with binomial probability. Exact figures enumerate all K values; sampled figures come from 2,000 groups with the specified seed.

Model: a is Bernoulli(p), R = a, and the score with respect to the logit is a − p. The independent baseline is fixed before this group, like a previous moving average, not its current mean. RLOO excludes each own reward. The uncorrected group mean has expectation (G−1)/G times the gradient; RLOO corrects this factor. The deviation is population deviation; when it is zero the normalized estimator is defined as zero. This random division changes the expectation and does not guarantee unbiasedness.

0.30
4
0.30
42
Estimator
True gradient
0.2100
Exact expectation
0.2100
Exact bias
0.0000
Exact variance
0.01575
Mean of 2,000 groups
0.2090
Variance of 2,000 groups
0.01602
Compare bias and dispersion of estimators in an explicit Bernoulli bandit.

This explicit bandit has a Bernoulli action, reward equal to the action and score a − p. Enumeration uses the exact binomial distribution; the 2000 draws use the same seed and generator as the figure. The independent baseline is fixed before the group, and standard deviation is population-based; when zero, normalized advantage is defined as zero.

[ ]Baseline varianceBrowser
"""Comparación exacta y muestreada de estimadores de política en un bandido."""
import math

METHODS = ['none', 'independent', 'rloo', 'group', 'standardized']

def estimate(k, group, p, method, independent):
    if method in ('none', 'independent'):
        b = independent if method == 'independent' else 0.
        return (k*(1-b)*(1-p)+(group-k)*b*p)/group
    centered = k*(group-k)/(group*group)
    if method == 'group': return centered
    if method == 'rloo': return centered*group/(group-1)
    if method != 'standardized': raise ValueError('Método desconocido')
    fraction = k/group
    sd = math.sqrt(fraction*(1-fraction))
    return centered/sd if sd else 0.

def distribution(group, p, method, independent):
    rows = [(k, math.comb(group,k)*p**k*(1-p)**(group-k), estimate(k,group,p,method,independent))
            for k in range(group+1)]
    mean = sum(prob*value for _,prob,value in rows)
    variance = sum(prob*(value-mean)**2 for _,prob,value in rows)
    return {'rows':rows,'mean':mean,'variance':variance,'truth':p*(1-p)}

def mulberry32(seed):
    # Misma aritmética entera de 32 bits que rng(seed) del kit.
    mask = 0xffffffff
    a = seed & mask
    while True:
        a = (a+0x6d2b79f5) & mask
        t = ((a^(a >> 15))*(a | 1)) & mask
        t = (t ^ ((t + (((t^(t >> 7))*(t | 61)) & mask)) & mask)) & mask
        yield ((t^(t >> 14)) & mask)/4294967296

def sample(group, p, method, independent, seed, count=2000):
    generator = mulberry32(seed)
    frequencies = [0]*(group+1)
    for _ in range(count):
        k = sum(next(generator) < p for _ in range(group))
        frequencies[k] += 1
    mean = sum(f*estimate(k,group,p,method,independent) for k,f in enumerate(frequencies))/count
    var = sum(f*(estimate(k,group,p,method,independent)-mean)**2 for k,f in enumerate(frequencies))/count
    return {'frequencies':frequencies,'mean':mean,'variance':var,'count':count}

def advantages(rewards, lengths, max_length=100):
    group = len(rewards)
    if group < 2 or group != len(lengths) or any(not isinstance(n,int) or not 1 <= n <= max_length for n in lengths):
        raise ValueError('Grupo o longitudes inválidos')
    identical = all(r == rewards[0] for r in rewards)
    mean = rewards[0] if identical else sum(rewards)/group
    sd = 0. if identical else math.sqrt(sum((r-mean)**2 for r in rewards)/group)
    rows = []
    for r,length in zip(rewards,lengths):
        center = r-mean
        grpo = center/sd if sd else 0.
        rloo = center*group/(group-1)
        rows.append({'reward':r,'length':length,'grpo':grpo,'drgrpo':center,'rloo':rloo,
                     'grpoToken':grpo/(group*length),'drgrpoToken':center/(group*max_length),'rlooToken':rloo/group})
    return {'mean':mean,'sd':sd,'rows':rows}

group, p, baseline, seed = 4, .3, .3, 42
exact = {method:distribution(group,p,method,baseline) for method in METHODS}
drawn = {method:sample(group,p,method,baseline,seed) for method in METHODS}
truth = p*(1-p)
assert abs(exact['none']['mean']-truth) < 1e-12
assert abs(exact['independent']['mean']-truth) < 1e-12
assert abs(exact['rloo']['mean']-truth) < 1e-12
assert abs(exact['group']['mean']-(group-1)/group*truth) < 1e-12
assert len({tuple(value['frequencies']) for value in drawn.values()}) == 1
table = advantages([1.,0.,0.,0.], [10,25,40,60])
assert abs(table['sd']-math.sqrt(3)/4) < 1e-12
assert abs(table['rows'][0]['grpo']-math.sqrt(3)) < 1e-12
assert abs(table['rows'][1]['grpo']+1/math.sqrt(3)) < 1e-12
assert abs(table['rows'][0]['rloo']-1) < 1e-12
assert abs(table['rows'][1]['rloo']+1/3) < 1e-12
uniform = advantages([.1,.1,.1], [1,2,3])
assert uniform['sd'] == 0 and all(row['grpo'] == 0 for row in uniform['rows'])
print('Gradiente verdadero:',truth)
for method in METHODS:
    a,b = exact[method],drawn[method]
    print(method, 'esperanza exacta:',a['mean'],'varianza exacta:',a['variance'],
          'media muestral:',b['mean'],'varianza muestral:',b['variance'])
print('Frecuencias de K en 2000 grupos, semilla 42:',drawn['none']['frequencies'])
print('Tabla para recompensas [1, 0, 0, 0]:',table)
print('Comprobados RLOO, factor (G−1)/G, normalización poblacional y grupo sin variación.')

RLOO: other responses as the baseline

In REINFORCE leave-one-out, G≥2G\geq2 conditionally independent responses are generated for one prompt from the same frozen policy. For response ii, use the mean reward of the others:

b−i=1G−1∑j≠iRj,g^RLOO=1G∑i=1G(Ri−b−i)∇log⁡π(yi∣x).b_{-i}=\frac{1}{G-1}\sum_{j\ne i}R_j,\qquad \hat g_{\mathrm{RLOO}}=\frac1G\sum_{i=1}^{G}(R_i-b_{-i})\nabla\log\pi(y_i\mid x).

Conditional on the prompt, the other responses do not depend on yiy_i. Therefore the term with b−ib_{-i} has zero expectation and the estimator preserves the expected gradient. This proof requires appropriate conditional independence and support: it does not automatically apply if sampling couples responses or if data from a different policy are reused without correction.

If the full mean Rˉ\bar R is used as baseline, the current sample participates in it. For iid samples without division by standard deviation, the estimator’s expectation becomes (G−1)/G(G-1)/G of the original gradient. Also, Ri−b−i=G(Ri−Rˉ)/(G−1)R_i-b_{-i}=G(R_i-\bar R)/(G-1). The difference is a known factor in that case, not a claim that every group normalization is unbiased.

GRPO: compare responses to the same prompt

Group Relative Policy Optimization uses group rewards to construct relative advantages and then applies a clipped token-level objective. A common convention with population standard deviation is

Rˉ=1G∑iRi,σR=1G∑i(Ri−Rˉ)2,Ai=Ri−RˉσR+ϵ.\bar R=\frac1G\sum_i R_i,\quad \sigma_R=\sqrt{\frac1G\sum_i(R_i-\bar R)^2},\quad A_i=\frac{R_i-\bar R}{\sigma_R+\epsilon}.

The same AiA_i is assigned to valid response tokens if supervision is outcome-based. For ratio ρi,t=πθ(yi,t∣si,t)/πold(yi,t∣si,t)\rho_{i,t}=\pi_\theta(y_{i,t}\mid s_{i,t})/\pi_{\mathrm{old}}(y_{i,t}\mid s_{i,t}), the maximized policy term is min⁡(ρi,tAi,clip⁡(ρi,t,1−δ,1+δ)Ai)\min(\rho_{i,t}A_i,\operatorname{clip}(\rho_{i,t},1-\delta,1+\delta)A_i). The old policy and advantages are frozen while using the batch. Temperature, EOS and masks must match the distribution that generated the responses.

If all rewards are equal, the numerator is zero: define advantage as zero and avoid dividing by zero. Zero-variance groups contribute no policy gradient from that reward, although a KL penalty or another term can still contribute a gradient. Record their fraction and composition; too many simultaneous failures or successes can leave little relative signal without establishing the cause by themselves.

InteractiveGroup advantages and length
ResponserlengthA GRPOA Dr. GRPOA RLOOGRPO weight / tokenDr. GRPO weight / tokenRLOO weight / token
11.0101.73210.75001.00000.04330.00190.2500
20.025−0.5774−0.2500−0.3333−0.0058−0.0006−0.0833
30.040−0.5774−0.2500−0.3333−0.0036−0.0006−0.0833
40.060−0.5774−0.2500−0.3333−0.0024−0.0006−0.0833

With identical rewards the deviation is zero and, by convention, GRPO returns zero advantages. The ratio is not evaluated in that case.

GRPO uses (r−mean)/population deviation; Dr. GRPO uses r−mean; RLOO uses r−mean of the other G−1 responses. Displayed weights are coefficients before score or clipping: A/(G·length) with per-sequence mean in GRPO; A/(G·100) for Dr. GRPO with a fixed 100-token budget; A/G for RLOO with per-sequence sum. The fixed budget changes scale, not relative weight across lengths. A long negative advantage has lower magnitude per token under per-sequence normalization; alone this does not establish a change in generated length.

4
1.0
10
0.0
25
0.0
40
0.0
60
Mean
0.250
Population deviation
0.433
Group without variation
no
Change rewards and lengths to compare advantages and token coefficients.

So you can check the calculations by hand, the figure uses ϵ=0\epsilon=0 when deviation is positive and defines advantages as zero when it is exactly zero. The training lab declares its own ϵ\epsilon; with a small positive deviation that term changes advantages.

What normalization changes

GRPO normalization bias has several distinct sources. If each response is averaged over its TiT_i tokens and responses are then averaged, each token’s coefficient in a response is proportional to Ai/TiA_i/T_i. Two responses with equal advantage and different lengths have different per-token weights; this alone does not determine their total gradient magnitude, because token scores can differ or cancel.

For binary rewards, if a group has kk successes out of GG with 0<k<G0<k<G, population standard deviation is k(G−k)/G\sqrt{k(G-k)}/G. Scaling multiplies all centered advantages in that group by G/k(G−k)G/\sqrt{k(G-k)}. For fixed GG, the factor is larger in groups with one success or one failure than in balanced groups. This is a relative group weight compared with not dividing by standard deviation, not a guarantee that hard prompts always dominate the expected gradient: their frequency and scores matter too.

Liu and colleagues analyze both effects and propose Dr. GRPO, which removes group standard-deviation division and uses constant length normalization in its formulation. DAPO studies, among other decisions, token-level reduction and dynamic sampling. Changing reduction changes the objective and gradient scale; replacing one line is not enough to attribute any improvement solely to length.

KL in the loss and frozen samples

DeepSeekMath uses a KL penalty in the GRPO loss instead of including it in reward used to calculate advantages. For q=πθq=\pi_\theta, p=πrefp=\pi_{\mathrm{ref}} and u=log⁡(q/p)u=\log(q/p), estimator k3=e−u−1+uk_3=e^{-u}-1+u is nonnegative and has expectation DKL(q∥p)D_{\mathrm{KL}}(q\Vert p) when samples come from qq and both distributions have the necessary support. The KL estimators lesson develops those conditions.

Equality of expected values does not automatically resolve the derivative. If you hold samples from πold\pi_{\mathrm{old}} fixed and differentiate only k3k_3 at those points, you do not include the term differentiating the sampling distribution. That penalty can serve as a surrogate objective, but its gradient is generally not the exact gradient of DKL(πθ∥πref)D_{\mathrm{KL}}(\pi_\theta\Vert\pi_{\mathrm{ref}}). Importance ratios and their derivatives require their own justification, especially after several epochs or with filters whose support changes.

The following discrete calculation compares both gradients at one state. The policy is Bernoulli with q(1)=0,8q(1)=0{,}8, the reference is uniform and the parameter is the logit of qq.

[ ]KL and frozen samplesBrowser
import math
q, p = .8, .5
grad_kl = q * (1-q) * math.log(q*(1-p)/(p*(1-q)))
grad_k3_fijo = q-p
print('Gradiente de KL directa:', grad_kl)
print('Gradiente medio de k3 con muestras fijas:', grad_k3_fijo)

Both values refer to the same point, but answer different operations. The lab states which it uses and does not interpret a negative sampled KL or reward change as evidence of general stability.

Rewards that can be checked

Verifiable rewards run a rule on a response: for example, comparing an extracted integer with an independently calculated solution. Verifiable means the rule can be executed, not that it captures everything you want. An expression containing multiple numbers, an incomplete format or accidental match can fool a naive extractor. Define an output grammar, reject ambiguities and test harmless adversarial cases before training.

In coding tasks, passing public tests does not demonstrate general correctness: separate hidden tests, control resources and avoid executing untrusted code without suitable isolation. A format reward can lead to repeating a structure without solving the problem. Report semantic accuracy, format, length and rejected cases separately; do not combine metrics and then present the total as accuracy.

GRPO with a verifiable reward

The problem is generated from integer addition, subtraction and multiplication and split by prompt; commutative reversals are excluded, but absence of other equivalences or prior model contamination is not demonstrated. Reward is one only if the entire response is an <answer> tag containing the correct integer; the parser does not evaluate expressions or execute code. Only the final termination token is removed; any interior special token invalidates the response. The strict rule may also reject correct responses in another format.

Qwen2.5-0.5B-Instruct loads with a pinned revision and LoRA. ORYON_GRPO_VARIANT accepts grpo, dr_grpo or rloo; the first divides by exact population deviation without epsilon and averages tokens per response, with zero advantage when deviation is zero. The second omits that division and uses a fixed denominator; RLOO sums tokens per sequence with a leave-one-out baseline. The mask includes EOS if present and excludes only padding. In this implementation clipping is per token, so its later updates are not automatically the original unbiased RLOO estimator. ORYON_QUICK=1 reduces group, data and steps; ORYON_OFFLINE=1 requires weights already cached. Output is written to ORYON_GRPO_DIR.

The k3 term has expectation equal to forward KL if samples come from the current policy and common support holds. Here it is differentiated in the loss on frozen old-policy samples; that produces a surrogate and does not itself include the derivative of the sampling distribution. Sampled KL and small-group results are estimates, not guarantees. Install PyTorch, Transformers, PEFT, huggingface-hub and NumPy, with CUDA available.

[ ]GRPO with verifiable arithmeticLocal GPU
"""GRPO/RLOO con recompensa aritmética verificable, sin crítico."""
import gc
import hashlib
import json
import math
import os
import random
import re
from collections.abc import Mapping
from pathlib import Path

import numpy as np
import torch
from huggingface_hub import snapshot_download
from peft import LoraConfig, get_peft_model
from torch.nn import functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer

QUICK=os.getenv('ORYON_QUICK')=='1'
OFFLINE=os.getenv('ORYON_OFFLINE')=='1'
MODE=os.getenv('ORYON_GRPO_VARIANT','grpo')
if MODE not in ('grpo','dr_grpo','rloo'): raise ValueError('Variante GRPO desconocida')
OUT=Path(os.getenv('ORYON_GRPO_DIR','./oryon-grpo'))
MODEL='Qwen/Qwen2.5-0.5B-Instruct'
REV='7ae557604adf67be50417f59c2c2f167def9a775'
SEED=2220; DATA_SEED=220022
GROUP=2 if QUICK else 8
MAX_NEW=12 if QUICK else 48
UPDATES=2 if QUICK else 128
EPOCHS=1 if QUICK else 2
N_TRAIN,N_VAL,N_TEST=(8,4,4) if QUICK else (512,64,64)
BETA=.01; CLIP=.2; LR=1e-5
torch.set_num_threads(1)

def sha(text): return hashlib.sha256(text.encode('utf-8')).hexdigest()
def file_hash(path):
    h=hashlib.sha256()
    with Path(path).open('rb') as f:
        for chunk in iter(lambda:f.read(1048576),b''): h.update(chunk)
    return h.hexdigest()
def write_json(path,value): path.write_text(json.dumps(value,ensure_ascii=False,indent=2),encoding='utf-8')
def unpack_ids(value): return value['input_ids'] if isinstance(value,Mapping) else value

def parse_answer(text):
    # Solo un entero dentro de una única etiqueta completa. Nunca se ejecuta texto.
    if not isinstance(text,str) or len(text)>256: return None
    match=re.fullmatch(r'\s*<answer>\s*([+-]?(?:0|[1-9][0-9]{0,7}))\s*</answer>\s*',text,flags=re.ASCII)
    return int(match.group(1)) if match else None

def decode_answer(tok,actions,end):
    if not actions: raise ValueError('No hay tokens generados')
    content=actions[:-1] if actions[-1] in end else actions
    internal_special=any(token in tok.all_special_ids for token in content)
    text=tok.decode(content,skip_special_tokens=False,clean_up_tokenization_spaces=False)
    return text, None if internal_special else parse_answer(text), internal_special

def make_tasks():
    tasks=[]
    for a in range(2,41):
        for b in range(2,21):
            for op in ('+','-','*'):
                if op in ('+','*') and a<b: continue
                answer=a+b if op=='+' else a-b if op=='-' else a*b
                text=f'Calculate {a} {op} {b}. Reply only as <answer>INTEGER</answer>.'
                tasks.append({'id':sha(text),'prompt':text,'answer':answer,'a':a,'b':b,'operation':op})
    random.Random(DATA_SEED).shuffle(tasks)
    total=N_TRAIN+N_VAL+N_TEST
    if total>len(tasks): raise ValueError('Faltan problemas distintos')
    train=tasks[:N_TRAIN]; val=tasks[N_TRAIN:N_TRAIN+N_VAL]; test=tasks[N_TRAIN+N_VAL:total]
    ids=[{x['id'] for x in part} for part in (train,val,test)]
    if any(ids[i]&ids[j] for i in range(3) for j in range(i+1,3)): raise ValueError('Solapamiento exacto de prompts')
    return train,val,test

def group_advantages(rewards,mode):
    rewards=torch.as_tensor(rewards,dtype=torch.float32)
    if rewards.ndim!=1 or rewards.numel()<2 or not torch.isfinite(rewards).all(): raise ValueError('Grupo inválido')
    centered=rewards-rewards.mean()
    if mode=='rloo': return centered*rewards.numel()/(rewards.numel()-1)
    if mode=='dr_grpo': return centered
    if mode=='grpo':
        std=rewards.std(unbiased=False)
        return torch.zeros_like(centered) if float(std)==0 else centered/std
    raise ValueError('Variante desconocida')

def token_objective(new,old,ref,adv,mask,beta,clip,mode,max_new):
    if new.ndim!=2 or new.shape!=old.shape or new.shape!=ref.shape or new.shape!=mask.shape:
        raise ValueError('Formas de tokens incompatibles')
    if adv.ndim!=1 or adv.shape[0]!=new.shape[0] or not torch.isfinite(adv).all(): raise ValueError('Ventajas inválidas')
    if not math.isfinite(beta) or beta<0 or not 0<=clip<1 or max_new<1: raise ValueError('Hiperparámetros inválidos')
    m=mask.to(dtype=new.dtype); lengths=m.sum(-1)
    if bool((lengths<=0).any()) or bool(((m!=0)&(m!=1)).any()): raise ValueError('Máscara inválida')
    logratio=torch.where(m.bool(),new-old,torch.zeros_like(new))
    if not torch.isfinite(logratio[m.bool()]).all(): raise ValueError('Ratio no finito')
    ratio=torch.exp(logratio); delta=torch.where(m.bool(),ref-new,torch.zeros_like(new))
    k3=torch.expm1(delta)-delta
    if not torch.isfinite(ratio[m.bool()]).all() or not torch.isfinite(k3[m.bool()]).all(): raise ValueError('Desbordamiento')
    scalar=adv[:,None]
    policy=-torch.minimum(ratio*scalar,ratio.clamp(1-clip,1+clip)*scalar)
    if mode=='dr_grpo':
        denom=new.shape[0]*max_new
        policy_loss=(policy*m).sum()/denom; kl_loss=(k3*m).sum()/denom
    elif mode=='rloo':
        policy_loss=(policy*m).sum()/new.shape[0]; kl_loss=(k3*m).sum()/new.shape[0]
    elif mode=='grpo':
        policy_loss=((policy*m).sum(-1)/lengths).mean()
        kl_loss=((k3*m).sum(-1)/lengths).mean()
    else: raise ValueError('Variante desconocida')
    return policy_loss+beta*kl_loss,policy_loss,kl_loss

def prompt_ids(tok,text):
    if any(s and s in text for s in tok.all_special_tokens): raise ValueError('Grafía de control en el prompt')
    ids=unpack_ids(tok.apply_chat_template([{'role':'user','content':text}],tokenize=True,add_generation_prompt=True))
    if not ids: raise ValueError('Prompt vacío')
    return ids

def stats(model,prefix,actions,reference=False):
    x=torch.tensor([prefix+actions],dtype=torch.long,device='cuda')
    manager=model.disable_adapter() if reference else None
    if manager is not None: manager.__enter__()
    try:
        logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,len(prefix)-1:-1].float()
        logp=logits.log_softmax(-1); target=torch.tensor(actions,dtype=torch.long,device='cuda')
        selected=logp.gather(1,target[:,None]).squeeze(1)
        entropy=-(logp.exp()*logp).sum(-1)
        return selected,entropy
    finally:
        if manager is not None: manager.__exit__(None,None,None)

def rollout(model,tok,task,seed,greedy=False):
    prefix=prompt_ids(tok,task['prompt']); actions=[]; sampled_logp=[]
    if len(prefix)+MAX_NEW>model.config.max_position_embeddings: raise ValueError('El prompt no cabe en contexto')
    generator=torch.Generator(device='cuda').manual_seed(seed)
    end={tok.convert_tokens_to_ids('<|im_end|>'),tok.convert_tokens_to_ids('<|endoftext|>')}
    model.eval()
    with torch.no_grad():
        for _ in range(MAX_NEW):
            x=torch.tensor([prefix+actions],dtype=torch.long,device='cuda')
            logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,-1].float()
            logp=logits.log_softmax(-1)
            token=int(logp.argmax()) if greedy else int(torch.multinomial(logp.exp(),1,generator=generator))
            actions.append(token); sampled_logp.append(float(logp[token]))
            if token in end: break
        old,entropy=stats(model,prefix,actions)
        ref,_=stats(model,prefix,actions,reference=True)
        if not torch.allclose(old,torch.tensor(sampled_logp,device='cuda'),atol=2e-4,rtol=2e-4):
            raise ValueError('El muestreo y la evaluación no coinciden')
    text,parsed,internal_special=decode_answer(tok,actions,end)
    return {'task_id':task['id'],'prefix':prefix,'actions':actions,'text':text,'parsed':parsed,
            'answer':task['answer'],'reward':float(parsed==task['answer']),
            'internal_special':internal_special,
            'old_logp':old.tolist(),'ref_logp':ref.tolist(),'entropy':entropy.tolist(),
            'ended_with':tok.convert_ids_to_tokens(actions[-1]) if actions[-1] in end else 'límite','seed':seed}

def generate_group(model,tok,task,step):
    group=[]
    for i in range(GROUP):
        seed=(SEED+step*GROUP+i+int(task['id'][:16],16))%(2**63-1)
        group.append(rollout(model,tok,task,seed))
    return group

def padded_objective(model,rows,adv):
    width=max(len(r['actions']) for r in rows)
    if width>MAX_NEW: raise ValueError('Longitud mayor que el horizonte')
    new=[]; old=[]; ref=[]; mask=[]
    for row in rows:
        p,_=stats(model,row['prefix'],row['actions']); n=len(row['actions']); padding=width-n
        new.append(F.pad(p,(0,padding)))
        old.append(F.pad(torch.tensor(row['old_logp'],device='cuda'),(0,padding)))
        ref.append(F.pad(torch.tensor(row['ref_logp'],device='cuda'),(0,padding)))
        mask.append(F.pad(torch.ones(n,device='cuda'),(0,padding)))
    return token_objective(torch.stack(new),torch.stack(old),torch.stack(ref),adv.to('cuda'),torch.stack(mask),
                           BETA,CLIP,MODE,MAX_NEW)

def evaluate(model,tok,tasks):
    rows=[]
    for task in tasks:
        seed=(SEED+1+int(task['id'][:16],16))%(2**63-1)
        rows.append(rollout(model,tok,task,seed,greedy=True))
    return {'count':len(rows),'accuracy':sum(r['reward'] for r in rows)/len(rows),
            'mean_length':sum(len(r['actions']) for r in rows)/len(rows),'rows':rows}

def reference_probe(model,tok,task):
    ids=prompt_ids(tok,task['prompt']); x=torch.tensor([ids],dtype=torch.long,device='cuda')
    with torch.no_grad(),model.disable_adapter():
        return model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,-1].float().cpu()

def load_policy():
    snapshot=Path(snapshot_download(MODEL,revision=REV,local_files_only=OFFLINE,
                                    allow_patterns=['*.safetensors','tokenizer.json','tokenizer_config.json']))
    weights={p.name:file_hash(p) for p in sorted(snapshot.glob('*.safetensors'))}
    if not weights: raise ValueError('Faltan pesos base')
    tokenizer_hashes={name:file_hash(snapshot/name) for name in ('tokenizer.json','tokenizer_config.json')}
    tok=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=OFFLINE)
    base=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,dtype=torch.float32,local_files_only=OFFLINE).to('cuda')
    base.config.use_cache=False
    model=get_peft_model(base,LoraConfig(r=8,lora_alpha=16,lora_dropout=0.,bias='none',task_type='CAUSAL_LM',
                                         target_modules=['q_proj','k_proj','v_proj','o_proj'])).eval()
    named=[(n,p) for n,p in model.named_parameters() if p.requires_grad]
    if not named or any('lora_' not in n for n,_ in named): raise ValueError('Solo LoRA debe entrenarse')
    return base,model,tok,[p for _,p in named],{'weights_sha256':weights,'tokenizer_sha256':tokenizer_hashes}

def main():
    if not torch.cuda.is_available(): raise RuntimeError('Este laboratorio requiere CUDA')
    OUT.mkdir(parents=True,exist_ok=True)
    random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED); torch.cuda.manual_seed_all(SEED)
    train,val,test=make_tasks()
    base,model,tok,params,provenance=load_policy()
    opt=torch.optim.AdamW(params,lr=LR)
    def checkpoint(step):
        path=OUT/f'checkpoint-{step}'; model.save_pretrained(path,safe_serialization=True)
        item={'step':step,'model':MODEL,'revision':REV,'seed':SEED,'variant':MODE,
              'weights_sha256':provenance['weights_sha256'],'tokenizer_sha256':provenance['tokenizer_sha256'],
              'adapter_sha256':file_hash(path/'adapter_model.safetensors'),
              'group_std':'poblacional exacta sin epsilon; ventaja cero si std=0',
              'mask':'todos los tokens generados, incluido EOS; padding excluido',
              'purpose':'inferencia; no incluye estado de optimizador ni reanudación exacta'}
        write_json(path/'manifest.json',item)
        return item
    checkpoints=[checkpoint(0)]; initial=evaluate(model,tok,test); history=[]; rollouts=[]
    reference_before=reference_probe(model,tok,val[0])
    for step in range(UPDATES):
        task=train[step%len(train)]; group=generate_group(model,tok,task,step)
        rewards=[r['reward'] for r in group]
        adv=group_advantages(rewards,MODE)
        for row,value in zip(group,adv.tolist()): row['advantage']=value
        zero_variance=all(r==rewards[0] for r in rewards)
        # Control de que los rollouts guardados pertenecen a la política congelada.
        with torch.no_grad():
            for row in group:
                now,_=stats(model,row['prefix'],row['actions'])
                if not torch.allclose(now,torch.tensor(row['old_logp'],device='cuda'),atol=2e-4,rtol=2e-4):
                    raise ValueError('Log-probs antiguas no reproducen el muestreo')
        loss_value=policy_value=kl_value=None
        for _ in range(EPOCHS):
            opt.zero_grad(set_to_none=True)
            loss,policy_loss,kl_loss=padded_objective(model,group,adv)
            if not torch.isfinite(loss): raise ValueError('Pérdida no finita')
            loss.backward(); torch.nn.utils.clip_grad_norm_(params,1.); opt.step()
            loss_value=float(loss.detach()); policy_value=float(policy_loss.detach()); kl_value=float(kl_loss.detach())
        token_count=sum(len(r['actions']) for r in group)
        sampled_kl=sum(sum(a-b for a,b in zip(r['old_logp'],r['ref_logp'])) for r in group)/token_count
        history.append({'step':step+1,'task_id':task['id'],'accuracy':sum(rewards)/GROUP,
                        'mean_length':token_count/GROUP,'entropy':sum(sum(r['entropy']) for r in group)/token_count,
                        'sampled_log_ratio_per_token':sampled_kl,'zero_variance':zero_variance,
                        'zero_variance_fraction_cumulative':sum(x['zero_variance'] for x in history+[{'zero_variance':zero_variance}])/(step+1),
                        'loss':loss_value,'policy_loss':policy_value,'k3_surrogate':kl_value,
                        'generated_tokens':token_count})
        rollouts.append({'step':step+1,'group':group})
        if (step+1)%(1 if QUICK else 16)==0 or step+1==UPDATES:
            checkpoints.append(checkpoint(step+1))
    final=evaluate(model,tok,test); validation=evaluate(model,tok,val)
    reference_after=reference_probe(model,tok,val[0]); reference_change=float((reference_after-reference_before).abs().max())
    if not torch.allclose(reference_before,reference_after,atol=2e-5,rtol=2e-5): raise ValueError('La referencia cambió')
    report={'model':MODEL,'revision':REV,**provenance,
            'quick':QUICK,'variant':MODE,'seed':SEED,'data_seed':DATA_SEED,
            'task':'operaciones enteras generadas; respuesta solo entre etiquetas',
            'split_ids':{'train':[x['id'] for x in train],'validation':[x['id'] for x in val],'test':[x['id'] for x in test]},
            'config':{'group_size':GROUP,'max_new_tokens':MAX_NEW,'updates':UPDATES,'epochs_per_group':EPOCHS,
                      'beta':BETA,'clip':CLIP,'learning_rate':LR,'temperature':1,'top_k':None,'top_p':None,
                      'std':'poblacional exacta, sin epsilon; grupo sin varianza produce ventaja cero',
                      'mask':'todos los tokens generados, incluido EOS; padding excluido',
                      'grpo_denominator':'media por respuesta y después por grupo',
                      'dr_denominator':'G * horizonte máximo','rloo_denominator':'G, suma por secuencia'},
            'history':history,'checkpoints':checkpoints,'reference_probe_max_logit_change':reference_change,
            'test_before':initial,'test_after':final,'validation_after':validation,
            'limits':'Los resultados de entrenamiento son de los grupos muestreados, no exactitud general. k3 tiene valor esperado KL directa con muestras de la política actual y soporte común; sobre muestras congeladas es un surrogate y su gradiente no incorpora el cambio de distribución. RLOO aquí usa clipping por token: solo su dirección sin recorte y con muestras vigentes conserva el argumento de insesgadez del gradiente por secuencia. Las particiones excluyen prompts idénticos e inversiones conmutativas, pero no otras equivalencias ni contaminación del preentrenamiento.'}
    write_json(OUT/'grpo-report.json',report); write_json(OUT/'grpo-rollouts.json',rollouts)
    print('Variante:',MODE,'test inicial/final:',initial['accuracy'],final['accuracy'],flush=True)
    print('Informe:',OUT/'grpo-report.json',flush=True)
    del loss,policy_loss,kl_loss,opt,model,base; gc.collect(); torch.cuda.empty_cache()

if __name__=='__main__': main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The figure shows a real short test with one seed, two-response groups and two updates per variant. Six groups and their metrics were checked from saved rollouts; they are a functional check, not a performance comparison. The embedded report has SHA-256 9efb3f184fa167d9bed626162b82e8287d4ee5c0c8117bd3438fa6f26ad4a737.

InteractiveVerifiable rewards during fine-tuning

Preparing the training report.

Compare metrics recorded in the lab's short test.

The next lab compares RLOO, GRPO and Dr. GRPO with Qwen2.5-0.5B-Instruct and explicitly generated integer operations. The same seed fixes initial weights, tasks and sampling streams in each branch; as policies diverge, responses and lengths can change. The budget equalizes groups, responses and updates, not tokens or FLOPs. Splits separate identical prompts and commutative variants, but do not guarantee absence of equivalences or pretraining contamination.

The preliminary check calls TRL 1.17.1 GRPOTrainer._compute_loss with identical log probabilities and masks and compares loss and gradient. Advantages are supplied directly: the test does not compare how TRL calculates deviation; this lab uses exact population deviation without epsilon and produces zero advantages for constant groups. This is a local test of the internal function, not a run of the complete trainer. RLOO sums per sequence and is checked against rescaled dr_grpo; clipping here is per token and does not necessarily match a sequence-ratio variant. Reward requires an integer answer inside tags; generated code is not executed. Mean k3 on frozen rollouts is a surrogate, not exact KL or its exact gradient under the current policy. Curves record training groups; the report separately retains greedy evaluation on held-out test.

Memory and generation budget

On an 8 GB GPU, policy weights, adapters and their optimizer, backward activations and generation tokens and caches compete for memory. Disabling the adapter permits querying the frozen reference without keeping a second independent base copy, provided that reference is precisely the unadapted base. If a group does not fit, generate responses in batches and retain needed rewards and log probabilities until the whole group is available; normalizing each batch separately would change the estimator. Reducing horizon, batch or precision also changes cost and, depending on the case, the experiment: record those changes.

A separate inference engine can amortize generation when many rollouts share a policy and enough work justifies startup, synchronization and memory costs. It must update to the correct checkpoint and declare which policy produced each sample; serving another copy on the same small GPU can backfire. Measure generation and training separately on your machine: there is no universal group-size threshold above which a separate engine is better.

Install PyTorch, transformers, PEFT, datasets and trl==1.17.1 compatible with your CUDA. Use ORYON_QUICK=1 for two groups per variant and one seed; without it, eight responses per group, 128 groups and three seeds per variant are used. Measure RAM and VRAM before running. The program writes compare-report.json and compare-rollouts.json under ORYON_COMPARE_DIR; figures only exist after a real run. The short experiment may produce no positive rewards and does not establish a general trend.

Primary references: DeepSeekMath, RLOO, Dr. GRPO and GRPOTrainer code.

[ ]Compare RLOO, GRPO and Dr. GRPOLocal GPU
"""GRPO/RLOO con recompensa aritmética verificable, sin crítico."""
import gc
import hashlib
import json
import math
import os
import random
import re
from collections.abc import Mapping
from pathlib import Path

import numpy as np
import torch
from huggingface_hub import snapshot_download
from peft import LoraConfig, get_peft_model
from torch.nn import functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer

QUICK=os.getenv('ORYON_QUICK')=='1'
OFFLINE=os.getenv('ORYON_OFFLINE')=='1'
MODE=os.getenv('ORYON_GRPO_VARIANT','grpo')
if MODE not in ('grpo','dr_grpo','rloo'): raise ValueError('Variante GRPO desconocida')
OUT=Path(os.getenv('ORYON_GRPO_DIR','./oryon-grpo'))
MODEL='Qwen/Qwen2.5-0.5B-Instruct'
REV='7ae557604adf67be50417f59c2c2f167def9a775'
SEED=2220; DATA_SEED=220022
GROUP=2 if QUICK else 8
MAX_NEW=12 if QUICK else 48
UPDATES=2 if QUICK else 128
EPOCHS=1 if QUICK else 2
N_TRAIN,N_VAL,N_TEST=(8,4,4) if QUICK else (512,64,64)
BETA=.01; CLIP=.2; LR=1e-5
torch.set_num_threads(1)

def sha(text): return hashlib.sha256(text.encode('utf-8')).hexdigest()
def file_hash(path):
    h=hashlib.sha256()
    with Path(path).open('rb') as f:
        for chunk in iter(lambda:f.read(1048576),b''): h.update(chunk)
    return h.hexdigest()
def write_json(path,value): path.write_text(json.dumps(value,ensure_ascii=False,indent=2),encoding='utf-8')
def unpack_ids(value): return value['input_ids'] if isinstance(value,Mapping) else value

def parse_answer(text):
    # Solo un entero dentro de una única etiqueta completa. Nunca se ejecuta texto.
    if not isinstance(text,str) or len(text)>256: return None
    match=re.fullmatch(r'\s*<answer>\s*([+-]?(?:0|[1-9][0-9]{0,7}))\s*</answer>\s*',text,flags=re.ASCII)
    return int(match.group(1)) if match else None

def decode_answer(tok,actions,end):
    if not actions: raise ValueError('No hay tokens generados')
    content=actions[:-1] if actions[-1] in end else actions
    internal_special=any(token in tok.all_special_ids for token in content)
    text=tok.decode(content,skip_special_tokens=False,clean_up_tokenization_spaces=False)
    return text, None if internal_special else parse_answer(text), internal_special

def make_tasks():
    tasks=[]
    for a in range(2,41):
        for b in range(2,21):
            for op in ('+','-','*'):
                if op in ('+','*') and a<b: continue
                answer=a+b if op=='+' else a-b if op=='-' else a*b
                text=f'Calculate {a} {op} {b}. Reply only as <answer>INTEGER</answer>.'
                tasks.append({'id':sha(text),'prompt':text,'answer':answer,'a':a,'b':b,'operation':op})
    random.Random(DATA_SEED).shuffle(tasks)
    total=N_TRAIN+N_VAL+N_TEST
    if total>len(tasks): raise ValueError('Faltan problemas distintos')
    train=tasks[:N_TRAIN]; val=tasks[N_TRAIN:N_TRAIN+N_VAL]; test=tasks[N_TRAIN+N_VAL:total]
    ids=[{x['id'] for x in part} for part in (train,val,test)]
    if any(ids[i]&ids[j] for i in range(3) for j in range(i+1,3)): raise ValueError('Solapamiento exacto de prompts')
    return train,val,test

def group_advantages(rewards,mode):
    rewards=torch.as_tensor(rewards,dtype=torch.float32)
    if rewards.ndim!=1 or rewards.numel()<2 or not torch.isfinite(rewards).all(): raise ValueError('Grupo inválido')
    centered=rewards-rewards.mean()
    if mode=='rloo': return centered*rewards.numel()/(rewards.numel()-1)
    if mode=='dr_grpo': return centered
    if mode=='grpo':
        std=rewards.std(unbiased=False)
        return torch.zeros_like(centered) if float(std)==0 else centered/std
    raise ValueError('Variante desconocida')

def token_objective(new,old,ref,adv,mask,beta,clip,mode,max_new):
    if new.ndim!=2 or new.shape!=old.shape or new.shape!=ref.shape or new.shape!=mask.shape:
        raise ValueError('Formas de tokens incompatibles')
    if adv.ndim!=1 or adv.shape[0]!=new.shape[0] or not torch.isfinite(adv).all(): raise ValueError('Ventajas inválidas')
    if not math.isfinite(beta) or beta<0 or not 0<=clip<1 or max_new<1: raise ValueError('Hiperparámetros inválidos')
    m=mask.to(dtype=new.dtype); lengths=m.sum(-1)
    if bool((lengths<=0).any()) or bool(((m!=0)&(m!=1)).any()): raise ValueError('Máscara inválida')
    logratio=torch.where(m.bool(),new-old,torch.zeros_like(new))
    if not torch.isfinite(logratio[m.bool()]).all(): raise ValueError('Ratio no finito')
    ratio=torch.exp(logratio); delta=torch.where(m.bool(),ref-new,torch.zeros_like(new))
    k3=torch.expm1(delta)-delta
    if not torch.isfinite(ratio[m.bool()]).all() or not torch.isfinite(k3[m.bool()]).all(): raise ValueError('Desbordamiento')
    scalar=adv[:,None]
    policy=-torch.minimum(ratio*scalar,ratio.clamp(1-clip,1+clip)*scalar)
    if mode=='dr_grpo':
        denom=new.shape[0]*max_new
        policy_loss=(policy*m).sum()/denom; kl_loss=(k3*m).sum()/denom
    elif mode=='rloo':
        policy_loss=(policy*m).sum()/new.shape[0]; kl_loss=(k3*m).sum()/new.shape[0]
    elif mode=='grpo':
        policy_loss=((policy*m).sum(-1)/lengths).mean()
        kl_loss=((k3*m).sum(-1)/lengths).mean()
    else: raise ValueError('Variante desconocida')
    return policy_loss+beta*kl_loss,policy_loss,kl_loss

def prompt_ids(tok,text):
    if any(s and s in text for s in tok.all_special_tokens): raise ValueError('Grafía de control en el prompt')
    ids=unpack_ids(tok.apply_chat_template([{'role':'user','content':text}],tokenize=True,add_generation_prompt=True))
    if not ids: raise ValueError('Prompt vacío')
    return ids

def stats(model,prefix,actions,reference=False):
    x=torch.tensor([prefix+actions],dtype=torch.long,device='cuda')
    manager=model.disable_adapter() if reference else None
    if manager is not None: manager.__enter__()
    try:
        logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,len(prefix)-1:-1].float()
        logp=logits.log_softmax(-1); target=torch.tensor(actions,dtype=torch.long,device='cuda')
        selected=logp.gather(1,target[:,None]).squeeze(1)
        entropy=-(logp.exp()*logp).sum(-1)
        return selected,entropy
    finally:
        if manager is not None: manager.__exit__(None,None,None)

def rollout(model,tok,task,seed,greedy=False):
    prefix=prompt_ids(tok,task['prompt']); actions=[]; sampled_logp=[]
    if len(prefix)+MAX_NEW>model.config.max_position_embeddings: raise ValueError('El prompt no cabe en contexto')
    generator=torch.Generator(device='cuda').manual_seed(seed)
    end={tok.convert_tokens_to_ids('<|im_end|>'),tok.convert_tokens_to_ids('<|endoftext|>')}
    model.eval()
    with torch.no_grad():
        for _ in range(MAX_NEW):
            x=torch.tensor([prefix+actions],dtype=torch.long,device='cuda')
            logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,-1].float()
            logp=logits.log_softmax(-1)
            token=int(logp.argmax()) if greedy else int(torch.multinomial(logp.exp(),1,generator=generator))
            actions.append(token); sampled_logp.append(float(logp[token]))
            if token in end: break
        old,entropy=stats(model,prefix,actions)
        ref,_=stats(model,prefix,actions,reference=True)
        if not torch.allclose(old,torch.tensor(sampled_logp,device='cuda'),atol=2e-4,rtol=2e-4):
            raise ValueError('El muestreo y la evaluación no coinciden')
    text,parsed,internal_special=decode_answer(tok,actions,end)
    return {'task_id':task['id'],'prefix':prefix,'actions':actions,'text':text,'parsed':parsed,
            'answer':task['answer'],'reward':float(parsed==task['answer']),
            'internal_special':internal_special,
            'old_logp':old.tolist(),'ref_logp':ref.tolist(),'entropy':entropy.tolist(),
            'ended_with':tok.convert_ids_to_tokens(actions[-1]) if actions[-1] in end else 'límite','seed':seed}

def generate_group(model,tok,task,step):
    group=[]
    for i in range(GROUP):
        seed=(SEED+step*GROUP+i+int(task['id'][:16],16))%(2**63-1)
        group.append(rollout(model,tok,task,seed))
    return group

def padded_objective(model,rows,adv):
    width=max(len(r['actions']) for r in rows)
    if width>MAX_NEW: raise ValueError('Longitud mayor que el horizonte')
    new=[]; old=[]; ref=[]; mask=[]
    for row in rows:
        p,_=stats(model,row['prefix'],row['actions']); n=len(row['actions']); padding=width-n
        new.append(F.pad(p,(0,padding)))
        old.append(F.pad(torch.tensor(row['old_logp'],device='cuda'),(0,padding)))
        ref.append(F.pad(torch.tensor(row['ref_logp'],device='cuda'),(0,padding)))
        mask.append(F.pad(torch.ones(n,device='cuda'),(0,padding)))
    return token_objective(torch.stack(new),torch.stack(old),torch.stack(ref),adv.to('cuda'),torch.stack(mask),
                           BETA,CLIP,MODE,MAX_NEW)

def evaluate(model,tok,tasks):
    rows=[]
    for task in tasks:
        seed=(SEED+1+int(task['id'][:16],16))%(2**63-1)
        rows.append(rollout(model,tok,task,seed,greedy=True))
    return {'count':len(rows),'accuracy':sum(r['reward'] for r in rows)/len(rows),
            'mean_length':sum(len(r['actions']) for r in rows)/len(rows),'rows':rows}

def reference_probe(model,tok,task):
    ids=prompt_ids(tok,task['prompt']); x=torch.tensor([ids],dtype=torch.long,device='cuda')
    with torch.no_grad(),model.disable_adapter():
        return model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,-1].float().cpu()

def load_policy():
    snapshot=Path(snapshot_download(MODEL,revision=REV,local_files_only=OFFLINE,
                                    allow_patterns=['*.safetensors','tokenizer.json','tokenizer_config.json']))
    weights={p.name:file_hash(p) for p in sorted(snapshot.glob('*.safetensors'))}
    if not weights: raise ValueError('Faltan pesos base')
    tokenizer_hashes={name:file_hash(snapshot/name) for name in ('tokenizer.json','tokenizer_config.json')}
    tok=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=OFFLINE)
    base=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,dtype=torch.float32,local_files_only=OFFLINE).to('cuda')
    base.config.use_cache=False
    model=get_peft_model(base,LoraConfig(r=8,lora_alpha=16,lora_dropout=0.,bias='none',task_type='CAUSAL_LM',
                                         target_modules=['q_proj','k_proj','v_proj','o_proj'])).eval()
    named=[(n,p) for n,p in model.named_parameters() if p.requires_grad]
    if not named or any('lora_' not in n for n,_ in named): raise ValueError('Solo LoRA debe entrenarse')
    return base,model,tok,[p for _,p in named],{'weights_sha256':weights,'tokenizer_sha256':tokenizer_hashes}

def verify_trl():
    """Compara la llamada real al trainer con tensores y máscaras idénticos en CPU."""
    from collections import defaultdict
    from types import SimpleNamespace
    import trl
    from trl import GRPOTrainer
    if trl.__version__!='1.17.1': raise RuntimeError('El contraste requiere TRL 1.17.1; otras versiones pueden cambiar la API interna')
    mask=torch.tensor([[1.,1.,1.,0.],[1.,1.,0.,0.],[1.,1.,1.,1.]],dtype=torch.float64)
    old=torch.tensor([[-1.,-1.2,-.8,0.],[-.9,-1.1,0.,0.],[-1.3,-1.,-.7,-1.1]],dtype=torch.float64)
    ref=old+torch.tensor([[.2,-.1,.05,0.],[.1,.15,0.,0.],[-.2,.1,.05,.2]],dtype=torch.float64)
    start=old+torch.tensor([[.4,-.35,.1,0.],[-.3,.25,0.,0.],[.12,-.15,.3,-.4]],dtype=torch.float64)
    advantages=torch.tensor([.8,-.6,.15],dtype=torch.float64)
    result={}
    for mode in ('grpo','dr_grpo','rloo'):
        a=start.clone().requires_grad_(True)
        own=token_objective(a,old,ref,advantages,mask,.1,.2,mode,4)[0]
        grad_own=torch.autograd.grad(own,a)[0]
        b=start.clone().requires_grad_(True)
        accel=SimpleNamespace(reduce=lambda x,**kw:x,gather=lambda x:x)
        helper=SimpleNamespace(model=SimpleNamespace(training=False),aux_loss_enabled=False,top_entropy_quantile=1.,
            off_policy_mask_threshold=None,importance_sampling_level='token',beta=.1,epsilon_low=.2,epsilon_high=.2,
            args=SimpleNamespace(use_bias_correction_kl=False,delta=None),use_vllm=False,
            vllm_importance_sampling_correction=False,loss_type='grpo' if mode=='grpo' else 'dr_grpo',
            max_completion_length=4,_entropy_bonus_enabled=False,accelerator=accel,
            _metrics={'eval':defaultdict(list),'train':defaultdict(list)},
            _get_per_token_logps_and_entropies=lambda *args,**kwargs:(b,torch.zeros_like(b),None))
        inputs={'prompt_ids':torch.zeros((3,1),dtype=torch.long),'prompt_mask':torch.ones((3,1)),
                'completion_ids':torch.zeros((3,4),dtype=torch.long),'completion_mask':mask,
                'advantages':advantages,'old_per_token_logps':old,'ref_per_token_logps':ref}
        trl_loss=GRPOTrainer._compute_loss(helper,helper.model,inputs)
        # RLOO suma por secuencia; TRL dr_grpo divide además por el horizonte fijo.
        if mode=='rloo': trl_loss=trl_loss*4
        grad_trl=torch.autograd.grad(trl_loss,b)[0]
        ld=float(abs(own.detach()-trl_loss.detach())); gd=float((grad_own-grad_trl).abs().max())
        if ld>1e-8 or gd>1e-8: raise ValueError(f'Discrepancia TRL en {mode}: pérdida {ld}, gradiente {gd}')
        result[mode]={'loss_difference':ld,'max_gradient_difference':gd}
    return {'trl_version':trl.__version__,'comparison':result,'mask':mask.tolist(),
            'protocol':'GRPOTrainer._compute_loss con log-probabilidades sintéticas idénticas; RLOO usa dr_grpo escalado por horizonte. Las ventajas se inyectan: no se coteja el cálculo de desviación de TRL. No es una ejecución del entrenador completo.'}

def compare_main():
    global MODE,SEED
    if not torch.cuda.is_available(): raise RuntimeError('La comparación necesita CUDA')
    proof=verify_trl()
    output=Path(os.getenv('ORYON_COMPARE_DIR','./oryon-grpo-comparison'))
    output.mkdir(parents=True,exist_ok=True)
    seeds=[2220] if QUICK else [2220,2221,2222]
    train,val,test=make_tasks(); runs=[]; all_rollouts=[]
    for seed in seeds:
        for variant in ('rloo','grpo','dr_grpo'):
            MODE=variant; SEED=seed
            random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
            base,model,tok,params,provenance=load_policy()
            opt=torch.optim.AdamW(params,lr=LR)
            reference_before=reference_probe(model,tok,test[0])
            before=evaluate(model,tok,test); history=[]; generated_total=0; train_input_total=0; generation_input_total=0
            for step in range(UPDATES):
                task=train[step%len(train)]; group=generate_group(model,tok,task,step)
                rewards=[r['reward'] for r in group]; adv=group_advantages(rewards,variant)
                with torch.no_grad():
                    for row in group:
                        current,_=stats(model,row['prefix'],row['actions'])
                        if not torch.allclose(current,torch.tensor(row['old_logp'],device='cuda'),atol=2e-4,rtol=2e-4):
                            raise ValueError('La política antigua no reproduce el rollout')
                for epoch in range(EPOCHS):
                    opt.zero_grad(set_to_none=True); loss,policy_loss,kl_loss=padded_objective(model,group,adv)
                    if not torch.isfinite(loss): raise ValueError('Pérdida no finita')
                    loss.backward(); torch.nn.utils.clip_grad_norm_(params,1.); opt.step()
                    train_input_total+=sum(len(r['prefix'])+len(r['actions']) for r in group)
                n=sum(len(r['actions']) for r in group); generated_total+=n
                generation_input_total+=sum(sum(len(r['prefix'])+i for i in range(len(r['actions']))) for r in group)
                with torch.no_grad():
                    values=[]
                    for row in group:
                        new,_=stats(model,row['prefix'],row['actions']); ref=torch.tensor(row['ref_logp'],device='cuda')
                        delta=ref-new; values.extend((torch.expm1(delta)-delta).tolist())
                if not all(math.isfinite(x) for x in values): raise ValueError('k3 no finito')
                zero=all(x==rewards[0] for x in rewards)
                history.append({'step':(step+1)*EPOCHS,'accuracy':sum(rewards)/GROUP,'mean_length':n/GROUP,
                    'entropy':sum(sum(r['entropy']) for r in group)/n,'kl_k3':sum(values)/n,
                    'zero_variance':zero,'zero_variance_fraction':sum(x['zero_variance'] for x in history+[{'zero_variance':zero}])/(step+1),
                    'generated_tokens':generated_total,'training_forward_input_tokens':train_input_total,
                    'autoregressive_input_tokens':generation_input_total,'loss':float(loss.detach()),'task_id':task['id']})
                all_rollouts.append({'method':variant,'seed':seed,'step':step+1,'group':group})
            reference_after=reference_probe(model,tok,test[0])
            reference_difference=float((reference_before-reference_after).abs().max())
            if not torch.allclose(reference_before,reference_after,atol=2e-5,rtol=2e-5):
                raise ValueError('La referencia congelada ha cambiado')
            after=evaluate(model,tok,test); validation=evaluate(model,tok,val)
            runs.append({'method':variant,'seed':seed,'history':history,'test_before':before,'test_after':after,
                         'validation_after':validation,'provenance':provenance,
                         'reference_max_logit_difference':reference_difference,
                         'budget':{'groups':UPDATES,'responses':UPDATES*GROUP,'optimizer_updates':UPDATES*EPOCHS,
                           'generated_tokens':generated_total,'training_forward_input_tokens':train_input_total,
                           'autoregressive_input_tokens':generation_input_total}})
            del loss,policy_loss,kl_loss,opt,model,base,params; gc.collect(); torch.cuda.empty_cache()
    report={'model':MODEL,'revision':REV,'quick':QUICK,'group_size':GROUP,'max_new_tokens':MAX_NEW,
            'seeds':seeds,'data_seed':DATA_SEED,'runs':runs,'trl_check':proof,
            'split_ids':{'train':[r['id'] for r in train],'validation':[r['id'] for r in val],'test':[r['id'] for r in test]},
            'protocol':{'beta':BETA,'clip':CLIP,'epochs_per_group':EPOCHS,'temperature':1,'top_k':None,'top_p':None,
              'task':'Aritmética generada, respuesta exacta en etiquetas; sin ejecutar código',
              'normalization':'RLOO suma por secuencia y divide por G; GRPO media por longitud y desviación poblacional; Dr. GRPO suma y divide por G*horizonte',
              'note':'Recorte por token en las tres variantes. RLOO puede diferir de una formulación con razón de secuencia. Los tokens no son FLOPs; no incluyen todos los forwards de evaluación y referencia.'},
            'limits':'Prompts separados solo por igualdad exacta y conmutatividad; pueden compartir operaciones o estar en preentrenamiento. Muestras de entrenamiento no son test; k3 sobre muestras antiguas es surrogate. Diferencias no demuestran causalidad o superioridad general.'}
    write_json(output/'compare-report.json',report); write_json(output/'compare-rollouts.json',all_rollouts)
    print('Informe:',output/'compare-report.json','TRL:',json.dumps(proof,ensure_ascii=False),flush=True)

if __name__=='__main__': compare_main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

To compare RLOO, GRPO and Dr. GRPO, fix prompts, initial policy, verifier rule, number of generations and token budget; also declare seeds and truncation. An entropy decline alongside stagnation can motivate investigating exploration or diversity, but correlation alone does not identify the cause. Training and validation must use separate problems, and the final test must not guide checkpoint or hyperparameter selection.

Exercises

[ ]Group advantagesBrowser
import math
r = [1., 0., 0., 0.]
mean = sum(r)/len(r)
std = math.sqrt(sum((x-mean)**2 for x in r)/len(r))
print('Media y desviación poblacional:', mean, std)
print('GRPO:', [(x-mean)/std for x in r])
print('RLOO:', [x-(sum(r)-x)/(len(r)-1) for x in r])
NumericOne success in four
A group has rewards 1, 0, 0 and 0. With population standard deviation and ε = 0, what is the GRPO advantage of the success?
ProofThe other samples' baseline
Prove: Prove RLOO is unbiased for a fixed prompt.
0
There are G ≥ 2 iid responses from a policy with sufficient support and regularity; reward is fixed given prompt and response.

Step 1 of 3. What does sample i's baseline depend on?

ProofWhat deviation weights
Prove: Analyze scaling of a binary-reward group.
0
A group of size G has k successes, with 0 < k < G; use population deviation without epsilon.

Step 1 of 3. What is the group mean?

QuizLength without improvement
Average length grows but accuracy does not improve. Which diagnosis is best supported?
CodeGroup advantages and clipped loss
Implement grpo_advantages(rewards, group_size, scale_by_std, eps=1e-8) and clipped_loss(logp, old_logp, advantages, mask, clip). rewards is a finite nonempty real vector whose length is a multiple of group_size, an integer at least 2. Within each group subtract the mean; if scale_by_std is True, divide by population deviation plus eps. If all group rewards are equal, its advantages are exactly zero. Require boolean scale_by_std and finite positive scalar eps. In clipped_loss, logp, old_logp and mask have shape (B,T), with positive B and T; advantages has shape (B,). The mask is boolean or zeros and ones, with at least one valid token per sequence. Ignore padding, even with non-finite log-probs; active values and advantages must be finite. For each token use ρ = exp(logp−old_logp) and loss −min(ρA, clip(ρ,1−clip,1+clip)A), then average valid tokens per sequence and finally sequences. Require finite scalar clip in [0,1). Do not modify inputs; reject shapes, parameters or results outside representable numeric range with ValueError.
import numpy as np

def grpo_advantages(rewards, group_size, scale_by_std, eps=1e-8):
  pass

def clipped_loss(logp, old_logp, advantages, mask, clip):
  pass
Shift+Enter to run
Key idea

A baseline reduces or rescales noise according to how it is constructed. In GRPO, grouping, normalization, mask, support and verifier determine which gradient is computed and what you can conclude from it.