File size: 9,891 Bytes
d58704b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Generated-data core quickstart: admission, calibration, deep updates, restore.

This is an executable API example and engineering check, not a benchmark.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import sys
import torch
from torch.nn import functional as F

CORE = Path(__file__).resolve().parents[1] / "src"
sys.path.insert(0, str(CORE))
from avenyra_omega import FrozenFeatures, OrthogonalMemory, ResidualMLP, BoundedResidualClassifier
from avenyra_omega.calibration import acquisition_scores
from avenyra_omega.renewal import FreshRiskController


def old_distribution(seed, count_per_class=256):
    generator = torch.Generator().manual_seed(seed)
    y = torch.arange(2).repeat_interleave(count_per_class)
    x = .015 * torch.randn(len(y), 8, generator=generator)
    x[:, 0] += torch.where(y == 0, -torch.ones(len(y)), torch.ones(len(y))) * 3.
    return x, y


def construct():
    features = FrozenFeatures(8, kind="linear", seed=7000)
    memory = OrthogonalMemory(features.feature_dim, 3, feature_signature=features.signature,
                              failure_budget=.05)
    raw = ResidualMLP(8, 3, width=24)
    return features, memory, raw


def tree_equal(a, b):
    if torch.is_tensor(a):
        return torch.equal(a, b)
    if isinstance(a, dict):
        return a.keys() == b.keys() and all(tree_equal(a[k], b[k]) for k in a)
    if isinstance(a, (list, tuple)):
        return len(a) == len(b) and all(tree_equal(x, y) for x, y in zip(a, b))
    return a == b


def run(output):
    output = Path(output)
    output.mkdir(parents=True, exist_ok=False)
    torch.set_num_threads(1)
    torch.manual_seed(7000)
    features, memory, raw = construct()
    fit_x, fit_y = old_distribution(7001, 128)
    # Acquisition reference, center and feature map are fixed using ONLY this fit split.
    proposal = memory.ridge_proposal(features(fit_x), F.one_hot(fit_y, 3).double(), ridge=.001)
    admission = memory.admit(proposal, residual_radius=0., label="initial old-class center")
    assert admission["status"] == "ACCEPTED"
    calibration_x, calibration_y = old_distribution(7002, 256)
    certificates = []
    for cls in (0, 1):
        z = features(calibration_x[calibration_y == cls])
        reference_logits, power = memory.center_and_power(z)
        scores = acquisition_scores(reference_logits, reference_logits, power)
        certificate = memory.calibrate_acquisition(scores, task=cls, risk=.05,
            failure_probability=.025, independent_calibration=True, stratum=f"old_class{cls}",
            distribution="independent generated old-class Gaussian", reference_id="fit-only initial center")
        if certificate.status != "CONDITIONAL":
            raise RuntimeError("This example did not obtain a positive radius; failed attempt remains registered")
        memory.add_certificate(certificate)
        certificates.append(certificate.to_dict())
    assert len(memory.calibration_attempts) == 2 and memory.check_confidence_budget() == .05
    model = BoundedResidualClassifier(features, memory, raw, radius=0.)
    radius = model.set_certified_radius(.6)
    assert radius > 0
    signature = features.validate_signature()
    # Every raw-network parameter is mutable; there is no projected-head-only update.
    assert all(p.requires_grad for p in raw.parameters())
    initial_raw = {name: p.detach().clone() for name, p in raw.named_parameters()}
    generator = torch.Generator().manual_seed(7004)
    new_x = .03 * torch.randn(192, 8, generator=generator)
    new_x[:, 1] += 3.
    new_y = torch.full((len(new_x),), 2, dtype=torch.long)
    optimizer = torch.optim.Adam(raw.parameters(), lr=.02)
    losses = []
    max_residual_bound_excess = -float("inf")
    for _ in range(40):
        optimizer.zero_grad(set_to_none=True)
        prediction, parts = model(new_x, return_parts=True)
        excess = float((parts["residual"].detach().norm(dim=1) - radius * parts["power"]).max())
        max_residual_bound_excess = max(max_residual_bound_excess, excess)
        loss = F.cross_entropy(prediction, new_y)
        loss.backward()
        optimizer.step()
        losses.append(float(loss.detach()))
    assert max_residual_bound_excess <= 1e-12
    assert features.validate_signature() == signature
    motion = {name: float((p.detach() - initial_raw[name]).norm()) for name, p in raw.named_parameters()}
    assert all(value > 0 for value in motion.values())
    evaluation_x, evaluation_y = old_distribution(7003, 512)
    with torch.no_grad():
        reference = memory.center_and_power(features(evaluation_x))[0].argmax(1)
        final_old = model(evaluation_x).argmax(1)
        old_accuracy = float((final_old == evaluation_y).double().mean())
        old_reference_flip = float((final_old != reference).double().mean())
        new_accuracy = float((model(new_x).argmax(1) == new_y).double().mean())
        probe = torch.cat((evaluation_x[:32], new_x[:32]))
        before_restore = model(probe).clone()
    checkpoint = output / "full_checkpoint.pt"
    torch.save({"model": model.state_dict(), "optimizer": optimizer.state_dict(),
        "torch_rng_state": torch.get_rng_state(), "configuration": {
            "feature_kind": "linear", "input_dim": 8, "classes": 3, "width": 24,
            "fit_seed": 7001, "calibration_seed": 7002, "evaluation_seed": 7003, "new_fit_seed": 7004}}, checkpoint)
    restored_features, restored_memory, restored_raw = construct()
    restored = BoundedResidualClassifier(restored_features, restored_memory, restored_raw, radius=0.)
    loaded = torch.load(checkpoint, map_location="cpu", weights_only=True)
    restored.load_state_dict(loaded["model"])
    restored_optimizer = torch.optim.Adam(restored.raw_model.parameters(), lr=.02)
    restored_optimizer.load_state_dict(loaded["optimizer"])
    torch.set_rng_state(loaded["torch_rng_state"])
    assert torch.equal(before_restore, restored(probe).detach())
    assert tree_equal(optimizer.state_dict(), restored_optimizer.state_dict())
    assert len(restored.memory.calibration_attempts) == 2 and len(restored.memory.certificates) == 2
    # A matched extra step verifies that restored optimizer moments are operational.
    for candidate, opt in ((model, optimizer), (restored, restored_optimizer)):
        opt.zero_grad(set_to_none=True)
        F.cross_entropy(candidate(new_x), new_y).backward()
        opt.step()
    assert torch.equal(model(probe).detach(), restored(probe).detach())

    # Separate fresh-checkpoint controller: labels, not old-teacher predictions.
    fresh = FreshRiskController(failure_budget=.05)
    fresh_events = []
    for attempt, invert in enumerate((False, True)):
        evidence_x, evidence_y = old_distribution(8001 + attempt, 256)
        # Both candidate functions are predeclared before their evidence is drawn.
        predicted = (evidence_x[:, 0] > 0).long()
        if invert:
            predicted = 1 - predicted
        blocks = {}
        for cls in (0, 1):
            mask = evidence_y == cls
            blocks[f"class{cls}"] = {"errors": (predicted[mask] != evidence_y[mask]).numpy(),
                "source_ids": (torch.arange(256) + 100000 + attempt * 1000 + cls * 256).numpy()}
        event = fresh.evaluate_candidate(blocks, candidate_id="good_fixed_rule" if not invert else "inverted_fixed_rule",
            risk=.05, failure_probability=.01, fixed_before_evidence=True, required_strata=blocks.keys())
        fresh_events.append(event)
    assert [event["status"] for event in fresh_events] == ["ACCEPTED", "REFUSED"]
    assert fresh.deployed_candidate == "good_fixed_rule" and len(fresh.used_ids) == 1024
    fresh_copy = FreshRiskController(failure_budget=.05)
    fresh_copy.load_state_dict(fresh.state_dict())
    assert fresh_copy.state_dict() == fresh.state_dict()
    (output / "fresh_controller.json").write_text(json.dumps(fresh.state_dict(), indent=2) + "\n")
    report = {"scope": "Generated-data API and engineering example; no benchmark superiority or exact floating-point population guarantee",
        "initial_admission": admission, "registered_calibration_attempts": len(memory.calibration_attempts),
        "confidence_spent": memory.check_confidence_budget(), "certificates": certificates,
        "configured_residual_radius": radius, "all_raw_parameters_trainable": True,
        "raw_parameter_motion_by_tensor": motion, "frozen_feature_signature_unchanged": True,
        "new_fit_loss_first": losses[0], "new_fit_loss_last": losses[-1], "new_fit_accuracy": new_accuracy,
        "independent_old_evaluation_accuracy": old_accuracy, "independent_old_reference_flip_rate": old_reference_flip,
        "max_observed_residual_bound_excess": max_residual_bound_excess,
        "checkpoint_prediction_roundtrip_exact": True, "optimizer_roundtrip_exact": True,
        "matched_resume_step_exact": True, "checkpoint_file_bytes": checkpoint.stat().st_size,
        "fresh_controller_statuses": [event["status"] for event in fresh_events],
        "fresh_controller_deployed_after_refusal": fresh.deployed_candidate,
        "fresh_controller_confidence_spent_including_refusal": fresh.confidence_spent,
        "fresh_controller_unique_evidence_sources": len(fresh.used_ids),
        "fresh_controller_checkpoint_roundtrip_exact": True,
        "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        "core_source_sha256": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted((CORE / "avenyra_omega").glob("*.py"))}}
    (output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
    return report


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    print(json.dumps(run(args.output), indent=2))