diff --git a/operatorx/README.md b/operatorx/README.md index c81ff849f4..60fa5176e0 100644 --- a/operatorx/README.md +++ b/operatorx/README.md @@ -29,3 +29,7 @@ Results: one JSON per run under `results///`; in CI, the `ope - Backend: `runners//backends/.py` exporting `IMPLS = [BackendImpl(...)]`; its image in `containers.toml`. - Op: `ops/.py` calling `register(OpSpec(type=..., arg_schema=..., parallel_axes=...))`. - Shapes: `testlists/.json`. + +## Ascend reproduction harness + +The [standalone Ascend GEMM harness](scripts/ascend/README.md) accepts these testlists for native unquantized and FP32-block-scale FP8 measurements with queued NPU timing, numerical checks, resumable journals and an installed-tiling L0A guard. It does not add an Ascend CI pool or change the NVIDIA/AMD runners. diff --git a/operatorx/scripts/ascend/README.md b/operatorx/scripts/ascend/README.md new file mode 100644 index 0000000000..20bd05273e --- /dev/null +++ b/operatorx/scripts/ascend/README.md @@ -0,0 +1,111 @@ +# Ascend GEMM reproduction + +This standalone harness measures single-device native `torch_npu` GEMMs with queued events and numerical checks. It accepts OperatorX testlists and stores raw samples, validation results, runtime/source fingerprints and per-case telemetry in a resumable SQLite journal. It does not register an OperatorX platform, add a CI pool, or upload results. + +The measurement path supports unquantized BF16/FP16/FP32 contracts and E4M3 GEMM with dynamic FP32 activation scales `[1,128]`, static FP32 weight scales `[128,128]`, and BF16 output. Activation quantization is inside the FP8 timer; static weight preparation is outside. Unsupported arguments, K tails, and cases above the explicit memory budget remain visible in the plan rather than being silently changed or padded. Parallel/distributed cases are not implemented. + +## Environment + +The hardware-tested stack is Ascend950PR_9579 (28 Cube cores, 128 GiB HBM), CANN 9.1.0, PyTorch 2.10.0 and torch_npu 2.10.0.post4 on Linux. Load the installed CANN environment and make the driver's libraries available before running. The host also needs `npu-smi`; FP8 preflight needs a C++17 compiler and `libdl`. No GPU libraries are imported for CPU-only planning. + +Run commands from the repository root, in the Python environment containing `torch_npu`. Choose board/chip/logical-device IDs from the actual SMI/ACL mapping; the example below uses board 0, chip 0 and logical device 0. The controller checks that mapping and requires an idle, healthy board with clean fault/ECC/PCIe diagnostics. Identity probing occurs in a disposable process before Torch initializes ACL. + +```bash +ASCEND_SCRIPTS="$PWD/operatorx/scripts/ascend" +ASCEND_RESULTS="/tmp/ascend-results" +mkdir -p "$ASCEND_RESULTS" +``` + +Use a fresh result directory for a changed plan, source, hardware identity or timing configuration. An existing directory cannot silently combine measurements from different fingerprints. The health parser is strict: an unrecognized driver table fails rather than guessing the device identity. + +## Unquantized GEMM + +The bundled examples include the large BF16 shape `M=49152, N=7168, K=6144`. A normal testlist such as `operatorx/testlists/gemm_deepseek_v4.json` can replace the example input; multiple files are accepted. Case identity includes every argument, including output precision and scale descriptors. + +```bash +python "$ASCEND_SCRIPTS/prepare.py" \ + --input "$ASCEND_SCRIPTS/examples/bf16.json" --kind unquantized \ + --memory-budget-bytes 103079215104 --output "$ASCEND_RESULTS/bf16-plan.json" + +python "$ASCEND_SCRIPTS/operatorx_batch_campaign.py" run \ + --plan "$ASCEND_RESULTS/bf16-plan.json" --run-dir "$ASCEND_RESULTS/bf16" \ + --phase smoke --device 0 --board-id 0 --chip-id 0 --expected-name 950PR \ + --warmups 5 --warmup-ms 25 --samples 10 --seed 20261023 \ + --timeout-seconds 300 --cpu-threads 4 +``` + +Then repeat the controller command with `--phase all-ready`, the same plan and run directory. Already successful smoke cases are reused; every other selected case receives its own before/after numerical gates. Execution stops on an unexpected kernel, numerical, health or timeout failure. Inspect failures before resuming in a fresh process. The 300-second per-case watchdog preserves a running marker if execution hangs. + +## FP8: inspect the installed tile first + +The tested CANN kernel can select a local A tile larger than L0A. For `M=264, N=2304, K=7168`, the installed tile is `272×128`: two FP8 A buffers require 69,632 bytes, exceeding the 65,536-byte capacity. This is a **local tile** limit, not a limit on whole matrix size or a blanket `M <= 256` rule. + +The preload hook reads the actual host tiling before GEMM dispatch. Preflight always rejects the GEMM with error `100000`, including tiles that fit; it produces no timing result. The decoder supports the validated 152-byte ABI and dispatch key 5124 for the named FP8 kernel. Other kernels/ABIs are skipped as unverified. The double-buffer bound is conservative and source-derived; this is not a general CANN tiling decoder. + +```bash +c++ -std=c++17 -O2 -shared -fPIC \ + "$ASCEND_SCRIPTS/operatorx_fp8_l0_guard.cpp" -ldl \ + -o "$ASCEND_RESULTS/liboperatorx_fp8_l0_guard.so" + +python "$ASCEND_SCRIPTS/prepare.py" \ + --input "$ASCEND_SCRIPTS/examples/fp8.json" --kind fp8 \ + --memory-budget-bytes 103079215104 --output "$ASCEND_RESULTS/fp8-plan.json" + +python "$ASCEND_SCRIPTS/operatorx_batch_campaign.py" _preflight-child \ + "$ASCEND_RESULTS/health.json" \ + '{"board_id":0,"chip_id":0,"device":0,"expected_name":"950PR","expect_pci":null}' + +TASK_QUEUE_ENABLE=0 LD_PRELOAD="$ASCEND_RESULTS/liboperatorx_fp8_l0_guard.so" \ +python "$ASCEND_SCRIPTS/operatorx_fp8_l0_preflight.py" \ + --shape 240 2304 7168 --output "$ASCEND_RESULTS/guard-smoke.jsonl" \ + --guard-so "$ASCEND_RESULTS/liboperatorx_fp8_l0_guard.so" \ + --worker-dir "$ASCEND_SCRIPTS" --health-report "$ASCEND_RESULTS/health.json" \ + --device 0 --memory-budget-bytes 103079215104 +``` + +First verify that this known-safe smoke records `status=inspected`, `observed=true`, `decision=within_capacity`, `mode=1`, `forward_allowed=false`, and 61,440 L0A bytes. Do not check a potentially unsafe shape until actual interception is established on the installed stack. + +```bash +TASK_QUEUE_ENABLE=0 LD_PRELOAD="$ASCEND_RESULTS/liboperatorx_fp8_l0_guard.so" \ +python "$ASCEND_SCRIPTS/operatorx_fp8_l0_preflight.py" \ + --plan "$ASCEND_RESULTS/fp8-plan.json" --output "$ASCEND_RESULTS/guard.jsonl" \ + --guard-so "$ASCEND_RESULTS/liboperatorx_fp8_l0_guard.so" \ + --worker-dir "$ASCEND_SCRIPTS" --health-report "$ASCEND_RESULTS/health.json" \ + --device 0 --memory-budget-bytes 103079215104 + +python "$ASCEND_SCRIPTS/fp8_plan.py" \ + --plan "$ASCEND_RESULTS/fp8-plan.json" --observations "$ASCEND_RESULTS/guard.jsonl" \ + --output "$ASCEND_RESULTS/fp8-approved.json" + +python "$ASCEND_SCRIPTS/operatorx_batch_campaign.py" run \ + --plan "$ASCEND_RESULTS/fp8-approved.json" --run-dir "$ASCEND_RESULTS/fp8" \ + --worker-script "$ASCEND_SCRIPTS/operatorx_fp8_block_worker.py" \ + --phase smoke --device 0 --board-id 0 --chip-id 0 --expected-name 950PR \ + --warmups 5 --warmup-ms 25 --samples 10 --seed 20261023 \ + --timeout-seconds 300 --cpu-threads 4 +``` + +Run `all-ready` afterward as above. `LD_PRELOAD` and `TASK_QUEUE_ENABLE=0` are scoped to the inspection commands and must not be set for timing. The controller requires complete observations for the selected FP8 plan and rechecks the device identity before execution. Over-capacity and unverified cases remain explicit skips, with no fallback implementation or accepted latency. + +## Timing and validation contract + +- Five warmups, followed by a 25 ms ramp; the first timing call in each process has a 1-second ramp floor. +- Ten preallocated event pairs, a 256 MiB write before each operation, all ten calls queued, then one synchronization. The reported latency is the sixth sorted sample. +- Four queued cache writes precede the timed batch as a launch shield. They are **not equivalent to CUDA `_sleep`**. Cache eviction is not proven. NPU graphs and GPU throttle-retry selection are not emulated. +- BF16 uses the serving-style contiguous `[N,K]` weight layout. FP8 times dynamic quantization and native GEMM together. FP8 uses one Torch CPU thread, while the unquantized worker uses the controller's configured count. +- Sampled CPU FP64 full-K dot products and a full output-finiteness scan run before and after timing. FP8 additionally checks every activation's quantization error and scale validity. This is not an exhaustive CPU output reference or a claim of CUDA-quantizer byte equivalence. +- Queued batch wall time includes shield/cache writes and final synchronization. It is recorded separately and is not represented as individual synchronized wall samples. +- Journals keep all attempts and raw event samples. The last attempt determines resume status; no fastest-of-retries selection is performed. Nothing is submitted automatically. + +The measurement routines were used for the queued 950PR campaign; the large BF16 shape reproduced approximately 377 TFLOPS against a 378-TFLOPS nominal Cube reference. The entry-point packaging and plan approval checks are separate from the external campaign's frozen source hashes. Results from a per-sample synchronized loop are a different protocol and must not be mixed into these curves. + +## Files and checks + +`results.sqlite3` contains the runtime/source fingerprint and append-only attempts. `results.json` is a latest-attempt summary. Each attempt directory contains the requested case, raw worker output, stdout/stderr, process checks and sampled SMI telemetry. These standalone artifacts are not the normal `operatorx.core.Result` ingestion format. + +```bash +python -m pytest operatorx/tests/test_ascend_plan.py \ + operatorx/tests/test_ascend_queued_timing.py operatorx/tests/test_ascend_l0_guard.py +``` + +The guard fixture is captured host tiling data, not a vendor device binary. Tests compile the guard on the CPU and exercise real decoder and launch-hook behavior against a mock runtime. Native preflight is still required to establish Linux symbol interception on each installed stack. diff --git a/operatorx/scripts/ascend/examples/bf16.json b/operatorx/scripts/ascend/examples/bf16.json new file mode 100644 index 0000000000..211ac85e62 --- /dev/null +++ b/operatorx/scripts/ascend/examples/bf16.json @@ -0,0 +1,5 @@ +[ + {"type":"gemm","args":{"m":128,"n":512,"k":512,"a":{"dtype":"bf16"},"b":{"dtype":"bf16"},"out":"bf16"},"sources":[]}, + {"type":"gemm","args":{"m":128,"n":128,"k":128,"a":{"dtype":"bf16"},"b":{"dtype":"bf16"},"out":"fp32"},"sources":[]}, + {"type":"gemm","args":{"m":49152,"n":7168,"k":6144,"a":{"dtype":"bf16"},"b":{"dtype":"bf16"},"out":"bf16"},"sources":[]} +] diff --git a/operatorx/scripts/ascend/examples/fp8.json b/operatorx/scripts/ascend/examples/fp8.json new file mode 100644 index 0000000000..7cc2ca89f0 --- /dev/null +++ b/operatorx/scripts/ascend/examples/fp8.json @@ -0,0 +1,4 @@ +[ + {"type":"gemm","args":{"m":240,"n":2304,"k":7168,"a":{"dtype":"e4m3","scale":{"dtype":"fp32","group":[1,128],"static":false}},"b":{"dtype":"e4m3","scale":{"dtype":"fp32","group":[128,128],"static":true}},"out":"bf16"},"sources":[]}, + {"type":"gemm","args":{"m":264,"n":2304,"k":7168,"a":{"dtype":"e4m3","scale":{"dtype":"fp32","group":[1,128],"static":false}},"b":{"dtype":"e4m3","scale":{"dtype":"fp32","group":[128,128],"static":true}},"out":"bf16"},"sources":[]} +] diff --git a/operatorx/scripts/ascend/fp8_plan.py b/operatorx/scripts/ascend/fp8_plan.py new file mode 100644 index 0000000000..52307b0227 --- /dev/null +++ b/operatorx/scripts/ascend/fp8_plan.py @@ -0,0 +1,135 @@ +from __future__ import annotations + +import argparse +import hashlib +import json +from collections import Counter +from pathlib import Path +from typing import Any + +KERNEL = "QuantBatchMatmulV3_ND_ND_fp8e4m3_fp8e4m3_fp32_bf16_high_performance" + + +def validate_observation( + row: dict[str, Any], case: dict[str, Any], worker_sha: str +) -> str: + if any(row.get(k) != case.get(k) for k in ("case_id", "opType", "args")): + raise ValueError("Guard case identity mismatch") + provenance = row.get("provenance", {}) + error = row.get("launch_exception", "") + guard = row.get("guard", {}) + if ( + row.get("status") != "inspected" + or "100000" not in error + or any(code in error for code in ("507015", "507035")) + or provenance.get("worker_sha256") != worker_sha + or provenance.get("task_queue_enable") != "0" + or guard.get("observed") is not True + or guard.get("mode") != 1 + or guard.get("forward_allowed") is not False + ): + raise ValueError("Guard did not establish an isolated prelaunch rejection") + if guard.get("decision") == "unverified": + return "skipped_unverified_tiling" + if guard.get("dispatch_key") != 5124 or guard.get("kernel_name") not in { + KERNEL, + KERNEL + "_5124", + KERNEL + "_5124_mix_aic", + KERNEL + "_5124_mix_aiv", + }: + raise ValueError("Unknown FP8 kernel ABI/key") + for dimension in ("m", "n", "k"): + if any( + guard.get(prefix + dimension) != case["args"][dimension] + for prefix in ("", "expected_") + ): + raise ValueError( + "Observed tiling dimensions differ from the requested case" + ) + for name, alignment in (("base_m", 16), ("base_n", 16), ("base_k", 32)): + value = guard.get(name) + if type(value) is not int or value <= 0 or value % alignment: + raise ValueError("Invalid local tile") + required = 2 * guard["base_m"] * guard["base_k"] + if guard.get("l0a_bytes") != required or guard.get("l0a_capacity_bytes") != 65536: + raise ValueError("Invalid L0A capacity calculation") + expected = "within_capacity" if required <= 65536 else "over_capacity" + if guard.get("decision") != expected: + raise ValueError("Guard decision contradicts its local tile") + return "new" if required <= 65536 else "skipped_l0a_capacity" + + +def apply_guard(plan: dict[str, Any], rows: list[dict[str, Any]]) -> dict[str, Any]: + if plan.get("kind") != "fp8": + raise ValueError("Only FP8 plans require this guard") + selected = {c["case_id"]: c for c in plan["cases"] if c["phase"] == "new"} + observations = {} + identities = set() + for row in rows: + cid = row.get("case_id") + if cid not in selected or cid in observations: + raise ValueError("Unexpected or duplicate guard case") + phase = validate_observation(row, selected[cid], plan["worker_sha256"]) + identity = row.get("hardware_identity") + if not isinstance(identity, str) or len(identity) != 64: + raise ValueError("Missing guard hardware identity") + identities.add(identity) + observations[cid] = phase + if set(observations) != set(selected) or len(identities) != 1: + raise ValueError("Incomplete guard coverage or mixed hardware identities") + result = json.loads(json.dumps(plan)) + for case in result["cases"]: + if case["case_id"] in observations: + case["phase"] = observations[case["case_id"]] + valid = {cid for cid, phase in observations.items() if phase == "new"} + result["smoke_case_ids"] = [cid for cid in plan["smoke_case_ids"] if cid in valid] + if valid and not result["smoke_case_ids"]: + result["smoke_case_ids"] = [sorted(valid)[0]] + result["counts"] = dict(Counter(c["phase"] for c in result["cases"])) + result["fp8_l0a"] = {"hardware_identity": identities.pop(), "observations": rows} + return result + + +def verify_plan(plan: dict[str, Any]) -> None: + proof = plan.get("fp8_l0a") + if not isinstance(proof, dict): + raise ValueError( + "FP8 requires an approved prelaunch L0A plan; run the guard first" + ) + original = json.loads(json.dumps(plan)) + for case in original["cases"]: + if case["phase"] in ("skipped_l0a_capacity", "skipped_unverified_tiling"): + case["phase"] = "new" + checked = apply_guard(original, proof["observations"]) + if ( + checked["cases"] != plan["cases"] + or checked["fp8_l0a"]["hardware_identity"] != proof["hardware_identity"] + ): + raise ValueError("FP8 plan differs from the validated tiling observations") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--observations", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + plan = apply_guard( + json.loads(args.plan.read_text()), + [ + json.loads(line) + for line in args.observations.read_text().splitlines() + if line.strip() + ], + ) + plan["fp8_l0a"]["source_sha256"] = hashlib.sha256( + args.observations.read_bytes() + ).hexdigest() + with args.output.open("x") as stream: + json.dump(plan, stream, indent=2, allow_nan=False) + stream.write("\n") + print(json.dumps(plan["counts"])) + + +if __name__ == "__main__": + main() diff --git a/operatorx/scripts/ascend/operatorx_ascend_worker.py b/operatorx/scripts/ascend/operatorx_ascend_worker.py new file mode 100644 index 0000000000..01bf96c346 --- /dev/null +++ b/operatorx/scripts/ascend/operatorx_ascend_worker.py @@ -0,0 +1,772 @@ +#!/usr/bin/env python3 + +from __future__ import annotations + +import hashlib +import json +import math +import platform +import random +import sys +from datetime import datetime, timezone +from pathlib import Path + +import operatorx_queued_timing as queued_timing + +SCHEMA_VERSION = 1 +DTYPE_BYTES = {"bf16": 2, "fp16": 2, "fp32": 4} +DEFAULT_CACHE_WRITE_BYTES = 256 * 1024**2 +DEFAULT_WORKSPACE_RESERVE_BYTES = 512 * 1024**2 +DEFAULT_REFERENCE_SAMPLES = 64 +MAX_WARMUP_LAUNCHES = 1_000_000 +FINITE_CHUNK_ELEMENTS = 1024 * 1024 +LAYOUT = ( + "contiguous A[M,K], contiguous W[N,K], output[M,N]; mathematical A @ W.T + bias" +) +FP32_REFERENCE_SOURCE = "https://github.com/SemiAnalysisAI/InferenceX/blob/8f03d279200eedfae08027615fdeca9f43b81cc1/experimental/operatorx/runners/common/vllm/linear.py" +REFERENCE_SOURCE_SHA256 = ( + "6c4cea138b9eb99154fb3385a77f459e04eec14bdaf3ec33f3855cea047c15a6" +) +WEIGHT_STD = 0.02 + + +def _unsupported(code, reason): + return { + "supported": False, + "status": "unsupported", + "reason_code": code, + "reason": reason, + "normalized": None, + } + + +def _positive_int(value): + return type(value) is int and value > 0 + + +def classify_case(case): + """Pure, fail-closed support classification; supported does not mean tested.""" + if not isinstance(case, dict): + return _unsupported("invalid_case", "Case must be a JSON object") + op_type = case.get("opType", case.get("op_type")) + if "opType" in case and "op_type" in case and case["opType"] != case["op_type"]: + return _unsupported("invalid_case", "Conflicting opType and op_type") + if op_type != "gemm": + return _unsupported( + "operator_not_implemented", "This worker implements only GEMM" + ) + args = case.get("args") + if not isinstance(args, dict): + return _unsupported("invalid_args", "args must be a JSON object") + unknown = set(args) - {"m", "n", "k", "a", "b", "out", "bias", "activation"} + if unknown: + return _unsupported( + "unknown_semantic_arguments", + "Unimplemented GEMM argument(s): " + ", ".join(sorted(unknown)), + ) + for name in ("m", "n", "k"): + if not _positive_int(args.get(name)): + return _unsupported( + "invalid_dimensions", f"{name} must be a positive integer" + ) + for name in ("a", "b"): + desc = args.get(name) + if not isinstance(desc, dict) or "dtype" not in desc: + return _unsupported( + "invalid_tensor_descriptor", f"{name} must contain a dtype descriptor" + ) + if set(desc) != {"dtype"}: + return _unsupported( + "tensor_semantics_not_implemented", + f"{name}: scales, quantization and additional descriptor fields require a separate exact adapter", + ) + if not isinstance(desc["dtype"], str) or desc["dtype"] not in DTYPE_BYTES: + return _unsupported( + "dtype_not_implemented", + f"{name}: only native bf16/fp16/fp32 are implemented", + ) + out = args.get("out", "bf16") + if not isinstance(out, str) or out not in DTYPE_BYTES: + return _unsupported( + "output_dtype_not_implemented", + "Canonical out must be the string bf16/fp16/fp32, not a descriptor object", + ) + dtype = args["a"]["dtype"] + dtype_b = args["b"]["dtype"] + bias = args.get("bias", False) + if type(bias) is not bool: + return _unsupported( + "bias_semantics_not_implemented", + "bias must be a boolean (native model-dtype vector of length N)", + ) + if args.get("activation") is not None: + return _unsupported( + "activation_not_implemented", "Fused activation is not implemented" + ) + implementation = "native_linear" + tolerance_dtype = out + if dtype == dtype_b == out: + pass + elif dtype == "bf16" and dtype_b in {"bf16", "fp32"} and out == "fp32": + if dtype_b == "bf16" and not bias: + implementation = "native_bf16_mm_fp32_output" + elif dtype_b == "bf16": + implementation = "source_defined_bf16_linear_then_fp32_cast" + tolerance_dtype = "bf16" + else: + implementation = "source_defined_timed_fp32_input_promotion" + else: + return _unsupported( + "mixed_precision_not_implemented", + "No exact adapter for this input/output precision combination; output casts are not a substitute for native FP32 accumulation", + ) + return { + "supported": True, + "status": "supported_unvalidated", + "reason_code": "native_linear_candidate", + "reason": "Unquantized GEMM candidate; hardware/API execution and correctness validation are still required", + "normalized": { + "m": args["m"], + "n": args["n"], + "k": args["k"], + "dtype": out, + "dtype_a": dtype, + "dtype_b": dtype_b, + "dtype_out": out, + "tolerance_dtype": tolerance_dtype, + "implementation": implementation, + "bias": bias, + "layout": LAYOUT, + "fp32_semantics_source": FP32_REFERENCE_SOURCE + if implementation != "native_linear" + else None, + }, + } + + +def estimate_memory( + case, + *, + cache_write_bytes=DEFAULT_CACHE_WRITE_BYTES, + workspace_reserve_bytes=DEFAULT_WORKSPACE_RESERVE_BYTES, +): + """Conservative live tensor estimate; reserve is a budget, not measured workspace. + + Two output buffers cover Python reassignment while the old output is alive. + Reference/finite validation transfers use CPU chunks, not full input clones. + Library allocator fragmentation and opaque workspace can exceed the reserve. + """ + support = classify_case(case) + if not support["supported"]: + raise ValueError(support["reason"]) + for name, value in ( + ("cache_write_bytes", cache_write_bytes), + ("workspace_reserve_bytes", workspace_reserve_bytes), + ): + if type(value) is not int or value < 0: + raise ValueError(f"{name} must be a nonnegative integer") + n = support["normalized"] + width = DTYPE_BYTES[n["dtype_out"]] + result = { + "a_bytes": n["m"] * n["k"] * DTYPE_BYTES[n["dtype_a"]], + "weight_bytes": n["n"] * n["k"] * DTYPE_BYTES[n["dtype_b"]], + "bias_bytes": n["n"] * DTYPE_BYTES[n["dtype_b"]] if n["bias"] else 0, + "output_bytes": n["m"] * n["n"] * width, + "output_live_buffer_count": 2, + "timed_input_promotion_bytes": n["m"] * n["k"] * 4 + if n["implementation"] == "source_defined_timed_fp32_input_promotion" + else 0, + "timed_intermediate_output_bytes": n["m"] * n["n"] * 2 + if n["implementation"] == "source_defined_bf16_linear_then_fp32_cast" + else 0, + "cache_write_bytes": cache_write_bytes, + "workspace_reserve_bytes": workspace_reserve_bytes, + } + result["tensor_and_cache_bytes"] = ( + result["a_bytes"] + + result["weight_bytes"] + + result["bias_bytes"] + + 2 * result["output_bytes"] + + cache_write_bytes + + result["timed_input_promotion_bytes"] + + result["timed_intermediate_output_bytes"] + ) + # Preserve the public full-tensor randn/scaling/cast arithmetic. For plain + # linear, out-of-place scaling overlaps random and scaled model-dtype weights. + # For _TorchMM, FP32 random weights are scaled in place before the final cast. + if n["implementation"] == "native_linear": + weight_generation_peak = 2 * result["weight_bytes"] + bias_generation_peak = result["weight_bytes"] + 2 * result["bias_bytes"] + else: + weight_generation_peak = n["n"] * n["k"] * 4 + if n["dtype_b"] != "fp32": + weight_generation_peak += result["weight_bytes"] + bias_generation_peak = result["weight_bytes"] + result["bias_bytes"] + result["input_generation_peak_bytes"] = max( + weight_generation_peak, + bias_generation_peak, + result["a_bytes"] + result["weight_bytes"] + result["bias_bytes"], + ) + result["generation_temporary_extra_bytes"] = max( + 0, result["input_generation_peak_bytes"] - result["tensor_and_cache_bytes"] + ) + result["estimated_required_bytes"] = ( + max(result["tensor_and_cache_bytes"], result["input_generation_peak_bytes"]) + + workspace_reserve_bytes + ) + result["required_bytes"] = result["estimated_required_bytes"] + # At most two FP64 K-length reference rows and a bounded finite-check CPU chunk. + result["reference_cpu_working_bytes_estimate"] = 32 * n[ + "k" + ] + FINITE_CHUNK_ELEMENTS * (width + 1) + result["workspace_is_measured"] = False + return result + + +def check_memory_budget(estimate, *, available_bytes, memory_budget_bytes): + for name, value in ( + ("available_bytes", available_bytes), + ("memory_budget_bytes", memory_budget_bytes), + ): + if not _positive_int(value): + raise ValueError(f"{name} must be a positive integer") + limit = min(available_bytes, memory_budget_bytes) + return { + "fits": estimate["estimated_required_bytes"] <= limit, + "available_bytes": available_bytes, + "memory_budget_bytes": memory_budget_bytes, + "effective_limit_bytes": limit, + "estimated_required_bytes": estimate["estimated_required_bytes"], + } + + +def upper_median(values): + if not values or any(not math.isfinite(x) or x <= 0 for x in values): + raise ValueError( + "Timing samples must be nonempty, finite and strictly positive" + ) + return sorted(values)[len(values) // 2] + + +def sample_coordinates(m, n, count, seed): + """Seeded coverage including boundaries; no allocation proportional to M*N.""" + if not all(_positive_int(x) for x in (m, n, count)): + raise ValueError("Reference dimensions/count must be positive integers") + count = min(count, m * n) + indices = [] + for index in (0, n - 1, (m - 1) * n, m * n - 1, (m // 2) * n + n // 2): + if index not in indices and len(indices) < count: + indices.append(index) + rng = random.Random(seed) + while len(indices) < count: + index = rng.randrange(m * n) + if index not in indices: + indices.append(index) + return [(index // n, index % n) for index in indices] + + +def error_statistics(actual, reference, *, dtype, k, input_product_scale=1.0): + """Compare native output values with independent FP64 dot products. + + Relative tolerance is two output epsilons (four for FP32). Absolute tolerance + is input_product_scale * 1e-5 * max(1,sqrt(K)) for cancellation near zero. The absolute + component scales like random-input accumulation error, not like BF16 output + epsilon; an all-zero result or broad output quantization does not pass. + """ + if dtype not in DTYPE_BYTES or not _positive_int(k): + raise ValueError("Invalid reference dtype/K") + if not math.isfinite(input_product_scale) or input_product_scale <= 0: + raise ValueError("Reference input-product scale must be finite and positive") + if not actual or len(actual) != len(reference): + raise ValueError("Actual and reference samples must have equal nonzero lengths") + epsilon = {"bf16": 2**-7, "fp16": 2**-10, "fp32": 2**-23}[dtype] + rtol = epsilon * (4 if dtype == "fp32" else 2) + atol = input_product_scale * 1e-5 * max(1.0, math.sqrt(k)) + finite = all(math.isfinite(x) for x in (*actual, *reference)) + stats = { + "passed": False, + "all_samples_finite": finite, + "sample_count": len(actual), + "atol": atol, + "rtol": rtol, + "reference_dtype": "fp64", + "input_product_scale_for_tolerance": input_product_scale, + "tolerance_rule": "abs(error) <= atol + rtol * abs(fp64_reference)", + } + if not finite: + stats.update( + { + "failed_samples": len(actual), + "max_abs_error": None, + "max_rel_error": None, + "rms_error": None, + "normalized_rms_error": None, + "max_tolerance_ratio": None, + } + ) + return stats + errors = [abs(a - r) for a, r in zip(actual, reference)] + limits = [atol + rtol * abs(r) for r in reference] + failed = sum(e > limit for e, limit in zip(errors, limits)) + rms = math.sqrt(sum(e * e for e in errors) / len(errors)) + reference_rms = math.sqrt(sum(r * r for r in reference) / len(reference)) + stats.update( + { + "passed": failed == 0, + "failed_samples": failed, + "max_abs_error": max(errors), + "max_rel_error": max( + e / max(abs(r), atol) for e, r in zip(errors, reference) + ), + "rms_error": rms, + "normalized_rms_error": rms / max(reference_rms, atol), + "max_tolerance_ratio": max(e / limit for e, limit in zip(errors, limits)), + } + ) + return stats + + +def tensor_descriptor(tensor): + return { + "shape": list(tensor.shape), + "stride": list(tensor.stride()), + "dtype": str(tensor.dtype), + "device": str(tensor.device), + "contiguous": tensor.is_contiguous(), + "numel": tensor.numel(), + "bytes": tensor.numel() * tensor.element_size(), + } + + +def sampled_reference(torch, a, weight, bias, coordinates): + """Copy only the requested rows, then multiply/sum them on CPU in FP64.""" + values = [] + for row, col in coordinates: + # CPU transfer precedes the conversion: no accidental FP64 NPU operation. + av = a[row].detach().cpu().to(dtype=torch.float64) + wv = weight[col].detach().cpu().to(dtype=torch.float64) + if not bool(torch.isfinite(av).all()) or not bool(torch.isfinite(wv).all()): + raise ValueError("Nonfinite generated input in sampled reference rows") + value = torch.dot(av, wv).item() + if bias is not None: + value += bias[col].detach().cpu().item() + values.append(value) + return values + + +def validate_output( + torch, output, *, normalized, coordinates, reference, input_product_scale=1.0 +): + expected_shape = [normalized["m"], normalized["n"]] + expected_dtype = { + "bf16": torch.bfloat16, + "fp16": torch.float16, + "fp32": torch.float32, + }[normalized["dtype"]] + if list(output.shape) != expected_shape or output.dtype != expected_dtype: + raise ValueError( + "Native kernel output shape/dtype does not match the requested case" + ) + if not output.is_contiguous(): + raise ValueError("Native kernel returned a noncontiguous output") + # Check every output element for NaN/Inf with bounded CPU transfer memory. + flat = output.detach().view(-1) + all_finite = True + for offset in range(0, flat.numel(), FINITE_CHUNK_ELEMENTS): + if not bool( + torch.isfinite(flat[offset : offset + FINITE_CHUNK_ELEMENTS].cpu()).all() + ): + all_finite = False + break + actual = [output[row, col].detach().cpu().item() for row, col in coordinates] + stats = error_statistics( + actual, + reference, + dtype=normalized["tolerance_dtype"], + k=normalized["k"], + input_product_scale=input_product_scale, + ) + stats["tolerance_dtype"] = normalized["tolerance_dtype"] + stats["all_output_elements_finite"] = all_finite + stats["passed"] = stats["passed"] and all_finite + # Nonfinite values cannot appear in JSON; the failed check remains explicit. + stats["samples"] = [ + { + "row": row, + "col": col, + "actual": a if math.isfinite(a) else None, + "reference_fp64": r if math.isfinite(r) else None, + } + for (row, col), a, r in zip(coordinates, actual, reference) + ] + return stats + + +def _provenance(case): + semantic = { + "opType": case.get("opType", case.get("op_type")), + "args": case.get("args"), + } + return { + "worker_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "case_semantic_sha256": hashlib.sha256( + json.dumps( + semantic, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode() + ).hexdigest(), + "python": platform.python_version(), + "machine": platform.machine(), + "started_at": datetime.now(timezone.utc).isoformat(), + "native_kernel_result_not_rewritten_for_validation": True, + } + + +def _base_result(case): + return { + "schema_version": SCHEMA_VERSION, + "case_id": case.get("case_id", case.get("id")), + "opType": case.get("opType", case.get("op_type")), + "args": case.get("args"), + "sources": case.get("sources", []), + "testlists": case.get("testlists", []), + "support": classify_case(case), + "status": "unvalidated", + "metrics": None, + "warnings": [ + "Prepared worker; an unvalidated plan is not a hardware result.", + "Cache writes do not establish a cold-cache state or public protocol equivalence.", + "Correctness uses sampled FP64 dot products and a full-output finite check; it is not an exhaustive reference comparison.", + ], + "provenance": _provenance(case), + } + + +def plan_case( + case, + *, + cache_write_bytes=DEFAULT_CACHE_WRITE_BYTES, + workspace_reserve_bytes=DEFAULT_WORKSPACE_RESERVE_BYTES, +): + result = _base_result(case) + if not result["support"]["supported"]: + result["status"] = "unsupported" + return result + result["memory_estimate"] = estimate_memory( + case, + cache_write_bytes=cache_write_bytes, + workspace_reserve_bytes=workspace_reserve_bytes, + ) + return result + + +class WorkerFailure(Exception): + def __init__(self, kind, message): + super().__init__(message) + self.kind = kind + + +def execute_linear(torch, a, weight, bias, implementation): + """The complete timed operation; there are no hidden casts in validation. + + FP32 mixed paths reproduce _TorchMM.forward in the pinned reference. In + particular, the BF16+bias final cast is explicitly *not* FP32 accumulation. + No fallback substitutes a cast if the native out_dtype API is unavailable. + """ + if implementation == "native_linear": + return torch.nn.functional.linear(a, weight, bias) + if implementation == "native_bf16_mm_fp32_output": + try: + return torch.mm(a, weight.t(), out_dtype=torch.float32) + except (TypeError, NotImplementedError) as exc: + raise WorkerFailure( + "native_output_dtype_api_unavailable", str(exc) + ) from exc + if implementation in { + "source_defined_bf16_linear_then_fp32_cast", + "source_defined_timed_fp32_input_promotion", + }: + return torch.nn.functional.linear(a.to(weight.dtype), weight, bias).float() + raise WorkerFailure("invalid_implementation", "Unknown implementation path") + + +def generate_inputs(torch, spec, *, device): + """Match pinned _fill/_TorchMM generation arithmetic outside timed regions. + + _prepare_gemm sets the default dtype to BF16 around _fill, so its unqualified + randn and out-of-place scaling both use BF16. _TorchMM instead creates FP32 + random weights, scales in place and casts to the final dtype. Explicit dtypes + here avoid depending on the caller's mutable default. Full tensor generation + retains the source's RNG call shapes; no chunking changes the sample stream. + Parameter wrapper construction/copy_ is omitted because it does not change + values. Matching random values across CUDA and NPU generators is not claimed. + """ + dtypes = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32} + plain = spec["implementation"] == "native_linear" + if plain: + weight = ( + torch.randn( + spec["n"], spec["k"], device=device, dtype=dtypes[spec["dtype_b"]] + ) + * WEIGHT_STD + ) + bias = ( + torch.randn(spec["n"], device=device, dtype=dtypes[spec["dtype_b"]]) + * WEIGHT_STD + if spec["bias"] + else None + ) + else: + weight = ( + torch.randn(spec["n"], spec["k"], device=device, dtype=torch.float32) + .mul_(WEIGHT_STD) + .to(dtypes[spec["dtype_b"]]) + ) + bias = ( + torch.zeros(spec["n"], device=device, dtype=dtypes[spec["dtype_b"]]) + if spec["bias"] + else None + ) + a = torch.randn(spec["m"], spec["k"], device=device, dtype=dtypes[spec["dtype_a"]]) + matched = ( + not plain or spec["dtype_a"] == spec["dtype_b"] == spec["dtype_out"] == "bf16" + ) + recipe = { + "source_url": FP32_REFERENCE_SOURCE, + "source_sha256": REFERENCE_SOURCE_SHA256, + "source_functions": "_prepare_gemm -> _fill" + if plain + else "_prepare_fp32_out -> _TorchMM.__init__", + "a_recipe": f"torch.randn(M,K,device=device,dtype={spec['dtype_a']}) after weight and bias generation", + "weight_recipe": ( + f"torch.randn(N,K,device=device,dtype={spec['dtype_b']}) * 0.02" + if plain + else f"torch.randn(N,K,device=device,dtype=fp32).mul_(0.02).to({spec['dtype_b']})" + ), + "bias_recipe": ( + f"torch.randn(N,device=device,dtype={spec['dtype_b']}) * 0.02" + if plain + else f"torch.zeros(N,device=device,dtype={spec['dtype_b']})" + ) + if spec["bias"] + else "none", + "generation_order": ["weight", "bias" if spec["bias"] else "no_bias", "a"], + "a_dtype": spec["dtype_a"], + "weight_and_bias_dtype": spec["dtype_b"], + "generated_device": device, + "weight_standard_deviation_before_dtype_rounding": WEIGHT_STD, + "public_input_distribution_reproduced": matched, + "full_tensor_rng_calls": True, + "cross_stack_rng_identity_claimed": False, + "parameter_allocation_copy_omitted": True, + } + if not matched: + recipe["qualification"] = ( + "Requested FP16/FP32 plain-linear dtype extends _fill; this exact dtype combination has no path in the pinned vLLM reference" + ) + return a, weight, bias, recipe + + +def _run_native(case, config, result): + # Deliberately local imports: classification/planning never load torch or NPU. + import torch + import torch_npu + + result["provenance"].update( + {"torch": str(torch.__version__), "torch_npu": str(torch_npu.__version__)} + ) + npu = torch.npu + if not npu.is_available(): + raise WorkerFailure("hardware_unavailable", "torch.npu.is_available() is false") + device = f"npu:{config['device']}" + npu.set_device(device) + # Preserve the advertised FP32 inputs. Reduced-precision HF32 is not requested. + npu.matmul.allow_hf32 = False + if bool(npu.matmul.allow_hf32): + raise WorkerFailure("precision_configuration", "Cannot disable NPU matmul HF32") + result["provenance"]["allow_hf32"] = False + torch.set_grad_enabled(False) + torch.manual_seed(config["seed"]) + npu.manual_seed(config["seed"]) + npu.synchronize() + free, total = npu.mem_get_info(config["device"]) + budget = check_memory_budget( + result["memory_estimate"], + available_bytes=int(free), + memory_budget_bytes=config["memory_budget_bytes"], + ) + budget["total_device_bytes"] = int(total) + result["memory_budget_check"] = budget + if not budget["fits"]: + raise WorkerFailure( + "memory_budget_exceeded", + "Estimated inputs, two outputs, cache writes and workspace reserve exceed the smaller of free device memory and configured budget", + ) + npu.reset_peak_memory_stats(config["device"]) + baseline = { + "allocated_bytes": int(npu.memory_allocated(config["device"])), + "reserved_bytes": int(npu.memory_reserved(config["device"])), + } + try: + spec = result["support"]["normalized"] + a, weight, bias, generation = generate_inputs(torch, spec, device=device) + cache = torch.empty( + config["cache_write_bytes"], device=device, dtype=torch.uint8 + ) + npu.synchronize() + result["tensors"] = { + "a": tensor_descriptor(a), + "weight": tensor_descriptor(weight), + "bias": tensor_descriptor(bias) if bias is not None else None, + "cache_write": tensor_descriptor(cache), + } + result["provenance"]["implementation"] = spec["implementation"] + result["provenance"]["fp32_semantics_source"] = spec["fp32_semantics_source"] + result["input_generation"] = {**generation, "seed": config["seed"]} + coordinates = sample_coordinates( + spec["m"], spec["n"], config["reference_samples"], config["seed"] + ) + reference = sampled_reference(torch, a, weight, bias, coordinates) + output = execute_linear(torch, a, weight, bias, spec["implementation"]) + npu.synchronize() + result["tensors"]["output"] = tensor_descriptor(output) + before = validate_output( + torch, + output, + normalized=spec, + coordinates=coordinates, + reference=reference, + input_product_scale=WEIGHT_STD, + ) + result["correctness"] = {"before_timing": before, "after_timing": None} + if not before["passed"]: + raise WorkerFailure( + "correctness_failed", + "Before-timing FP64 reference or finite check failed", + ) + del output # Retain at most two live result buffers during queued execution. + output, timing = queued_timing.time_op( + npu, + lambda: execute_linear(torch, a, weight, bias, spec["implementation"]), + cache, + config, + ) + timing["timed_implementation"] = spec["implementation"] + result["timing"] = timing + latency_us = upper_median(timing["device_event_samples_us"]) + after = validate_output( + torch, + output, + normalized=spec, + coordinates=coordinates, + reference=reference, + input_product_scale=WEIGHT_STD, + ) + result["correctness"]["after_timing"] = after + if not after["passed"]: + raise WorkerFailure( + "correctness_failed", + "After-timing FP64 reference or finite check failed", + ) + result["metrics"] = { + "latency_us": latency_us, + "queued_wall_latency_us_per_call": timing["queued_wall_us_per_call"], + "tflops": 2 * spec["m"] * spec["n"] * spec["k"] / (latency_us * 1e6), + "npu_graph": False, + } + result["status"] = "ok" + result["warnings"].pop(0) + finally: + result["memory_high_water"] = { + "baseline": baseline, + "max_allocated_bytes": int(npu.max_memory_allocated(config["device"])), + "max_reserved_bytes": int(npu.max_memory_reserved(config["device"])), + "scope": "PyTorch NPU allocator after initialization; opaque driver memory is not included", + } + + +def run_case( + case, + *, + memory_budget_bytes, + device=0, + samples=10, + warmups=5, + warmup_ms=25, + seed=20261023, + reference_samples=DEFAULT_REFERENCE_SAMPLES, + cache_write_bytes=DEFAULT_CACHE_WRITE_BYTES, + workspace_reserve_bytes=DEFAULT_WORKSPACE_RESERVE_BYTES, +): + result = plan_case( + case, + cache_write_bytes=cache_write_bytes, + workspace_reserve_bytes=workspace_reserve_bytes, + ) + if result["status"] == "unsupported": + return result + config = { + "memory_budget_bytes": memory_budget_bytes, + "device": device, + "samples": samples, + "warmups": warmups, + "warmup_ms": warmup_ms, + "seed": seed, + "reference_samples": reference_samples, + "cache_write_bytes": cache_write_bytes, + "workspace_reserve_bytes": workspace_reserve_bytes, + } + result["config"] = config + try: + if not _positive_int(memory_budget_bytes): + raise WorkerFailure( + "invalid_config", "memory_budget_bytes must be a positive integer" + ) + if ( + type(device) is not int + or device < 0 + or type(seed) is not int + or not 0 <= seed < 2**63 + ): + raise WorkerFailure( + "invalid_config", + "device must be nonnegative and seed must be in [0,2**63)", + ) + if type(samples) is not int or not 10 <= samples <= 10000: + raise WorkerFailure( + "invalid_config", "samples must be an integer in [10,10000]" + ) + if type(warmups) is not int or not 1 <= warmups <= 10000: + raise WorkerFailure( + "invalid_config", "warmups must be an integer in [1,10000]" + ) + if ( + type(warmup_ms) not in (int, float) + or not math.isfinite(warmup_ms) + or not 0 <= warmup_ms <= 10000 + ): + raise WorkerFailure( + "invalid_config", "warmup_ms must be finite and in [0,10000]" + ) + if type(reference_samples) is not int or not 1 <= reference_samples <= 4096: + raise WorkerFailure( + "invalid_config", "reference_samples must be an integer in [1,4096]" + ) + _run_native(case, config, result) + except Exception as exc: + result["status"] = ( + "skipped_memory" + if isinstance(exc, WorkerFailure) and exc.kind == "memory_budget_exceeded" + else "error" + ) + result["metrics"] = None + result["error"] = { + "kind": exc.kind if isinstance(exc, WorkerFailure) else "execution_failure", + "exception_type": type(exc).__name__, + "message": str(exc), + } + print( + f"OperatorX worker {result['error']['kind']}: {type(exc).__name__}: {exc}", + file=sys.stderr, + ) + result["provenance"]["finished_at"] = datetime.now(timezone.utc).isoformat() + return result diff --git a/operatorx/scripts/ascend/operatorx_batch_campaign.py b/operatorx/scripts/ascend/operatorx_batch_campaign.py new file mode 100644 index 0000000000..6d3ce3e1fd --- /dev/null +++ b/operatorx/scripts/ascend/operatorx_batch_campaign.py @@ -0,0 +1,663 @@ +#!/usr/bin/env python3 + +from __future__ import annotations + +import argparse +import contextlib +import datetime as dt +import fcntl +import gc +import hashlib +import importlib +import importlib.util +import json +import math +import os +import sys +import tempfile +import threading +import time +import traceback +from importlib import metadata +from pathlib import Path + +HERE = Path(__file__).resolve().parent +_spec = importlib.util.spec_from_file_location( + "operatorx_batch_base_campaign", HERE / "operatorx_campaign.py" +) +c = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(c) +HEALTH_QUERIES = {"health", "current-fault-event", "ecc", "ecc-enable", "pcie-err"} +EXECUTION_MODE = "persistent_worker_process" + + +def worker_script(args): + return Path( + getattr(args, "worker_script", None) or HERE / "operatorx_ascend_worker.py" + ).resolve() + + +def preflight_subprocess(args): + """Do not initialize ACL in the persistent process before torch_npu. + + CANN can retain the first aclInit configuration even after aclFinalize. The + identity helper's aclInit(None) must therefore occur in a disposable child. + A report file keeps native ACL stdout chatter separate from structured data. + """ + settings = { + key: getattr(args, key) + for key in ("board_id", "chip_id", "device", "expected_name", "expect_pci") + } + with tempfile.TemporaryDirectory(prefix="operatorx-preflight-") as temporary: + report_path = Path(temporary) / "report.json" + capture = c.command( + [ + sys.executable, + str(Path(__file__).resolve()), + "_preflight-child", + str(report_path), + c.canonical(settings), + ], + timeout=180, + ) + if capture["returncode"] != 0 or not report_path.is_file(): + raise RuntimeError("Preflight subprocess failed: " + c.canonical(capture)) + report = json.loads(report_path.read_text()) + before = report["before"] + before["preflight_subprocess"] = { + "pid": report["pid"], + "returncode": capture["returncode"], + "elapsed_s": capture["elapsed_s"], + "stdout": capture.get("stdout", ""), + "stderr": capture.get("stderr", ""), + } + args.acl_runtime_mapping = report["acl_runtime_mapping"] + # Loading the helper is pure; its ACL mapping function is never called here. + helper = c.load_module(c.idle_helper_path(), "operatorx_batch_pure_health_helper") + return before, helper, report["mapped"] + + +def preflight_child(report_path, settings_json): + args = argparse.Namespace(**json.loads(settings_json)) + before, _helper, mapped = c.preflight(args) + c.write_json( + Path(report_path), + { + "before": before, + "mapped": mapped, + "pid": os.getpid(), + "acl_runtime_mapping": getattr(args, "acl_runtime_mapping", None), + }, + ) + return 0 + + +def latest_records(connection): + latest = {} + for case_id, record in connection.execute( + "SELECT case_id,record FROM results ORDER BY seq" + ): + latest[case_id] = json.loads(record) + return latest + + +def completed_case_ids(connection): + # A new running/failed attempt invalidates an older success for resume. + return { + case_id + for case_id, record in latest_records(connection).items() + if record["status"] == "ok" + } + + +def require_smoke(plan, phase, completed): + if phase != "smoke" and not set(plan["smoke_case_ids"]).issubset(completed): + raise ValueError( + "Run every smoke case successfully in this same batch run/configuration before the full phases" + ) + + +def process_snapshot(args, helper, mapped, own_pids): + capture = c.command(["npu-smi", "info"]) + if capture["returncode"] != 0: + raise RuntimeError("Cannot verify NPU process status") + parsed = helper.status_rows(capture["stdout"], args.board_id) + keywords = {} + if getattr(args, "acl_runtime_mapping", None) is not None: + keywords["acl_runtime_mapping"] = args.acl_runtime_mapping + selected = helper.validate_identity( + parsed, + mapped, + args.board_id, + args.chip_id, + args.device, + args.expect_pci, + **keywords, + ) + foreign = [row for row in parsed["processes"] if row["pid"] not in own_pids] + capture.update(parsed=parsed, selected=selected, own_pids=sorted(own_pids)) + if foreign: + raise RuntimeError("Foreign NPU process detected: " + c.canonical(foreign)) + # Utilization can report the preceding case after its synchronization. The + # process check, not stale utilization alone, distinguishes foreign work. + capture["nonzero_utilization_alone_rejected"] = False + return capture + + +@contextlib.contextmanager +def capture_native_output(folder): + """Keep Python and native runtime diagnostics in durable per-attempt files.""" + folder = Path(folder) + folder.mkdir(parents=True, exist_ok=True) + sys.stdout.flush() + sys.stderr.flush() + saved = (os.dup(1), os.dup(2)) + try: + with ( + (folder / "stdout.txt").open("a") as out, + (folder / "stderr.txt").open("a") as err, + ): + os.dup2(out.fileno(), 1) + os.dup2(err.fileno(), 2) + yield + sys.stdout.flush() + sys.stderr.flush() + finally: + sys.stdout.flush() + sys.stderr.flush() + os.dup2(saved[0], 1) + os.dup2(saved[1], 2) + os.close(saved[0]) + os.close(saved[1]) + + +class CaseWatchdog: + """Exit 124 on expiry; the committed running marker remains the latest row.""" + + def __init__(self, seconds, evidence_path, case_id): + if not math.isfinite(seconds) or seconds <= 0: + raise ValueError("Watchdog timeout must be finite and positive") + self.seconds = seconds + self.evidence_path = Path(evidence_path) + self.case_id = case_id + self.lock = threading.Lock() + self.active = False + self.timer = None + + def _expire_locked(self): + try: + c.write_json( + self.evidence_path, + { + "status": "timeout", + "case_id": self.case_id, + "utc": c.utc(), + "exit_code": 124, + "timeout_seconds": self.seconds, + "metrics": None, + }, + ) + finally: + # No terminal success can be committed after this hard process exit. + os._exit(124) + + def _fire(self): + with self.lock: + if self.active: + self._expire_locked() + + def start(self): + with self.lock: + self.active = True + self.deadline = time.monotonic() + self.seconds + self.timer = threading.Timer(self.seconds, self._fire) + self.timer.daemon = True + self.timer.start() + + def disarm(self): + # Serialize against the callback and check the deadline ourselves, so a + # delayed watchdog thread cannot allow an expired execution to become ok. + with self.lock: + if self.active and time.monotonic() >= self.deadline: + self._expire_locked() + self.active = False + if self.timer is not None: + self.timer.cancel() + if self.timer is not None: + self.timer.join(timeout=1) + + +def _runtime_versions(torch, torch_npu): + packages = {} + for name in ("torch", "torch-npu", "numpy"): + try: + packages[name] = metadata.version(name) + except metadata.PackageNotFoundError: + packages[name] = None + cann_home = os.environ.get("ASCEND_HOME_PATH") + cann_versions = {} + if cann_home: + for name in ( + "version.cfg", + "version.info", + "compiler/version.info", + "runtime/version.info", + ): + path = Path(cann_home) / name + if path.is_file(): + cann_versions[name] = path.read_text(errors="replace") + return { + "python": sys.version, + "python_executable": str(Path(sys.executable).resolve()), + "packages": packages, + "torch_imported_version": str(torch.__version__), + "torch_npu_imported_version": str(torch_npu.__version__), + "cann_home": str(Path(cann_home).resolve()) if cann_home else None, + "cann_versions": cann_versions, + } + + +def load_runtime(cpu_threads): + os.environ["OMP_NUM_THREADS"] = str(cpu_threads) + os.environ["MKL_NUM_THREADS"] = str(cpu_threads) + torch = importlib.import_module("torch") + torch_npu = importlib.import_module("torch_npu") + torch.set_num_threads(cpu_threads) + return torch, torch_npu + + +def make_fingerprint(args, before, config, torch, torch_npu): + return { + "execution_mode": EXECUTION_MODE, + "timing_helper_sha256": c.digest(HERE / "operatorx_queued_timing.py"), + "reference_helper_sha256": c.digest(HERE / "operatorx_ascend_worker.py"), + "plan_sha256": c.digest(args.plan), + "batch_controller_sha256": c.digest(__file__), + "campaign_helper_sha256": c.digest(HERE / "operatorx_campaign.py"), + "worker_sha256": c.digest(worker_script(args)), + "worker_script": str(worker_script(args)), + "idle_helper_sha256": c.digest(c.idle_helper_path()), + "hardware_identity": before["identity_sha256"], + "config": config, + "runtime": _runtime_versions(torch, torch_npu), + } + + +def cleanup_runtime(torch): + gc.collect() + torch.npu.synchronize() + torch.npu.empty_cache() + torch.npu.synchronize() + + +def _attempt_folder(run_dir, case_id): + stem = hashlib.sha256(case_id.encode()).hexdigest()[:24] + attempts = run_dir / "attempts" + attempts.mkdir(exist_ok=True) + number = 1 + while True: + folder = attempts / f"{stem}-{number:04d}" + try: + folder.mkdir() + return folder, number + except FileExistsError: + number += 1 + + +def _invalidate(outcome, status, reason): + if outcome.get("metrics") is not None: + outcome["diagnostic_metrics_not_accepted"] = outcome["metrics"] + outcome.update(status=status, reason=reason, metrics=None) + + +def execute_case( + connection, case, config, args, worker, torch, helper, mapped, worker_sha +): + own_pids = {os.getpid()} + before = process_snapshot(args, helper, mapped, own_pids) + folder, attempt = _attempt_folder(args.run_dir, case["case_id"]) + c.write_json(folder / "case.json", case) + c.write_json(folder / "process-before.json", before) + begun = time.monotonic() + marker = { + "status": "running", + "metrics": None, + "case_id": case["case_id"], + "opType": case["opType"], + "args": case["args"], + "sources": case.get("sources", []), + "phase": args.phase, + "attempt": attempt, + "started_at": c.utc(), + "execution_mode": EXECUTION_MODE, + "controller_pid": os.getpid(), + "attempt_directory": str(folder.relative_to(args.run_dir)), + "timeout_seconds": config["timeout_seconds"], + } + c.record_result(connection, case["case_id"], marker) + watchdog = CaseWatchdog( + config["timeout_seconds"], folder / "watchdog-timeout.json", case["case_id"] + ) + state = {"lock": threading.Lock(), "own_pids": own_pids, "issues": []} + stop = threading.Event() + telemetry = folder / "telemetry.jsonl" + + def monitored(): + try: + c.monitor(stop, telemetry, args.board_id, helper, state) + except BaseException as exc: + with state["lock"]: + state["issues"].append( + { + "process_check_error": f"Monitor terminated: {type(exc).__name__}: {exc}" + } + ) + + monitor_thread = threading.Thread(target=monitored, daemon=True) + outcome = {"status": "error", "metrics": None} + interruption = None + watchdog.start() + monitor_thread.start() + try: + with capture_native_output(folder): + try: + kwargs = { + key: config[key] + for key in ( + "memory_budget_bytes", + "device", + "samples", + "warmups", + "warmup_ms", + "seed", + "cache_write_bytes", + "workspace_reserve_bytes", + ) + } + raw = worker.run_case(case, **kwargs) + # Preserve even malformed/failed original output independently of + # the acceptance record. No benchmark JSON is constructed here. + (folder / "worker-return.json").write_text( + json.dumps(raw, indent=2, allow_nan=True, default=repr) + "\n" + ) + try: + c.validate_worker_result(raw, case, config, worker_sha) + outcome = raw + except (ValueError, TypeError, KeyError) as exc: + outcome = { + "status": "error", + "metrics": None, + "reason": "Invalid worker output: " + str(exc), + } + except BaseException as exc: + traceback.print_exc() + outcome = { + "status": "interrupted" + if isinstance(exc, (KeyboardInterrupt, SystemExit)) + else "error", + "metrics": None, + "reason": f"{type(exc).__name__}: {exc}", + } + if isinstance(exc, (KeyboardInterrupt, SystemExit)): + interruption = exc + finally: + try: + cleanup_runtime(torch) + except BaseException as exc: + traceback.print_exc() + _invalidate( + outcome, + "error", + f"NPU cleanup failed: {type(exc).__name__}: {exc}", + ) + if isinstance(exc, (KeyboardInterrupt, SystemExit)): + interruption = exc + finally: + stop.set() + monitor_thread.join(timeout=15) + if monitor_thread.is_alive(): + _invalidate(outcome, "error", "Cannot drain per-case process monitor") + with state["lock"]: + issues = list(state["issues"]) + if not telemetry.exists() or not telemetry.stat().st_size: + issues.append( + {"process_check_error": "No under-load monitor sample was captured"} + ) + if issues: + outcome["process_monitor_issues"] = issues + if outcome.get("status") == "ok": + _invalidate( + outcome, + "contaminated", + "Foreign NPU work or unverified process status observed during this case", + ) + if outcome.get("status") != "ok" and outcome.get("metrics") is not None: + _invalidate( + outcome, outcome["status"], outcome.get("reason", "Unaccepted result") + ) + # Disarm only after synchronization, cleanup, validation and monitor drain. + # Expiry exits immediately, leaving the running marker and raw artifacts. + watchdog.disarm() + record = { + **marker, + **outcome, + "status": outcome["status"], + "finished_at": c.utc(), + "elapsed_s": time.monotonic() - begun, + "process_before": before, + "raw_artifacts": { + "worker_return": "worker-return.json", + "stdout": "stdout.txt", + "stderr": "stderr.txt", + "telemetry": "telemetry.jsonl", + }, + } + c.write_json(folder / "accepted-result.json", record) + c.record_result(connection, case["case_id"], record) + if interruption is not None: + raise interruption + return record + + +def run_locked(args): + plan = json.loads(args.plan.read_text()) + ids = [case["case_id"] for case in plan["cases"]] + if len(ids) != len(set(ids)) or not set(plan["smoke_case_ids"]).issubset(ids): + raise ValueError("Invalid duplicate cases or missing smoke references") + names = { + "unquantized": "operatorx_ascend_worker.py", + "fp8": "operatorx_fp8_block_worker.py", + } + if ( + plan.get("kind") not in names + or worker_script(args) != (HERE / names[plan["kind"]]).resolve() + ): + raise ValueError("Select the packaged worker matching the plan kind") + dependencies = plan.get("dependency_hashes", {}) + if set(dependencies) != { + "operatorx_queued_timing.py", + "operatorx_ascend_worker.py", + }: + raise ValueError( + "Plan lacks the timing/reference dependency fingerprint; prepare a new plan" + ) + if any( + c.digest(HERE / name) != expected for name, expected in dependencies.items() + ): + raise ValueError("Timing/reference dependency changed after planning") + if plan["kind"] == "fp8": + from fp8_plan import verify_plan + + verify_plan(plan) + selected = c.select_cases(plan, args.phase) + if not selected or any( + case.get("phase") not in ("new", "remeasure") for case in selected + ): + raise ValueError( + "Selected phase contains no ready cases or includes unprepared cases" + ) + worker_path = worker_script(args) + if plan.get("worker_sha256") != c.digest(worker_path): + raise ValueError("Worker changed after planning; rebuild plan") + args.run_dir.mkdir(parents=True, exist_ok=True) + before, helper, mapped = preflight_subprocess(args) + if ( + len(before.get("idle_observations", [])) != 2 + or set(before.get("diagnostic_gate") or {}) != HEALTH_QUERIES + ): + raise ValueError( + "Two idle checks and the complete health/fault/ECC/PCIe gate are required before torch import" + ) + if ( + "fp8_l0a" in plan + and plan["fp8_l0a"]["hardware_identity"] != before["identity_sha256"] + ): + raise ValueError("FP8 guard was recorded on different hardware") + session = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%S%fZ") + c.write_json(args.run_dir / f"preflight-{session}.json", before) + config = { + "warmups": args.warmups, + "warmup_ms": args.warmup_ms, + "samples": args.samples, + "seed": args.seed, + "device": args.device, + "timeout_seconds": args.timeout_seconds, + "cpu_threads": args.cpu_threads, + **plan["config"], + } + with capture_native_output(args.run_dir / f"runtime-{session}"): + torch, torch_npu = load_runtime(args.cpu_threads) + fingerprint = make_fingerprint(args, before, config, torch, torch_npu) + connection = c.open_journal(args.run_dir / "results.sqlite3", fingerprint) + failed = False + try: + completed = completed_case_ids(connection) + require_smoke(plan, args.phase, completed) + worker = c.load_module(worker_path, "operatorx_persistent_worker") + for case in selected: + if case["case_id"] in completed: + continue + record = execute_case( + connection, + case, + config, + args, + worker, + torch, + helper, + mapped, + fingerprint["worker_sha256"], + ) + print( + c.canonical( + { + "case_id": case["case_id"], + "status": record["status"], + "elapsed_s": record["elapsed_s"], + "execution_mode": EXECUTION_MODE, + } + ), + flush=True, + ) + if record["status"] == "ok": + completed.add(case["case_id"]) + elif record["status"] not in ("skipped_memory", "unsupported"): + failed = True + break + finally: + summary = c.export_journal(connection, args.run_dir / "results.json") + connection.close() + # Own context remains until this process exits; this capture is therefore + # explicitly process status, not a claim that the board is idle again. + c.write_json( + args.run_dir / f"process-status-after-{session}.json", + c.command(["npu-smi", "info"]), + ) + print( + c.canonical( + { + "counts": summary["counts"], + "stopped_on_failure": failed, + "execution_mode": EXECUTION_MODE, + } + ), + flush=True, + ) + return 1 if failed else 0 + + +def main(argv=None): + argv = list(sys.argv[1:] if argv is None else argv) + if len(argv) == 3 and argv[0] == "_preflight-child": + return preflight_child(argv[1], argv[2]) + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + run = sub.add_parser("run") + for flag in ("plan", "run-dir"): + run.add_argument("--" + flag, type=Path, required=True) + run.add_argument( + "--worker-script", + type=Path, + default=HERE / "operatorx_ascend_worker.py", + help="Worker implementing run_case with the same validated result contract", + ) + run.add_argument( + "--phase", choices=("smoke", "new", "remeasure", "all-ready"), required=True + ) + for flag in ( + "device", + "board-id", + "chip-id", + "warmups", + "samples", + "seed", + "timeout-seconds", + "cpu-threads", + ): + run.add_argument("--" + flag, type=int, required=True) + run.add_argument("--warmup-ms", type=float, required=True) + run.add_argument("--expected-name", required=True) + run.add_argument("--expect-pci") + args = parser.parse_args(argv) + if ( + min(args.device, args.board_id, args.chip_id, args.seed) < 0 + or args.seed >= 2**63 + ): + parser.error("Device identifiers/seed are out of range") + if ( + not 1 <= args.warmups <= 10000 + or not 10 <= args.samples <= 10000 + or not 0 <= args.warmup_ms <= 10000 + ): + parser.error("Invalid warmup/sample configuration") + if min(args.timeout_seconds, args.cpu_threads) <= 0 or args.timeout_seconds > 300: + parser.error("Timeout must be in [1,300] seconds and CPU threads positive") + if os.environ.get("LD_PRELOAD") or os.environ.get("TASK_QUEUE_ENABLE") not in ( + None, + "1", + ): + raise ValueError( + "Timing must not inherit the preflight preload or disabled task queue" + ) + if "torch" in sys.modules or "torch_npu" in sys.modules: + raise RuntimeError( + "Launch this controller in a fresh process so preflight precedes torch import" + ) + with open( + Path("/tmp") / f"operatorx-ascend-board-{args.board_id}.lock", "a" + ) as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + raise RuntimeError( + "Another OperatorX campaign holds this board lock" + ) from None + return run_locked(args) + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except (ValueError, RuntimeError, OSError) as exc: + print(str(exc), file=sys.stderr) + raise SystemExit(1) diff --git a/operatorx/scripts/ascend/operatorx_campaign.py b/operatorx/scripts/ascend/operatorx_campaign.py new file mode 100644 index 0000000000..5bfb431bf8 --- /dev/null +++ b/operatorx/scripts/ascend/operatorx_campaign.py @@ -0,0 +1,353 @@ +#!/usr/bin/env python3 + +from __future__ import annotations + +import datetime as dt +import hashlib +import importlib.util +import json +import math +import os +import sqlite3 +import subprocess +import sys +import time +from collections import Counter +from pathlib import Path + +HERE = Path(__file__).resolve().parent +GIB = 1024**3 + + +def utc(): + return dt.datetime.now(dt.timezone.utc).isoformat() + + +def canonical(value): + return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False) + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") + temporary.replace(path) + + +def load_module(path, name): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +def idle_helper_path(): + return HERE / "operatorx_npu_health.py" + + +def select_cases(plan, phase): + if phase == "smoke": + wanted = set(plan["smoke_case_ids"]) + return [case for case in plan["cases"] if case["case_id"] in wanted] + if phase == "all-ready": + return [case for case in plan["cases"] if case["phase"] in ("new", "remeasure")] + return [case for case in plan["cases"] if case["phase"] == phase] + + +def command(argv, timeout=15): + start = time.monotonic() + try: + result = subprocess.run(argv, capture_output=True, text=True, timeout=timeout) + return { + "argv": argv, + "utc": utc(), + "returncode": result.returncode, + "stdout": result.stdout, + "stderr": result.stderr, + "elapsed_s": time.monotonic() - start, + } + except (OSError, subprocess.TimeoutExpired) as exc: + return {"argv": argv, "utc": utc(), "returncode": None, "error": str(exc)} + + +def idle_snapshot(args, helper, mapped): + capture = command(["npu-smi", "info"]) + if capture["returncode"] != 0: + raise RuntimeError("npu-smi info failed: " + canonical(capture)) + parsed = helper.status_rows(capture["stdout"], args.board_id) + keywords = {} + if getattr(args, "acl_runtime_mapping", None) is not None: + keywords["acl_runtime_mapping"] = args.acl_runtime_mapping + selected = helper.validate_identity( + parsed, + mapped, + args.board_id, + args.chip_id, + args.device, + args.expect_pci, + **keywords, + ) + capture["parsed"] = parsed + capture["selected"] = selected + if parsed["processes"] or any( + row["aicore_percent"] != 0 for row in parsed["devices"] + ): + raise RuntimeError("Selected board is not idle: " + canonical(capture)) + return capture + + +def preflight(args): + helper = load_module(idle_helper_path(), "operatorx_idle_probe") + visibility = { + k: os.environ[k] for k in helper.VISIBILITY_VARIABLES if os.environ.get(k) + } + if visibility: + raise RuntimeError( + "Device remapping must be resolved before running: " + canonical(visibility) + ) + mapping = command(["npu-smi", "info", "-m"]) + if mapping["returncode"] != 0: + raise RuntimeError("Cannot obtain NPU mapping: " + canonical(mapping)) + mapped = helper.mapping_rows(mapping["stdout"]) + if any( + row["logical_device_id"] is None + for row in mapped + if row["board"] == args.board_id + ): + args.acl_runtime_mapping = helper.collect_acl_runtime_mapping(args.device) + observations = [idle_snapshot(args, helper, mapped)] + time.sleep(1) + observations.append(idle_snapshot(args, helper, mapped)) + queries = { + kind: command(["npu-smi", "info", "-t", kind, "-i", str(args.board_id)]) + for kind in ("board", "common") + } + diagnostic_gate = None + if hasattr(helper, "validate_diagnostic_queries"): + for kind in ("health", "current-fault-event", "ecc", "ecc-enable", "pcie-err"): + queries[kind] = command( + ["npu-smi", "info", "-t", kind, "-i", str(args.board_id)] + ) + diagnostic_gate = helper.validate_diagnostic_queries( + list(queries.values()), args.board_id + ) + raw_identity = canonical( + {"mapping": mapped, "board": queries["board"].get("stdout")} + ) + if args.expected_name.lower() not in (raw_identity + canonical(queries)).lower(): + raise RuntimeError( + "Expected chip name not present in npu-smi identity captures" + ) + if queries["board"]["returncode"] != 0: + raise RuntimeError( + "A successful board identity capture is required for resumable results" + ) + identity = { + "board_id": args.board_id, + "chip_id": args.chip_id, + "device": args.device, + "pci": observations[-1]["selected"]["pci"], + "mapping": mapped, + "board_text": queries["board"]["stdout"], + } + report = { + "utc": utc(), + "mapping": mapping, + "idle_observations": observations, + "queries": queries, + "identity": identity, + "diagnostic_gate": diagnostic_gate, + "acl_runtime_mapping": getattr(args, "acl_runtime_mapping", None), + "identity_sha256": hashlib.sha256(canonical(identity).encode()).hexdigest(), + } + return report, helper, mapped + + +def open_journal(path, metadata): + connection = sqlite3.connect(path) + connection.execute("PRAGMA synchronous=FULL") + connection.execute( + "CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL)" + ) + connection.execute( + "CREATE TABLE IF NOT EXISTS results (seq INTEGER PRIMARY KEY, case_id TEXT NOT NULL, status TEXT NOT NULL, record TEXT NOT NULL)" + ) + fingerprint = canonical(metadata) + existing = connection.execute( + "SELECT value FROM metadata WHERE key='fingerprint'" + ).fetchone() + if existing and existing[0] != fingerprint: + connection.close() + raise ValueError( + "Resume refused: plan, scripts, hardware identity or timing configuration changed; use a new run directory" + ) + if not existing: + with connection: + connection.execute( + "INSERT INTO metadata VALUES ('fingerprint', ?)", (fingerprint,) + ) + return connection + + +def record_result(connection, case_id, record): + with connection: + connection.execute( + "INSERT INTO results(case_id,status,record) VALUES (?,?,?)", + (case_id, record["status"], canonical(record)), + ) + + +def export_journal(connection, path): + latest = {} + for case_id, record in connection.execute( + "SELECT case_id,record FROM results ORDER BY seq" + ): + latest[case_id] = json.loads(record) + summary = { + "exported_at": utc(), + "counts": dict(Counter(x["status"] for x in latest.values())), + "results": list(latest.values()), + "qualification": "Eager NPU events with a cache-write preparation. This is not proof of cache eviction or public-run protocol parity. Correctness is sampled CPU FP64 reference validation, not full output certification.", + } + write_json(path, summary) + return summary + + +def validate_worker_result(outcome, case, config, worker_sha): + if not isinstance(outcome, dict) or outcome.get("status") not in ( + "ok", + "error", + "unsupported", + "skipped_memory", + ): + raise ValueError("Worker did not return a recognized terminal status") + if ( + outcome.get("case_id") != case["case_id"] + or outcome.get("opType") != case["opType"] + or outcome.get("args") != case["args"] + ): + raise ValueError("Worker result identity differs from the requested case") + semantic = {"opType": case["opType"], "args": case["args"]} + provenance = outcome.get("provenance", {}) + if not isinstance(provenance, dict): + raise ValueError("Worker provenance is not an object") + if ( + provenance.get("worker_sha256") != worker_sha + or provenance.get("case_semantic_sha256") + != hashlib.sha256(canonical(semantic).encode()).hexdigest() + ): + raise ValueError("Worker/source or semantic hash mismatch") + if outcome["status"] != "ok": + if outcome.get("metrics") is not None: + raise ValueError("Unsuccessful result must not contain performance metrics") + return + for key in ("config", "correctness", "timing", "metrics", "tensors"): + if not isinstance(outcome.get(key), dict): + raise ValueError("Successful result requires an object: " + key) + for key in ( + "samples", + "warmups", + "warmup_ms", + "seed", + "device", + "cache_write_bytes", + "workspace_reserve_bytes", + "memory_budget_bytes", + ): + if outcome.get("config", {}).get(key) != config[key]: + raise ValueError("Worker configuration mismatch: " + key) + for when in ("before_timing", "after_timing"): + check = outcome.get("correctness", {}).get(when, {}) + if ( + not isinstance(check, dict) + or check.get("passed") is not True + or check.get("all_output_elements_finite") is not True + or not check.get("samples") + ): + raise ValueError("Missing successful correctness/finite gate: " + when) + samples = outcome.get("timing", {}).get("device_event_samples_us", []) + if ( + not isinstance(samples, list) + or len(samples) != config["samples"] + or any( + type(x) not in (int, float) or not math.isfinite(x) or x <= 0 + for x in samples + ) + ): + raise ValueError("Invalid or incomplete raw event timing samples") + median = sorted(samples)[len(samples) // 2] + metrics = outcome.get("metrics", {}) + if metrics.get("latency_us") != median or metrics.get("npu_graph") is not False: + raise ValueError("Reported latency or graph mode disagrees with the raw timing") + a = case["args"] + expected = 2 * a["m"] * a["n"] * a["k"] / (median * 1e6) + if not math.isclose(metrics.get("tflops", float("nan")), expected, rel_tol=1e-12): + raise ValueError( + "Throughput disagrees with requested work and measured latency" + ) + output = outcome.get("tensors", {}).get("output", {}) + dtype = { + "bf16": "torch.bfloat16", + "fp16": "torch.float16", + "fp32": "torch.float32", + }[a.get("out", "bf16")] + if ( + not isinstance(output, dict) + or output.get("shape") != [a["m"], a["n"]] + or output.get("dtype") != dtype + ): + raise ValueError("Output descriptor differs from the requested shape/precision") + + +def monitor(stop, path, board_id, helper, state): + with path.open("a") as handle: + while not stop.is_set(): + sample_start = time.monotonic() + row = { + "utc": utc(), + "status": command(["npu-smi", "info"], timeout=5), + "common": command( + ["npu-smi", "info", "-t", "common", "-i", str(board_id)], timeout=5 + ), + } + try: + if row["status"]["returncode"] != 0: + raise ValueError("npu-smi status query failed") + parsed = helper.status_rows(row["status"]["stdout"], board_id) + with state["lock"]: + foreign = [ + p + for p in parsed["processes"] + if p["pid"] not in state["own_pids"] + ] + if foreign: + row["foreign_processes"] = foreign + with state["lock"]: + state["issues"].append( + { + "start": sample_start, + "end": time.monotonic(), + "utc": row["utc"], + "foreign_processes": foreign, + } + ) + except ValueError as exc: + row["process_check_error"] = str(exc) + with state["lock"]: + state["issues"].append( + { + "start": sample_start, + "end": time.monotonic(), + "utc": row["utc"], + "process_check_error": str(exc), + } + ) + handle.write(canonical(row) + "\n") + handle.flush() + stop.wait(1) diff --git a/operatorx/scripts/ascend/operatorx_fp8_block_worker.py b/operatorx/scripts/ascend/operatorx_fp8_block_worker.py new file mode 100644 index 0000000000..8c4a0eca9b --- /dev/null +++ b/operatorx/scripts/ascend/operatorx_fp8_block_worker.py @@ -0,0 +1,669 @@ +from __future__ import annotations + +import hashlib +import importlib.util +import json +import math +import platform +import sys +from datetime import datetime, timezone +from pathlib import Path + +import operatorx_queued_timing as queued_timing + +HELPER_PATH = Path(__file__).with_name("operatorx_ascend_worker.py") +HELPER_SHA256 = hashlib.sha256(HELPER_PATH.read_bytes()).hexdigest() +_SPEC = importlib.util.spec_from_file_location( + "operatorx_fp8_dense_helper", HELPER_PATH +) +dense = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(dense) + +SCHEMA_VERSION = 1 +DEFAULT_CACHE_WRITE_BYTES = 256 * 1024**2 +DEFAULT_WORKSPACE_RESERVE_BYTES = 2 * 1024**3 +DEFAULT_REFERENCE_SAMPLES = 64 +QUANT_CHECK_CHUNK_ELEMENTS = 262144 +SOURCE_URL = dense.FP32_REFERENCE_SOURCE +SOURCE_SHA256 = dense.REFERENCE_SOURCE_SHA256 +IMPLEMENTATION = "native_dynamic_block_quant_fp32_scales_then_quant_matmul" + + +def classify_case(case): + if not isinstance(case, dict): + return dense._unsupported("invalid_case", "Case must be a JSON object") + op_type = case.get("opType", case.get("op_type")) + if "opType" in case and "op_type" in case and case["opType"] != case["op_type"]: + return dense._unsupported("invalid_case", "Conflicting operator types") + if op_type != "gemm": + return dense._unsupported( + "operator_not_implemented", + "This worker implements FP32 block-scaled E4M3 GEMM only", + ) + args = case.get("args") + if not isinstance(args, dict) or set(args) - { + "m", + "n", + "k", + "a", + "b", + "out", + "bias", + "activation", + }: + return dense._unsupported("invalid_args", "Unknown or invalid GEMM arguments") + if any(not dense._positive_int(args.get(key)) for key in ("m", "n", "k")): + return dense._unsupported( + "invalid_dimensions", "M, N and K must be positive integers" + ) + for key, group, static in (("a", [1, 128], False), ("b", [128, 128], True)): + operand = args.get(key) + if ( + not isinstance(operand, dict) + or set(operand) != {"dtype", "scale"} + or operand["dtype"] != "e4m3" + ): + return dense._unsupported( + "operand_format_not_implemented", + "Only exact E4M3 descriptors with one FP32 block scale are implemented", + ) + scale = operand["scale"] + if ( + not isinstance(scale, dict) + or set(scale) != {"dtype", "group", "static"} + or scale["dtype"] != "fp32" + or type(scale["static"]) is not bool + or scale["static"] is not static + or not isinstance(scale["group"], list) + or len(scale["group"]) != 2 + or any(type(value) is not int for value in scale["group"]) + or scale["group"] != group + ): + return dense._unsupported( + "scale_semantics_not_implemented", + "Require dynamic A FP32 [1,128] and static W FP32 [128,128] scales", + ) + if args.get("out", "bf16") != "bf16" or not isinstance( + args.get("out", "bf16"), str + ): + return dense._unsupported( + "output_not_implemented", "This FP8 path returns BF16" + ) + if ( + type(args.get("bias", False)) is not bool + or args.get("bias", False) is not False + or args.get("activation") is not None + ): + return dense._unsupported( + "epilogue_not_implemented", "Bias and activation are not implemented" + ) + if args["k"] % 128: + return dense._unsupported( + "k_group_tail_requires_validation", + "K must be divisible by 128; partial final K groups need separate validation", + ) + return { + "supported": True, + "status": "supported_unvalidated", + "reason_code": "native_fp8_block_candidate", + "reason": "Exact declared block format; every device case still requires numerical validation", + "normalized": { + "m": args["m"], + "n": args["n"], + "k": args["k"], + "dtype": "bf16", + "dtype_out": "bf16", + "tolerance_dtype": "bf16", + "implementation": IMPLEMENTATION, + "bias": False, + "dtype_a_input": "bf16", + "dtype_a_quantized": "e4m3", + "dtype_b": "e4m3", + "scale_dtype": "fp32", + "group_sizes": [1, 128, 128], + "layout": "A[M,K], W[N,K], Wscale[ceil(N/128),K/128]; compute A_quant @ W.T with FP32 scales", + }, + } + + +def estimate_memory( + case, + *, + cache_write_bytes=DEFAULT_CACHE_WRITE_BYTES, + workspace_reserve_bytes=DEFAULT_WORKSPACE_RESERVE_BYTES, +): + support = classify_case(case) + if not support["supported"]: + raise ValueError(support["reason"]) + if any( + type(value) is not int or value < 0 + for value in (cache_write_bytes, workspace_reserve_bytes) + ): + raise ValueError("Cache/workspace budgets must be nonnegative integers") + m, n, k = (support["normalized"][key] for key in ("m", "n", "k")) + memory = { + "a_bytes": 2 * m * k, + "weight_bytes": n * k, + "weight_scale_bytes": 4 * ((n + 127) // 128) * (k // 128), + "quantized_a_bytes": m * k, + "activation_scale_bytes": 4 * m * (k // 128), + "output_bytes": 2 * m * n, + "output_live_buffer_count": 2, + "quantized_input_live_buffer_count": 2, + "cache_write_bytes": cache_write_bytes, + "workspace_reserve_bytes": workspace_reserve_bytes, + "workspace_is_measured": False, + } + memory["tensor_and_cache_bytes"] = ( + memory["a_bytes"] + + memory["weight_bytes"] + + memory["weight_scale_bytes"] + + cache_write_bytes + + 2 + * ( + memory["quantized_a_bytes"] + + memory["activation_scale_bytes"] + + memory["output_bytes"] + ) + ) + memory["input_generation_peak_bytes"] = max( + 4 * n * k, + memory["a_bytes"] + memory["weight_bytes"] + memory["weight_scale_bytes"], + ) + memory["estimated_required_bytes"] = ( + max(memory["tensor_and_cache_bytes"], memory["input_generation_peak_bytes"]) + + workspace_reserve_bytes + ) + memory["required_bytes"] = memory["estimated_required_bytes"] + memory["reference_cpu_working_bytes_estimate"] = ( + 48 * max(k, QUANT_CHECK_CHUNK_ELEMENTS) + 32 * k + ) + return memory + + +def _base_result(case): + semantic = { + "opType": case.get("opType", case.get("op_type")), + "args": case.get("args"), + } + return { + "schema_version": SCHEMA_VERSION, + "case_id": case.get("case_id", case.get("id")), + "opType": semantic["opType"], + "args": case.get("args"), + "sources": case.get("sources", []), + "testlists": case.get("testlists", []), + "support": classify_case(case), + "status": "unvalidated", + "metrics": None, + "warnings": [ + "Prepared candidate; a plan is not a hardware measurement.", + "Native quantizer rounding and zero-group scale differ from the pinned CUDA quantizer; byte parity is not claimed.", + "Cache writes do not prove cache eviction or public protocol parity.", + "GEMM correctness uses sampled CPU FP64 dots; quantization quality and output finiteness scan all elements.", + ], + "provenance": { + "worker_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "dense_helper_sha256": HELPER_SHA256, + "case_semantic_sha256": hashlib.sha256( + json.dumps( + semantic, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode() + ).hexdigest(), + "python": platform.python_version(), + "machine": platform.machine(), + "started_at": datetime.now(timezone.utc).isoformat(), + "native_kernel_result_not_rewritten_for_validation": True, + "implementation": IMPLEMENTATION, + "cuda_quantizer_byte_parity_claimed": False, + "min_scale": 0.0, + "native_zero_scale_for_zero_group_allowed": True, + }, + } + + +def plan_case( + case, + *, + cache_write_bytes=DEFAULT_CACHE_WRITE_BYTES, + workspace_reserve_bytes=DEFAULT_WORKSPACE_RESERVE_BYTES, +): + result = _base_result(case) + if not result["support"]["supported"]: + result["status"] = "unsupported" + else: + result["memory_estimate"] = estimate_memory( + case, + cache_write_bytes=cache_write_bytes, + workspace_reserve_bytes=workspace_reserve_bytes, + ) + return result + + +def native_parameters(torch): + wanted = { + "npu::npu_dynamic_block_quant": { + "x", + "min_scale", + "round_mode", + "dst_type", + "row_block_size", + "col_block_size", + }, + "npu::npu_quant_matmul": { + "x1", + "x2", + "scale", + "offset", + "pertoken_scale", + "bias", + "output_dtype", + "group_sizes", + }, + } + extensions = { + "npu::npu_dynamic_block_quant": {"dst_type_max"}, + "npu::npu_quant_matmul": { + "x1_dtype", + "x2_dtype", + "pertoken_scale_dtype", + "scale_dtype", + "y_scale", + }, + } + metadata, names = {}, {} + for op, required in wanted.items(): + schemas = [ + schema + for schema in torch._C._jit_get_schemas_for_operator(op) + if schema.overload_name == "" + ] + if len(schemas) != 1: + raise ValueError(f"Missing or ambiguous native schema for {op}") + schema = schemas[0] + args = list(schema.arguments) + names[op] = {arg.name for arg in args} + leading = ["x"] if op.endswith("dynamic_block_quant") else ["x1", "x2", "scale"] + if ( + [arg.name for arg in args[: len(leading)]] != leading + or any(str(arg.type) != "Tensor" for arg in args[: len(leading)]) + or not required <= names[op] + or names[op] - required - extensions[op] + or any( + not arg.has_default_value() + for arg in args + if arg.name in extensions[op] + ) + ): + raise ValueError(f"Unrecognized native operator signature for {op}") + metadata[op] = str(schema) + quant = { + "min_scale": 0.0, + "round_mode": "rint", + "dst_type": torch.float8_e4m3fn, + "row_block_size": 1, + "col_block_size": 128, + } + if "dst_type_max" in names["npu::npu_dynamic_block_quant"]: + quant["dst_type_max"] = 0.0 + mm = { + "offset": None, + "bias": None, + "output_dtype": torch.bfloat16, + "group_sizes": [1, 128, 128], + } + for name in names["npu::npu_quant_matmul"] & extensions["npu::npu_quant_matmul"]: + mm[name] = None + return quant, mm, metadata + + +def generate_inputs(torch, spec, *, device): + weight = ( + torch.randn(spec["n"], spec["k"], device=device, dtype=torch.bfloat16) * 0.5 + ).to(torch.float8_e4m3fn) + weight_scale = torch.full( + ((spec["n"] + 127) // 128, spec["k"] // 128), + 0.01, + device=device, + dtype=torch.float32, + ) + a = torch.randn(spec["m"], spec["k"], device=device, dtype=torch.bfloat16) + recipe = { + "source_url": SOURCE_URL, + "source_sha256": SOURCE_SHA256, + "source_functions": "_prepare_gemm -> _fill", + "weight_recipe": "BF16 randn(N,K) * 0.5 in BF16, then E4M3 cast", + "weight_scale_recipe": "FP32 full(ceil(N/128),K/128,0.01)", + "a_recipe": "BF16 randn(M,K) after weight/scales", + "generation_order": ["weight", "weight_scale", "a"], + "public_input_distribution_reproduced": True, + "cross_stack_rng_identity_claimed": False, + "parameter_allocation_copy_omitted": True, + "weights_static_outside_timer": True, + "activation_quantization_inside_timer": True, + } + return a, weight, weight_scale, recipe + + +def execute_native(torch_npu, a, weight, weight_scale, quant_kwargs, mm_kwargs): + quantized, scales = torch_npu.npu_dynamic_block_quant(a, **quant_kwargs) + output = torch_npu.npu_quant_matmul( + quantized, weight.t(), weight_scale.t(), pertoken_scale=scales, **mm_kwargs + ) + return output, quantized, scales + + +def validate_quantization( + torch, a, quantized, scales, *, chunk_elements=QUANT_CHECK_CHUNK_ELEMENTS +): + if ( + a.dtype != torch.bfloat16 + or quantized.dtype != torch.float8_e4m3fn + or scales.dtype != torch.float32 + ): + raise ValueError("Unexpected activation/quantizer dtype") + m, k = a.shape + if ( + k % 128 + or list(quantized.shape) != [m, k] + or list(scales.shape) != [m, k // 128] + ): + raise ValueError("Unexpected activation/quantizer shape") + if not quantized.is_contiguous() or not scales.is_contiguous(): + raise ValueError("Unexpected native quantizer output strides") + rows_per_chunk = max(1, chunk_elements // k) + bad_elements = bad_groups = zero_groups = 0 + max_error = max_ratio = 0.0 + finite = True + for start in range(0, m, rows_per_chunk): + end = min(m, start + rows_per_chunk) + original = ( + a[start:end].detach().cpu().float().reshape(end - start, k // 128, 128) + ) + codes = ( + quantized[start:end] + .detach() + .cpu() + .float() + .reshape(end - start, k // 128, 128) + ) + ss = scales[start:end].detach().cpu() + chunk_finite = ( + bool(torch.isfinite(original).all()) + and bool(torch.isfinite(codes).all()) + and bool(torch.isfinite(ss).all()) + ) + finite &= chunk_finite + if not chunk_finite: + bad_elements += (end - start) * k + continue + zero = (ss == 0) & (original.abs().amax(-1) == 0) & (codes.abs().amax(-1) == 0) + valid = (ss > 0) | zero + bad_groups += int((~valid).sum().item()) + zero_groups += int(zero.sum().item()) + error = (codes * ss.unsqueeze(-1) - original).abs() + bound = original.abs() / 16.0 + ss.unsqueeze(-1) / 1024.0 + bad_elements += int((error > bound).sum().item()) + max_error = max(max_error, float(error.max().item())) + ratio = torch.where( + bound > 0, + error / bound, + torch.where( + error == 0, + torch.zeros_like(error), + torch.full_like(error, float("inf")), + ), + ) + max_ratio = max(max_ratio, float(ratio.max().item())) + return { + "passed": finite and bad_elements == 0 and bad_groups == 0, + "all_quantized_inputs_finite": finite, + "checked_elements": m * k, + "checked_groups": m * (k // 128), + "invalid_scale_groups": bad_groups, + "zero_scale_zero_groups": zero_groups, + "failed_elements": bad_elements, + "max_abs_reconstruction_error": max_error if finite else None, + "max_error_bound_ratio": max_ratio if math.isfinite(max_ratio) else None, + "bound": "abs(decoded-original) <= abs(original)/16 + scale/1024; zero scale valid only for an all-zero original and payload group", + "scope": "Every activation element checked on CPU in bounded chunks; CUDA payload/scale equality is not required", + } + + +def sampled_decoded_reference( + torch, quantized, scales, weight, weight_scale, coordinates +): + values = [] + for row, col in coordinates: + q = quantized[row].detach().cpu().to(torch.float64) + s = scales[row].detach().cpu().to(torch.float64).repeat_interleave(128) + w = weight[col].detach().cpu().to(torch.float64) + ws = ( + weight_scale[col // 128] + .detach() + .cpu() + .to(torch.float64) + .repeat_interleave(128) + ) + if any(not bool(torch.isfinite(x).all()) for x in (q, s, w, ws)): + raise ValueError("Nonfinite sampled decoded operand") + values.append(torch.dot(q * s, w * ws).item()) + return values + + +def validate_state(torch, a, weight, weight_scale, state, spec, coordinates): + output, quantized, scales = state + quant = validate_quantization(torch, a, quantized, scales) + reference = sampled_decoded_reference( + torch, quantized, scales, weight, weight_scale, coordinates + ) + check = dense.validate_output( + torch, + output, + normalized=spec, + coordinates=coordinates, + reference=reference, + input_product_scale=0.005, + ) + check["quantization"] = quant + check["reference_scope"] = ( + "CPU FP64 full-K dots of this kernel call's E4M3 payloads with their FP32 block scales" + ) + check["passed"] = check["passed"] and quant["passed"] + return check + + +def _run_native(case, config, result): + import torch + import torch_npu + + npu = torch.npu + if not npu.is_available(): + raise dense.WorkerFailure("hardware_unavailable", "No available Ascend NPU") + quant_kwargs, mm_kwargs, schemas = native_parameters(torch) + device = f"npu:{config['device']}" + npu.set_device(device) + torch.set_grad_enabled(False) + torch.set_num_threads(1) + torch.manual_seed(config["seed"]) + npu.manual_seed(config["seed"]) + npu.synchronize() + result["provenance"].update( + torch=str(torch.__version__), + torch_npu=str(torch_npu.__version__), + native_schemas=schemas, + quantizer_parameters={ + key: str(value) if key == "dst_type" else value + for key, value in quant_kwargs.items() + }, + matmul_parameters={ + key: str(value) if key == "output_dtype" else value + for key, value in mm_kwargs.items() + }, + ) + free, total = npu.mem_get_info(config["device"]) + budget = dense.check_memory_budget( + result["memory_estimate"], + available_bytes=int(free), + memory_budget_bytes=config["memory_budget_bytes"], + ) + result["memory_budget_check"] = {**budget, "total_device_bytes": int(total)} + if not budget["fits"]: + raise dense.WorkerFailure( + "memory_budget_exceeded", + "FP8 input/transient/output/cache/workspace estimate exceeds the available budget", + ) + npu.reset_peak_memory_stats(config["device"]) + baseline = { + "allocated_bytes": int(npu.memory_allocated(config["device"])), + "reserved_bytes": int(npu.memory_reserved(config["device"])), + } + try: + spec = result["support"]["normalized"] + a, weight, weight_scale, recipe = generate_inputs(torch, spec, device=device) + cache = torch.empty( + config["cache_write_bytes"], device=device, dtype=torch.uint8 + ) + result["input_generation"] = {**recipe, "seed": config["seed"]} + result["tensors"] = { + "a": dense.tensor_descriptor(a), + "weight": dense.tensor_descriptor(weight), + "weight_scale": dense.tensor_descriptor(weight_scale), + "cache_write": dense.tensor_descriptor(cache), + } + coordinates = dense.sample_coordinates( + spec["m"], spec["n"], config["reference_samples"], config["seed"] + ) + state = execute_native( + torch_npu, a, weight, weight_scale, quant_kwargs, mm_kwargs + ) + npu.synchronize() + before = validate_state( + torch, a, weight, weight_scale, state, spec, coordinates + ) + result["correctness"] = {"before_timing": before, "after_timing": None} + if not before["passed"]: + raise dense.WorkerFailure( + "correctness_failed", "Pre-timing quantization/GEMM reference failed" + ) + del state # Retain at most two live result buffers during queued execution. + state, timing = queued_timing.time_op( + npu, + lambda: execute_native( + torch_npu, a, weight, weight_scale, quant_kwargs, mm_kwargs + ), + cache, + config, + ) + timing.update( + timed_implementation=IMPLEMENTATION, + activation_quantization_inside_timer=True, + static_weight_preparation_inside_timer=False, + ) + result["timing"] = timing + latency = dense.upper_median(timing["device_event_samples_us"]) + after = validate_state(torch, a, weight, weight_scale, state, spec, coordinates) + result["correctness"]["after_timing"] = after + result["tensors"].update( + output=dense.tensor_descriptor(state[0]), + quantized_a=dense.tensor_descriptor(state[1]), + activation_scale=dense.tensor_descriptor(state[2]), + ) + if not after["passed"]: + raise dense.WorkerFailure( + "correctness_failed", "Post-timing quantization/GEMM reference failed" + ) + result["metrics"] = { + "latency_us": latency, + "queued_wall_latency_us_per_call": timing["queued_wall_us_per_call"], + "tflops": 2 * spec["m"] * spec["n"] * spec["k"] / (latency * 1e6), + "npu_graph": False, + } + result["status"] = "ok" + result["warnings"].pop(0) + finally: + result["memory_high_water"] = { + "baseline": baseline, + "max_allocated_bytes": int(npu.max_memory_allocated(config["device"])), + "max_reserved_bytes": int(npu.max_memory_reserved(config["device"])), + "scope": "PyTorch NPU allocator, including generation and two live result tuples; opaque driver memory excluded", + } + + +def run_case( + case, + *, + memory_budget_bytes, + device=0, + samples=10, + warmups=5, + warmup_ms=25, + seed=20261023, + reference_samples=DEFAULT_REFERENCE_SAMPLES, + cache_write_bytes=DEFAULT_CACHE_WRITE_BYTES, + workspace_reserve_bytes=DEFAULT_WORKSPACE_RESERVE_BYTES, +): + result = plan_case( + case, + cache_write_bytes=cache_write_bytes, + workspace_reserve_bytes=workspace_reserve_bytes, + ) + if result["status"] == "unsupported": + return result + config = { + "memory_budget_bytes": memory_budget_bytes, + "device": device, + "samples": samples, + "warmups": warmups, + "warmup_ms": warmup_ms, + "seed": seed, + "reference_samples": reference_samples, + "cache_write_bytes": cache_write_bytes, + "workspace_reserve_bytes": workspace_reserve_bytes, + } + result["config"] = config + try: + if ( + not dense._positive_int(memory_budget_bytes) + or type(device) is not int + or device < 0 + ): + raise ValueError( + "Positive memory budget and nonnegative device are required" + ) + if type(seed) is not int or not 0 <= seed < 2**63: + raise ValueError("Invalid seed") + if ( + type(samples) is not int + or not 10 <= samples <= 10000 + or type(warmups) is not int + or not 1 <= warmups <= 10000 + ): + raise ValueError("Invalid timing sample/warmup count") + if ( + type(warmup_ms) not in (int, float) + or not math.isfinite(warmup_ms) + or not 0 <= warmup_ms <= 10000 + ): + raise ValueError("Invalid warmup duration") + if type(reference_samples) is not int or not 1 <= reference_samples <= 4096: + raise ValueError("Invalid reference sample count") + _run_native(case, config, result) + except Exception as exc: + result["status"] = ( + "skipped_memory" + if isinstance(exc, dense.WorkerFailure) + and exc.kind == "memory_budget_exceeded" + else "error" + ) + result["metrics"] = None + result["error"] = { + "kind": exc.kind + if isinstance(exc, dense.WorkerFailure) + else "execution_failure", + "exception_type": type(exc).__name__, + "message": str(exc), + } + print(f"OperatorX FP8 worker {result['error']['kind']}: {exc}", file=sys.stderr) + result["provenance"]["finished_at"] = datetime.now(timezone.utc).isoformat() + return result diff --git a/operatorx/scripts/ascend/operatorx_fp8_l0_guard.cpp b/operatorx/scripts/ascend/operatorx_fp8_l0_guard.cpp new file mode 100644 index 0000000000..d27aa3a7be --- /dev/null +++ b/operatorx/scripts/ascend/operatorx_fp8_l0_guard.cpp @@ -0,0 +1,221 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int kBlocked = 100000; +constexpr uint64_t kCapacity = 65536; +constexpr size_t kTilingBytes = 152; +constexpr const char *kKernel = + "QuantBatchMatmulV3_ND_ND_fp8e4m3_fp8e4m3_fp32_bf16_high_performance"; +struct Placeholder { uint32_t addrOffset; uint32_t dataOffset; }; +static_assert(sizeof(Placeholder) == 8, "Installed placeholder ABI"); +struct Config { uint32_t m = 0, n = 0, k = 0; int mode = 0; }; +struct Decision { + int code = 2; + std::string reason = "not_inspected", kernel, hex; + uint64_t key = 0, l0a = 0; + uint32_t m = 0, n = 0, k = 0, bm = 0, bn = 0, bk = 0; + size_t supplied = 0, args_bytes = 0; + int64_t tiling_offset = -1, address_offset = -1; +}; +std::mutex g_mutex; +Config g_config; +std::unordered_map g_keys; +std::unordered_set g_logged; +std::string g_last = "{\"decision\":\"inactive\",\"observed\":false}"; + +uint32_t u32(const unsigned char *p) { + return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24; +} +std::string quote(const std::string &value) { + std::string out = "\""; + constexpr char digits[] = "0123456789abcdef"; + for (unsigned char c : value) { + if (c == '\\' || c == '"') { out += '\\'; out += char(c); } + else if (c < 32) { out += "\\u00"; out += digits[c >> 4]; out += digits[c & 15]; } + else out += char(c); + } + return out + '"'; +} +bool known_name(const std::string &name) { + return name == kKernel || name == std::string(kKernel) + "_5124" || + name == std::string(kKernel) + "_5124_mix_aic" || + name == std::string(kKernel) + "_5124_mix_aiv"; +} +Decision inspect(const char *kernel, uint64_t key, const void *data, size_t bytes, + uint32_t m, uint32_t n, uint32_t k) { + Decision d; + d.kernel = kernel ? kernel : ""; d.key = key; d.supplied = bytes; + if (!known_name(d.kernel)) { d.reason = "unknown_kernel_identity"; return d; } + if (key != 5124) { d.reason = "unknown_dispatch_key"; return d; } + if (!data || bytes < kTilingBytes) { d.reason = "short_or_null_tiling"; return d; } + const auto *p = static_cast(data); + constexpr char digits[] = "0123456789abcdef"; + for (size_t i = 0; i < kTilingBytes; ++i) { + d.hex += digits[p[i] >> 4]; d.hex += digits[p[i] & 15]; + } + d.m = u32(p + 88); d.n = u32(p + 92); d.k = u32(p + 96); + d.bm = u32(p + 100); d.bn = u32(p + 104); d.bk = u32(p + 108); + for (size_t offset = 0; offset < 60; offset += 4) { + if (u32(p + offset) != 1) { d.reason = "batch_fields_mismatch"; return d; } + } + if (u32(p + 60) != 32 || u32(p + 64) != 16) { + d.reason = "quant_modes_mismatch"; return d; + } + if (u32(p + 68) != 0 || p[125] != 0) { d.reason = "unexpected_bias"; return d; } + if (u32(p + 76) != 1 || u32(p + 80) != 128 || u32(p + 84) != 128) { + d.reason = "scale_groups_mismatch"; return d; + } + if (!m || !n || !k || d.m != m || d.n != n || d.k != k) { + d.reason = "matrix_shape_mismatch"; return d; + } + if (!d.bm || !d.bn || !d.bk || d.bm % 16 || d.bn % 16 || d.bk % 32) { + d.reason = "invalid_base_tile_alignment_or_zero"; return d; + } + if (uint64_t(d.bm) > std::numeric_limits::max() / 2 / d.bk) { + d.reason = "l0a_extent_integer_overflow"; return d; + } + d.l0a = 2ULL * d.bm * d.bk; + d.code = d.l0a > kCapacity ? 1 : 0; + d.reason = d.code ? "fp8_ping_pong_a_exceeds_l0a" : "fp8_ping_pong_a_within_l0a"; + return d; +} +std::string json(const Decision &d, const Config &cfg) { + std::ostringstream out; + out << "{\"schema_version\":1,\"observed\":true,\"decision\":" + << quote(d.code == 0 ? "within_capacity" : d.code == 1 ? "over_capacity" : "unverified") + << ",\"reason\":" << quote(d.reason) << ",\"kernel_name\":" << quote(d.kernel) + << ",\"dispatch_key\":" << d.key << ",\"mode\":" << cfg.mode + << ",\"forward_allowed\":" << (cfg.mode == 2 && d.code == 0 ? "true" : "false") + << ",\"expected_m\":" << cfg.m << ",\"expected_n\":" << cfg.n << ",\"expected_k\":" << cfg.k + << ",\"m\":" << d.m << ",\"n\":" << d.n << ",\"k\":" << d.k + << ",\"base_m\":" << d.bm << ",\"base_n\":" << d.bn << ",\"base_k\":" << d.bk + << ",\"l0a_bytes\":" << d.l0a << ",\"l0a_capacity_bytes\":" << kCapacity + << ",\"declared_tiling_bytes\":" << kTilingBytes << ",\"available_tiling_bytes\":" << d.supplied + << ",\"args_bytes\":" << d.args_bytes << ",\"tiling_offset\":" << d.tiling_offset + << ",\"placeholder_address_offset\":" << d.address_offset + << ",\"tiling_hex\":" << quote(d.hex) << '}'; + return out.str(); +} +void publish(const Decision &d, const Config &cfg, bool log) { + const std::string result = json(d, cfg); + std::lock_guard lock(g_mutex); + g_last = result; + if (log && g_logged.insert(result).second) { + std::fprintf(stderr, "OPERATORX_FP8_L0_GUARD %s\n", result.c_str()); + std::fflush(stderr); + } +} +template T next(const char *name) { + return reinterpret_cast(dlsym(RTLD_NEXT, name)); +} +} // namespace + +// Modes: 0 inactive, 1 preflight (block every target), 2 enforce (forward fits). +extern "C" int operatorx_fp8_guard_configure(uint32_t m, uint32_t n, uint32_t k, int mode) { + std::lock_guard lock(g_mutex); + if (mode < 0 || mode > 2 || (mode && (!m || !n || !k))) { + g_config = Config{0, 0, 0, 1}; + g_last = "{\"decision\":\"unverified\",\"reason\":\"invalid_configuration\",\"observed\":false}"; + return kBlocked; + } + g_config = Config{m, n, k, mode}; + g_last = mode ? "{\"decision\":\"pending\",\"observed\":false}" : + "{\"decision\":\"inactive\",\"observed\":false}"; + return 0; +} +extern "C" const char *operatorx_fp8_guard_last_json() { + thread_local std::string snapshot; + std::lock_guard lock(g_mutex); + snapshot = g_last; + return snapshot.c_str(); +} +// Pure host decoder for regression tests. Does not initialize or call the NPU. +extern "C" int operatorx_fp8_guard_validate(const char *kernel, uint64_t key, const void *data, + size_t bytes, uint32_t m, uint32_t n, uint32_t k) { + Decision d = inspect(kernel, key, data, bytes, m, n, k); + publish(d, Config{m, n, k, 1}, false); + return d.code; +} + +extern "C" int aclrtBinaryGetFunctionByEntry(void *binary, uint64_t entry, void **function) { + using Fn = int (*)(void *, uint64_t, void **); + static Fn real = next("aclrtBinaryGetFunctionByEntry"); + if (!real) return kBlocked; + const int result = real(binary, entry, function); + if (!result && function && *function) { + std::lock_guard lock(g_mutex); + g_keys[*function] = entry; + } + return result; +} + +extern "C" int aclrtLaunchKernelWithHostArgs(void *function, uint32_t blocks, void *stream, + void *cfg, void *args, size_t bytes, + Placeholder *placeholders, size_t count) { + using Launch = int (*)(void *, uint32_t, void *, void *, void *, size_t, Placeholder *, size_t); + using Name = int (*)(void *, uint32_t, char *); + static Launch real = next("aclrtLaunchKernelWithHostArgs"); + static Name get_name = next("aclrtGetFunctionName"); + Config config; + uint64_t key = 0; + { + std::lock_guard lock(g_mutex); + config = g_config; + const auto it = g_keys.find(function); + if (it != g_keys.end()) key = it->second; + } + if (!config.mode) return real ? real(function, blocks, stream, cfg, args, bytes, placeholders, count) : kBlocked; + char buffer[2048] = {}; + Decision decision; + if (!get_name || get_name(function, sizeof(buffer) - 1, buffer) != 0 || !buffer[0]) { + decision.reason = "kernel_name_unavailable"; + publish(decision, config, true); + return kBlocked; + } + const std::string name(buffer); + // Preparation kernels are allowed. Any unknown matmul identity is blocked. + if (name.find("Matmul") == std::string::npos && name.find("MatMul") == std::string::npos && + name.find("matmul") == std::string::npos) { + return real ? real(function, blocks, stream, cfg, args, bytes, placeholders, count) : kBlocked; + } + // A name explicitly containing the compiled key can corroborate it when the + // runtime obtained the handle before our entry hook. Never infer key 5124 + // from the unqualified base name. + if (!key && known_name(name) && name != kKernel) key = 5124; + decision.kernel = name; decision.key = key; decision.args_bytes = bytes; + if (!known_name(name) || key != 5124) { + decision.reason = "unknown_kernel_identity_or_dispatch_key"; + } else if (!args || !placeholders || !count || count > 64 || bytes > (1U << 20)) { + decision.reason = "invalid_launch_argument_envelope"; + } else { + size_t valid_count = 0; + Decision last_invalid = decision; + last_invalid.reason = "no_tiling_placeholder"; + for (size_t i = 0; i < count; ++i) { + const auto ph = placeholders[i]; + if (ph.addrOffset > bytes || bytes - ph.addrOffset < sizeof(void *) || + ph.dataOffset > bytes || bytes - ph.dataOffset < kTilingBytes || + ph.dataOffset < ph.addrOffset + sizeof(void *)) continue; + Decision candidate = inspect(name.c_str(), key, static_cast(args) + ph.dataOffset, + bytes - ph.dataOffset, config.m, config.n, config.k); + candidate.args_bytes = bytes; candidate.tiling_offset = ph.dataOffset; + candidate.address_offset = ph.addrOffset; + if (candidate.code != 2) { decision = candidate; ++valid_count; } + else last_invalid = candidate; + } + if (!valid_count) decision = last_invalid; + if (valid_count > 1) { decision.code = 2; decision.reason = "ambiguous_tiling_placeholders"; } + } + publish(decision, config, true); + if (config.mode == 1 || decision.code != 0) return kBlocked; + return real ? real(function, blocks, stream, cfg, args, bytes, placeholders, count) : kBlocked; +} diff --git a/operatorx/scripts/ascend/operatorx_fp8_l0_preflight.py b/operatorx/scripts/ascend/operatorx_fp8_l0_preflight.py new file mode 100644 index 0000000000..25f484b9d8 --- /dev/null +++ b/operatorx/scripts/ascend/operatorx_fp8_l0_preflight.py @@ -0,0 +1,220 @@ +from __future__ import annotations + +import argparse +import ctypes +import hashlib +import importlib.util +import json +import os +import sys +import threading +import traceback +from datetime import datetime, timezone +from pathlib import Path + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def validate_health_report(health, device): + identity = health.get("identity", {}) + if identity.get("device") != device: + raise ValueError("Health report belongs to a different logical device") + expected = hashlib.sha256( + json.dumps( + identity, sort_keys=True, separators=(",", ":"), allow_nan=False + ).encode() + ).hexdigest() + if ( + len(health.get("idle_observations", [])) != 2 + or health.get("identity_sha256") != expected + or set(health.get("diagnostic_gate", {})) + != {"health", "current-fault-event", "ecc", "ecc-enable", "pcie-err"} + ): + raise ValueError( + "Missing or inconsistent preflight health and hardware identity" + ) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--plan", type=Path) + p.add_argument("--shape", nargs=3, type=int, metavar=("M", "N", "K")) + p.add_argument("--output", type=Path, required=True) + p.add_argument("--guard-so", type=Path, required=True) + p.add_argument("--worker-dir", type=Path, required=True) + p.add_argument("--health-report", type=Path, required=True) + p.add_argument("--limit", type=int) + p.add_argument("--device", type=int, required=True) + p.add_argument("--memory-budget-bytes", type=int, required=True) + args = p.parse_args() + if ( + args.device < 0 + or args.memory_budget_bytes <= 0 + or not args.guard_so.is_absolute() + ): + p.error( + "Require a nonnegative device, positive memory budget and absolute guard-so path" + ) + if bool(args.plan) == bool(args.shape): + p.error("Choose exactly one of --plan and --shape") + if os.environ.get("TASK_QUEUE_ENABLE") != "0" or str( + args.guard_so + ) not in os.environ.get("LD_PRELOAD", "").split(":"): + p.error("Start with TASK_QUEUE_ENABLE=0 and absolute guard-so in LD_PRELOAD") + path = args.worker_dir / "operatorx_fp8_block_worker.py" + expected = sha(path) + spec = importlib.util.spec_from_file_location("original_fp8", path) + worker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(worker) + if args.shape: + m, n, k = args.shape + cases = [ + { + "case_id": f"guard-smoke-{m}-{n}-{k}", + "opType": "gemm", + "args": { + "m": m, + "n": n, + "k": k, + "out": "bf16", + "a": { + "dtype": "e4m3", + "scale": {"dtype": "fp32", "group": [1, 128], "static": False}, + }, + "b": { + "dtype": "e4m3", + "scale": {"dtype": "fp32", "group": [128, 128], "static": True}, + }, + }, + } + ] + else: + cases = [ + c + for c in json.loads(args.plan.read_text())["cases"] + if c.get("phase") in ("new", "remeasure") + and worker.classify_case(c)["supported"] + ] + if args.limit: + cases = cases[: args.limit] + if args.output.exists(): + raise ValueError( + "Use a new output file; do not overwrite existing observations" + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + health = json.loads(args.health_report.read_text())["before"] + validate_health_report(health, args.device) + guard = ctypes.CDLL(str(args.guard_so)) + guard.operatorx_fp8_guard_configure.argtypes = [ctypes.c_uint32] * 3 + [ + ctypes.c_int + ] + guard.operatorx_fp8_guard_configure.restype = ctypes.c_int + guard.operatorx_fp8_guard_last_json.restype = ctypes.c_char_p + import torch + import torch_npu + + torch.set_grad_enabled(False) + torch.set_num_threads(1) + torch.npu.set_device(args.device) + device = f"npu:{args.device}" + torch.npu.synchronize() + _, mm, schemas = worker.native_parameters(torch) + provenance = { + "script_sha256": sha(__file__), + "guard_sha256": sha(args.guard_so), + "worker_sha256": expected, + "torch": str(torch.__version__), + "torch_npu": str(torch_npu.__version__), + "schemas": schemas, + "task_queue_enable": "0", + "diagnostic_only": True, + "inputs": "Uninitialized tensors with original quantized shape, dtype and strides; GEMM is blocked before launch.", + } + for index, case in enumerate(cases): + watchdog = threading.Timer(300, lambda: os._exit(124)) + watchdog.daemon = True + watchdog.start() + a = case["args"] + m, n, k = (a[x] for x in ("m", "n", "k")) + record = { + "case_id": case["case_id"], + "opType": "gemm", + "args": a, + "index": index, + "total": len(cases), + "hardware_identity": health["identity_sha256"], + "utc": datetime.now(timezone.utc).isoformat(), + "provenance": provenance, + } + try: + free, _ = torch.npu.mem_get_info(args.device) + required = worker.estimate_memory(case)["estimated_required_bytes"] + if required > min(int(free), args.memory_budget_bytes): + raise ValueError( + "Preflight tensors exceed the available/configured memory budget" + ) + q = torch.empty((m, k), device=device, dtype=torch.float8_e4m3fn) + w = torch.empty((n, k), device=device, dtype=torch.float8_e4m3fn) + ws = torch.empty( + ((n + 127) // 128, k // 128), device=device, dtype=torch.float32 + ) + scales = torch.empty((m, k // 128), device=device, dtype=torch.float32) + torch.npu.synchronize() + if guard.operatorx_fp8_guard_configure(m, n, k, 1): + raise RuntimeError("Guard configuration rejected") + error = None + try: + output = torch_npu.npu_quant_matmul( + q, w.t(), ws.t(), pertoken_scale=scales, **mm + ) + torch.npu.synchronize() + del output + except RuntimeError as exc: + error = str(exc) + finally: + record["guard"] = json.loads(guard.operatorx_fp8_guard_last_json()) + guard.operatorx_fp8_guard_configure(0, 0, 0, 0) + record["launch_exception"] = error + if not record["guard"].get("observed") or error is None: + raise RuntimeError( + "Prelaunch interception not proved; stop before checking further shapes" + ) + if ( + "100000" not in error + or record["guard"].get("mode") != 1 + or record["guard"].get("forward_allowed") is not False + ): + raise RuntimeError( + "Expected deliberate prelaunch rejection not verified" + ) + if "507015" in error or "507035" in error: + raise RuntimeError("Unexpected device fault despite prelaunch guard") + torch.npu.synchronize() + del q, w, ws, scales + torch.npu.empty_cache() + record["status"] = "inspected" + except Exception: + record["status"] = "error" + record["error"] = traceback.format_exc() + finally: + watchdog.cancel() + with args.output.open("a") as f: + f.write(json.dumps(record, allow_nan=False) + "\n") + f.flush() + os.fsync(f.fileno()) + print( + json.dumps( + {k: record[k] for k in ("case_id", "index", "total", "status")}, + default=str, + ), + flush=True, + ) + if record["status"] != "inspected": + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/operatorx/scripts/ascend/operatorx_npu_health.py b/operatorx/scripts/ascend/operatorx_npu_health.py new file mode 100644 index 0000000000..6498764682 --- /dev/null +++ b/operatorx/scripts/ascend/operatorx_npu_health.py @@ -0,0 +1,510 @@ +from __future__ import annotations + +import math +import os +import re + +PCI = re.compile(r"[0-9a-fA-F]{4}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}\.[0-7]") +VISIBILITY_VARIABLES = ( + "ASCEND_RT_VISIBLE_DEVICES", + "ASCEND_VISIBLE_DEVICES", + "NPU_VISIBLE_DEVICES", +) +MAPPING_COLUMNS = re.compile( + r"NPU ID|Slot ID|Chip Logic ID|Chip Phy-ID|Chip ID|Chip Name" +) + + +def mapping_rows(text): + lines = text.splitlines() + headers = [ + i for i, line in enumerate(lines) if "NPU ID" in line and "Chip Name" in line + ] + if len(headers) != 1: + raise ValueError("Expected one recognized npu-smi mapping header") + header = lines[headers[0]] + columns = MAPPING_COLUMNS.findall(header) + remainder = MAPPING_COLUMNS.sub("", header).replace("|", "").strip() + if ( + remainder + or len(columns) != len(set(columns)) + or not {"NPU ID", "Chip ID", "Chip Name"} <= set(columns) + ): + raise ValueError("Unrecognized npu-smi mapping columns") + if columns[-1] != "Chip Name" or not ( + {"Chip Logic ID", "Chip Phy-ID"} & set(columns) + ): + raise ValueError("Mapping must provide a logical or physical chip ID") + rows = [] + for line in lines[headers[0] + 1 :]: + line = line.strip().strip("|").strip() + if not line or set(line) <= set("+-=|"): + continue + fields = line.split(maxsplit=len(columns) - 1) + if len(fields) != len(columns): + raise ValueError("Malformed npu-smi mapping row") + values = dict(zip(columns, fields)) + if values["Chip Name"].lower() in {"mcu"}: + continue + if not re.fullmatch(r"(?:Ascend\S*|910B[1-4])", values["Chip Name"], re.I): + raise ValueError("Unknown device in npu-smi mapping") + if any( + not value.isdecimal() for key, value in values.items() if key != "Chip Name" + ): + raise ValueError("Mapping IDs must be nonnegative integers") + rows.append( + { + "board": int(values["NPU ID"]), + "chip": int(values["Chip ID"]), + "logical_device_id": int(values["Chip Logic ID"]) + if "Chip Logic ID" in values + else None, + "physical_device_id": int(values["Chip Phy-ID"]) + if "Chip Phy-ID" in values + else None, + "slot_id": int(values["Slot ID"]) if "Slot ID" in values else None, + "name": values["Chip Name"], + } + ) + if not rows or len({(r["board"], r["chip"]) for r in rows}) != len(rows): + raise ValueError("Missing or duplicate board/chip mapping") + for key in ("logical_device_id", "physical_device_id"): + ids = [r[key] for r in rows if r[key] is not None] + if len(ids) != len(set(ids)): + raise ValueError(f"Duplicate {key} mapping") + return rows + + +def _cells(line): + return [part.strip() for part in line.strip().strip("|").split("|")] + + +def _processes(text, board): + match = re.search(r"Process\s+id", text, re.I) + if match is None: + raise ValueError("Missing recognized process-table header") + lines = text[match.start() :].splitlines() + container_ids = "Process id in container" in lines[0] + records, empty_boards = [], set() + for line in lines[1:]: + if "|" not in line: + continue + cells = _cells(line) + if not any(cells): + continue + empty = re.fullmatch( + r"No running processes found(?: in NPU\s+(\d+))?", cells[0], re.I + ) + if len(cells) == 1 and empty: + empty_boards.add(int(empty[1]) if empty[1] is not None else None) + continue + identity = re.fullmatch(r"(\d+)(?:\s+(\d+))?", cells[0]) + if not identity or len(cells) < 4 or not cells[1].isdecimal(): + raise ValueError("Unrecognized process-table row") + record = { + "board": int(identity[1]), + "chip": int(identity[2]) if identity[2] else None, + "pid": int(cells[1]), + } + if container_ids: + if len(cells) < 5 or not cells[-1].isdecimal(): + raise ValueError( + "Container PID column is present but PID is unavailable" + ) + record.update( + host_pid=int(cells[1]), container_pid=int(cells[-1]), pid=int(cells[-1]) + ) + records.append(record) + selected = [record for record in records if record["board"] == board] + if selected and (None in empty_boards or board in empty_boards): + raise ValueError("Contradictory empty and occupied process status") + if not selected and None not in empty_boards and board not in empty_boards: + raise ValueError("No explicit process status for selected board") + return selected + + +def status_rows(text, board): + if "Health" not in text or "Bus-Id" not in text: + raise ValueError("Missing Health or Bus-Id status header") + board_only = "NPU Util(%)" in text + if board_only == ("AICore(%)" in text): + raise ValueError("Unrecognized or ambiguous utilization header") + id_header = re.search(r"\bChip\s+(Phy-ID|Device)\b", text) + chip_only = bool(re.search(r"\|\s*Chip\s*\|\s*Bus-Id\s*\|", text)) + if not board_only and not id_header and not chip_only: + raise ValueError("Unrecognized chip/status-ID header") + current = None + devices, health = [], [] + for line in text.splitlines(): + if re.search(r"Process\s+id", line, re.I): + break + if "|" not in line: + continue + cells = _cells(line) + combined = re.fullmatch(r"(\d+)\s+(?:Ascend\S*|910B[1-4])", cells[0], re.I) + separate = ( + len(cells) > 2 + and cells[0].isdecimal() + and re.fullmatch(r"(?:Ascend\S*|910B[1-4])", cells[1], re.I) + ) + if combined or separate: + current = int(combined[1]) if combined else int(cells[0]) + state = cells[1] if combined else cells[2] + if current == board: + if state != "OK": + raise ValueError(f"Selected board Health is {state!r}, expected OK") + health.append(state) + buses = [i for i, cell in enumerate(cells) if PCI.search(cell)] + if not buses: + continue + if current is None or len(buses) != 1: + raise ValueError("Cannot associate PCI status with one board") + index = buses[0] + if PCI.fullmatch(cells[index]) is None or index + 1 >= len(cells): + raise ValueError("Malformed PCI/utilization row") + util = re.match(r"^(\d+(?:\.\d+)?)(?:\s|$)", cells[index + 1]) + if ( + util is None + or not math.isfinite(float(util[1])) + or not 0 <= float(util[1]) <= 100 + ): + raise ValueError("Invalid utilization value") + chip, physical, reported = None, None, None + if not board_only: + pair = re.fullmatch(r"(\d+)" if chip_only else r"(\d+)\s+(\d+)", cells[0]) + if pair is None: + raise ValueError("Malformed chip/status-ID row") + chip = int(pair[1]) + reported = None if chip_only else int(pair[2]) + physical = reported if id_header and id_header[1] == "Phy-ID" else None + elif any(cells[i] for i in range(index)): + raise ValueError("Unexpected identity columns in board-only PCI row") + if current == board: + devices.append( + { + "board": board, + "chip": chip, + "physical_device_id": physical, + "reported_device_id": reported, + "reported_device_column": "none" + if board_only + else "Chip-only" + if chip_only + else id_header[1], + "pci": cells[index], + "aicore_percent": float(util[1]), + "utilization_metric": "NPU Util(%)" if board_only else "AICore(%)", + "health": "OK", + } + ) + if ( + not health + or not devices + or len({row["pci"].lower() for row in devices}) != len(devices) + ): + raise ValueError("Missing selected board health/status or duplicate PCI rows") + if board_only and len(devices) != 1: + raise ValueError("Board-only status must identify exactly one PCI device") + if not board_only and len({row["chip"] for row in devices}) != len(devices): + raise ValueError("Duplicate chip status") + return {"devices": devices, "processes": _processes(text, board), "health": "OK"} + + +def _acl_identity(record, logical_id, physical_id): + required = ( + "logical_device_id", + "physical_device_id", + "logical_to_physical_rc", + "physical_to_logical_rc", + "roundtrip_logical_device_id", + ) + if not isinstance(record, dict) or any( + type(record.get(key)) is not int for key in required + ): + raise ValueError( + "ACL runtime logical/physical cross-check is required with integer IDs and return codes" + ) + if record["logical_to_physical_rc"] != 0 or record["physical_to_logical_rc"] != 0: + raise ValueError("ACL runtime logical/physical query failed") + if ( + record["logical_device_id"] != logical_id + or record["physical_device_id"] != physical_id + or record["roundtrip_logical_device_id"] != logical_id + ): + raise ValueError( + "ACL runtime logical/physical mapping disagrees with requested device or SMI physical ID" + ) + user_keys = ( + "user_device_id", + "user_to_logical_rc", + "user_to_physical_rc", + "physical_to_user_rc", + "logical_to_user_rc", + "user_logical_device_id", + "user_physical_device_id", + "roundtrip_user_device_id", + ) + if any(key in record for key in user_keys): + if any(type(record.get(key)) is not int for key in user_keys): + raise ValueError("ACL runtime user-device mapping is incomplete") + if any(record[key] != 0 for key in user_keys if key.endswith("_rc")): + raise ValueError("ACL runtime user-device query failed") + if ( + record["user_device_id"] != logical_id + or record["user_logical_device_id"] != logical_id + or record["user_physical_device_id"] != physical_id + or record["roundtrip_user_device_id"] != record["user_device_id"] + ): + raise ValueError( + "ACL runtime user-device mapping differs from the requested unremapped index" + ) + return dict(record) + + +def validate_identity( + parsed, + mapped, + board, + chip, + logical_id, + expected_pci=None, + *, + acl_runtime_mapping=None, +): + expected = [row for row in mapped if row["board"] == board] + selected_mapping = [row for row in expected if row["chip"] == chip] + if len(selected_mapping) != 1: + raise ValueError("Requested board/chip mapping not present exactly once") + mapping = selected_mapping[0] + logical = mapping["logical_device_id"] + if logical is not None and logical != logical_id: + raise ValueError("Requested logical-device mapping differs from npu-smi") + acl = None + if logical is None: + if mapping["physical_device_id"] is None: + raise ValueError("Neither logical nor physical identity is available") + acl = _acl_identity( + acl_runtime_mapping, logical_id, mapping["physical_device_id"] + ) + elif acl_runtime_mapping is not None: + if mapping["physical_device_id"] is None: + raise ValueError( + "Cannot cross-check ACL mapping without an SMI physical ID" + ) + acl = _acl_identity( + acl_runtime_mapping, logical_id, mapping["physical_device_id"] + ) + rows = parsed["devices"] + if any(row["chip"] is None for row in rows): + if len(expected) != 1 or len(rows) != 1 or rows[0]["board"] != board: + raise ValueError("Board-only PCI status cannot identify a multi-chip board") + selected = dict(rows[0], chip=chip) + else: + if {(row["board"], row["chip"]) for row in rows} != { + (row["board"], row["chip"]) for row in expected + }: + raise ValueError("Status rows do not cover every mapped chip on the board") + selected = dict(next(row for row in rows if row["chip"] == chip)) + if selected.get("health") != "OK" or parsed.get("health") != "OK": + raise ValueError("Identity requires healthy status evidence") + physical = selected.get("physical_device_id") + if ( + physical is not None + and mapping["physical_device_id"] is not None + and physical != mapping["physical_device_id"] + ): + raise ValueError("Status physical ID differs from mapping") + if expected_pci and selected["pci"].lower() != expected_pci.lower(): + raise ValueError("Selected board/chip PCI address changed") + selected.update( + logical_device_id=logical_id, + physical_device_id=mapping["physical_device_id"] + if mapping["physical_device_id"] is not None + else physical, + identity_basis="SMI plus bidirectional ACL mapping" + if acl + else "SMI logical mapping", + ) + if acl is not None: + selected["acl_runtime_mapping"] = acl + return selected + + +def validate_health_query(capture, board): + fields = _query_fields(capture) + if ( + not {"NPU ID", "Health Status", "Error Code", "Error Information"} + <= fields.keys() + ): + raise ValueError("Health query omitted required status/error fields") + if fields["NPU ID"] != str(board) or fields["Health Status"] != "OK": + raise ValueError("Health-query identity/status mismatch") + if ( + fields["Error Code"] not in {"NA", "0", "0x0", "0x00000000"} + or fields["Error Information"] != "NA" + ): + raise ValueError("Health query reports an error or unrecognized error state") + return { + "board": board, + "health": "OK", + "error_code": fields["Error Code"], + "error_information": fields["Error Information"], + } + + +def _query_fields(capture): + if ( + not isinstance(capture, dict) + or type(capture.get("returncode")) is not int + or capture["returncode"] != 0 + ): + raise ValueError("npu-smi query did not succeed") + fields = {} + for line in capture.get("stdout", "").splitlines(): + if not line.strip(): + continue + key, sep, value = line.partition(":") + if not sep or key.strip() in fields: + raise ValueError("Malformed or duplicate diagnostic-query field") + fields[key.strip()] = value.strip() + return fields + + +def validate_diagnostic_queries(captures, board): + required = ("health", "current-fault-event", "ecc", "ecc-enable", "pcie-err") + selected = {} + for capture in captures: + argv = capture.get("argv", []) + if "-t" not in argv or argv.index("-t") + 1 >= len(argv): + continue + kind = argv[argv.index("-t") + 1] + if kind not in required: + continue + if ( + argv != ["npu-smi", "info", "-t", kind, "-i", str(board)] + or kind in selected + ): + raise ValueError("Ambiguous diagnostic query or wrong board") + selected[kind] = capture + if set(selected) != set(required): + raise ValueError("Missing required health/fault/ECC/PCIe queries") + result = {"health": validate_health_query(selected["health"], board)} + fault = _query_fields(selected["current-fault-event"]) + if fault != {"Fault Event Count": "0", "Fault Event Information": "NA"}: + raise ValueError("Current fault-event state is not explicitly clean") + result["current-fault-event"] = {"fault_event_count": 0} + enabled = _query_fields(selected["ecc-enable"]) + if enabled != {"HBM ECC-Enable Status": "True"}: + raise ValueError("HBM ECC is not explicitly enabled") + result["ecc-enable"] = {"enabled": True} + counters = { + "ecc": ( + "HBM Single Bit Error Count", + "HBM Double Bit Error Count", + "HBM Single Bit Aggregate Total Err Cnt", + "HBM Double Bit Aggregate Total Err Cnt", + "HBM Single Bit Isolated Pages Count", + "HBM Double Bit Isolated Pages Count", + "HBM Single Bit Next-Isolated Pages Count", + "HBM Double Bit Next-Isolated Pages Count", + ), + "pcie-err": ( + "TX Error Count", + "RX Error Count", + "Lcrc Error Count", + "Ecrc Error Count", + "Retry Count", + ), + } + for kind, names in counters.items(): + fields = _query_fields(selected[kind]) + if set(fields) != {"NPU ID", *names} or fields["NPU ID"] != str(board): + raise ValueError(f"{kind} query has missing/unknown fields or wrong board") + if any(fields[name] != "0" for name in names): + raise ValueError(f"{kind} counters are not all zero") + result[kind] = {name: 0 for name in names} + return result + + +def collect_acl_runtime_mapping(logical_id, *, library_path="libascendcl.so"): + import ctypes + + if type(logical_id) is not int or logical_id < 0: + raise ValueError("logical_id must be a nonnegative integer") + if any(os.environ.get(key) for key in VISIBILITY_VARIABLES): + raise ValueError( + "Resolve device visibility/remapping before ACL identity collection" + ) + lib = ctypes.CDLL(library_path) + lib.aclInit.argtypes, lib.aclInit.restype = [ctypes.c_char_p], ctypes.c_int + lib.aclFinalize.argtypes, lib.aclFinalize.restype = [], ctypes.c_int + names = ( + "aclrtGetUserDevIdByLogicDevId", + "aclrtGetLogicDevIdByUserDevId", + "aclrtGetPhyDevIdByUserDevId", + "aclrtGetPhyDevIdByLogicDevId", + "aclrtGetLogicDevIdByPhyDevId", + "aclrtGetUserDevIdByPhyDevId", + ) + for name in names: + fn = getattr(lib, name) + fn.argtypes, fn.restype = ( + [ctypes.c_int32, ctypes.POINTER(ctypes.c_int32)], + ctypes.c_int, + ) + initialized = int(lib.aclInit(None)) + if initialized != 0: + raise RuntimeError( + f"aclInit returned {initialized}; preflight must own an uninitialized ACL runtime" + ) + record = { + "library": library_path, + "acl_init_rc": initialized, + "logical_device_id": logical_id, + "queries": [], + } + failure = None + + def query(name, value): + output = ctypes.c_int32(-1) + rc = int(getattr(lib, name)(value, ctypes.byref(output))) + record["queries"].append( + {"api": name, "input": value, "returncode": rc, "output": output.value} + ) + if rc != 0 or output.value < 0: + raise RuntimeError( + f"{name}({value}) returned rc={rc}, output={output.value}" + ) + return output.value, rc + + try: + record["user_device_id"], record["logical_to_user_rc"] = query( + names[0], logical_id + ) + record["user_logical_device_id"], record["user_to_logical_rc"] = query( + names[1], record["user_device_id"] + ) + record["user_physical_device_id"], record["user_to_physical_rc"] = query( + names[2], record["user_device_id"] + ) + record["physical_device_id"], record["logical_to_physical_rc"] = query( + names[3], logical_id + ) + record["roundtrip_logical_device_id"], record["physical_to_logical_rc"] = query( + names[4], record["physical_device_id"] + ) + record["roundtrip_user_device_id"], record["physical_to_user_rc"] = query( + names[5], record["physical_device_id"] + ) + _acl_identity(record, logical_id, record["physical_device_id"]) + except Exception as exc: + failure = exc + finally: + record["acl_finalize_rc"] = int(lib.aclFinalize()) + if failure is not None: + raise RuntimeError( + f"ACL identity query failed: {failure}; aclFinalize={record['acl_finalize_rc']}" + ) from failure + if record["acl_finalize_rc"] != 0: + raise RuntimeError(f"aclFinalize returned {record['acl_finalize_rc']}") + return record diff --git a/operatorx/scripts/ascend/operatorx_queued_timing.py b/operatorx/scripts/ascend/operatorx_queued_timing.py new file mode 100644 index 0000000000..3e889ca287 --- /dev/null +++ b/operatorx/scripts/ascend/operatorx_queued_timing.py @@ -0,0 +1,74 @@ +import hashlib +import time +from pathlib import Path + +FIRST = True +PROTOCOL = "queued_10_events_5_warmups_25ms_ramp_4_write_shield_v1" +SOURCE_URL = "https://github.com/SemiAnalysisAI/InferenceX/blob/24e1caa715c0cd57e141969562ad06403023ca00/operatorx/runners/common/timing.py" + + +def time_op(npu, fn, cache, config): + global FIRST + if (config["samples"], config["warmups"], config["warmup_ms"]) != (10, 5, 25): + raise ValueError("Queued protocol requires 10 samples, 5 warmups, 25 ms ramp") + begun = time.perf_counter_ns() + for _ in range(5): + output = fn() + npu.synchronize() + floor_ms = 1000 if FIRST else 25 + FIRST = False + ramp_start = time.perf_counter_ns() + ramp_calls = 0 + while (time.perf_counter_ns() - ramp_start) / 1e6 < floor_ms: + if ramp_calls >= 1000000: + raise RuntimeError("Queued warmup iteration bound exceeded") + output = fn() + npu.synchronize() + ramp_calls += 1 + warmup_ms = (time.perf_counter_ns() - begun) / 1e6 + starts = [npu.Event(enable_timing=True) for _ in range(10)] + ends = [npu.Event(enable_timing=True) for _ in range(10)] + wall_start = time.perf_counter_ns() + for _ in range(4): + cache.zero_() + for start, end in zip(starts, ends): + cache.zero_() + start.record() + output = fn() + end.record() + npu.synchronize() + batch_wall_us = (time.perf_counter_ns() - wall_start) / 1000 + event_us = [float(s.elapsed_time(e)) * 1000 for s, e in zip(starts, ends)] + latency = sorted(event_us)[5] + cooldown = min(latency * 1e-6 * 15 * 4, 1.0) + time.sleep(cooldown) + timing = { + "protocol": PROTOCOL, + "device_event_samples_us": event_us, + "aggregation": "upper median: sorted(samples)[5] of 10", + "requested_samples": 10, + "warmups": 5, + "actual_warmups": 5 + ramp_calls, + "minimum_warmup_ms": 25, + "effective_ramp_floor_ms": floor_ms, + "actual_warmup_ms": warmup_ms, + "mode": "eager", + "npu_graph": False, + "cache_write_bytes_per_sample": config["cache_write_bytes"], + "cache_write_operation": "uint8 zero_ queued before each start event; no per-sample synchronization", + "cache_write_in_timed_interval": False, + "cold_cache_proven": False, + "launch_shield": "four queued cache zero_ writes; not CUDA _sleep", + "shield_writes": 4, + "synchronizations_inside_sample_loop": 0, + "queued_batch_wall_us": batch_wall_us, + "queued_wall_us_per_call": batch_wall_us / 10, + "wall_interval": "shield writes + all ten cache writes and event-bracketed calls + final synchronization", + "cooldown_seconds": cooldown, + "cooldown_inside_timer": False, + "timing_helper_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "operatorx_reference_url": SOURCE_URL, + "gpu_throttle_retry_equivalence_claimed": False, + "gpu_graph_equivalence_claimed": False, + } + return output, timing diff --git a/operatorx/scripts/ascend/prepare.py b/operatorx/scripts/ascend/prepare.py new file mode 100644 index 0000000000..77ba7e26d2 --- /dev/null +++ b/operatorx/scripts/ascend/prepare.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +import argparse +import hashlib +import importlib +import json +from collections import Counter +from pathlib import Path +from typing import Any + +WORKERS = { + "unquantized": "operatorx_ascend_worker", + "fp8": "operatorx_fp8_block_worker", +} + + +def canonical(value: Any) -> str: + return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False) + + +def normalize(entries: list[dict[str, Any]]) -> list[dict[str, Any]]: + cases = {} + for entry in entries: + op = entry.get("opType", entry.get("type")) + if not isinstance(op, str) or not isinstance(entry.get("args"), dict): + raise ValueError("Each entry needs type/opType and an args object") + if "opType" in entry and "type" in entry and entry["opType"] != entry["type"]: + raise ValueError("Conflicting operation types") + semantic = {"opType": op, "args": entry["args"]} + identity = canonical(semantic) + cid = op + "-" + hashlib.sha256(identity.encode()).hexdigest()[:16] + if "case_id" in entry and entry["case_id"] != cid: + raise ValueError("case_id does not match complete arguments") + sources = entry.get("sources", []) + if not isinstance(sources, list): + raise ValueError("sources must be a list") + if identity not in cases: + cases[identity] = {**semantic, "case_id": cid, "sources": []} + for source in sources: + if source not in cases[identity]["sources"]: + cases[identity]["sources"].append(source) + return list(cases.values()) + + +def make_plan(entries: list[dict[str, Any]], kind: str, budget: int) -> dict[str, Any]: + if type(budget) is not int or budget <= 0: + raise ValueError("Memory budget must be a positive integer") + worker = importlib.import_module(WORKERS[kind]) + config = { + "cache_write_bytes": 256 * 1024**2, + "workspace_reserve_bytes": 2 * 1024**3, + "memory_budget_bytes": budget, + } + cases = [] + for case in normalize(entries): + prepared = worker.plan_case( + case, + cache_write_bytes=config["cache_write_bytes"], + workspace_reserve_bytes=config["workspace_reserve_bytes"], + ) + case["support"] = prepared["support"] + case["phase"] = "implementation_required" + if prepared["support"]["supported"]: + case["memory"] = prepared["memory_estimate"] + case["phase"] = ( + "new" if case["memory"]["required_bytes"] <= budget else "memory_review" + ) + cases.append(case) + cases.sort( + key=lambda c: ( + c["phase"], + c.get("memory", {}).get("required_bytes", 0), + c["case_id"], + ) + ) + groups = {} + for case in cases: + if case["phase"] == "new": + spec = { + k: v + for k, v in case["support"]["normalized"].items() + if k not in {"m", "n", "k"} + } + groups.setdefault(canonical(spec), []).append(case) + smoke = [ + rows[i]["case_id"] + for rows in groups.values() + for i in sorted({0, len(rows) // 2, len(rows) - 1}) + ] + return { + "schema_version": 1, + "config": config, + "cases": cases, + "smoke_case_ids": smoke, + "counts": dict(Counter(c["phase"] for c in cases)), + "kind": kind, + "worker_sha256": hashlib.sha256(Path(worker.__file__).read_bytes()).hexdigest(), + "dependency_hashes": { + name: hashlib.sha256( + Path(__file__).with_name(name).read_bytes() + ).hexdigest() + for name in ("operatorx_queued_timing.py", "operatorx_ascend_worker.py") + }, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--input", type=Path, nargs="+", required=True) + parser.add_argument("--kind", choices=WORKERS, required=True) + parser.add_argument("--memory-budget-bytes", type=int, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + entries = [] + for path in args.input: + value = json.loads(path.read_text()) + value = value["cases"] if isinstance(value, dict) else value + if not isinstance(value, list): + raise ValueError("Input must be a testlist array or a cases object") + entries.extend(value) + plan = make_plan(entries, args.kind, args.memory_budget_bytes) + with args.output.open("x") as target: + json.dump(plan, target, indent=2, allow_nan=False) + target.write("\n") + print(json.dumps(plan["counts"])) + + +if __name__ == "__main__": + main() diff --git a/operatorx/tests/fixtures/ascend_fp8_tiling.bin b/operatorx/tests/fixtures/ascend_fp8_tiling.bin new file mode 100644 index 0000000000..d4e456f751 Binary files /dev/null and b/operatorx/tests/fixtures/ascend_fp8_tiling.bin differ diff --git a/operatorx/tests/test_ascend_l0_guard.py b/operatorx/tests/test_ascend_l0_guard.py new file mode 100644 index 0000000000..bd85367f4d --- /dev/null +++ b/operatorx/tests/test_ascend_l0_guard.py @@ -0,0 +1,389 @@ +import ctypes +import json +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parents[1] / "scripts" / "ascend" +SOURCE = HERE / "operatorx_fp8_l0_guard.cpp" +CAPTURE = Path(__file__).with_name("fixtures") / "ascend_fp8_tiling.bin" +KERNEL = b"QuantBatchMatmulV3_ND_ND_fp8e4m3_fp8e4m3_fp32_bf16_high_performance" + +# Exercise the actual hook code with deterministic fake runtime entry points. +# Redirecting dlsym keeps this CPU harness portable; Linux LD_PRELOAD resolution +# and the installed CANN ABI remain device-smoke responsibilities. +HARNESS = r""" +#include +#include +#include +#include +static char fake_name[2048] = {}; +static int fake_name_failure = 0; +static unsigned fake_launch_count = 0; +static int fake_name_query(void *, uint32_t n, char *out) { + if (fake_name_failure) return 1; + std::snprintf(out, n, "%s", fake_name); + return 0; +} +static int fake_entry(void *, uint64_t, void **out) { + *out = reinterpret_cast(0x1234); + return 0; +} +static int fake_launch(void *, uint32_t, void *, void *, void *, size_t, void *, size_t) { + ++fake_launch_count; + return 0; +} +static void *fake_dlsym(void *, const char *name) { + if (!std::strcmp(name, "aclrtGetFunctionName")) return reinterpret_cast(fake_name_query); + if (!std::strcmp(name, "aclrtBinaryGetFunctionByEntry")) return reinterpret_cast(fake_entry); + if (!std::strcmp(name, "aclrtLaunchKernelWithHostArgs")) return reinterpret_cast(fake_launch); + return nullptr; +} +#define dlsym fake_dlsym +#include "operatorx_fp8_l0_guard.cpp" +#undef dlsym +extern "C" void operatorx_test_reset(const char *name, int fail) { + std::snprintf(fake_name, sizeof(fake_name), "%s", name); + fake_name_failure = fail; + fake_launch_count = 0; +} +extern "C" unsigned operatorx_test_forward_count() { return fake_launch_count; } +""" + + +class Placeholder(ctypes.Structure): + _fields_ = [("addrOffset", ctypes.c_uint32), ("dataOffset", ctypes.c_uint32)] + + +def changed(raw, **fields): + offsets = { + "batchA": 0, + "quantA": 60, + "quantB": 64, + "groupM": 76, + "groupN": 80, + "groupK": 84, + "m": 88, + "n": 92, + "k": 96, + "baseM": 100, + "baseN": 104, + "baseK": 108, + } + result = bytearray(raw) + for name, value in fields.items(): + struct.pack_into("