|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: LicenseRef-Apache2 |
| 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 | +""" |
| 17 | +Test that parameter distributions are identical with and without meta device initialization. |
| 18 | +
|
| 19 | +These tests verify that when using meta device initialization (creating the model on meta device, then calling |
| 20 | +`to_empty` and `_init_weights`), the resulting parameter distributions (mean and std) match those from normal |
| 21 | +initialization. This is important because we previously observed differences in convergence between meta-device-init and |
| 22 | +non-meta-device-init training, which suggested that the initialization was not being applied correctly after `to_empty`. |
| 23 | +By explicitly calling `_init_weights` after `to_empty`, we ensure that parameters are properly initialized, leading to |
| 24 | +consistent training behavior regardless of whether meta device initialization is used. |
| 25 | +""" |
| 26 | + |
| 27 | +import os |
| 28 | +import subprocess |
| 29 | + |
| 30 | +import pytest |
| 31 | +import torch |
| 32 | +from torch.distributed.fsdp import fully_shard |
| 33 | +from torch.distributed.tensor import DTensor |
| 34 | +from transformers import AutoConfig, set_seed |
| 35 | + |
| 36 | +from esm.modeling_esm_te import NVEsmConfig, NVEsmForMaskedLM |
| 37 | + |
| 38 | + |
| 39 | +requires_multi_gpu = pytest.mark.skipif( |
| 40 | + not torch.cuda.is_available() or torch.cuda.device_count() < 2, |
| 41 | + reason="Test requires at least 2 GPUs", |
| 42 | +) |
| 43 | + |
| 44 | + |
| 45 | +def test_meta_device_init(): |
| 46 | + config = NVEsmConfig(**AutoConfig.from_pretrained("facebook/esm2_t6_8M_UR50D").to_dict()) |
| 47 | + |
| 48 | + set_seed(42) |
| 49 | + with torch.device("meta"): |
| 50 | + model_meta_init = NVEsmForMaskedLM(config) |
| 51 | + |
| 52 | + model_meta_init.to_empty(device="cuda") |
| 53 | + model_meta_init.apply(model_meta_init._init_weights) |
| 54 | + |
| 55 | + set_seed(42) |
| 56 | + model_normal_init = NVEsmForMaskedLM(config) |
| 57 | + model_normal_init.to("cuda") |
| 58 | + |
| 59 | + state_dict_meta_init = model_meta_init.state_dict() |
| 60 | + state_dict_normal_init = model_normal_init.state_dict() |
| 61 | + |
| 62 | + for key in state_dict_meta_init.keys(): |
| 63 | + meta_tensor = state_dict_meta_init[key] |
| 64 | + normal_tensor = state_dict_normal_init[key] |
| 65 | + # Skip non-numeric tensors (e.g., Byte/uint8 tensors like _extra_state) |
| 66 | + if meta_tensor.dtype not in ( |
| 67 | + torch.float16, |
| 68 | + torch.float32, |
| 69 | + torch.float64, |
| 70 | + torch.bfloat16, |
| 71 | + torch.complex64, |
| 72 | + torch.complex128, |
| 73 | + ): |
| 74 | + continue |
| 75 | + torch.testing.assert_close( |
| 76 | + normal_tensor.mean(), |
| 77 | + meta_tensor.mean(), |
| 78 | + atol=1e-3, |
| 79 | + rtol=1e-4, |
| 80 | + msg=lambda x: f"Mean mismatch for parameter {key}: {x}", |
| 81 | + ) |
| 82 | + torch.testing.assert_close( |
| 83 | + normal_tensor.std(), |
| 84 | + meta_tensor.std(), |
| 85 | + atol=1e-3, |
| 86 | + rtol=1e-4, |
| 87 | + msg=lambda x: f"Std mismatch for parameter {key}: {x}", |
| 88 | + ) |
| 89 | + |
| 90 | + |
| 91 | +@pytest.mark.parametrize("num_gpus", [1, pytest.param(2, marks=requires_multi_gpu)]) |
| 92 | +def test_meta_device_init_after_fully_shard(num_gpus: int): |
| 93 | + cmd = [ |
| 94 | + "torchrun", |
| 95 | + f"--nproc_per_node={num_gpus}", |
| 96 | + os.path.relpath(__file__), |
| 97 | + ] |
| 98 | + |
| 99 | + result = subprocess.run( |
| 100 | + cmd, |
| 101 | + check=False, |
| 102 | + text=True, |
| 103 | + stdout=subprocess.PIPE, |
| 104 | + stderr=subprocess.PIPE, |
| 105 | + timeout=240, |
| 106 | + ) |
| 107 | + |
| 108 | + if result.returncode != 0: |
| 109 | + print(f"STDOUT:\n{result.stdout}") |
| 110 | + print(f"STDERR:\n{result.stderr}") |
| 111 | + pytest.fail(f"Command failed with exit code {result.returncode}") |
| 112 | + |
| 113 | + |
| 114 | +if __name__ == "__main__": |
| 115 | + torch.distributed.init_process_group(backend="cuda:nccl") |
| 116 | + torch.cuda.set_device(torch.distributed.get_rank()) |
| 117 | + |
| 118 | + config = NVEsmConfig(**AutoConfig.from_pretrained("facebook/esm2_t6_8M_UR50D").to_dict()) |
| 119 | + |
| 120 | + set_seed(42) |
| 121 | + |
| 122 | + with torch.device("meta"): |
| 123 | + model_meta_init = NVEsmForMaskedLM(config) |
| 124 | + |
| 125 | + for layer in model_meta_init.esm.encoder.layers: |
| 126 | + fully_shard(layer) |
| 127 | + fully_shard(model_meta_init) |
| 128 | + |
| 129 | + model_meta_init.to_empty(device="cuda") |
| 130 | + model_meta_init.apply(model_meta_init._init_weights) |
| 131 | + |
| 132 | + set_seed(42) |
| 133 | + model_normal_init = NVEsmForMaskedLM(config) |
| 134 | + |
| 135 | + for layer in model_normal_init.esm.encoder.layers: |
| 136 | + fully_shard(layer) |
| 137 | + fully_shard(model_normal_init) |
| 138 | + |
| 139 | + state_dict_meta_init = model_meta_init.state_dict() |
| 140 | + state_dict_normal_init = model_normal_init.state_dict() |
| 141 | + |
| 142 | + for key in state_dict_meta_init.keys(): |
| 143 | + meta_tensor = state_dict_meta_init[key] |
| 144 | + normal_tensor = state_dict_normal_init[key] |
| 145 | + # Skip non-numeric tensors (e.g., Byte/uint8 tensors like _extra_state) |
| 146 | + if meta_tensor.dtype not in ( |
| 147 | + torch.float16, |
| 148 | + torch.float32, |
| 149 | + torch.float64, |
| 150 | + torch.bfloat16, |
| 151 | + torch.complex64, |
| 152 | + torch.complex128, |
| 153 | + ): |
| 154 | + continue |
| 155 | + |
| 156 | + torch.testing.assert_close( |
| 157 | + normal_tensor.mean(), |
| 158 | + meta_tensor.mean(), |
| 159 | + atol=1e-3, |
| 160 | + rtol=1e-4, |
| 161 | + msg=lambda x: f"Mean mismatch for parameter {key}: {x}", |
| 162 | + ) |
| 163 | + |
| 164 | + if isinstance(normal_tensor, DTensor) and isinstance(meta_tensor, DTensor): |
| 165 | + torch.testing.assert_close( |
| 166 | + normal_tensor.full_tensor().std(), |
| 167 | + meta_tensor.full_tensor().std(), |
| 168 | + atol=1e-3, |
| 169 | + rtol=1e-4, |
| 170 | + msg=lambda x: f"Std mismatch for parameter {key}: {x}", |
| 171 | + ) |
| 172 | + |
| 173 | + else: |
| 174 | + torch.testing.assert_close( |
| 175 | + normal_tensor.std(), |
| 176 | + meta_tensor.std(), |
| 177 | + atol=1e-3, |
| 178 | + rtol=1e-4, |
| 179 | + msg=lambda x: f"Std mismatch for parameter {key}: {x}", |
| 180 | + ) |
0 commit comments