1. 代码部分 : quantize_qwen3_coder_30b_a3b_instruct_gptq.py
import os########## 环境变量设置 ##########
# 当前可用的 CUDA 编号
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
# GPU 显存资源片段优化
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
# GPU 物理设备
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"import torchfrom datasets import load_dataset
from transformers import AutoTokenizer
from gptqmodel import GPTQModel, QuantizeConfig# 校准数据集路径 (公开代码生成 bigcode/the-stack 数据集的 python 代码部分数据集)
local_parquet_path = "./calibration_dataset/train-00000-of-00206.parquet"
# Qwen3-Coder-30B-A3B-Instruct 模型路径
model_name_or_path = "./models/Qwen3-Coder-30B-A3B-Instruct"
# 量化后模型保存路径
quantized_model_dir = "./models/Qwen3-Coder-30B-A3B-Instruct-GPTQ"# 量化配置
# 参考 gptqmodel 示例和文档进行调整
quantize_config = QuantizeConfig(bits=4,                  # 量化为 4-bitgroup_size=128,          # group size 128 依据模型的 config.json "head_dim": 128damp_percent=0.01,       # Dampeningdesc_act=False,          # 设为 False 可提升速度和兼容性static_groups=False,     # 不设置静态组sym=True,                # 对称量化true_sequential=True,    # 真正的顺序量化# 根据 gptqmodel 文档可能还有其他参数
)# 内存映射配置 (启用 CPU 卸载)
# 告诉 transformers / accelerate 如何分配 CPU 和 GPU 内存
max_memory = {1: "22GiB",       # 数字键值表示 GPU 编号,量化过程分配的 GPU 1 显存"cpu": "65GiB"    # 量化过程分配的 CPU 内存
}# 校准数据集配置
calibration_config = {"n_samples": 300,    # 校准样本数"seq_len": 1024,    # 序列长度"seed": 42,         # 随机种子
}########## 加载 tokenizer ##########
print("1. Loading tokenizer...")
# 使用 trust_remote_code=True (Qwen 系列模型通常需要)
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, use_fast=True, trust_remote_code=True)
# 如果词向量编码中没有 pad_token,则将 eos_token 给它
if tokenizer.pad_token is None:tokenizer.pad_token = tokenizer.eos_token########## 加载并准备校准数据集 ##########
print("2. Loading and preparing calibration dataset from local parquet file...")
try:n_samples = calibration_config["n_samples"]seq_len = calibration_config["seq_len"]seed = calibration_config["seed"]print(f"   Loading dataset from {local_parquet_path}...")# 加载本地 parquet 文件raw_datasets = load_dataset("parquet", data_files=local_parquet_path, split="train")print(f"   Total samples in file: {len(raw_datasets)}")# 随机打乱并选择样本print(f"   Shuffling and selecting {n_samples} samples...")raw_datasets = raw_datasets.shuffle(seed=seed).select(range(min(n_samples, len(raw_datasets))))########## tokenize function ##########def tokenize_function(example):"""对单个样本进行 Tokenize, 用于 GPTQ 的输入"""# 1. 获取文本内容,从 "content" 键获取代码文本text = example.get("content", "")# 2. 快速检查: 确保是字符串且非空if not isinstance(text, str) or not text.strip():# 如果不是字符串或为空,直接跳过return Nonetry:# 3. tokenize 文本#    设置 return_tensors=None 确保返回 Python List (通常是 List[List[int]])encodings = tokenizer(text,truncation=True,      # 超过 max_length 则截断padding=False,        # 不进行填充max_length=seq_len,   # 最大序列长度return_tensors=None,  # 返回 Python List)# 4. 提取 input_ids 和 attention_maskinput_ids = encodings["input_ids"]attention_mask = encodings["attention_mask"]# 5. 检查 input_ids 必须存在且是列表 (这一步会过滤掉所有不符合预期格式的样本)if not (isinstance(input_ids, list) and isinstance(attention_mask, list)):return None# 6. 检查数据长度必须足够if len(input_ids) != len(attention_mask) or len(input_ids) < 32:return None# 7. 截断到指定长度,虽然 truncation=True 已经处理了,但显式截断更安全input_ids = input_ids[:seq_len]attention_mask = attention_mask[:seq_len]# 8. 返回符合 gptqmodel 要求的格式: {"input_ids": List[int], "attention_mask": List[int]}# gptqmodel 内部会将这个列表转换为 tensorreturn {"input_ids": input_ids,"attention_mask": attention_mask}except Exception as e:# 6. 捕获任何在 tokenize 或处理过程中发生的意外错误,并跳过该样本#    这可以防止一个坏样本导致整个量化过程崩溃#    print(f"Warning: Skipping sample due to tokenization error: {e}")return None########## tokenize dataset ##########print("   Tokenizing dataset...")tokenized_datasets = raw_datasets.map(tokenize_function,batched=False,remove_columns=raw_datasets.column_names,   # 移除数据集原始列desc="Tokenizing the stack (Python)",)########## 过滤无效样本 ##########print("   Filtering tokenized dataset...")initial_count = len(tokenized_datasets)tokenized_datasets = tokenized_datasets.filter(lambda example: example is not None andisinstance(example["input_ids"], list) andlen(example["input_ids"]) >= 32)filtered_count = len(tokenized_datasets)print(f"   Samples after filtering: {filtered_count} (removed {initial_count - filtered_count})")########## 准备最终校准数据集格式 ##########print("   Formatting final calibration dataset...")calibration_dataset = []for sample in tokenized_datasets:input_ids_list = sample["input_ids"]attention_mask_list = sample["attention_mask"]# 最终检查并转换为 tensorif (isinstance(input_ids_list, list) andisinstance(attention_mask_list, list) andlen(input_ids_list) == len(attention_mask_list) andlen(input_ids_list) >= 32):try:tensor_input_ids = torch.tensor(input_ids_list, dtype=torch.long)tensor_attention_mask = torch.tensor(attention_mask_list, dtype=torch.long)calibration_dataset.append({"input_ids": tensor_input_ids, "attention_mask": tensor_attention_mask})except Exception:# 忽略无法转换为 tensor 的样本passprint(f"   Final calibration dataset prepared with {len(calibration_dataset)} samples.")if len(calibration_dataset) == 0:raise ValueError("Final calibration dataset is empty!")except Exception as e:print(f"Error during data loading / preparation: {e}")raise########## 加载模型 ##########
print("3. Loading model with memory mapping...")
try:# 使用 device_map="auto" 和 max_memory 自动管理内存分配model = GPTQModel.from_pretrained(model_name_or_path,quantize_config=quantize_config,device_map="auto",                # 自动分配设备,可以自动将模型卸载到 CPU 内存上,量化过程中 CPU-GPU 之间的数据交互max_memory=max_memory,            # 指定最大内存分配torch_dtype=torch.bfloat16,       # 使用模型精度 bfloat16 加载trust_remote_code=True,           # Qwen 系列通常需要# low_cpu_mem_usage=True,         # 尝试减少 CPU 内存峰值# offload_folder="offload",       # 如果需要,指定一个磁盘文件夹用于卸载)print("   Model loaded successfully.")
except Exception as e:print(f"Error loading model: {e}")raise########## 执行量化 ##########
print("4. Starting quantization process...")
try:model.quantize(calibration_dataset=calibration_dataset)print("   Quantization completed successfully.")
except Exception as e:print(f"Error during quantization: {e}")raise  # 重新抛出以停止########## 保存模型 ##########
print("5. Saving quantized model...")
try:model.save_quantized(quantized_model_dir)tokenizer.save_pretrained(quantized_model_dir)print(f"   Quantized model saved to {quantized_model_dir}.")
except Exception as e:print(f"Error saving model: {e}")raiseprint("All steps completed successfully!")
  1. 执行过程会报错:
    INFO -----------------------------------------------------------------------------------------------------------------------------------------
    INFO | gptq | 0 | mlp.experts.121.down_proj | 0.00020292 | 267 | 0.01000 | 0.206 | 16.782 | /48] 2.1%
    INFO -----------------------------------------------------------------------------------------------------------------------------------------
    INFO | gptq | 0 | mlp.experts.122.down_proj | 0.00045387 | 295 | 0.01000 | 0.203 | 16.782 | /48] 2.1%
    INFO -----------------------------------------------------------------------------------------------------------------------------------------
    INFO | gptq | 0 | mlp.experts.123.down_proj | 0.00005101 | 291 | 0.01000 | 0.208 | 16.782 | /48] 2.1%
    INFO -----------------------------------------------------------------------------------------------------------------------------------------
    INFO | gptq | 0 | mlp.experts.124.down_proj | 0.00336569 | 296 | 0.01000 | 0.269 | 16.782 | /48] 2.1%
    INFO -----------------------------------------------------------------------------------------------------------------------------------------
    INFO | gptq | 0 | mlp.experts.125.down_proj | 0.00214480 | 295 | 0.01000 | 0.203 | 16.782 | /48] 2.1%
    INFO -----------------------------------------------------------------------------------------------------------------------------------------
    INFO | gptq | 0 | mlp.experts.126.down_proj | 0.00106318 | 297 | 0.01000 | 0.205 | 16.782 | /48] 2.1%
    INFO -----------------------------------------------------------------------------------------------------------------------------------------
    INFO | gptq | 0 | mlp.experts.127.down_proj | 0.00021535 | 271 | 0.01000 | 0.207 | 16.782 | /48] 2.1%
    INFO -----------------------------------------------------------------------------------------------------------------------------------------
    Quantizing layer 1 of 47 [1 of 47] ██-----------------------------------------------------| 0:04:07 / 1:38:48 [2/48] 4.2%Error during quantization: The size of tensor a (32) must match the size of tensor b (128) at non-singleton dimension 3
    Traceback (most recent call last):
    File “~/Quantization/quantize_qwen3_coder_30b_a3b_instruct_gptq.py”, line 194, in
    model.quantize(calibration_dataset=calibration_dataset)

File “~/quantization/lib/python3.13/site-packages/gptqmodel/models/base.py”, line 450, in quantize
return module_looper.loop(
~~~~~~~~~~~~~~~~~~^
calibration_enable_gpu_cache=calibration_enable_gpu_cache,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
…<2 lines>…
backend=backend,
^^^^^^^^^^^^^^^^
)
^
File “~/quantization/lib/python3.13/site-packages/torch/utils/_contextlib.py”, line 120, in decorate_context
return func(*args, **kwargs)
File “~/quantization/lib/python3.13/site-packages/gptqmodel/looper/module_looper.py”, line 315, in loop
module(*layer_input) if is_lm_head_module else module(*layer_input,
~~~~~~^^^^^^^^^^^^^^
**additional_layer_inputs)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File “~/quantization/lib/python3.13/site-packages/transformers/modeling_layers.py”, line 94, in call
return super().call(*args, **kwargs)
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File “~/quantization/lib/python3.13/site-packages/torch/nn/modules/module.py”, line 1773, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File “~/quantization/lib/python3.13/site-packages/torch/nn/modules/module.py”, line 1784, in _call_impl
return forward_call(*args, **kwargs)
File “~/quantization/lib/python3.13/site-packages/transformers/models/qwen3_moe/modeling_qwen3_moe.py”, line 342, in forward
hidden_states, _ = self.self_attn(
~~~~~~~~~~~~~~^
hidden_states=hidden_states,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
…<5 lines>…
**kwargs,
^^^^^^^^^
)
^
File “~/quantization/lib/python3.13/site-packages/torch/nn/modules/module.py”, line 1773, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File “~/quantization/lib/python3.13/site-packages/torch/nn/modules/module.py”, line 1784, in _call_impl
return forward_call(*args, **kwargs)
File “~/quantization/lib/python3.13/site-packages/transformers/models/qwen3_moe/modeling_qwen3_moe.py”, line 167, in forward
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)

File “~/quantization/lib/python3.13/site-packages/transformers/models/qwen3_moe/modeling_qwen3_moe.py”, line 78, in apply_rotary_pos_emb
q_embed = (q * cos) + (rotate_half(q) * sin)
^~~
RuntimeError: The size of tensor a (32) must match the size of tensor b (128) at non-singleton dimension 3

参考 https://github.com/ModelCloud/GPTQModel/issues/1665 解决错误
将 modeling_qwen3_moe.py 中 Qwen3MoeDecoderLayer 类的 forward 改写如图
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/bicheng/92434.shtml
繁体地址,请注明出处:http://hk.pswp.cn/bicheng/92434.shtml
英文地址,请注明出处:http://en.pswp.cn/bicheng/92434.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于python、django的疫苗接种管理系统

基于python、django的疫苗接种管理系统

Go语言实战案例:使用sync.Map构建线程安全map

在并发编程中&#xff0c;共享资源的访问是一个绕不开的问题。Go 中的 map 在并发读写时是不安全的&#xff0c;直接使用可能导致程序 panic。因此&#xff0c;在多协程同时访问 Map 的场景下&#xff0c;必须采取有效的同步措施。本篇将通过一个实战案例&#xff0c;介绍 Go 的…

关于vue2中对接海康摄像头以及直播流rtsp或rtmp,后台ffmpeg转码后通过ws实现

最近项目中需要对接摄像头监控&#xff0c;海康摄像头为rtsp流格式有一个软件VLC media player&#xff0c;可以在线进行rtsp或者rtmp流播放&#xff0c;可用来测试流地址是否可用功能实现思路为后台通过fmpeg把rtsp流进行转码&#xff0c;然后通过ws方式进行一帧一帧推送。&am…

Docker容器强制删除及文件系统修复完整指南

Docker容器强制删除及文件系统修复完整指南 故障现象与原因分析 ​故障表现​&#xff1a; ERROR: for c9ca40be974d_OpIsosMD_OB unable to remove filesystem unlinkat /data/docker/storage/containers/c9ca40be974d...: structure needs cleaning​根本原因​&#xff1a;…

Matplotlib 知识点总结

1. 基础绘图&#xff08;plot函数&#xff09;基本语法&#xff1a;plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)功能特点&#xff1a;可绘制点、线和组合图形自动生成x轴&#xff08;0-N-1&#xff09;当x未指定时示例&#xff1a;绘制两点连线、多点不规则线等代码…

高可用微服务架构实战:Nacos集群+Nginx负载均衡,Spring Cloud无缝对接

"当你的注册中心挂了&#xff0c;整个微服务就变成了无头苍蝇。" 这是我在生产环境踩坑后最痛的领悟。今天&#xff0c;我将分享如何用Nacos集群Nginx搭建坚如磐石的注册中心&#xff0c;让你的微服务永不迷路&#xff01; 在 Windows 环境下配置 Nacos 集群&#x…

Spark大数据处理实战指南

Spark 简介 Apache Spark 是一个开源的分布式计算框架,专为大规模数据处理而设计。它通过内存计算和优化的执行引擎显著提升了数据处理速度,适用于批处理、实时流处理、机器学习和图计算等场景。 核心特性 高性能:利用内存计算(In-Memory Processing)减少磁盘 I/O,比传…

浏览器缓存机制全解析:强缓存与协商缓存

浏览器缓存是浏览器为提升页面加载速度、减少服务器压力和节省网络带宽&#xff0c;在本地存储资源&#xff08;如 HTML、CSS、JS、图片等&#xff09;的机制。其核心分为强缓存和协商缓存&#xff0c;并涉及多种 HTTP 头字段和存储位置。以下是详细解析&#xff1a;⚙️ 一、缓…

知识随记-----Qt 实用技巧:自定义倒计时按钮防止用户频繁点击

Qt 技巧&#xff1a;实现自定义倒计时按钮防止用户频繁点击注册 项目场景 在一个基于 Qt 开发的聊天应用中&#xff0c;用户注册时需要获取验证码。为防止用户频繁点击获取验证码按钮&#xff0c;需要实现一个倒计时功能&#xff0c;用户点击后按钮进入倒计时状态&#xff0c;倒…

Linux与Windows应急响应

本人首先进行了linux的应急响应&#xff0c;windows之后再进行 Linux与Windows应急响应初体验1 linux应急响应1.1 账户&#xff1a;1.1.1 使用cat /etc/passwd命令查看passwd文件2.1.2 使用cat /etc/shadow命令查找shadow文件&#xff0c;该文件为密码文件的存储项1.2 入侵排查…

计算机网络1-4:计算机网络的定义和分类

目录 计算机网络的定义 计算机网络的分类 计算机网络的定义 计算机网络的分类 按交换技术分类&#xff1a;电路交换网络、报文交换网络、分组交换网络 按使用者分类&#xff1a;公用网、专用网 按传输介质分类&#xff1a;有线网络、无线网络 按覆盖范围分类&#xff1a;…

在QT中动态添加/删除控件,伸缩因子该怎么处理

开发中遇到的问题[TOC](开发中遇到的问题)处理方式在我们的界面开发过程中&#xff0c;通常需要开发一些可以动态添加or删除控件的容器&#xff0c;类似Tab页一样&#xff0c;为了美观的话&#xff0c;我们通常使用伸缩因子将容器中的控件往一个方向挤&#xff0c;类似下面的控…

【设计模式精解】什么是代理模式?彻底理解静态代理和动态代理

目录 静态代理 动态代理 JDK动态代理 CGLIB代理 JDK动态代理和CGLIB代理的区别 总结 代理模式简单来说就是 我们使用代理对象来代替对真实对象(real object)的访问&#xff0c;这样就可以在不修改原目标对象的前提下&#xff0c;扩展目标对象的功能。 代理模式有静态代理…

MCU AI/ML - 弥合智能和嵌入式系统之间的差距

作者&#xff1a;芯科科技产品营销高级经理Gopinath Krishniah 人工智能&#xff08;AI&#xff09;和机器学习&#xff08;ML&#xff09;是使系统能够从数据中学习、进行推理并随着时间的推移提高性能的关键技术。这些技术通常用于大型数据中心和功能强大的GPU&#xff0c;但…

Redis中的sdshdr的len和alloc那块的知识点详解

文章目录核心比喻&#xff1a;一个可以伸缩的水瓶场景一&#xff1a;创建一个新字符串场景二&#xff1a;追加字符串&#xff08;触发“空间预分配”&#xff09;场景三&#xff1a;再次追加字符串&#xff08;利用空闲空间&#xff09;场景四&#xff1a;缩短字符串&#xff0…

在Linux下访问MS SQL Server数据库

Linux作为一个免费的Unix类操作系统&#xff0c;以其开放性源代码、多任务、X window等特点为众多的用户所采用&#xff0c;并有很多企业采用Linux来作为其内部网的全功能服务器(WWW&#xff0c;FTP&#xff0c;Email、DNS)。企业的内部网不仅要提供文本信息的访问&#xff0c;…

计算机视觉-OpenCV

一下载第三方库opencv-python3.4.18.65opencv-contrib-python3.4.18.65import cv2 # 读取的格式是BGR numpy import numpy as np# 读取图片 a cv2.imread(generated_image.jpg) # 读取图片 print(a) # NumPy数组&#xff0c;其中存储了读取的图像文件的像素值。cv2.imshow…

解决GitHub无法打开

找到下图文件&#xff0c;用记事本打开 在最下方粘贴如下代码140.82.113.4 github.com 20.205.243.166 github.com 140.82.112.4 github.com 151.101.1.6 github.global.ssl.fastly.net 185.199.108.153 assets-cdn.github.com 185.199.109.153 assets-cdn.github.com 185.199.…

AWS VPC Transit Gateway 可观测最佳实践

AWS VPC Transit Gateway 介绍 Amazon VPC Transit Gateway 是一个网络传输中心&#xff0c;用于互连虚拟私有云 (VPCs) 和本地网络。随着您的云基础设施在全球扩展&#xff0c;区域间对等互连使用 AWS 全球基础设施将中转网关连接在一起。 AWS 数据中心之间的所有网络流量都在…

WeakRef的作用和使用

文章目录WeakRef的作用和使用使用 WeakRef 避免强引用&#xff1a;原理与实践一、WeakRef 的核心特性二、WeakRef 与强引用的对比三、WeakRef 的使用场景与示例1. 非关键数据缓存&#xff08;避免缓存导致内存泄漏&#xff09;2. 跟踪对象生命周期&#xff08;不干扰回收&#…