[{"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",1575,"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",491,"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-14 14:06:13",{"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,107,115,123,131],{"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":15,"licenseFileUrl":94,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":98},"01M7DV332YQMGD8WTRJ9DZQXTB","worktable-review-with-annotations","Create, inspect, reply to, update, or resolve situated Worktable annotations. Use when feedback belongs to a Doc section, block, text range, or HTML Doc, or when the user asks to address existing review feedback and coordinate a requested artifact edit.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-review-with-annotations\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-review-with-annotations\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"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":15,"licenseFileUrl":103,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":98},"01M7DV2YGHCZVBEB1AHYB6CGHE","worktable-find-and-synthesize-context","Find, assess, and synthesize context from Worktable Docs and Records. Use when the user asks what a workspace contains, wants workspace-backed research, needs current facts reconciled across artifacts, or requests a cited synthesis without changing workspace state.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-find-and-synthesize-context\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-find-and-synthesize-context\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":111,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":98},"01M7DV2TQN1H11ME2SAF9MXN7V","worktable-create-or-update-docs","Create, edit, rename, or maintain narrative Worktable Docs. Use for plans, decisions, briefs, notes, research syntheses, and other durable prose when the user requests a new artifact or a safe update to an existing one.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-update-docs\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-update-docs\u002FSKILL.md",[],[],{"skillNo":116,"name":117,"nameZh":6,"description":118,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":119,"sourceHtmlUrl":120,"categories":121,"keywords":122,"publishedAt":98},"01M7DV2NE452NEA8TXATKSNAJH","worktable-create-or-manage-records","Organize repeated structured information as durable Worktable Records. Use for research datasets, inventories, directories, pipelines, trackers, and other collections whose items need identity, fields, filtering, links, validation, or individual updates.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-records\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-records\u002FSKILL.md",[],[],{"skillNo":124,"name":125,"nameZh":6,"description":126,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":127,"sourceHtmlUrl":128,"categories":129,"keywords":130,"publishedAt":98},"01M7DV2HENRBR2KSCVM064WH0Y","worktable-create-or-manage-interactive-html","Create or improve durable visual and interactive artifacts in Worktable. Use for dashboards, trackers, calculators, mini apps, slide presentations, and other requests that benefit from a polished HTML Doc.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-interactive-html\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-interactive-html\u002FSKILL.md",[],[],{"skillNo":132,"name":133,"nameZh":6,"description":134,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":135,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":98},"01M7DV2CADR5R7RQFFYPNAGR9Y","worktable-collaborate-threads","Read, answer, and hand off messages through durable Worktable threads with users or other authenticated participants. Use when the user asks to check addressed messages, reply to a participant, continue a thread, request another agent's help, wait briefly for a response, or watch for comments and messages sent to the agent.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-collaborate-threads\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-collaborate-threads\u002FSKILL.md",[],[]]