Ascend-SACT/Qwen3.5-4B-SFT
模型介绍
文件和版本
Pull Requests
讨论
分析

Qwen3.5-4B基于MindSpeed-MM框架SFT微调(支持全参和LoRA)

0. 模型概览

  • 类型:带视觉编码器的因果语言模型
  • 训练阶段:预训练与后训练
  • 语言模型:
    • 参数量:4B
    • 隐藏层维度:2560
    • Token 嵌入维度:248320(已填充)
    • 层数:32
    • 隐藏层结构:8×(3×(门控 DeltaNet→FFN)→1×(门控注意力→FFN))8 \times (3 \times (\text{门控 DeltaNet} \rightarrow \text{FFN}) \rightarrow 1 \times (\text{门控注意力} \rightarrow \text{FFN}))8×(3×(门控 DeltaNet→FFN)→1×(门控注意力→FFN))
    • 门控 DeltaNet:
      • 线性注意力头数量:V 为 32,QK 为 16
      • 头维度:128
    • 门控注意力:
      • 注意力头数量:Q 为 16,KV 为 4
      • 头维度:256
      • 旋转位置嵌入维度:64
    • 前馈网络(FFN):
      • 中间层维度:9216
    • 语言模型输出维度:248320(与 token 嵌入绑定)
    • MTP:采用多步训练
  • 上下文长度:原生支持 262,144 tokens,可扩展至最多 1,010,000 tokens。

1. 环境搭建

Qwen3.5-4B可用8卡进行SFT微调,配套版本如下表格:

配套版本
硬件910B3
架构arm
CANN8.5.2
torch2.7.1
torch_npu2.7.1
triton-ascend3.2.0
transformers5.2.0.dev0
mindspeed-mmv26.0.0

1.1 训练镜像制作

拉取基础镜像cann:8.5.2-910b-openeuler24.03-py3.11,并且基于基础镜像启动容器

docker pull quay.io/ascend/cann:8.5.2-910b-openeuler24.03-py3.11

docker run -itd \
  --name mindspeed-mm-install \
  --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 \
  quay.io/ascend/cann:8.5.2-910b-openeuler24.03-py3.11 \
  bash

启动容器,创建目录

mkdir -p /workspace
cd /workspace

拉取MindSpeed-MM代码,切换到v26.0.0版本:

git clone --branch 26.0.0 https://gitcode.com/Ascend/MindSpeed-MM.git
cd MindSpeed-MM

执行如下指令一键安装:

bash scripts/install.sh --msid eb10b92 && bash examples/qwen3_5/install_extensions.sh

请确保torch和torch_npu版本都是2.7.1:

pip show torch
pip show torch_npu

如果不是,请执行下面的命令

pip install torch==2.7.1 torch-npu==2.7.1

2. 模型权重转换

2.1 下载模型

git clone https://www.modelscope.cn/Qwen/Qwen3.5-4B.git # 从modelscope下载
git clone https://huggingface.co/Qwen/Qwen3.5-4B # 从huggingface下载

2.2 权重转换

mm-convert Qwen35Converter hf_to_dcp \
--hf_dir "/mnt/public/models/huggface_models/Qwen/Qwen3.5-4B" \
--dcp_dir "/Qwen3.5-4B-dcp"

3. 训练数据

纯文本训练数据采用huggingface标准的格式,如下:

{"messages": [{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]}
{"messages": [{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]}

多模态数据数据参考: https://gitcode.com/Ascend/MindSpeed-MM/blob/v26.1.0/docs/zh/features/building_data_for_VLModel.md

4. Qwen3.5-4B 训练配置文件

4.1 配置文件

以下是主要配置信息,具体配置文件参考qwen3_5_4B_config.yaml

4.1.1 全参微调

# 并行策略
parallel:
  tensor_parallel_size: 1
  fully_shard_parallel_size: auto
  fsdp_plan:
    apply_modules:
      - model.visual.blocks.{*}
      - model.visual
      - model.language_model.layers.{*}
      - model.language_model.embed_tokens
      - model.language_model
      - lm_head
    param_dtype: bf16
    reduce_dtype: fp32
  recompute: true
  recompute_plan:
      apply_modules:
        - model.language_model.layers.{*}
  ulysses_parallel_size: 1 # 开启 ulysses-cp 时, 请将 model 的 attn_implementation 设置为 flash_attention_2

### 数据相关配置
data:
  dataset_param:
    dataset_type: huggingface
    #数据集属性
    attr:
      #images: images
      messages: messages
      role_tag: role
      content_tag: content
      user_tag: user
      assistant_tag: assistant

    # 数据预处理
    preprocess_parameters:
      model_name_or_path: /mnt/public/models/huggface_models/Qwen/Qwen3.5-4B # 替换为原始hf权重
      use_fast_tokenizer: true
      split_special_tokens: false
      image_max_pixels: 262144
      image_min_pixels: 1024
      video_max_pixels: 16384
      video_min_pixels: 0
      video_fps: 2.0
      video_maxlen: 64

    basic_parameters:
      cutoff_len: 1024
      template: qwen3_vl_nothink
      enable_thinking: false
      train_on_prompt: false
      mask_history: false
      dataset_dir: ./data
      dataset: /workspace/MindSpeed-MM/data/test.jsonl
      cache_dir: ./cache_dir/
      overwrite_cache: true
      preprocessing_batch_size: 1000
      preprocessing_num_workers: 16
      max_samples: null

  # 数据加载
  dataloader_param:
    pin_memory: true
    shuffle: false
    dataloader_mode: sampler
    drop_last: true
    sampler_type: BaseRandomBatchSampler
    num_workers: 8
    collate_param:
      model_name: qwen3vl
      ignore_pad_token_for_loss: true

# 模型配置
model:
  model_id: qwen3_5
  model_name_or_path: /mnt/public/models/huggface_models/Qwen/Qwen3.5-4B
  trust_remote_code: true
  attn_implementation: sdpa
  freeze:
    - model.visual
  loss_cfg:
    loss_type: default   # If you want raw loss in model, loss_type can be set to "raw".
    router_aux_loss_coef: 0.0
  enable_chunk_loss: false
  chunkloss_plan:
    apply_module: lm_head
    chunk_size: 1024
  use_triton_gdn: true

# 训练配置
training:
  micro_batch_size: 1
  gradient_accumulation_steps: 1
  seed: 42
  lr: 1.0e-5
  lr_decay_style: cosine
  lr_warmup_ratio: 0.1
  weight_decay: 0
  train_iters: 60
  clip_grad: 0.0
  init_model_with_meta_device: false
  optimizer: adamw
  adam_fused: true
  save_interval: 30
  no_load_optim: true  # Do not load optimizer state; remove if loading is needed.
  no_load_rng: true  # Do not load RNG state; remove if loading is needed.
  no_save_optim: true  # Do not save optimizer state; remove if saving is needed.
  no_save_rng: true  # Do not save RNG state; remove if saving is needed.
  load: /Qwen35-4B-dcp  # 替换为转换后的dcp权重
  save: ./save_path
  use_deter_comp: false
  plugin:
    - mindspeed_mm/fsdp/models/qwen3_5
    - mindspeed_mm/fsdp/data/datasets/huggingface

# 工具配置
tools:
  profile:
    enable: false
    profile_type: static
    ranks: [0]
    static_param:
      level: level1
      with_stack: false
      with_memory: false
      record_shapes: false
      with_cpu: true
      save_path: ./profiling
      start_step: 10
      end_step: 11
      data_simplification: false
      aic_metrics_type: PipeUtilization
  memory_profile:
      enable: false
      start_step: 1
      end_step: 2
      save_path: ./memory_snapshot
      dump_ranks: [0]
      stacks: all
      max_entries: null
      mem_info: false

4.1.2 LoRA

# 并行策略
parallel:
  tensor_parallel_size: 1
  fully_shard_parallel_size: auto
  fsdp_plan:
    apply_modules:
      - model.visual.blocks.{*}
      - model.visual
      - model.language_model.layers.{*}
      - model.language_model.embed_tokens
      - model.language_model
      - lm_head
    param_dtype: bf16
    reduce_dtype: fp32
  recompute: true
  recompute_plan:
      apply_modules:
        - model.language_model.layers.{*}
  ulysses_parallel_size: 1 # 开启 ulysses-cp 时, 请将 model 的 attn_implementation 设置为 flash_attention_2

### 数据相关配置
data:
  dataset_param:
    dataset_type: huggingface
    #数据集属性
    attr:
      #images: images
      messages: messages
      role_tag: role
      content_tag: content
      user_tag: user
      assistant_tag: assistant

    # 数据预处理
    preprocess_parameters:
      model_name_or_path: /mnt/public/models/huggface_models/Qwen/Qwen3.5-4B # 替换为原始hf权重
      use_fast_tokenizer: true
      split_special_tokens: false
      image_max_pixels: 262144
      image_min_pixels: 1024
      video_max_pixels: 16384
      video_min_pixels: 0
      video_fps: 2.0
      video_maxlen: 64

    basic_parameters:
      cutoff_len: 1024
      template: qwen3_vl_nothink
      enable_thinking: false
      train_on_prompt: false
      mask_history: false
      dataset_dir: ./data
      dataset: /workspace/MindSpeed-MM/data/test.jsonl
      cache_dir: ./cache_dir/
      overwrite_cache: true
      preprocessing_batch_size: 1000
      preprocessing_num_workers: 16
      max_samples: null

  # 数据加载
  dataloader_param:
    pin_memory: true
    shuffle: false
    dataloader_mode: sampler
    drop_last: true
    sampler_type: BaseRandomBatchSampler
    num_workers: 8
    collate_param:
      model_name: qwen3vl
      ignore_pad_token_for_loss: true

# 模型配置
model:
  model_id: qwen3_5
  model_name_or_path: /mnt/public/models/huggface_models/Qwen/Qwen3.5-4B
  trust_remote_code: true
  attn_implementation: sdpa
  freeze:
    - model.visual
  loss_cfg:
    loss_type: default   # If you want raw loss in model, loss_type can be set to "raw".
    router_aux_loss_coef: 0.0
  enable_chunk_loss: false
  chunkloss_plan:
    apply_module: lm_head
    chunk_size: 1024
  use_triton_gdn: true

# 训练配置
training:
  micro_batch_size: 1
  gradient_accumulation_steps: 1
  seed: 42
  lr: 1.0e-5
  lr_decay_style: cosine
  lr_warmup_ratio: 0.1
  weight_decay: 0
  train_iters: 60
  clip_grad: 0.0
  init_model_with_meta_device: false
  optimizer: adamw
  adam_fused: true
  save_interval: 30
  no_load_optim: true  # Do not load optimizer state; remove if loading is needed.
  no_load_rng: true  # Do not load RNG state; remove if loading is needed.
  no_save_optim: true  # Do not save optimizer state; remove if saving is needed.
  no_save_rng: true  # Do not save RNG state; remove if saving is needed.
  load: /Qwen35-4B-dcp  # 替换为转换后的dcp权重
  save: ./save_path
  use_deter_comp: false
  plugin:
    - mindspeed_mm/fsdp/models/qwen3_5
    - mindspeed_mm/fsdp/data/datasets/huggingface
  lora:
    enable: true
    rank: 8
    alpha: 16
    target_modules:
      - "model.language_model.layers.{*}.self_attn.q_proj"
      - "model.language_model.layers.{*}.self_attn.k_proj"
      - "model.language_model.layers.{*}.self_attn.v_proj"
      - "model.language_model.layers.{*}.self_attn.o_proj"
      - "model.language_model.layers.{*}.mlp.gate_proj"
      - "model.language_model.layers.{*}.mlp.up_proj"
      - "model.language_model.layers.{*}.mlp.down_proj"
    dropout: 0.0
    init_lora_weights: "kaiming"
    pretrained_lora_path: null

# 工具配置
tools:
  profile:
    enable: false
    profile_type: static
    ranks: [0]
    static_param:
      level: level1
      with_stack: false
      with_memory: false
      record_shapes: false
      with_cpu: true
      save_path: ./profiling
      start_step: 10
      end_step: 11
      data_simplification: false
      aic_metrics_type: PipeUtilization
  memory_profile:
      enable: false
      start_step: 1
      end_step: 2
      save_path: ./memory_snapshot
      dump_ranks: [0]
      stacks: all
      max_entries: null
      mem_info: false

4.2 关键参数配置

参数参数解释
ulysses_parallel_size长序列训练的序列并行大小,用于将长序列切分到多卡并行计算以降低显存压力,序列不长时设为1表示不开启
cutoff_len训练时输入序列的最大长度
shuffle是否在数据加载时打乱样本顺序
micro_batch_size单张NPU上每次计算的样本数
gradient_accumulation_steps梯度累计步数,GBS=micro_batch_size * gradient_accumulation_steps * DP
train_iters总训练迭代次数(iteration数)
save_interval模型保存间隔,即每训练多少iteration保存一次checkpoint
skip_gdn_recompute是否跳过GDN相关算子的重计算
skip_flash_attn_recompute是否跳过Flash Attention的重计算

5. 训练拉起

5.1 训练脚本配置

以下是单机主要训练参数配置,具体训练脚本见finetune_qwen3_5_4B.sh

source /usr/local/Ascend/cann/set_env.sh
export NON_MEGATRON=true
export MULTI_STREAM_MEMORY_REUSE=2
export TASK_QUEUE_ENABLE=2
export ASCEND_LAUNCH_BLOCKING=0
export ACLNN_CACHE_LIMIT=100000
export CPU_AFFINITY_CONF=1
export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True

NPUS_PER_NODE=8
MASTER_ADDR=localhost
MASTER_PORT=6000
NNODES=1
NODE_RANK=0
WORLD_SIZE=$(($NPUS_PER_NODE*$NNODES))

DISTRIBUTED_ARGS="
    --nproc_per_node $NPUS_PER_NODE \
    --nnodes $NNODES \
    --node_rank $NODE_RANK \
    --master_addr $MASTER_ADDR \
    --master_port $MASTER_PORT
"

logfile=$(date +%Y%m%d)_$(date +%H%M%S)
mkdir -p logs
torchrun $DISTRIBUTED_ARGS /workspace/MindSpeed-MM/mindspeed_mm/fsdp/train/trainer.py \
    /workspace/MindSpeed-MM/examples/qwen3_5/qwen3_5_4B_config.yaml \
    2>&1 | tee logs/train_${logfile}.log

5.2 关键参数配置

参数参数解释
MASTER_ADDR分布式训练中主节点的IP地址
MASTER_PORT分布式训练中主节点的通信端口
NODE_RANK当前节点在整个分布式训练中的编号(从0开始)
NPUS_PER_NODE每个节点上使用的NPU数量
NNODES分布式训练中使用的节点总数

5.3 启动训练

bash finetune_qwen3_5_4B.sh

6. 训练后权重转换

to_bf16设为true,模型权重将以bf16精度保存;如果设置为false,模型权重以fp32精度保存。

mm-convert Qwen35Converter dcp_to_hf\
--save_hf_dir ./models_Qwen3.5-4B_iter_xx \
--dcp_dir save_path/iter_00000xx \
--origin_hf_dir /PATH_TO_MODEL/Qwen3.5-4B \
--to_bf16 true