Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 73 additions & 1 deletion tests/pytorch/test_grouped_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

"""Tests for GroupedTensor class"""

from types import SimpleNamespace
from types import MethodType, SimpleNamespace
from typing import List, Optional, Tuple

import pytest
Expand Down Expand Up @@ -45,6 +45,78 @@
_fp8bs_pow2_required = _device_cc >= (10, 0)


@pytest.mark.parametrize("swap", [False, True])
def test_grouped_parameter_device_conversion(swap):
"""Module conversion moves packed storage and keeps caller-owned parameter state."""
previous_swap = torch.__future__.get_swap_module_params_on_conversion()
torch.__future__.set_swap_module_params_on_conversion(swap)
try:
module = te.GroupedLinear(
2,
32,
64,
device="cpu",
params_dtype=torch.float32,
single_grouped_weight=True,
single_grouped_bias=True,
)
originals = dict(module.named_parameters())
expected = {}
for name, parameter in originals.items():
parameter.probe_attr = object()
parameter.probe_method = MethodType(lambda parameter: parameter.probe_attr, parameter)
parameter.overwrite_main_grad = False
expected[name] = parameter.rowwise_data.to(dtype=torch.bfloat16)
parameter.quantized_tensors = parameter.split_into_quantized_tensors()
probes = {name: parameter.probe_attr for name, parameter in originals.items()}
module.to(device="cuda", dtype=torch.bfloat16)
for name, parameter in module.named_parameters():
assert parameter is originals[name]
assert isinstance(parameter, GroupedTensor)
assert parameter.device.type == "cuda"
assert parameter.rowwise_data.device == parameter.device
assert parameter.rowwise_data.dtype == parameter.dtype == torch.bfloat16
assert parameter.probe_attr is probes[name]
assert parameter.probe_method.__self__ is parameter
assert parameter.probe_method() is probes[name]
assert parameter.overwrite_main_grad is False
assert parameter.quantized_tensors is None
torch.testing.assert_close(parameter.rowwise_data.cpu(), expected[name])
for member in parameter.split_into_quantized_tensors():
assert member.device == parameter.device
assert (
member.untyped_storage().data_ptr()
== parameter.rowwise_data.untyped_storage().data_ptr()
)
module.cpu()
for name, parameter in module.named_parameters():
assert parameter is originals[name]
assert parameter.device.type == parameter.rowwise_data.device.type == "cpu"
torch.testing.assert_close(parameter.rowwise_data, expected[name])
finally:
torch.__future__.set_swap_module_params_on_conversion(previous_swap)


def test_grouped_parameter_data_assignment():
"""The data setter updates backing storage, not just the wrapper's TensorImpl."""
original = torch.randn(2, 32, 16)
parameter = torch.nn.Parameter(
GroupedTensor(
shape=(64, 16),
dtype=original.dtype,
num_tensors=2,
shapes=[(32, 16)] * 2,
data=original.reshape(-1),
)
)
parameter.split_into_quantized_tensors()
replacement = torch.randn_like(original, device="cuda")
parameter.data = replacement
assert parameter.device == parameter.rowwise_data.device == replacement.device
assert parameter.rowwise_data.data_ptr() == replacement.data_ptr()
torch.testing.assert_close(torch.stack(parameter.split_into_quantized_tensors()), replacement)


def test_mark_grouped_tensor_supports_plain_tensor():
tensor = torch.empty(16)

Expand Down
4 changes: 3 additions & 1 deletion transformer_engine/pytorch/module/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# See LICENSE for license information.

"""Base modules and utilities for TransformerEngine PyTorch API"""

import functools
import io
import math
Expand Down Expand Up @@ -63,6 +64,7 @@
from ..tensor.storage.mxfp4_tensor_storage import MXFP4TensorStorage
from ..tensor.storage.nvfp4_tensor_storage import NVFP4TensorStorage
from ..tensor.storage.hybrid_tensor_storage import HybridQuantizedTensorStorage
from ..tensor.storage.grouped_tensor_storage import GroupedTensorStorage
from ..utils import (
is_non_tn_fp8_gemm_supported,
torch_get_autocast_gpu_dtype,
Expand Down Expand Up @@ -1132,7 +1134,7 @@ def _apply(self, *args, **kwargs):
snapshots = {
name: (param, dict(param.__dict__))
for name, param in self._parameters.items()
if isinstance(param, QuantizedTensorStorage)
if isinstance(param, (QuantizedTensorStorage, GroupedTensorStorage))
}
out = super()._apply(*args, **kwargs)
for name, (old_param, attrs) in snapshots.items():
Expand Down
87 changes: 86 additions & 1 deletion transformer_engine/pytorch/tensor/grouped_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# See LICENSE for license information.

"""Grouped tensor class for handling collections of tensors with different shapes"""

from __future__ import annotations

from typing import List, Optional, Tuple
Expand All @@ -11,7 +12,12 @@
from torch.utils._pytree import tree_map

from transformer_engine.pytorch.device import te_device_type
from ..quantized_tensor import QuantizedTensorStorage, Quantizer
from ..quantized_tensor import (
QuantizedTensorStorage,
Quantizer,
_bind_op_args,
_device_conversion_ops,
)
from .storage.grouped_tensor_storage import GroupedTensorStorage
from ..constants import DType

Expand Down Expand Up @@ -227,6 +233,58 @@ def make_wrapper_like(src: GroupedTensor) -> GroupedTensor:
copy_grouped_storage_metadata(out, src)
return out

if func in _device_conversion_ops:
src = args[0]
conversion = _bind_op_args(func, args, kwargs)
other = conversion.get("other")
dtype = other.dtype if other is not None else conversion.get("dtype")
device = other.device if other is not None else conversion.get("device")
dtype = src.dtype if dtype is None else dtype
device = src.device if device is None else device
storage = src.copy()
for name, value in vars(storage).items():
if not isinstance(value, torch.Tensor):
continue
buffer_kwargs = {
name: conversion[name]
for name in ("layout", "pin_memory", "non_blocking", "memory_format")
if name in conversion
}
buffer_kwargs["device"] = device
buffer_kwargs["dtype"] = (
dtype
if name in ("rowwise_data", "columnwise_data") and src.quantizer is None
else value.dtype
)
setattr(storage, name, torch.ops.aten._to_copy.default(value, **buffer_kwargs))
return type(src)(
shape=storage.logical_shape,
dtype=dtype,
num_tensors=storage.num_tensors,
shapes=storage.tensor_shapes,
quantizer=storage.quantizer,
data=storage.rowwise_data,
columnwise_data=storage.columnwise_data,
scale_inv=storage.scale_inv,
columnwise_scale_inv=storage.columnwise_scale_inv,
amax=storage.amax,
columnwise_amax=storage.columnwise_amax,
scale=storage.scale,
first_dims=storage.first_dims,
last_dims=storage.last_dims,
tensor_offsets=storage.tensor_offsets,
offsets=storage.offsets,
scale_inv_offsets=storage.scale_inv_offsets,
columnwise_scale_inv_offsets=storage.columnwise_scale_inv_offsets,
with_gemm_swizzled_scales=storage._with_gemm_swizzled_scales,
row_scaled_nvfp4=storage.row_scaled_nvfp4,
nvfp4_use_4over6=storage.nvfp4_use_4over6,
nvfp4_e4m3_max=storage.nvfp4_e4m3_max,
scale_inv_dtype=storage._scale_inv_dtype,
stride=tuple(src.stride()),

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.

P1 Conversion fails after splitting

A native-created uniform GroupedTensor starts with a 2D wrapper and no tensor_shapes. Calling split_into_quantized_tensors() fills those member shapes. Conversion then passes them into the constructor, which chooses a 3D wrapper, while this line retains the original 2D stride. PyTorch rejects the different shape and stride lengths, so .cpu() or dtype conversion raises after splitting. Preserve the source wrapper shape when rebuilding it.

Knowledge Base Used: PyTorch tensor and operator abstractions

requires_grad=False,
)

# Parameter construction calls detach()/alias-like paths.
if func in (torch.ops.aten.detach.default, torch.ops.aten.alias.default):
src = args[0]
Expand Down Expand Up @@ -377,6 +435,33 @@ def maybe_update_inplace(arg, new_arg, schema_arg):

__torch_function__ = torch._C._disabled_torch_function_impl

# pylint: disable=unnecessary-dunder-call
def _get_data(self) -> torch.Tensor:
"""Detached grouped storage, including its backing buffers."""
return super().data

def _set_data(self, tensor: torch.Tensor) -> None:
"""Replace backing storage without losing parameter identity or caller state."""
if not isinstance(tensor, GroupedTensor):
if self.quantizer is not None or not self.all_same_shape():
raise TypeError("Assign grouped storage to a quantized or nonuniform GroupedTensor")
if tuple(tensor.shape) != tuple(self.shape) or not tensor.is_contiguous():
raise ValueError("GroupedTensor data must have the same shape and be contiguous")
tensor = GroupedTensor(
shape=self.logical_shape,
dtype=tensor.dtype,
num_tensors=self.num_tensors,
shapes=self.tensor_shapes,
data=tensor.reshape(-1),
)
storage = tensor.copy()
super(GroupedTensor, type(self)).data.__set__(self, tensor)
self.__dict__.update(vars(storage))

# pylint: enable=unnecessary-dunder-call

data = property(_get_data, _set_data)

def expand_as(self, other: torch.Tensor) -> torch.Tensor:
# pylint: disable=missing-function-docstring
# Needed during parameter creation/hook registration paths.
Expand Down
Loading