PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
Add quantization recipe notebooks for Qwen, OCR, and edge models (#2488)
Vishva R504aea5c77c5
diff --git a/examples/Cloudflare-clef/clef-flash_W4A16.ipynb b/examples/Cloudflare-clef/clef-flash_W4A16.ipynbnew file mode 100644index 000000000..8b9705543--- /dev/null+++ b/examples/Cloudflare-clef/clef-flash_W4A16.ipynb@@ -0,0 +1,311 @@+{+ "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",+ " 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+}diff --git a/examples/Cloudflare-clef/clef_W4A16.ipynb b/examples/Cloudflare-clef/clef_W4A16.ipynbnew file mode 100644index 000000000..fcfa9e6a4--- /dev/null+++ b/examples/Cloudflare-clef/clef_W4A16.ipynb@@ -0,0 +1,311 @@+{+ "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": "e749726c",+ "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\"\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=64, # 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",+ " 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-w4g64/auto-round-auto-gptq\"),\n",+ " os.path.join(OUTPUT_BASE_DIR, \"local_model-w4g64/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+}diff --git a/examples/DotsOCR/DotsmOCR_W4A16.ipynb b/examples/DotsOCR/DotsmOCR_W4A16.ipynbnew file mode 100644index 000000000..275b0cd60--- /dev/null+++ b/examples/DotsOCR/DotsmOCR_W4A16.ipynb@@ -0,0 +1,254 @@+{+ "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": "dacc255f",+ "metadata": {},+ "outputs": [],+ "source": [+ "# %pip install compressed-tensors --break-system-packages"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "a8040c46",+ "metadata": {},+ "outputs": [],+ "source": [+ "import os\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 AutoModelForCausalLM, AutoProcessor\n"+ ]+ },+ {+ "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 = \"dots-studio/dots.mocr\"\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 = AutoModelForCausalLM.from_pretrained(\n",+ " LOCAL_PATH, dtype=torch.bfloat16, device_map=\"auto\", trust_remote_code=True\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": [+ "\n",+ "# Configure optimization parameters for the AutoRound / SignRound algorithm\n",+ "alg_config = SignRoundConfig(\n",+ " iters=1000, # 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",+ " 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",+ " enable_torch_compile=True, # Compiles forward passes using torch.compile to accelerate calibration\n",+ " quant_nontext_module=False, # Leaves non-text modules (e.g., vision encoders) unquantized to protect precision\n",+ ")\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": "97d4d929",+ "metadata": {},+ "outputs": [],+ "source": [+ "def push_to_hub(local_dir, repo_name, token):\n",+ " \"\"\"Creates repo and uploads folder to Hugging Face.\"\"\"\n",+ " full_repo_id = f\"{HF_USER}/{repo_name}\"\n",+ " print(f\"\\n[Hub] Pushing {local_dir} to {full_repo_id}...\")\n",+ "\n",+ " try:\n",+ " api = HfApi()\n",+ " create_repo(\n",+ " full_repo_id, repo_type=\"model\", exist_ok=True, private=False, token=token\n",+ " )\n",+ "\n",+ " api.upload_folder(\n",+ " folder_path=local_dir, repo_id=full_repo_id, repo_type=\"model\", token=token\n",+ " )\n",+ " print(f\"[Hub] ✅ Successfully uploaded: https://huggingface.co/{full_repo_id}\")\n",+ " except Exception as e: # noqa: BLE001\n",+ " print(f\"[Hub] ❌ Error uploading: {e}\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "6022046c",+ "metadata": {},+ "outputs": [],+ "source": [+ "base_name = MODEL_ID.split(\"/\")[-1]\n",+ "hf_token = get_token()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "38aba13d",+ "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+}diff --git a/examples/LightOnOCR/LightOnOCR-3-0.8B_W4A16.ipynb b/examples/LightOnOCR/LightOnOCR-3-0.8B_W4A16.ipynbnew file mode 100644index 000000000..70c786d8b--- /dev/null+++ b/examples/LightOnOCR/LightOnOCR-3-0.8B_W4A16.ipynb@@ -0,0 +1,280 @@+{+ "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": "3ba94694",+ "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": "71ca5b44",+ "metadata": {},+ "outputs": [],+ "source": [+ "# %pip install compressed-tensors --break-system-packages"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "a8040c46",+ "metadata": {},+ "outputs": [],+ "source": [+ "import os\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\n"+ ]+ },+ {+ "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 = \"lightonai/LightOnOCR-3-0.8B\"\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": [+ "\n",+ "# 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",+ " 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",+ " enable_torch_compile=True, # Compiles forward passes using torch.compile to accelerate calibration\n",+ " quant_nontext_module=False, # Leaves non-text modules (e.g., vision encoders) unquantized to protect precision\n",+ ")\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",+ " # - 'llm_compressor': Compressed-tensors schema (vLLM / Neural Magic)\n",+ " format=\"auto_round,auto_gptq,llm_compressor\",\n",+ " # Overwrites weights in-place to avoid extra VRAM allocation\n",+ " inplace=True\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "97d4d929",+ "metadata": {},+ "outputs": [],+ "source": [+ "def push_to_hub(local_dir, repo_name, token):\n",+ " \"\"\"Creates repo and uploads folder to Hugging Face.\"\"\"\n",+ " full_repo_id = f\"{HF_USER}/{repo_name}\"\n",+ " print(f\"\\n[Hub] Pushing {local_dir} to {full_repo_id}...\")\n",+ "\n",+ " try:\n",+ " api = HfApi()\n",+ " create_repo(\n",+ " full_repo_id, repo_type=\"model\", exist_ok=True, private=False, token=token\n",+ " )\n",+ "\n",+ " api.upload_folder(\n",+ " folder_path=local_dir, repo_id=full_repo_id, repo_type=\"model\", token=token\n",+ " )\n",+ " print(f\"[Hub] ✅ Successfully uploaded: https://huggingface.co/{full_repo_id}\")\n",+ " except Exception as e:\n",+ " print(f\"[Hub] ❌ Error uploading: {e}\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "6022046c",+ "metadata": {},+ "outputs": [],+ "source": [+ "base_name = MODEL_ID.split(\"/\")[-1]\n",+ "hf_token = get_token()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "38aba13d",+ "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",+ " push_to_hub(\n",+ " os.path.join(OUTPUT_BASE_DIR, \"local_model-w4g32/llm-compressor-wint-a16\"),\n",+ " f\"{base_name}-W4A16-AutoRound-LLM-Compressor\",\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+}diff --git a/examples/LightOnOCR/LightOnOCR-3-4B_W4A16.ipynb b/examples/LightOnOCR/LightOnOCR-3-4B_W4A16.ipynbnew file mode 100644index 000000000..5ab1885a8--- /dev/null+++ b/examples/LightOnOCR/LightOnOCR-3-4B_W4A16.ipynb@@ -0,0 +1,280 @@+{+ "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": "a4c518fb",+ "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": "71ca5b44",+ "metadata": {},+ "outputs": [],+ "source": [+ "# %pip install compressed-tensors --break-system-packages"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "a8040c46",+ "metadata": {},+ "outputs": [],+ "source": [+ "import os\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\n"+ ]+ },+ {+ "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 = \"lightonai/LightOnOCR-3-4B\"\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": [+ "\n",+ "# 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",+ " 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",+ " enable_torch_compile=True, # Compiles forward passes using torch.compile to accelerate calibration\n",+ " quant_nontext_module=False, # Leaves non-text modules (e.g., vision encoders) unquantized to protect precision\n",+ ")\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",+ " # - 'llm_compressor': Compressed-tensors schema (vLLM / Neural Magic)\n",+ " format=\"auto_round,auto_gptq,llm_compressor\",\n",+ " # Overwrites weights in-place to avoid extra VRAM allocation\n",+ " inplace=True\n",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "97d4d929",+ "metadata": {},+ "outputs": [],+ "source": [+ "def push_to_hub(local_dir, repo_name, token):\n",+ " \"\"\"Creates repo and uploads folder to Hugging Face.\"\"\"\n",+ " full_repo_id = f\"{HF_USER}/{repo_name}\"\n",+ " print(f\"\\n[Hub] Pushing {local_dir} to {full_repo_id}...\")\n",+ "\n",+ " try:\n",+ " api = HfApi()\n",+ " create_repo(\n",+ " full_repo_id, repo_type=\"model\", exist_ok=True, private=False, token=token\n",+ " )\n",+ "\n",+ " api.upload_folder(\n",+ " folder_path=local_dir, repo_id=full_repo_id, repo_type=\"model\", token=token\n",+ " )\n",+ " print(f\"[Hub] ✅ Successfully uploaded: https://huggingface.co/{full_repo_id}\")\n",+ " except Exception as e:\n",+ " print(f\"[Hub] ❌ Error uploading: {e}\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "6022046c",+ "metadata": {},+ "outputs": [],+ "source": [+ "base_name = MODEL_ID.split(\"/\")[-1]\n",+ "hf_token = get_token()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "38aba13d",+ "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",+ " push_to_hub(\n",+ " os.path.join(OUTPUT_BASE_DIR, \"local_model-w4g32/llm-compressor-wint-a16\"),\n",+ " f\"{base_name}-W4A16-AutoRound-LLM-Compressor\",\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+}diff --git a/examples/LiquidAI/LiquidAId3B_W4A16.ipynb b/examples/LiquidAI/LiquidAId3B_W4A16.ipynbnew file mode 100644index 000000000..cabfa2e15--- /dev/null+++ b/examples/LiquidAI/LiquidAId3B_W4A16.ipynb@@ -0,0 +1,289 @@+{+ "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": "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\n"+ ]+ },+ {+ "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 = \"LiquidAI/d1-3B\"\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": [+ "\n",+ "# 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",+ " 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",+ " enable_torch_compile=False, # Compiles forward passes using torch.compile to accelerate calibration\n",+ " quant_nontext_module=False, # Leaves non-text modules (e.g., vision encoders) unquantized to protect precision\n",+ ")\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",+ " # - 'auto_round': Reference AutoRound format (Transformers / native loader)\n",+ " format=\"auto_round\",\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 required for remote code execution, tokenization, and processor initialization\n",+ "auxiliary_files: list[str] = [\n",+ " # Custom architecture / remote code execution\n",+ " \"modeling_d1.py\",\n",+ " \"lfm2_vl.py\",\n",+ " \"hybrid.py\",\n",+ " \"api.py\",\n",+ " \"runner.py\",\n",+ " \"prompt.py\",\n",+ " \"LICENSE\",\n",+ "]\n",+ "\n",+ "export_subdirs: list[str] = [\n",+ " os.path.join(OUTPUT_BASE_DIR, \"local_model-w4g32\"),\n",+ "]\n",+ "\n",+ "for export_dir in export_subdirs:\n",+ " if not os.path.exists(export_dir):\n",+ " continue\n",+ "\n",+ " print(f\"\\n--> Injecting inference 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",+ "\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\"),\n",+ " f\"{base_name}-W4A16-AutoRound\",\n",+ " hf_token,\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+}diff --git a/examples/Qwen3.5/Qwen3.5-0.8B_NVFP4.ipynb b/examples/Qwen3.5/Qwen3.5-0.8B_NVFP4.ipynbnew file mode 100644index 000000000..12baac191--- /dev/null+++ b/examples/Qwen3.5/Qwen3.5-0.8B_NVFP4.ipynb@@ -0,0 +1,272 @@+{+ "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": "1ecf0f22",+ "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": "dacc255f",+ "metadata": {},+ "outputs": [],+ "source": [+ "# %pip install compressed-tensors --break-system-packages"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "a8040c46",+ "metadata": {},+ "outputs": [],+ "source": [+ "import os\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 safetensors import safe_open\n",+ "from transformers import AutoModelForImageTextToText, AutoProcessor\n"+ ]+ },+ {+ "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 = \"Qwen/Qwen3.5-0.8B\"\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": "b8cbe572",+ "metadata": {},+ "outputs": [],+ "source": [+ "\n",+ "# Configure optimization parameters for the AutoRound / SignRound algorithm\n",+ "alg_config = SignRoundConfig(\n",+ " iters=1000, # Optimization iterations per block; balances calibration time and accuracy\n",+ " group_size=16, # Number of weights sharing one scale. Use 16 when 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=\"NVFP4\", # NVIDIA FP4 quantization format for reduced memory usage and accelerated inference on supported hardware\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, # Calibration batch size; balances processing speed and GPU memory usage\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=False, # Disables torch.compile to avoid the NVFP4/static warning\n",+ " ignore_layers=\"linear_attn,mtp,visual\", # Excludes linear-attention, MTP, and visual modules from quantization\n",+ " layer_config={\n",+ " \"mtp\": {\"data_type\": \"bfloat16\"}, # Keeps the MTP module in BF16 precision\n",+ " \"mtp.fc\": {\"data_type\": \"bfloat16\"}, # Keeps the MTP fully connected layer in BF16 precision\n",+ " }, # Preserves BF16 precision for the specified MTP layers\n",+ ")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "ec12fa86",+ "metadata": {},+ "outputs": [],+ "source": [+ "# Quantize once and export to disk using the recommended schema for NVFP4\n",+ "ar.quantize_and_save(\n",+ " OUTPUT_BASE_DIR,\n",+ " # Use 'llm_compressor' for the compressed-tensors schema, recommended for NVFP4 inference with vLLM / Neural Magic\n",+ " format=\"llm_compressor\",\n",+ " # Overwrites weights in-place to avoid extra VRAM allocation\n",+ " inplace=True,\n",+ ")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "97d4d929",+ "metadata": {},+ "outputs": [],+ "source": [+ "def push_to_hub(local_dir, repo_name, token):\n",+ " \"\"\"Creates repo and uploads folder to Hugging Face.\"\"\"\n",+ " full_repo_id = f\"{HF_USER}/{repo_name}\"\n",+ " print(f\"\\n[Hub] Pushing {local_dir} to {full_repo_id}...\")\n",+ "\n",+ " try:\n",+ " api = HfApi()\n",+ " create_repo(\n",+ " full_repo_id, repo_type=\"model\", exist_ok=True, private=False, token=token\n",+ " )\n",+ "\n",+ " api.upload_folder(\n",+ " folder_path=local_dir, repo_id=full_repo_id, repo_type=\"model\", token=token\n",+ " )\n",+ " print(f\"[Hub] ✅ Successfully uploaded: https://huggingface.co/{full_repo_id}\")\n",+ " except Exception as e:\n",+ " print(f\"[Hub] ❌ Error uploading: {e}\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "6022046c",+ "metadata": {},+ "outputs": [],+ "source": [+ "base_name = MODEL_ID.split(\"/\")[-1]\n",+ "hf_token = get_token()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "38aba13d",+ "metadata": {},+ "outputs": [],+ "source": [+ "if hf_token:\n",+ " push_to_hub(\n",+ " os.path.join(OUTPUT_BASE_DIR, \"local_model-nvfp-w4g16\"),\n",+ " f\"{base_name}-W4A16-AutoRound-NVFP4\",\n",+ " hf_token,\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+}diff --git a/examples/Qwen3.5/Qwen3.5-2B_NVFP4.ipynb b/examples/Qwen3.5/Qwen3.5-2B_NVFP4.ipynbnew file mode 100644index 000000000..84b796c8c--- /dev/null+++ b/examples/Qwen3.5/Qwen3.5-2B_NVFP4.ipynb@@ -0,0 +1,272 @@+{+ "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": "1ecf0f22",+ "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": "dacc255f",+ "metadata": {},+ "outputs": [],+ "source": [+ "# %pip install compressed-tensors --break-system-packages"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "a8040c46",+ "metadata": {},+ "outputs": [],+ "source": [+ "import os\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 safetensors import safe_open\n",+ "from transformers import AutoModelForImageTextToText, AutoProcessor\n"+ ]+ },+ {+ "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 = \"Qwen/Qwen3.5-2B\"\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": "b8cbe572",+ "metadata": {},+ "outputs": [],+ "source": [+ "\n",+ "# Configure optimization parameters for the AutoRound / SignRound algorithm\n",+ "alg_config = SignRoundConfig(\n",+ " iters=1000, # Optimization iterations per block; balances calibration time and accuracy\n",+ " group_size=16, # Number of weights sharing one scale. Use 16 when 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=\"NVFP4\", # NVIDIA FP4 quantization format for reduced memory usage and accelerated inference on supported hardware\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, # Calibration batch size; balances processing speed and GPU memory usage\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=False, # Disables torch.compile to avoid the NVFP4/static warning\n",+ " ignore_layers=\"linear_attn,mtp,visual\", # Excludes linear-attention, MTP, and visual modules from quantization\n",+ " layer_config={\n",+ " \"mtp\": {\"data_type\": \"bfloat16\"}, # Keeps the MTP module in BF16 precision\n",+ " \"mtp.fc\": {\"data_type\": \"bfloat16\"}, # Keeps the MTP fully connected layer in BF16 precision\n",+ " }, # Preserves BF16 precision for the specified MTP layers\n",+ ")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "ec12fa86",+ "metadata": {},+ "outputs": [],+ "source": [+ "# Quantize once and export to disk using the recommended schema for NVFP4\n",+ "ar.quantize_and_save(\n",+ " OUTPUT_BASE_DIR,\n",+ " # Use 'llm_compressor' for the compressed-tensors schema, recommended for NVFP4 inference with vLLM / Neural Magic\n",+ " format=\"llm_compressor\",\n",+ " # Overwrites weights in-place to avoid extra VRAM allocation\n",+ " inplace=True,\n",+ ")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "97d4d929",+ "metadata": {},+ "outputs": [],+ "source": [+ "def push_to_hub(local_dir, repo_name, token):\n",+ " \"\"\"Creates repo and uploads folder to Hugging Face.\"\"\"\n",+ " full_repo_id = f\"{HF_USER}/{repo_name}\"\n",+ " print(f\"\\n[Hub] Pushing {local_dir} to {full_repo_id}...\")\n",+ "\n",+ " try:\n",+ " api = HfApi()\n",+ " create_repo(\n",+ " full_repo_id, repo_type=\"model\", exist_ok=True, private=False, token=token\n",+ " )\n",+ "\n",+ " api.upload_folder(\n",+ " folder_path=local_dir, repo_id=full_repo_id, repo_type=\"model\", token=token\n",+ " )\n",+ " print(f\"[Hub] ✅ Successfully uploaded: https://huggingface.co/{full_repo_id}\")\n",+ " except Exception as e:\n",+ " print(f\"[Hub] ❌ Error uploading: {e}\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "6022046c",+ "metadata": {},+ "outputs": [],+ "source": [+ "base_name = MODEL_ID.split(\"/\")[-1]\n",+ "hf_token = get_token()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "38aba13d",+ "metadata": {},+ "outputs": [],+ "source": [+ "if hf_token:\n",+ " push_to_hub(\n",+ " os.path.join(OUTPUT_BASE_DIR, \"local_model-nvfp-w4g16\"),\n",+ " f\"{base_name}-W4A16-AutoRound-NVFP4\",\n",+ " hf_token,\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+}diff --git a/examples/Qwen3.5/Qwen3.5-4B_NVFP4.ipynb b/examples/Qwen3.5/Qwen3.5-4B_NVFP4.ipynbnew file mode 100644index 000000000..ca2123e9b--- /dev/null+++ b/examples/Qwen3.5/Qwen3.5-4B_NVFP4.ipynb@@ -0,0 +1,272 @@+{+ "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": "1ecf0f22",+ "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": "dacc255f",+ "metadata": {},+ "outputs": [],+ "source": [+ "# %pip install compressed-tensors --break-system-packages"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "a8040c46",+ "metadata": {},+ "outputs": [],+ "source": [+ "import os\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 safetensors import safe_open\n",+ "from transformers import AutoModelForImageTextToText, AutoProcessor\n"+ ]+ },+ {+ "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 = \"Qwen/Qwen3.5-4B\"\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": "b8cbe572",+ "metadata": {},+ "outputs": [],+ "source": [+ "\n",+ "# Configure optimization parameters for the AutoRound / SignRound algorithm\n",+ "alg_config = SignRoundConfig(\n",+ " iters=1000, # Optimization iterations per block; balances calibration time and accuracy\n",+ " group_size=16, # Number of weights sharing one scale. Use 16 when 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=\"NVFP4\", # NVIDIA FP4 quantization format for reduced memory usage and accelerated inference on supported hardware\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, # Calibration batch size; balances processing speed and GPU memory usage\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=False, # Disables torch.compile to avoid the NVFP4/static warning\n",+ " ignore_layers=\"linear_attn,mtp,visual\", # Excludes linear-attention, MTP, and visual modules from quantization\n",+ " layer_config={\n",+ " \"mtp\": {\"data_type\": \"bfloat16\"}, # Keeps the MTP module in BF16 precision\n",+ " \"mtp.fc\": {\"data_type\": \"bfloat16\"}, # Keeps the MTP fully connected layer in BF16 precision\n",+ " }, # Preserves BF16 precision for the specified MTP layers\n",+ ")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "ec12fa86",+ "metadata": {},+ "outputs": [],+ "source": [+ "# Quantize once and export to disk using the recommended schema for NVFP4\n",+ "ar.quantize_and_save(\n",+ " OUTPUT_BASE_DIR,\n",+ " # Use 'llm_compressor' for the compressed-tensors schema, recommended for NVFP4 inference with vLLM / Neural Magic\n",+ " format=\"llm_compressor\",\n",+ " # Overwrites weights in-place to avoid extra VRAM allocation\n",+ " inplace=True,\n",+ ")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "97d4d929",+ "metadata": {},+ "outputs": [],+ "source": [+ "def push_to_hub(local_dir, repo_name, token):\n",+ " \"\"\"Creates repo and uploads folder to Hugging Face.\"\"\"\n",+ " full_repo_id = f\"{HF_USER}/{repo_name}\"\n",+ " print(f\"\\n[Hub] Pushing {local_dir} to {full_repo_id}...\")\n",+ "\n",+ " try:\n",+ " api = HfApi()\n",+ " create_repo(\n",+ " full_repo_id, repo_type=\"model\", exist_ok=True, private=False, token=token\n",+ " )\n",+ "\n",+ " api.upload_folder(\n",+ " folder_path=local_dir, repo_id=full_repo_id, repo_type=\"model\", token=token\n",+ " )\n",+ " print(f\"[Hub] ✅ Successfully uploaded: https://huggingface.co/{full_repo_id}\")\n",+ " except Exception as e:\n",+ " print(f\"[Hub] ❌ Error uploading: {e}\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "6022046c",+ "metadata": {},+ "outputs": [],+ "source": [+ "base_name = MODEL_ID.split(\"/\")[-1]\n",+ "hf_token = get_token()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "38aba13d",+ "metadata": {},+ "outputs": [],+ "source": [+ "if hf_token:\n",+ " push_to_hub(\n",+ " os.path.join(OUTPUT_BASE_DIR, \"local_model-nvfp-w4g16\"),\n",+ " f\"{base_name}-W4A16-AutoRound-NVFP4\",\n",+ " hf_token,\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+}diff --git a/examples/Qwen3.5/Qwen3.5-9B_NVFP4.ipynb b/examples/Qwen3.5/Qwen3.5-9B_NVFP4.ipynbnew file mode 100644index 000000000..ef9dcdd1b--- /dev/null+++ b/examples/Qwen3.5/Qwen3.5-9B_NVFP4.ipynb@@ -0,0 +1,272 @@+{+ "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": "1ecf0f22",+ "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": "dacc255f",+ "metadata": {},+ "outputs": [],+ "source": [+ "# %pip install compressed-tensors --break-system-packages"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "a8040c46",+ "metadata": {},+ "outputs": [],+ "source": [+ "import os\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 safetensors import safe_open\n",+ "from transformers import AutoModelForImageTextToText, AutoProcessor\n"+ ]+ },+ {+ "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 = \"Qwen/Qwen3.5-9B\"\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": "b8cbe572",+ "metadata": {},+ "outputs": [],+ "source": [+ "\n",+ "# Configure optimization parameters for the AutoRound / SignRound algorithm\n",+ "alg_config = SignRoundConfig(\n",+ " iters=1000, # Optimization iterations per block; balances calibration time and accuracy\n",+ " group_size=16, # Number of weights sharing one scale. Use 16 when 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=\"NVFP4\", # NVIDIA FP4 quantization format for reduced memory usage and accelerated inference on supported hardware\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, # Calibration batch size; balances processing speed and GPU memory usage\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=False, # Disables torch.compile to avoid the NVFP4/static warning\n",+ " ignore_layers=\"linear_attn,mtp,visual\", # Excludes linear-attention, MTP, and visual modules from quantization\n",+ " layer_config={\n",+ " \"mtp\": {\"data_type\": \"bfloat16\"}, # Keeps the MTP module in BF16 precision\n",+ " \"mtp.fc\": {\"data_type\": \"bfloat16\"}, # Keeps the MTP fully connected layer in BF16 precision\n",+ " }, # Preserves BF16 precision for the specified MTP layers\n",+ ")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "ec12fa86",+ "metadata": {},+ "outputs": [],+ "source": [+ "# Quantize once and export to disk using the recommended schema for NVFP4\n",+ "ar.quantize_and_save(\n",+ " OUTPUT_BASE_DIR,\n",+ " # Use 'llm_compressor' for the compressed-tensors schema, recommended for NVFP4 inference with vLLM / Neural Magic\n",+ " format=\"llm_compressor\",\n",+ " # Overwrites weights in-place to avoid extra VRAM allocation\n",+ " inplace=True,\n",+ ")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "97d4d929",+ "metadata": {},+ "outputs": [],+ "source": [+ "def push_to_hub(local_dir, repo_name, token):\n",+ " \"\"\"Creates repo and uploads folder to Hugging Face.\"\"\"\n",+ " full_repo_id = f\"{HF_USER}/{repo_name}\"\n",+ " print(f\"\\n[Hub] Pushing {local_dir} to {full_repo_id}...\")\n",+ "\n",+ " try:\n",+ " api = HfApi()\n",+ " create_repo(\n",+ " full_repo_id, repo_type=\"model\", exist_ok=True, private=False, token=token\n",+ " )\n",+ "\n",+ " api.upload_folder(\n",+ " folder_path=local_dir, repo_id=full_repo_id, repo_type=\"model\", token=token\n",+ " )\n",+ " print(f\"[Hub] ✅ Successfully uploaded: https://huggingface.co/{full_repo_id}\")\n",+ " except Exception as e:\n",+ " print(f\"[Hub] ❌ Error uploading: {e}\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "6022046c",+ "metadata": {},+ "outputs": [],+ "source": [+ "base_name = MODEL_ID.split(\"/\")[-1]\n",+ "hf_token = get_token()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "38aba13d",+ "metadata": {},+ "outputs": [],+ "source": [+ "if hf_token:\n",+ " push_to_hub(\n",+ " os.path.join(OUTPUT_BASE_DIR, \"local_model-nvfp-w4g16\"),\n",+ " f\"{base_name}-W4A16-AutoRound-NVFP4\",\n",+ " hf_token,\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+}diff --git a/examples/Qwen3.8/Qwen3_8_27B_W4A16.ipynb b/examples/Qwen3.8/Qwen3_8_27B_W4A16.ipynbnew file mode 100644index 000000000..a53d6e7c8--- /dev/null+++ b/examples/Qwen3.8/Qwen3_8_27B_W4A16.ipynb@@ -0,0 +1,279 @@+{+ "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": "1ecf0f22",+ "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": "3d2005ae",+ "metadata": {},+ "outputs": [],+ "source": [+ "# %pip install compressed-tensors --break-system-packages"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "a8040c46",+ "metadata": {},+ "outputs": [],+ "source": [+ "import os\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 = \"Qwen/Qwen3.8-27B\"\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": [+ "\n",+ "# Configure optimization parameters for the AutoRound / SignRound algorithm\n",+ "alg_config = SignRoundConfig(\n",+ " iters=600, # Optimization iterations per block; balances calibration time and accuracy\n",+ " group_size=64, # 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; reduced to manage GPU memory usage on 48GB VRAM\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",+ " enable_torch_compile=True, # Compiles forward passes using torch.compile to accelerate calibration\n",+ " quant_nontext_module=False, # Leaves non-text modules (e.g., vision encoders) unquantized to protect precision\n",+ " ignore_layers=\"linear_attn,mtp,visual\", # Specific layer-level overrides and exemptions\n",+ " layer_config={\n",+ " \"mtp\": {\"data_type\": \"bfloat16\"}, # Keeps the MTP module in BF16 precision\n",+ " \"mtp.fc\": {\"data_type\": \"bfloat16\"}, # Keeps the MTP fully connected layer in BF16 precision\n",+ " }, # Preserves BF16 precision for the specified MTP layers\n",+ ")\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": "97d4d929",+ "metadata": {},+ "outputs": [],+ "source": [+ "def push_to_hub(local_dir, repo_name, token):\n",+ " \"\"\"Creates repo and uploads folder to Hugging Face.\"\"\"\n",+ " full_repo_id = f\"{HF_USER}/{repo_name}\"\n",+ " print(f\"\\n[Hub] Pushing {local_dir} to {full_repo_id}...\")\n",+ "\n",+ " try:\n",+ " api = HfApi()\n",+ " create_repo(\n",+ " full_repo_id, repo_type=\"model\", exist_ok=True, private=False, token=token\n",+ " )\n",+ "\n",+ " api.upload_folder(\n",+ " folder_path=local_dir, repo_id=full_repo_id, repo_type=\"model\", token=token\n",+ " )\n",+ " print(f\"[Hub] ✅ Successfully uploaded: https://huggingface.co/{full_repo_id}\")\n",+ " except Exception as e:\n",+ " print(f\"[Hub] ❌ Error uploading: {e}\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "6022046c",+ "metadata": {},+ "outputs": [],+ "source": [+ "base_name = MODEL_ID.split(\"/\")[-1]\n",+ "hf_token = get_token()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "38aba13d",+ "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+}diff --git a/examples/vLLM-sr/d3-edge_W4A16.ipynb b/examples/vLLM-sr/d3-edge_W4A16.ipynbnew file mode 100644index 000000000..ff51b7364--- /dev/null+++ b/examples/vLLM-sr/d3-edge_W4A16.ipynb@@ -0,0 +1,318 @@+{+ "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": "1b826c71",+ "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\n"+ ]+ },+ {+ "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-edge\"\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=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",+ " 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": "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",+ " # - 'auto_round': Reference AutoRound format (Transformers / native loader)\n",+ " format=\"auto_round\",\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",+ " # 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+}diff --git a/examples/vLLM-sr/d3-lite_W4A16.ipynb b/examples/vLLM-sr/d3-lite_W4A16.ipynbnew file mode 100644index 000000000..399cebc9b--- /dev/null+++ b/examples/vLLM-sr/d3-lite_W4A16.ipynb@@ -0,0 +1,318 @@+{+ "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": "22106e62",+ "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-lite\"\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": "8b088f2f",+ "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",+ " 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": "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",+ " # - 'auto_round': Reference AutoRound format (Transformers / native loader)\n",+ " format=\"auto_round\",\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",+ " # 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+}diff --git a/examples/vLLM-sr/d3-mini_W4A16.ipynb b/examples/vLLM-sr/d3-mini_W4A16.ipynbnew file mode 100644index 000000000..245426f7f--- /dev/null+++ b/examples/vLLM-sr/d3-mini_W4A16.ipynb@@ -0,0 +1,301 @@+{+ "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",+ " 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+}diff --git a/examples/vLLM-sr/d3-nano_W4A16.ipynb b/examples/vLLM-sr/d3-nano_W4A16.ipynbnew file mode 100644index 000000000..f02594aa9--- /dev/null+++ b/examples/vLLM-sr/d3-nano_W4A16.ipynb@@ -0,0 +1,318 @@+{+ "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": "7da56c57",+ "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-nano\"\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": "7c1063ff",+ "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",+ " 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": "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",+ " # - 'auto_round': Reference AutoRound format (Transformers / native loader)\n",+ " format=\"auto_round\",\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",+ " # 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+}