昇腾910B + MindSpore Transformers套件实现知识蒸馏的体验与心得
收藏回复举报
昇腾910B + MindSpore Transformers套件实现知识蒸馏的体验与心得
新人帖
发表于2025-04-21 22:57:48
0 查看

本次实验是根据官方教程实现在数学推理数据集上的蒸馏学习。

  • 官方配套的文章(还有视频教程):

https://modelers.cn/models/MindSpore-Lab/OpenR1-Qwen-7B

1. MindSpore Transformers知识回顾

近期,本人也跟着“昇思五日谈”系列视频学习了挺多关于MindSpore知识的,在此做个复习回顾。

首先MindSpore整个大模型训推一体框架与套件已经非常丰富了,能满足大多数业务场景的需求。

cke_33311.png

其次,在DeepSeek R1/V3系列模型爆火后,官方也很快做了跟进。各种新特性与算子都做了支持与融合,大大降低了业界的部署门槛,提升了模型推理效率。

cke_7832.png

cke_16526.png

纸上得来终觉浅,这次终于有机会实践一下MindSpore Transformers在昇腾硬件上的训练。

2. 实验过程

  • 知识蒸馏过程:

cke_101509.png

  • 数据集:OpenR1-Math-220k。这是一个大规模的数学推理数据集,包含 22 万个数学问题,以及由DeepSeek-R1为其中的问题生成的包含两到四条推理思维链(CoT)的答案。整体有20GB,在实验中,我们使用了其中的default分类数据集,大约2GB。
  • 蒸馏目标模型:Qwen2.5-Math-7B-Instruct。用蒸馏出来的数据集精调Qwen2.5-Math-7B-Instruct,最终期望得出一个规格虽小,但带有DeepSeek-R1推理思维链(CoT)的强大模型。

操作流程:

1. 登录准备好的实验机器,机器上已经准备好实验的docker镜像,直接跳过繁琐的环境准备(666)。

npu-smi info可以看到机器上有8张910B1 TPU。

cke_163255.png

2. 进入docker容器,copy个人实验目录:

docker exec -it sft bash
cd /home/HwHiAiUser
cp -R tutorial 个人名字拼音

3. 检查训练前Qwen2.5-Math-7B-Instruct的输出:

cd mindformers
python research/qwen2_5/run_qwen2_5.py                      \
    --config /home/HwHiAiUser/<name>/Qwen2.5-Math-7B/predict_qwen2_5_math_7b_instruct.yaml \
    --load_checkpoint /home/HwHiAiUser/<name>/Qwen2.5-Math-7B/ms_safetensors    \
    --vocab_file /home/HwHiAiUser/<name>/Qwen2.5-Math-7B/vocab.json        \
    --merges_file /home/HwHiAiUser/<name>/Qwen2.5-Math-7B/merges.txt       \
    --run_mode predict                                      \
    --predict_data "Find the invertibles modulo 8, then their inverses. Do the same modulo 9."

...

2025-03-29 13:30:02,375 - mindformers[mindformers/trainer/base_trainer.py:1290] - INFO - output resul
t is: [{'text_generation_text': ['<|im_start|>system\nYou are a helpful assistant.\n<|im_start|>user\
nFind the invertibles modulo 8, then their inverses. Do the same modulo 9.\n<|im_start|>assistant\n! 
To find the invertible elements modulo \\( n \\) and their inverses, we need to identify the integers
 \\( a \\) such that \\( \\gcd(a, n) = 1 \\). An integer \\( a \\) is invertible modulo \\( n \\) if 
and only if it is coprime with \\( n \\). The inverse of \\( a \\) modulo \\( n \\) is an integer \\(
 b \\) such']}]

可以看到模型的输出虽然有一些CoT的步骤,但不是DeepSeek R1的长推理格式与内容(无&lt;think&gt;&lt;/think&gt;, &lt;answer&gt;&lt;/answer&gt;标签)。

4. 修改配置文件:

finetune_qwen_2_5_7b_dyn.yaml 
seed: 42
output_dir: './output' # 训练结果保存路径,根据实际情况修改
load_checkpoint: '/home/HwHiAiUser/<name>/Qwen2.5-Math-7B/ms_safetensors' # 权重加载路径,根据实际情况修改
load_ckpt_format: 'safetensors'
...

5. 启动微调:

设置如下环境变量防止OOM:
export ACLNN_CACHE_LIMIT=10 # CANN 缓存限制
export MS_DEV_RUNTIME_CONF="aclnn_cache_queue_length:128" # MS缓存队列长度建议设置成128,设置过大内存容易OOM,设置越小性能越差

# 启动
bash scripts/msrun_launcher.sh "run_mindformer.py --config /path/to/finetune_qwen_2_5_7b.yaml --run_mode finetune" 8

日志记录在output/msrun_log目录下,可以通过tail指令查看日志信息。
微调完成后,输出的权重文件在output/checkpoint目录下。

注意只有最后一个卡,即卡7上的worker会输出loss,其他的worker输出的loss会显示0 (pipeline stages: 2 &gt; 1, the loss on the last card is valid.):

tail -f worker_7.log
2025-03-29 15:15:38,348 - mindformers[mindformers/core/callback/callback.py:384] - WARNING - pipeline
 stages: 2 > 1, the loss on the last card is valid.
2025-03-29 15:15:38,349 - mindformers[mindformers/core/callback/callback.py:528] - INFO - { Epoch:[  
1/  1], step:[   22/ 2343], loss: 0.522, per_step_time: 6281ms, lr: 4.4871795e-06, overflow cond: Fal
se, loss_scale: 4096.0, global_norm: [1.1911869]
2025-03-29 15:15:38,350 - mindformers[mindformers/core/callback/callback.py:553] - INFO -    0.9% |  
                                                | 0.15920 samples/s/p  4:02:59 }
2025-03-29 15:15:43,239 - mindformers[mindformers/core/callback/callback.py:384] - WARNING - pipeline
 stages: 2 > 1, the loss on the last card is valid.
2025-03-29 15:15:43,239 - mindformers[mindformers/core/callback/callback.py:528] - INFO - { Epoch:[  
1/  1], step:[   23/ 2343], loss: 0.646, per_step_time: 4884ms, lr: 4.700855e-06, overflow cond: Fals
e, loss_scale: 4096.0, global_norm: [1.4656488]
2025-03-29 15:15:43,240 - mindformers[mindformers/core/callback/callback.py:553] - INFO -    1.0% |  
                                                | 0.20472 samples/s/p  3:08:52 }
...

微调过程中的显存使用情况:

[root@bms-910b-04 ~]# npu-smi info
+------------------------------------------------------------------------------------------------+
| npu-smi 24.1.rc3                 Version: 24.1.rc3                                             |
+---------------------------+---------------+----------------------------------------------------+
| NPU   Name                | Health        | Power(W)    Temp(C)           Hugepages-Usage(page)|
| Chip                      | Bus-Id        | AICore(%)   Memory-Usage(MB)  HBM-Usage(MB)        |
+===========================+===============+====================================================+
| 0     910B1               | OK            | 129.2       35                0    / 0             |
| 0                         | 0000:C1:00.0  | 0           0    / 0          61322/ 65536         |
+===========================+===============+====================================================+
| 1     910B1               | OK            | 118.3       38                0    / 0             |
| 0                         | 0000:01:00.0  | 0           0    / 0          61400/ 65536         |
+===========================+===============+====================================================+
| 2     910B1               | OK            | 114.4       35                0    / 0             |
| 0                         | 0000:C2:00.0  | 0           0    / 0          61362/ 65536         |
+===========================+===============+====================================================+
| 3     910B1               | OK            | 114.3       38                0    / 0             |
| 0                         | 0000:02:00.0  | 0           0    / 0          61300/ 65536         |
+===========================+===============+====================================================+
| 4     910B1               | OK            | 331.6       43                0    / 0             |
| 0                         | 0000:81:00.0  | 44          0    / 0          54702/ 65536         |
+===========================+===============+====================================================+
| 5     910B1               | OK            | 341.9       50                0    / 0             |
| 0                         | 0000:41:00.0  | 47          0    / 0          54702/ 65536         |
+===========================+===============+====================================================+
| 6     910B1               | OK            | 342.1       47                0    / 0             |
| 0                         | 0000:82:00.0  | 49          0    / 0          54702/ 65536         |
+===========================+===============+====================================================+
| 7     910B1               | OK            | 332.1       46                0    / 0             |
| 0                         | 0000:42:00.0  | 51          0    / 0          54702/ 65536         |
+===========================+===============+====================================================+
+---------------------------+---------------+----------------------------------------------------+
| NPU     Chip              | Process id    | Process name             | Process memory(MB)      |
+===========================+===============+====================================================+
| 0       0                 | 2466127       | python                   | 57864                   |
+===========================+===============+====================================================+
| 1       0                 | 2466133       | python                   | 57944                   |
+===========================+===============+====================================================+
| 2       0                 | 2466139       | python                   | 57906                   |
+===========================+===============+====================================================+
| 3       0                 | 2466145       | python                   | 57844                   |
+===========================+===============+====================================================+
| 4       0                 | 2466151       | python                   | 51247                   |
+===========================+===============+====================================================+
| 5       0                 | 2466157       | python                   | 51246                   |
+===========================+===============+====================================================+
| 6       0                 | 2466163       | python                   | 51247                   |
+===========================+===============+====================================================+
| 7       0                 | 2466169       | python                   | 51246                   |
+===========================+===============+====================================================+

在训练进度到一半的时候,出现了一个小插曲(报了显存OOM):

2025-03-29 17:36:58,976 - mindformers[mindformers/core/callback/callback.py:553] - INFO -   54.1% |███████████████████████████                       | 0.09450 samples/s/p  3:09:36 }
[WARNING] DISTRIBUTED(880627,ffebdcf9f120,python):2025-03-29-17:37:28.861.859 [mindspore/ccsrc/distributed/rpc/tcp/connection.cc:79] SocketEventHandler] Event value fd: 372, events: 8193, state: 4, errcode: 0, errno: 0 Success, remote peer: 10.14.10.102:8893, type:1, remote: 0, count: 1, this peer: 10.14.10.102:37150, please check remote peer address: 10.14.10.102:8893 in worker log to find out which worker disconnected.
[ERROR] TBE Subprocess[task_distribute] raise error[], main process disappeared!
[ERROR] TBE Subprocess[task_distribute] raise error[], main process disappeared!
[ERROR] TBE Subprocess[task_distribute] raise error[], main process disappeared!
[ERROR] TBE Subprocess[task_distribute] raise error[], main process disappeared!
[ERROR] TBE Subprocess[task_distribute] raise error[], main process disappeared!
[ERROR] TBE Subprocess[task_distribute] raise error[], main process disappeared!
[ERROR] TBE Subprocess[task_distribute] raise error[], main process disappeared!
[ERROR] TBE Subprocess[task_distribute] raise error[], main process disappeared!
/usr/lib/python3.10/multiprocessing/resource_tracker.py:224: UserWarning: resource_tracker: There appear to be 30 leaked semaphore objects to clean up at shutdown
  warnings.warn('resource_tracker: There appear to be %d '
RuntimeError: 
----------------------------------------------------
- Memory not enough:
----------------------------------------------------
Device(id:0) memory isn't enough and alloc failed, kernel name: 10976_Gradients/Default/Grad_Split/Co
ncat-op288, alloc size: 160104448B.

----------------------------------------------------
- C++ Call Stack: (For framework developers)
----------------------------------------------------
mindspore/ccsrc/runtime/graph_scheduler/graph_scheduler.cc:1282 Run

但是由于训练的步数已经达到checkpoint的步数,所以有已经保存好的checkpoint可以继续恢复训练或者直接使用。

6. 合并checkpoint的模型权重:

模型权重在多卡上训练,需要合并多卡worker保存的权重

python unified_safetensors.py \
--mindspore_ckpt_dir /home/HwHiAiUser/<name>/mindformers/output/checkpoint_network/ \
--src_strategy_dirs /home/HwHiAiUser/<name>/mindformers/output/strategy/ \
--output_dir /home/HwHiAiUser/<name>/sft_output_1000 \
--file_suffix "1000_1" \
--format "safetensors"

合并后的权重在:/home/HwHiAiUser/&lt;name&gt;/sft_output_1000/1000_1_ckpt_convert/unified_safe/ 下

ls -lht /home/HwHiAiUser/
<name>/sft_output_1000/1000_1_ckpt_convert/unified_safe/
total 29G
-rw-r----- 1 root root 6.9G Mar 29 21:12 part5.safetensors
-rw-r----- 1 root root 2.9G Mar 29 21:12 part8.safetensors
-rw-r----- 1 root root 2.7G Mar 29 21:12 part6.safetensors
-rw-r----- 1 root root 2.6G Mar 29 21:12 part2.safetensors
-rw-r----- 1 root root 2.7G Mar 29 21:12 part4.safetensors
-rw-r----- 1 root root 2.4G Mar 29 21:12 part9.safetensors
-rw-r----- 1 root root 2.3G Mar 29 21:12 part7.safetensors
-rw-r----- 1 root root 2.0G Mar 29 21:12 part0.safetensors
-rw-r----- 1 root root 2.5G Mar 29 21:12 part3.safetensors
-rw-r----- 1 root root 1.9G Mar 29 21:12 part1.safetensors
-rw-r----- 1 root root  22K Mar 29 21:12 param_name_map.json

7. 测试推理并检查训练结果:

python research/qwen2_5/run_qwen2_5.py --config /home/HwHiAiUser/<name>/Qwen2.5-Math-7B/predict_qwen2_5_math_7b_instruct.yaml \
--load_checkpoint /home/HwHiAiUser/<name>/sft_output_1000/1000_1_ckpt_convert/unified_safe/ \
--vocab_file /home/HwHiAiUser/<name>/Qwen2.5-Math-7B/vocab.json \
--merges_file /home/HwHiAiUser/<name>/Qwen2.5-Math-7B/merges.txt \
--seq_length 4096 \
--predict_length 4096 \
--predict_data 'Given $0 \\leqslant x, y, z \\leqslant 1$, solve the equation:\n$$\\frac{x}{1+y+z x}+\\frac{y}{1+z+x y}+\\frac{z}{1+x+y z}=\\frac{3}{x+y+z} .$$'
...
2025-03-29 21:28:36,884 - mindformers[mindformers/trainer/base_trainer.py:1290] - INFO - output resul
t is: [{'text_generation_text': ["<|im_start|>system\nYou are a helpful assistant.\n<|im_start|>user\
nGiven $0 \\\\leqslant x, y, z \\\\leqslant 1$, solve the equation:\\n$$\\\\frac{x}{1+y+z x}+\\\\frac
{y}{1+z+x y}+\\\\frac{z}{1+x+y z}=\\\\frac{3}{x+y+z} .$$\n<|im_start|>assistant\n<think>\nOkay, so I 
need to solve this equation where x, y, z are all between 0 and 1 inclusive:\n\n$$\\frac{x}{1+y+z x} 
+ \\frac{y}{1+z+x y} + \\frac{z}{1+x+y z} = \\frac{3}{x+y+z}.$$\n\nHmm, let's see. All variables are 
in [0,1], so maybe there's some symmetry here. Let me check if x = y = z is a solution. That often si
mplifies things.\n\nLet’s assume x = y = z = t. Then the left-hand side (LHS) becomes:\n\n$$3 \\cdot 
\\frac{t}{1 + t + t \\cdot t} = 3 \\cdot \\frac{t}{1 + t + t^2}.$$\n\nThe right-hand side (RHS) is:\n
\n$$\\frac{3}{3t} = \\frac{1}{t}.$$\n\nSo setting them equal:\n\n$$3 \\cdot \\frac{t}{1 + t + t^2} =
...

从模型的输出可以看到&lt;think&gt;标签,并且推理过程更长,更复杂,训练效果达成!✌️

3. 实验总结

  • 整个过程其实官方都照顾到新手的方方面面,包括环境、数据集转换、配置文件等都准备妥当。虽然让我等新手很快上手,但似乎缺少一点磨练。
  • 可以看到MindSpore Transformers套件与其他成熟框架非常接近,中间虽然遇到一个小问题,但checkpoint功能好用,易用性很好,👍。
  • 希望越来越多人能够真正把MindSpore Transformers用起来,共同把它完善好。

4. 后续。。。

  • 后面我另外在某DL平台租了个2卡910B机器做了一个部署推理 Qwen2.5-7B-Instruct 的实验,也比较顺利,可见MindSpore Transformers套件确实是成熟与稳定的。

本帖最后由 匿名用户2025/04/21 23:10:53 编辑

我要发帖子