【大模型】通义千问safetensors_rust.SafetensorError: Error while deserializing header: HeaderTooLarge解决方法

文章介绍了在使用通义千问模型时遇到的SafetensorError:HeaderTooLarge问题,提供了两种解决方法:一是通过modelscope安装模型,二是直接下载特定版本的Qwen-14B-Chat-Int8模型。同时,文中还给出了模型的要求和下载、推理的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【大模型】通义千问safetensors_rust.SafetensorError: Error while deserializing header: HeaderTooLarge解决方法

通义千问介绍

GitHub:https://github.com/QwenLM/Qwen

Requirements

  • python 3.8及以上版本
  • pytorch 1.12及以上版本,推荐2.0及以上版本
  • 建议使用CUDA 11.4及以上(GPU用户、flash-attention用户等需考虑此选项)

模型下载

git clone https://www.modelscope.cn/qwen/Qwen-7B-Chat.git

模型推理

infer_qwen.py:

from modelscope import AutoModelForCausalLM, AutoTokenizer
from modelscope import GenerationConfig

# Note: The default behavior now has injection attack prevention off.
tokenizer = AutoTokenizer.from_pretrained("qwen/Qwen-7B-Chat", trust_remote_code=True)

# use bf16
# model = AutoModelForCausalLM.from_pretrained("qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True, bf16=True).eval()
# use fp16
# model = AutoModelForCausalLM.from_pretrained("qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True, fp16=True).eval()
# use cpu only
# model = AutoModelForCausalLM.from_pretrained("qwen/Qwen-7B-Chat", device_map="cpu", trust_remote_code=True).eval()
# use auto mode, automatically select precision based on the device.
model = AutoModelForCausalLM.from_pretrained("qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True).eval()

# Specify hyperparameters for generation. But if you use transformers>=4.32.0, there is no need to do this.
# model.generation_config = GenerationConfig.from_pretrained("Qwen/Qwen-7B-Chat", trust_remote_code=True) # 可指定不同的生成长度、top_p等相关超参

# 第一轮对话 1st dialogue turn
response, history = model.chat(tokenizer, "你好", history=None)
print(response)

# 第二轮对话 2nd dialogue turn
response, history = model.chat(tokenizer, "给我讲一个年轻人奋斗创业最终取得成功的故事。", history=history)
print(response)

# 第三轮对话 3rd dialogue turn
response, history = model.chat(tokenizer, "给这个故事起一个标题", history=history)
print(response)

执行推理时报错如下:

root:/workspace/tmp/LLM# python infer_qwen.py
2023-12-16 01:35:43,760 - modelscope - INFO - PyTorch version 2.0.1 Found.
2023-12-16 01:35:43,762 - modelscope - INFO - TensorFlow version 2.10.0 Found.
2023-12-16 01:35:43,762 - modelscope - INFO - Loading ast index from /root/.cache/modelscope/ast_indexer
2023-12-16 01:35:43,883 - modelscope - INFO - Loading done! Current index file version is 1.9.1, with md5 5f21e812815a5fbb6ced75f40587fe94 and a total number of 924 components indexed
The model is automatically converting to bf16 for faster inference. If you want to disable the automatic precision, please manually add bf16/fp16/fp32=True to "AutoModelForCausalLM.from_pretrained".
Try importing flash-attention for faster inference...
Warning: import flash_attn rotary fail, please install FlashAttention rotary to get higher efficiency https://github.com/Dao-AILab/flash-attention/tree/main/csrc/rotary
Warning: import flash_attn rms_norm fail, please install FlashAttention layer_norm to get higher efficiency https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm
Warning: import flash_attn fail, please install FlashAttention to get higher efficiency https://github.com/Dao-AILab/flash-attention
Loading checkpoint shards:   0%|                                                                                                        | 0/8 [00:00<?, ?it/s]
Traceback (most recent call last):
  File "/workspace/tmp/LLM/infer_qwen.py", line 13, in <module>
    model = AutoModelForCausalLM.from_pretrained(model_path, device_map="cpu", trust_remote_code=True).eval()
  File "/usr/local/lib/python3.10/dist-packages/modelscope/utils/hf_util.py", line 171, in from_pretrained
    module_obj = module_class.from_pretrained(model_dir, *model_args,
  File "/usr/local/lib/python3.10/dist-packages/transformers/models/auto/auto_factory.py", line 479, in from_pretrained
    return model_class.from_pretrained(
  File "/usr/local/lib/python3.10/dist-packages/modelscope/utils/hf_util.py", line 72, in from_pretrained
    return ori_from_pretrained(cls, model_dir, *model_args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/transformers/modeling_utils.py", line 2881, in from_pretrained
    ) = cls._load_pretrained_model(
  File "/usr/local/lib/python3.10/dist-packages/transformers/modeling_utils.py", line 3214, in _load_pretrained_model
    state_dict = load_state_dict(shard_file)
  File "/usr/local/lib/python3.10/dist-packages/transformers/modeling_utils.py", line 450, in load_state_dict
    with safe_open(checkpoint_file, framework="pt") as f:
safetensors_rust.SafetensorError: Error while deserializing header: HeaderTooLarge

解决方法

先 pip 安装 modelscope

# python
from modelscope import snapshot_download
model_dir = snapshot_download('qwen/Qwen-7B-Chat')

下载过程如下:
在这里插入图片描述
就看网速了,慢慢等待。。。

解决方法2

先安装:

apt-get install git-lfs

再下载:

 git clone https://www.modelscope.cn/qwen/Qwen-14B-Chat-Int8.git

下载等待:
在这里插入图片描述
这里会等待比较久,就看网速了。。。

如果出现下面的错误:

fatal: destination path 'Qwen-14B-Chat-Int8' already exists and is not an empty directory.

执行:

rm -rf Qwen-14B-Chat-Int8
root@autodl-container-8bf9409db0-3243e00c:~/autodl-tmp# python utils_one.py 2025-06-04 22:18:14,601 - __main__ - INFO - 初始化对话评估系统... 2025-06-04 22:18:14,602 - __main__ - INFO - 加载嵌入模型: /root/autodl-tmp/paraphrase-multilingual-MiniLM-L12-v2 2025-06-04 22:18:16,425 - __main__ - INFO - 嵌入模型加载成功,设备: cuda 2025-06-04 22:18:16,426 - __main__ - INFO - 加载生成模型: /root/autodl-tmp/Qwen3-14b 2025-06-04 22:18:16,651 - accelerate.utils.modeling - INFO - We will use 90% of the memory on device 0 for storing the model, and 10% for the buffer to avoid OOM. You can set `max_memory` in to a higher value to use more memory (at your own risk). Loading checkpoint shards: 67%|██████████████████████████████████████████████████████████████████████████████████████████████████████▋ | 4/6 [00:03<00:01, 1.27it/s] 2025-06-04 22:18:19,830 - __main__ - ERROR - 生成模型加载失败: Error while deserializing header: MetadataIncompleteBuffer 2025-06-04 22:18:19,830 - __main__ - ERROR - 生成模型加载失败: Error while deserializing header: MetadataIncompleteBuffer 2025-06-04 22:18:19,830 - __main__ - ERROR - 评估系统初始化失败: Error while deserializing header: MetadataIncompleteBuffer Traceback (most recent call last): File "/root/autodl-tmp/utils_one.py", line 482, in <module> evaluator = DialogueEvaluator( ^^^^^^^^^^^^^^^^^^ File "/root/autodl-tmp/utils_one.py", line 231, in __init__ self.dialogue_generator = DialogueGenerator(gen_model_path, device) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/root/autodl-tmp/utils_one.py", line 88, in __init__ self.model = AutoModelForCausalLM.from_pretrained( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/root/miniconda3/lib/python3.12/site-packages/transformers/models/auto/auto_factory.py", line 571, in from_pretrained return model_class.from_pretrained( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/root/miniconda3/lib/python3.12/site-packages/transformers/modeling_utils.py", line 279, in _wrapper return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/root/miniconda3/lib/python3.12/site-packages/transformers/modeling_utils.py", line 4400, in from_pretrained ) = cls._load_pretrained_model( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/root/miniconda3/lib/python3.12/site-packages/transformers/modeling_utils.py", line 4818, in _load_pretrained_model state_dict = load_state_dict( ^^^^^^^^^^^^^^^^ File "/root/miniconda3/lib/python3.12/site-packages/transformers/modeling_utils.py", line 513, in load_state_dict with safe_open(checkpoint_file, framework="pt") as f: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ safetensors_rust.SafetensorError: Error while deserializing header: MetadataIncompleteBuffer
最新发布
06-05
<think>嗯,用户现在遇到了一个模型加载题,显示错误“safetensors_rust.SafetensorError:Errorwhiledeserializingheader:MetadataIncompleteBuffer”。这个题出现于尝试加载一个生成模型时,用户在引用中提供了错误信息和一些相关资料。用户似乎在使用HuggingFaceTransformers库,并且尝试从本地加载模型。在引用中看到两个关键点:第一是版本兼容性题,transformers4.46.1和safetensors0.4.5可能存在冲突;第二是文件头部的元数据缓冲区不完整导致解析失败。需要思考几个可能的解决方案路径。版本题往往是最常见的根源,尤其是当库依赖更新不及时时。用户使用的transformers版本可能太旧,而safetensors库较新,可能引入了新特性导致旧版本transformer兼容性出题。升级transformer到较新版本是值得尝试的方案。另一个可能性是模型文件在下载过程中损坏。大型模型文件在传输中断可能导致元数据区损坏。建议用户重新下载模型或者重新导出模型文件。还有一个思路是尝试使用不同加载方式。用户可能在用from_pretrained加载模型,可以改为直接使用PyTorch加载权重,或者强制使用.pt格式来绕过safetensors解析器。此外,用户环境方面也值得关注。如果使用虚拟环境,可能存在多个版本库混杂的题。考虑用户升级版本后是否可能引入其他兼容性题,需要提醒用户创建新的环境测试。</think> 好的,这个`MetadataIncompleteBuffer`错误通常表示模型文件(`.safetensors`)的**头部元数据**在读取时遇到了不完整的数据缓冲区,无法正确解析文件结构。这往往与**文件损坏、文件未完全下载/传输、或者safetensors库版本兼容性题**有关。 以下是针对`Error while deserializing header: MetadataIncompleteBuffer`的详细解决步骤: ### 1. 验证文件完整性与重新下载/传输 (首要步骤) * **检查文件大小:** 对比你本地`.safetensors`文件的大小是否与官方源(如Hugging Face Hub上的文件页面)提供的文件大小**完全一致**。任何大小差异都表明文件未完全下载或传输中断/出错。 * **校验哈希值(推荐):** 如果模型源提供了文件哈希值(如sha256),使用命令行工具计算本地文件的哈希值并进行比较。 * `Linux/macOS:` `shasum -a 256 /path/to/your/model.safetensors` * `Windows (PowerShell):` `Get-FileHash -Path 'C:\path\to\your\model.safetensors' -Algorithm SHA256` * 不同哈希值确认文件损坏或下载不完整。 * **重新下载/传输:** * **官方源下载:** 直接从模型仓库(如Hugging Face Hub)重新下载对应的`.safetensors`文件。下载时确保网络稳定,避免中断。 * **本地传输:** 如果是本地机器之间拷贝导致的题,尝试重新拷贝一次,或者考虑使用`rsync`(Linux/macOS)等支持校验的工具,避免使用可能不可靠的图形界面传输工具。 * **替代模型格式:** 如果源仓库同时提供了`PyTorch`格式(`.bin`或`.pth`等)的模型文件,尝试下载和使用这种格式。在使用`AutoModelForCausalLM.from_pretrained`时,库会自动优先查找`.safetensors`,但如果找不到或出题,它会回退加载`PyTorch`格式的权重。只需确保`model`目录下有`pytorch_model.bin`等相关文件。 ### 2. 升级关键库版本 (解决可能的兼容性Bug) `MetadataIncompleteBuffer`错误在一些特定的库版本组合下更容易出现,尤其是在较新的模型文件格式与旧版库之间。更新是最稳妥的解决兼容性题的方法。 * **升级`transformers`库:** ```bash pip install --upgrade transformers ``` * 使用最新稳定版通常是兼容性最好的。 * **升级`safetensors`库:** ```bash pip install --upgrade safetensors ``` * 这是处理`.safetensors`文件的核心库,其更新往往修复读取/解析错误。 * **考虑`huggingface-hub`库:** ```bash pip install --upgrade huggingface-hub ``` * 虽然不是直接原因,但它负责模型下载和部分缓存管理,保持最新也有助于减少潜在题。 ### 3. 排除文件特定部分题 如果上述方法无效,且你怀疑模型文件的元数据部分可能有不常见的格式(虽然可能性较小): * **尝试其他模型文件:** * 下载仓库中另一个已知工作正常的`.safetensors`文件,看是否能加载。这能判断题是全局性的(库、环境)还是特定于你这个模型文件的。 * **使用`safetensors`命令行工具检查:** * 安装`safetensors`后,可以用其自带的命令行工具检查文件: ```bash safetensors <path/to/your/model.safetensors> ``` * 如果文件损坏或不完整,这个命令通常会报出更明确的错误信息。 ### 4. 尝试强制加载PyTorch格式 (如果文件损坏但PyTorch格式可用) 如果模型目录下同时存在`pytorch_model.bin`等权重文件,并且它们是完整的,你可以尝试**强制`from_pretrained`加载PyTorch格式文件**,而不是`.safetensors`。设置参数`use_safetensors=False`: ```python from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained( '/path/to/local/model', # 确保路径指向包含 config.json 和其他文件的目录 use_safetensors=False # 强制不使用 safetensors ) ``` ### 5. 提交错误报告 如果上述所有方法**都尝试过后仍然失败**: 1. 确认环境纯净(在新虚拟环境里测试)。 2. 提供**详细的版本信息**(`transformers`, `safetensors`, `torch`, `Python`)。 3. 提供 **加载代码片段**。 4. 描述 **你已尝试过的所有解决方案**。 5. 确认**文件完整性检查**。 6. 在`transformers`库的GitHub仓库或Hugging Face论坛提交Issue。 ### 总结步骤优先级建议 1. **立即验证并重新下载模型文件(最关键!)。** 2. **升级`transformers`和`safetensors`到最新版。** 3. 如果本地有完整的PyTorch格式权重,尝试`use_safetensors=False`加载。 4. 检查`safetensors`命令行工具的输出。 5. 如果失败且已排除文件和版本题,考虑提交详细错误报告。 遇到`MetadataIncompleteBuffer`错误通常意味着文件本身存在题或者库版本过旧,优先关注文件完整性和升级库通常能解决题[^1][^2][^3]。 --- **相关题** 1. `.safetensors`文件比`.bin`(PyTorch格式)有哪些优势?加载速度更快吗? 2. 如何安全地断点续传下载大型模型文件以避免损坏? 3. 创建Python虚拟环境来管理机器学习项目依赖有什么好处?如何操作? 4. 除了`MetadataIncompleteBuffer`,加载`.safetensors`文件还可能遇到哪些常见错误?如何解决? 5. 为什么Hugging Face大力推广`.safetensors`格式? [^1]: 参考:Transformers导入本地模型显示safetensors_rust.SafetensorError: Error while deserializing header: HeaderTooLarge_transformers4.46.1与safetensors0.4.5兼容版本号-优快云博客 [^2]: safetensors_rust.SafetensorError: Error while deserializing header: HeaderTooLarge... [详细错误栈] [^3]: safetensors_rust.SafetensorError: Error while deserializing header: MetadataIncompleteBuffer... [链接到相关讨论]
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

szZack

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值