Celestis-RL / examples /certified_update.py
PureOne's picture
Release Celestis-RL v2.0.0: audited research reference
f95cbd4 verified
Raw History Blame Contribute Delete
1.69 kB
"""Fresh paired audit and rollback on a known binary-reward task."""
import json
import numpy as np
import torch
from torch import nn
from celestis_rl.certificates import ConfidenceLedger,paired_gain_audit
from celestis_rl.losses import token_loss
from celestis_rl.transaction import transactional_step
def main():
torch.set_num_threads(1)
policy=nn.Embedding(1,2,dtype=torch.float64)
with torch.no_grad():policy.weight.zero_()
opt=torch.optim.SGD(policy.parameters(),lr=4.)
q=torch.full((128,1,2),.5,dtype=torch.float64)
actions=torch.multinomial(q[:,0],1,generator=torch.Generator().manual_seed(5))
returns=actions[:,0].double();mask=torch.ones(128,1,dtype=torch.bool)
def proposal():return token_loss(policy.weight[None].expand(128,1,2),actions,q,mask,returns)[0]
ledger=ConfidenceLedger(.05);rng=np.random.default_rng(193)
before=float(policy.weight.detach().softmax(-1)[0,1])
def audit():
after=float(policy.weight.detach().softmax(-1)[0,1])
# Same u per pair gives coupled returns with correct marginals.
# New independent u for every audit. No old holdout is reused.
u=rng.random(4000)
return paired_gain_audit((u<after).astype(float),(u<before).astype(float),
ledger=ledger,reward_min=0.,reward_max=1.)
result=transactional_step(policy,opt,proposal,audit)
print(json.dumps({"accepted":result.accepted,"before_exact_value":before,
"after_exact_value":float(policy.weight.detach().softmax(-1)[0,1]),
"audit":result.audit.__dict__,"confidence_attempts":ledger.attempts},indent=2))
if __name__=="__main__":main()