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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import unittest
|
| 3 |
+
from apex.transformer.testing import global_vars
|
| 4 |
+
from apex.transformer.testing.standalone_bert import bert_model_provider
|
| 5 |
+
from apex.transformer.pipeline_parallel.schedules.common import (
|
| 6 |
+
_get_params_for_weight_decay_optimization, build_model
|
| 7 |
+
)
|
| 8 |
+
from apex.transformer.pipeline_parallel.schedules import get_forward_backward_func
|
| 9 |
+
from apex.transformer.pipeline_parallel.utils import (
|
| 10 |
+
average_losses_across_data_parallel_group, unwrap_model, setup_microbatch_calculator
|
| 11 |
+
)
|
| 12 |
+
from apex.transformer.log_util import set_logging_level
|
| 13 |
+
from apex.transformer import tensor_parallel, parallel_state
|
| 14 |
+
from apex.transformer.enums import ModelType
|
| 15 |
+
from apex.transformer._ucc_util import HAS_UCC
|
| 16 |
+
from apex.transformer.testing.distributed_test_base import UccDistributedTestBase, NcclDistributedTestBase
|
| 17 |
+
import logging
|
| 18 |
+
|
| 19 |
+
from torch.testing._internal import common_utils
|
| 20 |
+
|
| 21 |
+
logging.getLogger("torch").setLevel(logging.WARNING)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logging.getLogger("apex").setLevel(logging.WARNING)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
set_logging_level("WARNING")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class BertTestBase:
|
| 31 |
+
|
| 32 |
+
def _download_fancy_data(self):
|
| 33 |
+
text = """
|
| 34 |
+
An original sentence not subject to any license restrictions, copyright, or royalty payments. Nothing to see here. Commercial or non-commercial use. Research or non-research purposes. The quick brown fox jumps over the lazy dog. Lorem ipsum.
|
| 35 |
+
"""
|
| 36 |
+
text = text * 1024
|
| 37 |
+
encoded = text.encode("ascii", "replace")
|
| 38 |
+
ints = [int(encoded[i]) for i in range(len(encoded))]
|
| 39 |
+
return torch.tensor(ints)
|
| 40 |
+
|
| 41 |
+
# build a batch given sequence_len and batch size
|
| 42 |
+
def _generate_fancy_data_labels(self, sequence_len, batch_size):
|
| 43 |
+
temps = []
|
| 44 |
+
for i in range(batch_size):
|
| 45 |
+
if self.inds is None or self.data_idx >= len(self.inds):
|
| 46 |
+
# hack as use of RNG will fall out of sync due to pipelines being different
|
| 47 |
+
torch.manual_seed(self.MANUAL_SEED)
|
| 48 |
+
self.inds = torch.randperm(
|
| 49 |
+
self.effective_length, device="cuda")
|
| 50 |
+
self.masks = (
|
| 51 |
+
torch.rand(
|
| 52 |
+
len(self.inds) // batch_size + 1, batch_size, sequence_len, device="cuda"
|
| 53 |
+
)
|
| 54 |
+
>= self.MASK_PROB
|
| 55 |
+
).long()
|
| 56 |
+
self.MANUAL_SEED += 1
|
| 57 |
+
self.data_idx = 0
|
| 58 |
+
if self.rank == 0:
|
| 59 |
+
print("new epoch", len(self.inds))
|
| 60 |
+
print("my start", self.inds[0:5])
|
| 61 |
+
print("masks_checksum:", torch.sum(self.masks))
|
| 62 |
+
if self.EASY_MODE:
|
| 63 |
+
data_idx_ = self.data_idx % self.EASY_MODE_SIZ
|
| 64 |
+
else:
|
| 65 |
+
data_idx_ = self.data_idx
|
| 66 |
+
offset = self.inds[data_idx_] # * SEQUENCE_LEN
|
| 67 |
+
self.data_idx += 1
|
| 68 |
+
|
| 69 |
+
curr = self.fancy_data[offset: offset +
|
| 70 |
+
sequence_len].clone().detach()
|
| 71 |
+
temps.append(curr)
|
| 72 |
+
temp = torch.stack(temps, dim=0).cuda()
|
| 73 |
+
mask = self.masks[self.data_idx // batch_size]
|
| 74 |
+
mask_not = torch.logical_not(mask).long()
|
| 75 |
+
data = mask * temp + mask_not * 124
|
| 76 |
+
label = temp
|
| 77 |
+
if parallel_state.get_tensor_model_parallel_rank() == 0:
|
| 78 |
+
data_dict = {"text": data, "label": label, "mask_not": mask_not}
|
| 79 |
+
else:
|
| 80 |
+
data_dict = None
|
| 81 |
+
keys = ["text", "label", "mask_not"]
|
| 82 |
+
broadcasted_data = tensor_parallel.broadcast_data(
|
| 83 |
+
keys, data_dict, torch.long)
|
| 84 |
+
return (
|
| 85 |
+
broadcasted_data["text"].long(),
|
| 86 |
+
broadcasted_data["label"].long(),
|
| 87 |
+
broadcasted_data["mask_not"],
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
def _fwd_step_func(self, batch, model):
|
| 91 |
+
data, label, loss_mask = batch
|
| 92 |
+
y = model(data, torch.ones_like(data), lm_labels=label)
|
| 93 |
+
|
| 94 |
+
def loss_func(output_tensor):
|
| 95 |
+
output_tensor, _ = output_tensor
|
| 96 |
+
lm_loss_ = output_tensor.float()
|
| 97 |
+
lm_loss = torch.sum(lm_loss_.view(-1) *
|
| 98 |
+
loss_mask.reshape(-1)) / loss_mask.sum()
|
| 99 |
+
averaged_loss = average_losses_across_data_parallel_group([
|
| 100 |
+
lm_loss])
|
| 101 |
+
if self.data_idx >= 1536:
|
| 102 |
+
# NOTE (patwang): Loss cutoff might be excessively high but roughly one in five
|
| 103 |
+
# unlucky random seeds do cause loss to spike to just under 8.0
|
| 104 |
+
self.assertLess(averaged_loss, 8.0)
|
| 105 |
+
return lm_loss, {"avg": averaged_loss}
|
| 106 |
+
|
| 107 |
+
return y, loss_func
|
| 108 |
+
|
| 109 |
+
def _train(
|
| 110 |
+
self, model, optim, virtual_pipeline_model_parallel_size, pipeline_model_parallel_size, async_comm
|
| 111 |
+
):
|
| 112 |
+
args = global_vars.get_args()
|
| 113 |
+
sequence_len = args.seq_length
|
| 114 |
+
micro_batch_size = args.micro_batch_size
|
| 115 |
+
hidden_size = args.hidden_size
|
| 116 |
+
global_batch_size = args.global_batch_size
|
| 117 |
+
forward_backward_func = get_forward_backward_func(
|
| 118 |
+
virtual_pipeline_model_parallel_size, pipeline_model_parallel_size
|
| 119 |
+
)
|
| 120 |
+
tensor_shape = (sequence_len, micro_batch_size, hidden_size)
|
| 121 |
+
for _ in range(16):
|
| 122 |
+
batch = self._generate_fancy_data_labels(
|
| 123 |
+
sequence_len, global_batch_size)
|
| 124 |
+
optim.zero_grad()
|
| 125 |
+
forward_backward_func(
|
| 126 |
+
self._fwd_step_func,
|
| 127 |
+
batch,
|
| 128 |
+
model,
|
| 129 |
+
forward_only=False,
|
| 130 |
+
tensor_shape=tensor_shape,
|
| 131 |
+
async_comm=async_comm,
|
| 132 |
+
sequence_parallel_enabled=args.sequence_parallel,
|
| 133 |
+
)
|
| 134 |
+
# All-reduce layernorm parameters across model parallel nodes
|
| 135 |
+
# when sequence parallelism is used
|
| 136 |
+
if parallel_state.get_tensor_model_parallel_world_size() > 1 and args.sequence_parallel:
|
| 137 |
+
for model_module in model:
|
| 138 |
+
unwrapped_model = unwrap_model(model_module)
|
| 139 |
+
for param in unwrapped_model.parameters():
|
| 140 |
+
if getattr(param, 'sequence_parallel_enabled', False):
|
| 141 |
+
grad = param.grad
|
| 142 |
+
torch.distributed.all_reduce(
|
| 143 |
+
grad, group=parallel_state.get_tensor_model_parallel_group())
|
| 144 |
+
|
| 145 |
+
optim.step()
|
| 146 |
+
|
| 147 |
+
@unittest.skipUnless(torch.cuda.device_count() > 2, "requires at least 3 gpus")
|
| 148 |
+
def test_bert_without_interleaving(self):
|
| 149 |
+
self._test_bert(virtual_pipeline_model_parallel_size=None)
|
| 150 |
+
|
| 151 |
+
@unittest.skipUnless(torch.cuda.device_count() > 2, "requires at least 3 gpus")
|
| 152 |
+
def test_bert_with_interleaving(self):
|
| 153 |
+
if self.DISTRIBUTED_BACKEND == 'ucc':
|
| 154 |
+
self.skipTest('skip interleaving with ucc')
|
| 155 |
+
self._test_bert(virtual_pipeline_model_parallel_size=2)
|
| 156 |
+
|
| 157 |
+
def _test_bert(self, virtual_pipeline_model_parallel_size):
|
| 158 |
+
|
| 159 |
+
self.MANUAL_SEED = 42
|
| 160 |
+
self.inds = None
|
| 161 |
+
self.masks = None
|
| 162 |
+
self.data_idx = 0
|
| 163 |
+
self.MASK_PROB = 0.1
|
| 164 |
+
self.EASY_MODE = False
|
| 165 |
+
self.EASY_MODE_SIZ = 32
|
| 166 |
+
|
| 167 |
+
tensor_model_parallel_size = 2 if self.world_size % 2 == 0 and self.world_size > 4 else 1
|
| 168 |
+
pipeline_model_parallel_size = self.world_size // tensor_model_parallel_size
|
| 169 |
+
|
| 170 |
+
override_args = {
|
| 171 |
+
"micro_batch_size": 2,
|
| 172 |
+
"num_layers": 16,
|
| 173 |
+
"hidden_size": 256,
|
| 174 |
+
"num_attention_heads": 8,
|
| 175 |
+
"max_position_embeddings": 512,
|
| 176 |
+
"seq_length": 512,
|
| 177 |
+
"global_batch_size": 128,
|
| 178 |
+
"pipeline_model_parallel_size": pipeline_model_parallel_size,
|
| 179 |
+
"tensor_model_parallel_size": tensor_model_parallel_size,
|
| 180 |
+
"bert_binary_head": False,
|
| 181 |
+
"world_size": self.world_size,
|
| 182 |
+
"rank": self.rank,
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
global_vars.set_global_variables(override_args=override_args, ignore_unknown_args=True)
|
| 186 |
+
args = global_vars.get_args()
|
| 187 |
+
|
| 188 |
+
self.fancy_data = self._download_fancy_data()
|
| 189 |
+
self.effective_length = self.fancy_data.size(0) // args.seq_length
|
| 190 |
+
self.effective_length = self.fancy_data.size(0) - args.seq_length
|
| 191 |
+
|
| 192 |
+
if self.rank == 0:
|
| 193 |
+
print(
|
| 194 |
+
f'testing backend: {self.DISTRIBUTED_BACKEND} with virtual_pipeline_model_parallel_size: {virtual_pipeline_model_parallel_size}')
|
| 195 |
+
async_comm = not args.sequence_parallel and virtual_pipeline_model_parallel_size is None
|
| 196 |
+
self.data_idx = 0
|
| 197 |
+
args.padded_vocab_size = 128 # needed in standalone gpt
|
| 198 |
+
args.model_type = ModelType.encoder_or_decoder
|
| 199 |
+
setup_microbatch_calculator(
|
| 200 |
+
args.rank,
|
| 201 |
+
args.rampup_batch_size,
|
| 202 |
+
args.global_batch_size,
|
| 203 |
+
args.micro_batch_size,
|
| 204 |
+
args.data_parallel_size,
|
| 205 |
+
)
|
| 206 |
+
parallel_state.initialize_model_parallel(
|
| 207 |
+
args.tensor_model_parallel_size,
|
| 208 |
+
args.pipeline_model_parallel_size,
|
| 209 |
+
virtual_pipeline_model_parallel_size,
|
| 210 |
+
default_backend="nccl",
|
| 211 |
+
p2p_backend=self.DISTRIBUTED_BACKEND,
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
tensor_parallel.random.model_parallel_cuda_manual_seed(0)
|
| 215 |
+
model = build_model(
|
| 216 |
+
bert_model_provider,
|
| 217 |
+
wrap_with_ddp=parallel_state.get_data_parallel_world_size() > 1,
|
| 218 |
+
virtual_pipeline_model_parallel_size=virtual_pipeline_model_parallel_size,
|
| 219 |
+
cpu_offload=args.cpu_offload,
|
| 220 |
+
)
|
| 221 |
+
assert isinstance(model, list)
|
| 222 |
+
assert len(model) == (
|
| 223 |
+
1
|
| 224 |
+
if virtual_pipeline_model_parallel_size is None
|
| 225 |
+
else virtual_pipeline_model_parallel_size
|
| 226 |
+
)
|
| 227 |
+
_param_groups = _get_params_for_weight_decay_optimization(model)
|
| 228 |
+
optim = torch.optim.Adam(_param_groups)
|
| 229 |
+
self._train(
|
| 230 |
+
model,
|
| 231 |
+
optim,
|
| 232 |
+
virtual_pipeline_model_parallel_size,
|
| 233 |
+
args.pipeline_model_parallel_size,
|
| 234 |
+
async_comm,
|
| 235 |
+
)
|
| 236 |
+
torch.cuda.synchronize()
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class NcclBertTest(BertTestBase, NcclDistributedTestBase):
|
| 240 |
+
@property
|
| 241 |
+
def world_size(self) -> int:
|
| 242 |
+
return min(torch.cuda.device_count(), 8)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@unittest.skipUnless(HAS_UCC, "requires pytorch to be built with native ucc")
|
| 246 |
+
class UccBertTest(BertTestBase, UccDistributedTestBase):
|
| 247 |
+
@property
|
| 248 |
+
def world_size(self) -> int:
|
| 249 |
+
return min(torch.cuda.device_count(), 8)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
if __name__ == "__main__":
|
| 253 |
+
common_utils.run_tests()
|