训练的Loss和输出突然全是nan【小白找bug】

某一天,我重新跑了两天之前正常跑的代码,训练的Loss和输出突然全是nan(从epoch0就是nan了),我惊慌失措。我的代码是关于微调llama的,于是我开始找问题,在输入进入llama之前都是没问题的,进入llama的输出变成了nan,所以有可能是llama本身的数值有问题,我是用下载好的llama权重文件初始化的,可以使用简单的程序验证一下是不是下载的权重文件的问题:

python 复制代码
import torch
import transformers
from transformers import LlamaForCausalLM, LlamaTokenizer
from transformers import pipeline


model_dir = "/llama/"  # 权重文件的路径

model = LlamaForCausalLM.from_pretrained (model_dir)
tokenizer = LlamaTokenizer.from_pretrained (model_dir)

print(type(model))
for name, param in model.named_parameters():
    if torch.isnan(param).any():
        print(f"Parameter {name} contains NaN")
    if torch.isinf(param).any():
        print(f"Parameter {name} contains Inf")
    if param.abs().max() > 1e6:  # 值过大可能导致数值溢出
        print(f"Parameter {name} has very large values: {param.abs().max()}")

pipeline = transformers.pipeline (
          "text-generation",
          model=model,
          tokenizer=tokenizer,
          torch_dtype=torch.float16,
          device_map="auto",
          )

sequences = pipeline (
          'I have tomatoes, basil and cheese at home. What can I cook for dinner?\n',
          do_sample=True,
          top_k=10,
          num_return_sequences=1,
          eos_token_id=tokenizer.eos_token_id,
          max_length=400,
          )

for seq in sequences:
    print (f"{seq ['generated_text']}")

运行这个程序后,有的param确实是NaN和Inf,也报错了。但是我刚下载完llama权重时候运行这个程序是没问题的。

确认就是llama权重文件的问题。

只能使用convert_llama_weights_to_hf.py再转换一份权重文件了。运行这个代码的时候又报错了:

python 复制代码
ImportError: cannot import name 'TikTokenConverter' from 'transformers.convert_slow_tokenizer'

于是只好重新安装transformers,不报错了

python 复制代码
pip install git+https://github.com/huggingface/transformers

注意安装transformer的命令并不是pip install transformers==xxx版本,我一开始这样安装都没解决报错。

后记:很奇怪,可能是服务器磁盘坏了一小块?我不理解,两天前没毛病,两天后全是毛病,心累,哭/(ㄒoㄒ)/~~

相关推荐
iAm_Ike13 小时前
Go 中自定义类型与基础类型间的显式类型转换详解
jvm·数据库·python
iuvtsrt13 小时前
Golang怎么实现方法集与接口的匹配_Golang如何理解值类型和指针类型实现接口的区别【详解】
jvm·数据库·python
旦莫14 小时前
AI驱动的纯视觉自动化测试:知识库里应该积累什么知识内容
人工智能·python·测试开发·pytest·ai测试
知识领航员15 小时前
蘑兔AI音乐深度实测:功能拆解、实测表现与适用场景
java·c语言·c++·人工智能·python·算法·github
如何原谅奋力过但无声16 小时前
【灵神高频面试题合集06-08】反转链表、快慢指针(环形链表/重排链表)、前后指针(删除链表/链表去重)
数据结构·python·算法·leetcode·链表
deephub16 小时前
2026 RAG 选型指南:Vector、Graph、Vectorless 该怎么挑
人工智能·python·大语言模型·rag
倔强的胖蚂蚁18 小时前
主流大模型使用指南:Gemma/Llama 全流程
云原生·llama
狐狐生风18 小时前
使用 UV 创建并运行 Python 项目(完整步骤)
python·uv
噜噜噜阿鲁~18 小时前
python学习笔记 | 9.2、模块-安装第三方模块
笔记·python·学习
现代野蛮人18 小时前
【深度学习】 —— VGG-16 网络实现猫狗识别
网络·人工智能·python·深度学习·tensorflow