Celestis-RL / src /celestis_rl /hf_reference.py
PureOne's picture
Release Celestis-RL v2.0.0: audited research reference
f95cbd4 verified
Raw History Blame Contribute Delete
5.31 kB
"""Architecture-neutral, dense-output causal-LM adapter.
No transformers import is needed for these protocol functions. A compatible
model must return `.logits` for `input_ids=..., use_cache=False`. This path is
single-process, untruncated categorical sampling, with explicit finite-horizon
termination. It is intentionally simple, not a distributed training engine.
"""
from dataclasses import dataclass
import hashlib
import math
import torch
from .estimators import canonical_q, draw_correction, exact_correction
from .losses import token_loss
from .stratified import stratified_correction
@dataclass
class LanguageRollout:
prompt: torch.Tensor # [P], CPU int64
actions: torch.Tensor # [T], CPU int64
q: torch.Tensor # [T,V], CPU float64, actual sampler
reward: float
sampler_version: str
termination: str # eos or declared time_limit
temperature: float
digest: str
def compute_digest(self):
import json
h=hashlib.sha256(json.dumps({"reward":self.reward,"sampler_version":self.sampler_version,
"termination":self.termination,"temperature":self.temperature},sort_keys=True,allow_nan=False).encode())
for x in (self.prompt,self.actions,self.q):
a=x.detach().cpu().contiguous().numpy()
h.update(str((a.dtype.str,a.shape)).encode());h.update(a.tobytes())
return h.hexdigest()
def verify(self):
if not self.sampler_version or self.termination not in ("eos","time_limit"):
raise ValueError("missing sampler version or complete termination")
if not math.isfinite(self.reward) or not math.isfinite(self.temperature) or self.temperature<=0:
raise ValueError("invalid reward/temperature")
if self.prompt.ndim!=1 or not len(self.prompt) or self.actions.ndim!=1 or not len(self.actions):
raise ValueError("nonempty prompt and response required")
if self.prompt.dtype!=torch.long or self.actions.dtype!=torch.long:
raise ValueError("integer token IDs required")
if self.q.ndim!=2 or len(self.q)!=len(self.actions):
raise ValueError("historical sampler shape mismatch")
if ((self.actions<0)|(self.actions>=self.q.shape[-1])).any():
raise ValueError("action outside vocabulary")
q=canonical_q(self.q)
if (q.gather(-1,self.actions[:,None])<=0).any():
raise ValueError("sampled action outside support")
if self.compute_digest()!=self.digest: raise ValueError("rollout tampering detected")
@torch.no_grad()
def collect_language_rollout(model, prompt, *, horizon, eos_token_id, temperature,
generator, reward_fn, sampler_version, device="cpu"):
"""reward_fn receives CPU response IDs after the complete bounded episode.
A horizon hit is a declared terminal state of this bounded task, not an
unnoticed discarded partial response. Disabling dropout is mandatory here
and during replay; stochastic model layers require an expanded sampler
contract not implemented in this reference.
"""
if model.training: raise ValueError("use model.eval() consistently for sampling and training")
if isinstance(horizon,bool) or not isinstance(horizon,int) or horizon<1:
raise ValueError("horizon must be positive integer")
if not math.isfinite(temperature) or temperature<=0: raise ValueError("invalid temperature")
if prompt.ndim!=1 or prompt.dtype!=torch.long or len(prompt)==0: raise ValueError("prompt [P] int64 required")
prefix=prompt.to(device)[None];qs=[];acts=[];termination="time_limit"
for _ in range(horizon):
z=model(input_ids=prefix,use_cache=False).logits[0,-1].double()/temperature
q=canonical_q(z.softmax(-1))
a=torch.multinomial(q,1,generator=generator)
acts.append(a.cpu());qs.append(q.cpu())
prefix=torch.cat((prefix,a[None]),-1)
if eos_token_id is not None and int(a)==int(eos_token_id):
termination="eos";break
actions=torch.cat(acts);reward=float(reward_fn(actions))
rec=LanguageRollout(prompt.detach().cpu().clone(),actions,torch.stack(qs),reward,
sampler_version,termination,temperature,"")
rec.digest=rec.compute_digest();rec.verify();return rec
def language_rollout_loss(model, record, *, beta=.1, mode="stratified_safe", budget=32,
generator=None, device="cpu"):
if model.training: raise ValueError("model.eval() is required; gradients still work in eval mode")
record.verify()
p=record.prompt.to(device);a=record.actions.to(device)
inputs=torch.cat((p,a[:-1]))[None]
z=model(input_ids=inputs,use_cache=False).logits[:,len(p)-1:]/record.temperature
q=record.q.to(device)[None];mask=torch.ones(1,len(a),dtype=torch.bool,device=device)
if z.shape!=q.shape: raise ValueError("model vocabulary or response shape changed")
rec=(stratified_correction(q,mask,budget,head=mode.split("_",1)[1],generator=generator) if mode.startswith("stratified_")
else exact_correction(q,mask) if mode=="full" else draw_correction(q,mask,budget,mode,generator=generator))
return token_loss(z,a[None],q,mask,torch.tensor([record.reward],device=device),
correction=rec,beta=beta)