Repository navigation
Fine-grained quantization: a host quantizer that mixes methods per module - #49818
IlyasMoutawwakil wants to merge 18 commits into
Conversation
|
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. |
8e4e2b9 to
c4b87fa
Compare
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>
c4b87fa to
5441a38
Compare
SunMarc
left a comment
There was a problem hiding this comment.
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.
| 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 | ||
|
|
There was a problem hiding this comment.
can we try to think of a better name ? Also the description is a bit cryptic, so if you can update it
| 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. |
| 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 |
| 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" |
There was a problem hiding this comment.
we try to keep it "modules_to_not_convert" most of the time but there are some exception indeed with bnb
| """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. | ||
| """ |
There was a problem hiding this comment.
keep it simple, i don't think we need that level of detail, also really hard to understand
| def get_loading_attributes(self): | ||
| return {"dtype_plan": self.dtype_plan, "dequantize": self.dequantize} |
There was a problem hiding this comment.
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"): |
There was a problem hiding this comment.
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: |
| 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 |
| 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." | ||
| ) |
There was a problem hiding this comment.
hmmmm a small inconsistency, here you say that the user should set modules_to_not_convert in FineGrainedConfig but FineGrainedConfig don't accept it.
|
[For maintainers] Suggested jobs to run (before merge) run-slow: finegrained |
What.
FineGrainedConfigandFineGrainedHfQuantizer. The config'sdtype_planmaps module patterns to the configsof registered quantization methods, or to
Nonefor full precision. It is the only module selection: every skip-listbecomes a
Noneentry. The quantizer builds one member quantizer per distinct config, and each module loads throughthe 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.
param_needs_quantization,param_element_size) goes to the member that owns its module.update_weight_conversions,update_parallel_plan,validate_environmentand post-load.AutoHfQuantizer.from_config, the same dispatch as a config passed alone. Each works on itsown copy of its config, so the saved config keeps the plan as passed.
skip_list_attributenames the config field that holds it:modules_to_not_convertby default,llm_int8_skip_modulesfor bitsandbytes. The host writes the scope there, onthe member's config copy. After each member's hook, the host checks the member replaced only its own modules.
checkpoint_module_names). A fusedmodule, such as
experts, has one name per piece, e.g.experts.3.gate_proj. It takes an entry only when all itspieces have the same one. An entry that matches no module raises.
get_quantize_opsreturnsMemberQuantize. 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-dequantizedmodel never loads.
Its op,
MemberDispatch, runs each module's tensors through its own member's version. Versions that agree and runonly model ops stay plain. So a member's ops never see the host.
is_serializable,is_trainable,is_compileable) need every member.What a member must do. A registered quantizer can be a member. It must:
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;
dequantize, ...) from its config, where the host sets them;The
FineGrainedHfQuantizerdocstring 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'sconfig. Here a plan entry's config lends to the plan, e.g.
Fp8Config(dequantize=True)on a mixed checkpoint. Itsskip-list joins the plan as
Noneentries. A passed plan adds only itsNoneentries anddequantize. The mergelives in
FineGrainedConfig, so the merge inAutoHfQuantizerstays 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.pyruns the host on two test-only quantizers that are notblock-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/bnbpasses withRUN_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