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    experiment.distributed(rank, world_size)

Create configurations

87    conf = Configs()

Load configurations

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

Start the experiment

104    with experiment.start():

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

106        _ = conf.model

Train the model

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

115if __name__ == '__main__':

Log the machine configurations

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

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

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