Skip to content

llmcompressor.entrypoints.higgs

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

Modules:

  • base –

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

  • ilp_solver –

    ILP-based optimization for mixed-precision quantization scheme selection.

  • utils –

    Utility functions for HIGGS mixed-precision quantization.

Classes:

Functions:

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

compute_fused_layer_mse

compute_fused_layer_mse(weights, scheme, device=None)

Compute MSE for layers that share an NVFP4 global scale.

Source code in src/llmcompressor/entrypoints/higgs/utils.py
def compute_fused_layer_mse(weights, scheme, device=None):
    """Compute MSE for layers that share an NVFP4 global scale."""
    try:
        modules = {}
        for name, weight in weights.items():
            device = device or weight.device
            weight = weight.to(device)
            out_features, in_features = weight.shape
            module = torch.nn.Linear(
                in_features, out_features, bias=False, device="meta"
            )
            module.weight = torch.nn.Parameter(weight, requires_grad=False)
            initialize_module_for_quantization(module, scheme, force_zero_point=False)
            initialize_observer(module, "weight")
            apply_calibration_status(module)
            modules[name] = module

        FusionHandler.fuse(
            [(module.weight_observer, module) for module in modules.values()]
        )
        observe(modules.values(), base_name="weight")
        update_qparams(modules.values(), base_name="weight")

        mse = {}
        for name, module in modules.items():
            scale = module.weight_scale
            zero_point = getattr(module, "weight_zero_point", torch.zeros_like(scale))
            quantized = fake_quantize(
                x=module.weight,
                scale=scale,
                zero_point=zero_point,
                args=scheme.weights,
                global_scale=getattr(module, "weight_global_scale", None),
            )
            mse[name] = torch.mean((module.weight - quantized) ** 2).item()
            freeze_module_quantization(module)

        return mse

    except Exception as e:
        logger.warning(
            f"Failed to compute MSE for scheme {scheme}: {e}. Returning inf."
        )
        return {name: float("inf") for name in weights}

compute_heuristic_alphas

compute_heuristic_alphas(
    layer_names: List[str],
    layer_param_counts: Dict[str, int],
) -> Dict[str, float]

Compute importance weights: log(size+1) * (1 + depth*0.05) * type_multiplier.

Source code in src/llmcompressor/entrypoints/higgs/utils.py
def compute_heuristic_alphas(
    layer_names: List[str],
    layer_param_counts: Dict[str, int],
) -> Dict[str, float]:
    """Compute importance weights: log(size+1) * (1 + depth*0.05) * type_multiplier."""
    alphas = {}
    for name in layer_names:
        size = layer_param_counts.get(name, 0)
        if size == 0:
            alphas[name] = 1.0
            continue

        depth_match = _DEPTH_RE.search(name)
        depth = int(depth_match.group(1)) if depth_match else 0

        type_mult = 1.0
        lower = name.lower()
        for keywords, mult in _TYPE_KEYWORDS.values():
            if any(kw in lower for kw in keywords):
                type_mult = mult
                break

        alphas[name] = float(np.log(size + 1) * (1 + depth * 0.05) * type_mult)

    if alphas:
        vals = list(alphas.values())
        logger.info(
            f"Heuristic alphas for {len(alphas)} layers: "
            f"range=[{min(vals):.2f}, {max(vals):.2f}], mean={np.mean(vals):.2f}"
        )
    return alphas

compute_layer_mse

compute_layer_mse(weight, scheme, device=None)

Compute MSE between original and fake-quantized weight.

Source code in src/llmcompressor/entrypoints/higgs/utils.py
def compute_layer_mse(weight, scheme, device=None):
    """Compute MSE between original and fake-quantized weight."""
    return compute_fused_layer_mse({"weight": weight}, scheme, device)["weight"]

generate_config_groups

generate_config_groups(
    ilp_solution: Dict[str, str],
    candidate_schemes: Dict[str, QuantizationScheme],
) -> Dict[str, QuantizationScheme]

Convert ILP assignments into config groups with targets and formats.

Source code in src/llmcompressor/entrypoints/higgs/utils.py
def generate_config_groups(
    ilp_solution: Dict[str, str],
    candidate_schemes: Dict[str, QuantizationScheme],
) -> Dict[str, QuantizationScheme]:
    """Convert ILP assignments into config groups with targets and formats."""
    scheme_to_layers: dict[str, list[str]] = defaultdict(list)
    for layer, scheme_name in ilp_solution.items():
        scheme_to_layers[scheme_name].append(layer)

    config_groups = {}
    quantized_groups = [
        item
        for item in sorted(scheme_to_layers.items())
        if item[0] != UNQUANTIZED_SCHEME
    ]
    for idx, (scheme_name, layer_list) in enumerate(quantized_groups):
        base_scheme = candidate_schemes.get(scheme_name)
        if base_scheme is None:
            logger.warning(f"Scheme {scheme_name} not in candidate_schemes, skipping")
            continue

        scheme_dict = base_scheme.model_dump()
        scheme_dict["targets"] = _collapse_expert_patterns(sorted(layer_list))

        if base_scheme.format is None:
            dummy = torch.nn.Linear(64, 64, bias=False)
            initialize_module_for_quantization(
                dummy, base_scheme, force_zero_point=False
            )
            scheme_dict["format"] = infer_module_format(type(dummy), base_scheme).value

        group_name = f"group_{idx}"
        config_groups[group_name] = QuantizationScheme(**scheme_dict)
        logger.info(f"Config group '{group_name}': {len(layer_list)} layers")

    unquantized_layers = scheme_to_layers.get(UNQUANTIZED_SCHEME, [])
    if unquantized_layers:
        logger.info(f"Leaving {len(unquantized_layers)} layers unquantized")

    return config_groups

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

solve_ilp_mixed_precision

solve_ilp_mixed_precision(
    mse_matrix: Dict[str, Dict[str, float]],
    alphas: Dict[str, float],
    candidate_schemes: List[str],
    fused_groups: List[List[str]] = None,
    target_avg_bitwidth: Optional[float] = None,
    layer_param_counts: Optional[Dict[str, int]] = None,
    scheme_bitwidths: Optional[Dict[str, float]] = None,
    target_avg_act_bitwidth: Optional[float] = None,
    scheme_act_bitwidths: Optional[Dict[str, float]] = None,
) -> Dict[str, str]

Solve ILP to select optimal quantization scheme for each layer.

Formulation: Decision variables: x[layer][scheme] ∈ {0, 1}

Objective:
    minimize: Σ_layer Σ_scheme (
        MSE[layer][scheme] * alpha[layer] * x[layer][scheme]
    )

Constraints:
    1. Each layer gets exactly one scheme:
       Σ_scheme x[layer][scheme] = 1  ∀ layer

    2. Fused layers use same scheme (if fused_groups provided):
       x[layer_i][scheme] = x[layer_j][scheme]  ∀ scheme,
       ∀ (layer_i, layer_j) in same group

    3. Optional: Average weight bitwidth constraint
       (if target_avg_bitwidth provided):
       Σ_layer (bitwidth[scheme] * params[layer] * x[layer][scheme])
       / Σ_layer params[layer] <= target_avg_bitwidth

    4. Optional: Average activation bitwidth constraint
       (if target_avg_act_bitwidth provided):
       Σ_layer (act_bitwidth[scheme] * params[layer] * x[layer][scheme])
       / Σ_layer params[layer] <= target_avg_act_bitwidth

Args: mse_matrix: Nested dict mapping layer_name -> scheme_name -> mse_value alphas: Dict mapping layer_name -> importance weight candidate_schemes: List of scheme names (must match keys in mse_matrix) fused_groups: Optional list of layer name groups that must use same scheme target_avg_bitwidth: Optional constraint on weighted average weight bitwidth layer_param_counts: Required if either average bitwidth target is set scheme_bitwidths: Required if target_avg_bitwidth is set target_avg_act_bitwidth: Optional constraint on weighted average activation bitwidth scheme_act_bitwidths: Required if target_avg_act_bitwidth is set

Returns: Dict mapping layer_name -> selected_scheme_name

Raises: ValueError: If ILP is infeasible or unbounded

Source code in src/llmcompressor/entrypoints/higgs/ilp_solver.py
def solve_ilp_mixed_precision(
    mse_matrix: Dict[str, Dict[str, float]],
    alphas: Dict[str, float],
    candidate_schemes: List[str],
    fused_groups: List[List[str]] = None,
    target_avg_bitwidth: Optional[float] = None,
    layer_param_counts: Optional[Dict[str, int]] = None,
    scheme_bitwidths: Optional[Dict[str, float]] = None,
    target_avg_act_bitwidth: Optional[float] = None,
    scheme_act_bitwidths: Optional[Dict[str, float]] = None,
) -> Dict[str, str]:
    """
    Solve ILP to select optimal quantization scheme for each layer.

    Formulation:
        Decision variables: x[layer][scheme] ∈ {0, 1}

        Objective:
            minimize: Σ_layer Σ_scheme (
                MSE[layer][scheme] * alpha[layer] * x[layer][scheme]
            )

        Constraints:
            1. Each layer gets exactly one scheme:
               Σ_scheme x[layer][scheme] = 1  ∀ layer

            2. Fused layers use same scheme (if fused_groups provided):
               x[layer_i][scheme] = x[layer_j][scheme]  ∀ scheme,
               ∀ (layer_i, layer_j) in same group

            3. Optional: Average weight bitwidth constraint
               (if target_avg_bitwidth provided):
               Σ_layer (bitwidth[scheme] * params[layer] * x[layer][scheme])
               / Σ_layer params[layer] <= target_avg_bitwidth

            4. Optional: Average activation bitwidth constraint
               (if target_avg_act_bitwidth provided):
               Σ_layer (act_bitwidth[scheme] * params[layer] * x[layer][scheme])
               / Σ_layer params[layer] <= target_avg_act_bitwidth

    Args:
        mse_matrix: Nested dict mapping layer_name -> scheme_name -> mse_value
        alphas: Dict mapping layer_name -> importance weight
        candidate_schemes: List of scheme names (must match keys in mse_matrix)
        fused_groups: Optional list of layer name groups that must use same scheme
        target_avg_bitwidth: Optional constraint on weighted average weight bitwidth
        layer_param_counts: Required if either average bitwidth target is set
        scheme_bitwidths: Required if target_avg_bitwidth is set
        target_avg_act_bitwidth: Optional constraint on weighted average
            activation bitwidth
        scheme_act_bitwidths: Required if target_avg_act_bitwidth is set

    Returns:
        Dict mapping layer_name -> selected_scheme_name

    Raises:
        ValueError: If ILP is infeasible or unbounded
    """
    if pulp is None:
        raise ImportError(
            "HIGGS ILP solver requires the 'pulp' package. "
            "Install with: pip install llmcompressor[higgs]"
        )

    if fused_groups is None:
        fused_groups = []

    # Validate inputs
    if target_avg_bitwidth is not None:
        if layer_param_counts is None or scheme_bitwidths is None:
            raise ValueError(
                "target_avg_bitwidth requires layer_param_counts and scheme_bitwidths"
            )
    if target_avg_act_bitwidth is not None:
        if layer_param_counts is None or scheme_act_bitwidths is None:
            raise ValueError(
                "target_avg_act_bitwidth requires layer_param_counts and "
                "scheme_act_bitwidths"
            )

    # Create ILP problem
    prob = pulp.LpProblem("MixedPrecisionQuantization", pulp.LpMinimize)

    # Decision variables: x[layer][scheme] ∈ {0, 1}
    x = {}
    for layer in mse_matrix:
        x[layer] = {}
        for scheme in candidate_schemes:
            variable_name = f"x_{_sanitize_name(layer)}_{scheme}"
            if hasattr(prob, "add_variable"):
                x[layer][scheme] = prob.add_variable(
                    name=variable_name,
                    cat=pulp.LpBinary,
                )
            else:
                # Compatibility with PuLP versions before add_variable was
                # introduced. Direct construction is not deprecated there.
                x[layer][scheme] = pulp.LpVariable(
                    variable_name,
                    cat=pulp.LpBinary,
                )

    # Objective: minimize weighted MSE
    objective_terms = []
    for layer in mse_matrix:
        alpha = alphas.get(layer, 1.0)  # Default alpha = 1.0 if missing
        for scheme in candidate_schemes:
            mse = mse_matrix[layer].get(scheme, float("inf"))
            mse = max(min(1e10, mse), 0)  # clamp between 0 and 1e10
            objective_terms.append(mse * alpha * x[layer][scheme])

    prob += pulp.lpSum(objective_terms), "WeightedMSE"

    # Constraint 1: Each layer gets exactly one scheme
    for layer in mse_matrix:
        prob += (
            pulp.lpSum([x[layer][scheme] for scheme in candidate_schemes]) == 1,
            f"OneSchemePerLayer_{_sanitize_name(layer)}",
        )

    # Constraint 2: Fused layers use same scheme
    for group_idx, group in enumerate(fused_groups):
        if len(group) < 2:
            continue

        base_layer = group[0]
        if base_layer not in mse_matrix:
            logger.warning(
                f"Fused group layer {base_layer} not in MSE matrix, skipping"
            )
            continue

        for other_layer in group[1:]:
            if other_layer not in mse_matrix:
                logger.warning(
                    f"Fused group layer {other_layer} not in MSE matrix, skipping"
                )
                continue

            for scheme in candidate_schemes:
                prob += (
                    x[base_layer][scheme] - x[other_layer][scheme] == 0,
                    f"FusedGroup{group_idx}_{_sanitize_name(base_layer)}_{_sanitize_name(other_layer)}_{scheme}",
                )

    # Constraint 3: Optional average bitwidth constraint
    if target_avg_bitwidth is not None:
        total_params = sum(layer_param_counts.get(layer, 0) for layer in mse_matrix)

        if total_params == 0:
            logger.warning("Total parameter count is 0, skipping bitwidth constraint")
        else:
            weighted_bitwidth_terms = []
            for layer in mse_matrix:
                param_fraction = layer_param_counts.get(layer, 0) / total_params
                for scheme in candidate_schemes:
                    bitwidth = scheme_bitwidths.get(scheme, 0)
                    weighted_bitwidth_terms.append(
                        bitwidth * param_fraction * x[layer][scheme]
                    )

            # Average bitwidth = sum(bitwidth * params * x) / total_params
            prob += (
                pulp.lpSum(weighted_bitwidth_terms) <= target_avg_bitwidth,
                "AverageWeightBitwidthConstraint",
            )

    # Constraint 4: Optional average activation bitwidth constraint
    # NOTE: actual number of activation elements will be proportional to in_features
    # rather than in_features * out_features = params. However we should probably
    # just use actual performance numbers at the end of the day.
    if target_avg_act_bitwidth is not None:
        total_params = sum(layer_param_counts.get(layer, 0) for layer in mse_matrix)

        if total_params == 0:
            logger.warning(
                "Total parameter count is 0, skipping activation bitwidth constraint"
            )
        else:
            weighted_act_bitwidth_terms = []
            for layer in mse_matrix:
                param_fraction = layer_param_counts.get(layer, 0) / total_params
                for scheme in candidate_schemes:
                    act_bitwidth = scheme_act_bitwidths.get(scheme, 16.0)
                    weighted_act_bitwidth_terms.append(
                        act_bitwidth * param_fraction * x[layer][scheme]
                    )

            prob += (
                pulp.lpSum(weighted_act_bitwidth_terms) <= target_avg_act_bitwidth,
                "AverageActBitwidthConstraint",
            )

    # Solve the ILP
    logger.info(
        f"Solving ILP with {len(mse_matrix)} layers and "
        f"{len(candidate_schemes)} schemes"
    )
    logger.info(f"  Variables: {sum(len(x[layer]) for layer in x)}")
    logger.info(f"  Fused groups: {len([g for g in fused_groups if len(g) >= 2])}")

    # Use CBC through the non-deprecated COIN_CMD interface. Older PuLP
    # versions bundle the executable under PULP_CBC_CMD, so reuse that path
    # without constructing the deprecated solver class.
    bundled_cbc_path = getattr(
        getattr(pulp, "PULP_CBC_CMD", None), "pulp_cbc_path", None
    )
    solver = pulp.COIN_CMD(
        path=bundled_cbc_path,
        msg=0,
        timeLimit=300,
    )  # 5 minute timeout
    status = prob.solve(solver)

    # Check solution status
    status_name = pulp.LpStatus[status]
    logger.info(f"ILP solver status: {status_name}")

    if status != pulp.LpStatusOptimal:
        raise ValueError(
            f"ILP solver failed with status: {status_name}. "
            f"Problem may be infeasible or unbounded."
        )

    # Extract solution
    solution = {}
    for layer in mse_matrix:
        for scheme in candidate_schemes:
            if pulp.value(x[layer][scheme]) > 0.5:  # Binary variable = 1
                solution[layer] = scheme
                break

        # Sanity check: every layer should have a scheme
        if layer not in solution:
            logger.error(f"Layer {layer} has no scheme assigned in ILP solution!")
            # Assign first scheme as fallback
            solution[layer] = candidate_schemes[0]

    # Log objective value
    objective_value = pulp.value(prob.objective)
    logger.info(f"ILP optimal objective value: {objective_value:.6f}")

    # Log scheme distribution
    scheme_counts = {}
    for scheme in solution.values():
        scheme_counts[scheme] = scheme_counts.get(scheme, 0) + 1
    logger.info(f"Scheme distribution: {scheme_counts}")

    return solution