You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Transformers的trainer.py的compute_loss中打印labels值?

解决Transformers Trainer中compute_loss打印labels无效的方法

以下几种方法可以尝试解决print和logger.info无法输出labels的问题:

  • 强制刷新输出缓冲:print时加上flush=True参数,避免输出被缓冲积压不显示:

    print(labels, flush=True)
    
  • 转换张量为可打印格式:labels通常是PyTorch/TensorFlow张量,直接打印可能被截断或无法正常显示,先转成numpy数组或列表:

    # PyTorch环境
    print(labels.detach().cpu().numpy(), flush=True)
    # TensorFlow环境
    print(labels.numpy(), flush=True)
    
  • 切换到标准错误输出:如果训练时stdout被重定向到日志文件,stderr通常会直接输出到终端:

    import sys
    print(labels, file=sys.stderr, flush=True)
    
  • 调整日志级别并使用debug日志:如果用logger,先全局调低日志等级,再用debug级别输出:

    # 训练前添加日志配置
    import logging
    logging.basicConfig(level=logging.DEBUG)
    
    # 在compute_loss中使用
    logger.debug(labels.detach().cpu().numpy())
    
  • 关闭tqdm进度条:进度条的动态刷新可能会覆盖print输出,初始化Trainer时关闭tqdm:

    trainer = Trainer(
        # 其他参数
        disable_tqdm=True
    )
    

内容的提问来源于stack exchange,提问作者Charlene Fung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 14:37:33