Skip to content

[PyTorch][torch.compile] Make quantizers opaque value objects#3152

Merged
pggPL merged 32 commits into
NVIDIA:mainfrom
pggPL:make_qunatizers_opaque
Jul 6, 2026
Merged

[PyTorch][torch.compile] Make quantizers opaque value objects#3152
pggPL merged 32 commits into
NVIDIA:mainfrom
pggPL:make_qunatizers_opaque

Conversation

@pggPL

@pggPL pggPL commented Jun 29, 2026

Copy link
Copy Markdown
Collaborator

Description

Tensorless quantizers in TE (MXFP8, FP8 blockwise, FP8 current-scaling, NVFP4)
are fully described by a handful of plain, reproducible scalars — they hold no
live tensors and no process groups. This PR turns them into opaque value
objects
so torch.compile can treat them as baked-in constants: two
quantizers with the same configuration become interchangeable, hashable, and
reconstructible inside an FX graph.

Quantizers that hold live state (delayed-scaling Float8Quantizer, which keeps
scale/amax tensors) and any user-defined quantizer keep the default
identity semantics, so the change is opt-in and backward compatible. On older
PyTorch builds without the opaque-object API the registration is a graceful
no-op.

Along the way this also un-breaks the existing test_torch_compile.py suite:
that file lived on main but was never wired into CI, and its
test_autocast_nested_custom case (nested te.autocast with multiple
CustomRecipe instances) was failing because of the CustomRecipe state-caching
bug fixed here. The file is now run in CI and passes.

Type of change

  • Documentation change (change only to the documentation, either a fix or a new content)
  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Infra/Build change
  • Code refactoring

Changes

  • Add opt-in value-object identity to the base Quantizer
    (_value_fields / _value_key / __eq__ / __hash__). Returning None
    from _value_fields() (the default) keeps identity semantics.
  • New module transformer_engine/pytorch/dynamo.py holding the
    torch.compile glue: __fx_repr__, value-key reconstruction and
    register_value_opaque_quantizer (gracefully no-op without PyTorch's
    opaque-object API).
  • Register MXFP8Quantizer, Float8BlockQuantizer,
    Float8CurrentScalingQuantizer and NVFP4Quantizer as value opaque types
    (the deprecated amax_reduction_group is never part of the value).
  • Fix CustomRecipe state caching in TransformerEngineBaseModule.set_meta_tensor:
    rebuild quantizers when the CustomRecipe instance changes (e.g. nested
    te.autocast regions) instead of reusing the first recipe's state, since
    every CustomRecipe shares the CustomRecipeState type but carries its own
    qfactory. This fixes the previously-failing test_autocast_nested_custom.
  • Enable tests/pytorch/test_torch_compile.py in the L0_pytorch_unittest QA
    suite (it existed on main but was never run in CI), and add the quantizer
    value-object tests to it. Bringing it into CI required fixing the existing
    CustomRecipe torch.compile path: the qfactory now dispatches on
    QuantizerRole.tensor_type supplied by ToyLinear.get_quantizer_roles.
  • Guard the value-object path against a stored amax reduction group: __fx_repr__
    already rejects any quantizer holding a process group, and __eq__ / __hash__
    now raise too. The group is excluded from the value key, so a stored group would
    otherwise compare/hash equal to a groupless quantizer and let torch.compile
    reuse a graph that skips the reduction. Pass the group per quantize call instead.

Checklist:

  • I have read and followed the contributing guidelines
  • The functionality is complete
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

pggPL and others added 8 commits June 29, 2026 11:25
…ompile

Give tensorless quantizers (MXFP8, FP8 blockwise, FP8 current-scaling,
NVFP4) value-object semantics so torch.compile can treat them as baked-in
constants:

- Add opt-in value identity to the base Quantizer (_value_fields /
  _value_key / __eq__ / __hash__). Quantizers holding live tensors
  (delayed-scaling Float8Quantizer) and custom quantizers keep identity
  semantics.
- New transformer_engine/pytorch/dynamo.py houses the torch.compile glue:
  __fx_repr__, value-key reconstruction and register_value_opaque_quantizer
  (gracefully a no-op on PyTorch builds without the opaque-object API).
- Register the four tensorless quantizers as value opaque types.

Also fix CustomRecipe state caching in TransformerEngineBaseModule:
set_meta_tensor now rebuilds quantizers when the CustomRecipe instance
changes (e.g. nested te.autocast regions) instead of reusing the first
recipe's state, since every CustomRecipe shares the CustomRecipeState type
but carries its own qfactory.

Move the quantizer value-object tests into tests/pytorch/test_torch_compile.py
and add that file to the L0 pytorch unittest QA suite.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
…globals

Follow-up to the value-opaque quantizer support:

- Remove the module-level _QUANTIZER_VALUE_REGISTRY (qualname -> class) and
  _quantizer_from_value_key. __fx_repr__ now captures the quantizer class
  directly in the FX globals and reconstructs via _rebuild_quantizer(cls, items),
  matching how PyTorch's own value opaque types (e.g. DTensor placements)
  reconstruct themselves. This removes global mutable state and the qualname
  collision risk.
- Consolidate the quantizer value-object tests in test_torch_compile.py down to
  two functions and exercise reconstruction through the public __fx_repr__ path
  instead of internal helpers.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Replace the single dynamo.py module with a dynamo/ package so the
torch.compile glue can grow with a clear responsibility split across the
stacked branches. This branch owns the value-opaque quantizer layer.

  * dynamo/quantizer_opaque.py -- register_value_opaque_quantizer and helpers
  * dynamo/__init__.py -- re-exports the public API so callers keep importing
    from transformer_engine.pytorch.dynamo unchanged

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
A value-opaque quantizer must not carry live distributed state. Scan the
quantizer attributes in __fx_repr__ and raise TypeError if any holds a
torch.distributed.ProcessGroup (e.g. a non-None deprecated amax_reduction_group),
so it cannot be silently baked into a torch.compile FX graph. Clarify the related
comments accordingly.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
NVFP4Quantizer is registered as a value-opaque quantizer but was missing
from the value-semantics / __fx_repr__ round-trip test. Add it to
_VALUE_QUANTIZERS (skipped without CUDA, which it needs to construct).

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
…__/__hash__

The amax reduction group is excluded from the value key, so a value quantizer
that stored one would compare/hash equal to a groupless one and let torch.compile
reuse a graph that skips the reduction. __eq__/__hash__ now raise (mirroring
__fx_repr__, which already rejects any process-group-bearing quantizer). The
group should be passed per quantize call, not stored on the quantizer.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Add is_value_opaque_quantizer() + the _te_compile_value_opaque flag stamped at
registration, so dynamo-traced code can detect registered quantizers (and fall
back to eager for unregistered ones).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
…fp4 value key

- Narrow register_opaque_type except to (RuntimeError, TypeError): the API is
  already imported above, so ImportError/AttributeError there only mask real errors.
- Add test_quantizer_value_object_fullgraph exercising torch.compile(fullgraph=True)
  end-to-end to verify opaque-type registration took effect.
- Restore missing NVFP4Quantizer._with_random_sign_mask assignment required by
  _value_fields()/_value_key().

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
@pggPL pggPL requested a review from ksivaman as a code owner June 29, 2026 09:36
@pggPL

pggPL commented Jun 29, 2026

Copy link
Copy Markdown
Collaborator Author

/te-ci pytorch

@greptile-apps

greptile-apps Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR turns four tensorless quantizers (MXFP8Quantizer, Float8BlockQuantizer, Float8CurrentScalingQuantizer, NVFP4Quantizer) into hashable, equality-comparable value objects so torch.compile can bake them into compiled FX graphs as constants rather than breaking the graph. The change is opt-in: only classes explicitly registered via register_value_opaque_quantizer gain value semantics; all others keep identity-based __eq__/__hash__.

  • New dynamo/quantizer_opaque.py: implements _rebuild_quantizer (bypasses __init__, then calls _rebuild_derived_state), _quantizer_fx_repr (generates eval-able FX code), and register_value_opaque_quantizer (validates annotated fields are plain value types, sets _value_field_names, attaches __fx_repr__, and calls PyTorch's opaque-object registration \u2014 gracefully no-op on older builds).
  • NVFP4Quantizer restructuring: rht_matrix (a torch.Tensor) and amax_reduction_group removed from annotations; _rebuild_derived_state reconstructs rht_matrix from the cached get_rht_matrix; copy() now correctly propagates with_random_sign_mask via rht_matrix_random_sign_mask_t != 0.
  • Tests: test_torch_compile.py is wired into CI and covers equality, hash, FX repr round-trip, and a fullgraph=True compile path; the kernel quantize round-trip verifies that derived state (including rht_matrix) is faithfully restored.

Confidence Score: 5/5

Safe to merge; the value-object path is strictly opt-in and the changes do not alter the quantization kernels or their inputs.

The core correctness paths — annotation validation at registration time, value-key construction, FX repr generation, and _rebuild_derived_state for NVFP4's derived tensor — are all well-guarded and covered by the new quantize kernel round-trip tests. The one identified gap (enum-to-int conversion keyed on the field name "dtype" rather than the field type) has no impact on any currently registered quantizer.

transformer_engine/pytorch/dynamo/quantizer_opaque.py and transformer_engine/pytorch/quantized_tensor.py — specifically the name-based enum conversion logic that would need updating before any new Enum-typed annotation is added to a registered quantizer.

Important Files Changed

Filename Overview
transformer_engine/pytorch/dynamo/quantizer_opaque.py New module implementing value-opaque quantizer registration for torch.compile; logic is correct for current quantizers but enum serialization is hardcoded to the "dtype" field name, creating a latent trap for future annotated enum fields.
transformer_engine/pytorch/quantized_tensor.py Adds _value_fields, _value_key, eq, and hash to Quantizer base class; opt-in value semantics via _value_field_names class attribute; enum-to-int conversion in _value_key is name-specific ("dtype") rather than type-based.
transformer_engine/pytorch/tensor/nvfp4_tensor.py Removes rht_matrix and amax_reduction_group from annotations; introduces _rebuild_derived_state hook that restores rht_matrix from the cached get_rht_matrix; copy() now passes with_random_sign_mask correctly.
transformer_engine/pytorch/tensor/float8_tensor.py Removes amax_reduction_group annotation from Float8CurrentScalingQuantizer and adds register_value_opaque_quantizer call; copy() uses getattr with default None for the deprecated field.
transformer_engine/pytorch/tensor/mxfp8_tensor.py Registers MXFP8Quantizer as a value-opaque type; minimal change, only dtype annotation is in the quantizer-specific fields.
transformer_engine/pytorch/tensor/float8_blockwise_tensor.py Registers Float8BlockQuantizer as a value-opaque type; all annotated fields are plain value types.
tests/pytorch/test_torch_compile.py Adds value-object tests (equality, hash, FX round-trip, fullgraph compile); tests are well-structured including quantize kernel round-trip to catch missing derived state.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["register_value_opaque_quantizer(cls)"] --> B["_annotated_fields(): collect MRO annotations"]
    B --> C{"All fields are int/bool/float/str/Enum?"}
    C -- No --> D["Raise TypeError at import time"]
    C -- Yes --> E["cls._value_field_names = tuple(fields)"]
    E --> F["Attach __fx_repr__ = _quantizer_fx_repr"]
    F --> G{"torch opaque-object API available?"}
    G -- No --> H["Value semantics only; torch.compile graph-breaks"]
    G -- Yes --> I["register_opaque_type(cls, typ='value')"]
    I --> J["_VALUE_OPAQUE_QUALNAMES.add(cls.__qualname__)"]
    K["quantizer.__fx_repr__()"] --> L["_value_key() raises if ProcessGroup stored"]
    L --> M["_rebuild_quantizer(cls, items)"]
    M --> N["cls.__new__(cls); set attrs via object.__setattr__"]
    N --> O{"_rebuild_derived_state exists?"}
    O -- Yes --> P["Restore rht_matrix (NVFP4 only)"]
    O -- No --> Q["Rebuilt quantizer ready"]
    P --> Q
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
    A["register_value_opaque_quantizer(cls)"] --> B["_annotated_fields(): collect MRO annotations"]
    B --> C{"All fields are int/bool/float/str/Enum?"}
    C -- No --> D["Raise TypeError at import time"]
    C -- Yes --> E["cls._value_field_names = tuple(fields)"]
    E --> F["Attach __fx_repr__ = _quantizer_fx_repr"]
    F --> G{"torch opaque-object API available?"}
    G -- No --> H["Value semantics only; torch.compile graph-breaks"]
    G -- Yes --> I["register_opaque_type(cls, typ='value')"]
    I --> J["_VALUE_OPAQUE_QUALNAMES.add(cls.__qualname__)"]
    K["quantizer.__fx_repr__()"] --> L["_value_key() raises if ProcessGroup stored"]
    L --> M["_rebuild_quantizer(cls, items)"]
    M --> N["cls.__new__(cls); set attrs via object.__setattr__"]
    N --> O{"_rebuild_derived_state exists?"}
    O -- Yes --> P["Restore rht_matrix (NVFP4 only)"]
    O -- No --> Q["Rebuilt quantizer ready"]
    P --> Q
Loading

Reviews (10): Last reviewed commit: "Enable post-RHT amax in the NVFP4 value-..." | Re-trigger Greptile

Comment thread transformer_engine/pytorch/tensor/nvfp4_tensor.py Outdated
Comment thread transformer_engine/pytorch/quantized_tensor.py
…trip

_rebuild_quantizer only restores value-key fields, so a reconstructed
NVFP4Quantizer was missing the derived rht_matrix tensor (not hashable, so not
in the value key) and failed at copy()/quantize time. Add a _rebuild_derived_state
hook (called by _rebuild_quantizer) that NVFP4Quantizer uses to rebuild rht_matrix
from _with_random_sign_mask (lru_cache -> cheap).

Extend test_quantizer_value_object to also quantize with the original and the
rebuilt quantizer and require bit-exact results (gated on HW support), so a
field the kernel needs but the value key omits can no longer slip through.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>

@kshitij12345 kshitij12345 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Overall LGTM, would be good to resolve the inline comments before merging.

Comment thread transformer_engine/pytorch/dynamo/quantizer_opaque.py
Comment thread transformer_engine/pytorch/dynamo/quantizer_opaque.py Outdated
pggPL and others added 2 commits June 29, 2026 14:46
Move the ProcessGroup guard out of the (overridable) __fx_repr__ into
Quantizer._value_key -- the single point every value-materialization path
(__eq__/__hash__/__fx_repr__) goes through -- so a custom __fx_repr__ can no
longer bypass it. Generalizes the old amax-only check to any field holding a
ProcessGroup. Add a test that a value quantizer carrying a live group raises.

Addresses review on NVIDIA#3152.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
…assthrough

Replace the trivial pass-through fullgraph test with one that drives each
production quantizer through a minimal custom op (quantize + dequantize) under
torch.compile(fullgraph=True) and compares to eager -- so the opaque-type
registration is actually exercised inside the graph (a graph break would make
fullgraph=True raise). Op registration sits right before the test. Also drop
stale comments referencing the old __fx_repr__-side process-group guard.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Comment thread transformer_engine/pytorch/dynamo/quantizer_opaque.py Outdated
pggPL and others added 3 commits June 29, 2026 15:29
…paque flag

- rht_matrix_random_sign_mask_t is a device-independent int derived from
  _with_random_sign_mask (the device only places a throwaway tensor); fix the
  misleading comment.
- Explain why registration uses a class attribute, not a registry set:
  is_value_opaque_quantizer is traced inside the compile graph and dynamo can
  bake a getattr constant but cannot do 'type(q) in set' on the opaque class.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
is_opaque_value_type(cls) sat between the import guard and the
register_opaque_type guard, so on a partial/experimental opaque-object build it
could raise RuntimeError/TypeError and crash TE import. Move it inside the same
except so the 'registration never crashes import' promise holds for both calls.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
@pggPL

pggPL commented Jun 29, 2026

Copy link
Copy Markdown
Collaborator Author

/te-ci pytorch

Comment thread tests/pytorch/test_torch_compile.py Outdated
Comment thread tests/pytorch/test_torch_compile.py
Comment thread transformer_engine/pytorch/dynamo/quantizer_opaque.py
Comment thread transformer_engine/pytorch/dynamo/quantizer_opaque.py Outdated
Comment thread transformer_engine/pytorch/dynamo/quantizer_opaque.py
Comment thread transformer_engine/pytorch/quantized_tensor.py
return quantizer

def _value_fields(self) -> Tuple[str, ...]:
return ("dtype", "block_len", "amax_epsilon", "force_pow_2_scales", "block_scaling_dim")

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.

There are some ways of getting that list without hardcoding it again, e.g. using inspect.get_annotations in the cases like we have where we provide all of the data members up front or via vars.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I see It's quite messy, but it is result of mess in quantizers. There are some fields called in the constructor (and arguments names sometimes does not match the field name). Some fields are set like .internal or .block_len are not arguments to constructor. And some of them are excluded on purpose like amax_reduction_group or rht_matrix.

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.

Shouldn't we then try to clean the quantizers code instead of adding to the messiness? I think the quantizers should advertise properly all of the fields that the value object would need.
I don't think internal is a problem necessarily (although we could just as well have it in the quantizer constructor, it seems that right now it is very easily discoverable), since you also do not put it in this function, and I assumed what you want here are just the constructor arguments from this subclass?
The ones that we want to "deprecate" in a sense like the amax_reduction_group should be removed from the annotated fields, right?

Comment thread transformer_engine/pytorch/tensor/nvfp4_tensor.py Outdated
pggPL and others added 6 commits June 30, 2026 23:44
Move the _VALUE_OPAQUE_FLAG setattr to the end of
register_value_opaque_quantizer, after register_opaque_type succeeds (or
the type is already opaque). Previously the flag was set up front, so
is_value_opaque_quantizer reported True even when the opaque-object API
was missing or registration raised, since both paths are swallowed.
Eager value semantics (__eq__/__hash__/__fx_repr__) are independent of
the flag, so this only tightens the predicate to mean torch actually
knows the type as opaque.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
_check_value_has_no_process_group ran on every guard eval (via
__eq__/__hash__) and scanned all of vars(self) recursively. The only
attribute that can hold a ProcessGroup is the deprecated
amax_reduction_group, so check it directly (O(1)) and drop the
_contains_process_group helper. Same guarantee, off the hot path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
# Conflicts:
#	transformer_engine/pytorch/tensor/float8_blockwise_tensor.py
#	transformer_engine/pytorch/tensor/float8_tensor.py
#	transformer_engine/pytorch/tensor/mxfp8_tensor.py
#	transformer_engine/pytorch/tensor/nvfp4_tensor.py
Remove the a==b / hash / dict-key block that just exercised Python's own
dict semantics; equality and hashing are still covered by the
__fx_repr__ round-trip (rebuilt == a, hash match) and the bit-exact
kernel check. other_kwargs is now unused, so drop it from the
parametrization and both test signatures.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Comment thread transformer_engine/pytorch/dynamo/quantizer_opaque.py Outdated
Comment thread transformer_engine/pytorch/dynamo/quantizer_opaque.py
Comment thread transformer_engine/pytorch/tensor/float8_tensor.py Outdated
Comment thread transformer_engine/pytorch/tensor/mxfp8_tensor.py Outdated
Comment thread tests/pytorch/test_torch_compile.py Outdated
Comment thread tests/pytorch/test_torch_compile.py Outdated
pggPL added 11 commits July 6, 2026 16:07
- Replace the class-attribute value-opaque flag with a module-level set of
  class qualnames: a set of class objects is untraceable under fullgraph=True
  (opaque classes have no equality rule in Dynamo), but the qualname
  constant-folds to a plain string; also avoids falsely reporting
  unregistered subclasses.
- Register MXFP8Quantizer right after the class like the other quantizers.
- Clarify the amax_reduction_group exclusion comment in
  Float8CurrentScalingQuantizer._value_fields.
- Restore import order in test_torch_compile.py, import NVFP4Quantizer from
  transformer_engine.pytorch, drop unused Float8Quantizer import.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Make the class annotations the single source of truth for what defines a
quantizer's value, instead of hand-written per-class _value_fields lists:

- Quantizer._value_fields is now derived from the annotations across the
  MRO (subsuming _BASE_VALUE_FIELDS); register_value_opaque_quantizer is
  the explicit opt-in and validates at import time that no annotated field
  is a tensor or process group.
- Drop the four per-class _value_fields overrides.
- Remove the deprecated amax_reduction_group annotation from
  Float8CurrentScalingQuantizer and NVFP4Quantizer (the attribute is still
  set for backward compatibility).
- NVFP4: rename _with_random_sign_mask to with_random_sign_mask (annotated,
  matching the constructor argument), stop storing the derived
  rht_matrix_random_sign_mask_t in the value key and rebuild it together
  with rht_matrix in _rebuild_derived_state (lru-cached getters), which
  __init__ now also uses. copy() now propagates with_random_sign_mask.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
- NVFP4: stop storing with_random_sign_mask; the annotated value field is
  the derived (deterministic, device-independent) rht_matrix_random_sign_mask_t
  and rht_matrix is rebuilt from it in _rebuild_derived_state. Quantizers
  pickled before this PR already carry the mask in __dict__, so old
  checkpoints keep working (a boolean back-fill default could lie for
  quantizers created with with_random_sign_mask=False).
- Value semantics no longer leak into unregistered subclasses:
  register_value_opaque_quantizer stores the field tuple on the class and
  _value_fields looks it up in the class's own __dict__, so a subclass must
  register explicitly (it previously inherited value eq/hash that ignored
  its unannotated fields and skipped the annotation check).
- The value-field tuple is computed once at registration instead of an MRO
  walk per __eq__/__hash__ call (these run per compiled-function invocation
  via the EQUALS_MATCH guard); registration validation and field derivation
  now share one annotation walk (Quantizer._annotated_fields). Drop the
  unreachable other._value_fields() branch and do the cheap type check
  first in __eq__.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Replace the substring blocklist with get_type_hints + an allowlist of value
types (int/bool/float/str/enum): aliased tensor types no longer slip through
and benign types whose name merely contains "Tensor" are no longer rejected.
Runs once per class at import time, not in any hot path.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
_rebuild_quantizer no longer back-fills the deprecated amax_reduction_group
(and loses the field_names set that existed only for that check): a rebuilt
quantizer deliberately lacks the attribute, so anything that genuinely needs
it fails loudly instead of silently getting None. The only unconditional
readers were the two copy() methods, which now tolerate the absent field;
_canonicalized_amax_reduction_group (used by the kernel only when
with_amax_reduction is set) still raises AttributeError on a rebuilt
quantizer, which is the intended behavior.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
@pggPL

pggPL commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

/te-ci pytorch

ptrendx
ptrendx previously approved these changes Jul 6, 2026
The quantize kernel rejects with_rht=True without with_post_rht_amax=True
(pre-RHT amax unsupported); mirror the recipe, which always sets both
together. Unnoticed locally because the NVFP4 round-trip is skipped on
non-NVFP4 hardware.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
@pggPL pggPL merged commit f99a017 into NVIDIA:main Jul 6, 2026
10 of 15 checks passed
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