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

ms-swift 4.3.0 中如何注册自定义Loss呢

Open wkchao opened this issue 6 months ago • 5 comments

Checklist / 检查清单

  • [x] I have searched existing issues, and this is a new question or discussion topic. / 我已经搜索过现有的 issues,确认这是一个新的问题与讨论。

Question Description / 问题描述

文档中写道:

Loss的mapping文件可以参考[这里](https://github.com/modelscope/ms-swift/blob/main/swift/loss/mapping.py)。 swift支持自定义loss(当前只支持sft/pretrain/reranker/embedding任务),注册后在训练时设置--loss_type <loss-name>使用你定制的loss方法。

自定义Loss需继承自BaseLoss,并实现__call__方法,返回标量Tensor。你可以参考[CustomCrossEntropyLoss](https://github.com/modelscope/ms-swift/blob/0d7c9f5bc0e7e7d67d914ce6edeb9ce24f60746f/swift/loss/causal_lm.py#L5)进行定制。例如:

class CustomLoss(BaseLoss):

    def __call__(self, outputs, labels, **kwargs) -> torch.Tensor:
        pass

但是未提及如何在外部注册(可能是我没找到?只有一些旧版本文档中有)这个loss函数到swift中来支持命令行调用,目前是直接在swift源码loss中实现的损失函数再在mapping中指定,也可以做到

wkchao avatar May 28 '26 09:05 wkchao

自定义损失函数的.py文件在使用时通过--external_plugins参数导入: swift sft
--external_plugins /path/to/plugin.py
--loss_type my_loss
# ... 其中--loss_type对应的值为loss_map中注册的自定义损失函数对应key;lose_scale同理,需要注册在loss_scale_map中。

z0o0ey avatar Jul 27 '26 08:07 z0o0ey

自定义损失函数的.py文件在使用时通过--external_plugins参数导入: swift sft --external_plugins /path/to/plugin.py --loss_type my_loss # ... 其中--loss_type对应的值为loss_map中注册的自定义损失函数对应key;lose_scale同理,需要注册在loss_scale_map中。

这个方法支持megatron sft吗?

jianhai0527 avatar Aug 14 '26 08:08 jianhai0527

megatron 目前需要改动 trainer 里的 loss_func, 未来会支持更简单的自定义逻辑

hjh0119 avatar Aug 14 '26 08:08 hjh0119

This issue has been inactive for over 3 months and will be automatically closed in 7 days. If this issue is still relevant, please reply to this message.

github-actions[bot] avatar Nov 13 '26 00:11 github-actions[bot]

This issue has been automatically closed due to inactivity. If needed, it can be reopened.

github-actions[bot] avatar Nov 21 '26 00:11 github-actions[bot]