File size: 6,282 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 | """Instruction-derived deterministic checks for Task 45."""
import html
import os
import pathlib
import re
import shutil
import struct
import subprocess
import tempfile
ROOT = pathlib.Path.cwd()
IMAGE_FILE = ROOT / "train-images-idx3-ubyte"
LABEL_FILE = ROOT / "train-labels-idx1-ubyte"
report_raw = (ROOT / "report.html").read_text(encoding="utf-8", errors="ignore")
report = html.unescape(report_raw).casefold()
source = "\n".join(
path.read_text(encoding="utf-8", errors="ignore")
for path in sorted(ROOT.rglob("*.py"))
if "tests" not in path.parts and "logs" not in path.parts
).casefold()
def labeled_values(text, labels):
joined = "|".join(labels)
pattern = rf"(?:{joined})[^0-9]{{0,40}}(0(?:\.\d+)?|1(?:\.0+)?)"
return [float(value) for value in re.findall(pattern, text)]
def has_labeled_count(text, labels, value):
joined = "|".join(labels)
after = rf"(?:{joined})[^0-9]{{0,30}}{value}(?!\d)"
before = rf"(?<!\d){value}[^0-9]{{0,30}}(?:{joined})"
return bool(re.search(after, text) or re.search(before, text))
image_header = IMAGE_FILE.read_bytes()[:16]
label_header = LABEL_FILE.read_bytes()[:8]
magic, count, rows, cols = struct.unpack(">IIII", image_header)
label_magic, label_count = struct.unpack(">II", label_header)
# ENHANCED_CASE_1: validate complete IDX framing. Pixel-accurate sample
# visualization and the MLP contract are checked in validate_contract.py.
def enhanced_case_1():
assert magic == 2051 and label_magic == 2049, "invalid bundled IDX magic numbers"
assert count == label_count and count > 0, "IDX image/label counts disagree"
assert IMAGE_FILE.stat().st_size == 16 + count * rows * cols, (
"IDX image payload length does not match its header"
)
assert LABEL_FILE.stat().st_size == 8 + label_count, (
"IDX label payload length does not match its header"
)
assert "mnist" in report, "report does not identify the loaded MNIST fixture"
# ENHANCED_CASE_2: the fixed ten-sample fixture implies an 8/2 split. Validate
# observable report values and implementation evidence for 80/20, seed(1), and
# an applied transform without requiring a particular ML library.
def enhanced_case_2():
expected_train = int(count * 0.8)
expected_validation = count - expected_train
assert re.search(r"80\s*(?:%|/\s*20)|0\.8|4\s*:\s*1", report), (
"report does not state the required 80/20 split"
)
assert has_labeled_count(report, ("train", "训练"), expected_train), (
f"report does not state the fixture-derived training count {expected_train}"
)
assert has_labeled_count(report, ("validation", "valid", "val", "验证"), expected_validation), (
f"report does not state the fixture-derived validation count {expected_validation}"
)
assert re.search(r"(?:seed|random_state)\s*(?:\(|=|:)?\s*1(?!\d)", report), (
"implementation/report does not identify seed(1) or random_state=1"
)
assert re.search(r"transform|normaliz|标准化|归一化|scale", report), (
"implementation/report lacks an applied transform or normalization"
)
# ENHANCED_CASE_3: seed(1) must make final reported metrics reproducible. Run
# the candidate again in a clean isolated directory and compare labeled acc/F1
# values, without prescribing the reference's classifier or an ML framework.
def enhanced_case_3():
baseline_accuracy = labeled_values(report, ("accuracy", "acc", "准确率"))
baseline_f1 = labeled_values(report, ("macro[ _-]?f1", "f1(?:[ _-]?score)?"))
assert baseline_accuracy and baseline_f1, "report lacks labeled final accuracy and F1 values"
py_files = sorted(
path for path in ROOT.rglob("*.py")
if "tests" not in path.parts and "logs" not in path.parts
)
assert py_files, "no candidate Python program found"
main_py = py_files[0]
for path in py_files:
if any(token in path.name.casefold() for token in ("analysis", "example", "transform", "main")):
main_py = path
break
with tempfile.TemporaryDirectory(prefix="task45_case3_") as tmp_name:
work = pathlib.Path(tmp_name) / "work"
shutil.copytree(
ROOT,
work,
ignore=shutil.ignore_patterns("tests", "logs", "*.pyc", "__pycache__"),
)
(work / "report.html").unlink(missing_ok=True)
env = os.environ.copy()
for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"):
env.pop(key, None)
env["PYTHONHASHSEED"] = "1"
subprocess.run(
["python3", str(main_py.relative_to(ROOT))], cwd=work, env=env,
timeout=60, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
)
rerun_path = work / "report.html"
assert rerun_path.is_file() and rerun_path.stat().st_size > 0, (
"isolated rerun did not emit report.html"
)
rerun = html.unescape(rerun_path.read_text(encoding="utf-8", errors="ignore")).casefold()
rerun_accuracy = labeled_values(rerun, ("accuracy", "acc", "准确率"))
rerun_f1 = labeled_values(rerun, ("macro[ _-]?f1", "f1(?:[ _-]?score)?"))
assert rerun_accuracy and rerun_f1, "isolated rerun lost labeled final metrics"
assert baseline_accuracy == rerun_accuracy, (
f"accuracy is not reproducible with seed(1): {baseline_accuracy} vs {rerun_accuracy}"
)
assert baseline_f1 == rerun_f1, (
f"F1 is not reproducible with seed(1): {baseline_f1} vs {rerun_f1}"
)
all_cases = (
("ENHANCED_CASE_1", enhanced_case_1),
("ENHANCED_CASE_2", enhanced_case_2),
("ENHANCED_CASE_3", enhanced_case_3),
)
selected = os.environ.get("ENHANCED_CASE")
assert selected is None or selected in dict(all_cases), f"unknown ENHANCED_CASE: {selected}"
failures = []
for case_id, validator in all_cases:
if selected and case_id != selected:
continue
try:
validator()
print(f"PASS {case_id}")
except Exception as error: # keep cases independently executable/reportable
failures.append((case_id, error))
print(f"FAIL {case_id}: {error}")
assert not failures, f"{len(failures)} enhanced case(s) failed"
|