使用 gptqmodel 量化 Qwen3-Coder-30B-A3B-Instruct

  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;不干擾回收&#…