fix loss_scale bug when meeting <image>,<audio>,<video> #4922
+62
−2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
PR type
PR information
在自定义损失权值计算时,遇到了 loss_scale 维度不匹配的问题。查询 PR 记录后,发现该问题此前已被提出,但一直未得到解决。因此,提出了此 PR 以完善 Swift 框架。
此 PR 基于 #3036,结合最新的 3.7.0.dev0 版本代码进行了以下工作:
通过这些工作,希望能为 Swift 框架提供更稳定的自定义损失权值计算支持。
BUG内容:
对于Input: 多媒体 + text,Output: text类型的多模态模型,当训练数据user的content包含多媒体,例如 image 时,如果同时启用
会出现:
只对input_ids, lables的token进行扩展,之后遇见
自定义LossScale类代码,如下所示:
缺少同时扩展loss_scale维度的函数:
缺少loss_scale传递的函数(部分代码):
自定义loss无法计算的函数:
解决方案
增加def _extend_loss_scale():函数:
Experiment results
增添代码后,涉及的所有模块
通过对整个项目进行关键字查询,发现共涉及到15种多模态模板类的_encode()函数,如下图所示:

分别是:
问题复现及验证修改结果
实验设置
实验结果概括
① 以下模板受制于设备,未进行验证,但认为扩展逻辑一样,如果理解有误,敬请指教.
②以下模板既未扩展loss_scale, 也未传递loss_scale,因此无法进行自定义权值计算loss
③ 除此之外,其他模板均未扩展loss_scale,但可以传递loss_scale,因此无法进行自定义权值计算loss.
具体结果如下:
1. Qwen2VLTemplate
模型:
allenai/olmOCR-7B-0225-preview
缺乏扩展
问题复现
验证修改结果
2. Qwen2_5OmniTemplat
模型:
Qwen2.5-Omni-3B
缺乏扩展
问题复现
验证修改结果
3. PixtralTemplate
模型:
Pixtral-12B-2409-bnb-4bit
loss_scale维度不匹配
问题复现
验证修改结果
4. mPlugOwl3Template
模型:
mPLUG-Owl3-2B-241014
loss_scale丢失
问题复现
验证修改结果
5. KimiVLTemplate
模型:
在modelscope上, mlx-community/Kimi-VL-A3B-Thinking-4bit的model.safetensors.index.json文件内容,是未量化版本模型的配置,不是量化版本的配置.
官方版本模型受制于实验设备,未进行验证,但扩展逻辑一样
问题复现
pass
验证修改结果
pass
6. Mistral2503Template
模型:
Mistral-Small-3.1-24B-Base-2503-bnb-4bit
loss_scale维度不匹配
问题复现
验证修改结果
7. MiniCPMV2_6Template
模型:
MiniCPM-V_2_6
loss_scale丢失
问题复现
验证修改结果
8. Phi4MMTemplate
模型:
问题复现
pass
验证修改结果
pass
9. MegrezOmniTemplate
AI-ModelScope/Megrez-3B-Omni
模型:
问题复现
验证修改结果
10. Llama4Template
模型:
ResearchLlama-4-Scout-Dense-12B
问题复现
pass
验证修改结果
pass
11. Internvl2Template
模型:
InternVL2_5-1B
缺乏扩展
问题复现
验证修改结果
12. Gemma3VisionTemplate
模型:
gemma-3-4b-it
问题复现
验证修改结果
13. Gemma3nTemplate
模型:
gemma-3n-E4B
问题复现
验证修改结果
14. KeyeVLTemplate
模型:
Keye-VL-8B-Preview
问题复现
验证修改结果
15. Emu3ChatTemplate
模型:
问题复现
pass
验证修改结果
pass