PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "19aa22cb",
"metadata": {},
"outputs": [],
"source": [
"# %pip install --upgrade transformers --break-system-packages"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dc47bad2",
"metadata": {},
"outputs": [],
"source": [
"# %pip install auto-round --break-system-packages"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c18b96a7",
"metadata": {},
"outputs": [],
"source": [
"# %pip install git+https://github.com/sustcsonglin/flash-linear-attention.git --no-build-isolation --break-system-packages"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9a5a3569",
"metadata": {},
"outputs": [],
"source": [
"# %pip install git+https://github.com/Dao-AILab/causal-conv1d.git --no-build-isolation --break-system-packages"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "df0ee49b",
"metadata": {},
"outputs": [],
"source": [
"# %pip install compressed-tensors --break-system-packages"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a8040c46",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import shutil\n",
"\n",
"import torch\n",
"from auto_round import AutoRound, SignRoundConfig\n",
"from huggingface_hub import HfApi, create_repo, get_token, notebook_login\n",
"from transformers import AutoModelForImageTextToText, AutoProcessor"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1cddaebc",
"metadata": {},
"outputs": [],
"source": [
"os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6517109c",
"metadata": {},
"outputs": [],
"source": [
"print(f\"PyTorch Version: {torch.__version__}\")\n",
"print(f\"CUDA Available: {torch.cuda.is_available()}\")\n",
"\n",
"if torch.cuda.is_available():\n",
" print(f\"CUDA Version: {torch.version.cuda}\")\n",
" print(f\"GPU Name: {torch.cuda.get_device_name(0)}\")\n",
" print(f\"VRAM: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f} GB\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4920035b",
"metadata": {},
"outputs": [],
"source": [
"notebook_login()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "48b05d64",
"metadata": {},
"outputs": [],
"source": [
"MODEL_ID = \"Cloudflare/clef-flash\"\n",
"HF_USER = \"your_hf_username\" # Replace with your Hugging Face username\n",
"OUTPUT_BASE_DIR = \"./AutoRound\"\n",
"LOCAL_PATH = \"./local_model\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1b1c02ea",
"metadata": {},
"outputs": [],
"source": [
"!hf download $MODEL_ID --local-dir $LOCAL_PATH"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f99b1719",
"metadata": {},
"outputs": [],
"source": [
"model = AutoModelForImageTextToText.from_pretrained(\n",
" LOCAL_PATH, dtype=torch.bfloat16, device_map=\"auto\"\n",
")\n",
"processor = AutoProcessor.from_pretrained(LOCAL_PATH)\n",
"\n",
"tokenizer = processor.tokenizer\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "00d0a924",
"metadata": {},
"outputs": [],
"source": [
"# Configure optimization parameters for the AutoRound / SignRound algorithm\n",
"alg_config = SignRoundConfig(\n",
" iters=800, # Optimization iterations per block; balances calibration time and accuracy\n",
" group_size=32, # Number of weights sharing one scale. Cannot go below 32 (vLLM's GPTQ kernel won't run it). Only use 16 if targeting NVFP4.\n",
" sym=True, # Symmetric quantization; enables faster compute and broader engine compatibility\n",
")\n",
"\n",
"# Initialize the AutoRound quantization pipeline\n",
"ar = AutoRound(\n",
" model=model, # Target pretrained model to be quantized\n",
" tokenizer=tokenizer, # Tokenizer used to process text calibration samples\n",
" processor=processor, # Processor for multimodal models (vision/audio), if present\n",
" scheme=\"W4A16\", # Quantization precision: 4-bit weights and 16-bit activations\n",
" alg_configs=alg_config, # Applies the algorithm-specific optimization settings defined above\n",
" nsamples=512, # Total calibration dataset samples to maintain quality and avoid overfitting\n",
" batch_size=2, # Batch size for calibration; kept < 8 to avoid slow execution/high memory overhead\n",
" gradient_accumulate_steps=4, # Set to 8 / batch_size to maintain an effective global batch size of 8; smaller values risk accuracy drop \n",
" seqlen=2048, # Calibration context length; captures long-range dependency activations\n",
" low_gpu_mem_usage=False, # Keeps modules on GPU to maximize speed if sufficient VRAM is available\n",
" quant_nontext_module=False, # Leaves non-text modules (e.g., vision encoders) unquantized to protect precision\n",
" enable_torch_compile=True, # Compiles forward passes using torch.compile to accelerate calibration\n",
" ignore_layers=\"linear_attn,mtp,visual\", # Specific layer-level overrides and exemptions\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ec12fa86",
"metadata": {},
"outputs": [],
"source": [
"# Quantize once and export to disk across all major loader schemas\n",
"ar.quantize_and_save(\n",
" OUTPUT_BASE_DIR,\n",
" # Serializes weights to 3 formats simultaneously to guarantee compatibility:\n",
" # - 'auto_round': Reference AutoRound format (vLLM GPTQ/Marlin, Transformers / native loader)\n",
" # - 'auto_gptq': AutoGPTQ tensor layout (vLLM GPTQ/Marlin, TGI)\n",
" format=\"auto_round,auto_gptq\",\n",
" # Overwrites weights in-place to avoid extra VRAM allocation\n",
" inplace=True\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9177f7b1",
"metadata": {},
"outputs": [],
"source": [
"# Files that must accompany the quantized backbone for downstream inference\n",
"auxiliary_files = [\n",
" \"joint_head.safetensors\",\n",
" \"joint_head_config.json\",\n",
" \"joint_schema_model.py\",\n",
" \"chat_template.jinja\",\n",
"]\n",
"\n",
"export_subdirs = [\n",
" os.path.join(OUTPUT_BASE_DIR, \"local_model-w4g32/auto-round-auto-gptq\"),\n",
" os.path.join(OUTPUT_BASE_DIR, \"local_model-w4g32/auto-gptq\"),\n",
"]\n",
"\n",
"for export_dir in export_subdirs:\n",
" if os.path.exists(export_dir):\n",
" print(f\"\\n--> Injecting Clef joint head assets into: {export_dir}\")\n",
" for filename in auxiliary_files:\n",
" src = os.path.join(LOCAL_PATH, filename)\n",
" dst = os.path.join(export_dir, filename)\n",
" if os.path.exists(src):\n",
" shutil.copy2(src, dst)\n",
" print(f\" Copied: {filename}\")\n",
" else:\n",
" print(f\" Warning: Missing {src}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "97d4d929",
"metadata": {},
"outputs": [],
"source": [
"def push_to_hub(local_dir, repo_name, token):\n",
" if not os.path.exists(local_dir):\n",
" print(f\"[Hub] Directory not found, skipping: {local_dir}\")\n",
" return\n",
"\n",
" full_repo_id = f\"{HF_USER}/{repo_name}\"\n",
" try:\n",
" api = HfApi()\n",
" print(f\"[Hub] Preparing repo: {full_repo_id}...\")\n",
" create_repo(\n",
" full_repo_id, repo_type=\"model\", private=False, token=token, exist_ok=True\n",
" )\n",
"\n",
" print(f\"[Hub] Uploading folder from {local_dir}...\")\n",
" api.upload_folder(\n",
" folder_path=local_dir, repo_id=full_repo_id, repo_type=\"model\", token=token\n",
" )\n",
" print(f\"[Hub] Upload complete: https://huggingface.co/{full_repo_id}\")\n",
" except Exception as e:\n",
" print(f\"[Hub] Error uploading {full_repo_id}: {e}\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dd65ece3",
"metadata": {},
"outputs": [],
"source": [
"base_name = MODEL_ID.split(\"/\")[-1]\n",
"hf_token = get_token()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c699c57c",
"metadata": {},
"outputs": [],
"source": [
"if hf_token:\n",
" push_to_hub(\n",
" os.path.join(OUTPUT_BASE_DIR, \"local_model-w4g32/auto-round-auto-gptq\"),\n",
" f\"{base_name}-W4A16-AutoRound\",\n",
" hf_token,\n",
" )\n",
" push_to_hub(\n",
" os.path.join(OUTPUT_BASE_DIR, \"local_model-w4g32/auto-gptq\"),\n",
" f\"{base_name}-W4A16-AutoRound-GPTQ\",\n",
" hf_token,\n",
" )\n",
"\n",
"else:\n",
" print(\"No Hugging Face token found. Skipping upload to hub.\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}