Skip to content

Fine-grained quantization: a host quantizer that mixes methods per module - #49818

Draft
IlyasMoutawwakil wants to merge 18 commits into
fg-split/3-experts-tpfrom
fg-split/4a-host
Draft

IlyasMoutawwakil wants to merge 18 commits into
fg-split/3-experts-tpfrom
fg-split/4a-host

Conversation

@IlyasMoutawwakil

@IlyasMoutawwakil IlyasMoutawwakil commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

🤗 Transformers CI

What. FineGrainedConfig and FineGrainedHfQuantizer. The config's dtype_plan maps module patterns to the configs
of registered quantization methods, or to None for full precision. It is the only module selection: every skip-list
becomes a None entry. The quantizer builds one member quantizer per distinct config, and each module loads through
the member of its entry. DeepSeek-V4 is the case that needs it: MXFP4 experts over block-FP8 linears.
No shipped method is used here. The block-scaled formats come in the next PRs.

Why a host, and not a base class. The block-scaled formats share code, and that lives in BlockScaledQuantizer
(next PR). Mixing methods in one model is a separate job, so the host only routes and composes. It does not know
any format.

How the host composes members.

  • A hook on one tensor (param_needs_quantization, param_element_size) goes to the member that owns its module.
  • A hook on the whole model runs on every member: module replacement, update_weight_conversions,
    update_parallel_plan, validate_environment and post-load.
  • Members are built with AutoHfQuantizer.from_config, the same dispatch as a config passed alone. Each works on its
    own copy of its config, so the saved config keeps the plan as passed.
  • The host scopes each member through its own skip-list. skip_list_attribute names the config field that holds it:
    modules_to_not_convert by default, llm_int8_skip_modules for bitsandbytes. The host writes the scope there, on
    the member's config copy. After each member's hook, the host checks the member replaced only its own modules.
  • The plan resolves once, over the names each module has in the checkpoint (checkpoint_module_names). A fused
    module, such as experts, has one name per piece, e.g. experts.3.gate_proj. It takes an entry only when all its
    pieces have the same one. An entry that matches no module raises.
  • get_quantize_ops returns MemberQuantize. It hands each tensor to its owner's quantize op when it runs.
  • validate_environment: if one member falls back to a dequantized load, the whole model does. A half-dequantized
    model never loads.
  • Each member updates its own copy of the model's conversions. Versions that read the same keys become one converter.
    Its op, MemberDispatch, runs each module's tensors through its own member's version. Versions that agree and run
    only model ops stay plain. So a member's ops never see the host.
  • Hooks with one answer (is_serializable, is_trainable, is_compileable) need every member.

What a member must do. A registered quantizer can be a member. It must:

  • build its skip-list with get_modules_to_not_convert. 19 of the 27 in-tree quantizers do, bitsandbytes included.
    The others join once they make that one call. Until then a plan with one raises at load and names the helper;
  • take its loading options (dequantize, ...) from its config, where the host sets them;
  • keep its whole-model hooks to its own modules, or make them safe to run once per member.

The FineGrainedHfQuantizer docstring says the same.

Hooks and why they exist.

  • loading_attributes_source: lets a passed config of another class lend its loading options to a checkpoint's
    config. Here a plan entry's config lends to the plan, e.g. Fp8Config(dequantize=True) on a mixed checkpoint. Its
    skip-list joins the plan as None entries. A passed plan adds only its None entries and dequantize. The merge
    lives in FineGrainedConfig, so the merge in AutoHfQuantizer stays as on main.
  • HfQuantizer.skip_list_attribute: the config field of a method's skip-list, where the host writes a member's scope.

Depends on. #49775.

How tested. tests/quantization/finegrained/test_host.py runs the host on two test-only quantizers that are not
block-scaled, over a tiny Llama. It covers routing, scoping, the ownership check, the shared skip-list, a plan without
a catch-all, the saved config, the single fallback, the conversion dispatch, the dtype routing, fused modules named
per piece and unmatched entries, on CPU. A GPU test
mixes bitsandbytes 4-bit MLPs with 8-bit attention: it loads, matches the bf16 logits, saves and reloads.
tests/quantization/bnb passes with RUN_SLOW=1.

The comments and docstrings that say why each change exists are there for readability. Feel free to ask for any of them to go if it's self-evident.

🤖 Generated with Claude Code

@IlyasMoutawwakil IlyasMoutawwakil changed the title fg split/4a host Fine-grained quantization: a host quantizer that mixes methods per module Oct 21, 2026
@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@IlyasMoutawwakil IlyasMoutawwakil changed the title Fine-grained quantization: a host quantizer that mixes methods per module 🚨 Fine-grained quantization: a host quantizer that mixes methods per module Oct 21, 2026
@IlyasMoutawwakil IlyasMoutawwakil changed the title 🚨 Fine-grained quantization: a host quantizer that mixes methods per module Fine-grained quantization: a host quantizer that mixes methods per module Oct 22, 2026
IlyasMoutawwakil and others added 17 commits October 23, 2026 13:34
FineGrainedConfig maps module patterns to the configs of registered quantization methods.
FineGrainedHfQuantizer builds one member quantizer per config. A hook on one tensor goes to the member
that owns its module. A hook on the whole model runs on every member, each limited to its own modules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The host routes shared ops through member_for only, and loads a converter in the dtype of the member that
added it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…onfig

A None entry keeps its modules in full precision and wins over any other entry. modules_to_not_convert and the
model's default skips load as None entries, so the host scopes each member from the plan alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A member's skip entry also matched container modules. When checkpoint names differ, as in a VLM, the skip-list
then took the whole sub-tree, so the member converted nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The skip-list and the fp32 modules always win. A default skip such as a tied lm_head no longer overrides an entry
that names it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dedupe_conversions is private to the host. loading_attributes_lender is named loading_attributes_source.
FineGrainedConfig drops modules_to_not_convert, which never shipped: full-precision modules are None entries, and
a passed format config's skip-list joins the plan as None entries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The loader takes the quantize op before it reads the tensor. The host's op finds the member when it runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… a plan

- The host scopes each member through dtype_plan_skip, which get_modules_to_not_convert returns.
- A member that converts another entry's module raises.
- Members are built and read through the same dispatch as a config passed alone.
- Conversions of several members that read the same keys become one converter, which runs each module through
  its own member's version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The post-load hook rebuilds each member's versions from the conversions the loader kept.
- A merged converter copies the patterns as passed, so it reverses like its versions.
- WeightTransform keeps a copy of a passed pattern list. It processed the caller's list in place, so a reverse
  rewrote the original's own patterns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each quantizer names its skip-list field with skip_list_attribute. The host writes a member's scope there, on the member's own config copy. get_modules_to_not_convert stays a static method, as on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
checkpoint_module_names gives each module its checkpoint names, with one name per piece for a fused module. A fused module takes an entry only when all its pieces have it. An entry that matches no module raises.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
loading_attributes_source returns the merged plan, so the merge in AutoHfQuantizer stays as on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
_resolve_plan already knows which patterns hit each checkpoint name. Searching the whole plan again for each name made resolution scale with names times patterns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@SunMarc SunMarc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Couple of comments, thanks for enabling mixed quants !

One thing we need to be a tad careful is when loading a config that was mixed from the start e.g deepseek one with expert_dtype, we should keep the same config if possible when saving or we need to add compatibly with other engines so that they support our new config. But we can probably look at that later on as I see you deal with deepspeek case in another pr.

Comment on lines +207 to +216
def loading_attributes_source(self, config: "QuantizationConfigMixin") -> Optional["QuantizationConfigMixin"]:
"""
Return the config whose loading attributes override this checkpoint config.

`config` is the config passed to `from_pretrained`. Return `None` if it cannot override this one.
By default only a config of the same class can. A method may accept others, e.g. a `FineGrainedConfig`
checkpoint takes the config of one of its plan entries.
"""
return config if config.__class__.__name__ == self.__class__.__name__ else None

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we try to think of a better name ? Also the description is a bit cryptic, so if you can update it

Comment on lines +1775 to +1777
def loading_attributes_source(self, config):
# A passed plan adds its `None` entries to this plan. The config of an entry's method adds its skip-list as
# `None` entries. The weights keep this plan's formats.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here

Comment on lines +264 to +271
if quantization_config_from_args is not None:
source = quantization_config.loading_attributes_source(quantization_config_from_args)
if source is None:
raise ValueError(
f"The model is quantized with {quantization_config.__class__.__name__} but you are passing a {quantization_config_from_args.__class__.__name__} config. "
"Please make sure to pass the same quantization config class to `from_pretrained` with different loading attributes."
)
quantization_config_from_args = source

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice !

Comment on lines +90 to +97
skip_list_attribute (`str`):
The config field that holds this method's skip-list. [`FineGrainedHfQuantizer`] writes the modules a
member must leave there, on the member's own copy of its config.
"""

requires_calibration = False
dequantized_saves_unquantized = False
skip_list_attribute = "modules_to_not_convert"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we try to keep it "modules_to_not_convert" most of the time but there are some exception indeed with bnb

Comment on lines +33 to +46
"""Quantizer that hosts one member quantizer per config in the config's `dtype_plan`.

A hook on one tensor goes to the member that owns its module. A hook on the whole model runs on every member.
DeepSeek-V4 is an example, with MXFP4 experts and block FP8 linears.

A registered quantizer can be a member. The host relies on it to:
- build its skip-list with `get_modules_to_not_convert`, from the config field `skip_list_attribute` names. The host
writes each member's scope there. A member that converts a module of another entry raises.
- take its loading options, such as `dequantize`, from its config. The host sets them on the member's own copy.
- keep its whole-model hooks to its own modules, or make them safe to run once per member.

Each member updates its own copy of the model's conversions. Conversions of several members that read the same
keys become one converter, which runs each module's tensors through its own member's version.
"""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

keep it simple, i don't think we need that level of detail, also really hard to understand

Comment on lines +1772 to +1773
def get_loading_attributes(self):
return {"dtype_plan": self.dtype_plan, "dequantize": self.dequantize}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we shouldn't allow users to change dtype_plan once the model is quantized no ?

"`get_modules_to_not_convert`."
)

def _resolve_plan(self, model: "PreTrainedModel"):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move some methods to quantization utils if possible. Let's try to keep quantizer_finegrained light.

setattr(model, "_weight_conversions", self._merge(given, updated))
return model

def _merge(self, given: list, versions: list[list]) -> list:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here

Comment on lines +318 to +344
def _parents(name: str) -> list[str]:
"""Return the names of the modules above `name`, e.g. `a` and `a.b` for `a.b.c`."""
parts = name.split(".")
return [".".join(parts[:end]) for end in range(1, len(parts))]


def _skip_unowned(own: list[str], others: list[str], parents: set[str]) -> str:
"""Return a skip-list entry that matches every module a member with the `own` patterns does not own.

Another entry's targeted pattern wins over a catch-all. A member without the catch-all owns only what its patterns
match. The entry never matches one of `parents`, the modules above the ones the member owns.
"""
unowned = []
if targeted := [pattern for pattern in others if pattern != ".*"]:
unowned.append(f"(?=.*(?:{'|'.join(targeted)}))")
if ".*" not in own:
unowned.append(f"(?!.*(?:{'|'.join(own)}))")
if not unowned:
return "(?!)"
kept = f"(?!(?:{'|'.join(map(re.escape, sorted(parents)))})$)" if parents else ""
return f"{kept}(?:{'|'.join(unowned)}).*"


def _signature(conversion) -> tuple:
"""Return what a conversion does: the keys it reads, where they go and the ops they run through."""
operations = tuple(type(op).__name__ for op in getattr(conversion, "operations", ()))
return type(conversion), tuple(conversion.source_patterns), tuple(conversion.target_patterns), operations

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and those

Comment on lines +1750 to +1755
loading = [name for name in self._entry_loading_options if getattr(entry, name, None)]
if loading:
raise ValueError(
f"dtype_plan entry {pattern!r} sets {loading}. They hold for the whole model, so set them on the "
"FineGrainedConfig."
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmmmm a small inconsistency, here you say that the user should set modules_to_not_convert in FineGrainedConfig but FineGrainedConfig don't accept it.

@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: finegrained

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants