Ascend NPU ARM operator CI
Use this runbook to deploy, operate, troubleshoot, and extend Ascend NPU ARM CI. It covers the operator workflow and the separate Qwen3 model evaluation workflow that shares the NPU runner infrastructure.
Prerequisites
Before you enable hardware jobs or run operator tests, prepare the following resources and permissions:
- Repository permission to configure GitHub Actions variables and workflows.
- An ephemeral Linux ARM64 NPU runner that meets the runner deployment contract. Do not enable hardware jobs before the deployment is ready.
- An existing exclusive NPU allocation and the image-provided environment for standalone operator commands. Standalone commands do not allocate devices.
- For Qwen3 model evaluation, the read-only
/data/weights/Qwen3-0.6Bcheckpoint on the runner.
Triggers and change selection
The operator workflow is defined in .github/workflows/ascend-npu-tests.yml and appears as Ascend NPU Tests in GitHub Actions. It runs in lightseekorg/tokenspeed or the repository identified by the full owner/repository value of the TOKENSPEED_NPU_CI_REPOSITORY repository variable. Forks must explicitly set that variable.
Enable NPU CI in a fork or another allowed repository
The upstream repository enables operator and model CI without repository variables. GitHub does not provide repository variables to fork pull_request runs, and GitHub's fork workflow approval requirements still apply.
For a fork or another allowed repository, enable hardware jobs after you complete the runner deployment:
From the repository home page, open the Variables page under Settings, Secrets and variables, and Actions.
Configure the required repository variables described in the following table:
Variable Purpose TOKENSPEED_NPU_CI_REPOSITORYSet the full owner/repositoryvalue for forks. The officiallightseekorg/tokenspeedrepository is already on the allowlist.TOKENSPEED_NPU_ARM_CI_ENABLEDIn other allowed repositories, set to trueonly after deployment requirements are met. Leave unset to disable hardware jobs. Upstream does not require this variable.Open an Ascend NPU Tests run and confirm that the
selectjob completes. A matching change must produceshould_run=truebefore GitHub schedules the hardware job.
In other allowed repositories, leaving TOKENSPEED_NPU_ARM_CI_ENABLED unset skips the hardware job without entering a runner queue. A positive selection result does not mean the operators have run. Verify execution through the phase reports and uploaded evidence.
To disable NPU CI upstream, disable the Ascend NPU Tests and Ascend NPU Model Tests workflows in GitHub Actions. The enable variable controls only other allowed repositories.
The NPU allowlist uses its own TOKENSPEED_NPU_CI_REPOSITORY variable. It does not require the shared repository variable used by GPU workflows, so enabling NPU CI does not enable other vendors' scheduling.
Trigger and security behavior
The workflow has the following triggers and execution boundaries:
- Pushes to
main,pull_requestevents targetingmain, andworkflow_dispatchtrigger the workflow. - Supported PR events are
opened,synchronize,reopened, andready_for_review. Draft PRs do not start the NPU job. - The independent
pr-test-npu-armconcurrency group is keyed by PR or ref. Pull request events cancel older runs for the same PR; pushes and manual runs do not initiate cancellation. - Test code never runs through
pull_request_target. - PRs execute repository test code. Use a dedicated isolated runner, preserve GitHub's external-contributor approval policy, and do not inject deployment credentials into test processes.
Change selection behavior
The GitHub-hosted select job checks out the event commit, runs the CPU-only API regression tests with python3 -B -m unittest discover -s test/ci_system/npu -p test_changes.py, and then runs test/ci_system/npu/changes.py. Selection uses the same GitHub API change-list checks as the independent NPU workflow:
- PRs: Read every page of
/pulls/<number>/fileswith 100 files per page. The current PR head and base must match the event before and after reading. The file count must remain stable and match the complete response. More than 3,000 files, duplicates, malformed paths, or partial responses fail selection. - Pushes: Read
/compare/<before>...<after>. Both SHAs must be nonzero. Responses with 300 or more files fail because the compare API can truncate the list. Creating a branch with an all-zerobeforefails selection instead of guessing missing changes. - Manual runs: Select the full suite without an API file request.
- Renames: Check both
filenameandprevious_filename. API failures fail the job instead of silently skipping tests.
The selector uses the event's PR identity and the complete API file list without depending on the parents of GitHub's temporary test-merge commit. GitHub can supply an older test-merge SHA while refreshing that reference. The hardware job still checks out and verifies the event's exact GITHUB_SHA; selection does not substitute the PR head SHA. The selection step receives only the read-permission GITHUB_TOKEN through GH_TOKEN; no token is passed to operator test processes.
Path rules in test/ci/npu/manifest.json cover the NPU package, the shared tokenspeed-kernel/python/ dependency, dependency configuration, NPU CI scripts, the task YAML and pipeline, and both the NPU caller and shared task workflow. Documentation changes ending in .md or .rst are excluded. Matching is case-sensitive and includes additions, modifications, deletions, and both sides of a rename within the API completeness limits.
Any matching path selects every registered operator. Unrelated changes emit should_run=false and reason=no-watched-changes. The workflow has no top-level path filter, so unrelated changes still produce a selection result.
The caller passes the selected test/ci/ut/npu-operators.yaml task to .github/workflows/run-ci-task-matrix.yml with the dedicated NPU runner label. This shared workflow invokes test/ci_system/pipeline.py in the existing NPU environment; the task has no dependency-install stage or Docker requirement.
NPU CI implementation and operator tests live under test/ci_system/npu/ and test/ci/npu/; new operators do not require changes to GPU task lists. The dedicated npu matrix group selects the tokenspeed-npu-arm64- runner family. AMD MI350, AMD MI450, and NVIDIA groups exclude that runner. GPU path selection also ignores NPU-only task YAML changes.
Components and execution order
The following components implement change selection, execution, and reporting:
| Component | Responsibility |
|---|---|
test/ci_system/npu/changes.py | Validates the manifest and event identity, and then selects relevant changes. |
test/ci/npu/manifest.json | Uses schema version 3 to define watched paths, operator order, one script path per operator, and expected counts. |
test/ci/npu/expected-plans.json | Retains schema version 2 and records accuracy cases, performance configurations, sampling parameters, and associated hashes. |
test/ci_system/npu/run_step.sh | Checks ARM/Linux and the checkout identity, and then prepares per-run caches. |
test/ci_system/npu/run_phase.py | Runs one phase in order, supervises child processes and timeouts, saves evidence, and returns an exit code. |
test/ci_system/npu/reporting.py | Validates structured logs and generates JSON reports and English Markdown summaries. |
test/ci/npu/tests/<operator>-test.py | Combines numerical checks and performance sampling in one script with a required --mode argument. |
test/ci/npu/operator_cli.py | Parses the explicit mode and runs the selected phase callbacks, stopping on the first failure. |
The tests/ directory contains the registered operator scripts. Each <operator>-test.py runs by file path through the manifest or an explicit command and requires an NPU for accuracy and performance modes. The hyphenated names are executable script paths, not Python module import names.
CI phase order
Before invoking the pipeline, the shared workflow validates NPU deployment, platform, and event inputs, creates an isolated run/attempt directory, and checks out the requested SHA. NPU_CI_WORK identifies that directory, and commands run from its checkout/ directory.
The task runs exactly two sequential commands:
- Run the accuracy phase for every operator with
bash test/ci_system/npu/run_step.sh accuracy "$NPU_CI_WORK". - After accuracy succeeds, run the performance phase for every operator with
bash test/ci_system/npu/run_step.sh performance "$NPU_CI_WORK".
Accuracy tests for all operators finish before performance tests begin. The executor starts each manifest script with --mode accuracy or --mode performance; it has no operator-name branches. The standalone --mode all option is a convenience for one operator only. CI does not use it because CI preserves the global ordering of all accuracy tests before any performance test.
Performance reuses the directory only after accuracy succeeds. Both commands retain the existing Linux, ARM64, SHA, and clean-checkout checks and cache preparation in run_step.sh. The runner image supplies the environment, and the scheduler owns the exclusive NPU allocation.
The shared workflow checks out the requested SHA with actions/checkout and does not persist checkout credentials for NPU tasks. Scripts use the image-provided python3 from PATH with -B -u, and the two kernel package directories in the checkout precede other entries in PYTHONPATH.
Test coverage and performance measurements
The registered operators have the following accuracy and performance coverage:
| Operator | Accuracy cases | Performance configurations | Performance samples |
|---|---|---|---|
| scatter | 5 | 6 | 30 |
| virtual_slots_to_local | 48 | 8 | 40 |
The suite has 53 accuracy cases, 14 performance configurations, and 70 samples. Each configuration performs 10 warmup iterations and then collects 5 samples of 50 executions each. Median latency is the median of the five per-execution sample averages, measured in milliseconds.
The record_only policy validates execution and sampling completeness only: performance_verdict=not_evaluated and threshold_ms=null. There are no latency thresholds. A completed result does not mean performance passed a target.
Failures, logs, and cleanup
Use the failure behavior and evidence in this section to diagnose an unsuccessful run.
Failure behavior
- Any case, configuration, script, checkout, environment, or required evidence-write failure returns nonzero and stops subsequent tests.
- Later operators in the current phase are recorded as
not_run; if accuracy fails, the performance command is skipped. - Only necessary evidence saving and resource cleanup continue after failure. Report or Actions summary write failures also fail the step.
- Each script has a 600-second timeout, and the job has a 60-minute timeout. These limits are not performance thresholds.
Logs and process supervision
Merged stdout and stderr output is written to disk and flushed to the console as it arrives. Python output is unbuffered. Each operator prints its start, finish, elapsed time, and exit code. A heartbeat is printed every 30 seconds while a script remains active.
Original exceptions are preserved. Error annotations escape %, CR, and LF; failure explanations and English summaries are generated within the same step. Executor exceptions also include a traceback.
Test subprocesses run in private process groups. Completion, nonzero exit, timeout, SIGINT, and SIGTERM all attempt to terminate remaining processes in that group. Test processes must not escape supervision by starting a new session. SIGKILL or host failure can leave partial logs without a final summary.
Cleanup behavior
The scheduler retains the NPU allocation for the lifetime of the ephemeral runner, including both phases and cleanup. Source recording, artifact upload, and work-directory cleanup use the shared workflow. Cleanup runs even after a task failure; phase process cleanup remains in the existing executor.
Runner deployment contract and evidence locations
runs-on uses only the dedicated tokenspeed-npu-arm64-1npu label without adding the default self-hosted label. The hardware job is disabled by default. These are deployment requirements, not assertions that upstream already has a runner, NPU, or configured runtime.
Deploy an NPU runner
- Register an ephemeral Linux ARM64 NPU runner that runs as a non-root user. For an organization runner scale set, register at organization scope and grant the repository access through its runner group.
- Assign
tokenspeed-npu-arm64-{1,2,4,8}npulabels with the corresponding exclusive device allocation. The operator task selectstokenspeed-npu-arm64-1npu; it does not duplicate its single-device cases across the larger allocations. - Provide Python, PyYAML, PyTorch, TorchNPU, Triton Ascend, and a compatible CANN environment on
PATHin the runner image before the runner starts. Model runner images have additional requirements in Qwen3 model evaluation. - Grant the runner account permission to create and remove job directories under
GITHUB_WORKSPACE. No fixed host environment path, host-wide lock, fixed runner-name variable, or username is required; runner names are dynamic. - Provide an exclusive NPU allocation for the entire job and account for workloads outside its scheduler. Do not use unreserved host devices.
- Before enabling the workflow, confirm that the visible NPU count matches the selected label. The workflow checks NPU availability and the visible count before checkout.
- After enabling a run, confirm that a runner picks up the hardware job. If no available runner has the required label, the job waits for scheduling and cannot execute runtime checks. Installing the runner alone is insufficient.
Evidence locations
The shared workflow creates GITHUB_WORKSPACE/run-<run_id>-<attempt>-<task>-<runner>/, with checkout/, separate accuracy/ and performance/ result directories, and caches. The following table lists the evidence available in each location:
| Location | Contents |
|---|---|
| Each phase directory | context.json, report.json, and summary.md. |
| Each operator directory | Raw logs, process.json, result.json, and known exit codes. |
checkout/.ci-artifacts/published/npu/ | Phase evidence collected after execution. |
checkout/.ci-artifacts/ | The pipeline's result.json and the shared source reporter's source.json. |
Summaries are appended to GITHUB_STEP_SUMMARY, and the workflow uploads the artifact after collecting the evidence. The phase directories remain outside the checkout during execution so both commands can verify a clean source tree. .ci-artifacts/ is created only when the pipeline writes its final result.
Use the uploaded artifacts for verification after shared cleanup removes the entire run directory, including checkout and caches. Deploy from a clean baseline worktree rather than reusing a fault-injection branch.
Add cases, operators, and structured events
Use the following procedures to extend the suite without changing the common execution path.
Add a case
- Update the operator script and its test plan.
- Synchronize parameters, ordering, counts, and script hashes in
expected-plans.json. - Synchronize the manifest and script hashes.
- Validate the changes through the ARM NPU workflow.
Add an operator
- Create
test/ci/npu/tests/<name>-test.py. - In the manifest's
operatorslist, register its name, a singlescriptfield pointing to that canonical path, and its counts. Schema version 3 rejects the former per-phasescriptsmapping. - Add its accuracy plan, performance plan, and timing parameters to
expected-plans.json. The expected plan retains schema version 2 and has onesource_sha256entry for each registered script. - Require the
--mode {accuracy,performance,all}argument in the script. Parse arguments before importing NPU dependencies so--help, missing arguments, and invalid values work on a CPU host. - Use the shared CLI with two callbacks that return integer exit codes.
allcalls accuracy first and starts performance only after accuracy returns zero. Exceptions, nonzero exits, and invalid callback results stop execution. Do not store the active mode in mutable global state. - Update
watch_pathsfor new source dependencies. Do not add operator-name branches to the common executor or additional workflow steps. - Synchronize the manifest and script hashes, and then validate the changes.
Synchronize manifest and script hashes
Any byte change to the manifest or registered scripts, including formatting, requires hash synchronization. Hashes bind the plan to specific files; they do not replace review of expected values.
After formatting, update manifest_sha256 and every registered source_sha256 entry by running this command from the repository root:
python3 - <<'PY'
import hashlib, json
from pathlib import Path
root = Path('test/ci/npu')
manifest = json.loads((root / 'manifest.json').read_text())
plan_path = root / 'expected-plans.json'
plan = json.loads(plan_path.read_text())
plan['manifest_sha256'] = hashlib.sha256((root / 'manifest.json').read_bytes()).hexdigest()
plan['source_sha256'] = {
entry['script']: hashlib.sha256(Path(entry['script']).read_bytes()).hexdigest()
for entry in manifest['operators']
}
plan_path.write_text(json.dumps(plan, indent=2, ensure_ascii=False) + '\n')
PYA successful run exits without errors and rewrites test/ci/npu/expected-plans.json with the current hashes. Repeat this step after any later formatting change.
Run one operator on an ARM runner
Load the runner image environment and use an existing exclusive allocation. Standalone scripts print results but do not allocate an NPU or save phase reports. They are not a replacement for the CI entry point.
From the repository root, set
PYTHONPATHand choose an explicit mode. The following example lists the three supported invocations forscatter; replacetests/scatter-test.pywithtests/virtual_slots_to_local-test.pyto test the other operator:bashexport PYTHONPATH="$PWD/tokenspeed-kernel/python:$PWD/tokenspeed-kernel-npu/python${PYTHONPATH:+:$PYTHONPATH}" python3 -B -u \ test/ci/npu/tests/scatter-test.py --mode accuracy python3 -B -u \ test/ci/npu/tests/scatter-test.py --mode performance python3 -B -u \ test/ci/npu/tests/scatter-test.py --mode allThere is no default mode.
allperforms accuracy and then performance for that operator, preserving distinctphase=accuracyandphase=performancestructured events. Any accuracy failure prevents performance from starting.Confirm that the selected command exits with status zero and emits a
completedevent for each requested phase. For--mode all, verify that the accuracycompletedevent appears before the performancestartedevent.
Run the common phase executor directly
Direct executor invocation does not allocate an NPU or include the workflow deployment checks. Use an output directory that does not already exist, and prefer the workflow entry point for acceptance.
To run the accuracy phase with a new output directory, use this command from the repository root. Replace /tmp/npu-accuracy-unique with another unused path if necessary:
python3 -B -u \
test/ci_system/npu/run_phase.py --repo-root "$PWD" --phase accuracy \
--output-dir /tmp/npu-accuracy-unique --timeout-seconds 600A successful run exits with status zero and writes context.json, report.json, and summary.md to the new output directory.
Emit structured events
Each structured event occupies one line: NPU_RESULT_JSON=<JSON object>. Use allow_nan=False and flush output promptly. Common fields are schema_version=1, operator, phase, and event; machine field names and values remain unchanged.
Other lines can contain diagnostics, but must not embed the structured marker. Duplicate keys, NaN/Infinity, out-of-order or missing events, and inconsistent counts fail validation.
For each accuracy run, emit events in this order:
- Emit
startedwithexpected_casesandcase_names. - For each case, emit
case_startedandcase_completed, including the completecase, planned metadata fields, and completionstatus. - Emit
completedwith expected, completed, passed, and failed counts.
For each performance run, emit events in this order:
- Emit
startedwithexpected_configsandconfig_names. - For each configuration, emit
config_startedwith the completeconfig, metadata,warmup,iterations, andexpected_samples. - Emit
sampleevents with a configuration-name string, zero-basedsample_index, and positive finitelatency_ms. - Emit
config_completedwith the sample list, count, median,threshold_ms=null, andperformance_verdict=not_evaluated. - Emit
completedwith expected and completed configuration counts.
On the first failure, emit a terminal failed event and return nonzero. Include completed counts, current_case or current_config, and the original error_type and error. Do not continue to the next case or configuration. Uncaught import or process errors can omit the terminal event; the executor still reports failure.
For field validation and examples, see validate_accuracy and validate_performance in reporting.py and the existing operator scripts.
Validate changes before acceptance
- In the target environment, run the complete
pre-commit run --all-filescommand before committing. - Recheck the plan hashes and sign off the commit.
- Validate operator changes through the ARM NPU workflow.
- For final acceptance, use real Actions runs to demonstrate success, unrelated-change skipping, accuracy failure with performance skipped, and agreement between Actions summaries and VM evidence.
Qwen3 model evaluation
The model workflow in .github/workflows/ascend-npu-model-tests.yml runs the separate test/ci/eval/qwen3-0.6b-evalscope-gsm8k-npu.yaml task on one NPU. The evaluation uses the following settings:
| Setting | Value |
|---|---|
| Model checkpoint | /data/weights/Qwen3-0.6B from the runner's read-only mount |
| Evaluation data | First 100 GSM8K examples, fetched separately |
| Decoding | Greedy, with thinking disabled |
| Concurrent requests | 4 |
| Generation limit | 1,024 tokens |
| Accuracy floor | 0.60 |
| Job timeout | 60 minutes |
The task fails if the checkpoint is absent and does not download model weights. The accuracy floor is a bounded regression check, not a full benchmark result.
The model workflow uses the same repository allowlist, enable variable, and non-draft PR gate as operator CI. It runs for runtime, kernel, and CI changes and on manual dispatch.
Model environment and cache contract
The native engine is installed from the checked-out source. The Python runtime and NPU kernel modules are imported from that same checkout through PYTHONPATH. Installation retains the image's torch, TorchNPU, Triton, Triton-Ascend, and CANN-compatible dependency versions, including protobuf and the pytest version required by Triton-Ascend.
Torchvision uses the matching CPU wheel to avoid CUDA-linked operators in the NPU environment. Installation checks the Transformers model import before serving. The model task keeps the image pytest instead of the runtime project's development-test pin. Its image must provide protobuf compatible with the SMG protocol package. Native engine installation uses the existing engine build helper. The shared CI executor owns server readiness, score checking, process cleanup, and result artifacts. The operator suite and its manifest are unchanged.
Model runner images have the following optional preinstallation and caching behavior:
- Images can preinstall runtime dependencies, Rust, and the engine's declared build requirements and advertise
NPU_CI_PREINSTALLED=1. Images advertising this marker must also provide ccache 4.5 or later. - The model workflow resolves build requirements before computing the existing source/environment wheel key. It restores a matching Actions cache into
RUNNER_TEMPand saves only a successfully imported wheel under that exact key. - The Ascend NPU Model Tests push-to-
mainjob populates the default-branch cache that fork jobs can restore. Fork jobs never save it; their temporary build outputs are discarded with the runner. Shared host wheel caches remain disabled for forks. - On a wheel miss, the model workflow restores job-local compiler caches. CMake's C/C++ compilation, including the scheduler and xgrammar, uses ccache capped at 256 MB.
- Images can additionally provide sccache 0.21.0 at a versioned executable path to cache Rust libraries and dependencies, capped at 512 MB. Older images continue without Rust caching. Rust binaries, dynamic libraries, procedural macros, and build-script executables still compile and link normally.
- A matching build environment can reuse unchanged compilation results across source revisions. Compiler, flags, source, and header checks remain enabled. Checkout paths are normalized for cache lookup, while Rust environment dependencies that embed manifest paths retain their original values in the key. Both caches use the wheel cache's fork isolation and report per-job hits and misses. Each job owns its sccache socket and stops the server before publishing the compiler cache.
- An image can expose a separate EvalScope 1.15.1 environment through
EVALSCOPE_VENV; the model task validates and reuses it. Older images keep the task-local installation path.