Finetune GPT-NeoX with Zero3 memory optimizer

This script trains the bias parameters of the GPT-NeoX model on multiple devices with Zero-DP Memory Optimization.

14import datetime
15
16import torch
17import torch.distributed
18
19from labml import experiment, monit, tracker
20from labml.configs import option
21from labml.logger import inspect
22from labml_nn.neox.samples.finetune import PipelineParallelTrainerConf

Use the Pipeline Parallel Trainer configurations and adapt it for Zero3 memory optimizer.

27class Configs(PipelineParallelTrainerConf):
28    rank: int
29    world_size: int

Set the optimizers for the model

Note that we pass the sharded parameters from get_trainable_chunk .

32@option(Configs.optimizer, 'Zero3Adam')
33def _optimizer(c: Configs):
39    from labml_nn.optimizers.adam_fp16 import AdamFP16
40    return AdamFP16(c.model.get_trainable_chunk(), lr=c.learning_rate)

Create the model with Zero3 memory optimizer

43@option(Configs.model, 'Zero3')
44def _model(c: Configs):
48    from labml_nn.scaling.zero3 import Zero3Layer, Zero3Sequential

To make sure the fine tuner sets the trainable parameters

51    _ = c.fine_tuner

Wrap the layers with Zero3Layer

54    modules = []
55    for m in monit.iterate('Zero3', c.layers):
56        modules.append(Zero3Layer(m.to(c.device),
57                                  c.rank, c.world_size, c.device, c.dtype))

Create a sequential model

60    model = Zero3Sequential(modules)

63    return model

Run the training on the node with rank rank .

66def main(rank: int, world_size: int, init_method: str = 'tcp://localhost:23456'):

Initialize PyTorch distributed process group

71    with monit.section('Distributed'):
72        torch.distributed.init_process_group('nccl',
73                                             timeout=datetime.timedelta(seconds=30),
74                                             init_method=init_method,
75                                             rank=rank,
76                                             world_size=world_size)

Set current device

79    device = torch.device(f'cuda:{rank}')
80    torch.cuda.set_device(device)

Create the experiment

83    experiment.create(name='zero3_neox', writers={'screen', 'labml'},
84                      distributed_world_size=world_size,
85                      distributed_rank=rank)

Create configurations

88    conf = Configs()

Load configurations

91    experiment.configs(conf, {
92        'model': 'Zero3',
93        'optimizer': 'Zero3Adam',
94
95        'device': device,
96        'rank': rank,
97        'world_size': world_size,
98
99        'learning_rate': 3e-4,
100        'max_seq_len': 128,
101        'batch_size': 16,
102    })

Start the experiment

105    with experiment.start():

Initialize the model. Do this before the loop for cleaner logs.

107        _ = conf.model

Train the model

110        for epoch in monit.loop(conf.epochs):
111            conf.train_epoch()
112            tracker.new_line()

116if __name__ == '__main__':

Log the machine configurations

118    inspect([torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())])
119    inspect(
120        n_gpus=torch.cuda.device_count(),
121        mpi=torch.distributed.is_mpi_available(),
122        nccl=torch.distributed.is_nccl_available(),
123    )
124
125    n_gpu = torch.cuda.device_count()

Start a process for each GPU. You will need a separate launcher if you are using multiple computers.

128    torch.multiprocessing.spawn(main, args=(n_gpu,), nprocs=n_gpu, join=True)