import pytest import torch from celestis_rl import selected_linear_scores, draw_correction, token_loss, selected_token_loss @pytest.mark.parametrize("chunk",[1,3,17,30]) @pytest.mark.parametrize("temperature",[.7,1.,2.]) def test_selected_backward_matches_dense(chunk,temperature): torch.manual_seed(4) h=torch.randn(4,6,dtype=torch.float64,requires_grad=True) w=torch.randn(17,6,dtype=torch.float64,requires_grad=True) bias=torch.randn(17,dtype=torch.float64,requires_grad=True) q=(torch.randn(2,2,17,dtype=torch.float64)*2).softmax(-1) mask=torch.ones(2,2,dtype=torch.bool) actions=torch.tensor([[1,7],[8,9]]) corr=draw_correction(q,mask,5,generator=torch.Generator().manual_seed(8)) ids=torch.cat([actions[...,None],corr.ids],-1).reshape(4,-1) scores=selected_linear_scores(h,w,ids,bias=bias,chunk_size=chunk,temperature=temperature) logits=scores.logits.reshape(2,2,-1); lp=scores.log_probs.reshape(2,2,-1) qlog=q.gather(-1,actions[...,None]).squeeze(-1).log() reward=torch.tensor([1.,.2],dtype=torch.float64) loss,_=selected_token_loss(logits[...,0],logits[...,1:],corr,lp[...,0],qlog,reward) gs=torch.autograd.grad(loss,(h,w,bias)) dense=((h@w.T+bias)/temperature).reshape(2,2,-1) dl,_=token_loss(dense,actions,q,mask,reward,correction=corr) gd=torch.autograd.grad(dl,(h,w,bias)) assert torch.allclose(scores.log_probs, dense.detach().reshape(4,17).log_softmax(-1).gather(-1,ids),atol=1e-13,rtol=1e-13) for a,b in zip(gs,gd): assert torch.allclose(a,b,atol=2e-13,rtol=2e-13) def test_tied_input_output_embedding_gradient(): torch.manual_seed(23) w=torch.randn(11,4,dtype=torch.float64,requires_grad=True) input_ids=torch.tensor([2,6]); a=torch.tensor([[1],[4]]) q=torch.randn(2,1,11,dtype=torch.float64).softmax(-1) m=torch.ones(2,1,dtype=torch.bool) rec=draw_correction(q,m,3,generator=torch.Generator().manual_seed(9)) ids=torch.cat((a[...,None],rec.ids),-1).reshape(2,-1) reward=torch.tensor([1.,-.1],dtype=torch.float64) h=w[input_ids]*.4 scores=selected_linear_scores(h,w,ids,chunk_size=3) z=scores.logits[:,None]; lp=scores.log_probs[:,None] qlog=q.gather(-1,a[...,None]).squeeze(-1).log() l,_=selected_token_loss(z[...,0],z[...,1:],rec,lp[...,0],qlog,reward) g1=torch.autograd.grad(l,w)[0] dense=(w[input_ids]*.4@w.T)[:,None] l2,_=token_loss(dense,a,q,m,reward,correction=rec) g2=torch.autograd.grad(l2,w)[0] assert torch.allclose(g1,g2,atol=1e-13) def test_extreme_scores_and_float32_precision(): h=torch.tensor([[100.,-100.]],requires_grad=True) w=torch.tensor([[100.,100.],[-100.,100.],[100.,-100.]],requires_grad=True) s=selected_linear_scores(h,w,torch.tensor([[0,2]]),chunk_size=1) assert torch.isfinite(s.log_probs).all() assert s.log_probs[0,1] == 0 assert not s.log_probs.requires_grad @pytest.mark.parametrize("bad", [0,-1,1.5]) def test_bad_chunk_size(bad): with pytest.raises(ValueError): selected_linear_scores(torch.ones(1,2),torch.ones(3,2),torch.tensor([[1]]),chunk_size=bad)