Skip to content

Commit 2e11a92

Browse files
committed
feat: Pipeline parallelism divides the model into chunks during construction
1 parent 962509c commit 2e11a92

File tree

15 files changed

+696
-628
lines changed

15 files changed

+696
-628
lines changed

example/gpt2/main.cc

Lines changed: 58 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,6 @@ DEFINE_bool(sequence_parallel, false, "Whether to enable Sequence Parallel");
6767
DEFINE_uint32(
6868
pipeline_parallel, 1,
6969
"Pipeline Parallel world size, will always use device=cuda and use all cuda visible devices when set to true");
70-
DEFINE_uint32(num_microbatches, 4, "the num of microbatches in pipeline parallelism");
7170

7271
// precision
7372
DEFINE_string(dtype, "float32", "precision used in training (float32/bfloat16)");
@@ -148,14 +147,16 @@ void Train(const nn::parallel::Rank &rank) {
148147
pp_pg = ProcessGroupFactory::Instance()->GetOrCreate(
149148
GetPipelineParallelProcessGroupName(rank.thread_rank()), GetPipelineParallelGroupRanks(pp_world_size));
150149
pp_rank = pp_pg->GetGroupRank(rank.thread_rank());
150+
151+
nn::parallel::pp_rank = pp_rank;
151152
}
152153
} else {
153154
device = FLAGS_device == kDeviceCPU ? DeviceManager::Instance()->GetDefaultDevice()
154155
: DeviceManager::Instance()->GetDevice(DeviceType::kCUDA, 0);
155156
}
156157

157158
// calculate gradient accumulation from the desired total batch size and the current run configuration
158-
const auto tokens_per_fwdbwd = FLAGS_batch_size * FLAGS_sequence_length * (ddp_world_size * pp_world_size);
159+
const auto tokens_per_fwdbwd = FLAGS_batch_size * FLAGS_sequence_length * ddp_world_size;
159160
CHECK_EQ(FLAGS_total_batch_size % tokens_per_fwdbwd, 0);
160161
const auto grad_accum_steps = FLAGS_total_batch_size / tokens_per_fwdbwd;
161162
LOG(INFO) << "total desired batch size: " << FLAGS_total_batch_size
@@ -197,16 +198,9 @@ void Train(const nn::parallel::Rank &rank) {
197198
model = std::make_shared<DistributedDataParallel>(model, rank.thread_rank());
198199
}
199200

200-
std::unique_ptr<DataLoader> train_loader;
201-
if (pp_world_size > 1) {
202-
train_loader = std::make_unique<DataLoader>(
203-
std::make_shared<TinyShakespeareDataset>(FLAGS_input_bin, FLAGS_sequence_length),
204-
FLAGS_batch_size * pp_world_size);
205-
} else {
206-
train_loader = std::make_unique<DistributedDataLoader>(
207-
std::make_shared<TinyShakespeareDataset>(FLAGS_input_bin, FLAGS_sequence_length), FLAGS_batch_size,
208-
ddp_rank, ddp_world_size);
209-
}
201+
auto num_microbatches = FLAGS_total_batch_size / (FLAGS_batch_size * FLAGS_sequence_length * ddp_world_size);
202+
DistributedDataLoader train_loader(std::make_shared<TinyShakespeareDataset>(FLAGS_input_bin, FLAGS_sequence_length),
203+
FLAGS_batch_size * num_microbatches, ddp_rank, ddp_world_size);
210204

211205
std::optional<DistributedDataLoader> val_loader = std::nullopt;
212206
if (!FLAGS_input_val_bin.empty()) {
@@ -231,7 +225,7 @@ void Train(const nn::parallel::Rank &rank) {
231225
};
232226
auto optimizer = optimizer_factory(model->Parameters());
233227

234-
auto train_iter = train_loader->begin();
228+
auto train_iter = train_loader.begin();
235229
std::shared_ptr<nn::Module> loss_fn
236230
= (tp_world_size > 1) ? std::static_pointer_cast<nn::Module>(
237231
std::make_shared<VocabParallelCrossEntropyLoss>(model_config.original_vocab_size))
@@ -240,13 +234,9 @@ void Train(const nn::parallel::Rank &rank) {
240234
LOG(INFO) << "Rank " << rank.thread_rank() << ": start training";
241235

242236
if (pp_world_size > 1) {
243-
CHECK_EQ((FLAGS_batch_size * pp_world_size) % FLAGS_num_microbatches, 0)
244-
<< "FLAGS_batch_size (" << (FLAGS_batch_size * pp_world_size)
245-
<< ") must be divisible by FLAGS_num_microbatches (" << FLAGS_num_microbatches << ")";
246-
auto shapes = std::vector<std::vector<int64_t>>{{(FLAGS_batch_size * pp_world_size) / FLAGS_num_microbatches,
247-
FLAGS_sequence_length, model->GetConfig()["n_embd"]}};
237+
auto shapes = std::vector<std::vector<int64_t>>{{FLAGS_batch_size, FLAGS_sequence_length, model_config.n_embd}};
248238

249-
model = std::make_shared<nn::parallel::PipelineParallel>(model, pp_world_size, FLAGS_num_microbatches, shapes,
239+
model = std::make_shared<nn::parallel::PipelineParallel>(model, pp_world_size, num_microbatches, shapes,
250240
pp_rank, optimizer_factory);
251241
}
252242

@@ -274,65 +264,68 @@ void Train(const nn::parallel::Rank &rank) {
274264
break;
275265
}
276266

267+
float lossf = 0.0f;
277268
// model->Train();
278269
if (pp_world_size == 1) {
279270
optimizer->ZeroGrad();
280-
}
281-
// if we are trying to overfit a single batch, we reset the loader here
282-
if (FLAGS_overfit_single_batch) {
283-
// train_loader.Reset();
284-
}
285-
float lossf = 0.0f;
271+
272+
// if we are trying to overfit a single batch, we reset the loader here
273+
if (FLAGS_overfit_single_batch) {
274+
// train_loader.Reset();
275+
}
276+
286277
#ifdef PROFILE_MODE
287-
Profiler::Instance().SetTag("Step_" + std::to_string(step));
278+
Profiler::Instance().SetTag("Step_" + std::to_string(step));
288279
#endif
289-
for (int micro_step = 0; micro_step < grad_accum_steps; ++micro_step) {
290-
// enable autocast for the current step
291-
infini_train::AutocastGuard autocast_guard(device->Type(), dtype);
280+
for (int micro_step = 0; micro_step < grad_accum_steps; ++micro_step) {
281+
// enable autocast for the current step
282+
infini_train::AutocastGuard autocast_guard(device->Type(), dtype);
283+
284+
// (bs, seq_len), (bs, seq_len)
285+
auto [x, y] = *train_iter;
286+
// if we are trying to overfit a single batch, we reset the loader here by commenting out the line below
287+
// TODO(dcj): support dataloader.reset() later
288+
++train_iter;
289+
x = std::make_shared<Tensor>(x->To(device));
290+
y = std::make_shared<Tensor>(y->To(device));
291+
292+
LOG(INFO) << "Rank " << rank.thread_rank() << ": start forward";
293+
// (bs, seq_len, vocab_size)
294+
auto logits = model->Forward({x, y})[0];
295+
LOG(INFO) << "Rank " << rank.thread_rank() << ": finish model forward, start loss forward";
296+
auto loss = loss_fn->Forward({logits, y})[0];
297+
loss = loss / grad_accum_steps;
298+
299+
// disable autocast for the current step (backward is not under autocast)
300+
autocast_guard.Disable();
301+
302+
LOG(INFO) << "Rank " << rank.thread_rank() << ": finish loss forward";
303+
if (ddp_world_size > 1) {
304+
function::AllReduce(loss, function::ReduceOpType::kAvg);
305+
}
306+
auto loss_cpu = loss->To(DeviceManager::Instance()->GetDefaultDevice());
307+
lossf += static_cast<const float *>(loss_cpu.DataPtr())[0];
308+
LOG(INFO) << "Rank " << rank.thread_rank() << ": start backward";
309+
loss->Backward();
310+
LOG(INFO) << "Rank " << rank.thread_rank() << ": finish backward";
311+
}
292312

293-
// (bs, seq_len), (bs, seq_len)
313+
optimizer->Step();
314+
} else {
294315
auto [x, y] = *train_iter;
295316
// if we are trying to overfit a single batch, we reset the loader here by commenting out the line below
296317
// TODO(dcj): support dataloader.reset() later
297318
++train_iter;
298319
x = std::make_shared<Tensor>(x->To(device));
299320
y = std::make_shared<Tensor>(y->To(device));
300321

301-
if (pp_world_size > 1) {
302-
lossf = model->TrainStep({x}, {y}, loss_fn);
303-
304-
auto loss_tensor = std::make_shared<Tensor>(std::vector<int64_t>{}, DataType::kFLOAT32);
305-
static_cast<float *>(loss_tensor->DataPtr())[0] = lossf;
306-
auto loss_device_ptr = std::make_shared<Tensor>(loss_tensor->To(device));
307-
function::AllReduce(loss_device_ptr, function::ReduceOpType::kMax);
308-
auto loss_copy = loss_device_ptr->To(DeviceManager::Instance()->GetDefaultDevice());
309-
lossf = static_cast<const float *>(loss_copy.DataPtr())[0];
310-
continue;
311-
}
312-
313-
LOG(INFO) << "Rank " << rank.thread_rank() << ": start forward";
314-
// (bs, seq_len, vocab_size)
315-
auto logits = model->Forward({x, y})[0];
316-
LOG(INFO) << "Rank " << rank.thread_rank() << ": finish model forward, start loss forward";
317-
auto loss = loss_fn->Forward({logits, y})[0];
318-
loss = loss / grad_accum_steps;
319-
320-
// disable autocast for the current step (backward is not under autocast)
321-
autocast_guard.Disable();
322-
323-
LOG(INFO) << "Rank " << rank.thread_rank() << ": finish loss forward";
324-
if (ddp_world_size > 1) {
325-
function::AllReduce(loss, function::ReduceOpType::kAvg);
326-
}
327-
auto loss_cpu = loss->To(DeviceManager::Instance()->GetDefaultDevice());
328-
lossf += static_cast<const float *>(loss_cpu.DataPtr())[0];
329-
LOG(INFO) << "Rank " << rank.thread_rank() << ": start backward";
330-
loss->Backward();
331-
LOG(INFO) << "Rank " << rank.thread_rank() << ": finish backward";
332-
}
333-
334-
if (pp_world_size == 1) {
335-
optimizer->Step();
322+
lossf = model->TrainStep({x}, {y}, loss_fn);
323+
auto loss_tensor = std::make_shared<Tensor>(std::vector<int64_t>{}, DataType::kFLOAT32);
324+
static_cast<float *>(loss_tensor->DataPtr())[0] = lossf;
325+
auto loss_device_ptr = std::make_shared<Tensor>(loss_tensor->To(device));
326+
function::AllReduce(loss_device_ptr, function::ReduceOpType::kMax);
327+
auto loss_copy = loss_device_ptr->To(DeviceManager::Instance()->GetDefaultDevice());
328+
lossf = static_cast<const float *>(loss_copy.DataPtr())[0];
336329
}
337330
const auto iter_end = std::chrono::high_resolution_clock::now();
338331
const double duration_us = std::chrono::duration<double, std::micro>(iter_end - iter_start).count();

0 commit comments

Comments
 (0)