GPTQModel Documentation

repository·main·Indexed 22 days ago

https://github.com/modelcloud/gptqmodel

A production-ready LLM model compression and quantization toolkit supporting hardware-accelerated inference for CPU and GPU via HF, vLLM, and SGLang. It features EoRA (Eigenspace Low-Rank Approximation) for training-free quantization error mitigation, Machete for mixed precision GEMM on Hopper architectures, and broad backend support for NVIDIA CUDA, AMD ROCm, Huawei Ascend NPU, Intel XPU, and Apple Silicon. Supports multiple quantization methods including GPTQ, AWQ, PARO, QQQ, GGUF, FP8, BitsAndBytes, and EXL3.

Tokens
15.6K
Snippets
27
Records
47
Agent score
79%

What's inside GPTQModel

  1. Check platform and hardware support for GPTQModel

    main

    GPTQModel supports a wide range of platforms and hardware architectures, including NVIDIA GPUs, AMD GPUs, Huawei Ascend NPUs, Intel XPUs, and Apple Silicon. Support varies by device, optimized architecture, and available kernels.

    Supported Platforms and Devices

    PlatformDeviceOptimized ArchKernels
    🐧 LinuxNVIDIA GPUTuring+ (sm_75+)Machete, Marlin, Exllama V3 / EXL3, Exllama V2, AWQ GEMM/GEMV, ParoQuant CUDA/Triton, GGUF CUDA/Triton, QQQ, BitBLAS, Triton, BitsAndBytes, Torch
    🐧 LinuxAMD GPU7900XT+, ROCm 6.2+Exllama V2, AWQ GEMM/GEMV, QQQ, FP8 Torch, Torch
    🐧 LinuxHuawei Ascend NPUAscend 910B, torch-npu / CANNNative Torch kernels for GPTQ, AWQ, ParoQuant, GGUF, QQQ, and EXL3
    🐧 LinuxIntel XPUArc, Datacenter MaxTorchFused, TorchFusedAWQ, FP8 Torch, Torch
    🐧 LinuxIntel/AMD CPUavx, amxTorchFused, TorchFusedAWQ, TorchAten int4, TorchInt8, GGUF C++, BitsAndBytes, Torch
    🍎 macOSGPU (Metal) / CPUApple Silicon, M1+Torch, FP8 Torch, MLX via conversion
    🪟 WindowsGPU (NVIDIA) / CPUNVIDIATorch

    Key Notes

    • NVIDIA GPUs: Marlin and JIT CUDA kernels support Turing+ (sm_75+) architectures.
    • Huawei Ascend NPU: Uses native Torch kernels via torch-npu / CANN.
    • macOS: Supports Apple Silicon (M1+) via Torch, FP8 Torch, or MLX (via conversion).
  2. What is EoRA and how does it work?

    main

    EoRA (Eigenspace Low-Rank Approximation) is a training-free method designed to mitigate quantization errors in compressed Large Language Models (LLMs). It uses a calibration dataset to construct low-rank matrices that compensate for the loss of accuracy caused by quantization.

    Key characteristics:

    • Training-free: It does not require model fine-tuning.
    • Calibration-driven: You can use general-purpose data (like C4) to boost overall model quality, or task-specific data (like MMLU validation sets) to improve performance on specific downstream tasks.
    • Efficiency: The generation process takes approximately the same amount of time as standard GPTQ quantization.
  3. Use Machete for Mixed Precision GEMM

    main

    Machete is a Cutlass-based Mixed Precision GEMM optimized for Hopper architectures. It performs quantized matrix multiplication using the following logic:

    scale_type = w_s.dtype
    compute_type = a.dtype
    out = (w_q.to(scale_type) * w_s - w_z.to(scale_type)) @ a

    Important Note on Zeropoints (w_z):
    Because w_z is subtracted after the scales are applied to allow for FMA (Fused Multiply-Add) operations, the supplied zeropoints must have the scales pre-applied if they were originally intended to be subtracted before scaling.

  4. Configure Rule Actions and Target Configs

    main

    The protocol allows combining actions (like balancing) with target configurations (weight, input, prepare, quantize, export).

    Execution Order within a stage:

    1. Evaluate rules in order.
    2. Resolve matches.
    3. Resolve optional aliases.
    4. Run rule actions.
    5. Run target prepare.
    6. Collect calibration/replay data.
    7. Run target quantize.
    8. Run target export.
    9. Emit stage outputs.

    Pattern: Use actions to apply transformations (like smoothquant) to specific scopes (like .*self_attn$), while using weight and input rules to define the quantization and export policies for the whole model or specific sub-modules.

    # Example: Applying an action to a scope, then defining global defaults
    Rule(
        match=".*self_attn$",
        actions=[smoothquant(alpha=0.5)],
    )
    
    Rule(
        match="*",
        weight={
            "prepare": [clip.mad(k=2.75)],
            "quantize": gptq(bits=4, sym=True, group_size=128),
            "export": {"format": "gptq", "impl": "default"},
        },
        input={
            "quantize": mxfp4(mode="dynamic", block_size=32, scale_bits=8),
            "export": {
                "format": "fp4",
                "variant": "mxfp4",
                "impl": "modelopt",
            },
        },
    )
  5. Understand the GPTQModel unit test flow

    main

    The GPTQModel CI testing process follows a multi-stage pipeline to ensure environment consistency and efficient test execution across different hardware and dependency configurations:

    1. check-vm: Computes execution metadata like ip, run_id, install_ts, and matrix parallelism, writing them to GITHUB_OUTPUT.
    2. list-test-files: Scans the tests/ directory, filters tests based on regex or ignore rules, categorizes them into torch, model, or mlx buckets, and builds environment matrices using deps.yaml and test.yaml.
    3. prepare: Deduplicates environment rows and uses uv to create/refresh environments in parallel, installing base requirements and syncing git dependencies.
    4. Environment Activation & Setup:
      • activate-test-env resolves environment variables such as GPU_COUNT, HAS_SPECIFIC_DEPS, ENV_NAME, and UV_CACHE_DIR.
      • setup-specific-env applies compiler/Python settings and manages package installation/uninstallation rules defined in deps.yaml and blacklist.yaml.
    5. Package Installation: Uses install-package to perform serialized source installs with lock files to prevent race conditions in shared environments.
    6. Execution: Pytest execution and log extraction are handled by the testing utility scripts.
  6. Understand Torch Fused INT4 Transformations for XPU and CPU

    main

    The TorchFusedLinear class uses transform_xpu(dtype) and transform_cpu(dtype) to prepare GPTQ-format tensors for high-performance fused torch.ops.aten kernels. These transformations convert raw quantized weights into specific layouts required by the hardware-optimized matmul operators.

    Core Terminology

    • I: Number of input features.
    • O: Number of output features.
    • B: Quantization bits (fixed at 4).
    • W: Bits per lane in pack_dtype (default 32).
    • pack_factor: W / B (e.g., 8 when B=4).
    • group_size: Number of input channels sharing one (scale, zero) pair.
    • G: Number of groups, calculated as ceil(I / group_size).

    Initial GPTQ v2 Layout

    Immediately after loading, tensors have these shapes:

    • qweight: [I / pack_factor, O] (dtype: pack_dtype, typically int32)
    • qzeros: [G, O / pack_factor] (dtype: pack_dtype, typically int32)
    • scales: [G, O] (dtype: fp16)
    • g_idx: [I] (dtype: int32, maps input channel to group ID)
  7. Understand the GPTQModel Quantization Protocol structure

    main

    The quantization protocol in gptqmodel is a pipeline-based configuration system used to define how a model is quantized. It is designed to be stage-based, where each stage contains a set of rules that match specific model components (modules) and apply operations to them.

    The protocol can be authored in two ways:

    1. Python DSL: An ergonomic builder API for programmatic configuration.
    2. YAML/JSON: A portable serialized format for checked-in configs and non-Python tooling.

    The root of the protocol consists of two primary fields:

    • version: The protocol version.
    • stages: An ordered list of Stage objects defining the execution flow.
    version = 2
    
    stages = [
        Stage(
            name="ptq",
            rules=[
                Rule(
                    match="*",
                    # ... other fields
                ),
            ],
        ),
    ]
  8. Understand Merge and Override Semantics in Quantization Rules

    main

    Rules in the quantization protocol compose from top to bottom within a stage.

    Key Semantics:

    • Defaults vs. Refinement: Broader rules (e.g., match="*") define defaults, while narrower rules (e.g., specific layer names) refine or override them.
    • Merging: Target sections merge recursively by default. However, target-local lists like prepare append by default.
    • Leaf Fields: For quantizer fields (bits, sym, group_size) and exporter fields (format, variant, impl, version), the last-match-wins.
    • Method Changes: If quantize.method or export.format changes, previous fields specific to the old method/format are discarded unless explicitly repeated.
    • Control Flags:
      • skip(): Skips the quantization for the matched target.
      • stop=True: Prevents any subsequent rules from changing the same matched object.
      • mode="replace": Replaces the inherited configuration with only the fields provided in the current rule.
  9. Configure tensor target transformations with `prepare`, `quantize`, and `export`

    main

    Each tensor target (e.g., weight, input, or output) can define three primary stages of the quantization lifecycle:

    1. prepare: Local pre-quantization transformations applied to the target. Use this for target-only modifications like clipping or padding.
      • Example: clip.mad(k=2.75) or pad.columns(multiple=4).
    2. quantize: Defines the method used to compute the quantized state.
      • Example: gptq(bits=4, sym=True) or skip() to bypass quantization.
    3. export: Defines the final encoded representation (format, variant, and implementation) for the target.

    Placement Rule: Use prepare for local target-only modifications. Use actions for modifications that involve cross-target or rule-context logic.

    weight={
        "prepare": [...],     # optional
        "quantize": ...,      # optional
        "export": ...,        # optional
    }
  10. Apply rule-scoped actions vs target-local preparation

    main

    The protocol distinguishes between operations that affect the module context (actions) and operations that affect specific tensors (prepare).

    • actions: Used for rule-scoped or cross-target behavior (e.g., smoothquant, awq_balance, calibrate_router). These run in the context of the rule match but do not rematch the whole model.
    • weight.prepare: Used for target-local pre-quantization behavior (e.g., local weight clipping, padding, or smoothing).

    Decision Guide:

    • If the operation is a balancing step like SmoothQuant: use actions.
    • If the operation is a local transformation on a specific tensor: use weight.prepare.
  11. Apply rules using the Patch-First Override Model

    main

    Rules in the protocol act as patches over an accumulated configuration. A broad rule defines defaults, and narrower rules (matched via regex) patch only specific fields. Unchanged fields are inherited from the broader rule.

    Example Workflow:

    1. A global rule (match: "*") sets method: gptq, bits: 4, and format: gptq.
    2. A specific rule (match: ".*down_proj$") sets bits: 3.
    3. The effective configuration for down_proj becomes: method: gptq, bits: 3, group_size: 128, and format: gptq.

    Advanced: mode: replace By default, rules merge. To bypass merging and explicitly replace the entire target configuration, use mode: replace.

    - match: "*"
      weight:
        quantize:
          method: gptq
          bits: 4
          sym: true
          group_size: 128
        export:
          format: gptq
    
    - match: ".*down_proj$"
      weight:
        quantize:
          bits: 3
  12. Map CUDA APIs to Huawei Ascend NPU equivalents

    main

    When working with Huawei Ascend NPUs using the Ascend Extension for PyTorch (7.3.0) and PyTorch (2.9.0), you must replace torch.cuda.* calls with their corresponding torch_npu.npu.* or torch.npu.* equivalents.

    Key Mapping Rules:

    • For supported APIs, replace the cuda namespace with npu.
    • torch_npu.npu.* and torch.npu.* are functionally equivalent.
    • Graph Support: Most CUDAGraph equivalents (e.g., torch.npu.NPUGraph) are supported for inference only; training is unsupported.
    • Device Properties: torch.npu.get_device_properties only populates name, total_memory, L2_cache_size, cube_core_num, and vector_core_num. Other CUDA properties will be empty.
    • Unverified APIs: Any PyTorch CUDA API not explicitly listed in the support tables should be treated as unverified on NPU.