Skip to content

Use Ascend ACL Graph Memory Saver ​

Use Memory Saver to release selected physical NPU memory between rollout windows without stopping workers. When workers wake, they retain their original decode graphs and virtual addresses. After all managed allocations on a rank are paused, the worker calls torch.npu.empty_cache() once to release unused allocator cache.

Budget separately for resident executables, HCCL workspaces, and live unmanaged allocations. Measure reclaimed memory with driver free-memory readings because virtual reservation counters can stay high.

Before you start ​

The primary baseline is single-host Atlas A2 (Ascend 910B3), Linux aarch64, Python 3.12, PyTorch 2.9.0+cpu, PTA 2.9.0-730 plus exactly six official backports, and CANN/HCCL 9.0.0. No additional PTA patches or system-library replacements are required.

The July 30 PTA base is 9d40ac3a2b3714df7e5d164bda28a42eff3282cd. Build its wheel for the deployment's Python, PyTorch C++ ABI, and CANN from the public PTA backport branch or pinned snapshot 74e6508b896f630e5d5cacd39a3877047e91c19a. That snapshot and tested build ee1742b06d2c0e59cb0b357288ec29ee190cfd2d have identical source tree 546ac928ce6199c1e2f221d7f5279b4eef6713a8; the reported commit can be either checkout identity.

The primary baseline requires the following backports:

Required backportBehavior
!39221MemPool allocation/lifetime handling
!45270Preserve allocator ownership during pool capture
!30625Normal ProcessGroupHCCL shutdown
!32154Stream synchronization during HCCL shutdown
!32564Multi-stream capture task-queue ordering
!38431Remove HCCL pending-event wait during capture

Stock, unpatched TorchNPU 2.13.0 already contains these changes. It passed an earlier single-host A2 compatibility run with CANN 9.0.0; its official pairing is CANN 9.2.0. This route has not been rerun for the current integration. To reproduce that historical route, use a separate environment and the official TorchNPU compatibility matrix.

Install ​

Install the runtime in a dedicated virtual environment. The primary environment used torch==2.9.0+cpu, torch-npu==2.9.0+gitee1742b, and torchvision==0.24.0.

  1. Install the matching PyTorch, PTA, and TorchVision packages in the dedicated virtual environment.

  2. Preserve those package versions during subsequent installation by generating metadata-derived constraints without importing a device module:

    bash
    export PIP_CONSTRAINT="$(mktemp)"
    python - <<'PYVERSIONS' > "$PIP_CONSTRAINT"
    from importlib.metadata import version
    for name in ("torch", "torch-npu", "torchvision"):
        print(f"{name}=={version(name)}")
    PYVERSIONS

    The file at $PIP_CONSTRAINT contains one exact == version constraint for each of the three packages.

  3. From the root of one TokenSpeed checkout, build the runtime, kernels, and native host. Use the matching SMG gateway to supply HTTP control. These commands target the older primary stack separately from the prepared model-CI environment. If your CANN 9.0.0 toolkit uses a different installation path, replace TOKENSPEED_CANN_ROOT with that path:

    bash
    export TOKENSPEED_CANN_ROOT=/usr/local/Ascend/cann-9.0.0
    source "$TOKENSPEED_CANN_ROOT/set_env.sh"
    python -m pip install --timeout 600 \
      'apache-tvm-ffi==0.1.13.post3' 'transformers==5.12.0' 'triton-ascend==3.2.1' \
      --extra-index-url https://mirrors.huaweicloud.com/ascend/repos/pypi
    python -m pip install --no-deps -e ./tokenspeed-kernel-npu
    PYTHONPATH="$PWD/python:$PWD/tokenspeed-kernel/python:$PWD/tokenspeed-kernel-npu/python${PYTHONPATH:+:$PYTHONPATH}" \
      python test/ci_system/verify_triton_ascend.py
    
    TOKENSPEED_KERNEL_BACKEND=npu python -m pip install \
      -e ./tokenspeed-kernel/python ./tokenspeed-engine -e ./python
    export TORCH_DEVICE_BACKEND_AUTOLOAD=1
    export PYTORCH_NPU_ALLOC_CONF=expandable_segments:False
    export TORCH_HCCL_ZERO_COPY=0
    export TASK_QUEUE_ENABLE=1 ASCEND_LAUNCH_BLOCKING=0

    Confirm that verify_triton_ascend.py exits successfully before you start the server.

  4. Install torch-npu-memory-saver==0.1.7 (allocator ABI 5). The NPU installation builds the PyPI source package against the active CANN toolkit. CPython 3.12 and Linux AArch64 workers on the tested A2 CANN 9.0.0 stack can instead install the prebuilt torch-npu-memory-saver wheel first.

  5. Optional: To use expandable segments during ordinary prefill, set PYTORCH_NPU_ALLOC_CONF=expandable_segments:True before startup. Saver-managed allocations and graph capture temporarily disable expansion.

Ascend requires protocol 3 and matching host and runtime modules. The server rejects an older host before model initialization. NPU exit protection is automatic, including when Memory Saver is disabled.

Keep backend autoload enabled. Leave PYTORCH_NO_NPU_MEMORY_CACHING unset or set it to 0; bypassing the caching allocator bypasses managed pools and is rejected. PTA must provide NPUPluggableAllocator, MemPool, use_mem_pool, and user-pool ACL capture with preserved ownership. Startup checks these APIs and verifies parameter, KV, and graph backing against live native VMM segments. Views can share segments; eager serving needs no graph pool, and captured pools can be allocation-free. Qualify other PTA and CANN builds separately.

Configure and launch Memory Saver ​

Memory saving is opt-in and requires an explicit weight policy:

  • cpu_backup restores original parameters.
  • discard avoids their host copy and requires complete replacement before generation.

Memory tags and policies ​

Select policies for the following memory tags:

TagPolicy
weightsParameters follow the explicit weight policy. Forward inputs, model runtime state, and model workspaces use a separate CPU-backed pool under this tag.
kv_cacheWith target weights on cpu_backup, back up shared target and draft KV and keep the prefix index. A weight update invalidates the old prefix even when its version string is reused. With target weights on discard, drop KV and clear it on wake.
acl_graphThe default --acl-graph-memory-policy discard releases temporaries that replay overwrites. Select cpu_backup to restore their bytes from host memory. Both retain the executable and virtual addresses. Releasing this tag also suspends KV. KV can wake and service page operations while the graph is still asleep. The immutable cache layout stays in the runtime allocator.

Persistent backup consumes pinned host memory and adds transfer time. HCCL communicators and their workspaces stay resident. On Atlas A3, the saver uses the node-local HCCL group to register managed memory when there are multiple local ranks. The library deactivates and reactivates that backing as the existing memory tags pause and resume. This path requires the HCCL VMM registration API.

Start the server ​

Prepare a complete local dense BF16 Qwen3 checkpoint. The following example uses the discard weight policy.

  1. Set CHECKPOINT_A to the path of the complete local checkpoint.

  2. Start TokenSpeed with Memory Saver enabled:

    bash
    tokenspeed serve "$CHECKPOINT_A" \
      --host 127.0.0.1 --port 8000 --enable-rl \
      --device npu --tensor-parallel-size 1 --dtype bfloat16 \
      --attention-backend mha --sampling-backend greedy \
      --disable-prefill-graph --disable-pdl \
      --max-model-len 4096 --max-num-seqs 4 --max-total-tokens 16384 \
      --cudagraph-capture-sizes 1 4 \
      --enable-memory-saver --weight-memory-policy discard
  3. Verify that startup completes without allocator, protocol, or backing-store errors. The startup checks must find the required PTA APIs and verify parameter, KV, and graph backing against live native VMM segments.

The workers stay alive with their original decode graphs and virtual addresses when you later release and restore managed memory.

Update a checkpoint ​

Send control calls through SMG's /v1/rl gateway or the headless message transport. Each replica frontend relays the calls to its TP ranks. Wait for each call's successful result on every serving replica before advancing; HTTP success alone is insufficient. For coordination requirements, see the memory transition protocol section of this document.

The following procedure updates checkpoint A to checkpoint B with the discard weight policy. Prepare an immutable checkpoint B of the same architecture at a path visible to every worker.

  1. Stop rollout submission.

  2. In a shell on the control client, define a helper for the control calls. Replace the base URL if your SMG gateway uses a different address:

    bash
    base=http://127.0.0.1:8000/v1/rl
    rl() {
      curl --fail-with-body -sS -H 'Content-Type: application/json' \
        -d "$2" "$base/$1"
    }
  3. Drain the server and release KV, weights, and graph memory:

    bash
    rl release_memory_occupation '{"tags":["kv_cache","weights","acl_graph"]}'

    A successful result on every replica confirms that all participating TP ranks completed the device transition. The selected physical memory is now released, while the workers and HCCL communicators stay resident.

  4. Train and publish checkpoint B. Before restoring serving, free the trainer's device allocations. Do not modify the checkpoint files during the subsequent reload.

  5. Restore weight and graph mappings while keeping KV asleep:

    bash
    rl resume_memory_occupation '{"tags":["weights","acl_graph"]}'

    The successful result confirms that the mappings are restored. Discarded parameters are not valid until the new checkpoint is committed.

  6. Load the complete new target and commit it on every rank. Replace /path/to/checkpoint-b with the path to checkpoint B and step-42 with its weight version:

    bash
    rl update_weights_from_disk \
      '{"model_path":"/path/to/checkpoint-b","load_format":"auto","weight_version":"step-42","flush_cache":true}'

    Ascend updates require flush_cache=true, which clears L1 and L2 and deletes the old L3 namespace before parameter writes. The discard policy requires a complete checkpoint and a model loading contract that can verify complete replacement. For Qwen3, the disk loader ignores stored rotary frequencies and a head on a rank that does not own it. Every required local tensor must still arrive once. File selection and loading follow the existing checkpoint loader; Memory Saver does not introduce another format allowlist.

    Wait for a successful update result everywhere before waking KV. A successful result confirms that all ranks committed the update.

  7. Clear and wake KV, wait for success on every replica, and then resume rollouts:

    bash
    rl resume_memory_occupation '{"tags":["kv_cache"]}'

    The successful result confirms that all participating ranks completed the device transition. With discard, always wake the explicit tags in this order so that KV cannot precede the newly committed weights.

With cpu_backup, omit the update when keeping the original weights, or supply a partial disk checkpoint or SDK update to replace selected weights. All target weight allocations are backed up and restored; weights omitted from the update keep their restored values. Partial reloads use the same general loader as CUDA and retain the partial disk update limits. Device KV still rebuilds; same-weight host prefixes remain reusable until an update flushes them.

Recover from a failed transition ​

Keep rollout submission stopped until every replica reports success. A refusal before device or update work does not change mappings, so you can retry the operation in the correct order. The following failures require different recovery actions:

FailureRecovery
Device transition failure or failed allocation rollbackRestart the affected worker.
Load failure after a weight transaction beginsRestart the affected worker.
Device-apply or post-readiness L1-clear failureRestart every affected worker before training or serving resumes.
Missing participants cause the 30-second queue-head timeoutCollect the continue_generation reply and every outstanding memory reply before retrying.

continue_generation cancels the whole observed pending batch before device work and leaves already released memory asleep. If participants are missing, the timeout refuses that whole observed batch while no earlier release is draining. Late deliveries can reply later. Continue success alone does not fence earlier fanout.

A partial transition failure keeps the replica unavailable.

Memory transition protocol ​

The native host and Python runtime negotiate the following control guarantees:

ProtocolMeaning
WEIGHT_UPDATE_PROTOCOL (v2)Weight-load preflight, result agreement, and commit. Memory operations use the usual drain and synchronization.
WEIGHT_UPDATE_WITH_MEMORY_TRANSITIONS_PROTOCOL (v3)Adds agreement on release and resume direction, tags, and transition ID; readiness and drain checks; and device-completion acknowledgements from all participating ranks.

The Ascend saver selects v3. CUDA, ROCm, and disabled savers use v2. Within an Ascend serving instance, ranks agree on the selected version over Gloo before saver-specific HCCL setup. Both versions exchange ordinary address strings when the native mesh starts.

Send each participating ingress the same direction, canonical tags, and optional single-string transition_id. Direct-wire clients use the same field and can assign rid independently for each request. Use a fresh ID for each operation, or omit it for ordered calls. Success waits for every TP rank's device completion. A pre-device refusal changes no mappings. HCCL stays resident, and the server rejects communication release tags before any memory is released.

Partial disk update limits ​

Safetensors preflight compares overlapping names with held checkpoint headers; binary sources lack equivalent preflight. The shared loader does not validate every global source shape before TP slicing or agree supplied inventories across ranks. Strengthening these checks remains outside this change under issue #3456.

Model Updater SDK ​

To update weights through the Model Updater SDK instead of disk, use the following alternative procedure:

  1. Install an Ascend-capable provider in every worker. The provider must supply ready CPU or local-NPU tensors and retain their storage until copies finish.

  2. Set all four flags explicitly:

    FlagValue
    --model-update-configProvider configuration JSON object
    --model-update-sdk-moduleInstalled provider import path
    --model-update-engine-typeProvider's engine type
    --model-update-draft-weightsretain for frozen independent drafts; refresh for eligible complete target and draft replacement in one version
  3. Replace step 6 of the checkpoint-cycle procedure with the following call. Replace 42 with the committed checkpoint version:

    bash
    rl update_weights_from_mooncake '{"version":42,"flush_cache":true}'

    Optional snapshot carries publication metadata. With flush, the version string becomes the cache namespace unless weight_version overrides it. Wait for a successful update result on every replica before waking KV.

Disk reload replaces only the target. Under cpu_backup, independent draft weights keep their restored values even when the SDK policy is refresh. Under discard, a target-only disk reload is refused if the independent draft also needs replacement. SDK refresh must publish both independent models together; the target updates shared tensors.

Send full-shaped HF tensors for each rank's required names in the provider's target-first model order. Loaders perform rank-local slicing and fusion and validate each model's inventory before the all-rank commit. For provider and request fields, see Mooncake weight updates.

Verify memory release and token restoration ​

Use driver free-memory readings to verify reclamation. Compare readings before release, after a successful release, and after resume. Account for resident executables, HCCL workspaces, and live unmanaged allocations separately. Do not use virtual reservation counters as the reclaimed-memory measurement because they can stay high.

For token-level restoration checks, match the actual per-rank execution batches, not just the client request list. The wire driver submits requests individually, so admission can split the same list differently before and after resume.

  1. Use the existing scheduler pause and resume controls to queue each complete batch.
  2. Record the actual execution shapes on every rank before release.
  3. After resume, queue the same complete batch and verify its execution shapes.
  4. Compare the first restored output for the matching per-rank execution batch.

Validation coverage and limitations ​

  • The shared L2 pool registers device KV once for RDMA. TokenSpeed rejects --shared-l2-config with --enable-memory-saver for either weight policy.
  • Memory Saver adds no model, attention, sampling, or speculative-algorithm allowlist. Actual execution support remains with the existing runtime and kernels. Weight discard requires the existing complete-replacement and preserved-state contract; cpu_backup does not require that contract.
  • Hardware qualification has covered single-host A2 TP1, TP2, TP4, and TP8. Dense BF16 Qwen3 and selected speculative configurations are test coverage, not startup eligibility. Other configurations, especially cross-host layouts, require their own qualification; removing a Saver gate does not implement a kernel.
  • For fixed-width speculative verification, check the installed attention backend's query-width support. The upstream native Ascend paged MHA decode supports one query per request. Earlier multi-token MTP graph results used separate attention and RoPE changes.
  • Complete target and draft SDK refresh used a synthetic Qwen3 MTP draft and test provider. Real TCP with CPU staging covered local TP2 and remote publisher/TP1; production providers, RDMA, and native draft refresh require qualification.

On the primary PTA and CANN baseline, BF16 Qwen3 TP4 and TP8 passed eight controlled restoration cycles with the token-level restoration procedure. Different admission groups reproduced the previously differing tokens with Saver disabled. These diagnostic runs used HCCL_DETERMINISTIC=true; they do not establish batch-independent logits or production throughput.

For implementation details, see the Ascend ACL Graph Memory Saver design invariants.

TokenSpeed documentation