File size: 6,500 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
#!/usr/bin/env python3
"""Check the sample PNG pixels and serialized MLP predictions independently."""

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


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


def read_png(path):
    with Image.open(path) as image:
        assert image.format == 'PNG' and image.mode == 'L' and image.size == (40, 8), 'expected a 40x8 8-bit grayscale PNG'
        image.load()
        return [[image.getpixel((x, y)) for x in range(40)] for y in range(8)]


def finite_vector(value, length):
    assert isinstance(value, list) and len(value) == length
    assert all(type(v) in (int, float) and math.isfinite(v) for v in value)


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


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


def check(root):
    images, labels = idx(root)
    rows = read_png(root / "mnist_samples.png")
    for y in range(8):
        assert rows[y] == [value for image in images[:5] for value in image[y * 8:(y + 1) * 8]], (
            "sample PNG pixels differ from source IDX images"
        )
    model = json.loads((root / "model.json").read_text(encoding="utf-8"))
    assert {"w1", "b1", "w2", "b2"} <= set(model)
    assert len(model["w1"]) == 16 and len(model["w2"]) == 2
    for row in model["w1"]:
        finite_vector(row, 64)
    for row in model["w2"]:
        finite_vector(row, 16)
    finite_vector(model["b1"], 16)
    finite_vector(model["b2"], 2)
    assert any(abs(v) > 1e-9 for row in model["w1"] for v in row)
    assert any(abs(v) > 1e-9 for row in model["w2"] for v in row)
    order = list(range(10))
    random.Random(1).shuffle(order)
    validation = order[8:]
    with (root / "predictions.csv").open(newline="", encoding="utf-8") as handle:
        reader = csv.DictReader(handle)
        assert reader.fieldnames == ["index", "true_label", "predicted_label"]
        predictions = list(reader)
    assert len(predictions) == 2
    for row, sample in zip(predictions, validation):
        assert int(row["index"]) == sample and int(row["true_label"]) == labels[sample]
        assert int(row["predicted_label"]) == model_predict(model, images[sample])
    accuracy = sum(int(row["true_label"]) == int(row["predicted_label"]) for row in predictions) / 2
    report = (root / "report.html").read_text(encoding="utf-8")
    assert re.search(r'<img[^>]+src=["\']mnist_samples\.png["\']', report, re.I)
    text = unescape(re.sub(r'<[^>]+>', ' ', report))
    assert re.search(r"80\s*/\s*20|80\s*%[^;]*20\s*%", text)
    assert re.search(r"\b8\s*/\s*2\b|(?:train|训练)(?:\s*(?:samples|样本数?))?\s*[:=:]\s*8.*(?:validation|验证)(?:\s*(?:samples|样本数?))?\s*[:=:]\s*2", text, re.I | re.S)
    assert re.search(r"MLP|network|网络", text, re.I)
    match = re.search(r"(?:validation\s+accuracy|验证准确率)\s*[:=:]\s*(0(?:\.\d+)?|1(?:\.0+)?)", text, re.I)
    assert match and abs(float(match.group(1)) - accuracy) <= 5e-4, "report accuracy mismatch"
    return model, rows


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 mutation(root, baseline_model, baseline_png):
    with tempfile.TemporaryDirectory(prefix="task49-mutated-") as tmp:
        work = Path(tmp) / "candidate"
        shutil.copytree(root, work, ignore=shutil.ignore_patterns("tests", "logs", "__pycache__", "*.pyc"))
        order = list(range(10))
        random.Random(1).shuffle(order)
        labels_path = work / "train-labels-idx1-ubyte"
        label_bytes = bytearray(labels_path.read_bytes())
        image_path = work / "train-images-idx3-ubyte"
        image_bytes = bytearray(image_path.read_bytes())
        # Change a validation image that appears in the montage. The training
        # inputs remain identical while the label response is measured.
        offset = 16 + order[8] * 64
        image_bytes[offset] = 255 - image_bytes[offset]
        image_path.write_bytes(image_bytes)
        originals, _ = idx(root)
        for affected in (order[:1], order[:8]):
            updated_label_bytes = bytearray(label_bytes)
            for index in affected:
                updated_label_bytes[8 + index] = 1 - updated_label_bytes[8 + index]
            labels_path.write_bytes(updated_label_bytes)
            for name in ("model.json", "predictions.csv", "mnist_samples.png", "report.html"):
                (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 changed input: {result.stderr}"
            updated_model, updated_png = check(work)
            assert updated_png != baseline_png, "sample PNG did not respond to changed input pixel"
            if functional_change(baseline_model, updated_model, originals):
                return
        raise AssertionError("training-label changes affected no model logit differences")

if __name__ == "__main__":
    root = Path.cwd()
    model, png = check(root)
    mutation(root, model, png)
    print("MLP, PNG and changed-input checks passed")