diff --git a/tests/pytorch/test_quantized_tensor.py b/tests/pytorch/test_quantized_tensor.py index b284cfef54..5afd171eb8 100644 --- a/tests/pytorch/test_quantized_tensor.py +++ b/tests/pytorch/test_quantized_tensor.py @@ -873,6 +873,221 @@ def test_mxfp8_fsdp_extract_keeps_partial_columnwise_scale_block(self) -> None: assert extracted_scale_inv.shape == (2, 128) torch.testing.assert_close(extracted_scale_inv, columnwise_scale_inv[:2], rtol=0, atol=0) + @staticmethod + def _make_padded_mxfp8_cpu_tensor( + shape: Tuple[int, ...], + *, + swizzled: bool = False, + fp8_dtype: te.DType = te.DType.kFloat8E4M3, + ) -> MXFP8Tensor: + """Build an MXFP8 tensor backed by padded CPU buffers.""" + quantizer = MXFP8Quantizer(fp8_dtype) + quantizer.optimize_for_gemm = swizzled + rowwise_scale_shape = quantizer.get_scale_shape(shape, columnwise=False) + columnwise_scale_shape = quantizer.get_scale_shape(shape, columnwise=True) + device = torch.device("cpu") + return MXFP8Tensor( + shape=shape, + dtype=torch.bfloat16, + rowwise_data=torch.full(shape, 1, dtype=torch.uint8, device=device), + rowwise_scale_inv=torch.full( + rowwise_scale_shape, 127, dtype=torch.uint8, device=device + ), + columnwise_data=torch.full(shape, 2, dtype=torch.uint8, device=device), + columnwise_scale_inv=torch.full( + columnwise_scale_shape, 128, dtype=torch.uint8, device=device + ), + fp8_dtype=quantizer.dtype, + quantizer=quantizer, + with_gemm_swizzled_scales=swizzled, + device=device, + ) + + @pytest.mark.parametrize( + "shape,scale_rows", + [ + ((48, 64), (48, 2)), + ((64, 64), (64, 2)), + ((64, 128), (64, 2)), + ((160, 64), (160, 5)), + ((2, 32, 128), (64, 2)), + ], + ) + def test_mxfp8_new_zeros_copies_unpadded_scales( + self, shape: Tuple[int, ...], scale_rows: Tuple[int, int] + ) -> None: + """Copy between padded MXFP8 buffers and new_zeros buffers on CPU.""" + padded = self._make_padded_mxfp8_cpu_tensor(shape) + unpadded = padded.new_zeros(shape) + assert isinstance(unpadded, MXFP8Tensor) + assert unpadded._rowwise_scale_inv.shape == (scale_rows[0], 4) + assert unpadded._columnwise_scale_inv.shape == (scale_rows[1], 128) + + unpadded.copy_(padded) + torch.testing.assert_close(unpadded._rowwise_data, padded._rowwise_data, rtol=0, atol=0) + torch.testing.assert_close( + unpadded._columnwise_data, padded._columnwise_data, rtol=0, atol=0 + ) + scale_pairs = ( + (padded._rowwise_scale_inv, unpadded._rowwise_scale_inv), + (padded._columnwise_scale_inv, unpadded._columnwise_scale_inv), + ) + for (padded_scale, unpadded_scale), active_rows in zip(scale_pairs, scale_rows): + torch.testing.assert_close(unpadded_scale, padded_scale[:active_rows], rtol=0, atol=0) + padded_scale.fill_(255) + + padded._rowwise_data.zero_() + padded._columnwise_data.zero_() + padded.copy_(unpadded) + torch.testing.assert_close(padded._rowwise_data, unpadded._rowwise_data, rtol=0, atol=0) + torch.testing.assert_close( + padded._columnwise_data, unpadded._columnwise_data, rtol=0, atol=0 + ) + for (padded_scale, unpadded_scale), active_rows in zip(scale_pairs, scale_rows): + torch.testing.assert_close(padded_scale[:active_rows], unpadded_scale, rtol=0, atol=0) + assert torch.count_nonzero(padded_scale[active_rows:]).item() == 0 + + def test_mxfp8_copy_preserves_equal_shape_scale_padding(self) -> None: + """Copy all scale bytes when the source and destination shapes match.""" + src = self._make_padded_mxfp8_cpu_tensor((64, 128)) + dst = self._make_padded_mxfp8_cpu_tensor((64, 128)) + dst._rowwise_scale_inv.zero_() + dst._columnwise_scale_inv.zero_() + + dst.copy_(src) + torch.testing.assert_close(dst._rowwise_scale_inv, src._rowwise_scale_inv, rtol=0, atol=0) + torch.testing.assert_close( + dst._columnwise_scale_inv, src._columnwise_scale_inv, rtol=0, atol=0 + ) + + def test_mxfp8_fsdp_shard_copy_from_padded_scales(self) -> None: + """Copy each padded chunk into an unpadded FSDP2 shard allocation.""" + full = self._make_padded_mxfp8_cpu_tensor((128, 128)) + row_values = torch.arange(1, 129, dtype=torch.uint8).view(-1, 1) + full._rowwise_data.copy_(row_values) + full._columnwise_data.copy_(129 - row_values) + full._rowwise_scale_inv.copy_(row_values + 32) + full._columnwise_scale_inv.copy_(torch.arange(129, 133, dtype=torch.uint8).view(-1, 1)) + + shards = torch.chunk(full, 2, dim=0) + assert len(shards) == 2 + for index, shard in enumerate(shards): + assert isinstance(shard, MXFP8Tensor) + assert shard._rowwise_scale_inv.shape == (128, 4) + assert shard._columnwise_scale_inv.shape == (4, 128) + dst = shard.new_zeros(shard.shape).copy_(shard) + assert isinstance(dst, MXFP8Tensor) + assert dst._rowwise_scale_inv.shape == (64, 4) + assert dst._columnwise_scale_inv.shape == (2, 128) + rows = slice(index * 64, (index + 1) * 64) + blocks = slice(index * 2, (index + 1) * 2) + torch.testing.assert_close(dst._rowwise_data, full._rowwise_data[rows], rtol=0, atol=0) + torch.testing.assert_close( + dst._columnwise_data, full._columnwise_data[rows], rtol=0, atol=0 + ) + torch.testing.assert_close( + dst._rowwise_scale_inv, full._rowwise_scale_inv[rows], rtol=0, atol=0 + ) + torch.testing.assert_close( + dst._columnwise_scale_inv, full._columnwise_scale_inv[blocks], rtol=0, atol=0 + ) + + @pytest.mark.parametrize( + "scale_attr,active_rows", [("_rowwise_scale_inv", 96), ("_columnwise_scale_inv", 3)] + ) + @pytest.mark.parametrize( + "mismatch", ["swizzled", "short", "inner_dim", "singleton_src", "singleton_dst"] + ) + def test_mxfp8_copy_rejects_incompatible_scale_shapes( + self, scale_attr: str, active_rows: int, mismatch: str + ) -> None: + """Reject invalid scale shapes before writing any destination buffers.""" + shape = (96, 128) + src = self._make_padded_mxfp8_cpu_tensor(shape, swizzled=mismatch == "swizzled") + dst = self._make_padded_mxfp8_cpu_tensor(shape, swizzled=mismatch == "swizzled") + src._rowwise_data.fill_(3) + src._columnwise_data.fill_(4) + src._rowwise_scale_inv.fill_(125) + src._columnwise_scale_inv.fill_(126) + + malformed = src if mismatch == "singleton_src" else dst + scale = getattr(malformed, scale_attr) + if mismatch == "swizzled": + scale = scale[:active_rows] + elif mismatch == "short": + scale = scale[: active_rows - 1] + elif mismatch == "inner_dim": + scale = scale[:, :-1] + else: + scale = scale[:1] + setattr(malformed, scale_attr, scale) + + dst_buffers = { + attr: getattr(dst, attr).clone() + for attr in ( + "_rowwise_data", + "_columnwise_data", + "_rowwise_scale_inv", + "_columnwise_scale_inv", + ) + } + + with pytest.raises(RuntimeError, match="Incompatible MXFP8 scale_inv shapes"): + dst.copy_(src) + + for attr, before in dst_buffers.items(): + torch.testing.assert_close(getattr(dst, attr), before, rtol=0, atol=0) + + @pytest.mark.parametrize( + "src_shape,src_fp8_dtype,can_broadcast", + [ + pytest.param((2, 32, 128), te.DType.kFloat8E5M2, True, id="mixed_fp8_formats"), + pytest.param((3, 32, 128), te.DType.kFloat8E4M3, False, id="shape_mismatch"), + pytest.param((1, 32, 128), te.DType.kFloat8E4M3, True, id="broadcastable_shape"), + ], + ) + def test_mxfp8_copy_falls_back_for_incompatible_tensors( + self, + src_shape: Tuple[int, ...], + src_fp8_dtype: te.DType, + can_broadcast: bool, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """Requantize values when FP8 formats or logical shapes differ.""" + src = self._make_padded_mxfp8_cpu_tensor(src_shape, fp8_dtype=src_fp8_dtype) + dst = self._make_padded_mxfp8_cpu_tensor((2, 32, 128)) + hp_src = torch.arange(src.numel(), dtype=torch.bfloat16, device="cpu").reshape(src.shape) + quantize_inputs = [] + dst_buffers = { + attr: getattr(dst, attr).clone() + for attr in ( + "_rowwise_data", + "_columnwise_data", + "_rowwise_scale_inv", + "_columnwise_scale_inv", + ) + } + for attr in dst_buffers: + getattr(src, attr).zero_() + + def quantize_(tensor: torch.Tensor) -> MXFP8Tensor: + quantize_inputs.append(tensor) + return dst + + monkeypatch.setattr(src, "dequantize", lambda: hp_src) + monkeypatch.setattr(dst, "quantize_", quantize_) + if can_broadcast: + assert dst.copy_(src) is dst + assert len(quantize_inputs) == 1 + torch.testing.assert_close(quantize_inputs[0], hp_src.expand_as(dst), rtol=0, atol=0) + else: + with pytest.raises(RuntimeError, match="expanded size of the tensor"): + dst.copy_(src) + assert not quantize_inputs + + for attr, before in dst_buffers.items(): + torch.testing.assert_close(getattr(dst, attr), before, rtol=0, atol=0) + @pytest.mark.parametrize("quantization", _quantization_list) @pytest.mark.parametrize("dim", [0, 1]) def test_chunk( diff --git a/transformer_engine/pytorch/tensor/mxfp8_tensor.py b/transformer_engine/pytorch/tensor/mxfp8_tensor.py index c65828707d..4d186f732e 100644 --- a/transformer_engine/pytorch/tensor/mxfp8_tensor.py +++ b/transformer_engine/pytorch/tensor/mxfp8_tensor.py @@ -356,6 +356,18 @@ def contiguous( return self raise ValueError("MXFP8Tensor does not support different memory formats!") + @staticmethod + def _can_copy_unswizzled_scale_rows( + dst_scale: torch.Tensor, src_scale: torch.Tensor, active_rows: int + ) -> bool: + """Return whether both scales contain a compatible active row prefix.""" + return ( + dst_scale.ndim == src_scale.ndim == 2 + and dst_scale.shape[1] == src_scale.shape[1] + and dst_scale.shape[0] >= active_rows + and src_scale.shape[0] >= active_rows + ) + @classmethod def __torch_dispatch__(cls, func, types, args, kwargs=None): if func == aten.view.default: @@ -395,20 +407,74 @@ def __torch_dispatch__(cls, func, types, args, kwargs=None): pass elif src._with_gemm_swizzled_scales != dst._with_gemm_swizzled_scales: pass + elif src._fp8_dtype != dst._fp8_dtype or src.shape != dst.shape: + src_hp = src.dequantize() + if src_hp.shape != dst.shape: + src_hp = src_hp.expand_as(dst) + return dst.quantize_(src_hp) else: - # src and dst match, so we can directly copy data + copy_args = args[2:] + copy_kwargs = kwargs or {} + rowwise_rows = math.prod(dst.shape[:-1]) if dst.ndim >= 2 else None + columnwise_rows = ( + ceil_div(rowwise_rows, MXFP8_BLOCK_SCALING_SIZE) + if rowwise_rows is not None + else None + ) + + # Validate both scale pairs before copying any buffers. + scale_copies = [] + for dst_data, dst_scale, src_scale, active_rows in ( + ( + dst._rowwise_data, + dst._rowwise_scale_inv, + src._rowwise_scale_inv, + rowwise_rows, + ), + ( + dst._columnwise_data, + dst._columnwise_scale_inv, + src._columnwise_scale_inv, + columnwise_rows, + ), + ): + if dst_data is None: + continue + if dst_scale.shape == src_scale.shape: + scale_copies.append((dst_scale, src_scale, None)) + elif ( + not dst._with_gemm_swizzled_scales + and active_rows is not None + and cls._can_copy_unswizzled_scale_rows( + dst_scale, src_scale, active_rows + ) + ): + scale_copies.append((dst_scale, src_scale, active_rows)) + else: + raise RuntimeError( + "Incompatible MXFP8 scale_inv shapes in copy_: " + f"dst {tuple(dst_scale.shape)} vs src {tuple(src_scale.shape)} " + f"for tensor shape {tuple(dst.shape)}" + ) + if dst._rowwise_data is not None: - dst._rowwise_data.copy_(src._rowwise_data.detach(), *args[2:], **kwargs) - dst._rowwise_scale_inv.copy_( - src._rowwise_scale_inv.detach(), *args[2:], **kwargs + dst._rowwise_data.copy_( + src._rowwise_data.detach(), *copy_args, **copy_kwargs ) if dst._columnwise_data is not None: dst._columnwise_data.copy_( - src._columnwise_data.detach(), *args[2:], **kwargs - ) - dst._columnwise_scale_inv.copy_( - src._columnwise_scale_inv.detach(), *args[2:], **kwargs + src._columnwise_data.detach(), *copy_args, **copy_kwargs ) + for dst_scale, src_scale, active_rows in scale_copies: + src_scale = src_scale.detach() + if active_rows is None: + dst_scale.copy_(src_scale, *copy_args, **copy_kwargs) + else: + dst_scale[:active_rows].copy_( + src_scale[:active_rows], *copy_args, **copy_kwargs + ) + if dst_scale.shape[0] > active_rows: + dst_scale[active_rows:].zero_() return dst if func == aten.split.Tensor: