[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6MAY7AR8DWNVRXAT7HW4Y1F":3,"skill-same:01M6MAY7AR8DWNVRXAT7HW4Y1F":89},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":40,"linkOnly":41,"markdownContent":42,"markdownBody":43,"frontMatter":44,"refName":51,"commitSha":52,"skillDirectory":53,"forksCount":54,"repositoryHtmlUrl":55,"repositoryHomepageUrl":56,"ownerHtmlUrl":57,"ownerBlogUrl":58,"ownerDescription":59,"updatedAt":60,"install":61,"resources":74},"01M6MAY7AR8DWNVRXAT7HW4Y1F","quantizing-models-bitsandbytes",null,"Quantizes LLMs to 8-bit or 4-bit for 50-75% memory reduction with minimal accuracy loss. Use when GPU memory is limited, need to fit larger models, or want faster inference. Supports INT8, NF4, FP4 formats, QLoRA training, and 8-bit optimizers. Works with HuggingFace Transformers.","hashgraph-online\u002Fawesome-codex-plugins","hashgraph-online","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F160371962?v=4","01M6CNB6NRJVNNGN14TR01Q6D3","HOL (Hashgraph Online)","01M6JT1HSKKG9V68KQAQGBA7XP",1566,"MIT","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Fquantizing-models-bitsandbytes\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39],"models","quantizing models bitsandbytes","Bitsandbytes","Memory Optimization","when","accuracy","for","formats","Efficient Inference","INT8","NF4","8-Bit","llms","4-Bit","Accelerate","fit","bit","Transformers","Optimization","training","memory","2026-11-10 10:12:30",false,"---\nname: quantizing-models-bitsandbytes\ndescription: Quantizes LLMs to 8-bit or 4-bit for 50-75% memory reduction with minimal accuracy loss. Use when GPU memory is limited, need to fit larger models, or want faster inference. Supports INT8, NF4, FP4 formats, QLoRA training, and 8-bit optimizers. Works with HuggingFace Transformers.\nlicense: MIT\nmetadata:\n  version: 1.0.0\n  category: ml-training\n  maintainer: Kalaris Labs\n  tags: Optimization, Bitsandbytes, Quantization, 8-Bit, 4-Bit, Memory Optimization, QLoRA, NF4, INT8, HuggingFace, Efficient Inference\n  dependencies: bitsandbytes, transformers, accelerate, torch\n---\n\n# bitsandbytes - LLM Quantization\n\n## Quick start\n\nbitsandbytes reduces LLM memory by 50% (8-bit) or 75% (4-bit) with \u003C1% accuracy loss.\n\n**Installation**:\n```bash\npip install bitsandbytes transformers accelerate\n```\n\n**8-bit quantization** (50% memory reduction):\n```python\nfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig\n\nconfig = BitsAndBytesConfig(load_in_8bit=True)\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-7b-hf\",\n    quantization_config=config,\n    device_map=\"auto\"\n)\n\n# Memory: 14GB → 7GB\n```\n\n**4-bit quantization** (75% memory reduction):\n```python\nconfig = BitsAndBytesConfig(\n    load_in_4bit=True,\n    bnb_4bit_compute_dtype=torch.float16\n)\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-7b-hf\",\n    quantization_config=config,\n    device_map=\"auto\"\n)\n\n# Memory: 14GB → 3.5GB\n```\n\n## Common workflows\n\n### Workflow 1: Load large model in limited GPU memory\n\nCopy this checklist:\n\n```\nQuantization Loading:\n- [ ] Step 1: Calculate memory requirements\n- [ ] Step 2: Choose quantization level (4-bit or 8-bit)\n- [ ] Step 3: Configure quantization\n- [ ] Step 4: Load and verify model\n```\n\n**Step 1: Calculate memory requirements**\n\nEstimate model memory:\n```\nFP16 memory (GB) = Parameters × 2 bytes \u002F 1e9\nINT8 memory (GB) = Parameters × 1 byte \u002F 1e9\nINT4 memory (GB) = Parameters × 0.5 bytes \u002F 1e9\n\nExample (Llama 2 7B):\nFP16: 7B × 2 \u002F 1e9 = 14 GB\nINT8: 7B × 1 \u002F 1e9 = 7 GB\nINT4: 7B × 0.5 \u002F 1e9 = 3.5 GB\n```\n\n**Step 2: Choose quantization level**\n\n| GPU VRAM | Model Size | Recommended |\n|----------|------------|-------------|\n| 8 GB | 3B | 4-bit |\n| 12 GB | 7B | 4-bit |\n| 16 GB | 7B | 8-bit or 4-bit |\n| 24 GB | 13B | 8-bit or 70B 4-bit |\n| 40+ GB | 70B | 8-bit |\n\n**Step 3: Configure quantization**\n\nFor 8-bit (better accuracy):\n```python\nfrom transformers import BitsAndBytesConfig\nimport torch\n\nconfig = BitsAndBytesConfig(\n    load_in_8bit=True,\n    llm_int8_threshold=6.0,  # Outlier threshold\n    llm_int8_has_fp16_weight=False\n)\n```\n\nFor 4-bit (maximum memory savings):\n```python\nconfig = BitsAndBytesConfig(\n    load_in_4bit=True,\n    bnb_4bit_compute_dtype=torch.float16,  # Compute in FP16\n    bnb_4bit_quant_type=\"nf4\",  # NormalFloat4 (recommended)\n    bnb_4bit_use_double_quant=True  # Nested quantization\n)\n```\n\n**Step 4: Load and verify model**\n\n```python\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-13b-hf\",\n    quantization_config=config,\n    device_map=\"auto\",  # Automatic device placement\n    torch_dtype=torch.float16\n)\n\ntokenizer = AutoTokenizer.from_pretrained(\"meta-llama\u002FLlama-2-13b-hf\")\n\n# Test inference\ninputs = tokenizer(\"Hello, how are you?\", return_tensors=\"pt\").to(\"cuda\")\noutputs = model.generate(**inputs, max_length=50)\nprint(tokenizer.decode(outputs[0]))\n\n# Check memory\nimport torch\nprint(f\"Memory allocated: {torch.cuda.memory_allocated()\u002F1e9:.2f}GB\")\n```\n\n### Workflow 2: Fine-tune with QLoRA (4-bit training)\n\nQLoRA enables fine-tuning large models on consumer GPUs.\n\nCopy this checklist:\n\n```\nQLoRA Fine-tuning:\n- [ ] Step 1: Install dependencies\n- [ ] Step 2: Configure 4-bit base model\n- [ ] Step 3: Add LoRA adapters\n- [ ] Step 4: Train with standard Trainer\n```\n\n**Step 1: Install dependencies**\n\n```bash\npip install bitsandbytes transformers peft accelerate datasets\n```\n\n**Step 2: Configure 4-bit base model**\n\n```python\nfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig\nimport torch\n\nbnb_config = BitsAndBytesConfig(\n    load_in_4bit=True,\n    bnb_4bit_compute_dtype=torch.float16,\n    bnb_4bit_quant_type=\"nf4\",\n    bnb_4bit_use_double_quant=True\n)\n\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-7b-hf\",\n    quantization_config=bnb_config,\n    device_map=\"auto\"\n)\n```\n\n**Step 3: Add LoRA adapters**\n\n```python\nfrom peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training\n\n# Prepare model for training\nmodel = prepare_model_for_kbit_training(model)\n\n# Configure LoRA\nlora_config = LoraConfig(\n    r=16,  # LoRA rank\n    lora_alpha=32,  # LoRA alpha\n    target_modules=[\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\"],\n    lora_dropout=0.05,\n    bias=\"none\",\n    task_type=\"CAUSAL_LM\"\n)\n\n# Add LoRA adapters\nmodel = get_peft_model(model, lora_config)\nmodel.print_trainable_parameters()\n# Output: trainable params: 4.2M || all params: 6.7B || trainable%: 0.06%\n```\n\n**Step 4: Train with standard Trainer**\n\n```python\nfrom transformers import Trainer, TrainingArguments\n\ntraining_args = TrainingArguments(\n    output_dir=\".\u002Fqlora-output\",\n    per_device_train_batch_size=4,\n    gradient_accumulation_steps=4,\n    num_train_epochs=3,\n    learning_rate=2e-4,\n    fp16=True,\n    logging_steps=10,\n    save_strategy=\"epoch\"\n)\n\ntrainer = Trainer(\n    model=model,\n    args=training_args,\n    train_dataset=train_dataset,\n    tokenizer=tokenizer\n)\n\ntrainer.train()\n\n# Save LoRA adapters (only ~20MB)\nmodel.save_pretrained(\".\u002Fqlora-adapters\")\n```\n\n### Workflow 3: 8-bit optimizer for memory-efficient training\n\nUse 8-bit Adam\u002FAdamW to reduce optimizer memory by 75%.\n\n```\n8-bit Optimizer Setup:\n- [ ] Step 1: Replace standard optimizer\n- [ ] Step 2: Configure training\n- [ ] Step 3: Monitor memory savings\n```\n\n**Step 1: Replace standard optimizer**\n\n```python\nimport bitsandbytes as bnb\nfrom transformers import Trainer, TrainingArguments\n\n# Instead of torch.optim.AdamW\nmodel = AutoModelForCausalLM.from_pretrained(\"model-name\")\n\ntraining_args = TrainingArguments(\n    output_dir=\".\u002Foutput\",\n    per_device_train_batch_size=8,\n    optim=\"paged_adamw_8bit\",  # 8-bit optimizer\n    learning_rate=5e-5\n)\n\ntrainer = Trainer(\n    model=model,\n    args=training_args,\n    train_dataset=train_dataset\n)\n\ntrainer.train()\n```\n\n**Manual optimizer usage**:\n```python\nimport bitsandbytes as bnb\n\noptimizer = bnb.optim.AdamW8bit(\n    model.parameters(),\n    lr=1e-4,\n    betas=(0.9, 0.999),\n    eps=1e-8\n)\n\n# Training loop\nfor batch in dataloader:\n    loss = model(**batch).loss\n    loss.backward()\n    optimizer.step()\n    optimizer.zero_grad()\n```\n\n**Step 2: Configure training**\n\nCompare memory:\n```\nStandard AdamW optimizer memory = model_params × 8 bytes (states)\n8-bit AdamW memory = model_params × 2 bytes\nSavings = 75% optimizer memory\n\nExample (Llama 2 7B):\nStandard: 7B × 8 = 56 GB\n8-bit: 7B × 2 = 14 GB\nSavings: 42 GB\n```\n\n**Step 3: Monitor memory savings**\n\n```python\nimport torch\n\nbefore = torch.cuda.memory_allocated()\n\n# Training step\noptimizer.step()\n\nafter = torch.cuda.memory_allocated()\nprint(f\"Memory used: {(after-before)\u002F1e9:.2f}GB\")\n```\n\n## When to use vs alternatives\n\n**Use bitsandbytes when:**\n- GPU memory limited (need to fit larger model)\n- Training with QLoRA (fine-tune 70B on single GPU)\n- Inference only (50-75% memory reduction)\n- Using HuggingFace Transformers\n- Acceptable 0-2% accuracy degradation\n\n**Use alternatives instead:**\n- **GPTQ\u002FAWQ**: Production serving (faster inference than bitsandbytes)\n- **GGUF**: CPU inference (llama.cpp)\n- **FP8**: H100 GPUs (hardware FP8 faster)\n- **Full precision**: Accuracy critical, memory not constrained\n\n## Common issues\n\n**Issue: CUDA error during loading**\n\nInstall matching CUDA version:\n```bash\n# Check CUDA version\nnvcc --version\n\n# Install matching bitsandbytes\npip install bitsandbytes --no-cache-dir\n```\n\n**Issue: Model loading slow**\n\nUse CPU offload for large models:\n```python\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"model-name\",\n    quantization_config=config,\n    device_map=\"auto\",\n    max_memory={0: \"20GB\", \"cpu\": \"30GB\"}  # Offload to CPU\n)\n```\n\n**Issue: Lower accuracy than expected**\n\nTry 8-bit instead of 4-bit:\n```python\nconfig = BitsAndBytesConfig(load_in_8bit=True)\n# 8-bit has \u003C0.5% accuracy loss vs 1-2% for 4-bit\n```\n\nOr use NF4 with double quantization:\n```python\nconfig = BitsAndBytesConfig(\n    load_in_4bit=True,\n    bnb_4bit_quant_type=\"nf4\",  # Better than fp4\n    bnb_4bit_use_double_quant=True  # Extra accuracy\n)\n```\n\n**Issue: OOM even with 4-bit**\n\nEnable CPU offload:\n```python\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"model-name\",\n    quantization_config=config,\n    device_map=\"auto\",\n    offload_folder=\"offload\",  # Disk offload\n    offload_state_dict=True\n)\n```\n\n## Advanced topics\n\n**QLoRA training guide**: See [references\u002Fqlora-training.md](references\u002Fqlora-training.md) for complete fine-tuning workflows, hyperparameter tuning, and multi-GPU training.\n\n**Quantization formats**: See [references\u002Fquantization-formats.md](references\u002Fquantization-formats.md) for INT8, NF4, FP4 comparison, double quantization, and custom quantization configs.\n\n**Memory optimization**: See [references\u002Fmemory-optimization.md](references\u002Fmemory-optimization.md) for CPU offloading strategies, gradient checkpointing, and memory profiling.\n\n## Hardware requirements\n\n- **GPU**: NVIDIA with compute capability 7.0+ (Turing, Ampere, Hopper)\n- **VRAM**: Depends on model and quantization\n  - 4-bit Llama 2 7B: 4GB\n  - 4-bit Llama 2 13B: 8GB\n  - 4-bit Llama 2 70B: 24GB\n- **CUDA**: 11.1+ (12.0+ recommended)\n- **PyTorch**: 2.0+\n\n**Supported platforms**: NVIDIA GPUs (primary), AMD ROCm, Intel GPUs (experimental)\n\n## Resources\n\n- GitHub: https:\u002F\u002Fgithub.com\u002Fbitsandbytes-foundation\u002Fbitsandbytes\n- HuggingFace docs: https:\u002F\u002Fhuggingface.co\u002Fdocs\u002Ftransformers\u002Fquantization\u002Fbitsandbytes\n- QLoRA paper: \"QLoRA: Efficient Finetuning of Quantized LLMs\" (2023)\n- LLM.int8() paper: \"LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale\" (2022)\n\n## Agent operating procedure\n\n1. **Check the environment.** Check GPU type, memory and driver\u002FCUDA versions (`nvidia-smi`), framework versions, and dataset location and size.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Do a smoke run: tiny model or subset, few steps, and confirm loss decreases and checkpoints save.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Track metrics on held-out data, compare against a baseline, and record seeds, configs and hardware.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| CUDA out-of-memory | Reduce batch size, enable gradient accumulation\u002Fcheckpointing or mixed precision, or shard the model. |\n| Loss is NaN or diverges | Lower the learning rate, check data for invalid values, and enable gradient clipping. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Never claim training results without logs; estimate compute cost before launching large jobs.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n\n## Related skills\n\n- `awq-quantization`: Activation-aware weight quantization for 4-bit LLM compression with 3x speedup and minimal accuracy loss.\n- `gptq`: Quantizes LLMs to 4-bit (also 3-bit) with GPTQ using group-wise quantization (group size 128 by default), via AutoGPTQ and transformers.\n- `hqq-quantization`: Half-Quadratic Quantization for LLMs without calibration data.\n","# bitsandbytes - LLM Quantization\n\n## Quick start\n\nbitsandbytes reduces LLM memory by 50% (8-bit) or 75% (4-bit) with \u003C1% accuracy loss.\n\n**Installation**:\n```bash\npip install bitsandbytes transformers accelerate\n```\n\n**8-bit quantization** (50% memory reduction):\n```python\nfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig\n\nconfig = BitsAndBytesConfig(load_in_8bit=True)\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-7b-hf\",\n    quantization_config=config,\n    device_map=\"auto\"\n)\n\n# Memory: 14GB → 7GB\n```\n\n**4-bit quantization** (75% memory reduction):\n```python\nconfig = BitsAndBytesConfig(\n    load_in_4bit=True,\n    bnb_4bit_compute_dtype=torch.float16\n)\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-7b-hf\",\n    quantization_config=config,\n    device_map=\"auto\"\n)\n\n# Memory: 14GB → 3.5GB\n```\n\n## Common workflows\n\n### Workflow 1: Load large model in limited GPU memory\n\nCopy this checklist:\n\n```\nQuantization Loading:\n- [ ] Step 1: Calculate memory requirements\n- [ ] Step 2: Choose quantization level (4-bit or 8-bit)\n- [ ] Step 3: Configure quantization\n- [ ] Step 4: Load and verify model\n```\n\n**Step 1: Calculate memory requirements**\n\nEstimate model memory:\n```\nFP16 memory (GB) = Parameters × 2 bytes \u002F 1e9\nINT8 memory (GB) = Parameters × 1 byte \u002F 1e9\nINT4 memory (GB) = Parameters × 0.5 bytes \u002F 1e9\n\nExample (Llama 2 7B):\nFP16: 7B × 2 \u002F 1e9 = 14 GB\nINT8: 7B × 1 \u002F 1e9 = 7 GB\nINT4: 7B × 0.5 \u002F 1e9 = 3.5 GB\n```\n\n**Step 2: Choose quantization level**\n\n| GPU VRAM | Model Size | Recommended |\n|----------|------------|-------------|\n| 8 GB | 3B | 4-bit |\n| 12 GB | 7B | 4-bit |\n| 16 GB | 7B | 8-bit or 4-bit |\n| 24 GB | 13B | 8-bit or 70B 4-bit |\n| 40+ GB | 70B | 8-bit |\n\n**Step 3: Configure quantization**\n\nFor 8-bit (better accuracy):\n```python\nfrom transformers import BitsAndBytesConfig\nimport torch\n\nconfig = BitsAndBytesConfig(\n    load_in_8bit=True,\n    llm_int8_threshold=6.0,  # Outlier threshold\n    llm_int8_has_fp16_weight=False\n)\n```\n\nFor 4-bit (maximum memory savings):\n```python\nconfig = BitsAndBytesConfig(\n    load_in_4bit=True,\n    bnb_4bit_compute_dtype=torch.float16,  # Compute in FP16\n    bnb_4bit_quant_type=\"nf4\",  # NormalFloat4 (recommended)\n    bnb_4bit_use_double_quant=True  # Nested quantization\n)\n```\n\n**Step 4: Load and verify model**\n\n```python\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-13b-hf\",\n    quantization_config=config,\n    device_map=\"auto\",  # Automatic device placement\n    torch_dtype=torch.float16\n)\n\ntokenizer = AutoTokenizer.from_pretrained(\"meta-llama\u002FLlama-2-13b-hf\")\n\n# Test inference\ninputs = tokenizer(\"Hello, how are you?\", return_tensors=\"pt\").to(\"cuda\")\noutputs = model.generate(**inputs, max_length=50)\nprint(tokenizer.decode(outputs[0]))\n\n# Check memory\nimport torch\nprint(f\"Memory allocated: {torch.cuda.memory_allocated()\u002F1e9:.2f}GB\")\n```\n\n### Workflow 2: Fine-tune with QLoRA (4-bit training)\n\nQLoRA enables fine-tuning large models on consumer GPUs.\n\nCopy this checklist:\n\n```\nQLoRA Fine-tuning:\n- [ ] Step 1: Install dependencies\n- [ ] Step 2: Configure 4-bit base model\n- [ ] Step 3: Add LoRA adapters\n- [ ] Step 4: Train with standard Trainer\n```\n\n**Step 1: Install dependencies**\n\n```bash\npip install bitsandbytes transformers peft accelerate datasets\n```\n\n**Step 2: Configure 4-bit base model**\n\n```python\nfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig\nimport torch\n\nbnb_config = BitsAndBytesConfig(\n    load_in_4bit=True,\n    bnb_4bit_compute_dtype=torch.float16,\n    bnb_4bit_quant_type=\"nf4\",\n    bnb_4bit_use_double_quant=True\n)\n\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"meta-llama\u002FLlama-2-7b-hf\",\n    quantization_config=bnb_config,\n    device_map=\"auto\"\n)\n```\n\n**Step 3: Add LoRA adapters**\n\n```python\nfrom peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training\n\n# Prepare model for training\nmodel = prepare_model_for_kbit_training(model)\n\n# Configure LoRA\nlora_config = LoraConfig(\n    r=16,  # LoRA rank\n    lora_alpha=32,  # LoRA alpha\n    target_modules=[\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\"],\n    lora_dropout=0.05,\n    bias=\"none\",\n    task_type=\"CAUSAL_LM\"\n)\n\n# Add LoRA adapters\nmodel = get_peft_model(model, lora_config)\nmodel.print_trainable_parameters()\n# Output: trainable params: 4.2M || all params: 6.7B || trainable%: 0.06%\n```\n\n**Step 4: Train with standard Trainer**\n\n```python\nfrom transformers import Trainer, TrainingArguments\n\ntraining_args = TrainingArguments(\n    output_dir=\".\u002Fqlora-output\",\n    per_device_train_batch_size=4,\n    gradient_accumulation_steps=4,\n    num_train_epochs=3,\n    learning_rate=2e-4,\n    fp16=True,\n    logging_steps=10,\n    save_strategy=\"epoch\"\n)\n\ntrainer = Trainer(\n    model=model,\n    args=training_args,\n    train_dataset=train_dataset,\n    tokenizer=tokenizer\n)\n\ntrainer.train()\n\n# Save LoRA adapters (only ~20MB)\nmodel.save_pretrained(\".\u002Fqlora-adapters\")\n```\n\n### Workflow 3: 8-bit optimizer for memory-efficient training\n\nUse 8-bit Adam\u002FAdamW to reduce optimizer memory by 75%.\n\n```\n8-bit Optimizer Setup:\n- [ ] Step 1: Replace standard optimizer\n- [ ] Step 2: Configure training\n- [ ] Step 3: Monitor memory savings\n```\n\n**Step 1: Replace standard optimizer**\n\n```python\nimport bitsandbytes as bnb\nfrom transformers import Trainer, TrainingArguments\n\n# Instead of torch.optim.AdamW\nmodel = AutoModelForCausalLM.from_pretrained(\"model-name\")\n\ntraining_args = TrainingArguments(\n    output_dir=\".\u002Foutput\",\n    per_device_train_batch_size=8,\n    optim=\"paged_adamw_8bit\",  # 8-bit optimizer\n    learning_rate=5e-5\n)\n\ntrainer = Trainer(\n    model=model,\n    args=training_args,\n    train_dataset=train_dataset\n)\n\ntrainer.train()\n```\n\n**Manual optimizer usage**:\n```python\nimport bitsandbytes as bnb\n\noptimizer = bnb.optim.AdamW8bit(\n    model.parameters(),\n    lr=1e-4,\n    betas=(0.9, 0.999),\n    eps=1e-8\n)\n\n# Training loop\nfor batch in dataloader:\n    loss = model(**batch).loss\n    loss.backward()\n    optimizer.step()\n    optimizer.zero_grad()\n```\n\n**Step 2: Configure training**\n\nCompare memory:\n```\nStandard AdamW optimizer memory = model_params × 8 bytes (states)\n8-bit AdamW memory = model_params × 2 bytes\nSavings = 75% optimizer memory\n\nExample (Llama 2 7B):\nStandard: 7B × 8 = 56 GB\n8-bit: 7B × 2 = 14 GB\nSavings: 42 GB\n```\n\n**Step 3: Monitor memory savings**\n\n```python\nimport torch\n\nbefore = torch.cuda.memory_allocated()\n\n# Training step\noptimizer.step()\n\nafter = torch.cuda.memory_allocated()\nprint(f\"Memory used: {(after-before)\u002F1e9:.2f}GB\")\n```\n\n## When to use vs alternatives\n\n**Use bitsandbytes when:**\n- GPU memory limited (need to fit larger model)\n- Training with QLoRA (fine-tune 70B on single GPU)\n- Inference only (50-75% memory reduction)\n- Using HuggingFace Transformers\n- Acceptable 0-2% accuracy degradation\n\n**Use alternatives instead:**\n- **GPTQ\u002FAWQ**: Production serving (faster inference than bitsandbytes)\n- **GGUF**: CPU inference (llama.cpp)\n- **FP8**: H100 GPUs (hardware FP8 faster)\n- **Full precision**: Accuracy critical, memory not constrained\n\n## Common issues\n\n**Issue: CUDA error during loading**\n\nInstall matching CUDA version:\n```bash\n# Check CUDA version\nnvcc --version\n\n# Install matching bitsandbytes\npip install bitsandbytes --no-cache-dir\n```\n\n**Issue: Model loading slow**\n\nUse CPU offload for large models:\n```python\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"model-name\",\n    quantization_config=config,\n    device_map=\"auto\",\n    max_memory={0: \"20GB\", \"cpu\": \"30GB\"}  # Offload to CPU\n)\n```\n\n**Issue: Lower accuracy than expected**\n\nTry 8-bit instead of 4-bit:\n```python\nconfig = BitsAndBytesConfig(load_in_8bit=True)\n# 8-bit has \u003C0.5% accuracy loss vs 1-2% for 4-bit\n```\n\nOr use NF4 with double quantization:\n```python\nconfig = BitsAndBytesConfig(\n    load_in_4bit=True,\n    bnb_4bit_quant_type=\"nf4\",  # Better than fp4\n    bnb_4bit_use_double_quant=True  # Extra accuracy\n)\n```\n\n**Issue: OOM even with 4-bit**\n\nEnable CPU offload:\n```python\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"model-name\",\n    quantization_config=config,\n    device_map=\"auto\",\n    offload_folder=\"offload\",  # Disk offload\n    offload_state_dict=True\n)\n```\n\n## Advanced topics\n\n**QLoRA training guide**: See [references\u002Fqlora-training.md](references\u002Fqlora-training.md) for complete fine-tuning workflows, hyperparameter tuning, and multi-GPU training.\n\n**Quantization formats**: See [references\u002Fquantization-formats.md](references\u002Fquantization-formats.md) for INT8, NF4, FP4 comparison, double quantization, and custom quantization configs.\n\n**Memory optimization**: See [references\u002Fmemory-optimization.md](references\u002Fmemory-optimization.md) for CPU offloading strategies, gradient checkpointing, and memory profiling.\n\n## Hardware requirements\n\n- **GPU**: NVIDIA with compute capability 7.0+ (Turing, Ampere, Hopper)\n- **VRAM**: Depends on model and quantization\n  - 4-bit Llama 2 7B: 4GB\n  - 4-bit Llama 2 13B: 8GB\n  - 4-bit Llama 2 70B: 24GB\n- **CUDA**: 11.1+ (12.0+ recommended)\n- **PyTorch**: 2.0+\n\n**Supported platforms**: NVIDIA GPUs (primary), AMD ROCm, Intel GPUs (experimental)\n\n## Resources\n\n- GitHub: https:\u002F\u002Fgithub.com\u002Fbitsandbytes-foundation\u002Fbitsandbytes\n- HuggingFace docs: https:\u002F\u002Fhuggingface.co\u002Fdocs\u002Ftransformers\u002Fquantization\u002Fbitsandbytes\n- QLoRA paper: \"QLoRA: Efficient Finetuning of Quantized LLMs\" (2023)\n- LLM.int8() paper: \"LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale\" (2022)\n\n## Agent operating procedure\n\n1. **Check the environment.** Check GPU type, memory and driver\u002FCUDA versions (`nvidia-smi`), framework versions, and dataset location and size.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Do a smoke run: tiny model or subset, few steps, and confirm loss decreases and checkpoints save.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Track metrics on held-out data, compare against a baseline, and record seeds, configs and hardware.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| CUDA out-of-memory | Reduce batch size, enable gradient accumulation\u002Fcheckpointing or mixed precision, or shard the model. |\n| Loss is NaN or diverges | Lower the learning rate, check data for invalid values, and enable gradient clipping. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Never claim training results without logs; estimate compute cost before launching large jobs.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n\n## Related skills\n\n- `awq-quantization`: Activation-aware weight quantization for 4-bit LLM compression with 3x speedup and minimal accuracy loss.\n- `gptq`: Quantizes LLMs to 4-bit (also 3-bit) with GPTQ using group-wise quantization (group size 128 by default), via AutoGPTQ and transformers.\n- `hqq-quantization`: Half-Quadratic Quantization for LLMs without calibration data.\n",{"name":5,"license":15,"metadata":45,"description":7},{"tags":46,"version":47,"category":48,"maintainer":49,"dependencies":50},"Optimization, Bitsandbytes, Quantization, 8-Bit, 4-Bit, Memory Optimization, QLoRA, NF4, INT8, HuggingFace, Efficient Inference","1.0.0","ml-training","Kalaris Labs","bitsandbytes, transformers, accelerate, torch","main","2b63f856ce19c2a797929cacabd9e0fc936812fa","plugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Fquantizing-models-bitsandbytes",483,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins","https:\u002F\u002Fhol.org\u002Fplugins\u002Fbest-codex-plugins","https:\u002F\u002Fgithub.com\u002Fhashgraph-online","https:\u002F\u002Fhol.org","Open-source standards and developer tools for interoperable AI agents: discovery, identity, communication, payments, privacy and security.","2026-11-13 02:16:32",{"source":8,"skillName":5,"commands":62,"prompt":72,"zipAvailable":73},[63,66,69],{"tool":64,"command":65},"npx","npx skills add hashgraph-online\u002Fawesome-codex-plugins --skill quantizing-models-bitsandbytes",{"tool":67,"command":68},"bunx","bunx skills add hashgraph-online\u002Fawesome-codex-plugins --skill quantizing-models-bitsandbytes",{"tool":70,"command":71},"pnpm","pnpm dlx skills add hashgraph-online\u002Fawesome-codex-plugins --skill quantizing-models-bitsandbytes","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Fquantizing-models-bitsandbytes\u002FSKILL.md",true,[75,81,85],{"path":76,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":79,"sourceHtmlUrl":80},"references\u002Fmemory-optimization.md","REFERENCE","参考文档",12642,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Fquantizing-models-bitsandbytes\u002Freferences\u002Fmemory-optimization.md",{"path":82,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":83,"sourceHtmlUrl":84},"references\u002Fqlora-training.md",12015,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Fquantizing-models-bitsandbytes\u002Freferences\u002Fqlora-training.md",{"path":86,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":87,"sourceHtmlUrl":88},"references\u002Fquantization-formats.md",10258,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Fquantizing-models-bitsandbytes\u002Freferences\u002Fquantization-formats.md",[90,99,106,113,138,163],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":98},"01M746ZWACVKMZ1BJXJZHYJSSX","migrate-to-e2e","Moves an existing Playwright, Cypress, Selenium, Appium, Detox, Maestro, or TesterArmy suite to e2e one slice at a time, with the old suite running beside the new one until each ported test is proven. Keeps a MIGRATION.md progress file so any later session resumes where the last stopped. Optionally plants a defect to show both suites catch it. Use for \u002Fmigrate-to-e2e, \"migrate our tests to e2e\", \"port these Maestro flows\", \"move our TesterArmy tests\", or when a project has an e2e config and an older suite still running.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Ftester-army\u002Fe2e\u002Fskills\u002Fmigrate-to-e2e\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":98},"01M746ZPTAX1Q0FBKAB1CYND7E","e2e","Writes, runs, and debugs end-to-end tests for web and mobile apps with e2e, the agentic test runner, which mixes agent.act goals with exact locator assertions on a Playwright browser or an iOS or Android device. Also drives a project's running app live over the e2e MCP server to look at a screen, check a UI change, take a screenshot or record a video, and try a locator; and runs bug bashes, parallel e2e explore runs with each bug proven by a repro test. Use when a project depends on e2e or has an e2e.config.ts, when asked for end-to-end, browser, mobile, or agentic UI tests, to check a change in the running app, to QA or bug bash an app or branch, or when an e2e run fails.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Ftester-army\u002Fe2e\u002Fskills\u002Fe2e\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":98},"01M746ZJN784HVHMDP9MQGCSGG","create-verification-skill","Generate a project-local verify-\u003Capp> skill on top of e2e, so any coding agent can launch the app, check it is worth driving, exercise a feature the way a user does, keep evidence, and bug bash it. Writes the skill, a feature map with one explore charter per feature, and proves it once. Use for \u002Fcreate-verification-skill, \"make a verification skill for this repo\", or when a project has no scripted way to prove UI behavior.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Ftester-army\u002Fe2e\u002Fskills\u002Fcreate-verification-skill\u002FSKILL.md",[],[],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":40},"01M716A6ETNB9B1SQ3GXZC75VR","deja-search","deja-vu memory — search the user's past AI coding sessions with the deja CLI. Holds what they already settled and never wrote into the repo (naming rules, banned or already-tried tools, required checks before merge, preferred values, who owns what). Use before your first edit in a task, before you call a change done or ready to merge, before you recommend a tool, library, design or reviewer, before re-debugging an error that may already be solved, when they say 'didn't we fix this before', 'what did we decide about X' or 'I already have that', and before telling them something on this machine does not exist.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fvshulcz\u002Fdeja-vu\u002Fskills\u002Fdeja-search\u002FSKILL.md",[],[120,121,122,123,124,39,125,126,127,128,129,23,130,131,132,133,134,135,136,137],"search","deja search","never","error","ready","re","decide","fix","design","debugging","you","done","reviewer","io","change","cli","merge","past",{"skillNo":139,"name":140,"nameZh":6,"description":141,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":142,"categories":143,"keywords":144,"publishedAt":40},"01M716A3J2W5SENSE9VGMXB375","deja-reflect","End-of-session reflection and memory curation with deja-vu. Review what was decided, what commands broke and what repaired them, and record durable project rules or decisions with deja remember so the next session starts with them.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fvshulcz\u002Fdeja-vu\u002Fskills\u002Fdeja-reflect\u002FSKILL.md",[],[145,146,147,133,148,149,150,151,152,153,154,155,156,157,39,158,159,160,161,162],"deja reflect","reflect","review","with","record","github","next","https","node","Rules","decisions","brew","remember","project rules","project","session","end","reflection",{"skillNo":164,"name":165,"nameZh":6,"description":166,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":167,"categories":168,"keywords":180,"publishedAt":40},"01M715T3RR4BAYSR57HPPTJ0PF","revid","Make, edit, export and post AI videos with Revid (revid.ai) through the Revid MCP server. Use whenever the user wants a short-form or long-form video made (from an idea, a script, a URL, an article, a PDF, a tweet, a product page, their own clips, or a song), wants to find what is going viral on TikTok, YouTube, Instagram or X before making something, wants to edit or re-export an existing Revid project, generate a standalone AI image or clip, make a series episode, or publish and schedule a finished video to connected social accounts. Covers setup (hosted MCP with OAuth, or an API key), the 36 tools, credits, polling and the rules for publishing. Routes to the more specific revid-* skills when one fits.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Ftmakersas\u002Frevid-skills\u002Fskills\u002Frevid\u002FSKILL.md",[169,174,177],{"categoryNo":170,"categoryName":171,"taxonomyType":172,"taxonomyTypeDesc":173},"01JBSEEDCAT000000000000016","图像与多媒体","SCENARIO","使用场景",{"categoryNo":175,"categoryName":176,"taxonomyType":172,"taxonomyTypeDesc":173},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":178,"categoryName":179,"taxonomyType":172,"taxonomyTypeDesc":173},"01JBSEEDCAT000000000000010","后端与接口",[165,181,182,183,184,185,186,159,187,125,188,189,190,191,23,192,193,194,195,196],"URL","Video","short-form","standalone","PDF","viral","tiktok","short","social","MCP","song","image","mcp server","schedule","api","publish"]