File size: 7,740 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Independently check IDX -> MLP -> predictions -> report and a training mutation."""

import csv
import html
import json
import math
import random
import re
import shutil
import struct
import subprocess
import sys
import tempfile
from pathlib import Path


def load_idx(root):
    image_bytes = (root / "train-images-idx3-ubyte").read_bytes()
    label_bytes = (root / "train-labels-idx1-ubyte").read_bytes()
    magic, count, rows, cols = struct.unpack_from(">IIII", image_bytes)
    label_magic, label_count = struct.unpack_from(">II", label_bytes)
    assert (magic, label_magic) == (2051, 2049)
    assert count == label_count == 10 and (rows, cols) == (8, 8)
    assert len(image_bytes) == 16 + count * rows * cols
    assert len(label_bytes) == 8 + label_count
    images = [[pixel / 255 for pixel in image_bytes[16 + i * 64:16 + (i + 1) * 64]]
              for i in range(count)]
    return images, list(label_bytes[8:])


def matrix(value, rows, cols, name):
    assert isinstance(value, list) and len(value) == rows, f"{name} rows"
    for row in value:
        assert isinstance(row, list) and len(row) == cols, f"{name} columns"
        assert all(type(x) in (int, float) and math.isfinite(x) for x in row), f"{name} finite values"


def vector(value, size, name):
    assert isinstance(value, list) and len(value) == size, f"{name} size"
    assert all(type(x) in (int, float) and math.isfinite(x) for x in value), f"{name} finite values"


def load_model(root):
    model = json.loads((root / "model.json").read_text(encoding="utf-8"))
    assert {"w1", "b1", "w2", "b2"} <= set(model), 'model is missing required weights'
    matrix(model["w1"], 16, 64, "w1")
    vector(model["b1"], 16, "b1")
    matrix(model["w2"], 2, 16, "w2")
    vector(model["b2"], 2, "b2")
    assert any(abs(x) > 1e-9 for row in model["w1"] for x in row), "empty hidden layer"
    assert any(abs(x) > 1e-9 for row in model["w2"] for x in row), "empty output layer"
    return model


def logits(model, image):
    hidden = [max(0.0, sum(w * x for w, x in zip(row, image)) + bias)
              for row, bias in zip(model["w1"], model["b1"])]
    return [sum(w * h for w, h in zip(row, hidden)) + bias
            for row, bias in zip(model["w2"], model["b2"])]


def predict(model, image):
    scores = logits(model, image)
    return int(scores[1] > scores[0])


def metrics(pairs):
    accuracy = sum(truth == pred for truth, pred in pairs) / len(pairs)
    scores = []
    for label in (0, 1):
        tp = sum(truth == label and pred == label for truth, pred in pairs)
        fp = sum(truth != label and pred == label for truth, pred in pairs)
        fn = sum(truth == label and pred != label for truth, pred in pairs)
        scores.append(2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0)
    return accuracy, sum(scores) / 2


def check(root):
    images, labels = load_idx(root)
    model = load_model(root)
    indices = list(range(len(images)))
    random.Random(1).shuffle(indices)
    validation = indices[int(0.8 * len(indices)):]
    with (root / "predictions.csv").open(newline="", encoding="utf-8") as handle:
        reader = csv.DictReader(handle)
        assert reader.fieldnames == ["index", "true_label", "predicted_label"]
        rows = list(reader)
    assert len(rows) == len(validation), "validation row count"
    pairs = []
    for row, index in zip(rows, validation):
        assert int(row["index"]) == index, "validation index/order mismatch"
        truth, predicted = int(row["true_label"]), int(row["predicted_label"])
        assert truth == labels[index], "IDX label mismatch"
        assert predicted == predict(model, images[index]), "prediction disagrees with model forward pass"
        pairs.append((truth, predicted))
    accuracy, macro_f1 = metrics(pairs)
    report = (root / "report.html").read_text(encoding="utf-8")
    visible = html.unescape(re.sub(r'<[^>]+>', ' ', report))
    assert re.search(r"64\s*(?:inputs|输入|→|->)", visible, re.I)
    assert re.search(r"16\s*(?:个\s*)?ReLU", visible, re.I)
    assert re.search(r"(?:seed|种子)\s*[:=:]?\s*1", visible, re.I)
    assert re.search(r"(?:train|训练(?:样本)?(?:数)?)\s*[:=:]?\s*8", visible, re.I)
    assert re.search(r"(?:validation|验证(?:样本)?(?:数)?)\s*[:=:]?\s*2", visible, re.I)
    for label, expected in ((r"accuracy", accuracy), (r"macro\s*f1", macro_f1)):
        match = re.search(label + r"\s*[:=:]\s*(0(?:\.\d+)?|1(?:\.0+)?)", visible, re.I)
        assert match, f"report missing {label} metric"
        assert abs(float(match.group(1)) - expected) <= 1e-5, f"report {label} disagrees with predictions"
    # Each embedded 8x8 SVG preview must actually depict a bundled sample.
    figures = re.findall(r"<figure\b[^>]*>(.*?)</figure>", report, flags=re.I | re.S)
    assert len(figures) >= 2, "show at least two sample images"
    preview_indices = set()
    for figure in figures[:2]:
        match = re.search(r"index\s+(\d+)\s*,\s*label\s+(\d+)", figure, re.I)
        assert match, "sample preview lacks index and label"
        index, label = map(int, match.groups())
        preview_indices.add(index)
        assert 0 <= index < len(images) and label == labels[index]
        fills = re.findall(r"fill\s*=\s*['\"]rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)['\"]", figure)
        assert len(fills) == 64, "sample preview must contain all 64 pixels"
        expected = [255 - round(pixel * 255) for pixel in images[index]]
        assert [tuple(map(int, triplet)) for triplet in fills] == [(x, x, x) for x in expected], (
            "sample preview does not match IDX pixels"
        )
    assert len(preview_indices) >= 2, 'preview at least two distinct input samples'
    return model


def functional_change(before, after, examples):
    # Compare logit differences from the actual forward pass. Training may
    # change confidence even if the predicted classes all remain the same.
    for example in examples:
        original = logits(before, example)
        updated = logits(after, example)
        if not math.isclose(original[1] - original[0], updated[1] - updated[0],
                            rel_tol=0, abs_tol=1e-12):
            return True
    return False


def run_mutation(root, baseline_model):
    with tempfile.TemporaryDirectory(prefix="task45-mutation-") as tmp:
        work = Path(tmp) / "candidate"
        shutil.copytree(root, work, ignore=shutil.ignore_patterns("tests", "logs", "*.pyc", "__pycache__"))
        labels_path = work / "train-labels-idx1-ubyte"
        data = bytearray(labels_path.read_bytes())
        indices = list(range(10))
        random.Random(1).shuffle(indices)
        for affected in (indices[:1], indices[:8]):
            updated = bytearray(data)
            for index in affected:
                updated[8 + index] = 1 - updated[8 + index]
            labels_path.write_bytes(updated)
            for name in ("report.html", "predictions.csv", "model.json"):
                (work / name).unlink(missing_ok=True)
            result = subprocess.run([sys.executable, "solve.py"], cwd=work, capture_output=True,
                                    text=True, timeout=45)
            assert result.returncode == 0, f"candidate failed modified input: {result.stderr}"
            updated_model = check(work)
            images, _ = load_idx(work)
            if functional_change(baseline_model, updated_model, images):
                return
        raise AssertionError("training-label changes affected no model logit differences")

if __name__ == "__main__":
    root = Path.cwd()
    baseline = check(root)
    run_mutation(root, baseline)
    print("MLP contract and input-mutation checks passed")