File size: 11,699 Bytes
0784852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""CPU/FP64 identity check for shared/untied complete Transformer Jacobians.

No scientific training, dataset, checkpoint, or active experiment is accessed.
Two fixed token-logit scalars provide a cross-input Jacobian kernel. Actual
parameter identity determines aliases, including MLP-only sharing; the tied
input/output embedding is differentiated once with both computational paths.
Small plain-SGD steps below are finite-difference checks on disposable copies,
not claims about AdamW, generalization, or learning efficiency.
"""

from __future__ import annotations

import argparse
import copy
import hashlib
import json
import platform
import sys
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT / "src"))

import torch  # noqa: E402
import transformers  # noqa: E402

from llm_memory_editability.loop_learning import construct  # noqa: E402

SEED = 20261007
TOLERANCE = 1e-10
SGD_STEPS = (1e-4, 5e-5, 2.5e-5)
SPEC = {
    "initialization": SEED,
    "base_unique_blocks": 1,
    "repeats": 2,
    "initialization_reference_layers": 8,
    "model": {
        "vocab_size": 11,
        "positions": 16,
        "hidden_size": 8,
        "attention_heads": 2,
        "dropout": 0.0,
    },
}
OUTPUTS = {
    "query": {"tokens": [[1, 4, 2]], "position": 2, "token_logit": 7},
    "train": {"tokens": [[3, 1, 5]], "position": 2, "token_logit": 4},
}


def scalar_output(model, name):
    setting = OUTPUTS[name]
    tokens = torch.tensor(setting["tokens"], dtype=torch.long)
    return model(tokens)[0, setting["position"], setting["token_logit"]]


def scalar_jacobian(model, name):
    parameters = dict(model.named_parameters())
    output = scalar_output(model, name)
    gradients = torch.autograd.grad(output, tuple(parameters.values()))
    return float(output.detach()), {
        key: gradient.detach().clone() for key, gradient in zip(parameters, gradients, strict=True)
    }


def dot(left, right):
    return sum(float((left[key] * right[key]).sum()) for key in left)


def max_abs(value):
    return float(value.abs().max())


def parameter_aliases(model, untied):
    """Map each actual unique parameter to its independent execution copies."""
    unique = dict(model.named_parameters())
    names = {id(parameter): name for name, parameter in unique.items()}
    aliases = {name: [] for name in unique}
    for name, parameter in unique.items():
        if not name.startswith("transformer.h."):
            aliases[names[id(parameter)]].append(name)
    occurrence = 0
    for _ in range(model.repeats):
        for block in model.transformer.h:
            for name, parameter in block.named_parameters():
                aliases[names[id(parameter)]].append(f"transformer.h.{occurrence}.{name}")
            occurrence += 1
    independent = dict(untied.named_parameters())
    flattened = [alias for group in aliases.values() for alias in group]
    if len(flattened) != len(set(flattened)) or set(flattened) != set(independent):
        raise AssertionError("Alias groups must partition all independent parameters")
    for name, group in aliases.items():
        if not group or any(not torch.equal(unique[name], independent[alias]) for alias in group):
            raise AssertionError(f"Alias weights differ at common forward point: {name}")
    return aliases


def check_kernel(model, untied, reference, arm):
    aliases = parameter_aliases(model, untied)
    scalar_values, gradients = {}, {}
    gradient_errors = {}
    for output in OUTPUTS:
        scalar_values[output], gradients[output] = scalar_jacobian(model, output)
        errors = {}
        for name, group in aliases.items():
            expected = torch.stack([reference[output][alias] for alias in group]).sum(0)
            errors[name] = max_abs(gradients[output][name] - expected)
        gradient_errors[output] = errors

    common, diagonal, cross = 0.0, 0.0, 0.0
    for group in aliases.values():
        for left in group:
            for right in group:
                value = float((reference["query"][left] * reference["train"][right]).sum())
                if not left.startswith("transformer.h."):
                    if left != right:
                        raise AssertionError("Common parameters must occur exactly once")
                    common += value
                elif left == right:
                    diagonal += value
                else:
                    cross += value
                    if arm == "mlp_shared" and not (".mlp." in left and ".mlp." in right):
                        raise AssertionError("MLP-only sharing introduced a non-MLP cross term")

    actual = dot(gradients["query"], gradients["train"])
    independent_actual = dot(reference["query"], reference["train"])
    errors = {
        "scalar_jacobian_vs_alias_sum_max_abs": max(
            max(values.values()) for values in gradient_errors.values()
        ),
        "kernel_vs_common_plus_diagonal_plus_cross_abs": abs(actual - common - diagonal - cross),
        "untied_kernel_vs_common_plus_diagonal_abs": abs(independent_actual - common - diagonal),
        "kernel_difference_vs_cross_terms_abs": abs(actual - independent_actual - cross),
    }
    if not all(error < TOLERANCE for error in errors.values()):
        raise AssertionError(errors)
    embedding = "transformer.wte.weight"
    return {
        "arm": arm,
        "scalar_outputs": scalar_values,
        "unique_parameters": sum(parameter.numel() for parameter in model.parameters()),
        "parameter_aliases": aliases,
        "kernel": actual,
        "untied_kernel": independent_actual,
        "common_parameter_kernel": common,
        "common_tied_embedding_kernel": float(
            (reference["query"][embedding] * reference["train"][embedding]).sum()
        ),
        "block_diagonal_kernel": diagonal,
        "block_cross_call_kernel": cross,
        "per_parameter_jacobian_errors": gradient_errors,
        "errors": errors,
        "passed": True,
    }, gradients


def check_plain_sgd(model, gradients, kernel):
    """Check Eq. 26 for 1/2 * (one train logit - 0.5)**2 loss."""
    before = float(scalar_output(model, "query").detach())
    derivative = float(scalar_output(model, "train").detach()) - 0.5
    parameters = dict(model.named_parameters())
    direction = {name: -derivative * gradient for name, gradient in gradients["train"].items()}
    direct_derivative = dot(gradients["query"], direction)
    derivative_error = abs(direct_derivative + derivative * kernel)
    if derivative_error >= TOLERANCE:
        raise AssertionError({"SGD_first_derivative_error": derivative_error})
    records = []
    for step in SGD_STEPS:
        disposable = copy.deepcopy(model)
        with torch.no_grad():
            for name, parameter in disposable.named_parameters():
                parameter.copy_(parameters[name] + step * direction[name])
            change = float(scalar_output(disposable, "query")) - before
        prediction = step * direct_derivative
        residual = abs(change - prediction)
        records.append(
            {
                "step_size": step,
                "actual_query_logit_change": change,
                "kernel_first_order_change": prediction,
                "absolute_taylor_remainder": residual,
                "absolute_remainder_divided_by_step_squared": residual / step**2,
            }
        )
    ratios = [
        records[index]["absolute_taylor_remainder"]
        / records[index + 1]["absolute_taylor_remainder"]
        for index in range(len(records) - 1)
    ]
    # A halved step has quarter-sized quadratic error. These bounds only assess
    # the fixed, nondegenerate tiny numerical example; they are not a proof of
    # a global remainder bound or a rule for selecting a training learning rate.
    passed = all(3.0 < ratio < 5.0 for ratio in ratios)
    if not passed:
        raise AssertionError({"finite_difference_records": records, "ratios": ratios})
    return {
        "loss": "0.5 * (selected train token logit - 0.5)**2",
        "optimizer": "plain SGD, no momentum, clipping, decay or optimizer state",
        "kernel_directional_derivative_error": derivative_error,
        "steps": records,
        "remainder_ratio_when_step_halved": ratios,
        "accepted_ratio_interval": [3.0, 5.0],
        "passed": passed,
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=Path(__file__).with_suffix(".json"))
    args = parser.parse_args()
    torch.set_num_threads(1)
    torch.manual_seed(SEED)
    models = {
        arm: construct({**SPEC, "arm": arm}, "cpu").double().eval()
        for arm in ("shared", "untied", "mlp_shared")
    }
    untied = models["untied"]
    reference = {name: scalar_jacobian(untied, name)[1] for name in OUTPUTS}
    with torch.no_grad():
        tokens = torch.tensor([OUTPUTS[name]["tokens"][0] for name in OUTPUTS])
        baseline = untied(tokens)
        forward_errors = {arm: max_abs(model(tokens) - baseline) for arm, model in models.items()}
    if not all(error < TOLERANCE for error in forward_errors.values()):
        raise AssertionError(forward_errors)
    checks = {}
    for arm, model in models.items():
        check, gradients = check_kernel(model, untied, reference, arm)
        check["plain_sgd_taylor_check"] = check_plain_sgd(model, gradients, check["kernel"])
        checks[arm] = check
    files = [
        Path(__file__),
        ROOT / "src/llm_memory_editability/loop_learning.py",
        ROOT / "src/llm_memory_editability/grokking_reproduction.py",
    ]
    result = {
        "created_utc": datetime.now(timezone.utc).isoformat(),
        "purpose": "Independent numerical verification of theory Eq. 24-26; no science run changes",
        "device": "cpu",
        "dtype": "torch.float64",
        "python": platform.python_version(),
        "torch": torch.__version__,
        "transformers": transformers.__version__,
        "spec": SPEC,
        "scalar_selections": OUTPUTS,
        "absolute_error_tolerance": TOLERANCE,
        "initial_full_logits_max_abs_errors": forward_errors,
        "checks": checks,
        "source_sha256": {
            str(path.relative_to(ROOT)): hashlib.sha256(path.read_bytes()).hexdigest()
            for path in files
        },
        "passed": True,
        "limits": (
            "Tiny randomly initialized complete ReproductionGPT with causal attention, "
            "GELU MLP, residual paths, LayerNorm and tied input/output embedding. "
            "Kernel identities hold at the shared common-function point. Finite-difference "
            "steps use a fixed scalar squared loss and disposable CPU copies. No claim "
            "about AdamW dynamics, knowledge quality, generalization, sample efficiency, "
            "grokking, scientific training completion or an active GPU run is tested."
        ),
    }
    args.output.write_text(json.dumps(result, indent=2) + "\n")
    print(
        json.dumps(
            {
                "passed": True,
                "output": str(args.output),
                "absolute_error_tolerance": TOLERANCE,
                "initial_forward_errors": forward_errors,
                "kernel_errors": {arm: check["errors"] for arm, check in checks.items()},
                "quadratic_remainder_ratios": {
                    arm: check["plain_sgd_taylor_check"]["remainder_ratio_when_step_halved"]
                    for arm, check in checks.items()
                },
            },
            indent=2,
        )
    )


if __name__ == "__main__":
    main()