Skip to content

Fine-grained block-scaled quantization: the shared machinery - #49776

Draft
IlyasMoutawwakil wants to merge 9 commits into
fg-split/4a-hostfrom
fg-split/4-machinery
Draft

IlyasMoutawwakil wants to merge 9 commits into
fg-split/4a-hostfrom
fg-split/4-machinery

Conversation

@IlyasMoutawwakil

@IlyasMoutawwakil IlyasMoutawwakil commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

🤗 Transformers CI

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, FineGrainedGroupedLinear and FineGrainedExperts over
    kernels-community/finegrained-kernels. It also holds
    the layout ops (gate|up interleave, scale swizzle), quantize and dequantize, and the storage table.
  • BlockScaledConfig and BlockScaledQuantizer: what every format's config and quantizer share. One fallback rule
    applies. Without a GPU or XPU, below the required compute capability, or without the kernels package, a
    pre-quantized checkpoint is dequantized and quantizing on the fly raises.
  • BlockScaledQuantizer has no plan and no members. It quantizes the modules its skip-list leaves. Hosted by
    FineGrainedHfQuantizer (previous PR), each format is one member. Its ops always read their own member, since the
    host 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 plan
    entries 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.
  • The experts weight layout is picked at load, and the loading ops build it from the checkpoint. Experts loaded for
    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=False keeps the dense linears on the Triton kernels. It replaces the
    TRANSFORMERS_DISABLE_DEEPGEMM_LINEAR env var for the fine-grained configs. The legacy FP8 integration keeps it.
  • The moe_experts_* intra-expert TP styles with the post-expert-norm guard: they shard the scale grid and bias
    with their projection. First user is here.
  • The Mega MoE plan rewrite: FineGrainedExperts._impl_tp_layer_overrides swaps in the Mega MoE experts and router
    styles. BlockScaledQuantizer.update_parallel_plan applies it. This keeps main's pattern from the legacy FP8
    integration until the expert-parallel stack's ep_implementation replaces it.
  • The base has no format hooks of its own. A format overrides get_weight_conversions,
    update_weight_conversions or update_parallel_plan and calls super(). 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_scale instead
    of 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 rejects
    weight-only checkpoints) land in NVFP4 on the fine-grained machinery #49779.
  • DeepGEMM: the guards and the dense dispatch gate. The bf16 DeepGEMM experts arm now applies a post-expert norm, which
    models with a per-expert output norm need.
  • Format-specific ops and hooks land with the format that first uses them.

Depends on. #49818.

How tested. tests/quantization/finegrained/test_machinery.py tests the machinery with test-only formats. It
covers 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.py use a test-only MX
format until MXFP8 ships. Also tests/kernels/test_finegrained.py, tests/kernels/test_deepgemm.py and
tests/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

@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 force-pushed the fg-split/4-machinery branch 2 times, most recently from 9072093 to e4e40b2 Compare October 20, 2026 13:33
@IlyasMoutawwakil
IlyasMoutawwakil removed this pull request from stack #49781 October 20, 2026 13:41
@IlyasMoutawwakil IlyasMoutawwakil changed the title Fine-grained block-scaled quantization machinery, with no format Fine-grained block-scaled quantization: the shared machinery Oct 20, 2026
@IlyasMoutawwakil
IlyasMoutawwakil removed this pull request from stack #49788 October 20, 2026 16:25

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
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"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

we are missing examples! imo less text and just show it

Comment on lines +64 to +68
## 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`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

imo would keep this out

Comment thread src/transformers/quantizers/auto.py Outdated
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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

some inplace stuff? do we even need a return then?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why a utils? A bit weird, maybe a folder as we will add other ones in the future?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

block_scaled != finegrained
block scaled = fp8,mxfp4,nvfp4,mxfp8
finegrained = any quantizer

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.

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:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

why an extra fn?

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"]:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

dont see why another fn

@IlyasMoutawwakil
IlyasMoutawwakil force-pushed the fg-split/4-machinery branch 4 times, most recently from bd1d85b to 6d87752 Compare October 21, 2026 07:24
@IlyasMoutawwakil
IlyasMoutawwakil force-pushed the fg-split/4-machinery branch 2 times, most recently from 3e8f877 to d1dcda7 Compare October 21, 2026 08:59
@IlyasMoutawwakil
IlyasMoutawwakil removed this pull request from stack #49798 October 21, 2026 08:59
@IlyasMoutawwakil
IlyasMoutawwakil changed the base branch from fg-split/3-experts-tp to fg-split/4a-host October 21, 2026 08:59
@IlyasMoutawwakil
IlyasMoutawwakil force-pushed the fg-split/4-machinery branch 7 times, most recently from 1e027a8 to a6724ee Compare October 23, 2026 13:03
IlyasMoutawwakil and others added 8 commits October 23, 2026 13:34
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>

@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.

Left couples of comments ! Thanks !

rendered properly in your Markdown viewer.

-->

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.

please update to that it is simpler: less text and more example, illustrations

Comment on lines +129 to +141
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)

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 should probably create class for quantizer in general then QuantizationOps, so that we reuse this across the other conversion ops related to quants

Comment on lines +280 to +285
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)

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.

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):

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.

Let's try to keep this class as clean as possible and remove all stuff that are not really needed if possible.

Comment on lines +399 to +400
def from_module(
cls, module: nn.Linear, quantization_config: BlockScaledConfig, model: nn.Module

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.

make model optional

logger = logging.get_logger(__name__)


class BlockScaledQuantizer(HfQuantizer):

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.

i don't understand where this would be used

Comment on lines +1700 to +1710
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}

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.

just update get_loading_attributes

Comment on lines +291 to +293
for implementation, triton in (("grouped_mm", True), ("deepgemm", False), ("deepgemm_megamoe", False)):
cfg._experts_implementation = implementation
for config in configs:

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.

parametrize the test directly

@@ -0,0 +1,415 @@
# Copyright 2026 The HuggingFace Team. All rights reserved.

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.

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.

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.

also i don't see any reference to BlockScaledConfig in the docs, is this something the user should use ?

@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.

4 participants