Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add DataParallel and make Block support DataParallel #87

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions mingpt/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,11 @@ def __init__(self, config):
act = NewGELU(),
dropout = nn.Dropout(config.resid_pdrop),
))
m = self.mlp
self.mlpf = lambda x: m.dropout(m.c_proj(m.act(m.c_fc(x)))) # MLP forward

def forward(self, x):
x = x + self.attn(self.ln_1(x))
x = x + self.mlpf(self.ln_2(x))
m = self.mlp
x = x + m.dropout(m.c_proj(m.act(m.c_fc(self.ln_2(x))))) # MLP forward
return x

class GPT(nn.Module):
Expand Down
8 changes: 8 additions & 0 deletions mingpt/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from collections import defaultdict

import torch
import torch.nn as nn
from torch.utils.data.dataloader import DataLoader
from mingpt.utils import CfgNode as CN

Expand All @@ -26,6 +27,7 @@ def get_default_config():
C.betas = (0.9, 0.95)
C.weight_decay = 0.1 # only applied on matmul weights
C.grad_norm_clip = 1.0
C.data_parallel = True
return C

def __init__(self, config, model, train_dataset):
Expand Down Expand Up @@ -64,6 +66,10 @@ def run(self):
# setup the optimizer
self.optimizer = model.configure_optimizers(config)

if torch.cuda.device_count() > 1 and config.data_parallel:
model = nn.DataParallel(model)
model.to(self.device)

# setup the dataloader
train_loader = DataLoader(
self.train_dataset,
Expand Down Expand Up @@ -91,6 +97,8 @@ def run(self):

# forward the model
logits, self.loss = model(x, y)
if self.loss.nelement() > 1:
self.loss = self.loss.mean() # DataParallel can return a vector of losses

# backprop and update the parameters
model.zero_grad(set_to_none=True)
Expand Down