summaryrefslogtreecommitdiff
path: root/experiments/conv_local_smoke.py
blob: 8070d9f98a8700434a79a8e744535c2e8df6f44a (plain)
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
#!/usr/bin/env python3
"""Prove the convolutional local eligibility matches exact BP when instructed."""
import os
import sys

import torch
import torch.nn.functional as F

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sdil.conv import (CIFARLocalResNet, CIFARSDILResNet, ConvSDILConfig,
                       channel_subspace_apical_calibration, conv_local_step,
                       simultaneous_conv_node_perturbation,
                       vectorizer_subspace_apical_calibration)


def architecture_checks():
    expected = {
        8: (7, 74810),
        20: (19, 268346),
        32: (31, 461882),
        56: (55, 848954),
    }
    for depth, (hidden, parameters) in expected.items():
        net = CIFARLocalResNet(depth=depth)
        assert net.n_hidden == hidden
        assert net.n_forward_parameters == parameters
        assert len(net.blocks) == 3 * ((depth - 2) // 6)
        assert len(net.W) + 1 == depth
    batchnorm_parameters = {8: 75290, 20: 269722, 32: 464154, 56: 853018}
    for depth, parameters in batchnorm_parameters.items():
        net = CIFARLocalResNet(
            depth=depth, normalization="batchnorm", residual_scale=1.0)
        assert net.n_forward_parameters == parameters
    for depth in (7, 9, 21):
        try:
            CIFARLocalResNet(depth=depth)
        except ValueError:
            pass
        else:
            raise AssertionError(f"invalid depth {depth} was accepted")

    x = torch.arange(2 * 3 * 8 * 8, dtype=torch.float32).reshape(2, 3, 8, 8)
    shortcut = CIFARLocalResNet._option_a_shortcut(x, 6, 2)
    assert tuple(shortcut.shape) == (2, 6, 4, 4)
    assert torch.count_nonzero(shortcut[:, 0]) == 0
    assert torch.count_nonzero(shortcut[:, -2:]) == 0
    assert torch.equal(shortcut[:, 1:4], x[:, :, ::2, ::2])


def exact_local_gradient_check():
    torch.manual_seed(123)
    batch = 3
    x = torch.randn(batch, 3, 32, 32)
    y = torch.tensor([0, 3, 8])
    local = CIFARLocalResNet(depth=8, base_width=4, seed=19)
    bp = CIFARLocalResNet(depth=8, base_width=4, seed=19)

    parameters = local.W + [local.W_out, local.b_out]
    for parameter in parameters:
        parameter.requires_grad_(True)
    forward = local.forward(x, return_cache=True)
    for hidden in forward["hiddens"]:
        hidden.retain_grad()
    loss = F.cross_entropy(forward["logits"], y)
    loss.backward()

    # .backward() differentiated a batch-mean loss.  Multiplying hidden grads
    # by B recovers the per-example convention consumed by the local rule.
    teaching = [-batch * hidden.grad for hidden in forward["hiddens"]]
    output_error = (torch.softmax(forward["logits"].detach(), dim=1)
                    - F.one_hot(y, local.n_classes))
    (directions, gamma_directions, beta_directions,
     out_direction, bias_direction) = local.local_ascent_directions(
        teaching, output_error, forward)
    assert gamma_directions == beta_directions == []

    relative_errors = []
    for direction, parameter in zip(directions, local.W):
        absolute = (direction + parameter.grad).abs().max()
        scale = parameter.grad.abs().max().clamp_min(1e-12)
        relative_errors.append(float(absolute / scale))
    output_abs = float((out_direction + local.W_out.grad).abs().max())
    bias_abs = float((bias_direction + local.b_out.grad).abs().max())
    assert max(relative_errors) < 3e-5
    assert output_abs < 2e-6 and bias_abs < 2e-6

    for parameter in parameters:
        parameter.requires_grad_(False)
    eta = 0.017
    local.apply_ascent(directions, out_direction, bias_direction, eta)
    bp_loss = bp.bp_step(x, y, eta)
    assert abs(float(loss.detach()) - bp_loss) < 1e-7
    parameter_differences = [
        float((left - right).abs().max())
        for left, right in zip(
            local.W + [local.W_out, local.b_out],
            bp.W + [bp.W_out, bp.b_out])]
    assert max(parameter_differences) < 2e-7
    return {
        "max_relative_local_gradient_error": max(relative_errors),
        "output_absolute_error": output_abs,
        "post_update_parameter_max_error": max(parameter_differences),
    }


def exact_batchnorm_local_gradient_check():
    torch.manual_seed(31)
    batch = 4
    x = torch.randn(batch, 3, 32, 32)
    y = torch.tensor([0, 1, 2, 3])
    common = dict(
        depth=8, base_width=2, seed=29,
        normalization="batchnorm", residual_scale=1.0)
    local = CIFARLocalResNet(**common)
    bp = CIFARLocalResNet(**common)
    parameters = local.W + local.gamma + local.beta + [local.W_out, local.b_out]
    for parameter in parameters:
        parameter.requires_grad_(True)
    forward = local.forward(
        x, return_cache=True, training=True, update_stats=True)
    for hidden in forward["hiddens"]:
        hidden.retain_grad()
    loss = F.cross_entropy(forward["logits"], y)
    loss.backward()
    teaching = [-batch * hidden.grad for hidden in forward["hiddens"]]
    output_error = (torch.softmax(forward["logits"].detach(), dim=1)
                    - F.one_hot(y, 10))
    (directions, gamma_directions, beta_directions,
     out_direction, bias_direction) = local.local_ascent_directions(
        teaching, output_error, forward)
    groups = (
        (directions, local.W),
        (gamma_directions, local.gamma),
        (beta_directions, local.beta),
    )
    relative_errors = []
    for direction_group, parameter_group in groups:
        for direction, parameter in zip(direction_group, parameter_group):
            absolute = (direction + parameter.grad).abs().max()
            relative_errors.append(float(
                absolute / parameter.grad.abs().max().clamp_min(1e-12)))
    assert max(relative_errors) < 3e-5
    for parameter in parameters:
        parameter.requires_grad_(False)

    eta = 0.013
    local.apply_ascent(
        directions, out_direction, bias_direction, eta,
        gamma_directions=gamma_directions, beta_directions=beta_directions)
    bp.bp_step(x, y, eta)
    parameter_differences = [
        float((left - right).abs().max())
        for left, right in zip(
            local.W + local.gamma + local.beta + [local.W_out, local.b_out],
            bp.W + bp.gamma + bp.beta + [bp.W_out, bp.b_out])]
    running_differences = [
        float((left - right).abs().max())
        for left, right in zip(
            local.running_mean + local.running_var,
            bp.running_mean + bp.running_var)]
    assert max(parameter_differences) < 2e-7
    assert max(running_differences) == 0.0

    running_before = [value.clone() for value in local.running_mean + local.running_var]
    clean = local.forward(x, training=True, update_stats=False)
    simultaneous_conv_node_perturbation(
        local, x, y, clean, sigma=1e-3, n_directions=1,
        generator=torch.Generator(device="cpu").manual_seed(9))
    assert all(torch.equal(before, after) for before, after in zip(
        running_before, local.running_mean + local.running_var))
    assert torch.equal(local.logits(x), local.logits(x))
    return {
        "batchnorm_max_relative_local_gradient_error": max(relative_errors),
        "batchnorm_post_update_parameter_max_error": max(parameter_differences),
    }


def perturbation_checks():
    net = CIFARLocalResNet(depth=8, base_width=4, seed=3)
    x = torch.randn(2, 3, 32, 32)
    clean = net.forward(x)
    perturbations = [torch.zeros_like(hidden) for hidden in clean["hiddens"]]
    perturbed = net.forward(x, perturbations=perturbations)
    assert torch.equal(clean["logits"], perturbed["logits"])
    perturbations[0] = torch.ones_like(perturbations[0]) * 0.01
    changed = net.forward(x, perturbations=perturbations)
    assert not torch.equal(clean["logits"], changed["logits"])
    try:
        net.forward(x, perturbations=perturbations[:-1])
    except ValueError:
        pass
    else:
        raise AssertionError("short perturbation list was accepted")


def perturbation_estimator_check():
    """Antithetic finite differences equal the simultaneous hidden JVP."""
    torch.manual_seed(3)
    batch = 2
    net = CIFARSDILResNet(
        depth=8, base_width=2, seed=4, dtype=torch.float64)
    x = torch.randn(batch, 3, 32, 32, dtype=torch.float64)
    y = torch.tensor([2, 7])
    parameters = net.W + [net.W_out, net.b_out]
    for parameter in parameters:
        parameter.requires_grad_(True)
    clean = net.forward(x, return_cache=True)
    for hidden in clean["hiddens"]:
        hidden.retain_grad()
    F.cross_entropy(clean["logits"], y).backward()
    generator = torch.Generator(device="cpu").manual_seed(99)
    targets, diagnostics = simultaneous_conv_node_perturbation(
        net, x, y, clean, sigma=1e-6, n_directions=1,
        generator=generator, return_diagnostics=True)
    directions = diagnostics["directions"][0]
    derivative = diagnostics["directional_derivatives"][0]
    assert derivative["coupling"] == "per_example_objective"
    finite_difference = derivative["scaled_directional"]
    exact = sum(
        (batch * hidden.grad * direction).flatten(1).sum(dim=1)
        for hidden, direction in zip(clean["hiddens"], directions))
    relative = (finite_difference - exact).abs() / exact.abs().clamp_min(1e-12)
    assert float(relative.max()) < 2e-6
    for target, direction in zip(targets, directions):
        expected = -finite_difference[:, None, None, None] * direction
        assert torch.equal(target, expected)
    for parameter in parameters:
        parameter.requires_grad_(False)
    no_norm_relative = float(relative.max())

    batch = 3
    batchnorm = CIFARSDILResNet(
        depth=8, base_width=2, seed=14, dtype=torch.float64,
        normalization="batchnorm", residual_scale=1.0)
    xb = torch.randn(batch, 3, 32, 32, dtype=torch.float64)
    yb = torch.tensor([1, 4, 9])
    parameters = (batchnorm.W + batchnorm.gamma + batchnorm.beta
                  + [batchnorm.W_out, batchnorm.b_out])
    for parameter in parameters:
        parameter.requires_grad_(True)
    clean = batchnorm.forward(xb, training=True, update_stats=False)
    for hidden in clean["hiddens"]:
        hidden.retain_grad()
    F.cross_entropy(clean["logits"], yb).backward()
    targets, diagnostics = simultaneous_conv_node_perturbation(
        batchnorm, xb, yb, clean, sigma=1e-6, n_directions=1,
        generator=torch.Generator(device="cpu").manual_seed(101),
        return_diagnostics=True)
    directions = diagnostics["directions"][0]
    derivative = diagnostics["directional_derivatives"][0]
    assert derivative["coupling"] == "batch_objective"
    scaled = derivative["scaled_directional"]
    exact_sum_directional = sum(
        float((batch * hidden.grad * direction).sum())
        for hidden, direction in zip(clean["hiddens"], directions))
    batchnorm_relative = abs(float(scaled[0]) - exact_sum_directional) / max(
        abs(exact_sum_directional), 1e-12)
    assert batchnorm_relative < 2e-6
    assert torch.equal(scaled, scaled[:1].expand_as(scaled))
    for target, direction in zip(targets, directions):
        expected = -scaled[:, None, None, None] * direction
        assert torch.equal(target, expected)
    for parameter in parameters:
        parameter.requires_grad_(False)
    return {
        "perturbation_jvp_max_relative_error": no_norm_relative,
        "batchnorm_batch_objective_jvp_relative_error": batchnorm_relative,
    }


def channel_subspace_estimator_check():
    """The structured estimator targets representable base/gate moments."""
    torch.manual_seed(71)
    batch = 3
    hiddens = [
        torch.randn(batch, 2, 4, 4, dtype=torch.float64),
        torch.randn(batch, 3, 2, 2, dtype=torch.float64),
    ]
    negative_gradients = [torch.randn_like(value) for value in hiddens]
    estimated_base = [torch.zeros(
        batch, value.shape[1], dtype=value.dtype) for value in hiddens]
    estimated_gate = [torch.zeros_like(value) for value in estimated_base]
    generator = torch.Generator(device="cpu").manual_seed(211)
    directions = 4096
    inverse_sqrt_two = 1.0 / (2.0 ** 0.5)
    for _ in range(directions):
        hidden_directions = []
        base_random = []
        gate_random = []
        for hidden in hiddens:
            shape = (batch, hidden.shape[1])
            base = torch.empty(shape, dtype=hidden.dtype).bernoulli_(
                0.5, generator=generator).mul_(2).sub_(1)
            gate = torch.empty_like(base).bernoulli_(
                0.5, generator=generator).mul_(2).sub_(1)
            hidden_directions.append((
                base[:, :, None, None]
                + torch.tanh(hidden) * gate[:, :, None, None])
                * inverse_sqrt_two)
            base_random.append(base)
            gate_random.append(gate)
        # The exact loss derivative uses g=-negative_gradient and remains
        # per-example without BatchNorm coupling.
        directional = -sum(
            (gradient * direction).flatten(1).sum(dim=1)
            for gradient, direction in zip(
                negative_gradients, hidden_directions))
        for index, (hidden, base, gate) in enumerate(zip(
                hiddens, base_random, gate_random)):
            spatial = hidden.shape[2] * hidden.shape[3]
            scale = -(2.0 ** 0.5) / (spatial * directions)
            estimated_base[index].add_(directional[:, None] * base, alpha=scale)
            estimated_gate[index].add_(directional[:, None] * gate, alpha=scale)
    exact_base = [value.mean(dim=(2, 3)) for value in negative_gradients]
    exact_gate = [(value * torch.tanh(hidden)).mean(dim=(2, 3))
                  for value, hidden in zip(negative_gradients, hiddens)]
    estimated = torch.cat([
        value.flatten() for pair in zip(estimated_base, estimated_gate)
        for value in pair])
    exact = torch.cat([
        value.flatten() for pair in zip(exact_base, exact_gate)
        for value in pair])
    cosine = float(F.cosine_similarity(estimated, exact, dim=0))
    norm_ratio = float(estimated.norm() / exact.norm())
    assert cosine > 0.985
    assert 0.90 < norm_ratio < 1.10

    # The executable antithetic implementation must match the same structured
    # directional derivative, not an autograd surrogate.
    # Use a fixed nondegenerate point.  Width-one, zero-bias ReLU networks can
    # contain structurally exact-zero preactivations, where central differences
    # and PyTorch's chosen subgradient need not agree even as sigma -> 0.
    torch.manual_seed(3)
    net = CIFARSDILResNet(
        depth=8, base_width=2, seed=72, dtype=torch.float64,
        vectorizer_mode="channel_gated")
    x = torch.randn(2, 3, 32, 32, dtype=torch.float64)
    y = torch.tensor([2, 8])
    parameters = net.W + [net.W_out, net.b_out]
    for parameter in parameters:
        parameter.requires_grad_(True)
    clean = net.forward(x, return_cache=True)
    for hidden in clean["hiddens"]:
        hidden.retain_grad()
    loss = F.cross_entropy(clean["logits"], y)
    loss.backward()
    output_signal = (torch.softmax(clean["logits"].detach(), dim=1)
                     - F.one_hot(y, 10).to(torch.float64))
    _, diagnostics = channel_subspace_apical_calibration(
        net, x, y, clean, output_signal, sigma=1e-6,
        n_directions=1, eta=0.0,
        generator=torch.Generator(device="cpu").manual_seed(307),
        return_diagnostics=True)
    hidden_direction = diagnostics["directions"][0]["hidden"]
    finite_difference = diagnostics["directional_derivatives"][0][
        "scaled_directional"]
    exact_directional = sum(
        (x.shape[0] * hidden.grad * direction).flatten(1).sum(dim=1)
        for hidden, direction in zip(clean["hiddens"], hidden_direction))
    relative = ((finite_difference - exact_directional).abs()
                / exact_directional.abs().clamp_min(1e-12))
    assert float(relative.max()) < 2e-6
    for parameter in parameters:
        parameter.requires_grad_(False)

    # The local A/G update must equal the full-field delta rule after replacing
    # only its two target moments with the structured causal estimates.
    eta = 0.0023
    before_a = [value.clone() for value in net.A]
    before_g = [value.clone() for value in net.A_gate]
    expected_a = []
    expected_g = []
    for index, hidden in enumerate(clean["hiddens"]):
        base = output_signal @ before_a[index].t()
        gate_coefficient = output_signal @ before_g[index].t()
        gate = torch.tanh(hidden.detach())
        mean = gate.mean(dim=(2, 3))
        second = gate.square().mean(dim=(2, 3))
        base_error = diagnostics["target_base"][index] - (
            base + mean * gate_coefficient)
        gate_error = diagnostics["target_gate"][index] - (
            mean * base + second * gate_coefficient)
        expected_a.append(before_a[index] + eta * (
            base_error.t() @ output_signal / x.shape[0]))
        expected_g.append(before_g[index] + eta * (
            gate_error.t() @ output_signal / x.shape[0]))
    channel_subspace_apical_calibration(
        net, x, y, clean, output_signal, sigma=1e-6,
        n_directions=1, eta=eta,
        generator=torch.Generator(device="cpu").manual_seed(307))
    update_error = max(float((actual - expected).abs().max())
                       for actual, expected in zip(
                           net.A + net.A_gate, expected_a + expected_g))
    assert update_error < 1e-14

    return {
        "channel_subspace_moment_cosine": cosine,
        "channel_subspace_moment_norm_ratio": norm_ratio,
        "channel_subspace_jvp_relative_error": float(relative.max()),
        "channel_subspace_delta_rule_absolute_error": update_error,
    }


def vectorizer_subspace_estimator_check():
    """Direct A/G perturbations are unbiased and lower variance at batch 128."""
    torch.manual_seed(81)
    batch = 128
    output_dim = 5
    hiddens = [
        torch.randn(batch, 2, 4, 4, dtype=torch.float64),
        torch.randn(batch, 3, 2, 2, dtype=torch.float64),
    ]
    negative_gradients = [torch.randn_like(value) for value in hiddens]
    output_signal = torch.randn(batch, output_dim, dtype=torch.float64)
    exact_pairs = []
    for hidden, target in zip(hiddens, negative_gradients):
        exact_pairs.extend([
            target.mean(dim=(2, 3)).t() @ output_signal / batch,
            (target * torch.tanh(hidden)).mean(dim=(2, 3)).t()
            @ output_signal / batch,
        ])
    exact = torch.cat([value.flatten() for value in exact_pairs])
    coefficient_sum = torch.zeros_like(exact)
    vectorizer_sum = torch.zeros_like(exact)
    coefficient_mse = 0.0
    vectorizer_mse = 0.0
    directions = 2048
    generator = torch.Generator(device="cpu").manual_seed(401)
    inverse_sqrt_two = 1.0 / (2.0 ** 0.5)
    for _ in range(directions):
        random_coefficients = []
        hidden_directions = []
        for hidden in hiddens:
            shape = (batch, hidden.shape[1])
            base = torch.empty(shape, dtype=hidden.dtype).bernoulli_(
                0.5, generator=generator).mul_(2).sub_(1)
            gate = torch.empty_like(base).bernoulli_(
                0.5, generator=generator).mul_(2).sub_(1)
            random_coefficients.append((base, gate))
            hidden_directions.append((
                base[:, :, None, None]
                + torch.tanh(hidden) * gate[:, :, None, None])
                * inverse_sqrt_two)
        directional = -sum((target * direction).sum()
                           for target, direction in zip(
                               negative_gradients, hidden_directions))
        coefficient_values = []
        for hidden, (base, gate) in zip(hiddens, random_coefficients):
            spatial = hidden.shape[2] * hidden.shape[3]
            base_target = -(2.0 ** 0.5) * directional * base / spatial
            gate_target = -(2.0 ** 0.5) * directional * gate / spatial
            coefficient_values.extend([
                base_target.t() @ output_signal / batch,
                gate_target.t() @ output_signal / batch,
            ])
        coefficient_sample = torch.cat(
            [value.flatten() for value in coefficient_values])

        random_matrices = []
        hidden_directions = []
        for hidden in hiddens:
            shape = (hidden.shape[1], output_dim)
            base = torch.empty(shape, dtype=hidden.dtype).bernoulli_(
                0.5, generator=generator).mul_(2).sub_(1)
            gate = torch.empty_like(base).bernoulli_(
                0.5, generator=generator).mul_(2).sub_(1)
            base_field = output_signal @ base.t()
            gate_field = output_signal @ gate.t()
            random_matrices.append((base, gate))
            hidden_directions.append((
                base_field[:, :, None, None]
                + torch.tanh(hidden) * gate_field[:, :, None, None])
                * inverse_sqrt_two)
        directional = -sum((target * direction).sum()
                           for target, direction in zip(
                               negative_gradients, hidden_directions))
        vectorizer_values = []
        for hidden, (base, gate) in zip(hiddens, random_matrices):
            spatial = hidden.shape[2] * hidden.shape[3]
            scale = -(2.0 ** 0.5) * directional / (batch * spatial)
            vectorizer_values.extend([scale * base, scale * gate])
        vectorizer_sample = torch.cat(
            [value.flatten() for value in vectorizer_values])
        coefficient_sum.add_(coefficient_sample)
        vectorizer_sum.add_(vectorizer_sample)
        coefficient_mse += float((coefficient_sample - exact).square().mean())
        vectorizer_mse += float((vectorizer_sample - exact).square().mean())
    coefficient_mean = coefficient_sum / directions
    vectorizer_mean = vectorizer_sum / directions
    vectorizer_cosine = float(F.cosine_similarity(
        vectorizer_mean, exact, dim=0))
    vectorizer_norm_ratio = float(vectorizer_mean.norm() / exact.norm())
    variance_ratio = vectorizer_mse / coefficient_mse
    assert vectorizer_cosine > 0.95
    assert 0.90 < vectorizer_norm_ratio < 1.10
    assert variance_ratio < 0.25

    # Match the executable forward-only derivative and its exact A/G update.
    torch.manual_seed(3)
    net = CIFARSDILResNet(
        depth=8, base_width=2, seed=82, dtype=torch.float64,
        vectorizer_mode="channel_gated")
    x = torch.randn(2, 3, 32, 32, dtype=torch.float64)
    y = torch.tensor([1, 6])
    parameters = net.W + [net.W_out, net.b_out]
    for parameter in parameters:
        parameter.requires_grad_(True)
    clean = net.forward(x, return_cache=True)
    for hidden in clean["hiddens"]:
        hidden.retain_grad()
    F.cross_entropy(clean["logits"], y).backward()
    output_error = (torch.softmax(clean["logits"].detach(), dim=1)
                    - F.one_hot(y, 10).to(torch.float64))
    _, diagnostics = vectorizer_subspace_apical_calibration(
        net, x, y, clean, output_error, sigma=1e-6,
        n_directions=1, eta=0.0,
        generator=torch.Generator(device="cpu").manual_seed(503),
        return_diagnostics=True)
    finite_difference = diagnostics["directional_derivatives"][0][
        "scaled_directional"]
    exact_directional = sum(
        (x.shape[0] * hidden.grad * direction).sum()
        for hidden, direction in zip(
            clean["hiddens"], diagnostics["directions"][0]["hidden"]))
    jvp_relative = float((finite_difference - exact_directional).abs()
                         / exact_directional.abs().clamp_min(1e-12))
    assert jvp_relative < 2e-6
    for parameter in parameters:
        parameter.requires_grad_(False)

    eta = 0.0017
    before_a = [value.clone() for value in net.A]
    before_g = [value.clone() for value in net.A_gate]
    expected_a = []
    expected_g = []
    for index, hidden in enumerate(clean["hiddens"]):
        base = output_error @ before_a[index].t()
        gate_coefficient = output_error @ before_g[index].t()
        gate = torch.tanh(hidden.detach())
        mean = gate.mean(dim=(2, 3))
        second = gate.square().mean(dim=(2, 3))
        base_prediction = (base + mean * gate_coefficient).t() @ output_error / 2
        gate_prediction = (
            mean * base + second * gate_coefficient).t() @ output_error / 2
        expected_a.append(before_a[index] + eta * (
            diagnostics["target_base"][index] - base_prediction))
        expected_g.append(before_g[index] + eta * (
            diagnostics["target_gate"][index] - gate_prediction))
    vectorizer_subspace_apical_calibration(
        net, x, y, clean, output_error, sigma=1e-6,
        n_directions=1, eta=eta,
        generator=torch.Generator(device="cpu").manual_seed(503))
    update_error = max(float((actual - expected).abs().max())
                       for actual, expected in zip(
                           net.A + net.A_gate, expected_a + expected_g))
    assert update_error < 1e-14

    batchnorm = CIFARSDILResNet(
        depth=8, base_width=2, seed=83, dtype=torch.float64,
        normalization="batchnorm", residual_scale=1.0,
        vectorizer_mode="channel_gated")
    xb = torch.randn(3, 3, 32, 32, dtype=torch.float64)
    yb = torch.tensor([0, 4, 9])
    parameters = (batchnorm.W + batchnorm.gamma + batchnorm.beta
                  + [batchnorm.W_out, batchnorm.b_out])
    for parameter in parameters:
        parameter.requires_grad_(True)
    clean_b = batchnorm.forward(xb, training=True, update_stats=False)
    for hidden in clean_b["hiddens"]:
        hidden.retain_grad()
    F.cross_entropy(clean_b["logits"], yb).backward()
    output_b = (torch.softmax(clean_b["logits"].detach(), dim=1)
                - F.one_hot(yb, 10).to(torch.float64))
    _, diagnostics_b = vectorizer_subspace_apical_calibration(
        batchnorm, xb, yb, clean_b, output_b, sigma=1e-6,
        n_directions=1, eta=0.0,
        generator=torch.Generator(device="cpu").manual_seed(509),
        return_diagnostics=True)
    finite_b = diagnostics_b["directional_derivatives"][0][
        "scaled_directional"]
    exact_b = sum(
        (xb.shape[0] * hidden.grad * direction).sum()
        for hidden, direction in zip(
            clean_b["hiddens"], diagnostics_b["directions"][0]["hidden"]))
    batchnorm_relative = float(
        (finite_b - exact_b).abs() / exact_b.abs().clamp_min(1e-12))
    assert batchnorm_relative < 2e-6
    for parameter in parameters:
        parameter.requires_grad_(False)
    return {
        "vectorizer_subspace_mean_cosine": vectorizer_cosine,
        "vectorizer_subspace_mean_norm_ratio": vectorizer_norm_ratio,
        "vectorizer_vs_coefficient_mse_ratio": variance_ratio,
        "vectorizer_subspace_jvp_relative_error": jvp_relative,
        "vectorizer_subspace_batchnorm_jvp_relative_error": batchnorm_relative,
        "vectorizer_subspace_delta_rule_absolute_error": update_error,
    }


def apical_learning_checks():
    torch.manual_seed(11)
    net = CIFARSDILResNet(depth=8, base_width=2, seed=6)
    x = torch.randn(8, 3, 32, 32)
    y = torch.arange(8) % 10
    clean = net.forward(x, return_cache=True)
    output_signal = (torch.softmax(clean["logits"], dim=1)
                     - F.one_hot(y, 10))
    prediction, _, _ = net.apical_components(
        output_signal, clean["hiddens"], use_residual=True)
    targets = [torch.randn_like(value) * 0.01 for value in prediction]
    before = sum(float((target - value).square().sum())
                 for target, value in zip(targets, prediction))
    net.calibrate_apical(
        output_signal, clean["hiddens"], prediction, targets, eta=0.1)
    after_prediction, _, _ = net.apical_components(
        output_signal, clean["hiddens"], use_residual=True)
    after = sum(float((target - value).square().sum())
                for target, value in zip(targets, after_prediction))
    assert after < before

    gated = CIFARSDILResNet(
        depth=8, base_width=2, seed=6, vectorizer_mode="channel_gated")
    gated_clean = gated.forward(x)
    gated_signal = (torch.softmax(gated_clean["logits"], dim=1)
                    - F.one_hot(y, 10))
    gated_prediction, _, _ = gated.apical_components(
        gated_signal, gated_clean["hiddens"], use_residual=True)
    gated_targets = [torch.randn_like(value) * 0.01 for value in gated_prediction]
    gated_before = sum(float((target - value).square().sum())
                       for target, value in zip(gated_targets, gated_prediction))
    gated.calibrate_apical(
        gated_signal, gated_clean["hiddens"], gated_prediction,
        gated_targets, eta=0.1)
    gated_after_prediction, _, _ = gated.apical_components(
        gated_signal, gated_clean["hiddens"], use_residual=True)
    gated_after = sum(float((target - value).square().sum())
                      for target, value in zip(gated_targets, gated_after_prediction))
    assert gated_after < gated_before
    shifted_hidden = [torch.roll(value, shifts=(3, -2), dims=(2, 3))
                      for value in gated_clean["hiddens"]]
    shifted_instruction, _, _ = gated.apical_components(
        gated_signal, shifted_hidden, use_residual=True)
    original_instruction, _, _ = gated.apical_components(
        gated_signal, gated_clean["hiddens"], use_residual=True)
    assert all(torch.allclose(
        shifted, torch.roll(original, shifts=(3, -2), dims=(2, 3)))
        for shifted, original in zip(shifted_instruction, original_instruction))
    spatial_56 = CIFARSDILResNet(depth=56, vectorizer_mode="spatial_template")
    gated_56 = CIFARSDILResNet(depth=56, vectorizer_mode="channel_gated")
    assert spatial_56.n_vectorizer_parameters == 5_324_800
    assert gated_56.n_vectorizer_parameters == 40_640

    predictor_net = CIFARSDILResNet(depth=8, base_width=2, seed=8)
    hiddens = [torch.randn(64, *shape) for shape in predictor_net.hidden_shapes]
    initial = predictor_net.predictor_step(hiddens, eta=0.1, nuisance_scale=0.5)
    final = initial
    for _ in range(60):
        final = predictor_net.predictor_step(hiddens, eta=0.1, nuisance_scale=0.5)
    assert final < initial * 1e-3

    weights_before = [weight.clone() for weight in net.W]
    result = conv_local_step(
        net, x[:2], y[:2],
        ConvSDILConfig(
            eta=1e-3, eta_A=1e-3, momentum=0.0, weight_decay=0.0,
            pert_every=1),
        step=0, generator=torch.Generator(device="cpu").manual_seed(7))
    assert result["did_perturb"] and result["calibration"] is not None
    assert torch.isfinite(torch.tensor(list(
        value for key, value in result.items()
        if isinstance(value, float) and key != "predictor_mse"))).all()
    assert any(not torch.equal(before_weight, after_weight)
               for before_weight, after_weight in zip(weights_before, net.W))
    assert all(not parameter.requires_grad
               for parameter in net.W + [net.W_out, net.b_out])

    gated_weights_before = [value.clone() for value in gated.A + gated.A_gate]
    gated_result = conv_local_step(
        gated, x[:2], y[:2],
        ConvSDILConfig(
            eta=1e-3, eta_A=1e-3, momentum=0.0, weight_decay=0.0,
            pert_every=1, apical_calibration_mode="channel_subspace"),
        step=0, generator=torch.Generator(device="cpu").manual_seed(17))
    assert gated_result["did_perturb"]
    assert all(torch.isfinite(torch.tensor(value)) for value in
               gated_result["calibration"].values())
    assert any(not torch.equal(before, after) for before, after in zip(
        gated_weights_before, gated.A + gated.A_gate))
    return {"apical_mse_ratio": after / before,
            "gated_apical_mse_ratio": gated_after / gated_before,
            "gated_vectorizer_parameter_reduction": (
                spatial_56.n_vectorizer_parameters
                / gated_56.n_vectorizer_parameters),
            "predictor_mse_ratio": final / initial}


def main():
    architecture_checks()
    perturbation_checks()
    report = exact_local_gradient_check()
    report.update(exact_batchnorm_local_gradient_check())
    report.update(perturbation_estimator_check())
    report.update(channel_subspace_estimator_check())
    report.update(vectorizer_subspace_estimator_check())
    report.update(apical_learning_checks())
    print(report)
    print("ALL CONVOLUTIONAL LOCAL-ELIGIBILITY CHECKS PASSED")


if __name__ == "__main__":
    main()