Skip to content

Commit 7a35695

Browse files
authored
Add AQT tensor parallel for float8_dynamic_quant (#1078)
1 parent 6ea36c5 commit 7a35695

File tree

3 files changed

+175
-8
lines changed

3 files changed

+175
-8
lines changed

test/dtypes/test_affine_quantized_tensor_parallel.py

Lines changed: 142 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,20 @@
11
import torch
2+
import unittest
23
from torchao.testing.utils import copy_tests, TorchAOTensorParallelTestCase
34
from torch.testing._internal.common_utils import run_tests
4-
from torchao.quantization import int8_weight_only, float8_weight_only
5+
from torch.testing._internal import common_utils
6+
from torchao.quantization import int8_weight_only, float8_weight_only, float8_dynamic_activation_float8_weight
7+
from torchao.quantization.observer import PerRow, PerTensor
8+
import torch.distributed as dist
9+
from torch.distributed._tensor import DTensor, Replicate, Shard, DeviceMesh
10+
from torch.testing._internal.distributed._tensor.common_dtensor import (
11+
DTensorTestBase,
12+
with_comms,
13+
NUM_DEVICES,
14+
)
15+
from torchao.quantization.quant_api import quantize_
16+
from torchao.dtypes import AffineQuantizedTensor
17+
from torchao.utils import TORCH_VERSION_AT_LEAST_2_5
518

619
class TestInt8woAffineQuantizedTensorParallel(TorchAOTensorParallelTestCase):
720
QUANT_METHOD_FN = staticmethod(int8_weight_only)
@@ -13,5 +26,133 @@ class TestFloat8woAffineQuantizedTensorParallel(TorchAOTensorParallelTestCase):
1326
QUANT_METHOD_FN = staticmethod(float8_weight_only)
1427
copy_tests(TorchAOTensorParallelTestCase, TestFloat8woAffineQuantizedTensorParallel, "fp8wo_tp")
1528

29+
# Run only on H100
30+
if torch.cuda.is_available() and torch.cuda.get_device_capability() >= (9, 0):
31+
class TestFloat8dqAffineQuantizedTensorParallel(DTensorTestBase):
32+
"""Basic test case for tensor subclasses
33+
"""
34+
COMMON_DTYPES = [torch.bfloat16, torch.float16, torch.float32]
35+
TENSOR_SUBCLASS = AffineQuantizedTensor
36+
QUANT_METHOD_FN = staticmethod(float8_dynamic_activation_float8_weight)
37+
QUANT_METHOD_KWARGS = {}
38+
39+
@staticmethod
40+
def colwise_shard(m: torch.nn.Module, mesh: DeviceMesh) -> torch.nn.Module:
41+
"""
42+
Shard linear layer of the model in column-wise fashion
43+
"""
44+
# Column-wise is wrt to A^T, so for A it is row-wise.
45+
# Number of rows per rank
46+
orig_weight = m.linear.weight
47+
n_local_rows = orig_weight.size(0) // mesh.size()
48+
rank = mesh.get_local_rank()
49+
local_shard = orig_weight[rank * n_local_rows : (rank + 1) * n_local_rows, :]
50+
# Construct DTensor from local shard
51+
dtensor = DTensor.from_local(local_shard, mesh, [Shard(0)])
52+
# Replace parameter in module
53+
m.linear.weight = torch.nn.Parameter(
54+
dtensor, requires_grad=False
55+
)
56+
return m
57+
58+
@staticmethod
59+
def rowwise_shard(m: torch.nn.Module, mesh: DeviceMesh) -> torch.nn.Module:
60+
"""
61+
Shard linear layer of the model in row-wise fashion
62+
"""
63+
# Row-wise is wrt to A^T, so for A it is column-wise.
64+
# Number of rows per rank
65+
orig_weight = m.linear.weight
66+
n_local_cols = orig_weight.size(1) // mesh.size()
67+
rank = mesh.get_local_rank()
68+
local_shard = orig_weight[:, rank * n_local_cols : (rank + 1) * n_local_cols]
69+
# Construct DTensor from local shard
70+
dtensor = DTensor.from_local(local_shard, mesh, [Shard(1)], run_check=True)
71+
# Replace parameter in module
72+
m.linear.weight = torch.nn.Parameter(
73+
dtensor, requires_grad=False
74+
)
75+
return m
76+
77+
def quantize(self, m: torch.nn.Module) -> torch.nn.Module:
78+
"""
79+
Quantize the model
80+
"""
81+
quantize_(m, self.QUANT_METHOD_FN(**self.QUANT_METHOD_KWARGS))
82+
return m
83+
84+
def _test_tp(self, dtype):
85+
device = "cuda"
86+
# To make sure different ranks create the same module
87+
torch.manual_seed(5)
88+
89+
class M(torch.nn.Module):
90+
def __init__(self, in_features, out_features, **kwargs) -> None:
91+
super().__init__(**kwargs)
92+
self.linear = torch.nn.Linear(in_features, out_features, bias=False, device="cuda")
93+
94+
def forward(self, x: torch.Tensor) -> torch.Tensor:
95+
return self.linear(x)
96+
97+
# Get rank and device
98+
device = torch.device(f"cuda:{self.rank % torch.cuda.device_count()}")
99+
100+
# Original model
101+
proj_up = M(1024, 2048).to(device).to(dtype)
102+
proj_dn = M(2048, 1024).to(device).to(dtype)
103+
example_input = 100 * torch.randn(128, 1024, device=device, dtype=dtype)
104+
y = proj_dn(proj_up(example_input))
105+
# Quantize the model
106+
up_quant = self.quantize(proj_up)
107+
dn_quant = self.quantize(proj_dn)
108+
y_q = dn_quant(up_quant(example_input))
109+
110+
mesh = self.build_device_mesh()
111+
mesh.device_type = "cuda"
112+
113+
# Shard the models
114+
up_dist = self.colwise_shard(up_quant, mesh)
115+
dn_dist = self.rowwise_shard(dn_quant, mesh)
116+
117+
# We need to turn inputs into DTensor form as well -- just a format change
118+
input_dtensor = DTensor.from_local(
119+
example_input, mesh, [Replicate()]
120+
)
121+
122+
y_d = dn_dist(up_dist(input_dtensor))
123+
124+
if not TORCH_VERSION_AT_LEAST_2_5:
125+
# Need torch 2.5 to support compiled tensor parallelism
126+
return
127+
128+
up_compiled = torch.compile(up_dist)
129+
y_up = up_compiled(input_dtensor)
130+
dn_compiled = torch.compile(dn_dist)
131+
y_dn = dn_compiled(y_up)
132+
133+
class TestFloat8dqTensorAffineQuantizedTensorParallel(TestFloat8dqAffineQuantizedTensorParallel):
134+
QUANT_METHOD_FN = staticmethod(float8_dynamic_activation_float8_weight)
135+
QUANT_METHOD_KWARGS = {"granularity": PerTensor()}
136+
COMMON_DTYPES = [torch.bfloat16, torch.float16, torch.float32]
137+
138+
@common_utils.parametrize("dtype", COMMON_DTYPES)
139+
@with_comms
140+
@unittest.skipIf(not torch.cuda.is_available(), "Need CUDA available")
141+
def test_tp(self, dtype):
142+
return self._test_tp(dtype)
143+
144+
class TestFloat8dqRowAffineQuantizedTensorParallel(TestFloat8dqAffineQuantizedTensorParallel):
145+
QUANT_METHOD_FN = staticmethod(float8_dynamic_activation_float8_weight)
146+
QUANT_METHOD_KWARGS = {"granularity": PerRow()}
147+
COMMON_DTYPES = [torch.bfloat16]
148+
149+
@common_utils.parametrize("dtype", COMMON_DTYPES)
150+
@with_comms
151+
@unittest.skipIf(not torch.cuda.is_available(), "Need CUDA available")
152+
def test_tp(self, dtype):
153+
return self._test_tp(dtype)
154+
155+
common_utils.instantiate_parametrized_tests(TestFloat8dqTensorAffineQuantizedTensorParallel)
156+
common_utils.instantiate_parametrized_tests(TestFloat8dqRowAffineQuantizedTensorParallel)
16157
if __name__ == "__main__":
17158
run_tests()

torchao/dtypes/affine_quantized_tensor.py

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1062,9 +1062,12 @@ def __init__(
10621062

10631063
def _apply_fn_to_data(self, fn):
10641064
""" Applys a fn to all tensor components stored on this class"""
1065-
fn(self.float8_data)
1066-
fn(self.scale)
1067-
return self
1065+
return self.__class__(
1066+
fn(self.float8_data),
1067+
fn(self.scale),
1068+
self.transposed,
1069+
self._layout,
1070+
)
10681071

10691072
def to(self, *args, **kwargs):
10701073
kwargs = self._get_to_kwargs(*args, **kwargs)
@@ -1107,12 +1110,21 @@ def __torch_dispatch__(cls, func, types, args, kwargs):
11071110
elif func is aten.slice.Tensor:
11081111
self, dim, start, end, step = fill_defaults(args, 5, [0, None, None, 1])
11091112
if dim == 0:
1113+
#TODO: scale replecation should be dependent on block size
1114+
if self.scale.ndim == 1:
1115+
return return_and_correct_aliasing(
1116+
func, args, kwargs, args[0]._apply_fn_to_data(lambda x: aten.slice.Tensor(x, dim, start, end, step))
1117+
)
1118+
elif self.scale.ndim == 0:
1119+
return return_and_correct_aliasing(
1120+
func, args, kwargs, Float8AQTTensorImpl(aten.slice.Tensor(self.float8_data, dim, start, end, step), self.scale, None, self._layout)
1121+
)
1122+
else:
1123+
raise NotImplementedError(f"Float8AQTTensorImpl dispatch: attempting to run {func}, with scale ndim={dim}, that is not supported")
1124+
elif dim == 1:
11101125
return return_and_correct_aliasing(
1111-
func, args, kwargs, args[0]._apply_fn_to_data(lambda x: aten.slice.Tensor(x, dim, start, end, step))
1126+
func, args, kwargs, Float8AQTTensorImpl(aten.slice.Tensor(self.float8_data, dim, start, end, step).contiguous(), self.scale, None, self._layout)
11121127
)
1113-
elif dim == 1:
1114-
assert len(self.scale.shape) == 1, f"slice dim==1 only works when len(scale.shape) == 1 currently, got: {self.scale.shape}"
1115-
return Float8AQTTensorImpl(aten.slice.Tensor(self.float8_data, dim, start, end, step), self.scale, None, self._layout)
11161128
else:
11171129
raise NotImplementedError(f"Float8AQTTensorImpl dispatch: attempting to run {func}, with dim={dim}, that is not supported")
11181130
else:

torchao/quantization/linear_activation_quantized_tensor.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,20 @@ def _(func, types, args, kwargs):
165165
func, args, kwargs, args[0]._apply_fn_to_data(torch.t)
166166
)
167167

168+
@implements(aten.slice.Tensor)
169+
def _(func, types, args, kwargs):
170+
return return_and_correct_aliasing(
171+
func, args, kwargs, LinearActivationQuantizedTensor(
172+
func(args[0].original_weight_tensor, *args[1:]), args[0].input_quant_func)
173+
)
174+
175+
# this is needed for DTensor.from_local() and for flattening tensor
176+
@implements(aten.view.default)
177+
def _(func, types, args, kwargs):
178+
return return_and_correct_aliasing(
179+
func, args, kwargs, LinearActivationQuantizedTensor(func(args[0].original_weight_tensor, *args[1:]), args[0].input_quant_func)
180+
)
181+
168182
to_linear_activation_quantized = LinearActivationQuantizedTensor.from_float
169183

170184
if TORCH_VERSION_AT_LEAST_2_5:

0 commit comments

Comments
 (0)