Skip to content

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.6B checkpoint 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:

  1. From the repository home page, open the Variables page under Settings, Secrets and variables, and Actions.

  2. Configure the required repository variables described in the following table:

    VariablePurpose
    TOKENSPEED_NPU_CI_REPOSITORYSet the full owner/repository value for forks. The official lightseekorg/tokenspeed repository is already on the allowlist.
    TOKENSPEED_NPU_ARM_CI_ENABLEDIn other allowed repositories, set to true only after deployment requirements are met. Leave unset to disable hardware jobs. Upstream does not require this variable.
  3. Open an Ascend NPU Tests run and confirm that the select job completes. A matching change must produce should_run=true before 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_request events targeting main, and workflow_dispatch trigger the workflow.
  • Supported PR events are opened, synchronize, reopened, and ready_for_review. Draft PRs do not start the NPU job.
  • The independent pr-test-npu-arm concurrency 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>/files with 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-zero before fails selection instead of guessing missing changes.
  • Manual runs: Select the full suite without an API file request.
  • Renames: Check both filename and previous_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:

ComponentResponsibility
test/ci_system/npu/changes.pyValidates the manifest and event identity, and then selects relevant changes.
test/ci/npu/manifest.jsonUses schema version 3 to define watched paths, operator order, one script path per operator, and expected counts.
test/ci/npu/expected-plans.jsonRetains schema version 2 and records accuracy cases, performance configurations, sampling parameters, and associated hashes.
test/ci_system/npu/run_step.shChecks ARM/Linux and the checkout identity, and then prepares per-run caches.
test/ci_system/npu/run_phase.pyRuns one phase in order, supervises child processes and timeouts, saves evidence, and returns an exit code.
test/ci_system/npu/reporting.pyValidates structured logs and generates JSON reports and English Markdown summaries.
test/ci/npu/tests/<operator>-test.pyCombines numerical checks and performance sampling in one script with a required --mode argument.
test/ci/npu/operator_cli.pyParses 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:

  1. Run the accuracy phase for every operator with bash test/ci_system/npu/run_step.sh accuracy "$NPU_CI_WORK".
  2. 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:

OperatorAccuracy casesPerformance configurationsPerformance samples
scatter5630
virtual_slots_to_local48840

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 ​

  1. 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.
  2. Assign tokenspeed-npu-arm64-{1,2,4,8}npu labels with the corresponding exclusive device allocation. The operator task selects tokenspeed-npu-arm64-1npu; it does not duplicate its single-device cases across the larger allocations.
  3. Provide Python, PyYAML, PyTorch, TorchNPU, Triton Ascend, and a compatible CANN environment on PATH in the runner image before the runner starts. Model runner images have additional requirements in Qwen3 model evaluation.
  4. 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.
  5. Provide an exclusive NPU allocation for the entire job and account for workloads outside its scheduler. Do not use unreserved host devices.
  6. 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.
  7. 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:

LocationContents
Each phase directorycontext.json, report.json, and summary.md.
Each operator directoryRaw 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 ​

  1. Update the operator script and its test plan.
  2. Synchronize parameters, ordering, counts, and script hashes in expected-plans.json.
  3. Synchronize the manifest and script hashes.
  4. Validate the changes through the ARM NPU workflow.

Add an operator ​

  1. Create test/ci/npu/tests/<name>-test.py.
  2. In the manifest's operators list, register its name, a single script field pointing to that canonical path, and its counts. Schema version 3 rejects the former per-phase scripts mapping.
  3. Add its accuracy plan, performance plan, and timing parameters to expected-plans.json. The expected plan retains schema version 2 and has one source_sha256 entry for each registered script.
  4. 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.
  5. Use the shared CLI with two callbacks that return integer exit codes. all calls 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.
  6. Update watch_paths for new source dependencies. Do not add operator-name branches to the common executor or additional workflow steps.
  7. 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:

bash
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')
PY

A 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.

  1. From the repository root, set PYTHONPATH and choose an explicit mode. The following example lists the three supported invocations for scatter; replace tests/scatter-test.py with tests/virtual_slots_to_local-test.py to test the other operator:

    bash
    export 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 all

    There is no default mode. all performs accuracy and then performance for that operator, preserving distinct phase=accuracy and phase=performance structured events. Any accuracy failure prevents performance from starting.

  2. Confirm that the selected command exits with status zero and emits a completed event for each requested phase. For --mode all, verify that the accuracy completed event appears before the performance started event.

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:

bash
python3 -B -u \
  test/ci_system/npu/run_phase.py --repo-root "$PWD" --phase accuracy \
  --output-dir /tmp/npu-accuracy-unique --timeout-seconds 600

A 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:

  1. Emit started with expected_cases and case_names.
  2. For each case, emit case_started and case_completed, including the complete case, planned metadata fields, and completion status.
  3. Emit completed with expected, completed, passed, and failed counts.

For each performance run, emit events in this order:

  1. Emit started with expected_configs and config_names.
  2. For each configuration, emit config_started with the complete config, metadata, warmup, iterations, and expected_samples.
  3. Emit sample events with a configuration-name string, zero-based sample_index, and positive finite latency_ms.
  4. Emit config_completed with the sample list, count, median, threshold_ms=null, and performance_verdict=not_evaluated.
  5. Emit completed with 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 ​

  1. In the target environment, run the complete pre-commit run --all-files command before committing.
  2. Recheck the plan hashes and sign off the commit.
  3. Validate operator changes through the ARM NPU workflow.
  4. 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:

SettingValue
Model checkpoint/data/weights/Qwen3-0.6B from the runner's read-only mount
Evaluation dataFirst 100 GSM8K examples, fetched separately
DecodingGreedy, with thinking disabled
Concurrent requests4
Generation limit1,024 tokens
Accuracy floor0.60
Job timeout60 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_TEMP and saves only a successfully imported wheel under that exact key.
  • The Ascend NPU Model Tests push-to-main job 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.

TokenSpeed documentation