Skip to content

PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度

9.4 KB
Raw Blame
{
 "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": "ec237436",
   "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 = \"vllm-sr/d3-mini\"\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": "ec12fa86",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Configure optimization parameters for the AutoRound / SignRound algorithm\n",
    "alg_config = SignRoundConfig(\n",
    "    iters=1200,      # 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=4,                     # Batch size for calibration; kept < 8 to avoid slow execution/high memory overhead\n",
    "    gradient_accumulate_steps=2,      # Set to 8 / batch_size to maintain an effective global batch size of 8; smaller values risk accuracy drop    \n",
    "    seqlen=4096,                      # 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",
    ")"
   ]
  },
  {
   "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",
    "    # Custom scripts & modeling code\n",
    "    \"modeling_d3.py\",\n",
    "    \"pipeline_d3.py\",\n",
    "    \"d3_engine.py\",\n",
    "    \"d3_fast.py\",\n",
    "    \"d3_format.py\",\n",
    "    \"d3_kernels.py\",\n",
    "    \"d3_runtime.py\",\n",
    "    \"d3_server.py\",\n",
    "    # Dedicated readout head weights & configs\n",
    "    \"readout.safetensors\",\n",
    "    \"decision_config.json\",\n",
    "    \"MODEL_MANIFEST.json\",\n",
    "    # Templates & preprocessing configs\n",
    "    \"chat_template.jinja\",\n",
    "    \"video_preprocessor_config.json\",\n",
    "    \"requirements.txt\",\n",
    "]\n",
    "\n",
    "# Note: Uses w4g32 to match your TUNING_CONFIG group_size: 32\n",
    "export_subdirs = [\n",
    "    os.path.join(OUTPUT_BASE_DIR, \"local_model-w4g32/auto-round-auto-gptq\"),\n",
    "]\n",
    "\n",
    "for export_dir in export_subdirs:\n",
    "    if os.path.exists(export_dir):\n",
    "        print(f\"\\n--> Injecting d3-edge custom runtime 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}\")\n",
    "    else:\n",
    "        print(f\"\\n--> Target export directory not found: {export_dir}\")"
   ]
  },
  {
   "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\"),\n",
    "        f\"{base_name}-W4A16-AutoRound\",\n",
    "        hf_token,\n",
    "    )\n",
    "\n",
    "else:\n",
    "    print(\"No Hugging Face token found. Skipping upload.\")"
   ]
  }
 ],
 "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
}