File size: 7,703 Bytes
863963d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compare Core AI choice probabilities with the pinned upstream D3 Lite CPU reference."""

import argparse
import asyncio
import json
import resource
import statistics
import subprocess
import sys
import time
from pathlib import Path

import numpy as np

from validation_cases import CASES

ACTIONS = {
    "interrupt": "Stop or correct an active reply immediately.",
    "discard": "Clear noise or an acknowledgement that needs no answer.",
    "enqueue": "Complete input to handle next. Choose this when uncertain.",
    "continue_listening": "The user clearly has not finished speaking.",
}
DUPLEX = [
    ("zh_hold", "助手空闲。最新用户输入:帮我定一个", "continue_listening"),
    ("zh_join", "助手空闲。最新用户输入:帮我定一个\n明早八点的提醒", "enqueue"),
    ("zh_interrupt", "助手正在回复。最新用户输入:等等,先别继续了。", "interrupt"),
    ("zh_noise", "助手正在回复。最新 ASR:[噪声]", "discard"),
    ("en_hold", "Assistant is idle. Latest input: Could you set a", "continue_listening"),
    ("en_join", "Assistant is idle. Latest input: Could you set a\nreminder for 8 tomorrow?", "enqueue"),
    ("en_interrupt", "Assistant is speaking. Latest input: Stop, I changed my mind.", "interrupt"),
    ("en_noise", "Assistant is speaking. Latest ASR: [background noise]", "discard"),
]
CASES = CASES + [
    {
        "id": identifier,
        "state": state,
        "question": {
            "type": "choice", "instructions": "How should the assistant handle the latest user input?",
            "criteria": ACTIONS,
        },
        "expected": label,
    }
    for identifier, state, label in DUPLEX
]


def write_json(path, value):
    path.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n")


def softmax(logits):
    values = np.asarray(logits, dtype=np.float64)
    adjusted = np.exp(values - values.max())
    probabilities = adjusted / adjusted.sum()
    if not np.isfinite(probabilities).all():
        raise ValueError("Nonfinite readout probability")
    return probabilities


async def native(bundle, evidence):
    from coreai_d3 import D3CoreAI, pack

    start = time.perf_counter()
    model = await D3CoreAI.load(bundle)
    load_seconds = time.perf_counter() - start
    rows = []
    for case in CASES:
        if case["id"] == "long_text":
            continue
        start = time.perf_counter()
        logits, keys, encoded = await model.logits(case["state"], case["question"])
        elapsed_ms = (time.perf_counter() - start) * 1000
        probabilities = softmax(logits / model.config["temperature"])
        rows.append(
            dict(
                id=case["id"], labels=keys, native=probabilities.tolist(),
                selected=keys[int(probabilities.argmax())], expected=case.get("expected"),
                elapsed_ms=elapsed_ms, ids=encoded["input_ids"][0].tolist(),
            )
        )
        if not (bundle / "swift_fixture.json").exists():
            inputs = pack(encoded, model.manifest)
            write_json(bundle / "swift_fixture.json", {
                **{name: values.flatten().tolist() for name, values in inputs.items()},
                "output": model.manifest["output"],
                "expected": softmax(logits).tolist(),
            })

    sample = CASES[0]
    for label, state, question, media in [
        ("oversized", "refund " * 2000, sample["question"], {}),
        ("media", sample["state"], sample["question"], {"images": ["test.png"]}),
        ("empty_choice", sample["state"], {"type": "choice", "criteria": {}}, {}),
    ]:
        try:
            await model.logits(state, question, **media)
        except ValueError:
            pass
        else:
            raise AssertionError(f"{label} input accepted")

    repeat = []
    for _ in range(7):
        start = time.perf_counter()
        logits, _, _ = await model.logits(sample["state"], sample["question"])
        repeat.append((time.perf_counter() - start) * 1000)
    write_json(evidence / "native.json", rows)
    write_json(evidence / "runtime.json", {
        "hardware": subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"], text=True).strip(),
        "os": subprocess.check_output(["sw_vers", "-productVersion"], text=True).strip(),
        "load_seconds": load_seconds,
        "warm_repeat_ms": repeat,
        "warm_repeat_median_ms": statistics.median(repeat),
        "peak_process_rss_bytes": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
        "bounds_checked": ["oversized", "media", "empty_choice"],
    })
    print(f"Core AI validated {len(rows)} prompts; load {load_seconds:.3f}s", flush=True)


def reference(source, bundle, evidence):
    import torch
    # Import the upstream runtime before the packaged copy from the bundle.
    sys.path.insert(0, str(source.resolve()))
    from d3_runtime import D3

    torch.set_num_threads(4)
    model = D3.from_pretrained(source, device="cpu", verify="full")
    combined = []
    for original in json.loads((evidence / "native.json").read_text()):
        row = dict(original)
        ids = row.pop("ids")
        labels = row["labels"]
        with torch.inference_mode():
            probabilities = np.asarray(model.probabilities([ids], [len(labels)])[0])
        row["reference"] = probabilities.tolist()
        row["reference_choice"] = labels[int(probabilities.argmax())]
        row["max_probability_error"] = float(np.max(np.abs(probabilities - row["native"])))
        ordered = sorted(probabilities, reverse=True)
        row["reference_top_two_gap"] = float(ordered[0] - ordered[1]) if len(ordered) > 1 else 1.0
        combined.append(row)
        print(f'{row["id"]}: {row["reference_choice"]} -> {row["selected"]}, '
              f'error {row["max_probability_error"]:.6f}', flush=True)
    decisions = [row for row in combined if row["id"] in {case[0] for case in DUPLEX}]
    differences = [row["id"] for row in combined if row["selected"] != row["reference_choice"]]
    summary = {
        "cases": len(combined), "top_choice_matches": len(combined) - len(differences),
        "different_choices": differences,
        "max_probability_error": max(row["max_probability_error"] for row in combined),
        "four_choice_cases": len(decisions),
        "four_choice_correct_native": sum(row["selected"] == row["expected"] for row in decisions),
        "four_choice_correct_reference": sum(row["reference_choice"] == row["expected"] for row in decisions),
    }
    write_json(bundle / "validation.json", {
        "summary": summary, "runtime": json.loads((evidence / "runtime.json").read_text()), "cases": combined,
    })
    print(json.dumps(summary, indent=2), flush=True)
    if differences and any(
        row["reference_top_two_gap"] > 0.05 for row in combined if row["id"] in differences
    ):
        raise AssertionError("Conversion changed a reference choice with a clear margin")
    if summary["max_probability_error"] > 0.06:
        raise AssertionError("Probability drift exceeded 0.06")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("phase", choices=["native", "reference"])
    parser.add_argument("--source", type=Path, default=Path("upstream"))
    parser.add_argument("--bundle", type=Path, default=Path("bundle"))
    parser.add_argument("--evidence", type=Path, default=Path("evidence"))
    args = parser.parse_args()
    args.evidence.mkdir(parents=True, exist_ok=True)
    if args.phase == "native":
        asyncio.run(native(args.bundle, args.evidence))
    else:
        reference(args.source, args.bundle, args.evidence)