Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions docs/guides/candidate-static-check.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,120 @@ to override the L1 probe budget (default 120 seconds), and
The plan freezes the level, rule versions and timeouts. The static stage uses
Git locally for immutable diff objects, with no external act-base checkout or script.

## Freezing device probe inputs

To enable device replay for a benchmark, AB/BA project, sequential project or
service-reuse session, add `--candidate-pre-check=l1 --l1-probe-manifest /path/to/manifest.json`
to its start command. Python callers pass `candidate_pre_check="l1"` and
`l1_probe_manifest=Path("/path/to/manifest.json")` to the corresponding start request.
With no manifest, the static gate and missing-asset behavior remain available.

The version 1 JSON manifest names the scheduler backend (`cuda` or `npu`), the
expected device model, the probes this bundle supports, and operator-owned files.
The worker requests one device with `gpu run --gpus 1 --` by default. An operator
can set the private manifest's `scheduler_prefix` to a nonempty array of command
arguments for another single-device scheduler. The executor appends the frozen
Python child command to that prefix. The scheduler must set
`CUDA_VISIBLE_DEVICES` for CUDA or `ASCEND_RT_VISIBLE_DEVICES` for Ascend to the
allocated device. The worker clears inherited selectors before submitting the job.
The allocated process uses the session's frozen `--python` interpreter. Cancelling
a queued attempt revokes admission. If the scheduler exits while an admitted
child is still running, recovery waits for the child and reads its measurement.
For example, a Qwen2 operator and two-layer replay bundle can use:

```json
{
"schema_version": 1,
"backend": "cuda",
"device_model": "NVIDIA L20X",
"probes": ["L1_A", "L1_B", "multistream_fork_join"],
"assets": {
"adapter": "adapter.json",
"op_shape_corpus": "op_shape_corpus.json",
"layer_slice_2l": "layer_slice_2l.safetensors"
},
"thresholds": {"shape_target_count": 40, "steady_state_rounds": 50}
}
```

All asset paths are relative to the manifest directory. Keep the manifest and
assets in a private operator directory outside the candidate repository and
the task or project protocol inputs. An alias pointing to the bundle directory
is supported. The manifest, asset files and paths within that directory must be
regular files or directories without symlinks.
The adapter is JSON data consumed by the built-in replay implementation.
For Qwen2 layer replay, `adapter.layers` names layer 0 and the middle layer.
Each starting layer uses its captured `layers.<index>.input` activation and
matching weights from the safetensors archive. With `adapter.cross_layer_fusion`
set to `true`, declare a separate `adapter.entries.L1_B_fused` path in both
snapshots for the two-layer entry. The runtime applies the starting layer and
its immediate successor in sequence, with independently loaded baseline,
candidate and FP32 reference instances and KV caching disabled. Freeze weights
for both successors as well. A layer-only route needs the adapter and layer
archive. Full unpadded prefill defaults to zero-based positions. To replay an
offset, include `layers.<index>.position_ids` as a contiguous-position int64
tensor of shape `[batch, sequence]`. A missing fused entry or adjacent layer's
weights leaves the probe inconclusive.

Under `adapter.entries`, name each workload's snapshot-relative Python file.
Each file defines `forward(op, x)`, optionally preceded by `import torch`.
The evaluator reads its syntax tree and runs the supported tensor operations.
These include `op(x)`, arithmetic, dtype conversions, `square`, `pow`, `mean`
with a literal `keepdim`, `clone`, `contiguous`, `torch.rsqrt`, `torch.sigmoid`
and the functional `silu` and `rms_norm`. L1-A also provides RMSNorm's
`op.weight` and `op.variance_epsilon`. An entry may create a backend stream,
enter its context, wait on another stream and return a tensor with its recorded
event. Unsupported expressions, additional changed files outside the registered
workload entries, and other model families leave device replay inconclusive.
This device implementation is a controlled Qwen2 replay for unquantized
floating-point inputs on one device. Changes to Triton or native kernels,
unregistered helper files, or other model families require a separate runtime
adapter to establish coverage.
Benchmark-scope attribution and layer-specific shape or lookup warnings without
matching layer inputs remain coverage gaps. See the
[Qwen2 CUDA acceptance runs](../../evidence/l1-precheck-qwen2-cuda/README.md)
for the frozen input format, measured controls and backend coverage.

The adapter's `expected_kernels` identifies the baseline trace. To attribute a
changed path, the worker compares the candidate's kernel sequence and launch counts
with an independent trace of the trusted operator on the same input. L1-A also
recognizes PyTorch's fused RMSNorm. A repeatable above-threshold speedup with
the same calibrated kernel sequence fails attribution. An unknown or unavailable
trace leaves attribution inconclusive, even if another shape was attributed.
Graph replay uses two distinct input updates. Each replay must pass
the calibrated precision check and match its own eager control more closely than
the other two controls.

The optional `adapter.cxx17_syntax_entry` names one self-contained
`.cpp`, `.cc` or `.cxx` translation unit. The executor runs GNU g++ inside
bubblewrap. Literal system includes such as `#include <cstdint>` are supported.
Project headers, macros and custom source locations require a task toolchain.
A diagnostic can reach public feedback after the baseline compiles and the
evaluator verifies the reported location against the candidate source. A
matching single-file C++ candidate needs only the adapter asset for this check.
After a successful compile its runtime verdict remains inconclusive. An
unavailable sandbox or compiler also leaves the check inconclusive.

The optional `thresholds` object overrides the frozen probe defaults. The
shape sample count ranges from 30 to 50, the steady-state check takes at least
50 rounds, and the sampling protocol fixes the complexity multiplier at 1.5.
The gate rejects a repeatable shape cliff by default. A hardware exception
requires a frozen `adapter.alignment_multiple` and a calibrated adjacent length
on the specific center row. For example, a length-64 center can declare
`"calibrated_alignment_neighbors": [63]` for a measured boundary with
alignment 16. Length 65 remains subject to the gate. With `alignment_multiple`
omitted or set to `null`, every sampled neighbor is subject to the gate.

Startup copies the files once and binds their content hashes, device selection,
probe names and thresholds to `candidate_static_check.l1_manifest_id` in the
plan. Project intake approval includes that identifier. The frozen configuration
and assets live under `.private/l1-probes/` in the session. The private manifest
supplies the thresholds for both measurement and the final verdict. The allocated
worker verifies the assets and reads each snapshot once for both the compiler
and the tensor interpreter. The private per-attempt device result lives under
`.private/l1-device-<attempt_id>/`. The public `pre_check_report.json` contract
is unchanged.

InferRSI compares the retained candidate and frozen baseline, including a
single-file benchmark candidate or a project directory submitted before
committing. Service-reuse baselines use the existing committed reference.
Expand Down
99 changes: 99 additions & 0 deletions evidence/l1-precheck-qwen2-cuda/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Qwen2 single-device L1 gate

On 2026-12-02 the managed Python API launched the CUDA worker on one scheduler-reserved NVIDIA L20X on clean commit `f00b075559cad71a085968dc03b598f6235f897f` (rebased onto `5410bc2f`, zero `src/` diff against PR head). A zeroed Qwen2 RMSNorm result produced a public `FAIL`, settled one round and prevented downstream acceptance. An equivalent Qwen2 decoder entry produced a public `PASS` and the downstream worker accepted the attempt. The downstream protocol deliberately exits without a measurement (`downstream_scope="unavailable_by_design"`). Both L1 workers recorded verified cleanup and embed `git_head`, `working_tree_dirty=false`, `l1_rules_version`, and all 19 SHA-256 digests across evaluator, executor, and managed worker/dispatch/cleanup modules. [Managed precision failure](results/managed-precision_failure.json) · [Managed layer control](results/managed-identity.json) · [Managed run source fingerprints](plan/source-fingerprints.json) · [Acceptance issue](https://github.com/InferMatrixLab/InferRSI/issues/883)

## L20X retest of the revised cliff and attribution gates

The two fused RMSNorm trials each passed the FP64 comparison on all 40 BF16
shapes. The gate attributed 39 shapes in the first trial and 33 in the repeat
to the trusted fused kernel. Together the trials produced a measured trace for
each of the 40 shapes. Both individual verdicts were `INCONCLUSIVE` because
some shapes exceeded the frozen 5% AB/BA order-bias limit. The stale-output
controls failed on the first and second graph updates as expected in each run.

The decoder identity trial passed both graph updates at layers 0 and 14 in
each reservation. Its first timing verdict was `INCONCLUSIVE`, its repeat
`PASS`. Through the managed session API, the zero-output RMSNorm control
produced `FAIL`, charged one round, verified cleanup and blocked downstream
execution. The latest L20X retest is recorded in the compressed JSON Lines file.
Records 1–4 each carry the evaluator's `source_sha256` at the top level. Record 5
contains the managed result and omits that field. The initial direct trial
records carry their own `source_sha256`. [L20X retest measurements](results/gate-review-retest.jsonl.gz) · [Initial direct trial records](results/cuda-trials.jsonl)

## Previous L20X retest

Three fresh one-card reservations used the same checkpoint, BF16 calibration and
5% timing order-bias threshold. The records are in execution order and include
the evaluator source hashes for this revision. [Raw trials](results/review-cuda-trials.jsonl)

| Entry and case | Verdict | Observations |
| --- | --- | --- |
| A, fused RMSNorm | INCONCLUSIVE | All 40 shapes passed the FP64 comparison. Sequence lengths 56 and 59 each had only one AB/BA measurement within the order-bias limit. The other 38 traces matched the trusted fused operation. |
| B, identity decoder | PASS | Layers 0 and 14 each passed both updated-input CUDA graph replays. |
| A, fused RMSNorm, independent repeat | PASS | All 40 shapes passed precision and trace attribution. The baseline launched eight kernels and the candidate launched one on every shape. Median per-shape latency reduction was 79.65%, averaging the first two AB/BA gain estimates per shape. |

Both A trials also ran two faulty CUDA graphs with correct eager output. The
graph holding the capture input failed on update 1. The graph holding the first
replay input failed on update 2. The production fused entry passed both updates
on the representative shape `[1, 39, 1536]` in both trials.

## Initial direct backend trials

Each row ran the production device evaluator and verdict function in a fresh Python process under a separate, single-device scheduler reservation. A replays the checkpoint's input RMSNorm with an FP64 oracle. B replays decoder layers 0 and 14 at their respective real inputs with independently constructed FP32 layers. The candidate files wrap these production operations. `identity` adds parentheses to the return value. `matched_async` compares two equivalent event-returning entries. `async_event` compares an event-returning side stream against a synchronous baseline. [Per-shape measurements and decisions](results/cuda-trials.jsonl)

The initial direct trials froze the working evaluator on base `2e273f43`; the refreshed managed receipts (`results/managed-precision_failure.json`, `results/managed-identity.json`) and [Managed run source fingerprints](plan/source-fingerprints.json) now bind to clean commit `f00b075559cad71a085968dc03b598f6235f897f` on base `5410bc2f`, matching all 19 current evaluator, executor, and managed worker/dispatch/cleanup source hashes byte-for-byte.

| Entry | Case | Verdict | Reason | Queue and launch, s | Load, s | Probe, s |
| --- | --- | --- | --- | ---: | ---: | ---: |
| A | Identity | PASS | 40 shapes | 0.38 | 6.25 | 9.44 |
| B | Identity | PASS | Two real layer inputs | 0.33 | 7.90 | 1.10 |
| A | Matched async | INCONCLUSIVE | Persistent timing noise | 0.36 | 6.48 | 9.41 |
| B | Matched async | PASS | Two equivalent event contracts | 0.36 | 7.94 | 1.14 |
| A | Async event | FAIL | Repeatable single-shape slowdown | 0.34 | 6.61 | 0.46 |
| B | Async event | FAIL | Repeatable single-shape slowdown | 0.42 | 7.40 | 0.62 |
| A | Zero output | FAIL | Precision | 0.46 | 7.30 | 0.13 |
| B | Zero output | FAIL | Precision | 0.44 | 7.44 | 0.22 |
| A | Missing fork | FAIL | Immediate consumer disagrees with reference | 0.49 | 6.47 | 0.14 |
| B | Missing fork | FAIL | Immediate consumer disagrees with reference | 0.34 | 7.14 | 0.25 |
| A | Missing join | FAIL | Immediate consumer disagrees with reference | 0.40 | 6.18 | 0.16 |
| B | Missing join | FAIL | Immediate consumer disagrees with reference | 0.33 | 7.66 | 0.25 |

The entries use prebuilt PyTorch and Transformers libraries, so the worker recorded zero build time. Queue and launch time includes the scheduler wait and child startup. Excluding the queue, the identity runs took 15.70 s for A and 9.00 s for B. The proposed ranges are 10–30 s and 20–60 s respectively. The direct and matched async controls completed two updated-input graph replays and sampled allocated bytes, thread counts and live caller streams at rounds 0, 25 and 50. Both async-versus-synchronous cases passed the functional and steady-state checks before the performance gate rejected them.

## Inputs and calibration

The checkpoint is `Qwen/Qwen2.5-1.5B-Instruct` at revision `989aa7980e4cf806f80c7fef2b1adb7bc71aa306`. The generator verifies the local weight SHA-256 before use. It captured 20 real sequence lengths from eager Qwen2 prefill on tokenized repository prompt examples, measured input RMSNorm's share of forward time, and used separate arithmetic token sequences for 30 non-aligned and 10 held-out lengths. The default A sample used 16 real, 16 non-aligned and eight held-out shapes. Both layer inputs had shape `[1, 30, 1536]`. Weights, inputs and inference used BF16. The shape distribution represents this local prompt corpus. [Frozen shape corpus](plan/op_shape_corpus.json) · [Asset and runtime identities](plan/asset-capture.json)

The generator reserved three other prompts for calibration and exercised the offset and scale transformations used by the probes. The FP64 RMS reference and the FP32 decoder reference set independent BF16 tolerances, frozen before evaluating the candidates. The decoder's calibration yielded absolute tolerance 8, relative tolerance 0.015625 and minimum cosine 0.89053. The baseline and identity candidate matched on each retained decoder statistic. This case detects the large precision fault exercised here. Smaller layer errors require tighter calibration. [Frozen adapter](plan/adapter.json)

FP16 pilot runs produced non-finite eager activations, including the captured middle-layer input. The evaluator returned `INCONCLUSIVE` on that baseline. The final generator rejects non-finite calibration outputs and requires finite captured inputs. Earlier BF16 stream pilots reached CUDA graph capture before reproducing the missing dependency. The final device evaluator delayed the producer and consumer separately and observed an incorrect immediate snapshot in all four missing-edge cases. All runs used the default timing gates. [Pilot outcomes](results/calibration-history.json) · [Initial direct trial records](results/cuda-trials.jsonl)

## Reproduce

Use the source checkout, the local snapshot directory at the recorded revision, and a CUDA-enabled PyTorch/Transformers installation matching the capture record. The generator reads the prompt corpus from Git commit `2e273f43f40eb831091bf6a6d126fb95639dd0fc`. The following commands run from the repository root. `assets` and the run output paths must be new. The scripts retain raw timings in the requested output.

```bash
export PYTHONPATH="$PWD/src"
export PYTHONNOUSERSITE=1 HF_HUB_OFFLINE=1 OMP_NUM_THREADS=1
case_dir=evidence/l1-precheck-qwen2-cuda
assets=/tmp/qwen2-l1-assets
snapshot=/path/to/snapshots/989aa7980e4cf806f80c7fef2b1adb7bc71aa306
gpu run --gpus 1 -- python -P "$case_dir/plan/prepare.py" --snapshot "$snapshot" --repo . --output "$assets"

python -P "$case_dir/validator/run_case.py" --assets "$assets" --probe L1_A --case fused_rmsnorm \
--output /tmp/qwen2-l1-results/fused-rmsnorm.json
for probe in L1_A L1_B; do
for variant in identity precision_failure missing_fork missing_join async_event matched_async; do
python -P "$case_dir/validator/run_case.py" --assets "$assets" --probe "$probe" --case "$variant" \
--output "/tmp/qwen2-l1-results/$probe-$variant.json"
done
done
python -P "$case_dir/validator/run_managed.py" --assets "$assets" --case precision_failure --output /tmp/qwen2-managed-negative
python -P "$case_dir/validator/run_managed.py" --assets "$assets" --case identity --output /tmp/qwen2-managed-identity
```

Invoke the direct and managed drivers from outside an allocation. The direct driver calls `gpu run`, while the managed API delegates scheduling to its worker. The generated shape corpus includes newly measured baseline time shares. The original timing shares and manifest are retained with the plan. [Frozen manifest](plan/probe-plan.json)

## Outstanding device coverage

The validation host exposed CUDA. It had no Ascend device nodes, `npu-smi` or `torch_npu`; the configured NPU hostname did not resolve from this host. Ascend results remain `INCONCLUSIVE`. This campaign exercised unquantized, single-card entries with separate decoder layers. Cross-layer fusion, native compilation failures, production traffic screening rates, end-to-end throughput and full-model quality were outside the measured sample.
6 changes: 6 additions & 0 deletions evidence/l1-precheck-qwen2-cuda/patch/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Candidate controls

This acceptance bundle exercises the repository's L1 device probe gate against
synthetic Qwen2 RMSNorm and decoder-layer controls generated locally by
`validator/run_case.py` and `validator/run_managed.py`. No external optimization
patch is archived in this directory.
65 changes: 65 additions & 0 deletions evidence/l1-precheck-qwen2-cuda/plan/adapter.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"config": {
"architectures": [
"Qwen2ForCausalLM"
],
"attention_dropout": 0.0,
"bos_token_id": 151643,
"eos_token_id": 151645,
"hidden_act": "silu",
"hidden_size": 1536,
"initializer_range": 0.02,
"intermediate_size": 8960,
"max_position_embeddings": 32768,
"max_window_layers": 21,
"model_type": "qwen2",
"num_attention_heads": 12,
"num_hidden_layers": 28,
"num_key_value_heads": 2,
"rms_norm_eps": 1e-06,
"rope_theta": 1000000.0,
"sliding_window": 32768,
"tie_word_embeddings": true,
"torch_dtype": "bfloat16",
"transformers_version": "4.43.1",
"use_cache": true,
"use_sliding_window": false,
"vocab_size": 151936
},
"entries": {
"L1_A": "kernels/rms_norm.py",
"L1_B": "models/qwen2_decoder.py"
},
"expected_kernels": {
"L1_A": [
"reduce_kernel"
],
"L1_B": [
"gemm"
]
},
"graph_required": true,
"l2_flush_bytes": 134217728,
"layers": [
0,
14
],
"model": "qwen2",
"schema_version": 1,
"tolerances": {
"L1_A": {
"bfloat16": {
"atol": 0.000244140625,
"cosine_min": 0.9999,
"rtol": 0.015625
}
},
"L1_B": {
"bfloat16": {
"atol": 8,
"cosine_min": 0.8905339241027832,
"rtol": 0.015625
}
}
}
}
Loading
Loading