|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# // SPDX-License-Identifier: BSD |
| 3 | + |
| 4 | +# inspired by https://github.com/pytorch/pytorch/blob/main/torch/distributed/checkpoint/examples/stateful_example.py |
| 5 | + |
| 6 | +import os |
| 7 | + |
| 8 | +import torch |
| 9 | +import torch.distributed as dist |
| 10 | +import torch.distributed.checkpoint as dcp |
| 11 | +import torch.multiprocessing as mp |
| 12 | +import torch.nn as nn |
| 13 | +from torch.distributed.checkpoint.state_dict import ( |
| 14 | + _patch_model_state_dict, |
| 15 | + _patch_optimizer_state_dict, |
| 16 | +) |
| 17 | +from torch.distributed.device_mesh import init_device_mesh |
| 18 | +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP |
| 19 | + |
| 20 | +from s3torchconnector.dcp import S3StorageWriter, S3StorageReader |
| 21 | + |
| 22 | + |
| 23 | +class Model(torch.nn.Module): |
| 24 | + def __init__(self) -> None: |
| 25 | + super().__init__() |
| 26 | + torch.manual_seed(0) |
| 27 | + self.net1 = nn.Sequential(nn.Linear(8, 16), nn.ReLU()) |
| 28 | + self.net2 = nn.Sequential(nn.Linear(16, 32), nn.ReLU()) |
| 29 | + self.net3 = nn.Linear(32, 64) |
| 30 | + self.net4 = nn.Sequential(nn.ReLU(), nn.Linear(64, 8)) |
| 31 | + |
| 32 | + def forward(self, x): |
| 33 | + return self.net4(self.net3(self.net2(self.net1(x)))) |
| 34 | + |
| 35 | + def get_input(self): |
| 36 | + return torch.rand(8, 8, device="cuda") |
| 37 | + |
| 38 | + |
| 39 | +def _make_stateful(model, optim): |
| 40 | + _patch_model_state_dict(model) |
| 41 | + _patch_optimizer_state_dict(model, optimizers=optim) |
| 42 | + |
| 43 | + |
| 44 | +def _train(model, optim, train_steps=1): |
| 45 | + torch.manual_seed(0) |
| 46 | + loss = None |
| 47 | + for _ in range(train_steps): |
| 48 | + loss = model(model.get_input()).sum() |
| 49 | + loss.backward() |
| 50 | + optim.step() |
| 51 | + optim.zero_grad() |
| 52 | + |
| 53 | + return loss |
| 54 | + |
| 55 | + |
| 56 | +def _init_model(device, world_size): |
| 57 | + device_mesh = init_device_mesh(device, (world_size,)) |
| 58 | + model = Model().cuda() |
| 59 | + model = FSDP( |
| 60 | + model, |
| 61 | + device_mesh=device_mesh, |
| 62 | + use_orig_params=True, |
| 63 | + ) |
| 64 | + optim = torch.optim.Adam(model.parameters(), lr=0.1) |
| 65 | + _make_stateful(model, optim) |
| 66 | + |
| 67 | + return model, optim |
| 68 | + |
| 69 | + |
| 70 | +def _compare_models(model1, model2, rank, rtol=1e-5, atol=1e-8): |
| 71 | + model1.eval() |
| 72 | + model2.eval() |
| 73 | + |
| 74 | + with FSDP.summon_full_params(model1), FSDP.summon_full_params(model2): |
| 75 | + for (name1, param1), (name2, param2) in zip( |
| 76 | + model1.named_parameters(), model2.named_parameters() |
| 77 | + ): |
| 78 | + if name1 != name2: |
| 79 | + print(f"Parameter names don't match: {name1} vs {name2}. Rank:{rank}") |
| 80 | + return False |
| 81 | + |
| 82 | + if not torch.allclose(param1, param2, rtol=rtol, atol=atol): |
| 83 | + print(f"Parameters don't match for {name1}. Rank:{rank}") |
| 84 | + print( |
| 85 | + f"Max difference: {(param1 - param2).abs().max().item()}. Rank:{rank}" |
| 86 | + ) |
| 87 | + return False |
| 88 | + |
| 89 | + print(f"All parameters match within the specified tolerance. Rank:{rank}") |
| 90 | + return True |
| 91 | + |
| 92 | + |
| 93 | +def _setup(rank, world_size): |
| 94 | + # Set up world process group |
| 95 | + os.environ["MASTER_ADDR"] = "localhost" |
| 96 | + os.environ["MASTER_PORT"] = "12355" |
| 97 | + dist.init_process_group("cpu:gloo,cuda:nccl", rank=rank, world_size=world_size) |
| 98 | + torch.cuda.set_device(rank) |
| 99 | + |
| 100 | + |
| 101 | +def _train_initial_model(device, rank, world_size): |
| 102 | + print(f"Train initial model on rank:{rank}") |
| 103 | + model, optim = _init_model(device, world_size) |
| 104 | + _train(model, optim, train_steps=2) |
| 105 | + return model, optim |
| 106 | + |
| 107 | + |
| 108 | +def _train_model_to_different_state(device, model, rank, world_size): |
| 109 | + print(f"Train another model on rank:{rank}") |
| 110 | + loaded_model, loaded_optim = _init_model(device, world_size) |
| 111 | + _train(loaded_model, loaded_optim, train_steps=4) |
| 112 | + print(f"Check that models are different on rank:{rank}") |
| 113 | + assert not _compare_models(model, loaded_model, rank) |
| 114 | + return loaded_model, loaded_optim |
| 115 | + |
| 116 | + |
| 117 | +def _continue_training_loaded_model(loaded_model, loaded_optim, model, rank): |
| 118 | + print(f"Check that loaded model and original model are the same on rank:{rank}") |
| 119 | + assert _compare_models(model, loaded_model, rank) |
| 120 | + print(f"Train loaded model on rank:{rank}") |
| 121 | + _train(loaded_model, loaded_optim, train_steps=2) |
| 122 | + |
| 123 | + |
| 124 | +def run(rank, world_size, region, s3_uri, device="cuda"): |
| 125 | + _setup(rank, world_size) |
| 126 | + model, optim = _train_initial_model(device, rank, world_size) |
| 127 | + |
| 128 | + print(f"Saving checkpoint on rank:{rank}") |
| 129 | + # initialize S3StorageWriter with region and bucket name, before passing to dcp.save as writer |
| 130 | + storage_writer = S3StorageWriter(region, s3_uri) |
| 131 | + dcp.save( |
| 132 | + state_dict={"model": model, "optimizer": optim}, |
| 133 | + storage_writer=storage_writer, |
| 134 | + ) |
| 135 | + |
| 136 | + # presumably do something else and decided to return to previous version of model |
| 137 | + modified_model, modified_optim = _train_model_to_different_state( |
| 138 | + device, model, rank, world_size |
| 139 | + ) |
| 140 | + print(f"Load previously saved checkpoint on rank:{rank}") |
| 141 | + # initialize S3StorageReader with region and bucket name, before passing to dcp.load as reader |
| 142 | + storage_reader = S3StorageReader(region, s3_uri) |
| 143 | + dcp.load( |
| 144 | + state_dict={"model": modified_model, "optimizer": modified_optim}, |
| 145 | + storage_reader=storage_reader, |
| 146 | + ) |
| 147 | + _continue_training_loaded_model(modified_model, modified_optim, model, rank) |
| 148 | + print(f"Quiting on rank:{rank}") |
| 149 | + |
| 150 | + |
| 151 | +if __name__ == "__main__": |
| 152 | + world_size = torch.cuda.device_count() |
| 153 | + region = os.getenv("REGION") |
| 154 | + s3_uri = os.getenv("CHECKPOINT_PATH") |
| 155 | + print(f"Running stateful checkpoint example on {world_size} devices.") |
| 156 | + mp.spawn( |
| 157 | + run, |
| 158 | + args=(world_size, region, s3_uri), |
| 159 | + nprocs=world_size, |
| 160 | + join=True, |
| 161 | + ) |
0 commit comments