Repository navigation
Fine-grained block-scaled quantization: the shared machinery - #49776
IlyasMoutawwakil wants to merge 9 commits into
Conversation
eba7591 to
f85bc92
Compare
|
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. |
9072093 to
e4e40b2
Compare
5732607 to
637929d
Compare
637929d to
f324300
Compare
f324300 to
4abab57
Compare
4abab57 to
18bcfa2
Compare
vasqu
left a comment
There was a problem hiding this comment.
Ok longer review but I have no brain power when the actual quantizers / configs started
One thing that imo became clearer to me: Deepgemm looks like it doesn't hold much value for the code workarounds we need for it. Imo, yes perf is important but it's just too clashing and bloats things so much
|
|
||
| ## BlockScaledConfig | ||
|
|
||
| The base class of the block-scaled format configs below. Build one of those configs instead. |
There was a problem hiding this comment.
| The base class of the block-scaled format configs below. Build one of those configs instead. |
imo we just list here?
| ## Requirements | ||
|
|
||
| ```bash | ||
| pip install --upgrade accelerate "kernels>=0.17.2,<0.18" |
There was a problem hiding this comment.
I think you can do pip install "transformers[kernels]" or similar
| or newer. Without them, a pre-quantized checkpoint is dequantized to bf16 as it loads. Quantizing on the fly raises | ||
| an error. | ||
|
|
||
| ## Load, quantize and save |
There was a problem hiding this comment.
we are missing examples! imo less text and just show it
| ## Tensor and expert parallelism | ||
|
|
||
| Pass a [`DistributedConfig`] to [`~PreTrainedModel.from_pretrained`] to shard a quantized model. Each scale is sharded | ||
| with its weight. Quantized experts use [masking and all-reduce](../expert_parallelism) expert parallelism instead of | ||
| token dispatch. This is why `ep_size` must equal `tp_size`. |
There was a problem hiding this comment.
Imo could be a warning instead because of the requirement of ep == tp
| with its weight. Quantized experts use [masking and all-reduce](../expert_parallelism) expert parallelism instead of | ||
| token dispatch. This is why `ep_size` must equal `tp_size`. | ||
|
|
||
| ## Kernel autotuning |
| loading_attr_dict = quantization_config_from_args.get_loading_attributes() | ||
| for attr, val in loading_attr_dict.items(): | ||
| if attr == "dtype_plan" and isinstance(quantization_config, FineGrainedConfig): | ||
| val = _with_activation_formats(quantization_config.dtype_plan, val) |
There was a problem hiding this comment.
some inplace stuff? do we even need a return then?
There was a problem hiding this comment.
Why a utils? A bit weird, maybe a folder as we will add other ones in the future?
There was a problem hiding this comment.
by a folder you mean moving all quantizers that are block scaled to the same plase, but the idea here is to keep the nvfp4/mxfp4 quantizer and just extend them, lmk if you'd rather we drop them and start in a folder because that clashes a bit with arthur's "any quantizer can be finegrained" idea
There was a problem hiding this comment.
block_scaled != finegrained
block scaled = fp8,mxfp4,nvfp4,mxfp8
finegrained = any quantizer
There was a problem hiding this comment.
also i don't see any reference to BlockScaledConfig in the docs, is this something the user should use ?
| model._weight_conversions = self.update_weight_conversions(model._weight_conversions, model, for_save=True) | ||
| return model | ||
|
|
||
| def _missing_requirement(self) -> str | None: |
| unused_kwargs = {key: value for key, value in kwargs.items() if key not in to_remove} | ||
| return unused_kwargs | ||
|
|
||
| def loading_attributes_lender(self, config: "QuantizationConfigMixin") -> Optional["QuantizationConfigMixin"]: |
There was a problem hiding this comment.
this is important to note no? We have a priority we intro here
| ) | ||
|
|
||
| def get_loading_attributes(self): | ||
| return _loading_attributes(self, activation_format=self.activation_format) |
bd1d85b to
6d87752
Compare
6d87752 to
823b19a
Compare
3e8f877 to
d1dcda7
Compare
1e027a8 to
a6724ee
Compare
BlockScaledQuantizer holds what the block-scaled formats share: the fine-grained linear, grouped linear and experts modules, their load and save ops, the scale layouts, the device requirements and the dequantize fallback. Each format quantizer subclasses it. FineGrainedHfQuantizer can host them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The base no longer has its own format hooks. A format overrides get_weight_conversions, update_weight_conversions or update_parallel_plan and calls super(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The host now gives each member its own version of a shared conversion, so an op never sees the host. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
a6724ee to
49cbba8
Compare
SunMarc
left a comment
There was a problem hiding this comment.
Left couples of comments ! Thanks !
| rendered properly in your Markdown viewer. | ||
|
|
||
| --> | ||
|
|
There was a problem hiding this comment.
please update to that it is simpler: less text and more example, illustrations
| class _FineGrainedOp(ConversionOps): | ||
| """Base op that carries the quantizer that built it. | ||
|
|
||
| Its reverse is the same op with `inverse` flipped. Ops that reverse into another op override `reverse_op`. | ||
| """ | ||
|
|
||
| def __init__(self, hf_quantizer=None, inverse: bool = False): | ||
| self.hf_quantizer = hf_quantizer | ||
| self.inverse = inverse | ||
|
|
||
| @property | ||
| def reverse_op(self) -> ConversionOps: | ||
| return type(self)(self.hf_quantizer, inverse=not self.inverse) |
There was a problem hiding this comment.
we should probably create class for quantizer in general then QuantizationOps, so that we reuse this across the other conversion ops related to quants
| if value.device.type not in ("cuda", "xpu"): | ||
| raise ValueError( | ||
| f"on-the-fly {module.weight_format} quantization runs the kernels' quantizers on an " | ||
| f"accelerator, but the weight is on {value.device.type}" | ||
| ) | ||
| weight, scale, global_scale = self._quantize_group(value, format_spec) |
There was a problem hiding this comment.
I think it is better to warn the user that the weights are not placed correctly and use a default torch impl to do that ? it should be still quite fast no ? Also, this will help us check that the quantization is performed properly.
|
|
||
|
|
||
| @use_experts_implementation(experts_interface=ALL_FINEGRAINED_EXPERTS_FUNCTIONS) | ||
| class FineGrainedExperts(_FineGrainedModule, nn.Module): |
There was a problem hiding this comment.
Let's try to keep this class as clean as possible and remove all stuff that are not really needed if possible.
| def from_module( | ||
| cls, module: nn.Linear, quantization_config: BlockScaledConfig, model: nn.Module |
| logger = logging.get_logger(__name__) | ||
|
|
||
|
|
||
| class BlockScaledQuantizer(HfQuantizer): |
There was a problem hiding this comment.
i don't understand where this would be used
| def _loading_attributes(config, **attributes) -> dict[str, Any]: | ||
| """Return the loading attributes a passed config lends to a pre-quantized checkpoint's config. | ||
|
|
||
| These are `dequantize`, `modules_to_not_convert` when it is set, and `attributes`. | ||
| An unset `modules_to_not_convert` keeps the checkpoint's. | ||
| """ | ||
| loading = {"dequantize": config.dequantize} | ||
| if config.modules_to_not_convert is not None: | ||
| loading["modules_to_not_convert"] = config.modules_to_not_convert | ||
| return {**loading, **attributes} | ||
|
|
There was a problem hiding this comment.
just update get_loading_attributes
| for implementation, triton in (("grouped_mm", True), ("deepgemm", False), ("deepgemm_megamoe", False)): | ||
| cfg._experts_implementation = implementation | ||
| for config in configs: |
| @@ -0,0 +1,415 @@ | |||
| # Copyright 2026 The HuggingFace Team. All rights reserved. | |||
There was a problem hiding this comment.
For the tests, let's try to add only relevant tests if possible and simplify stuff here. There are an infinite amount of tests that we can perform so let's try to focus on the most important ones.
There was a problem hiding this comment.
also i don't see any reference to BlockScaledConfig in the docs, is this something the user should use ?
|
[For maintainers] Suggested jobs to run (before merge) run-slow: finegrained |
What. The shared machinery of the block-scaled formats, including the format storage table. No format is
registered, so this PR loads nothing on its own. The formats come in #49777 (FP8), #49778 (MXFP4), #49779 (NVFP4) and
#49780 (MXFP8). Each format adds itself to
BLOCK_SCALED_CONFIGS. The tests here patch in test-only formats.integrations/finegrained/:FineGrainedLinear,FineGrainedGroupedLinearandFineGrainedExpertsoverkernels-community/finegrained-kernels. It also holds
the layout ops (gate|up interleave, scale swizzle), quantize and dequantize, and the storage table.
BlockScaledConfigandBlockScaledQuantizer: what every format's config and quantizer share. One fallback ruleapplies. Without a GPU or XPU, below the required compute capability, or without the
kernelspackage, apre-quantized checkpoint is dequantized and quantizing on the fly raises.
BlockScaledQuantizerhas no plan and no members. It quantizes the modules its skip-list leaves. Hosted byFineGrainedHfQuantizer(previous PR), each format is one member. Its ops always read their own member, since thehost dispatches shared keys per module.
Hooks and why they exist.
FineGrainedConfig.loading_attributes_source: a passed format config also lends its activation format to the planentries of its format. A plan does not lend to a single-format checkpoint. Pass that format's config instead.
get_weight_conversions(model): the conversions depend on the modules actually built. First user is here.DeepGEMM hold gate|up stacked and scales row-major. The others hold the Triton layout: gate|up interleaved for the
fused GLU, and on SM100 MX scales swizzled. Block-scaled gate|up stay stacked off SM100, since a block scale spans
128 rows. The Triton kernels also read stacked row-major weights through an ungated call, so a switch from DeepGEMM
to Triton after load works. A switch the other way raises in the DeepGEMM shared check, which runs all of its
asserts. This replaces the per-implementation layout table and the switch check in
set_experts_implementation.prefer_deepgemm_linear=Falsekeeps the dense linears on the Triton kernels. It replaces theTRANSFORMERS_DISABLE_DEEPGEMM_LINEARenv var for the fine-grained configs. The legacy FP8 integration keeps it.moe_experts_*intra-expert TP styles with the post-expert-norm guard: they shard the scale grid and biaswith their projection. First user is here.
FineGrainedExperts._impl_tp_layer_overridesswaps in the Mega MoE experts and routerstyles.
BlockScaledQuantizer.update_parallel_planapplies it. This keeps main's pattern from the legacy FP8integration until the expert-parallel stack's
ep_implementationreplaces it.get_weight_conversions,update_weight_conversionsorupdate_parallel_planand callssuper(). FP8 in FP8 on the fine-grained machinery (Fp8Config) #49777 is the first.checkpoint_format: validated here, read from FP8 on the fine-grained machinery (Fp8Config) #49777. It picks the producer key names, e.g.weight_scaleinsteadof
weight_scale_inv, and the compressed-tensors NVFP4 globals in NVFP4 on the fine-grained machinery #49779._check_activation_format: no caller here. Its caller and its only override (NVFP4Config, which rejectsweight-only checkpoints) land in NVFP4 on the fine-grained machinery #49779.
models with a per-expert output norm need.
Depends on. #49818.
How tested.
tests/quantization/finegrained/test_machinery.pytests the machinery with test-only formats. Itcovers the shared format contract, module swap, kernel calls, load and save, mixed plans through the host,
dequantized loads and companion sharding. The layout-op tests in
tests/integrations/finegrained/test_conversions.pyuse a test-only MXformat until MXFP8 ships. Also
tests/kernels/test_finegrained.py,tests/kernels/test_deepgemm.pyandtests/tensor_parallel. All run on CPU with a mocked kernel bundle.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