解决Llama-2模型生成文本报错:RuntimeError: Expected tensor for argument #1 'indices' to have one of the following scalar types
解决Llama-2模型生成文本报错:RuntimeError: Expected tensor for argument #1 'indices' to have one of the following scalar types
在使用Llama-2模型生成文本时,你可能会遇到以下错误:
RuntimeError: Expected tensor for argument #1 'indices' to have one of the following scalar types: Long, Int; but got torch.FloatTensor instead (while checking arguments for embedding)
这个错误是由于model.generate函数的输入inputs.input_ids的数据类型不正确导致的。embedding函数要求输入的索引数据类型为Long或Int,而你可能将inputs.input_ids的数据类型转换为了torch.float32。
解决方法
要解决这个问题,你需要将inputs.input_ids的数据类型转换回Long或Int。你可以使用inputs.input_ids.long()或inputs.input_ids.int()将其转换为Long或Int类型。
下面是修改后的代码:
import torch
from modelscope import snapshot_download, Model
from modelscope.models.nlp.llama2 import Llama2Tokenizer
model_dir = snapshot_download('modelscope/Llama-2-7b-ms', revision='v1.0.1', ignore_file_pattern=[r'\w+\.safetensors'])
model = Model.from_pretrained(model_dir, device_map='auto', torch_dtype=torch.float32, offload_folder='path/to/offload_folder')
tokenizer = Llama2Tokenizer.from_pretrained(model_dir)
prompt = 'Hey, are you conscious? Can you talk to me?'
inputs = tokenizer(prompt, return_tensors='pt')
inputs.input_ids = inputs.input_ids.long() # 将input_ids转换为Long数据类型
# Generate
generate_ids = model.generate(inputs.input_ids, max_length=30)
print(tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0])
注意
- 我将
inputs.input_ids的数据类型转换为了Long。你可以根据需要选择Long或Int类型。 - 请确保你已经安装了必要的库,例如
torch、modelscope和transformers。 - 如果问题仍然存在,请检查你的代码中其他部分是否存在数据类型转换错误。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/qwK0 著作权归作者所有。请勿转载和采集!