|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | + |
| 3 | +# DeepSpeed Team |
| 4 | + |
| 5 | +import pytest |
| 6 | +import torch |
| 7 | +import deepspeed |
| 8 | +from unit.common import DistributedTest |
| 9 | +from unit.simple_model import SimpleModel, random_dataloader |
| 10 | + |
| 11 | + |
| 12 | +class TestZeroQuantBF16(DistributedTest): |
| 13 | + world_size = 2 |
| 14 | + |
| 15 | + @pytest.mark.parametrize("zero_quantized_weights", [True]) |
| 16 | + def test_bf16_quantized_weights(self, zero_quantized_weights): |
| 17 | + if not deepspeed.get_accelerator().is_bf16_supported(): |
| 18 | + pytest.skip("bf16 is not supported by this accelerator") |
| 19 | + |
| 20 | + config_dict = { |
| 21 | + "train_micro_batch_size_per_gpu": 1, |
| 22 | + "zero_optimization": { |
| 23 | + "stage": 3, |
| 24 | + "zero_quantized_weights": zero_quantized_weights, |
| 25 | + }, |
| 26 | + "bf16": { |
| 27 | + "enabled": True |
| 28 | + }, |
| 29 | + "optimizer": { |
| 30 | + "type": "Adam", |
| 31 | + "params": { |
| 32 | + "lr": 1e-3 |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + hidden_dim = 128 |
| 38 | + model = SimpleModel(hidden_dim=hidden_dim) |
| 39 | + model, _, _, _ = deepspeed.initialize(model=model, config=config_dict) |
| 40 | + |
| 41 | + # Ensure model is in bf16 |
| 42 | + for param in model.parameters(): |
| 43 | + assert param.dtype == torch.bfloat16 |
| 44 | + |
| 45 | + data_loader = random_dataloader(model=model, |
| 46 | + total_samples=2, |
| 47 | + hidden_dim=hidden_dim, |
| 48 | + device=model.device, |
| 49 | + dtype=torch.bfloat16) |
| 50 | + |
| 51 | + for n, batch in enumerate(data_loader): |
| 52 | + # This triggers all_gather and dequantization |
| 53 | + loss = model(batch[0], batch[1]) |
| 54 | + |
| 55 | + # Verify that param.data is indeed bfloat16 after all_gather |
| 56 | + for name, param in model.named_parameters(): |
| 57 | + assert param.data.dtype == torch.bfloat16, f"Parameter {name} data dtype is {param.data.dtype}, expected torch.bfloat16" |
| 58 | + |
| 59 | + model.backward(loss) |
| 60 | + model.step() |
| 61 | + break |
0 commit comments