Skip to content

llmcompressor.entrypoints.higgs.base

HIGGS: Heuristic ILP-Guided Grouped Scheme Mixed-Precision Quantization

MSE collection and high-level API for ILP-based mixed-precision quantization.

Classes:

Functions:

  • get_higgs_config –

    Compute optimal mixed-precision config via ILP on per-layer MSE.

HiggsMSECollectorConverter

HiggsMSECollectorConverter(
    candidate_schemes: List[Union[str, QuantizationScheme]],
    targets: Union[str, List[str]] = "Linear",
    ignore: List[str] = None,
    device: Union[str, device] = None,
    target_avg_bitwidth: Optional[float] = None,
    target_avg_act_bitwidth: Optional[float] = None,
    allow_unquantized: bool = False,
)

Bases: Converter

First-pass converter that collects per-layer MSE data, solves the ILP, and produces an optimal QuantizationConfig. Does NOT modify tensors.

Methods:

  • create_config –

    Solve ILP after all shards processed and return optimized config.

  • process –

    Compute MSE for each candidate scheme; return tensors unchanged.

  • set_weight_names –

    Precompute fused dependencies from the complete checkpoint index.

  • validate –

    Validate HIGGS inputs without materializing checkpoint tensors.

Source code in src/llmcompressor/entrypoints/higgs/base.py
def __init__(
    self,
    candidate_schemes: List[Union[str, QuantizationScheme]],
    targets: Union[str, List[str]] = "Linear",
    ignore: List[str] = None,
    device: Union[str, torch.device] = None,
    target_avg_bitwidth: Optional[float] = None,
    target_avg_act_bitwidth: Optional[float] = None,
    allow_unquantized: bool = False,
):
    self.targets = targets if isinstance(targets, list) else [targets]
    self.ignore = ignore or ["lm_head"]
    self.device = device or torch.device("cpu")
    self.target_avg_bitwidth = target_avg_bitwidth
    self.target_avg_act_bitwidth = target_avg_act_bitwidth
    self.allow_unquantized = allow_unquantized

    self.candidate_schemes = self._resolve_schemes(candidate_schemes)

    self.mse_matrix: Dict[str, Dict[str, float]] = {}
    self.layer_sizes: Dict[str, int] = {}
    self.ilp_solution: Dict[str, str] = {}
    self.optimal_config: Optional[QuantizationConfig] = None
    self._fused_partners: Optional[Dict[str, set[str]]] = None

create_config

create_config() -> QuantizationConfig

Solve ILP after all shards processed and return optimized config.

Source code in src/llmcompressor/entrypoints/higgs/base.py
def create_config(self) -> QuantizationConfig:
    """Solve ILP after all shards processed and return optimized config."""
    if self.optimal_config is not None:
        return self.optimal_config

    logger.info(
        f"Solving ILP for {len(self.mse_matrix)} layers "
        f"with {len(self.candidate_schemes)} candidate schemes"
    )

    alphas = compute_heuristic_alphas(
        list(self.mse_matrix.keys()), self.layer_sizes
    )

    fused_groups = [
        [tensor_name.removesuffix(".weight") for tensor_name in group.values()]
        for group in get_fused_names(f"{name}.weight" for name in self.mse_matrix)
    ]

    def _bitwidths(attr):
        return {
            name: float(getattr(s, attr).num_bits) if getattr(s, attr) else 16.0
            for name, s in self.candidate_schemes.items()
        }

    has_bw = self.target_avg_bitwidth is not None
    has_act = self.target_avg_act_bitwidth is not None

    ilp_candidate_schemes = list(self.candidate_schemes.keys())
    if self.allow_unquantized:
        ilp_candidate_schemes.append(UNQUANTIZED_SCHEME)

    weight_bitwidths = _bitwidths("weights") if has_bw else None
    activation_bitwidths = _bitwidths("input_activations") if has_act else None
    if self.allow_unquantized:
        if weight_bitwidths is not None:
            weight_bitwidths[UNQUANTIZED_SCHEME] = 16.0
        if activation_bitwidths is not None:
            activation_bitwidths[UNQUANTIZED_SCHEME] = 16.0

    self.ilp_solution = solve_ilp_mixed_precision(
        mse_matrix=self.mse_matrix,
        alphas=alphas,
        candidate_schemes=ilp_candidate_schemes,
        fused_groups=fused_groups,
        target_avg_bitwidth=self.target_avg_bitwidth,
        layer_param_counts=self.layer_sizes if (has_bw or has_act) else None,
        scheme_bitwidths=weight_bitwidths,
        target_avg_act_bitwidth=self.target_avg_act_bitwidth,
        scheme_act_bitwidths=activation_bitwidths,
    )

    config_groups = generate_config_groups(
        self.ilp_solution, self.candidate_schemes
    )
    formats = {
        CompressionFormat(s.format) for s in config_groups.values() if s.format
    }
    self.optimal_config = QuantizationConfig(
        config_groups=config_groups,
        format=_flatten_formats(formats).value,
        quantization_status=QuantizationStatus.COMPRESSED,
        ignore=self.ignore,
    )
    logger.info(
        f"ILP optimization complete: {len(config_groups)} config groups generated"
    )
    return self.optimal_config

process

process(
    tensors: Dict[str, Tensor],
) -> Dict[str, torch.Tensor]

Compute MSE for each candidate scheme; return tensors unchanged.

Source code in src/llmcompressor/entrypoints/higgs/base.py
def process(self, tensors: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
    """Compute MSE for each candidate scheme; return tensors unchanged."""
    tensors = split_fused_moe_experts(tensors)
    logger.info(f"Collecting MSE data from shard with {len(tensors)} tensors")

    quantizable_tensors = list(
        match_quantizable_tensors(tensors, self.ignore, self.targets)
    )
    tensor_to_module = {
        tensor_name: module_name for module_name, tensor_name in quantizable_tensors
    }
    matrix_tensor_names = {
        tensor_name
        for tensor_name in tensor_to_module
        if tensors[tensor_name].ndim == 2
    }
    fused_groups = get_fused_names(matrix_tensor_names)

    for tensor_name in matrix_tensor_names:
        module_name = tensor_to_module[tensor_name]
        self.layer_sizes[module_name] = tensors[tensor_name].numel()
        self.mse_matrix.setdefault(module_name, {})

    for scheme_name, scheme in self.candidate_schemes.items():
        fused_tensor_names = set()
        if is_microscale_scheme(scheme):
            for fused_group in fused_groups:
                names = list(fused_group.values())
                fused_mse = compute_fused_layer_mse(
                    {name: tensors[name] for name in names}, scheme, self.device
                )
                for name, mse in fused_mse.items():
                    self.mse_matrix[tensor_to_module[name]][scheme_name] = mse
                fused_tensor_names.update(names)

        for tensor_name in matrix_tensor_names - fused_tensor_names:
            module_name = tensor_to_module[tensor_name]
            self.mse_matrix[module_name][scheme_name] = compute_layer_mse(
                tensors[tensor_name], scheme, self.device
            )

    layers_processed = 0
    for module_name, tensor_name in quantizable_tensors:
        # ``Linear`` is an all-inclusive name target for checkpoint-only
        # conversion, so model-specific non-matrix weights can still
        # match it (for example norm vectors). HIGGS MSE is defined for
        # 2-D weight matrices, so leave vectors out of the ILP.
        if tensors[tensor_name].ndim != 2:
            continue

        if self.allow_unquantized:
            self.mse_matrix[module_name][UNQUANTIZED_SCHEME] = 0.0
        layers_processed += 1

    logger.info(f"Processed {layers_processed} layers in this shard")
    return tensors

set_weight_names

set_weight_names(weight_names: set[str]) -> None

Precompute fused dependencies from the complete checkpoint index.

Source code in src/llmcompressor/entrypoints/higgs/base.py
def set_weight_names(self, weight_names: set[str]) -> None:
    """Precompute fused dependencies from the complete checkpoint index."""
    self._fused_partners = {}
    for fused_group in get_fused_names(weight_names):
        primary, *partners = fused_group.values()
        self._fused_partners[primary] = set(partners)

validate

validate(
    tensors: Dict[str, Tensor],
) -> Dict[str, torch.Tensor]

Validate HIGGS inputs without materializing checkpoint tensors.

Source code in src/llmcompressor/entrypoints/higgs/base.py
def validate(self, tensors: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
    """Validate HIGGS inputs without materializing checkpoint tensors."""
    tensors = split_fused_moe_experts(tensors)
    quantizable_tensors = list(
        match_quantizable_tensors(tensors, self.ignore, self.targets)
    )
    self._validate_tensor_shapes(tensors, quantizable_tensors)

    if not quantizable_tensors:
        logger.warning(
            f"No quantizable tensors. Targets: {self.targets}, "
            f"Ignore: {self.ignore}"
        )
    return tensors

get_higgs_config

get_higgs_config(
    model_stub: Union[str, PathLike],
    candidate_schemes: List[Union[str, QuantizationScheme]],
    targets: Union[str, List[str]] = "Linear",
    ignore: List[str] = None,
    target_avg_bitwidth: Optional[float] = None,
    target_avg_act_bitwidth: Optional[float] = None,
    device: Optional[Union[str, device]] = None,
    allow_unquantized: bool = False,
    return_collector: bool = False,
) -> QuantizationConfig

Compute optimal mixed-precision config via ILP on per-layer MSE.

Reads model weights (model-free, no GPU model load), evaluates each candidate scheme's MSE on every layer, and solves an ILP to minimize weighted MSE under a bitwidth budget.

The returned QuantizationConfig can be applied via oneshot() or model_free_ptq().

Args: model_stub: HuggingFace model ID or path to model directory candidate_schemes: List of quantization schemes to choose from targets: Layer types to quantize (e.g., "Linear") ignore: Layers to skip (e.g., ["lm_head"]) target_avg_bitwidth: Optional constraint on average weight bitwidth target_avg_act_bitwidth: Optional constraint on average activation bitwidth device: Device for MSE computation (GPU recommended) allow_unquantized: Allow the ILP to leave layers unquantized at 16 bits return_collector: Return the collector alongside the optimized config.

Returns: QuantizationConfig with optimized config_groups

Source code in src/llmcompressor/entrypoints/higgs/base.py
def get_higgs_config(
    model_stub: Union[str, os.PathLike],
    candidate_schemes: List[Union[str, QuantizationScheme]],
    targets: Union[str, List[str]] = "Linear",
    ignore: List[str] = None,
    target_avg_bitwidth: Optional[float] = None,
    target_avg_act_bitwidth: Optional[float] = None,
    device: Optional[Union[str, torch.device]] = None,
    allow_unquantized: bool = False,
    return_collector: bool = False,
) -> QuantizationConfig:
    """
    Compute optimal mixed-precision config via ILP on per-layer MSE.

    Reads model weights (model-free, no GPU model load), evaluates each
    candidate scheme's MSE on every layer, and solves an ILP to minimize
    weighted MSE under a bitwidth budget.

    The returned QuantizationConfig can be applied via oneshot() or
    model_free_ptq().

    Args:
        model_stub: HuggingFace model ID or path to model directory
        candidate_schemes: List of quantization schemes to choose from
        targets: Layer types to quantize (e.g., "Linear")
        ignore: Layers to skip (e.g., ["lm_head"])
        target_avg_bitwidth: Optional constraint on average weight bitwidth
        target_avg_act_bitwidth: Optional constraint on average activation bitwidth
        device: Device for MSE computation (GPU recommended)
        allow_unquantized: Allow the ILP to leave layers unquantized at 16 bits
        return_collector: Return the collector alongside the optimized config.

    Returns:
        QuantizationConfig with optimized config_groups
    """
    if device is None:
        device = torch.device("cuda" if torch.accelerator.is_available() else "cpu")

    if ignore is None:
        ignore = ["lm_head"]

    if (
        len(candidate_schemes) + int(allow_unquantized) > 1
        and target_avg_bitwidth is None
    ):
        logger.warning(
            "Using multiple candidate schemes without target_avg_bitwidth constraint. "
            "ILP will select the scheme with lowest MSE for each layer. "
            "Set target_avg_bitwidth to enable true mixed-precision optimization."
        )

    logger.info("=" * 80)
    logger.info("HIGGS: Collecting MSE data and solving ILP...")
    logger.info("=" * 80)
    start = time.time()

    collector = HiggsMSECollectorConverter(
        candidate_schemes=candidate_schemes,
        targets=targets,
        ignore=ignore,
        device=device,
        target_avg_bitwidth=target_avg_bitwidth,
        target_avg_act_bitwidth=target_avg_act_bitwidth,
        allow_unquantized=allow_unquantized,
    )

    model_files = get_checkpoint_files(model_stub)
    weight_map = get_weight_map(model_files)
    collector.set_weight_names(set(weight_map))
    inverse_weight_maps = build_inverse_weight_maps(
        weight_map=weight_map,
        model_files=model_files,
        converters=[collector],
    )

    shard_names = [f for f in model_files if f.endswith("safetensors")]
    logger.info(f"Processing {len(shard_names)} shards for MSE collection...")

    for shard_name in shard_names:
        if shard_name not in inverse_weight_maps:
            continue
        tensors = load_tensors_from_inverse_weight_map(
            inverse_weight_maps[shard_name], torch.device("meta")
        )
        collector.validate(tensors)

    mse_start = time.time()
    for shard_name in shard_names:
        if shard_name not in inverse_weight_maps:
            logger.warning(f"Shard {shard_name} not in inverse_weight_maps, skipping")
            continue

        logger.info(f"Processing shard: {shard_name}")
        tensors = load_tensors_from_inverse_weight_map(
            inverse_weight_maps[shard_name], device
        )
        collector.process(tensors)

    mse_time = time.time() - mse_start
    logger.info(f"MSE collection completed in {mse_time:.2f}s")

    ilp_start = time.time()
    optimal_config = collector.create_config()
    ilp_time = time.time() - ilp_start

    total_time = time.time() - start
    logger.info(
        f"HIGGS complete in {total_time:.2f}s "
        f"(MSE: {mse_time:.2f}s, ILP: {ilp_time:.2f}s): "
        f"{len(optimal_config.config_groups)} config groups"
    )

    if return_collector:
        return optimal_config, collector
    return optimal_config