Celestis-RL / tests /test_hf_reference.py
PureOne's picture
Release Celestis-RL v2.0.0: audited research reference
f95cbd4 verified
Raw History Blame Contribute Delete
1.69 kB
from types import SimpleNamespace
import pytest
import torch
from celestis_rl.models import TinyCausalLM
from celestis_rl.hf_reference import collect_language_rollout,language_rollout_loss
class LocalModel(TinyCausalLM):
def forward(self,input_ids,use_cache=False):
return SimpleNamespace(logits=super().forward(input_ids))
def record(model):
return collect_language_rollout(model,torch.tensor([2]),horizon=3,eos_token_id=None,
temperature=.8,generator=torch.Generator().manual_seed(12),reward_fn=lambda a:float((a==3).float().mean()),
sampler_version="v0")
def test_adapter_exact_historical_sampler_and_gradient():
m=LocalModel().eval();r=record(m);r.verify()
prefix=torch.cat((r.prompt,r.actions[:-1]))[None]
q=(m(input_ids=prefix).logits[0].double()/.8).softmax(-1)
torch.testing.assert_close(r.q,q.detach(),atol=1e-8,rtol=1e-6)
loss,_=language_rollout_loss(m,r,generator=torch.Generator().manual_seed(34))
loss.backward();assert all(p.grad is None or torch.isfinite(p.grad).all() for p in m.parameters())
assert r.termination=="time_limit"
def test_adapter_tamper_and_dropout_contract():
m=LocalModel().eval();r=record(m);r.reward+=1
with pytest.raises(ValueError,match="tampering"):r.verify()
m.train()
with pytest.raises(ValueError,match="eval"):record(m)
def test_adapter_eos_is_complete():
m=LocalModel().eval();r0=record(m)
eos=int(r0.actions[0])
r=collect_language_rollout(m,torch.tensor([2]),horizon=3,eos_token_id=eos,temperature=.8,
generator=torch.Generator().manual_seed(12),reward_fn=lambda a:0.,sampler_version="v0")
assert len(r.actions)==1 and r.termination=="eos"