|
4 | 4 |
|
5 | 5 | import copy |
6 | 6 | from contextlib import nullcontext |
| 7 | +import socket |
7 | 8 |
|
8 | 9 | import pytest |
9 | 10 | import torch |
10 | 11 | from torch import nn |
11 | 12 | import transformer_engine.pytorch as te |
12 | | -from transformer_engine.common.recipe import DelayedScaling, MXFP8BlockScaling, Float8BlockScaling |
| 13 | +from transformer_engine.common.recipe import ( |
| 14 | + DelayedScaling, |
| 15 | + Float8BlockScaling, |
| 16 | + Float8CurrentScaling, |
| 17 | + MXFP8BlockScaling, |
| 18 | +) |
13 | 19 | from transformer_engine.pytorch import MultiheadAttention, quantized_model_init, is_bf16_available |
14 | 20 | from transformer_engine.pytorch import QuantizedTensor |
15 | 21 | from transformer_engine.pytorch.optimizers.fused_adam import ( |
|
19 | 25 |
|
20 | 26 | # Check if FP8 is supported |
21 | 27 | fp8_available, reason_for_no_fp8 = te.is_fp8_available(return_reason=True) |
| 28 | +mxfp8_available, reason_for_no_mxfp8 = te.is_mxfp8_available(return_reason=True) |
| 29 | +fp8_block_scaling_available, reason_for_no_fp8_block_scaling = te.is_fp8_block_scaling_available( |
| 30 | + return_reason=True |
| 31 | +) |
22 | 32 |
|
23 | 33 |
|
24 | 34 | class TestFusedOptimizer: |
@@ -100,6 +110,205 @@ def setup_method(self) -> None: |
100 | 110 | self.ref_optim = torch.optim.Adam |
101 | 111 | self.fused_optim = te.optimizers.FusedAdam |
102 | 112 |
|
| 113 | + @pytest.mark.parametrize("param_dtype", [torch.bfloat16, torch.float16, torch.float32]) |
| 114 | + @pytest.mark.parametrize("store_remainders", [False, True]) |
| 115 | + @pytest.mark.parametrize("initialized", [False, True]) |
| 116 | + @pytest.mark.parametrize("source_device", ["cpu", "cuda"]) |
| 117 | + def test_update_param(self, param_dtype, store_remainders, initialized, source_device): |
| 118 | + """Reload FP32 values exactly, preserving Adam history and the source tensor.""" |
| 119 | + param = nn.Parameter(torch.ones(32, dtype=param_dtype, device="cuda")) |
| 120 | + optimizer = self.fused_optim( |
| 121 | + [param], master_weights=True, store_param_remainders=store_remainders, **self.options |
| 122 | + ) |
| 123 | + if initialized: |
| 124 | + param.grad = torch.full_like(param, 0.125) |
| 125 | + optimizer.step() |
| 126 | + old_state = { |
| 127 | + name: (value, value.clone()) |
| 128 | + for name, value in optimizer.state[param].items() |
| 129 | + if name != "master_param" |
| 130 | + } |
| 131 | + step = optimizer.param_groups[0].get("step") |
| 132 | + # A strided FP32 source with positive/negative BF16 rounding ties and adjacent values. |
| 133 | + source = torch.full((64,), 1.001, device=source_device)[::2] |
| 134 | + source[:8] = torch.tensor( |
| 135 | + [1.00390625, 1.01171875, -1.00390625, -1.01171875, 0.0, -0.0, 2**-130, -(2**-130)], |
| 136 | + device=source_device, |
| 137 | + ) |
| 138 | + saved_source = source.clone() |
| 139 | + optimizer.update_param(param=param, values=source) |
| 140 | + assert torch.equal(source.view(torch.int32), saved_source.view(torch.int32)) |
| 141 | + assert optimizer.param_groups[0].get("step") == step |
| 142 | + for name, (old_tensor, old_value) in old_state.items(): |
| 143 | + assert optimizer.state[param][name] is old_tensor |
| 144 | + assert torch.equal(optimizer.state[param][name], old_value) |
| 145 | + if not initialized: |
| 146 | + for name in ("exp_avg", "exp_avg_sq"): |
| 147 | + assert torch.count_nonzero(optimizer.state[param][name]) == 0 |
| 148 | + |
| 149 | + if store_remainders and param_dtype == torch.bfloat16: |
| 150 | + assert torch.equal( |
| 151 | + param[:4], |
| 152 | + torch.tensor( |
| 153 | + [1.0078125, 1.015625, -1.0078125, -1.015625], |
| 154 | + device="cuda", |
| 155 | + dtype=torch.bfloat16, |
| 156 | + ), |
| 157 | + ) |
| 158 | + remainder = optimizer.state[param]["master_param"] |
| 159 | + high = param.view(torch.int16) - (remainder < 0).to(torch.int16) |
| 160 | + restored = (high.to(torch.int32) << 16) | (remainder.to(torch.int32) & 0xFFFF) |
| 161 | + assert torch.equal(restored.cpu(), source.contiguous().view(torch.int32).cpu()) |
| 162 | + else: |
| 163 | + master = optimizer.get_unscaled_state(param, "master_param") |
| 164 | + assert torch.equal(master.cpu(), source.cpu()) |
| 165 | + assert torch.equal(param.cpu(), source.to(dtype=param_dtype, device="cpu")) |
| 166 | + |
| 167 | + # Reload must create complete optimizer state, so the following real update works too. |
| 168 | + reference = nn.Parameter(source.to(device="cuda").clone()) |
| 169 | + reference_optimizer = self.fused_optim([reference], **self.options) |
| 170 | + reference_optimizer.state[reference] = { |
| 171 | + name: optimizer.state[param][name].clone() for name in ("exp_avg", "exp_avg_sq") |
| 172 | + } |
| 173 | + if step is not None: |
| 174 | + reference_optimizer.param_groups[0]["step"] = step |
| 175 | + param.grad = torch.full_like(param, 0.125) |
| 176 | + reference.grad = torch.full_like(reference, 0.125) |
| 177 | + optimizer.step() |
| 178 | + reference_optimizer.step() |
| 179 | + torch.testing.assert_close(param.float(), reference.float(), rtol=2**-7, atol=1e-7) |
| 180 | + |
| 181 | + @pytest.mark.parametrize( |
| 182 | + "recipe", |
| 183 | + [ |
| 184 | + pytest.param( |
| 185 | + DelayedScaling, |
| 186 | + marks=pytest.mark.skipif(not fp8_available, reason=reason_for_no_fp8), |
| 187 | + ), |
| 188 | + pytest.param( |
| 189 | + Float8CurrentScaling, |
| 190 | + marks=pytest.mark.skipif(not fp8_available, reason=reason_for_no_fp8), |
| 191 | + ), |
| 192 | + pytest.param( |
| 193 | + MXFP8BlockScaling, |
| 194 | + marks=pytest.mark.skipif(not mxfp8_available, reason=reason_for_no_mxfp8), |
| 195 | + ), |
| 196 | + pytest.param( |
| 197 | + Float8BlockScaling, |
| 198 | + marks=pytest.mark.skipif( |
| 199 | + not fp8_block_scaling_available, reason=reason_for_no_fp8_block_scaling |
| 200 | + ), |
| 201 | + ), |
| 202 | + ], |
| 203 | + ) |
| 204 | + def test_update_quantized_param(self, recipe): |
| 205 | + """Quantized parameters keep exact FP32 masters and quantized model storage.""" |
| 206 | + with quantized_model_init(enabled=True, recipe=recipe()): |
| 207 | + model = te.Linear(256, 256, bias=False, params_dtype=torch.bfloat16).cuda() |
| 208 | + param = model.weight |
| 209 | + assert isinstance(param, QuantizedTensor) |
| 210 | + optimizer = self.fused_optim( |
| 211 | + [param], master_weights=True, use_decoupled_grad=True, **self.options |
| 212 | + ) |
| 213 | + source = torch.full(param.shape, 1.001, device="cuda") |
| 214 | + expected = param.detach().clone() |
| 215 | + expected.copy_(source) |
| 216 | + optimizer.update_param(param, source) |
| 217 | + assert isinstance(param, QuantizedTensor) |
| 218 | + assert torch.equal(optimizer.state[param]["master_param"], source) |
| 219 | + assert torch.equal( |
| 220 | + param.dequantize(dtype=torch.float32), expected.dequantize(dtype=torch.float32) |
| 221 | + ) |
| 222 | + |
| 223 | + # The reloaded state must be complete enough for a real update. |
| 224 | + param.decoupled_grad = torch.full(param.shape, 0.125, device="cuda") |
| 225 | + optimizer.step() |
| 226 | + master = optimizer.state[param]["master_param"] |
| 227 | + assert torch.all(master < source) |
| 228 | + torch.testing.assert_close( |
| 229 | + param.dequantize(dtype=torch.float32), master, rtol=0.125, atol=0 |
| 230 | + ) |
| 231 | + |
| 232 | + @pytest.mark.parametrize("master_dtype", [torch.float32, torch.float16]) |
| 233 | + def test_update_param_mixed_dtypes(self, master_dtype): |
| 234 | + """Remainders apply only to BF16 parameters, and scaled masters use the existing setter.""" |
| 235 | + params = [ |
| 236 | + nn.Parameter(torch.ones(16, dtype=dtype, device="cuda")) |
| 237 | + for dtype in (torch.bfloat16, torch.float32) |
| 238 | + ] |
| 239 | + optimizer = self.fused_optim( |
| 240 | + params, |
| 241 | + master_weights=True, |
| 242 | + master_weight_dtype=master_dtype, |
| 243 | + store_param_remainders=True, |
| 244 | + **self.options, |
| 245 | + ) |
| 246 | + source = torch.full((16,), 1.001, device="cuda") |
| 247 | + original_source = source.clone() |
| 248 | + for param in params: |
| 249 | + optimizer.update_param(param, source) |
| 250 | + assert torch.equal(source, original_source) |
| 251 | + assert torch.equal(params[1], source) |
| 252 | + for param in params: |
| 253 | + state = optimizer.state[param]["master_param"] |
| 254 | + remainders = master_dtype == torch.float32 and param.dtype == torch.bfloat16 |
| 255 | + assert state.dtype == (torch.int16 if remainders else master_dtype) |
| 256 | + if not remainders: |
| 257 | + torch.testing.assert_close( |
| 258 | + optimizer.get_unscaled_state(param, "master_param"), |
| 259 | + source, |
| 260 | + rtol=2**-10, |
| 261 | + atol=0, |
| 262 | + ) |
| 263 | + |
| 264 | + @pytest.mark.parametrize("master_layout", ["matching", "local", "replicated", "plain_param"]) |
| 265 | + def test_update_dtensor_param(self, master_layout): |
| 266 | + """DTensor masters must match the parameter's distribution; local tensors are accepted.""" |
| 267 | + from torch.distributed.device_mesh import init_device_mesh |
| 268 | + from torch.distributed.tensor import DTensor, Replicate, Shard |
| 269 | + |
| 270 | + created_group = not torch.distributed.is_initialized() |
| 271 | + if created_group: |
| 272 | + with socket.socket() as sock: |
| 273 | + sock.bind(("127.0.0.1", 0)) |
| 274 | + port = sock.getsockname()[1] |
| 275 | + torch.distributed.init_process_group( |
| 276 | + "nccl", init_method=f"tcp://127.0.0.1:{port}", rank=0, world_size=1 |
| 277 | + ) |
| 278 | + try: |
| 279 | + mesh = init_device_mesh("cuda", (1,)) |
| 280 | + values = torch.ones(8, device="cuda", dtype=torch.bfloat16) |
| 281 | + if master_layout == "plain_param": |
| 282 | + param = nn.Parameter(values) |
| 283 | + else: |
| 284 | + param = nn.Parameter(DTensor.from_local(values, mesh, [Shard(0)])) |
| 285 | + optimizer = self.fused_optim([param], master_weights=True, **self.options) |
| 286 | + local = torch.full((8,), 1.001, device="cuda") |
| 287 | + if master_layout == "local": |
| 288 | + source = local |
| 289 | + else: |
| 290 | + # On one rank Shard(0) and Replicate() have identical local shapes, |
| 291 | + # so only the explicit layout check can tell them apart. |
| 292 | + placement = Replicate() if master_layout == "replicated" else Shard(0) |
| 293 | + source = DTensor.from_local(local, mesh, [placement]) |
| 294 | + |
| 295 | + if master_layout in ("replicated", "plain_param"): |
| 296 | + with pytest.raises(ValueError): |
| 297 | + optimizer.update_param(param, source) |
| 298 | + assert len(optimizer.state) == 0 |
| 299 | + return |
| 300 | + |
| 301 | + optimizer.update_param(param, source) |
| 302 | + state = optimizer.state[param] |
| 303 | + for name in ("exp_avg", "exp_avg_sq", "master_param"): |
| 304 | + assert isinstance(state[name], DTensor) |
| 305 | + assert state[name].placements == param.placements |
| 306 | + assert torch.equal(optimizer.get_unscaled_state(param, "master_param"), local) |
| 307 | + assert torch.equal(param.to_local(), local.bfloat16()) |
| 308 | + finally: |
| 309 | + if created_group: |
| 310 | + torch.distributed.destroy_process_group() |
| 311 | + |
103 | 312 | def test_float(self): |
104 | 313 | self.gen_single_type_test(param_type=torch.float) |
105 | 314 |
|
|
0 commit comments