"""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)