File size: 4,632 Bytes
f95cbd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import torch
import pytest
from celestis_rl.streaming import centered_linear_scores,linear_token_loss
from celestis_rl.estimators import draw_correction
from celestis_rl.losses import token_loss

@pytest.mark.parametrize('mode',['exact','sampled'])
@pytest.mark.parametrize('chunk',[1,4,20])
@pytest.mark.parametrize('temperature',[.3,1.,2.])
@pytest.mark.parametrize('has_bias',[False,True])
def test_streamed_gradient_oracle(mode,chunk,temperature,has_bias):
    torch.manual_seed(31)
    h=torch.randn(5,4,dtype=torch.float64,requires_grad=True)
    w=torch.randn(11,4,dtype=torch.float64,requires_grad=True)
    bias=torch.randn(11,dtype=torch.float64,requires_grad=True) if has_bias else None
    q=torch.randn(5,11,dtype=torch.float64).softmax(-1)
    a=torch.tensor([2,6,2,0,10]);g=torch.randn(5,dtype=torch.float64)
    opts={'q':q} if mode=='exact' else {}
    c=draw_correction(q[:,None],torch.ones(5,1,dtype=torch.bool),4,'iid',generator=torch.Generator().manual_seed(13))
    ids=torch.cat((a[:,None],c.ids[:,0]),-1)
    coefficients=torch.cat((torch.ones(5,1,dtype=torch.float64),-c.weights[:,0]),-1)
    if mode=='sampled':opts={'ids':ids,'coefficients':coefficients}
    res=centered_linear_scores(h,w,a,bias=bias,temperature=temperature,chunk_size=chunk,row_chunk_size=2,**opts)
    params=[h,w]+([bias] if has_bias else [])
    custom=torch.autograd.grad((res.centered_logits*g).sum(),params)
    z=(h@w.T+(bias if has_bias else 0))/temperature
    target=z.gather(-1,a[:,None]).squeeze(-1)-(q*z).sum(-1) if mode=='exact' else (z.gather(-1,ids)*coefficients).sum(-1)
    dense=torch.autograd.grad((target*g).sum(),params)
    assert torch.allclose(res.centered_logits,target,atol=2e-12,rtol=2e-12)
    assert torch.allclose(res.action_log_probs,z.log_softmax(-1).gather(-1,a[:,None]).squeeze(-1),atol=2e-12)
    assert not res.action_log_probs.requires_grad
    for x,y in zip(custom,dense):assert torch.allclose(x,y,atol=2e-12,rtol=2e-12)

@pytest.mark.parametrize('sampled',[False,True])
def test_token_loss_masked_equivalence(sampled):
    torch.manual_seed(17)
    h=torch.randn(2,3,4,dtype=torch.float64,requires_grad=True)
    w=torch.randn(9,4,dtype=torch.float64,requires_grad=True)
    q=torch.randn(2,3,9,dtype=torch.float64).softmax(-1)
    a=torch.tensor([[1,3,6],[4,2,0]]);mask=torch.tensor([[True,True,True],[True,True,False]])
    r=torch.tensor([1.,.5],dtype=torch.float64);weights=torch.tensor([.75,1.25],dtype=torch.float64)
    with torch.no_grad():h[1,2]=float('nan');q[1,2]=float('nan')
    rec=draw_correction(q,mask,3,'iid') if sampled else None
    L,_=linear_token_loss(h,w,a,q,mask,r,correction=rec,beta=.2,outer_weights=weights,normalizer=4.,chunk_size=4)
    gs=torch.autograd.grad(L,(h,w))
    z=h.masked_fill(~mask[...,None],0)@w.T
    oracle,_=token_loss(z,a,q,mask,r,correction=rec,beta=.2,outer_weights=weights,normalizer=4.)
    gd=torch.autograd.grad(oracle,(h,w))
    for x,y in zip(gs,gd):assert torch.allclose(x,y,atol=1e-12)
    assert torch.allclose(L,oracle,atol=1e-12)

@pytest.mark.parametrize('sampled',[False,True])
def test_gradcheck(sampled):
    torch.manual_seed(40)
    h=torch.randn(2,3,dtype=torch.float64,requires_grad=True)
    w=torch.randn(5,3,dtype=torch.float64,requires_grad=True)
    a=torch.tensor([1,3]);q=torch.ones(2,5,dtype=torch.float64)/5
    opts={'q':q}
    if sampled:opts={'ids':torch.tensor([[1,2],[3,1]]),'coefficients':torch.tensor([[1.,-1.],[1.,-1.]],dtype=torch.float64)}
    assert torch.autograd.gradcheck(lambda h,w:centered_linear_scores(h,w,a,chunk_size=2,**opts).centered_logits,(h,w))


def test_measure_and_nan_validation():
    h=torch.ones(1,2);w=torch.ones(3,2);a=torch.tensor([0])
    with pytest.raises(ValueError):centered_linear_scores(h,w,a,q=torch.ones(1,3))
    with pytest.raises(ValueError):centered_linear_scores(h,w,a,ids=a[:,None],coefficients=torch.ones(1,1))
    with pytest.raises(ValueError):centered_linear_scores(h,w,a,q=torch.ones(1,3)/3,row_chunk_size=0)
    with pytest.raises(ValueError):centered_linear_scores(h*float('nan'),w,a,q=torch.ones(1,3)/3)


def test_tied_embedding_gradient():
    torch.manual_seed(12)
    w=torch.randn(8,4,dtype=torch.float64,requires_grad=True)
    input_ids=torch.tensor([1,3,6]);a=torch.tensor([2,1,4]);q=torch.ones(3,8,dtype=torch.float64)/8
    h=w[input_ids]
    out=centered_linear_scores(h,w,a,q=q,chunk_size=3).centered_logits.sum()
    gc=torch.autograd.grad(out,w)[0]
    logits=w[input_ids]@w.T
    reference=(logits.gather(-1,a[:,None]).squeeze(-1)-(q*logits).sum(-1)).sum()
    gd=torch.autograd.grad(reference,w)[0]
    assert torch.allclose(gc,gd,atol=1e-12)