File size: 16,607 Bytes
fdcbc89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
"""Numerical oracles for the implemented parameter-space penalties.

The dense reference uses forward-mode transforms, whereas training contracts reverse-mode
derivatives. Reference for composable Jacobians: https://docs.pytorch.org/docs/stable/func.html
"""

from itertools import product
from math import sqrt

import pytest
import torch
from torch.func import jacfwd

from thirdloss.penalties import estimate


@pytest.mark.skipif(not torch.cuda.is_available(),reason="CUDA hardware unavailable")
def test_gpu_production_decoder_third_order_update_matches_cpu():
    """Verify the same fourth derivative on the actual eager CUDA kernels and CPU FP64."""
    from copy import deepcopy
    from thirdloss.models import StoryConfig, StoryTransformer, token_loss
    torch.manual_seed(7)
    cpu = StoryTransformer(StoryConfig(vocab_size=7,width=8,heads=2,layers=1,hidden=12,context=4)).double()
    gpu = deepcopy(cpu).cuda()
    ids = torch.tensor([[2,3,1,0],[4,2,5,3]])
    u = tuple(torch.randint(2,p.shape).double()*2-1 for p in cpu.parameters())
    v = tuple(torch.randint(2,p.shape).double()*2-1 for p in cpu.parameters())
    def calculate(model,device):
        parameters = tuple(model.parameters())
        loss = token_loss(model(ids.to(device)),((ids+1)%7).to(device))
        term = estimate(loss,parameters,"third",tuple(p.to(device) for p in u),tuple(p.to(device) for p in v))
        gradient = torch.autograd.grad(term,parameters)
        return term.detach().cpu(),torch.cat([g.flatten() for g in gradient]).detach().cpu()
    expected = calculate(cpu,"cpu")
    actual = calculate(gpu,"cuda")
    for reference,observed in zip(expected,actual,strict=True):
        torch.testing.assert_close(observed,reference,rtol=2e-8,atol=1e-5)


@pytest.fixture(scope="module", autouse=True)
def small_cpu_tensors():
    """Keep the tiny reference calculations deterministic and inexpensive on a CPU."""
    previous = torch.get_num_threads()
    torch.set_num_threads(1)
    yield
    torch.set_num_threads(previous)


def test_quartic_penalty_retains_fourth_derivative():
    """A detached numerical penalty would pass the value check and fail the gradient check."""
    x = torch.tensor(-0.375, dtype=torch.float64, requires_grad=True)
    one = torch.ones_like(x)
    penalty = estimate(x**4, (x,), "third", u=(one,), v=(-one,))
    torch.testing.assert_close(penalty, 576 * x.square())
    gradient, = torch.autograd.grad(penalty, x)
    torch.testing.assert_close(gradient, 1152 * x)


def test_mixed_cubic_exactly_averages_to_tensor_norm():
    """The xyz tensor has six unit entries at permutations of three distinct indices."""
    x = torch.tensor([0.3, -0.5, 0.7], dtype=torch.float64, requires_grad=True)
    signs = [x.new_tensor(s) for s in product((-1, 1), repeat=3)]
    values = [
        estimate(x[0] * x[1] * x[2], (x,), "third", u=(u,), v=(v,)).detach()
        for u, v in product(signs, repeat=2)
    ]
    torch.testing.assert_close(torch.stack(values).mean(), x.new_tensor(6.0))


def test_random_probe_generator_gives_independent_directions():
    """Reusing a probe for xyz always gives 12, twice the registered expectation."""
    x = torch.ones(3, dtype=torch.float64, requires_grad=True)
    generator = torch.Generator().manual_seed(307)
    values = [
        estimate(x[0] * x[1] * x[2], (x,), "third", generator=generator).item()
        for _ in range(256)
    ]
    # Each scalar draw is 4 or 12, with probability 1/4 of 12 under independent signs.
    assert set(values) == {4.0, 12.0}
    assert abs(sum(values) / len(values) - 6.0) < 1.0


@pytest.mark.parametrize("kind", ["third", "trace", "hessian_norm"])
def test_penalty_supports_linear_loss_and_unused_coordinates(kind):
    """Constant and unused derivatives contribute zero while ordinary training stays live."""
    x = torch.tensor(0.7, dtype=torch.float64, requires_grad=True)
    unused = torch.tensor(-0.1, dtype=torch.float64, requires_grad=True)
    ones = (torch.ones_like(x), torch.ones_like(unused))
    loss = 3 * x
    penalty = estimate(loss, (x, unused), kind, u=ones, v=ones)
    torch.testing.assert_close(penalty, x.new_zeros(()))
    gx, gu = torch.autograd.grad(loss + penalty, (x, unused), allow_unused=True)
    torch.testing.assert_close(gx, x.new_tensor(3.0))
    assert gu is None or gu.item() == 0


def test_quadratic_has_curvature_and_zero_third_derivative():
    """The third-order term must vanish even when the Hessian is arbitrarily steep."""
    x = torch.tensor(0.3, dtype=torch.float64, requires_grad=True)
    one = (torch.ones_like(x),)
    penalty = estimate(10_000 * x.square(), (x,), "third", u=one, v=one)
    torch.testing.assert_close(penalty, x.new_zeros(()))


def test_signed_hessian_trace_and_squared_norm_have_correct_gradients():
    """Concave curvature distinguishes the signed literature baseline from its square."""
    x = torch.tensor(0.2, dtype=torch.float64, requires_grad=True)
    one = (torch.ones_like(x),)
    hessian = 3 * x - 10
    trace = estimate((x**3 - 10 * x.square()) / 2, (x,), "trace", u=one)
    squared = estimate((x**3 - 10 * x.square()) / 2, (x,), "hessian_norm", u=one)
    torch.testing.assert_close(trace, hessian)
    torch.testing.assert_close(squared, hessian.square())
    torch.testing.assert_close(torch.autograd.grad(trace, x)[0], x.new_tensor(3.0))
    torch.testing.assert_close(torch.autograd.grad(squared, x)[0], 6 * hessian)


def tiny_causal_loss(theta):
    """A one-block decoder fixture with active coefficients in attention, MLP and head.

    Fixed input embeddings and held-fixed weights isolate a three-coordinate parameter
    subspace. The causal mask and trainable operations use smooth, deterministic math.
    """
    embeddings = theta.new_tensor([[0.7, -0.6], [0.2, 1.0], [-0.9, 0.5]])
    hidden = embeddings[[0, 1, 2]]
    query = hidden @ (theta.new_tensor([[1.0, 0.2], [-0.1, 0.8]])
                      + theta[0] * theta.new_tensor([[0.4, -0.2], [0.3, 0.6]]))
    key = hidden @ theta.new_tensor([[0.7, -0.4], [0.1, 0.9]])
    scores = query @ key.T / sqrt(hidden.size(-1))
    future = torch.ones_like(scores, dtype=torch.bool).triu(diagonal=1)
    attention = scores.masked_fill(future, float("-inf")).softmax(dim=-1)
    hidden = hidden + attention @ hidden
    expansion = hidden @ theta.new_tensor([[1.0, 0.2], [-0.5, 0.7]])
    hidden = hidden + torch.tanh(expansion * (0.8 + theta[1]))
    hidden = hidden * (hidden.square().mean(dim=-1, keepdim=True) + 1e-4).rsqrt()
    outputs = embeddings.T + theta[2] * theta.new_tensor([[0.2, 0.5, -0.4], [0.8, -0.3, 0.6]])
    logits = hidden @ outputs
    targets = torch.tensor([1, 2, 0], dtype=torch.long, device=theta.device)
    target_logits = logits.gather(1, targets[:, None]).squeeze(1)
    return (logits.logsumexp(dim=-1) - target_logits).mean()


def test_tiny_transformer_against_dense_tensor_and_finite_differences():
    """Compare a contracted third derivative and its parameter gradient to independent oracles."""
    theta = torch.tensor([0.19, -0.37, 0.22], dtype=torch.float64, requires_grad=True)
    u = theta.new_tensor([-1.0, 1.0, 1.0])
    v = theta.new_tensor([1.0, -1.0, 1.0])
    dense_third = jacfwd(jacfwd(jacfwd(tiny_causal_loss)))

    def reference(point):
        """Contract explicitly materialized partials in this small verification subspace."""
        tensor = dense_third(point)
        vector = torch.einsum("ijk,j,k->i", tensor, u, v)
        return vector.square().sum()

    point = theta.detach()
    penalty = estimate(tiny_causal_loss(theta), (theta,), "third", u=(u,), v=(v,))
    torch.testing.assert_close(penalty.detach(), reference(point), rtol=2e-9, atol=1e-11)
    gradient, = torch.autograd.grad(penalty, theta)
    # Central-difference the independent dense-AD scalar. Vary one parameter at a time.
    step = 2e-5
    basis = torch.eye(point.numel(), dtype=point.dtype)
    numerical = torch.stack([
        (reference(point + step * e) - reference(point - step * e)) / (2 * step)
        for e in basis
    ])
    assert numerical.norm() > 1e-5
    torch.testing.assert_close(gradient, numerical, rtol=3e-5, atol=1e-8)


def test_actual_adamw_update_responds_to_the_third_order_term():
    """The registered penalty reverses this ordinary gradient; detaching restores the CE step."""
    def updated(strength, detach=False):
        """Use AdamW itself, including its moment normalization."""
        x = torch.nn.Parameter(torch.tensor(0.25, dtype=torch.float64))
        optimizer = torch.optim.AdamW([x], lr=0.01, weight_decay=0)
        loss = x**4 - x
        one = (torch.ones_like(x),)
        penalty = estimate(loss, (x,), "third", u=one, v=one)
        (loss + strength * (penalty.detach() if detach else penalty)).backward()
        optimizer.step()
        return x.detach()

    ordinary = updated(0)
    assert updated(0.01).item() < 0.25 < ordinary.item()
    torch.testing.assert_close(updated(0.01, detach=True), ordinary, rtol=0, atol=0)


def test_production_story_model_exposes_full_weight_penalty_gradient():
    """Exercise all trainable coordinates through the same scratch-model entry point as training."""
    from thirdloss.models import StoryConfig, StoryTransformer, token_loss

    with torch.random.fork_rng(devices=[]):
        torch.manual_seed(42)
        config = StoryConfig(vocab_size=7, width=8, heads=2, layers=1, hidden=12, context=4)
        model = StoryTransformer(config).double().eval()
    ids = torch.tensor([[2, 4, 1, 5], [3, 6, 2, 1]])
    targets = torch.tensor([[4, 1, 5, 6], [6, 2, 1, 0]])
    loss = token_loss(model(ids), targets)
    weights = tuple(model.parameters())
    penalty = estimate(loss, weights, "third", generator=torch.Generator().manual_seed(7))
    augmented = torch.autograd.grad(loss + 0.01 * penalty, weights)
    plain = torch.autograd.grad(token_loss(model(ids), targets), weights)
    assert penalty.isfinite() and penalty > 0
    assert all(gradient.isfinite().all() for gradient in augmented)
    assert any(not torch.allclose(a, b, atol=1e-10, rtol=1e-9) for a, b in zip(augmented, plain))


def test_pythia_adapter_fourth_derivative_and_portable_checkpoint(tmp_path, monkeypatch, record_property):
    """Exercise the production PEFT and GPT-NeoX code on a small, offline CPU backbone.

    Compare the gradient with a finite difference along a fixed direction, then load the
    updated adapter into a fresh copy. https://huggingface.co/docs/peft/developer_guides/checkpoint
    """
    from peft import get_peft_model_state_dict, set_peft_model_state_dict
    from safetensors.torch import load_file
    from transformers import AutoModelForCausalLM, GPTNeoXConfig, GPTNeoXForCausalLM
    from thirdloss.models import build_model, export_weights, logits_of, token_loss

    def local_base(*args, **kwargs):
        config = GPTNeoXConfig(vocab_size=17, hidden_size=16, num_hidden_layers=1,
                               num_attention_heads=2, intermediate_size=32, max_position_embeddings=32,
                               attention_dropout=0.0, hidden_dropout=0.0, use_cache=False)
        config._attn_implementation = kwargs["attn_implementation"]
        return GPTNeoXForCausalLM(config)

    monkeypatch.setattr(AutoModelForCausalLM, "from_pretrained", local_base)
    model = build_model("abstracts", 27, "cpu", tmp_path).double().eval()
    named = [(name, p) for name, p in model.named_parameters() if p.requires_grad]
    assert len(named) == 2 and all("query_key_value.lora_" in name for name, _ in named)
    params = tuple(p for _, p in named)
    rng = torch.Generator().manual_seed(19)
    def signs():
        return tuple(torch.randint(2, p.shape, generator=rng).to(p) * 2 - 1 for p in params)

    u, v, direction = signs(), signs(), signs()
    ids = torch.tensor([[2, 4, 5, 6], [3, 5, 6, 1]])
    def penalty():
        loss = token_loss(logits_of(model, ids), (ids + 1) % 17)
        return estimate(loss, params, "third", u=u, v=v)

    grad = torch.autograd.grad(penalty(), params)
    projected = sum((g * d).sum() for g, d in zip(grad, direction, strict=True))
    initial = tuple(p.detach().clone() for p in params)
    def set_offset(distance):
        with torch.no_grad():
            for p, origin, d in zip(params, initial, direction, strict=True):
                p.copy_(origin + distance * d)

    # GPT-NeoX's eager softmax explicitly computes in FP32 even with FP64 parameters.
    # Combine two central differences to cancel their leading truncation error and avoid
    # subtracting nearly identical FP32-rounded attention outputs at a tiny displacement.
    # https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt_neox/modeling_gpt_neox.py
    def central(h):
        set_offset(h)
        plus = penalty().detach()
        set_offset(-h)
        return (plus-penalty().detach())/(2*h)

    coarse, fine = central(1e-3), central(5e-4)
    extrapolated = (4*fine-coarse)/3
    assert projected.abs() > 1e-7
    torch.testing.assert_close(projected, extrapolated, rtol=2e-5, atol=1e-8)
    record_property("adapter_directional_autograd", projected.item())
    record_property("adapter_directional_finite_difference", extrapolated.item())

    path = export_weights(model, tmp_path/"export")
    payload = load_file(str(path))
    fresh = build_model("abstracts", 27, "cpu", tmp_path).double().eval()
    assert set(payload) == set(get_peft_model_state_dict(fresh))
    set_peft_model_state_dict(fresh, payload)
    torch.testing.assert_close(logits_of(fresh, ids), logits_of(model, ids), rtol=0, atol=0)

    # The production FP64 replica receives the current optimized factors. Its registered
    # mask must prevent future tokens influencing earlier logits in the new attention backend.
    from thirdloss.objectives import derivative_replica, probe_gradient
    from thirdloss.penalties import random_signs
    from thirdloss.windows import generator, probe_rows
    monkeypatch.setenv("THIRDLOSS_ADAPTER_DERIVATIVE_DEVICE","cpu")
    before = torch.get_rng_state()
    replica = derivative_replica("abstracts",27,tmp_path)
    assert torch.equal(before,torch.get_rng_state())
    y = (ids+1)%17
    streamed,streamed_grad = probe_gradient(model,params,ids,y,"third",7,0,replica)
    precise = tuple(p for p in replica.parameters() if p.requires_grad)
    for source,dest in zip(params,precise,strict=True):
        torch.testing.assert_close(dest,source,rtol=0,atol=0)
    rows = probe_rows(7,0,len(ids))
    probe_rng = generator(ids.device,7,0,827)
    a,b = random_signs(params,probe_rng),random_signs(params,probe_rng)
    exact = estimate(token_loss(logits_of(replica,ids[rows]),y[rows]),precise,"third",u=a,v=b)
    torch.testing.assert_close(streamed,exact.detach(),rtol=1e-10,atol=1e-8)
    for observed,expected in zip(streamed_grad,torch.autograd.grad(exact,precise),strict=True):
        torch.testing.assert_close(observed,expected,rtol=1e-7,atol=1e-7)
    altered=ids.clone()
    altered[:,-1]=(altered[:,-1]+4)%17
    torch.testing.assert_close(logits_of(replica,ids)[:,:-1],logits_of(replica,altered)[:,:-1],rtol=0,atol=0)


def test_large_finite_gradient_norm_survives_squaring():
    """The real adapter calibration exposed overflow only in the FP32 norm reduction."""
    from thirdloss.objectives import vector_norm
    blocks = (torch.tensor([3e20]), torch.tensor([4e20]))
    actual = vector_norm(x for x in blocks)
    torch.testing.assert_close(actual.double(), torch.tensor(5e20, dtype=torch.float64), rtol=1e-7, atol=0)


def test_sequential_windows_reproduce_joint_penalty_and_training_gradient():
    """Shared probes preserve every cross-window term in the norm of the mean derivative."""
    from thirdloss.models import StoryConfig, StoryTransformer, token_loss
    from thirdloss.objectives import two_window_third_gradient
    from thirdloss.penalties import random_signs
    torch.manual_seed(23)
    model = StoryTransformer(StoryConfig(vocab_size=7,width=8,heads=2,layers=1,hidden=12,context=4)).double()
    params = tuple(model.parameters())
    x = torch.tensor([[2,3,1,0],[4,2,5,3]])
    y = (x+1)%7
    rng = torch.Generator().manual_seed(7)
    u,v = random_signs(params,rng),random_signs(params,rng)
    joint = estimate(token_loss(model(x),y),params,"third",u=u,v=v)
    reference = torch.autograd.grad(joint,params)
    value,gradient = two_window_third_gradient(model,params,x,y,u,v)
    torch.testing.assert_close(value,joint.detach(),rtol=3e-10,atol=1e-8)
    for cached,full in zip(gradient,reference,strict=True):
        torch.testing.assert_close(cached,full,rtol=1e-8,atol=1e-5)