Repository navigation
[PyTorch][Common] Add MXFP8 and NVFP4 QDQ for mixed-precision GEMM #3633
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
negvet
wants to merge
11
commits into
NVIDIA:main
Choose a base branch
from
negvet:nvfp4_qdq
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,878
−55
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
f543cd3
Refactor output dtype handling for Identity and Hybrid quantizers
negvet 359f6d3
Add experimental NVFP4 weight QDQ quantization
negvet ecbf527
Merge branch 'main' into nvfp4_qdq
negvet 7ee5281
Add MXFP8 QDQ and shared QDQ quantizer base
negvet 432e4d4
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] df8269c
Clarify QDQ operand labels and factory naming
negvet 1171a05
Add per-token outer scale to the fused nvfp4 path
negvet f51212d
Fix HybridQuantizer dtype validation and column source precision
negvet 9e09c01
Merge branch 'main' into nvfp4_qdq
negvet a82d551
Enable NVFP4 and MXFP8 QDQ on Ampere+
negvet 7f5e16f
Allow CustomRecipe without FP8 hardware and fix QDQ capability gates
negvet File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| /************************************************************************* | ||
| * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| * | ||
| * See LICENSE for license information. | ||
| ************************************************************************/ | ||
|
|
||
| #include <cmath> | ||
| #include <cstring> | ||
| #include <vector> | ||
|
|
||
| #include <cuda_runtime.h> | ||
| #include <gtest/gtest.h> | ||
| #include <transformer_engine/cast.h> | ||
|
|
||
| #include "../test_common.h" | ||
|
|
||
| using namespace transformer_engine; | ||
| using namespace test; | ||
|
|
||
| namespace { | ||
| template <typename T> | ||
| void check_qdq(size_t rows, size_t cols, bool row_scaled = false) { | ||
| cudaDeviceProp prop; | ||
| ASSERT_EQ(cudaGetDeviceProperties(&prop, 0), cudaSuccess); | ||
| if (prop.major < 10) GTEST_SKIP() << "Native packed Q+DQ reference requires SM10.0+"; | ||
| const auto dtype = TypeInfo<T>::dtype; | ||
| const std::vector<size_t> shape{rows, cols}; | ||
| Tensor input("input", shape, dtype); | ||
| Tensor packed("packed", shape, DType::kFloat4E2M1, true, false, NVTE_NVFP4_1D_SCALING, | ||
| DType::kFloat8E4M3); | ||
| Tensor reference("reference", shape, dtype); | ||
| Tensor output("output", shape, dtype); | ||
| Tensor amax("amax", std::vector<size_t>{1}, DType::kFloat32); | ||
| Tensor noop("noop", std::vector<size_t>{1}, DType::kFloat32); | ||
| fillCase<fp32>(&input, InputsFillCase::uniform); | ||
| input.to_cpu(); | ||
| float maximum = 0; | ||
| for (size_t i = 0; i < rows * cols; ++i) { | ||
| maximum = std::max(maximum, std::abs(static_cast<float>(input.rowwise_cpu_dptr<T>()[i]))); | ||
| } | ||
| packed.set_amax(maximum); | ||
| if (row_scaled) packed.set_row_scaled_nvfp4(true); | ||
| ASSERT_EQ(cudaMemcpy(amax.rowwise_dptr(), &maximum, sizeof(float), cudaMemcpyHostToDevice), | ||
| cudaSuccess); | ||
| QuantizationConfigWrapper config; | ||
| nvte_quantize_v2(input.data(), packed.data(), config, 0); | ||
| nvte_dequantize(packed.data(), reference.data(), 0); | ||
| if (row_scaled) { | ||
| nvte_nvfp4_qdq_row_scaled(input.data(), output.data(), nullptr, 0); | ||
| } else { | ||
| nvte_nvfp4_qdq(input.data(), output.data(), amax.data(), nullptr, 0); | ||
| } | ||
| ASSERT_EQ(cudaDeviceSynchronize(), cudaSuccess); | ||
| reference.to_cpu(); | ||
| output.to_cpu(); | ||
| EXPECT_EQ(std::memcmp(reference.rowwise_cpu_dptr<T>(), output.rowwise_cpu_dptr<T>(), | ||
| rows * cols * sizeof(T)), 0); | ||
| const float one = 1; | ||
| ASSERT_EQ(cudaMemcpy(noop.rowwise_dptr(), &one, sizeof(float), cudaMemcpyHostToDevice), | ||
| cudaSuccess); | ||
| ASSERT_EQ(cudaMemset(input.rowwise_dptr(), 0, rows * cols * sizeof(T)), cudaSuccess); | ||
| if (row_scaled) { | ||
| nvte_nvfp4_qdq_row_scaled(input.data(), output.data(), noop.data(), 0); | ||
| } else { | ||
| nvte_nvfp4_qdq(input.data(), output.data(), amax.data(), noop.data(), 0); | ||
| } | ||
| ASSERT_EQ(cudaDeviceSynchronize(), cudaSuccess); | ||
| output.to_cpu(); | ||
| EXPECT_EQ(std::memcmp(reference.rowwise_cpu_dptr<T>(), output.rowwise_cpu_dptr<T>(), | ||
| rows * cols * sizeof(T)), 0); | ||
| } | ||
| } // namespace | ||
|
|
||
| TEST(NVFP4QDQ, BF16) { | ||
| check_qdq<bf16>(32, 32); | ||
| check_qdq<bf16>(96, 160); | ||
| check_qdq<bf16>(512, 1024); | ||
| } | ||
|
|
||
| TEST(NVFP4QDQ, FP16) { | ||
| check_qdq<fp16>(32, 32); | ||
| check_qdq<fp16>(96, 160); | ||
| } | ||
|
|
||
| TEST(NVFP4QDQ, RowScaledBF16) { | ||
| check_qdq<bf16>(32, 32, true); | ||
| check_qdq<bf16>(96, 160, true); | ||
| check_qdq<bf16>(128, 4096, true); | ||
| } | ||
|
|
||
| TEST(NVFP4QDQ, RowScaledFP16) { | ||
| check_qdq<fp16>(32, 32, true); | ||
| check_qdq<fp16>(96, 160, true); | ||
| check_qdq<fp16>(32, 16384, true); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| # Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # | ||
| # See LICENSE for license information. | ||
|
|
||
| """Two-rank NVFP4 QDQ amax reduction and native reference parity.""" | ||
|
|
||
| import os | ||
|
|
||
| import torch | ||
| import torch.distributed as dist | ||
| from transformer_engine.pytorch.custom_recipes.qdq import NVFP4QDQQuantizer | ||
| from transformer_engine.pytorch.tensor.nvfp4_tensor import NVFP4Quantizer | ||
| import transformer_engine_torch as tex | ||
|
|
||
|
|
||
| def assert_bits(actual, expected): | ||
| assert actual.dtype == expected.dtype | ||
| assert torch.equal(actual.view(torch.int16), expected.view(torch.int16)) | ||
|
|
||
|
|
||
| def run_case(options, source_dtype): | ||
| rank = dist.get_rank() | ||
| torch.manual_seed(123 + rank) | ||
| x = torch.randn(128, 256, device="cuda", dtype=source_dtype) * (1 if rank == 0 else 17) | ||
| output_dtype = torch.bfloat16 | ||
| local_amax = x.float().abs().amax().reshape(1) | ||
| global_amax = local_amax.clone() | ||
| dist.all_reduce(global_amax, op=dist.ReduceOp.MAX) | ||
| assert dist.get_world_size() == 2 | ||
| if rank == 0: | ||
| assert global_amax.item() > local_amax.item() | ||
| native = NVFP4Quantizer(rowwise=True, columnwise=False, **options) | ||
| native.internal = True | ||
| q = NVFP4QDQQuantizer(native) | ||
| q.amax_reduction_group = dist.group.WORLD | ||
| q.with_amax_reduction = True | ||
| assert q.selected_backend(x, output_dtype) == "reference" | ||
| out = q.quantize(x, dtype=output_dtype) | ||
| expected = tex.nvfp4_quantize_with_amax(x, native, global_amax, global_amax).dequantize( | ||
| dtype=output_dtype | ||
| ) | ||
| assert_bits(out.dequantize(), expected) | ||
| saved = out._get_quantizer() | ||
| assert not saved.with_amax_reduction and saved.amax_reduction_group is None | ||
| assert q.with_amax_reduction and q.amax_reduction_group is dist.group.WORLD | ||
| pointer = out._hp_data.data_ptr() | ||
| x.mul_(2) | ||
| global_amax.mul_(2) | ||
| q.update_quantized(x, out) | ||
| expected = tex.nvfp4_quantize_with_amax(x, native, global_amax, global_amax).dequantize( | ||
| dtype=output_dtype | ||
| ) | ||
| assert_bits(out.dequantize(), expected) | ||
| assert out._hp_data.data_ptr() == pointer | ||
| # Saved workspaces intentionally update locally, without persistent collectives. | ||
| out.quantize_(x) | ||
| assert_bits(out.dequantize(), native(x).dequantize(dtype=output_dtype)) | ||
|
|
||
|
|
||
| def main(): | ||
| torch.cuda.set_device(int(os.environ["LOCAL_RANK"])) | ||
| dist.init_process_group("nccl") | ||
| try: | ||
| count = 0 | ||
| for options in ( | ||
| {}, | ||
| {"with_2d_quantization": True}, | ||
| { | ||
| "nvfp4_use_4over6": True, | ||
| "nvfp4_e4m3_max": 448, | ||
| "nvfp4_4over6_err_mode": "MSE", | ||
| }, | ||
| ): | ||
| for source_dtype in (torch.bfloat16, torch.float32): | ||
| run_case(options, source_dtype) | ||
| count += 1 | ||
| dist.barrier() | ||
| if dist.get_rank() == 0: | ||
| print(f"NVFP4 QDQ distributed: {count} cases passed on 2 ranks", flush=True) | ||
| finally: | ||
| dist.destroy_process_group() | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| # Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # | ||
| # See LICENSE for license information. | ||
|
|
||
| """Pytest launcher for distributed NVFP4 QDQ reference parity.""" | ||
|
|
||
| import os | ||
| from pathlib import Path | ||
| import subprocess | ||
| import sys | ||
|
|
||
| import pytest | ||
| import torch | ||
| import transformer_engine.pytorch as te | ||
|
|
||
|
|
||
| @pytest.mark.skipif(torch.cuda.device_count() < 2, reason="QDQ amax reduction requires two GPUs") | ||
| def test_nvfp4_qdq_amax_reduction(): | ||
| available, reason = te.is_nvfp4_available(return_reason=True) | ||
| if not available: | ||
| pytest.skip(reason) | ||
| script = Path(__file__).with_name("run_nvfp4_qdq.py") | ||
| subprocess.run( | ||
| [ | ||
| sys.executable, | ||
| "-m", | ||
| "torch.distributed.run", | ||
| "--standalone", | ||
| "--nproc_per_node=2", | ||
| str(script), | ||
| ], | ||
| env=os.environ.copy(), | ||
| check=True, | ||
| ) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can it support NVFP4 with per token second scale instead of global amax?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added support