File size: 11,880 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
"""Recomputed first-order linear-head VJPs for centered policy scores.

Exact mode removes auxiliary sampling noise; sampled mode preserves the
selected estimator. Neither stores an [N,K,D] autograd activation. Both still
need an exact forward softmax normalizer. These are portable PyTorch kernels,
not fused CUDA, and produce dense parameter gradients. Higher-order AD is
intentionally unsupported. q, correction weights, and temperature are fixed.
"""
from dataclasses import dataclass
import math
import torch
from torch import Tensor
from torch.autograd.function import once_differentiable
from .estimators import canonical_q, Correction
from .losses import _prepare, _reduce


@dataclass
class CenteredScores:
    centered_logits: Tensor
    action_log_probs: Tensor  # detached, only for coefficients


def _check(h,w,a,bias,chunk,temperature):
    if h.ndim!=2 or w.ndim!=2 or h.shape[1]!=w.shape[1] or min(*h.shape,*w.shape)<1:
        raise ValueError('nonempty hidden [N,D] and weight [V,D] required')
    if not h.is_floating_point() or not w.is_floating_point():
        raise ValueError('floating point model tensors required')
    if a.shape!=(len(h),) or a.dtype!=torch.long:
        raise ValueError('actions [N] must be int64')
    if h.device!=w.device or a.device!=h.device or ((a<0)|(a>=len(w))).any():
        raise ValueError('invalid actions/devices')
    if bias is not None and (bias.shape!=(len(w),) or bias.device!=w.device or not bias.is_floating_point()):
        raise ValueError('invalid bias')
    if isinstance(chunk,bool) or not isinstance(chunk,int) or chunk<1:
        raise ValueError('chunk size must be positive integer')
    if not math.isfinite(temperature) or temperature<=0:
        raise ValueError('temperature must be positive finite')
    if not torch.isfinite(h).all() or not torch.isfinite(w).all() or (bias is not None and not torch.isfinite(bias).all()):
        raise ValueError('nonfinite active model tensor')


class _Centered(torch.autograd.Function):
    @staticmethod
    def forward(ctx,h,w,a,bias,q,ids,coeff,chunk,rows,temperature,exact):
        dtype=torch.float64 if any(x is not None and x.dtype==torch.float64 for x in (h,w,bias)) else torch.float32
        ctx.dtype=dtype;ctx.chunk=chunk;ctx.rows=rows;ctx.temperature=temperature;ctx.exact=exact
        ctx.has_bias=bias is not None
        empty=torch.empty(0,device=h.device,dtype=dtype)
        qsum=q.sum(-1,keepdim=True,dtype=torch.float64) if exact else empty
        ctx.save_for_backward(h,w,a,bias if bias is not None else empty,q,ids,coeff,qsum)
        with torch.autocast(device_type=h.device.type,enabled=False):
            x=h.to(dtype)
            za=(x*w[a].to(dtype)).sum(-1)
            if bias is not None:za=za+bias[a].to(dtype)
            za=za/temperature
            normal=torch.full((len(h),),-torch.inf,device=h.device,dtype=dtype)
            expected=torch.zeros_like(normal)
            for start in range(0,len(w),chunk):
                end=min(start+chunk,len(w))
                z=x@w[start:end].to(dtype).T
                if bias is not None:z=z+bias[start:end].to(dtype)
                z=z/temperature
                normal=torch.logaddexp(normal,torch.logsumexp(z,-1))
                if exact:
                    qc=(q[:,start:end].double()/qsum).to(dtype)
                    expected=expected+(qc*z).sum(-1)
            if exact:
                centered=za-expected
            else:
                centered=torch.zeros_like(normal)
                for start in range(0,len(h),rows):
                    end=min(start+rows,len(h));ii=ids[start:end]
                    z=(x[start:end,None,:]*w[ii].to(dtype)).sum(-1)
                    if bias is not None:z=z+bias[ii].to(dtype)
                    centered[start:end]=(z*coeff[start:end].to(dtype)).sum(-1)/temperature
            lp=za-normal
            if not torch.isfinite(centered).all() or not torch.isfinite(lp).all():
                raise FloatingPointError('nonfinite centered linear scores')
        ctx.mark_non_differentiable(lp)
        return centered,lp

    @staticmethod
    @once_differentiable
    def backward(ctx,gcenter,glogp):
        h,w,a,bias,q,ids,coeff,qsum=ctx.saved_tensors
        dtype=ctx.dtype;temp=ctx.temperature
        if gcenter is None:gcenter=torch.zeros(len(h),device=h.device,dtype=dtype)
        with torch.autocast(device_type=h.device.type,enabled=False):
            x=h.to(dtype);g=gcenter.to(dtype)/temp
            gh=torch.zeros_like(x) if ctx.needs_input_grad[0] else None
            gw=torch.zeros(w.shape,device=w.device,dtype=dtype) if ctx.needs_input_grad[1] else None
            gb=torch.zeros(len(w),device=w.device,dtype=dtype) if ctx.has_bias and ctx.needs_input_grad[3] else None
            if ctx.exact:
                for start in range(0,len(w),ctx.chunk):
                    end=min(start+ctx.chunk,len(w))
                    c=-(q[:,start:end].double()/qsum).to(dtype)
                    active=(a>=start)&(a<end)
                    rr=active.nonzero().flatten()
                    c[rr,a[rr]-start]+=1
                    c=c*g[:,None]
                    if gh is not None:gh.add_(c@w[start:end].to(dtype))
                    if gw is not None:gw[start:end]=c.T@x
                    if gb is not None:gb[start:end]=c.sum(0)
            else:
                for start in range(0,len(h),ctx.rows):
                    end=min(start+ctx.rows,len(h));ii=ids[start:end]
                    c=coeff[start:end].to(dtype)*g[start:end,None]
                    if gh is not None:gh[start:end]=(c[:,:,None]*w[ii].to(dtype)).sum(1)
                    if gw is not None:
                        contributions=(c[:,:,None]*x[start:end,None,:]).reshape(-1,w.shape[1])
                        gw.index_add_(0,ii.reshape(-1),contributions)
                    if gb is not None:gb.index_add_(0,ii.reshape(-1),c.reshape(-1))
        return (None if gh is None else gh.to(h.dtype),None if gw is None else gw.to(w.dtype),None,
                None if gb is None else gb.to(bias.dtype),None,None,None,None,None,None,None)


def centered_linear_scores(hidden: Tensor,weight: Tensor,actions: Tensor,*,q: Tensor | None=None,
                           ids: Tensor | None=None,coefficients: Tensor | None=None,
                           bias: Tensor | None=None,chunk_size: int=4096,row_chunk_size: int=64,
                           temperature: float=1.) -> CenteredScores:
    """Compute z(a)-E_q[z], or sum_j coefficients_j*z(ids_j).

    Provide q for exact mode OR ids/coefficients for a sampled zero-sum
    measure (typically one action weight +1 and auxiliary weights summing -1).
    The action-normalization pass remains exact. No gradient is returned for
    the fixed measure, sampler, IDs, temperature, or detached log probabilities.
    """
    _check(hidden,weight,actions,bias,chunk_size,temperature)
    if isinstance(row_chunk_size,bool) or not isinstance(row_chunk_size,int) or row_chunk_size<1:
        raise ValueError('row_chunk_size must be positive integer')
    exact=q is not None
    empty=torch.empty(0,device=hidden.device)
    if exact:
        if ids is not None or coefficients is not None:raise ValueError('choose exact OR sampled measure')
        if q.shape!=(len(hidden),len(weight)) or q.device!=hidden.device or not q.is_floating_point():
            raise ValueError('q shape/device/type mismatch')
        if not torch.isfinite(q).all() or (q<0).any() or not torch.allclose(q.double().sum(-1),torch.ones(len(hidden),device=q.device,dtype=torch.float64),atol=2e-6,rtol=0):
            raise ValueError('invalid actual sampler probabilities')
        q=q.detach();ids=empty.long();coefficients=empty
    else:
        if ids is None or coefficients is None or ids.ndim!=2 or ids.shape!=coefficients.shape or ids.shape[0]!=len(hidden) or ids.shape[1]<1:
            raise ValueError('selected ids and coefficients [N,K] required')
        if ids.dtype!=torch.long or not coefficients.is_floating_point() or ids.device!=hidden.device or coefficients.device!=hidden.device:
            raise ValueError('invalid selected measure devices/types')
        if ((ids<0)|(ids>=len(weight))).any() or not torch.isfinite(coefficients).all():
            raise ValueError('invalid selected measure')
        if (coefficients.double().sum(-1).abs()>2e-6).any():
            raise ValueError('centered measure must have zero total mass')
        q=empty;coefficients=coefficients.detach()
    c,lp=_Centered.apply(hidden,weight,actions,bias,q,ids,coefficients,chunk_size,row_chunk_size,float(temperature),exact)
    return CenteredScores(c,lp)


def linear_token_loss(hidden: Tensor,weight: Tensor,actions: Tensor,q: Tensor,mask: Tensor,
                      returns: Tensor,*,correction: Correction | None=None,bias: Tensor | None=None,
                      beta: float=.1,baseline: Tensor | None=None,outer_weights: Tensor | None=None,
                      normalizer: float | None=None,temperature: float=1.,chunk_size: int=4096,
                      row_chunk_size: int=64) -> tuple[Tensor,dict]:
    """Memory-bounded full or sampled token update with inherited normalization.

    hidden [B,T,D], q [B,T,V]. None correction selects exact streaming.
    Masked hidden/return entries are sanitized BEFORE any arithmetic.
    """
    if hidden.ndim!=3 or actions.shape!=hidden.shape[:2] or q.shape!=(*hidden.shape[:2],len(weight)):
        raise ValueError('hidden [B,T,D], actions [B,T], q [B,T,V] required')
    if actions.dtype!=torch.long or mask.shape!=actions.shape or mask.dtype!=torch.bool or mask.device!=hidden.device:
        raise ValueError('invalid actions/mask')
    _,r=_prepare(hidden[...,0],mask,returns,beta)
    h=hidden.masked_fill(~mask[...,None],0);a=actions.masked_fill(~mask,0)
    if a.device!=h.device:raise ValueError('action device mismatch')
    sampler=canonical_q(q,mask)
    qa=sampler.gather(-1,a[...,None]).squeeze(-1)
    if (qa[mask]<=0).any():raise ValueError('observed action absent from behavior support')
    b,t,d=h.shape
    opts={'bias':bias,'temperature':temperature,'chunk_size':chunk_size,'row_chunk_size':row_chunk_size}
    if correction is None:
        scores=centered_linear_scores(h.reshape(-1,d),weight,a.reshape(-1),q=sampler.reshape(b*t,-1),**opts)
        route='exact_streaming'
    else:
        if not torch.equal(correction.mask,mask):raise ValueError('correction mask mismatch')
        if not torch.isfinite(correction.weights).all() or (correction.weights<0).any():raise ValueError('invalid correction weights')
        sums=correction.weights.sum(-1)
        if not torch.allclose(sums[mask],torch.ones_like(sums[mask]),atol=2e-6,rtol=0):raise ValueError('correction mass mismatch')
        ids=torch.cat((a[...,None],correction.ids),-1)
        coeff=torch.cat((mask[...,None].to(correction.weights.dtype),-correction.weights),-1)
        scores=centered_linear_scores(h.reshape(-1,d),weight,a.reshape(-1),ids=ids.reshape(b*t,-1),coefficients=coeff.reshape(b*t,-1),**opts)
        route='sampled_recomputed'
    lp=scores.action_log_probs.reshape(b,t).masked_fill(~mask,0)
    lq=qa.log().masked_fill(~mask,0)
    coefficient=r-beta*(lp-lq)
    if baseline is not None:
        if baseline.shape!=(b,t) or baseline.device!=h.device:raise ValueError('baseline [B,T] required')
        base=baseline.detach().masked_fill(~mask,0)
        if not torch.isfinite(base).all():raise ValueError('nonfinite active baseline')
        coefficient=coefficient-base
    coefficient=coefficient.detach().masked_fill(~mask,0)
    per=-(coefficient*scores.centered_logits.reshape(b,t)).sum(-1)
    loss=_reduce(per,outer_weights,normalizer)
    if not torch.isfinite(loss):raise FloatingPointError('nonfinite linear loss')
    return loss,{'route':route,'coefficient':coefficient,'per_response_surrogate':per.detach()}