Skip to Content
MS-SWIFT ร— TWINKLE
๐Ÿ’ป Hardware Platforms
DOCUMENTATION5.0.0.dev

๐Ÿ”๏ธ Ascend NPU Support

We have added Ascend NPU support to ms-swift, so users can fine-tune and run inference with models on Ascend NPUs.

This document describes how to complete environment preparation, model training, saving and merging, inference, deployment and troubleshooting on Ascend NPUs.

When using ms-swift on an NPU for the first time, reading in the following order is recommended:

  1. Start with "Support at a glance" to confirm whether the model, algorithm and backend have been verified.
  2. Decide from "Choose a route" whether to install only the base environment, or to additionally install Megatron/MegatronAdaptor/TransformerEngineNPU.
  3. Depending on how the environment is managed, choose "Local environment installation" or "Image/container environment installation", then run the "NPU availability check".
  4. Follow "Quick verification" to complete one round of ModelScope model LoRA training, merging, inference and deployment.
  5. Read the DDP, DeepSpeed and Megatron sections when larger-scale training is needed.

๐Ÿงฐ Hardware and supported operating systems

Table 1 Product hardware support list

ProductSupported
Ascend 950 series productsโˆš
Atlas A3 training series productsโˆš
Atlas A3 inference series productsx
Atlas A2 training series productsโˆš
Atlas A2 inference series productsx
Atlas 200I/500 A2 inference productsx
Atlas inference series productsx
Atlas training series productsx

Note: in the table of this section, "โˆš" means supported and "x" means not supported.

โœ… Support at a glance

Recommended base environment versions:

softwareversion
Python>= 3.10, < 3.12
CANN>= 8.5.1
torch>= 2.7.1
torch_npu>= 2.7.1.post4

For base environment preparation see the Ascend PyTorch installation documentation. The example environment in this page is 8 * Ascend 910B3 64G. vLLM-Ascend must be installed together with CANN, torch and torch_npu according to the full compatibility matrix; see the vLLM-Ascend 0.23.0 installation documentation for details.

CategoryFeatureStatus
Training paradigmCPTSupported
SFTSupported
DPOSupported
RMSupported
DistributedDDPSupported
FSDPSupported
FSDP2Supported
DeepSpeedSupported
Megatron (MCore 0.18 + MegatronAdaptor)Supported
Low-parameter fine-tuningFULLSupported
LoRASupported
QLoRANot yet supported
RLHFGRPOSupported
PPOSupported
Performance optimizationFA and other fused operatorsSupported
Liger-KernelNot yet supported
DeploymentPTSupported
vLLMSupported
SGLangNot yet supported

โœ… Verified SFT combinations

algorithmmodel familiesstrategyhardware
SFTQwen2.5-0.5B-InstructFSDP1/FSDP2/deepspeedAtlas 900 A2 PODc
SFTQwen2.5-1.5B-InstructFSDP1/FSDP2/deepspeedAtlas 900 A2 PODc
SFTQwen2.5-7B-InstructFSDP1/FSDP2/deepspeedAtlas 900 A2 PODc
SFTQwen2.5-VL-3B-InstructFSDP1/FSDP2/deepspeedAtlas 900 A2 PODc
SFTQwen2.5-VL-7B-InstructFSDP1/FSDP2/deepspeedAtlas 900 A2 PODc
SFTQwen2.5-Omni-3BFSDP1/FSDP2/deepspeedAtlas 900 A2 PODc
SFTQwen3-8BFSDP1/FSDP2/deepspeedAtlas 900 A2 PODc
SFTQwen3-30B-A3BFSDP1/FSDP2/deepspeedAtlas 900 A2 PODc
SFTQwen3-32BFSDP1/FSDP2/deepspeedAtlas 900 A2 PODc
SFTQwen3-VL-30B-A3B-InstructFSDP1/FSDP2/deepspeedAtlas 900 A2 PODc
SFTQwen3-Omni-30B-A3B-InstructFSDP1/FSDP2/deepspeed/MegatronAtlas 900 A2 PODc/A3 SuperPoD
SFTInternVL3-8BFSDP1/FSDP2/deepspeedAtlas 900 A2 PODc
SFTOvis2.5-2BFSDP1/FSDP2/deepspeedAtlas 900 A2 PODc
SFTQwen3.5-27BFSDP1/FSDP2/deepspeed/MegatronAtlas 900 A2 PODc/A3 SuperPoD
SFTQwen3.5-35B-A3BFSDP1/FSDP2/deepspeed/MegatronAtlas 900 A2 PODc/A3 SuperPoD

โœ… Verified RL combinations

algorithmmodel familiesstrategyrollout enginehardware
GRPOQwen2.5-7B-Instructdeepspeedvllm-ascendAtlas 900 A2 PODc
GRPOQwen3-8Bdeepspeedvllm-ascendAtlas 900 A2 PODc
DPOQwen2.5-7B-Instructdeepspeedvllm-ascendAtlas 900 A2 PODc
DPOQwen3-8Bdeepspeedvllm-ascendAtlas 900 A2 PODc
PPOQwen2.5-7B-Instructdeepspeedvllm-ascendAtlas 900 A2 PODc
PPOQwen3-8Bdeepspeedvllm-ascendAtlas 900 A2 PODc

โš ๏ธ Not yet supported or not fully verified

item
Liger-kernel
Quantization/QLoRA
Using sglang as the inference engine
LoRA training with ETP enabled under Megatron

โš ๏ธ PEFT Transformers 5 MoE fused expert LoRA limitation

When running LoRA training on Transformers 5 MoE models such as Qwen3.5-MoE and Qwen3-Omni-MoE, some expert weights may not be plain nn.Linear modules but fused nn.Parameters. These parameters need PEFT's target_parameters path to inject LoRA.

This path is not yet fully stable in combinations such as lora_dropout, ZeRO-3/FSDP and multiple adapters. Typical trigger conditions include:

  • Using an MoE model;
  • Using LoRA and wanting to cover the fused expert parameters;
  • The model configuration or the command-line --model_type triggering PEFT's Transformers 5 MoE target conversion path;
  • Using the default lora_dropout != 0, or using a parameter-sharding backend such as ZeRO-3/FSDP.

For ordinary Qwen3.5 GRPO/SFT LoRA training, avoid additionally specifying --model_type to widen the trigger range. If the model configuration already triggers this path, prefer full-parameter training or disable the corresponding LoRA combination. If training the fused expert parameters is really needed, wait for the upstream PEFT capability to stabilize, or use it only when lora_dropout=0 and the target model and training backend have been verified separately.

๐Ÿ“„ Choose a route

ScenarioRecommended routeMegatronAdaptor needed
Only ordinary SFT/LoRA/inferenceLocal environment installation or image/container environment installationNo
Megatron training of large modelsInstall the base environment first, then MCore 0.18, MegatronAdaptor, TransformerEngineNPU and mcore-bridgeYes
GRPO/PPO/DPO and other RLHFBase training environment + vLLM-Ascend rollout/deployUsually not needed
Only checking whether the NPU is availableRun the NPU availability check scriptNo

๐Ÿงฐ Environment preparation

๐Ÿ“ฆ Image/container environment installation

The official NPU image is published at quay.io/ascend/ms-swift. Picking a matching image tag by device generation, Python, CANN and system version is recommended first. To pin a branch or customize dependencies, build the image yourself with the Dockerfile provided by the project. The advantage of the container approach is that dependency versions are easier to pin, and the experimental environment is easier to reproduce across several Ascend machines.

The following uses the A2, Python 3.11, CANN 9.0.0, Ubuntu 22.04 tag as an example. In actual use, follow the latest tag on the Quay tags page that matches the current machine and software stack:

docker pull quay.io/ascend/ms-swift:5.0.0-A2-py311-CANN9.0.0-ubuntu22.04
export IMAGE_NAME=quay.io/ascend/ms-swift:5.0.0-A2-py311-CANN9.0.0-ubuntu22.04
export WORKSPACE=/path/to/workspace

To build the image yourself, first clone the modelscope repository, then use Dockerfile.ascend and build_image.py in the repository:

git clone https://github.com/modelscope/modelscope.git
cd modelscope
DOCKER_REGISTRY=ms-swift python docker/build_image.py \
  --image_type ascend \
  --python_version 3.11.11 \
  --soc_version ascend910b1 \
  --arch arm

The Ascend image name generated by build_image.py currently has the format {DOCKER_REGISTRY}:{swift_branch}-{atlas_hardware}-{python_tag}-{arch}. The command above takes the ARM Atlas 900 A2 PODc as an example and usually generates ms-swift:main-A2-py311-arm. If you use a self-built image, replace IMAGE_NAME above with the image name in the build log:

export IMAGE_NAME=ms-swift:main-A2-py311-arm

The image already contains ms-swift, twinkle and twinkle-server, so they do not need to be installed separately inside the container. Upgrade to a new version inside the container with pip install -U ms-swift.

Before starting the container, confirm the NPU devices exposed by the host:

ls /dev/davinci*

When starting the container, the NPU devices, driver, firmware, npu-smi and the necessary log directories must be mounted into it. The example below is written for the common 8-card devices davinci0 through davinci7. Some machines expose up to davinci15 as well; in that case, add all the corresponding devices to docker run according to the output of ls /dev/davinci*:

docker run -it \
  --name swift-ascend \
  --network=host --ipc=host --shm-size=128g \
  --device=/dev/davinci0 --device=/dev/davinci1 \
  --device=/dev/davinci2 --device=/dev/davinci3 \
  --device=/dev/davinci4 --device=/dev/davinci5 \
  --device=/dev/davinci6 --device=/dev/davinci7 \
  --device=/dev/davinci_manager --device=/dev/devmm_svm --device=/dev/hisi_hdc \
  -v /usr/local/Ascend/driver:/usr/local/Ascend/driver:ro \
  -v /usr/local/Ascend/firmware:/usr/local/Ascend/firmware:ro \
  -v /usr/local/sbin/npu-smi:/usr/local/sbin/npu-smi:ro \
  -v /etc/ascend_install.info:/etc/ascend_install.info:ro \
  -v /var/log/npu:/var/log/npu \
  -v ${WORKSPACE}:/workspace \
  ${IMAGE_NAME} \
  /bin/bash

After entering the container, run source /usr/local/Ascend/ascend-toolkit/set_env.sh first, then run the NPU availability check script below to confirm that the Ascend devices can be accessed correctly inside the container. If the NPU is not recognized inside the container, check first whether /dev/davinci*, /dev/davinci_manager, the driver directory and npu-smi are mounted correctly.

๐Ÿ“ฆ Local environment installation

Step 1: prepare the environment

# create a new conda virtual environment (optional)
conda create -n swift-npu python=3.12 -y
conda activate swift-npu

# note: source the CANN environment before continuing
source /usr/local/Ascend/ascend-toolkit/set_env.sh

# set the global pip mirror (optional, speeds up downloads)
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/

Step 2: install ms-swift (choose one of the following two methods)

Choose method A for ordinary use. Choose method B when the latest code on the main branch is needed or the source is to be modified. After running one of them, go directly to step 3; do not run the other.

Method A: install the PyPI release (recommended for ordinary use)

pip install ms-swift -U

Method B: install from source

git clone https://github.com/modelscope/ms-swift.git
cd ms-swift
pip install -e .

Step 3: install the runtime and optional components as needed

# install the matching PyTorch/TorchNPU runtime
pip install torch==2.10.0 torchvision==0.25.0 torchaudio==2.10.0
pip install torch_npu==2.10.0.post4 decorator \
  --extra-index-url https://mirrors.huaweicloud.com/ascend/repos/pypi
# when using deepspeed (controls memory usage; training speed drops somewhat)
pip install deepspeed

# install the following packages to use the evaluation feature
pip install evalscope[opencompass]

# install the following packages to use vllm-ascend for inference (see the [vLLM-Ascend website](https://docs.vllm.ai/projects/ascend/en/latest/installation.html) for more versions)
pip install vllm==0.23.0
pip install vllm-ascend==0.23.0 \
  --extra-index-url https://mirrors.huaweicloud.com/ascend/repos/pypi/variant \
  --extra-index-url https://mirrors.huaweicloud.com/ascend/repos/pypi

๐Ÿ” Environment self-check

Before training, run the following from the repository root with the Python environment used for training:

python examples/ascend/check_env.py

The script prints tables in four groups: base environment, software components, Ascend installation information and NPU status. The software components include PyTorch, torch-npu, ms-swift, Megatron Core, MindSpeed, mcore-bridge and triton-ascend, and each component that is not detected is reported item by item. The Note column shows the component installation location, the Python interpreter path, or the directory of the driver/CANN version file; long paths wrap automatically. When device information is collected, the status table from npu-smi is attached.

FOUND means the information was obtained, MISSING means the package metadata or tool was not found, UNKNOWN means the version or device information could not be determined, and UNAVAILABLE means the query failed. A missing optional component does not mean the base training environment is unusable, and an unknown version does not mean the component is not installed. The script does not judge compatibility, does not initialize Megatron and does not run NPU computation; a failure in one item does not interrupt the report. The availability check below can be run as needed.

triton-ascend is queried by its distribution metadata; the version of plain triton is not used as a substitute.

๐Ÿ” NPU availability check

Check that the environment is installed correctly and the NPU can be loaded:

from transformers.utils import is_torch_npu_available
import torch

print(is_torch_npu_available())  # True
print(torch.npu.device_count())  # 8
print(torch.randn(10, device='npu:0'))

๐Ÿ“ฆ Optional installation of MegatronAdaptor + TransformerEngineNPU

The NPU Megatron path uses MCore 0.18, MegatronAdaptor, TransformerEngineNPU and mcore-bridge, and does not install or import MindSpeed. The installation example below uses Python 3.12, CANN 9.1 beta and torch/torch_npu 2.10.

This section builds on the ms-swift and PyTorch/TorchNPU environment installed above and only adds the components needed for Megatron training.

The repositories below are all placed under ~/swift-npu. When using another directory, change the paths in the first two commands. If a source directory already exists, skip the corresponding clone command and run git checkout <branch name> inside that repository. Before using the commands in this section, the accompanying mcore-bridge PR #189 must be merged into the official main branch.

mkdir -p ~/swift-npu
cd ~/swift-npu

# 1. Install mcore-bridge from the official main branch.
git clone https://github.com/modelscope/mcore-bridge.git
cd mcore-bridge
git checkout main
pip install -e .
cd ..

# 2. Install MegatronAdaptor and TransformerEngineNPU.
git clone https://gitcode.com/Ascend/MegatronAdaptor.git
cd MegatronAdaptor
git checkout core_r0.18.0
pip install -e .
cd ..

git clone https://gitcode.com/Ascend/TransformerEngineNPU.git
cd TransformerEngineNPU
git checkout main
pip install -e . --no-build-isolation
cd ..

# 3. Fetch the matching Megatron-LM source and configure the source path.
git clone https://github.com/NVIDIA/Megatron-LM.git
cd Megatron-LM
git checkout core_r0.18.0
cd ..
export MEGATRON_LM_PATH="$(pwd)/Megatron-LM"
export PYTHONPATH="$MEGATRON_LM_PATH:$PYTHONPATH"

The installation commands follow mcore-bridge source installation, the MegatronAdaptor installation guide and the TENPU installation guide. Only TENPU uses --no-build-isolation per the official instructions. For the other prerequisites and version matching, see the official TENPU installation guide.

After the accompanying adaptations are merged, the main branch of the official mcore-bridge provides NPU LoRA LayerNormLinear, GroupedLinear/expert and checkpoint mapping adaptations for TransformerEngineNPU main, without depending on an uncommitted working-tree patch.

The accompanying bridge fix also removes the MindSpeed defaults probe. The admission condition should check both find_spec('mindspeed') is None and that mindspeed is not in sys.modules, and confirm that no MindSpeed reference exists in the bridge runtime code.

When verifying, record the complete command, source SHA, versions, actual topology, logs, exit code, and the pass/framework failure/environment failure/capacity failure classification separately for representative dense, GDN and MoE topologies. A two-step smoke or unit test result cannot serve as the acceptance basis for a long run.

When verifying, check both the source ownership and the absence of MindSpeed. Checking only that import succeeds is not enough to prove that the runtime binding is correct:

python - <<'PY'
import importlib.util
import os
from pathlib import Path
import megatron_adaptor, megatron.core, transformer_engine, mcore_bridge
from swift.megatron.init import init_megatron_env
init_megatron_env()
root = Path(os.environ['MEGATRON_LM_PATH']).expanduser().resolve().parent
for module, directory in (
    (megatron_adaptor, 'MegatronAdaptor'),
    (megatron.core, 'Megatron-LM'),
    (transformer_engine, 'TransformerEngineNPU'),
    (mcore_bridge, 'mcore-bridge'),
):
    source = Path(module.__file__).resolve()
    print(module.__name__, source)
    assert source.is_relative_to((root / directory).resolve()), source
assert importlib.util.find_spec('mindspeed') is None
print('NPU MegatronAdaptor/MCore 0.18 environment verified')
PY

๐Ÿ“„ Qwen3.5 MCore GDN notes

The Megatron NPU path of Qwen3.5 uses the GatedDeltaNet (GDN, gated DeltaNet state space layer) of MCore 0.18 by default. MegatronAdaptor provides the Torch-native causal-conv, GDN and normalization replacements required on NPU. USE_MCORE_GDN still takes effect: set it to 1 to use MCore GDN and to 0 to select transformers GDN. It is a model implementation choice and is unrelated to the 0.18 dependency migration.

Mcore-bridge connects the model parameters and packed/padding-free metadata of Qwen3.5/Omni to MCore. CP (context parallel, parallelism that splits along the sequence dimension) uses the MCore 0.18 implementation. The forward/backward, optimizer, packing, CP and save/resume of dense, GDN and MoE need to be verified separately. A successful environment installation here does not mean long training or performance has been accepted.

โšก Optional acceleration for GDN models: FLA and Triton-Ascend

When training models that contain GDN, such as Qwen3.5, FLA (Flash Linear Attention) and Triton-Ascend can be installed optionally to accelerate GDN operators on supported devices and backends. The Triton-Ascend version must match the existing CANN, PyTorch and TorchNPU environment. If a compatible version is already installed, its installation command can be skipped. For version matching and NPU backend notes see the FLA official installation guide.

cd ~/swift-npu
pip install triton-ascend --extra-index-url=https://triton-ascend.osinfra.cn/pypi/simple

git clone https://github.com/fla-org/flash-linear-attention.git
cd flash-linear-attention
git checkout main
pip install -e .
cd ..

Ascend 950 note: FLA has not yet been adapted to Ascend 950, and compatibility or runtime problems may occur. Verify on the target hardware with the actual training configuration.

๐Ÿ” Viewing the environment

View the P2P connections of the NPUs. The output shows that each NPU is connected to the other NPUs through 7 HCCS links

(valle) root@valle:~/src# npu-smi info -t topo
	   NPU0       NPU1       NPU2       NPU3       NPU4       NPU5       NPU6       NPU7       CPU Affinity
NPU0       X          HCCS       HCCS       HCCS       HCCS       HCCS       HCCS       HCCS       144-167
NPU1       HCCS       X          HCCS       HCCS       HCCS       HCCS       HCCS       HCCS       144-167
NPU2       HCCS       HCCS       X          HCCS       HCCS       HCCS       HCCS       HCCS       96-119
NPU3       HCCS       HCCS       HCCS       X          HCCS       HCCS       HCCS       HCCS       96-119
NPU4       HCCS       HCCS       HCCS       HCCS       X          HCCS       HCCS       HCCS       0-23
NPU5       HCCS       HCCS       HCCS       HCCS       HCCS       X          HCCS       HCCS       0-23
NPU6       HCCS       HCCS       HCCS       HCCS       HCCS       HCCS       X          HCCS       48-71
NPU7       HCCS       HCCS       HCCS       HCCS       HCCS       HCCS       HCCS       X          48-71

Legend:

  X    = Self
  SYS  = Path traversing PCIe and NUMA nodes. Nodes are connected through SMP, such as QPI, UPI.
  PHB  = Path traversing PCIe and the PCIe host bridge of a CPU.
  PIX  = Path traversing a single PCIe switch
  PXB  = Path traversing multiple PCIe switches
  HCCS = Connection traversing HCCS.
  NA   = Unknown relationship.

To view the NPU status, run the command below. For a detailed explanation of the npu-smi command, see the official documentation

(valle) root@valle:~/src# npu-smi info
+------------------------------------------------------------------------------------------------+
| npu-smi 24.1.rc1.b030            Version: 24.1.rc1.b030                                        |
+---------------------------+---------------+----------------------------------------------------+
| NPU   Name                | Health        | Power(W)    Temp(C)           Hugepages-Usage(page)|
| Chip                      | Bus-Id        | AICore(%)   Memory-Usage(MB)  HBM-Usage(MB)        |
+===========================+===============+====================================================+
| 0     910B3               | OK            | 101.8       43                0    / 0             |
| 0                         | 0000:C1:00.0  | 0           0    / 0          3318 / 65536         |
+===========================+===============+====================================================+
| 1     910B3               | OK            | 92.0        39                0    / 0             |
| 0                         | 0000:C2:00.0  | 0           0    / 0          3314 / 65536         |
+===========================+===============+====================================================+
| 2     910B3               | OK            | 102.0       40                0    / 0             |
| 0                         | 0000:81:00.0  | 0           0    / 0          3314 / 65536         |
+===========================+===============+====================================================+
| 3     910B3               | OK            | 99.8        40                0    / 0             |
| 0                         | 0000:82:00.0  | 0           0    / 0          3314 / 65536         |
+===========================+===============+====================================================+
| 4     910B3               | OK            | 98.6        45                0    / 0             |
| 0                         | 0000:01:00.0  | 0           0    / 0          3314 / 65536         |
+===========================+===============+====================================================+
| 5     910B3               | OK            | 99.7        44                0    / 0             |
| 0                         | 0000:02:00.0  | 0           0    / 0          3314 / 65536         |
+===========================+===============+====================================================+
| 6     910B3               | OK            | 103.8       45                0    / 0             |
| 0                         | 0000:41:00.0  | 0           0    / 0          3314 / 65536         |
+===========================+===============+====================================================+
| 7     910B3               | OK            | 98.2        44                0    / 0             |
| 0                         | 0000:42:00.0  | 0           0    / 0          3315 / 65536         |
+===========================+===============+====================================================+

๐Ÿ“š Quick verification: ModelScope model + dataset

To verify the environment with a model and dataset from ModelScope, follow this section to complete one full workflow: train a LoRA, find the latest checkpoint, merge the LoRA, run command-line inference, start a service, and verify with curl. The example uses a small model and a small sample to shorten verification time. To use your own model or dataset, only change the ID variables at the top.

export MODEL_ID=Qwen/Qwen3-0.6B
export DATASET_ID=AI-ModelScope/alpaca-gpt4-data-zh
export WORK_DIR=output/npu-modelscope-qwen3-0_6b-lora

Train and save a LoRA checkpoint:

ASCEND_RT_VISIBLE_DEVICES=0 \
swift sft \
    --model $MODEL_ID \
    --dataset $DATASET_ID#1000 \
    --split_dataset_ratio 0.01 \
    --torch_dtype bfloat16 \
    --tuner lora \
    --target_modules all-linear \
    --lora_rank 8 \
    --lora_alpha 32 \
    --num_train_epochs 1 \
    --per_device_train_batch_size 1 \
    --per_device_eval_batch_size 1 \
    --gradient_accumulation_steps 8 \
    --learning_rate 1e-4 \
    --max_length 2048 \
    --save_steps 100 \
    --eval_steps 100 \
    --save_total_limit 2 \
    --logging_steps 10 \
    --output_dir $WORK_DIR

After training, the checkpoint is saved under $WORK_DIR/*/checkpoint-*. The following command picks the latest checkpoint and merges the LoRA into complete model weights:

export CKPT_DIR=$(ls -dt $WORK_DIR/*/checkpoint-* | head -n 1)

ASCEND_RT_VISIBLE_DEVICES=0 \
swift merge \
    --adapters $CKPT_DIR

export MERGED_DIR=${CKPT_DIR}-merged

Inference verification can load the LoRA checkpoint directly or the merged complete weights:

# load the LoRA checkpoint directly
ASCEND_RT_VISIBLE_DEVICES=0 \
swift infer \
    --adapters $CKPT_DIR \
    --stream true \
    --temperature 0 \
    --max_new_tokens 512

# load the merged complete weights
ASCEND_RT_VISIBLE_DEVICES=0 \
swift infer \
    --model $MERGED_DIR \
    --stream true \
    --temperature 0 \
    --max_new_tokens 512

To start an OpenAI-compatible deployment service, the merged complete weights can be used:

ASCEND_RT_VISIBLE_DEVICES=0 \
swift deploy \
    --model $MERGED_DIR \
    --host 0.0.0.0 \
    --port 8000 \
    --max_new_tokens 512 \
    --served_model_name npu-modelscope-qwen3-0_6b

After the service starts, verify the endpoint with curl:

curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "npu-modelscope-qwen3-0_6b",
"messages": [{"role": "user", "content": "็”จไธ€ๅฅ่ฏไป‹็ปๆ˜‡่…พNPUใ€‚"}],
"max_tokens": 128,
"temperature": 0
}'

๐Ÿ‹๏ธ Training

The following covers LoRA fine-tuning. For full-parameter fine-tuning, set --tuner full. For more training scripts see here. For general capabilities such as pre-training, SFT, LoRA, full-parameter training and custom datasets, see Quick start and Custom datasets.

Model sizeNPU countdeepspeed typeMaximum memory usage
7B1None1 * 28 GB
7B4None4 * 22 GB
7B4zero24 * 28 GB
7B4zero34 * 22 GB
7B8None8 * 22 GB
14B1None1 * 45 GB
14B8None8 * 51 GB
14B8zero28 * 49 GB
14B8zero38 * 31 GB

๐Ÿ‹๏ธ Single-card training

Start single-card fine-tuning with the following command:

# experiment environment: Ascend 910B3
# memory requirement: 28 GB
# run time: 8 hours
ASCEND_RT_VISIBLE_DEVICES=0 \
swift sft \
    --model Qwen/Qwen2-7B-Instruct \
    --dataset AI-ModelScope/blossom-math-v2 \
    --split_dataset_ratio 0.01 \
    --num_train_epochs 5 \
    --tuner lora \
    --output_dir output \
    --learning_rate 1e-4 \
    --gradient_accumulation_steps 16 \
    --save_steps 100 \
    --eval_steps 100

๐Ÿ‹๏ธ Data-parallel training

We use 4 of the cards for ddp training

# experiment environment: 4 * Ascend 910B3
# memory requirement: 4 * 22 GB
# run time: 2 hours
NPROC_PER_NODE=4 \
ASCEND_RT_VISIBLE_DEVICES=0,1,2,3 \
swift sft \
    --model Qwen/Qwen2-7B-Instruct \
    --dataset AI-ModelScope/blossom-math-v2 \
    --split_dataset_ratio 0.01 \
    --num_train_epochs 5 \
    --tuner lora \
    --output_dir output \
    ...

๐Ÿ‹๏ธ DeepSpeed training

ZeRO2:

# experiment environment: 4 * Ascend 910B3
# memory requirement: 4 * 28GB
# run time: 3.5 hours
NPROC_PER_NODE=4 \
ASCEND_RT_VISIBLE_DEVICES=0,1,2,3 \
swift sft \
    --model Qwen/Qwen2-7B-Instruct \
    --dataset AI-ModelScope/blossom-math-v2 \
    --split_dataset_ratio 0.01 \
    --num_train_epochs 5 \
    --tuner lora \
    --output_dir output \
    --deepspeed zero2 \
    ...

ZeRO3:

# experiment environment: 4 * Ascend 910B3
# memory requirement: 4 * 22 GB
# run time: 8.5 hours
NPROC_PER_NODE=4 \
ASCEND_RT_VISIBLE_DEVICES=0,1,2,3 \
swift sft \
    --model Qwen/Qwen2-7B-Instruct \
    --dataset AI-ModelScope/blossom-math-v2 \
    --split_dataset_ratio 0.01 \
    --num_train_epochs 5 \
    --tuner lora \
    --output_dir output \
    --deepspeed zero3 \
    ...

๐Ÿ’ก Qwen3.5 single-node multi-card LoRA example

The following is an NPU LoRA example with a more recent model. The example uses Qwen3.5-4B; 4-card data parallelism is usually faster than a single card. If the model and dataset have been downloaded locally, --model and --dataset can be replaced with local paths.

# experiment environment: 4 * Ascend 910B3
NPROC_PER_NODE=4 \
ASCEND_RT_VISIBLE_DEVICES=0,1,2,3 \
swift sft \
    --model Qwen/Qwen3.5-4B \
    --dataset AI-ModelScope/alpaca-gpt4-data-zh#2000 \
    --split_dataset_ratio 0.01 \
    --torch_dtype bfloat16 \
    --num_train_epochs 1 \
    --tuner lora \
    --target_modules all-linear \
    --lora_rank 8 \
    --lora_alpha 32 \
    --per_device_train_batch_size 1 \
    --per_device_eval_batch_size 1 \
    --gradient_accumulation_steps 8 \
    --learning_rate 1e-4 \
    --max_length 2048 \
    --group_by_length true \
    --dataset_num_proc 4 \
    --dataloader_num_workers 4 \
    --save_steps 100 \
    --eval_steps 100 \
    --save_total_limit 2 \
    --output_dir output/Qwen3.5-4B-NPU

When tuning, focus on three goals: memory, throughput and stability.

  • Lower memory: reduce --max_length, --per_device_train_batch_size and --lora_rank first. Enable --deepspeed zero2/zero3 only if OOM still occurs. ZeRO clearly lowers memory pressure but adds communication and scheduling overhead.
  • Raise throughput: increase --per_device_train_batch_size when memory allows, then use --gradient_accumulation_steps to keep the global batch size. Increase --dataset_num_proc when data preprocessing is slow, and --dataloader_num_workers when data reading becomes the bottleneck.
  • Control save cost: --save_steps should not be too small, or frequent saves slow down training. --save_total_limit 2 is usually enough to keep the best checkpoint and the last checkpoint.
  • Raise stability: on NPU, prefer bfloat16. If the loss is abnormal or NaN appears, lower the learning rate and the batch size first, and temporarily switch to float32 for a controlled comparison if needed.

For the meaning of more arguments see the command-line arguments documentation.

NPU model patch

ms-swift enables a model-layer patch automatically in NPU environments to adapt some Transformers models to the operator and compatibility requirements of Ascend NPUs. The switch follows the platform: it is enabled on NPU and disabled on other hardware, and there is no corresponding command-line argument (the old --enable_npu_model_patch has been removed; an externally set SWIFT_ENABLE_NPU_MODEL_PATCH that does not match the platform is overridden and a warning is printed).

Model saving, Merge LoRA and resuming from a checkpoint

During training, --output_dir specifies the output directory, --save_steps controls the checkpoint save interval, and --save_total_limit controls how many checkpoints are kept at most. After LoRA training, the checkpoint directory contains the adapter weights, the training arguments and the trainer state. A common directory layout:

output/Qwen3.5-4B-NPU/vx-xxx/
โ”œโ”€โ”€ checkpoint-100/
โ”œโ”€โ”€ checkpoint-200/
โ””โ”€โ”€ ...

If you only run inference or continue LoRA training, the checkpoint directory can be used directly. To obtain a standalone complete model directory for vLLM-Ascend deployment, offline distribution or later quantization, run Merge LoRA:

ASCEND_RT_VISIBLE_DEVICES=0 \
swift merge \
    --adapters output/Qwen3.5-4B-NPU/vx-xxx/checkpoint-xxx

The merged model is saved in the checkpoint-xxx-merged directory by default. Afterwards it can be used like an ordinary model with --model checkpoint-xxx-merged.

If training is interrupted and needs to resume from a checkpoint, keep the original training arguments unchanged and only add --resume_from_checkpoint:

NPROC_PER_NODE=4 \
ASCEND_RT_VISIBLE_DEVICES=0,1,2,3 \
swift sft \
    --model Qwen/Qwen3.5-4B \
    --dataset AI-ModelScope/alpaca-gpt4-data-zh#2000 \
    --tuner lora \
    --output_dir output/Qwen3.5-4B-NPU \
    --resume_from_checkpoint output/Qwen3.5-4B-NPU/vx-xxx/checkpoint-xxx \
    ...

--resume_from_checkpoint restores the model weights, optimizer state, random seed and training progress. To load only the model weights without restoring the optimizer and data-skipping state, additionally set --resume_only_model true. For the related arguments see resume_from_checkpoint, resume_only_model, save_steps and save_total_limit in the command-line arguments documentation.

๐Ÿš€ Inference

Original model:

ASCEND_RT_VISIBLE_DEVICES=0 swift infer \
    --model Qwen/Qwen2-7B-Instruct \
    --stream true --max_new_tokens 2048

After LoRA fine-tuning:

ASCEND_RT_VISIBLE_DEVICES=0 swift infer \
    --adapters xxx/checkpoint-xxx --load_data_args true \
    --stream true --max_new_tokens 2048

For a model after full-parameter training or Merge LoRA, point --model to the corresponding complete weights directory:

ASCEND_RT_VISIBLE_DEVICES=0 swift infer \
    --model xxx/checkpoint-xxx-merged \
    --stream true --max_new_tokens 2048

๐ŸŒ Deployment

๐ŸŒ Deploy with native transformers

Original model:

ASCEND_RT_VISIBLE_DEVICES=0 swift deploy --model Qwen/Qwen2-7B-Instruct --max_new_tokens 2048

After LoRA fine-tuning:

ASCEND_RT_VISIBLE_DEVICES=0 swift deploy --adapters xxx/checkpoint-xxx --max_new_tokens 2048

# deploy the complete weights after Merge LoRA
ASCEND_RT_VISIBLE_DEVICES=0 swift merge --adapters xx/checkpoint-xxx
ASCEND_RT_VISIBLE_DEVICES=0 swift deploy --model xxx/checkpoint-xxx-merged --max_new_tokens 2048

๐ŸŒ Deploy with vLLM-ascend

Install from pypi:

# follow the official vLLM-Ascend compatibility matrix; the following are the versions recommended in this page.
pip install vllm==0.23.0
pip install vllm-ascend==0.23.0 \
  --extra-index-url https://mirrors.huaweicloud.com/ascend/repos/pypi/variant \
  --extra-index-url https://mirrors.huaweicloud.com/ascend/repos/pypi

Original model:

ASCEND_RT_VISIBLE_DEVICES=0 swift deploy \
    --model Qwen/Qwen2.5-7B-Instruct \
    --sampler_type vllm \
    --max_new_tokens 2048

After LoRA fine-tuning:

ASCEND_RT_VISIBLE_DEVICES=0 swift deploy \
    --adapters xxx/checkpoint-xxx \
    --sampler_type vllm \
    --max_new_tokens 2048

# deploy the complete weights after Merge LoRA
ASCEND_RT_VISIBLE_DEVICES=0 swift merge \
    --adapters xx/checkpoint-xxx

ASCEND_RT_VISIBLE_DEVICES=0 swift deploy \
    --model xxx/checkpoint-xxx-merged \
    --sampler_type vllm \
    --max_new_tokens 2048

๐Ÿ“ Evaluation

After training, inference or deployment, the built-in EvalScope capability of ms-swift can evaluate the original model or the fine-tuned checkpoint. For the arguments of swift eval see Command-line arguments.

๐Ÿ“„ Publishing

To publish an NPU-trained checkpoint, a merged model or a quantized model to ModelScope/HuggingFace, add --push_to_hub true --hub_model_id <model id> to swift export or swift merge to push directly. For the arguments see Command-line arguments.

โš ๏ธ FAQ

The following records problems that are more common in NPU scenarios and how to handle them.

โ“ Q1: How do I confirm that the current environment has recognized the NPU correctly?

First confirm that source /usr/local/Ascend/ascend-toolkit/set_env.sh has been run, then run the environment check script from the installation section of this page. In a normal environment, is_torch_npu_available() should return True, torch.npu.device_count() should return the number of available NPUs, and a tensor can be created on npu:0. If this fails, check first whether the CANN, torch and torch_npu versions match the versions recommended in this page.

โ“ Q2: Should I choose FSDP, DeepSpeed or Megatron-ms-swift for training?

For ordinary SFT, refer first to the FSDP1/FSDP2/deepspeed combinations in the compatibility table of this page. If the model is large and higher parallel capability is needed, use Megatron and additionally install MCore 0.18, MegatronAdaptor, TransformerEngineNPU and mcore-bridge as described in the installation section. DeepSpeed lowers memory pressure but may reduce speed. When performance problems appear, compare against the FSDP option.

โ“ Q3: Does the NPU model patch need to be turned off manually?

No, and there is no corresponding command-line argument: the switch is decided automatically by the platform (the old --enable_npu_model_patch has been removed). When troubleshooting an abnormal loss or a forward error, the patch cannot be turned off to compare against the native Transformers behavior.

Q4: What should be noted when deploying or running RL rollout with vLLM-Ascend?

Install the vllm and vllm-ascend versions recommended in this page, and prefer the model and algorithm combinations already verified in the compatibility table. The sglang inference engine has not completed support verification in NPU scenarios. If high-performance inference or RL rollout on NPU is needed, prefer vllm-ascend.

โ“ Q5: What happens if I forget to run source set_env.sh?

Common symptoms are is_torch_npu_available() returning False, torch.npu.device_count() being 0, or CANN/HCCL dynamic libraries not being found at runtime. After entering a new shell or a new container, run first:

source /usr/local/Ascend/ascend-toolkit/set_env.sh

If components such as NNAL/ATB are installed on the system, the corresponding set_env.sh also needs to be sourced according to the actual environment.

โ“ Q6: How do I tell whether the torch and torch_npu versions do not match?

Install according to the versions recommended in this page first. When versions do not match, common symptoms include import torch_npu failing, NPU devices being invisible, operator registration failing, and C++/symbol-not-found errors at runtime. Confirm the versions with the following command first:

python -c "import torch, torch_npu; print(torch.__version__); print(torch_npu.__version__)"

If the versions are inconsistent, uninstall and reinstall with the same set of CANN/PyTorch/torch_npu versions. Upgrading only one of the packages is not recommended.

โ“ Q7: What happens if ASCEND_RT_VISIBLE_DEVICES and NPROC_PER_NODE are inconsistent?

The two should match in distributed training. For example, ASCEND_RT_VISIBLE_DEVICES=0,1,2,3 usually corresponds to NPROC_PER_NODE=4. If the process count is greater than the number of visible devices, rank-to-device binding may fail, several processes may contend for the same device, initialization may block, or HCCL errors may appear. If the process count is smaller than the number of visible devices, only some NPUs are used.

โ“ Q8: What should be checked first when multi-card training hangs?

First confirm whether every rank has started and whether ASCEND_RT_VISIBLE_DEVICES and NPROC_PER_NODE match, then check whether the log stops at data preprocessing, model construction, weight loading or HCCL initialization. For low-level NPU/HCCL logs, look at:

ls ~/ascend/log/debug/plog

If the Python process has not exited but produces no output for a long time, use pystack to view the current stack of each rank and first determine whether it is stuck in data, communication or model forward/backward.

โ“ Q9: How do I start troubleshooting HCCL connection or timeout problems?

First use npu-smi info and npu-smi info -t topo to confirm device health and topology, then check whether other jobs are occupying the same group of NPUs. For single-node training, confirm first that the card indices, process count and visible devices are consistent. Multi-node training also requires confirming that the network, rank configuration, communication ports and environment variables on each node are consistent. If old training processes remain on the same machine, clean up the corresponding user's training processes first and then retry.

โ“ Q10: What usually causes npu-smi to be unavailable inside a container?

Usually the device or driver files are not mounted completely. Check first whether docker run includes /dev/davinci*, /dev/davinci_manager, /dev/devmm_svm, /dev/hisi_hdc, as well as /usr/local/Ascend/driver, /usr/local/Ascend/firmware, /usr/local/sbin/npu-smi and /etc/ascend_install.info. If npu-smi info fails on the host itself, fix the host driver environment first.

โ“ Q11: How do I choose between native transformers deployment and vLLM-Ascend deployment?

Native transformers deployment has better compatibility and is suited to first verifying that the model, adapter, template and output are correct. vLLM-Ascend suits high-throughput services, RL rollout, or performance scenarios that need an OpenAI-compatible interface. When vLLM-Ascend version or operator problems appear, confirm first that the model itself works with the transformers backend, then switch to vLLM-Ascend to troubleshoot the performance backend.

โ“ Q12: How do I handle device type mismatch or undefined symbol errors from vLLM-Ascend?

These problems are usually not caused by training script arguments but by a mismatch between the vllm-ascend wheel and the current hardware, PyTorch or C++ ABI. Check the build information inside the package and the current version first:

python -c "import torch, vllm_ascend; print(torch.__version__); print(vllm_ascend.__file__)"

If the error message contains Current device type ... does not match the installed version's device type ..., undefined symbol or similar, reinstall torch, torch_npu, vllm and vllm-ascend by device type (A2/A3/other) according to the official compatibility matrix. Do not replace only one package.

โ“ Q13: Can FP8 or quantized models be trained on NPU directly?

Do not assume so. Before downloading or loading a large model, check whether config.json contains quantization_config, then check the actual dtype of the safetensors. Quantization/QLoRA is still a not-yet-supported or not-fully-verified capability in the current NPU support scope. If the model weights are FP8 block quantized and the current NPU software stack does not support the corresponding FP8 path, switch to BF16 weights first, or convert to BF16 offline before training/loading.

โ“ Q14: How do I troubleshoot Megatron importing the wrong MCore/Adaptor?

Before running Megatron, PYTHONPATH, MEGATRON_LM_PATH and the local MegatronAdaptor/TransformerEngineNPU paths must point to the same set of sources under the installation directories above. Otherwise Python may start normally but actually import another MCore/Adaptor combination, and the subsequent errors look similar to model or argument problems.

export MEGATRON_LM_PATH="$HOME/swift-npu/Megatron-LM"
export PYTHONPATH="$MEGATRON_LM_PATH:$PYTHONPATH"
python -c "import importlib.util, megatron_adaptor, megatron.core, transformer_engine, os; print(megatron_adaptor.__file__); print(megatron.core.__file__); print(transformer_engine.__file__); print(os.environ.get('MEGATRON_LM_PATH')); assert importlib.util.find_spec('mindspeed') is None"

If the two are inconsistent, fix the environment variables first, then continue troubleshooting model construction, weight loading or parallel configuration.

๐Ÿ’ฌ NPU WeChat group

On this page

Hardware and supported operating systemsSupport at a glanceVerified SFT combinationsVerified RL combinationsNot yet supported or not fully verifiedPEFT Transformers 5 MoE fused expert LoRA limitationChoose a routeEnvironment preparationImage/container environment installationLocal environment installationEnvironment self-checkNPU availability checkOptional installation of MegatronAdaptor + TransformerEngineNPUQwen3.5 MCore GDN notesOptional acceleration for GDN models: FLA and Triton-AscendViewing the environmentQuick verification: ModelScope model + datasetTrainingSingle-card trainingData-parallel trainingDeepSpeed trainingQwen3.5 single-node multi-card LoRA exampleNPU model patchModel saving, Merge LoRA and resuming from a checkpointInferenceDeploymentDeploy with native transformersDeploy with vLLM-ascendEvaluationPublishingFAQQ1: How do I confirm that the current environment has recognized the NPU correctly?Q2: Should I choose FSDP, DeepSpeed or Megatron-ms-swift for training?Q3: Does the NPU model patch need to be turned off manually?Q4: What should be noted when deploying or running RL rollout with vLLM-Ascend?Q5: What happens if I forget to run source set_env.sh?Q6: How do I tell whether the torch and torch_npu versions do not match?Q7: What happens if ASCEND_RT_VISIBLE_DEVICES and NPROC_PER_NODE are inconsistent?Q8: What should be checked first when multi-card training hangs?Q9: How do I start troubleshooting HCCL connection or timeout problems?Q10: What usually causes npu-smi to be unavailable inside a container?Q11: How do I choose between native transformers deployment and vLLM-Ascend deployment?Q12: How do I handle device type mismatch or undefined symbol errors from vLLM-Ascend?Q13: Can FP8 or quantized models be trained on NPU directly?Q14: How do I troubleshoot Megatron importing the wrong MCore/Adaptor?NPU WeChat group