ms-swift icon indicating copy to clipboard operation
ms-swift copied to clipboard

multi node + qwen3.5 + megatron + sft 似乎存在内存泄露情况.

Open Night-Quiet opened this issue 7 months ago • 15 comments

Checklist / 检查清单

  • [x] I have searched existing issues, and this is a new bug report. / 我已经搜索过现有的 issues,确认这是一个新的 bug report。

Bug Description / Bug 描述

Image
  1. 内存一直处于持续上涨的状态.
  2. 目前是每个节点2T内存. 仅使用40万数据做SFT.
  3. 我查看了其他issues: https://github.com/modelscope/ms-swift/issues/2321, 似乎提出的解决方案是升级ms-swift解决. 但这个docker应该是最新的ms-swift版本.

How to Reproduce / 如何复现

节点信息

4节点.
每节点8卡H100.
每节点2T内存.

pip环境

# docker拉取
docker pull modelscope-registry.cn-hangzhou.cr.aliyuncs.com/modelscope-repo/modelscope:ubuntu22.04-cuda12.9.1-py312-torch2.10.0-vllm0.19.1-modelscope1.35.4-swift4.1.3
docker tag modelscope-registry.cn-hangzhou.cr.aliyuncs.com/modelscope-repo/modelscope:ubuntu22.04-cuda12.9.1-py312-torch2.10.0-vllm0.19.1-modelscope1.35.4-swift4.1.3 swift4.1.3

docker run \
    -itd \
    -v /mnt:/mnt \
    -v /root/log:/root/log \
    --network host \
    --ipc host \
    --gpus all \
    --ulimit memlock=-1 \
    --shm-size 1024g \
    --privileged \
    --device /dev/infiniband \
    --cap-add IPC_LOCK \
    --name swift \
    -e NCCL_IB_HCA=mlx5_3,mlx5_7 \
    -e NCCL_P2P_LEVEL=NVL \
    -e NCCL_IB_GID_INDEX=0 \
    -e NCCL_IB_CUDA_SUPPORT=1 \
    -e NCCL_IB_DISABLE=0 \
    -e NCCL_SOCKET_IFNAME=enp93s0f0 \
    -e NCCL_DEBUG=INFO \
    -e NCCL_NET_GDR_LEVEL=2 \
    -e NCCL_IB_MERGE_NICS=1 \
    -e NCCL_TIMEOUT=1800 \
    -e MODELSCOPE_CACHE=/mnt/temp/modelscope \
    -e HF_HOME=/mnt/temp/huggingface \
    -e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
    -e TORCH_NCCL_AVOID_RECORD_STREAMS=1 \
    -e NCCL_DEBUG=ERROR \
    -e TRAIN_NODE_RANK=$TRAIN_NODE_RANK \
    swift4.1.3 \
    /bin/bash

# 补充安装
docker exec swift pip install -e /mnt/code/lf_test/Liger-Kernel
docker exec swift pip install tilelang
docker exec swift pip install -U datasets
docker exec swift swanlab login -k xxxxxxxx

训练脚本

# 基础路径配置
ENV:
  HF_ENDPOINT: https://hf-mirror.com
  PYTHONUNBUFFERED: 1
  CUDA_VISIBLE_DEVICES: 0,1,2,3,4,5,6,7
  SWIFT_USE_MCORE_GDN: 1

# 训练可视化配置
swanlab_project: megatron-swift
# workspace: megatron-swift-base # vl_experiment
swanlab_exp_name: Qwen3.5-35B-A3B-vl_instruct

# 数据配置
dataset: /mnt/datasets/local/ms_swift/vl
load_from_cache_file: true
dataset_shuffle: true
train_dataloader_shuffle: true
group_by_length: false
split_dataset_ratio: 0.01
packing: true
add_non_thinking_prefix: False
max_length: 32768
dataloader_num_workers: 64
dataset_num_proc: 64
packing_num_proc: 64

# Model配置
model: /mnt/models/Qwen3.5-35B-A3B
tuner_type: full
finetune: true
# use_liger_kernel: true
attention_backend: flash
freeze_llm: false
freeze_vit: true
freeze_aligner: true
save_strategy: epoch
save_safetensors: true
expert_model_parallel_size: 8
output_dir: "/mnt/checkpoints/ms-swift/Qwen3.5-35B-A3B-instruct"
# save_total_limit: 5
no_save_optim: true
no_save_rng: true

# Megatron配置
tensor_model_parallel_size: 4
sequence_parallel: true
# pipeline_model_parallel_size: 2
# virtual_pipeline_model_parallel_size: 0
context_parallel_size: 1
overlap_param_gather: true
overlap_grad_reduce: true
moe_token_dispatcher_type: alltoall
moe_permute_fusion: true
moe_grouped_gemm: true
moe_shared_expert_overlap: true
moe_layer_recompute: false
# moe_aux_loss_coeff: 1.0e-6
recompute_granularity: full  # selective
recompute_method: uniform
recompute_num_layers: 1
cross_entropy_loss_fusion: true
moe_expert_capacity_factor: 2
use_precision_aware_optimizer: true
optimizer_cpu_offload: true
optimizer_offload_fraction: 0.64

# Trainer配置
micro_batch_size: 1
global_batch_size: 8
num_train_epochs: 2
lr: 1.0e-5
lr_warmup_fraction: 0.05
logging_steps: 1
min_lr: 1.0e-6
eval_steps: 200
save_steps: 200
bf16: true
report_to: swanlab

启动命令

NPROC_PER_NODE=8 NNODES={nnodes} MASTER_ADDR={master_addr} MASTER_PORT=29500 NODE_RANK={node_rank}
megatron sft megatron sft {yaml_path}

Additional Information / 补充信息

  1. 每个节点都处于内存持续上涨状态
  2. 内存中间的跳跃的时间应该是第一个epoch的完成时间.
  3. 当前没有训练问题, 但是并没有使用全量数据训练(全量大概2百万条), 所以想确定这个事件是否是bug, 还是我的配置有问题.

Night-Quiet avatar Apr 29 '26 06:04 Night-Quiet

试试 --dataloader_persistent_workers false,不知道是不是这个原因

Jintao-Huang avatar Apr 30 '26 02:04 Jintao-Huang

好的好的. 我试试看.

Night-Quiet avatar Apr 30 '26 09:04 Night-Quiet

如果有效,回复我一下,我将这个PR合并了

Jintao-Huang avatar May 05 '26 05:05 Jintao-Huang

哈咯 这个修改有效果吗

Jintao-Huang avatar May 13 '26 06:05 Jintao-Huang

单机 8卡 megatron pt也有这个问题

AshOneN avatar May 14 '26 16:05 AshOneN

是的,有一些用户提到了,不过我还没找到原因,你看看我的方案是否有效

Jintao-Huang avatar May 14 '26 16:05 Jintao-Huang

加了这个参数依然内存oom

AshOneN avatar May 14 '26 17:05 AshOneN

这是我的训练脚本export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True export SKIP_MULTIMODAL_MTP_VALIDATION=1

训练参数

export NPROC_PER_NODE=8 export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 export SWIFT_USE_MCORE_GDN=1 export OMP_NUM_THREADS=1 nohup megatron pt
--model /workspace/model_hub/Qwen3.5-9B/
--save_safetensors true
--use_chat_template false
--dataset '/workspace/mllm_cpt_data/mllm_cpt_data_.jsonl'
--load_from_cache_file true
--split_dataset_ratio 0
--tuner_type full
--loss_scale all
--tensor_model_parallel_size 8
--pipeline_model_parallel_size 1
--micro_batch_size 2
--global_batch_size 128
--num_train_epochs 1
--finetune true
--packing true
--freeze_llm false
--freeze_vit false
--freeze_aligner false
--cross_entropy_loss_fusion true
--enable_channel_loss true
--lr 5e-5
--lr_warmup_fraction 0.05
--min_lr 1e-6
--output_dir megatron_output/Qwen3.5-9B-mllm-cpt
--eval_steps 200
--save_steps 200
--max_length 32768
--dataloader_num_workers 128
--dataset_num_proc 128
--no_save_optim true
--no_save_rng true
--dataloader_persistent_workers false
--sequence_parallel true
--attention_backend flash

AshOneN avatar May 14 '26 18:05 AshOneN

应该是 dataloader_num_workers太大了

Jintao-Huang avatar May 15 '26 02:05 Jintao-Huang

Similar problem here. I get OMM errors every time I save/load the model. Lowering dataloader_num_workers does not help either. Here is my configuration for 32 node training. Eachnode has 4 A100 and 512GB of RAM.

--- Network & Distributed Config (Leonardo Specifics) ---

export PYTORCH_ALLOC_CONF="expandable_segments:True"

srun accelerate launch
--num_processes $(( $NNODES * $GPUS_PER_NODE ))
--num_machines $NNODES
--mixed_precision bf16
--dynamo_backend "no"
--rdzv_backend c10d
--main_process_ip $MAIN_PROCESS_IP
--main_process_port $MASTER_PORT
--machine_rank $SLURM_NODEID
$HOME/ms-swift/swift/cli/_megatron/sft.py
--model$WORK/baseModels/Qwen3.5-27B
--save_safetensors true
--cached_dataset $WORK/datasets/train/preprocessed/v2/qwen32b/train/
--load_from_cache_file true
--split_dataset_ratio 0.01
--add_non_thinking_prefix true
--tensor_model_parallel_size 4
--pipeline_model_parallel_size 1
--micro_batch_size 2
--packing true
--global_batch_size 512
--recompute_granularity full
--recompute_method uniform
--recompute_num_layers 1
--num_train_epochs 4
--finetune false
--cross_entropy_loss_fusion true
--lr 0.00001
--lr_warmup_fraction 0.05
--adam_beta1 0.9
--loss_scale ignore_empty_think
--adam_beta2 0.95
--adam_eps 1e-8
--lr_decay_style cosine
--output_dir $WORK/multimodalModels
--save_steps 250
--max_length 8192
--dataloader_num_workers 2
--dataset_num_proc 2
--sequence_parallel true
--attention_backend flash
--no_load_optim false
--no_load_rng false
--save_total_limit 8
--overlap_param_gather true
--overlap_grad_reduce true
--logging_steps 5
--no_save_optim false
--freeze_llm false
--freeze_vit true
--freeze_aligner false
--padding_free true
--use_distributed_optimizer
--use_precision_aware_optimizer true
--optimizer_cpu_offload true
--dist_ckpt_optim_fully_reshardable
--distrib_optim_fully_reshardable_mem_efficient
--bf16 true

LukasArana avatar May 15 '26 15:05 LukasArana

The reason in your case should be optimizer_cpu_offload.

Jintao-Huang avatar May 16 '26 03:05 Jintao-Huang

Hi, thank you for the rapid response. However, setting the optimizer_cpu_offload still results in the same OOM errors. In my case, this happens when loading a checkpoint (when load_optim is set to True) or saving the checkpoint.

LukasArana avatar May 18 '26 08:05 LukasArana

@Jintao-Huang 很抱歉这么晚才回复, 我邮箱设置错误了导致没看到这个信息.

我针对你的参数进行了一次消融(其他参数和之前的训练脚本一致, 训练数据涨到了80万多模态), 发现这并不是内存泄露的原因. 这是对比图:

--dataloader_persistent_workers true

Image

--dataloader_persistent_workers false

Image

可以看到, 两者曲线近乎一致. 内存依旧是稳定上涨的趋势(中间的波动是epoch切换), 预计第3个或者第4个epoch就会出现内存崩溃.

因为这个只是单纯的内存溢出问题, 并没有影响训练稳定, 所以之前为了赶实验就没有管这个问题.

可以看到训练收敛挺好

Image

感谢作者对这个问题的关注.

如果有其他需要我尝试的参数或者消融, 我会尽快进行尝试(这次邮件设置为公司邮箱, 会及时看到).

祝好.

Night-Quiet avatar May 20 '26 01:05 Night-Quiet

好的 感谢

Jintao-Huang avatar Jun 24 '26 03:06 Jintao-Huang

求问,脚本和上面差不多,内存一直上涨,ms-swift版本4.6.1,megatron-core 0.19.2, 求问需要配置啥参数吗?

yc0815024 avatar Nov 28 '26 08:11 yc0815024