|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""GPU/distributed tests for ``modelopt.torch.utils.distributed``.""" |
| 17 | + |
| 18 | +from functools import partial |
| 19 | + |
| 20 | +import pytest |
| 21 | +import torch |
| 22 | +import torch.nn as nn |
| 23 | +import torch.nn.functional as F |
| 24 | +from _test_utils.torch.transformers_models import get_tiny_llama |
| 25 | +from torch.distributed.checkpoint.state_dict import StateDictOptions, set_model_state_dict |
| 26 | +from torch.distributed.tensor import DTensor |
| 27 | + |
| 28 | +from modelopt.torch.utils.distributed import fsdp2_wrap |
| 29 | + |
| 30 | +VOCAB_SIZE = 32 |
| 31 | +N_EXPERTS = 4 |
| 32 | + |
| 33 | + |
| 34 | +class _Fp32Router(nn.Module): |
| 35 | + """An MoE router gate pinned to fp32, as Nemotron-3-Nano's modeling code declares it.""" |
| 36 | + |
| 37 | + def __init__(self, hidden_size: int): |
| 38 | + super().__init__() |
| 39 | + self.weight = nn.Parameter(torch.empty(N_EXPERTS, hidden_size, dtype=torch.float32)) |
| 40 | + nn.init.normal_(self.weight, std=0.02) |
| 41 | + |
| 42 | + def forward(self, hidden_states): |
| 43 | + return F.linear(hidden_states.float(), self.weight.float()) |
| 44 | + |
| 45 | + |
| 46 | +class _RoutedMLP(nn.Module): |
| 47 | + """Fronts a bf16 MLP with the fp32 router, so one decoder layer holds both dtypes.""" |
| 48 | + |
| 49 | + def __init__(self, mlp: nn.Module, hidden_size: int): |
| 50 | + super().__init__() |
| 51 | + self.mlp = mlp |
| 52 | + self.gate = _Fp32Router(hidden_size) |
| 53 | + |
| 54 | + def forward(self, hidden_states): |
| 55 | + scale = self.gate(hidden_states).softmax(-1)[..., :1].to(hidden_states.dtype) |
| 56 | + return self.mlp(hidden_states) * scale |
| 57 | + |
| 58 | + |
| 59 | +def _mixed_dtype_model(device): |
| 60 | + model = get_tiny_llama(vocab_size=VOCAB_SIZE).to(device) |
| 61 | + for layer in model.model.layers: |
| 62 | + layer.mlp = _RoutedMLP(layer.mlp, model.config.hidden_size).to(device) |
| 63 | + return model.eval() |
| 64 | + |
| 65 | + |
| 66 | +def _test_fsdp2_wrap_mixed_dtypes(rank, size): |
| 67 | + """A model with a few fp32 params must still wrap, forward, and load state dicts.""" |
| 68 | + device = torch.device(f"cuda:{rank}") |
| 69 | + model = _mixed_dtype_model(device) |
| 70 | + assert {p.dtype for p in model.model.layers[0].parameters()} == { |
| 71 | + torch.bfloat16, |
| 72 | + torch.float32, |
| 73 | + } |
| 74 | + |
| 75 | + fsdp2_wrap(model) |
| 76 | + |
| 77 | + # Raised "FSDP expects uniform original parameter dtype" before the ignored-param fix. |
| 78 | + input_ids = torch.randint(0, VOCAB_SIZE, (1, 8), device=device) |
| 79 | + with torch.no_grad(): |
| 80 | + assert model(input_ids=input_ids).logits.shape == (1, 8, VOCAB_SIZE) |
| 81 | + |
| 82 | + # bf16 weights are sharded; the fp32 router is left replicated in its original dtype. |
| 83 | + gate_weight = model.model.layers[0].mlp.gate.weight |
| 84 | + sharded_weight = model.model.layers[0].mlp.mlp.up_proj.weight |
| 85 | + assert isinstance(sharded_weight, DTensor) |
| 86 | + assert not isinstance(gate_weight, DTensor) |
| 87 | + assert gate_weight.dtype == torch.float32 |
| 88 | + # Left out of the wrap, it still has to sit on the compute device alongside the shards. |
| 89 | + assert gate_weight.device == sharded_weight.to_local().device |
| 90 | + |
| 91 | + # The FSDP2 loader pushes full tensors into each decoder layer; that must still reach the |
| 92 | + # replicated fp32 param as well as the sharded bf16 ones. |
| 93 | + layer = model.model.layers[0] |
| 94 | + hidden_size = model.config.hidden_size |
| 95 | + set_model_state_dict( |
| 96 | + layer, |
| 97 | + {"mlp.gate.weight": torch.full((N_EXPERTS, hidden_size), 3.0, device=device)}, |
| 98 | + options=StateDictOptions(full_state_dict=True, broadcast_from_rank0=False, strict=False), |
| 99 | + ) |
| 100 | + assert torch.equal( |
| 101 | + layer.mlp.gate.weight, torch.full((N_EXPERTS, hidden_size), 3.0, device=device) |
| 102 | + ) |
| 103 | + |
| 104 | + |
| 105 | +def test_fsdp2_wrap_mixed_dtypes(dist_workers): |
| 106 | + dist_workers.run(_test_fsdp2_wrap_mixed_dtypes) |
| 107 | + |
| 108 | + |
| 109 | +def _test_fsdp2_wrap_moves_ignored_params_to_device(rank, size, cpu_offload): |
| 110 | + """A CPU-resident model must end up computing on GPU: fully_shard skips the params it ignores.""" |
| 111 | + model = _mixed_dtype_model(torch.device("cpu")) |
| 112 | + assert model.model.layers[0].mlp.gate.weight.device.type == "cpu" |
| 113 | + |
| 114 | + fsdp2_wrap(model, cpu_offload=cpu_offload) |
| 115 | + |
| 116 | + # Under cpu_offload the shard rests on CPU, but compute — and so the ignored params — is |
| 117 | + # still on GPU, which is why the device is taken from the mesh and not from the local shard. |
| 118 | + sharded_weight = model.model.layers[0].mlp.mlp.up_proj.weight |
| 119 | + assert sharded_weight.to_local().device.type == ("cpu" if cpu_offload else "cuda") |
| 120 | + assert model.model.layers[0].mlp.gate.weight.device.type == "cuda" |
| 121 | + |
| 122 | + input_ids = torch.randint(0, VOCAB_SIZE, (1, 8), device=torch.device(f"cuda:{rank}")) |
| 123 | + with torch.no_grad(): |
| 124 | + assert model(input_ids=input_ids).logits.shape == (1, 8, VOCAB_SIZE) |
| 125 | + |
| 126 | + |
| 127 | +@pytest.mark.parametrize("cpu_offload", [False, True]) |
| 128 | +def test_fsdp2_wrap_moves_ignored_params_to_device(dist_workers, cpu_offload): |
| 129 | + dist_workers.run( |
| 130 | + partial(_test_fsdp2_wrap_moves_ignored_params_to_device, cpu_offload=cpu_offload) |
| 131 | + ) |
0 commit comments