Logotipo de Llm Model Quantization

Llm Model Quantization

Comunidad
j4flmao
llm-model-quantization

Use this skill when the user says 'quantize a model', 'GPTQ', 'AWQ', 'GGUF', 'Q4_K_M', 'INT4 / INT8 / FP8 weights', 'NF4', 'bitsandbytes', 'model too big for my GPU'. Explains how weight (and activation) quantization works, compares GPTQ, AWQ, GGUF k-quants, bitsandbytes NF4, and FP8, and gives working commands to produce and serve quantized models with an evaluation gate. Do NOT use for: KV cache sizing (ai/llm-engineering/kv-cache), QLoRA fine-tuning workflows (ai/llm-finetuning), or running local models end to end (rnd/ai-agents/local-slm-inference).

Descripción general

Editorj4flmao
Repositorioagent-skills
Nombre de la habilidadllm-model-quantization
Estrellas
41
Forks
6
Archivos incluidos
Solo instrucciones
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando una petición es realmente relevante.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Todo en las instrucciones

    Todo lo que necesita el modelo está en las instrucciones: no hay archivos adicionales que sincronizar.

  • Código abierto

    Publicada por j4flmao en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Llm Model Quantization en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-engineering/model-quantization
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → Desde URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/ai/llm-engineering/model-quantization .claude/skills/llm-model-quantization
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Llm Model Quantization en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición es relevante, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Llm Model Quantization automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Llm Model Quantization no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición relevante, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

Model Quantization

Purpose

Quantization stores weights (and optionally activations) in fewer bits so a model fits in less memory and decodes faster, since decoding is usually memory-bandwidth bound. The cost is a quality loss that depends on bit width, method, calibration data, and model. Pick the format your inference engine runs fastest, quantize with a calibration-aware method, and gate the result on your own evals.

Agent Protocol

Trigger

"quantize", "GPTQ", "AWQ", "GGUF", "k-quants", "Q4_K_M", "INT4", "INT8", "FP8", "NF4", "bitsandbytes", "fit model in VRAM".

Input Context

  • Model and size; target hardware (NVIDIA generation, Apple Silicon, CPU).
  • Inference engine (vLLM, TensorRT-LLM, llama.cpp/Ollama, transformers).
  • Quality tolerance and the eval set that measures it.

Output Artifact

Recommended format and bit width, quantization commands, memory estimate, eval comparison plan.

Response Format

Target: {hardware} via {engine}
Format: {fp8|awq-w4a16|gptq-w4a16|gguf Q4_K_M|nf4}
Memory: weights ≈ params × bits/8 (+ scales) = {GB}
Steps: {commands}
Eval gate: {metric} drop ≤ {x}% vs bf16 baseline

Completion Criteria

  • Format supported natively by the target engine/hardware.
  • Calibration data resembles production inputs.
  • Baseline vs quantized evaluated on task metrics, not only perplexity.
  • Throughput/latency measured, not assumed.

How It Works

Affine (asymmetric) quantization of a group of weights:

scale  s = (max(W) - min(W)) / (2^b - 1)
zero   z = round(-min(W) / s)
q      = clamp(round(W / s) + z, 0, 2^b - 1)
W_hat  = s · (q - z)

Symmetric quantization fixes z = 0 and uses a signed range. Group-wise quantization (e.g. group size 128) keeps a separate scale (and zero point) per group, limiting the damage from outliers at a cost of extra bits per weight (a 16-bit scale per 128 weights adds 0.125 bits/weight).

Weight-only schemes (W4A16, W8A16) dequantize inside the matmul kernel; they help most in the memory-bound decode phase. Weight+activation schemes (W8A8 INT8/FP8) also speed up compute-bound prefill on hardware with matching tensor-core support.

Methods

MethodIdeaCalibrationTypical use
RTN (round-to-nearest)Quantize each group independentlyNoneBaseline; fine at 8-bit
GPTQQuantize columns sequentially, compensate error in remaining weights using approximate second-order (Hessian) informationYes (small dataset)4-bit GPU serving
AWQFind salient weight channels via activation magnitudes; scale them up (inputs scaled down) before quantizing so their relative error shrinksYes4-bit GPU serving
SmoothQuantMigrate activation outliers into weights to enable W8A8YesINT8 activations
FP8 (E4M3)8-bit float weights/activations with per-tensor or per-channel scalesOptional (static scales)Hopper/Ada/Blackwell GPUs
NF4 (bitsandbytes)4-bit NormalFloat data type with double quantization of scalesNoneQLoRA training, quick experiments
GGUF k-quantsBlock quantization with super-blocks of quantized scales; optional importance matrixOptional (imatrix)llama.cpp / Ollama on CPU, Apple, mixed CPU+GPU

Choosing a Format

Engine?
├── vLLM / TensorRT-LLM / SGLang on recent NVIDIA (FP8-capable)
│   └── FP8 W8A8 first (near-lossless on most models); W4A16 (AWQ/GPTQ) if memory-bound
├── vLLM on older GPUs (Ampere) → W4A16 AWQ or GPTQ (Marlin kernels)
├── llama.cpp / Ollama / LM Studio → GGUF: Q4_K_M default, Q5_K_M/Q6_K for quality, Q8_0 near-lossless
├── transformers experiments / QLoRA → bitsandbytes NF4
└── Blackwell → FP4 variants (NVFP4/MXFP4) where the engine supports them; eval carefully

Producing Quantized Models

W4A16 GPTQ with llm-compressor (vLLM project); AutoGPTQ and AutoAWQ are no longer maintained, so prefer llm-compressor or GPTQModel:

python
from llmcompressor import oneshot
from llmcompressor.modifiers.quantization import GPTQModifier

recipe = GPTQModifier(targets="Linear", scheme="W4A16", ignore=["lm_head"])
oneshot(
    model="meta-llama/Llama-3.1-8B-Instruct",
    dataset="open_platypus",              # replace with in-domain calibration data
    recipe=recipe,
    max_seq_length=2048,
    num_calibration_samples=512,
    output_dir="Llama-3.1-8B-Instruct-W4A16",
)
# Serve: vllm serve ./Llama-3.1-8B-Instruct-W4A16   (format detected from the saved config)

GGUF with llama.cpp:

bash
python convert_hf_to_gguf.py ./Llama-3.1-8B-Instruct --outtype f16 --outfile llama-f16.gguf
./llama-imatrix -m llama-f16.gguf -f calibration.txt -o imatrix.dat      # optional, helps low bits
./llama-quantize --imatrix imatrix.dat llama-f16.gguf llama-Q4_K_M.gguf Q4_K_M

NF4 on load (bitsandbytes):

python
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
                         bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True)
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B-Instruct",
                                             quantization_config=bnb, device_map="auto")

Memory Estimates (weights only)

Paramsbf168-bit~4.5 bits (4-bit + scales)
8B16 GB8 GB~4.5 GB
70B140 GB70 GB~40 GB

Add KV cache and runtime overhead on top (see the kv-cache skill).

Evaluation Gate

  1. Run the bf16 baseline and the quantized model on the same task evals (accuracy, pass@k, rubric scores) plus a perplexity sanity check.
  2. Check long-context and tool-calling behaviour separately; they degrade before short QA does.
  3. Measure tokens/s and TTFT on the real engine and batch sizes; low-bit kernels can be slower at large batch.
  4. Ship only if the drop is within the agreed threshold.

Anti-Patterns

  • Judging quality by perplexity alone.
  • Calibrating on generic web text for a domain model (code, legal, non-English).
  • Quantizing lm_head/embeddings aggressively without testing.
  • Choosing a format the engine dequantizes in slow fallback kernels.
  • Comparing speed at batch size 1 when production runs batched.

Checklist

  • Format matches engine and GPU generation.
  • In-domain calibration set (hundreds of samples).
  • Baseline vs quantized eval table recorded.
  • Throughput/latency benchmark on target hardware.
  • Model card notes method, bits, group size, calibration data.

References

  • Frantar et al., "GPTQ" (ICLR 2023); Lin et al., "AWQ" (MLSys 2024); Xiao et al., "SmoothQuant" (ICML 2023); Dettmers et al., "QLoRA" (NeurIPS 2023).
  • llama.cpp docs: convert_hf_to_gguf.py, llama-quantize, llama-imatrix; vLLM quantization docs; llm-compressor examples.

Preguntas frecuentes

¿Qué hace la habilidad de IA Llm Model Quantization?

Use this skill when the user says 'quantize a model', 'GPTQ', 'AWQ', 'GGUF', 'Q4_K_M', 'INT4 / INT8 / FP8 weights', 'NF4', 'bitsandbytes', 'model too big for my GPU'. Explains how weight (and activation) quantization works, compares GPTQ, AWQ, GGUF k-quants, bitsandbytes NF4, and FP8, and gives working commands to produce and serve quantized models with an evaluation gate. Do NOT use for: KV cache sizing (ai/llm-engineering/kv-cache), QLoRA fine-tuning workflows (ai/llm-finetuning), or running local models end to end (rnd/ai-agents/local-slm-inference).

¿Por qué usar Llm Model Quantization en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Llm Model Quantization está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Llm Model Quantization en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-engineering/model-quantization. TypingMind lee su archivo SKILL.md y la instala como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Llm Model Quantization?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Llm Model Quantization?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Llm Model Quantization con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Llm Model Quantization?

Sí. j4flmao la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver todos

Crea ya tu propio espacio de trabajo IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇