X-Ray: Numerical Evidence and Divergence Attribution

X-Ray is CKE's evidence system for numerical correctness. It compares the generated CK runtime against pinned oracle backends checkpoint by checkpoint, joins the results with the call IR and the kernel registry, and reduces every failure to one first divergent semantic edge, one failure class, one named fix owner, and one recommended action.

Status: implemented production diagnostic tooling (v8).
X-Ray is not a proposal — it is the harness CKE uses to bring up model families and to keep parity honest. The visual surface lives in the IR visualizer's X-Ray tab; the machine-readable surface is a family of schema-validated JSON reports under build/xray/. Figures on this page are schematics that explain marker semantics; real evidence lives in run directories, the test report, and the nightly injected-fault validator.

What X-Ray is

  • An attribution tool: it joins artifacts that already exist — the call IR (every op with its resolved provider and numerical contract), the kernel registry, and oracle runs — into one schema-validated evidence chain.
  • A fail-closed capture system: a captured tensor is evidence only if the captured execution reproduces the uncaptured execution bit-for-bit on the same causal token history.
  • A fix-ownership policy encoded in the reports: first_divergence.fix_owner and architecture_policy travel with the failure, so the next agent receives the rule with the diagnosis.
  • A regression surface: nightly gates inject predetermined faults and require X-Ray to name the predetermined first boundary.

What X-Ray is not

  • Not permission to hardcode the observed answer. A diagnosis never becomes a model-name branch in the DSL or codegen; the fix lands in the circuit, the kernel map, the kernel, or the reference adapter.
  • Not a tolerance-relaxation mechanism. X-Ray exists to find the edge that violates a contract, not to widen the contract until the edge disappears.
  • Not a hardware profiler. It covers roughly 90–95% of ordinary model-integration failures; compiler instruction scheduling and hardware-specific transcendental behavior still need isolated kernel instrumentation after X-Ray identifies the edge.
  • Not a single command. There is deliberately no xray binary: each script pins exactly one oracle backend, and you select the backend by selecting the script.

The Evidence Pipeline: Join, Don't Instrument

The design principle is join, don't instrument. The call IR already carries every operation with its resolved kernel and contract. X-Ray reports already carry per-stop metrics. The kernel registry is already loaded. X-Ray connects the three instead of adding a parallel instrumentation stack inside the runtime.

The binding begins before any tensor exists. A circuit declares versioned semantic checkpoints; BuildIR binds each checkpoint to a generated operation, an exact kernel ID, a public function, a phase, a layer, a layout and named axes. GraphIR, LoweredIR and call IR retain the same metadata, so the checkpoint-manifest adapter takes tensor identity from the call IR rather than from backend-specific file names. Backend profiles hold observed storage policy and dtype tolerances outside the circuits.

X-Ray evidence pipeline. Sources on the left: call IR carrying every operation with resolved provider, numerical contract, phase, layer, layout and named axes; the kernel registry with provider IDs, contracts, ISA and required versus resolved capability; and oracle backends PyTorch and llama.cpp with one pinned backend per script. These feed capture and schema validation producing per-checkpoint tensors with dtype, shape, sha256, cache layout and strides, neutrality-gated and fail closed. The comparator checks metadata contracts first — storage, layout, reduction, position, execution policy — and computes numerical metrics only after metadata agrees: max absolute error, RMSE, exact ratio and top-1 ranking. Metadata faults never reach metrics. Classification reports the first divergent semantic edge with one failure class, one fix owner and one recommended action, embedded in the report rather than only in documentation. Three surfaces consume the evidence: the IR visualizer X-Ray tab with its backend board, drift chart, circuit rows, ranking strips, runbook and live reload; the test report with scoped scorecards that never show a bare 100 percent; and nightly gates whose injected-fault validator tests the diagnostic itself against predetermined first boundaries. The footer states that X-Ray is an attribution tool, not permission to hardcode the observed answer

The ordering rule is strict: metadata contracts are validated before tensor values are loaded. A storage, layout, reduction, position or execution-policy mismatch stops the comparison before any expensive model execution or numerical metric runs — a dtype disagreement is a contract fault, not a large RMSE. Named axes canonicalize compatible physical layouts, sparse checkpoints identify a failing interval, and the planner then requests only the internal edges of the first failing block.

What a Checkpoint Record Carries

Every captured artifact is self-describing and content-addressed. A trimmed real record from the checked-in fixture (version/v8/tests/fixtures/xray/xray_execution_trace.json, schema cke.xray_execution_trace):

{
 "checkpoint_id": "layer.0.attention.kv_append",
 "role": "new_key",
 "tensor_path": "tensors/layer0_new_key.f32",
 "dtype": "fp32",
 "shape": [1, 8, 1, 64],
 "sha256": "1a2b3c4d…"
}

state: position 8 · cache_token_count 9 · append_index 8
cache_layout: kv_cache_v1 · layer/head/token/channel strides

The execution trace records the schedule alongside the tensors: prefill segmentation, per-call kernel batches with kernel ID and numerical/effective contract IDs, cache actions, position progression, and the physical cache layout with its strides. Two runs whose schedules differ are different executions, and X-Ray says so before comparing a single value — a combined 1,307-row prefill is not numerical evidence about a backend that executes 33, 1,008 and 266-row segments.

Verdict Semantics and the Honest Scorecard

Every report lands in one of three states:

Verdict Meaning Consequence
pass · within gate all checkpoints inside thresholds scorecard may be published, fully scoped
cosmetic drift thresholds crossed, but no top-1 logit flips diagnose; not yet a behavioral claim
behavioral divergence at least one top-1 flip generation behavior changed; the first flip is the bug to fix

When a backend reaches full parity the board may say so, but the claim stays scoped. The honest banner is 79/79 edges within gate — FP32 · PyTorch · fixture 20260725 · 1 thread, never a bare "100%". Parity is always scoped to model family, dtype, backend version, fixture or seed, thread count and sample. Live mode keeps the scorecard a continuously re-proven state: the next agent run that regresses an edge flips the card back to amber or red with the first-divergence pin.

Anatomy of the Drift Chart

The visualizer's drift chart is the fastest way to read a run: stop index in execution order on the x-axis, log-scale max_abs and RMSE on the y-axis, one curve per loaded report, layer facets behind the points. The markers are the language of the chart:

Schematic drift chart labelled as illustrative, not real run data. Checkpoint stop index in execution order on the horizontal axis, log-scale error on the vertical axis, alternating layer facet bands. A green shaded byte-exact prefix ends at an amber pin marking the first non-exact checkpoint. The error curve rises past a purple triangle marking a per-edge jump greater than three times, crosses a dashed amber gate threshold line, passes a magenta diamond marking a monotonicity break, and reaches a red pin marking the first material divergence where a top-1 logit flips. Three callout cards: every point is clickable and opens checkpoint detail with op, function, buffer, shape, sha256 and required versus resolved contract; three verdict states are pass within gate, cosmetic drift, and behavioral divergence; coverage is explicit because operations without a checkpoint render gray and the header states how many of how many ops have X-ray edges

Capture Neutrality: Evidence Must Not Change the Answer

Checkpoint export is additional work inside the observed process — environment checks, memory copies, path formatting, file I/O between model operations. That work changes timing and cache state, and an existing race, unsafe scratch-buffer lifetime or scheduling-dependent reduction can become visible only when instrumentation perturbs the run. A plausible tensor dump is not sufficient: a captured tensor is evidence only if the captured execution reproduces an uncaptured execution on the same causal token history.

Capture neutrality acceptance sequence. Control A, an uncaptured execution, and Control B, an uncaptured forced replay of the same tokens, enter the repeatability gate. If they are not bit-identical, attribution is rejected before capture as uncaptured runtime is not repeatable, with an optional one-thread SIMD diagnostic. If identical, an aggregate capture replays the same forced tokens with all requested checkpoints enabled and faces the neutrality gate: captured logits must be bit-identical to Control B. If they differ, the isolated-boundary fallback runs one replay per boundary, each independently compared, which is unavailable for coupled KV and binary-parity captures. Accepted artifacts are returned in aggregate or isolated mode. Any remaining failure fails closed: rejected artifacts stay labelled, never enter the accepted list, and produce a nonzero CLI result even when CKE and the oracle otherwise agree. Two footers explain that same-runtime comparison is bit-exact because instrumentation must not change any output bit, while cross-engine comparison legitimately uses numerical metrics because reduction orders may differ

The neutrality comparison is bit-exact on purpose, and only within the same runtime. Two executions of the same CKE runtime, provider map, thread count and forced history have a strict contract: instrumentation must not change any output bit. A numerical tolerance here could hide precisely the small perturbation a deep recurrent model later amplifies. Cross-engine comparison is a different question — CKE and llama.cpp may legitimately use different reduction orders — so oracle parity uses numerical metrics and token decisions, never a bit-exact demand. If a production provider is intentionally nondeterministic, that fact must first be measured and declared as its own contract; X-Ray must not silently absorb it into a tolerance.

Why this gate exists: the Qwen3.6 qualification finding

During real Qwen3.6-27B Q4_K_M qualification, the neutrality contract rejected capture before instrumentation: two uncaptured 24-thread runs on the same forced trajectory first differed at generated step 76 — top-1 tokens still matched, but the full logits were not bit-identical (cosine 0.999641, RMSE 0.069543, max abs 0.326646). That corrected an earlier provisional interpretation that tensor export was perturbing CKE, and established production-path run-to-run nondeterminism as its own bug. For the same trajectory, two one-thread CKE runs were bit-exact (one worker; SIMD still enabled), making the one-thread SIMD diagnostic a useful internal reference — while llama.cpp remains the independent external oracle, reported separately.

Failure Classes

Classification is a closed vocabulary — every failure resolves to one class with a recommended action, and metadata faults never proceed to numerical metrics:

Group Classes Typical owner
Metadata & contract MISSING_CHECKPOINT · CIRCUIT_PRODUCER_MISMATCH · LAYOUT_MISMATCH · STORAGE_CONTRACT_MISMATCH · REDUCTION_CONTRACT_MISMATCH · POSITION_CONTRACT_MISMATCH · NUMERICAL_CONTRACT_MISMATCH · KERNEL_BINDING_MISMATCH · DIAGNOSTIC_EXPORT_MAPPING · MISSING_TOLERANCE_PROFILE circuit, kernel map, reference adapter
Execution & state EXECUTION_POLICY_MISMATCH · CACHE_STATE_METADATA_MISMATCH · STATE_CACHE_DIVERGENCE circuit, runtime schedule, cache provider
Numerical & behavioral KERNEL_IMPLEMENTATION_DIVERGENCE · ATTENTION_ARITHMETIC_DIVERGENCE · NONFINITE_OUTPUT · RANKING_DIVERGENCE kernel, provider arithmetic

The nightly injected-fault validator tests this vocabulary directly: public two-layer fixtures each change one tensor, metadata field, circuit edge or state transition, and X-Ray must report the predetermined first boundary — a BF16 storage boundary must come back as STORAGE_CONTRACT_MISMATCH, an off-by-one KV append index as CACHE_STATE_METADATA_MISMATCH, and so on. A clean control run must produce no false positive. The diagnostic itself is under test, not only the models.

Fix Ownership: Where a Diagnosis Is Allowed to Land

X-Ray is an attribution tool, not permission to hardcode the observed answer into code generation. Every accepted parity fix has exactly one explicit owner:

Owner Owns
Circuit model topology, producer/consumer edges, operation order, position semantics, required storage/rounding/reduction contracts
Kernel map exact public function, supported numerical contract, ISA, shape eligibility, threading/reduction capability
Kernel identical inputs produce incorrect values — reproduce in an isolated scalar/reference test, then run the applicable PyTorch or llama.cpp parity gate before promotion
Reference adapter / profile backend tensor naming, logical-axis mapping, exported boundaries, dtype-specific comparison tolerances
Generic compiler hardening schema validation, fail-closed resolution, metadata propagation, deterministic emission, removal of implicit assumptions — only when the missing behavior is model-independent infrastructure

The DSL and code generator remain a deterministic consumer of circuit requirements and resolved kernel-map decisions. No model-name, checkpoint-name or one-off parity branches in DSL/codegen: if X-Ray reports a model-specific mismatch, the fix lands in the circuit requirement, the kernel capability/map, the kernel arithmetic, or the reference adapter. Reports encode this rule in first_divergence.fix_owner and architecture_policy, so the policy arrives with the failure instead of living only in documentation. The full additive fix progression — execution policy first, cache state before attention math, first divergent edge, rerun from the last passing checkpoint — lives in v8 Numerical Contracts.

Report Taxonomy

Each X-Ray artifact is schema-validated JSON with a declared schema ID and version; unknown or malformed evidence fails closed. The principal report types:

Schema Purpose
cke.xray_execution_trace schedule + capture evidence: kernel batches, contracts, cache actions, position progression, cache layout/strides, content-addressed tensors
cke.xray_ranking_report shared ranking ABI for mixed-prefill, teacher-forced and persistent-vs-replay checks; per-position top-1 agreement with cosine — evaluated only after tensor checkpoints pass
cke.xray_execution_state_report bounded state comparison that stops at one of four boundaries: execution policy, cache metadata/content, attention input, attention arithmetic
cke.xray.capture-neutrality.v1 control repeatability, aggregate and isolated capture verdicts, accepted/rejected artifact lists, final accepted mode
cke.xray_attention_sensitivity forward amplification probe: sends reference and perturbed tensors through the same authoritative PyTorch operator to test whether a small forward difference is amplified downstream — diagnostic evidence, not a parity verdict
cke.xray_monotonic_provider_gate provider-promotion ratchet: a candidate must not regress beyond epsilon against the baseline across the gate rows

The Visualizer Surface

The IR visualizer's X-Ray tab is where a human watching an agent bring up a model sees, in seconds, which backend diverges, at which op, under which kernel contract, and whether it flips output tokens:

Known gaps are disclosed rather than smoothed over: the ranking-to-drift overlay is intentionally not rendered (token positions do not map cleanly onto op stops); the phase toggle has not been visually verified against real multi-phase data; rendered evidence so far comes from checked-in fixtures; failure-narrative sequencing and bug-bundle export are designed but not built.

Gates and Commands

# lightweight gate: schema, resolver, canonicalization, classification, bisection, manifest tests
make test-bf16-xray

# validator self-test: injected faults must produce the predetermined first diagnosis
make test-xray-validator-selftest

# real diagnosis, one pinned oracle per invocation
make xray-vision-parity BACKEND=llamacpp GGUF=<mmproj.gguf> XRAY_OUTPUT_DIR=build/xray/qwen3vl_llamacpp
make xray-vision-parity BACKEND=pytorch CHECKPOINT=<hf_ckpt> RUNTIME_DIR=<dir> \
  WEIGHTS_BUMP=<weights.bump> CALL_IR=<call.json> XRAY_OUTPUT_DIR=build/xray/qwen3vl_bf16

The lightweight gate downloads no model weights and is included in make test-bf16 and the BF16 nightly category; the injected-fault validator runs nightly as a dedicated test-report row. End-to-end: run the same model through N backend-pinned scripts, place the N schema-validated JSONs in the run directory, regenerate or live-serve the visualizer — the board groups cards by backend automatically.

X-Ray in the Wider Architecture

X-Ray is the evidence layer other CKE subsystems report into:

Standing rule: X-Ray never relaxes a tolerance, never substitutes a provider, and never fabricates identity. It narrows a failure to one semantic edge and names its owner — the fix is then made where the contract lives, and the rerun must move the first divergence to a later edge.
Image
100% | |
Scroll to zoom | Drag to pan | W/H to fit | 0 to reset | ESC to close