File size: 4,548 Bytes
0558aa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# Copyright (c) 2025, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os

import pytest
import torch
from megatron.core.optimizer import OptimizerConfig

from nemo import lightning as nl
from nemo.collections import llm
from nemo.collections.llm.gpt.data import PreTrainingDataModule
from nemo.collections.nlp.modules.common.tokenizer_utils import get_nmt_tokenizer
from nemo.lightning.pytorch.callbacks import DdpParityChecker


def make_parser():
    parser = argparse.ArgumentParser(description='Train a small GPT model using NeMo 2.0')
    parser.add_argument('--data-path', type=str, help="Path to data file")
    parser.add_argument('--vocab-path', type=str, help="Path to vocab file")
    parser.add_argument('--merges-path', type=str, help="Path to merges file")

    return parser


def wrap_config(config, trainer):
    class ConfigWrapper(type(config)):
        def configure_model(self, tokenizer, vp_stage=None) -> "MCoreGPTModel":
            return make_byzantine_model_wrapper(super().configure_model(tokenizer), trainer)

    config.__class__ = ConfigWrapper
    return config


def make_byzantine_model_wrapper(model, trainer):
    class ByzantineModel(type(model)):
        def forward(self, *ans, **kwargs):
            ans = super().forward(*ans, **kwargs)
            with torch.no_grad():
                import random

                rank = int(os.environ['LOCAL_RANK'])
                if rank != 1:
                    return ans
                for opt in trainer.strategy.model.optim._optimizers:
                    for g in opt.param_groups:
                        for param in g['params']:
                            param.fill_(random.uniform(0, 1))
            return ans

    model.__class__ = ByzantineModel
    return model


@pytest.mark.skip(reason="tested with GH")
def test_failing(trainer, ddp_parity, optim, data, tokenizer):
    config = llm.Llama2Config7B(num_layers=2)
    config = wrap_config(config, trainer)
    model = llm.LlamaModel(config, tokenizer=tokenizer, optim=optim)
    trainer.fit(model, data)


@pytest.mark.skip(reason="tested with GH")
def test_working(trainer, ddp_parity, optim, data, tokenizer):
    config = llm.Llama2Config7B(num_layers=2)
    model = llm.LlamaModel(config, tokenizer=tokenizer, optim=optim)
    trainer.fit(model, data)


def make_trainer_optim(args):
    ddp_parity = DdpParityChecker(1)
    trainer = nl.Trainer(
        devices=2,
        max_steps=4,
        accelerator="gpu",
        strategy=nl.MegatronStrategy(
            ckpt_load_optimizer=False,
            ckpt_save_optimizer=False,
        ),
        plugins=nl.MegatronMixedPrecision(precision="bf16-mixed"),
        limit_val_batches=1,
        num_sanity_val_steps=0,
        log_every_n_steps=1,
        logger=None,
        callbacks=[ddp_parity],
    )

    optim = nl.MegatronOptimizerModule(
        config=OptimizerConfig(
            optimizer="adam",
            lr=1e-5,
            use_distributed_optimizer=False,
            fp16=False,
            bf16=True,
            params_dtype=torch.float32,
        ),
    )

    tokenizer = get_nmt_tokenizer(
        "megatron",
        "GPT2BPETokenizer",
        vocab_file=args.vocab_path,
        merges_file=args.merges_path,
    )
    data = PreTrainingDataModule(
        paths=args.data_path,
        seq_length=2048,
        global_batch_size=32,
        seed=1234,
        tokenizer=tokenizer,
    )

    return trainer, ddp_parity, optim, data, tokenizer


@pytest.mark.skip(reason="tested with GH")
def main():
    args = make_parser().parse_args()
    trainer, ddp_parity, optim, data, tokenizer = make_trainer_optim(args)
    test_failing(trainer, ddp_parity, optim, data, tokenizer)
    if trainer.should_stop != True:
        raise ValueError("DDP parity checking failed.")

    try:
        test_working(*make_trainer_optim(args))
        print("DDP parity checking worked as expected")
    except:
        raise


if __name__ == "__main__":
    main()