-
Notifications
You must be signed in to change notification settings - Fork 59
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 an example of training a tabular model on multiple GPUs #474
Merged
+265
−12
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
1e3868d
add trompt ddp
akihironitta e3431d2
update
akihironitta f566dfd
update
akihironitta c411f93
update test
akihironitta 024e8a5
update
akihironitta 30ac943
update
akihironitta 4d07d34
no stream sync
akihironitta a494e01
update changelog
akihironitta 1941549
update
akihironitta 35d2fe5
update
akihironitta b312385
add --compile
akihironitta aabe3b0
update
akihironitta cd1ddc0
update
akihironitta 7d090e7
update
akihironitta 24ad096
Merge branch 'master' into aki/ddp
akihironitta File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,251 @@ | ||
import argparse | ||
import logging | ||
import os | ||
import os.path as osp | ||
|
||
import torch | ||
import torch.distributed as dist | ||
import torch.multiprocessing as mp | ||
import torch.nn.functional as F | ||
import torchmetrics | ||
from torch.nn.parallel import DistributedDataParallel | ||
from torch.optim.lr_scheduler import ExponentialLR | ||
from torch.utils.data.distributed import DistributedSampler | ||
from tqdm import tqdm | ||
|
||
from torch_frame.data import DataLoader | ||
from torch_frame.datasets import TabularBenchmark | ||
from torch_frame.nn import Trompt | ||
|
||
|
||
def prepare_dataset(dataset_str: str) -> TabularBenchmark: | ||
path = osp.join( | ||
osp.dirname(osp.realpath(__file__)), | ||
"..", | ||
"data", | ||
dataset_str, | ||
) | ||
materialized_path = osp.join(path, 'materialized_data.pt') | ||
if dist.get_rank() == 0: | ||
logging.info(f"Preparing dataset '{dataset_str}' from '{path}'") | ||
dataset = TabularBenchmark(root=path, name=dataset_str) | ||
logging.info("Materializing dataset") | ||
dataset.materialize(path=materialized_path) | ||
|
||
dist.barrier() | ||
if dist.get_rank() != 0: | ||
logging.info(f"Preparing dataset '{dataset_str}' from '{path}'") | ||
dataset = TabularBenchmark(root=path, name=dataset_str) | ||
logging.info("Loading materialized dataset") | ||
dataset.materialize(path=materialized_path) | ||
|
||
dist.barrier() | ||
return dataset | ||
|
||
|
||
def train( | ||
model: DistributedDataParallel, | ||
epoch: int, | ||
loader: DataLoader, | ||
optimizer: torch.optim.Optimizer, | ||
metric: torchmetrics.Metric, | ||
rank: int, | ||
) -> float: | ||
model.train() | ||
loss_accum = torch.tensor(0.0, device=rank, dtype=torch.float32) | ||
for tf in tqdm( | ||
loader, | ||
desc=f"Epoch {epoch:03d} (train)", | ||
disable=rank != 0, | ||
): | ||
tf = tf.to(rank) | ||
# [batch_size, num_layers, num_classes] | ||
out = model(tf) | ||
|
||
with torch.no_grad(): | ||
metric.update(out.mean(dim=1).argmax(dim=-1), tf.y) | ||
|
||
batch_size, num_layers, num_classes = out.size() | ||
# [batch_size * num_layers, num_classes] | ||
pred = out.view(-1, num_classes) | ||
y = tf.y.repeat_interleave( | ||
num_layers, | ||
output_size=num_layers * batch_size, | ||
) | ||
# Layer-wise logit loss | ||
loss = F.cross_entropy(pred, y) | ||
loss.backward() | ||
optimizer.step() | ||
optimizer.zero_grad() | ||
loss_accum += loss | ||
|
||
dist.all_reduce(loss_accum, op=dist.ReduceOp.AVG) | ||
metric_value = metric.compute() | ||
metric.reset() | ||
return loss_accum, metric_value | ||
|
||
|
||
@torch.no_grad() | ||
def test( | ||
model: DistributedDataParallel, | ||
epoch: int, | ||
loader: DataLoader, | ||
metric: torchmetrics.Metric, | ||
rank: int, | ||
desc: str, | ||
) -> float: | ||
model.eval() | ||
for tf in tqdm( | ||
loader, | ||
desc=f"Epoch {epoch:03d} ({desc})", | ||
disable=rank != 0, | ||
): | ||
tf = tf.to(rank) | ||
# [batch_size, num_layers, num_classes] -> [batch_size, num_classes] | ||
pred = model(tf).mean(dim=1) | ||
pred_class = pred.argmax(dim=-1) | ||
metric.update(pred_class, tf.y) | ||
|
||
metric_value = metric.compute() | ||
metric.reset() | ||
return metric_value | ||
|
||
|
||
def run(rank: int, world_size: int, args: argparse.Namespace) -> None: | ||
dist.init_process_group( | ||
backend='nccl', | ||
init_method='env://', | ||
world_size=world_size, | ||
rank=rank, | ||
) | ||
logging.basicConfig( | ||
format=(f"[rank={rank}/{world_size}] " | ||
f"[%(asctime)s] %(levelname)s: %(message)s"), | ||
level=logging.INFO, | ||
) | ||
logging.info(f"Initialized rank {rank}/{world_size}") | ||
dataset = prepare_dataset(args.dataset) | ||
assert dataset.task_type.is_classification | ||
|
||
# Ensure train, val and test splits are the same across all ranks by | ||
# setting the seed on each rank. | ||
torch.manual_seed(args.seed) | ||
dataset = dataset.shuffle() | ||
train_dataset, val_dataset, test_dataset = ( | ||
dataset[:0.7], | ||
dataset[0.7:0.79], | ||
dataset[0.79:], | ||
) | ||
# Note that the last batch of evaluation loops is dropped for now because | ||
# drop_last=False will duplicate samples to fill the last batch, leading to | ||
# the wrong evaluation metrics. | ||
# https://github.com/pytorch/pytorch/issues/25162 | ||
train_loader = DataLoader( | ||
train_dataset.tensor_frame, | ||
batch_size=args.batch_size, | ||
sampler=DistributedSampler( | ||
train_dataset, | ||
shuffle=True, | ||
drop_last=True, | ||
), | ||
) | ||
val_loader = DataLoader( | ||
val_dataset.tensor_frame, | ||
batch_size=args.batch_size, | ||
sampler=DistributedSampler( | ||
val_dataset, | ||
shuffle=True, | ||
drop_last=True, | ||
), | ||
) | ||
test_loader = DataLoader( | ||
test_dataset.tensor_frame, | ||
batch_size=args.batch_size, | ||
sampler=DistributedSampler( | ||
test_dataset, | ||
shuffle=True, | ||
drop_last=True, | ||
), | ||
) | ||
model = Trompt( | ||
channels=args.channels, | ||
out_channels=dataset.num_classes, | ||
num_prompts=args.num_prompts, | ||
num_layers=args.num_layers, | ||
col_stats=dataset.col_stats, | ||
col_names_dict=train_dataset.tensor_frame.col_names_dict, | ||
).to(rank) | ||
model = DistributedDataParallel(model, device_ids=[rank]) | ||
model = torch.compile(model) if args.compile else model | ||
optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) | ||
lr_scheduler = ExponentialLR(optimizer, gamma=0.95) | ||
metrics_kwargs = { | ||
"task": "multiclass", | ||
"num_classes": dataset.num_classes, | ||
} | ||
train_metric = torchmetrics.Accuracy(**metrics_kwargs).to(rank) | ||
val_metric = torchmetrics.Accuracy(**metrics_kwargs).to(rank) | ||
test_metric = torchmetrics.Accuracy(**metrics_kwargs).to(rank) | ||
best_val_acc = 0.0 | ||
test_acc = 0.0 | ||
for epoch in range(1, args.epochs + 1): | ||
train_loader.sampler.set_epoch(epoch) | ||
train_loss, train_acc = train( | ||
model, | ||
epoch, | ||
train_loader, | ||
optimizer, | ||
train_metric, | ||
rank, | ||
) | ||
val_acc = test( | ||
model, | ||
epoch, | ||
val_loader, | ||
val_metric, | ||
rank, | ||
'val', | ||
) | ||
if best_val_acc < val_acc: | ||
best_val_acc = val_acc | ||
test_acc = test( | ||
model, | ||
epoch, | ||
test_loader, | ||
test_metric, | ||
rank, | ||
'test', | ||
) | ||
if rank == 0: | ||
print(f"Train Loss: {train_loss:.4f}, " | ||
f"Train Acc: {train_acc:.4f}, " | ||
f"Val Acc: {val_acc:.4f}") | ||
|
||
lr_scheduler.step() | ||
|
||
if rank == 0: | ||
print(f"Best Val Acc: {best_val_acc:.4f}, " | ||
f"Test Acc: {test_acc:.4f}") | ||
|
||
dist.destroy_process_group() | ||
logging.info("Process group destroyed") | ||
|
||
|
||
if __name__ == "__main__": | ||
parser = argparse.ArgumentParser() | ||
parser.add_argument("--dataset", type=str, default="california") | ||
parser.add_argument("--channels", type=int, default=128) | ||
parser.add_argument("--num_prompts", type=int, default=128) | ||
parser.add_argument("--num_layers", type=int, default=6) | ||
parser.add_argument("--batch_size", type=int, default=256) | ||
parser.add_argument("--lr", type=float, default=0.001) | ||
parser.add_argument("--epochs", type=int, default=50) | ||
parser.add_argument("--seed", type=int, default=0) | ||
parser.add_argument("--compile", action="store_true") | ||
args = parser.parse_args() | ||
|
||
os.environ['MASTER_ADDR'] = 'localhost' | ||
os.environ['MASTER_PORT'] = '12355' | ||
|
||
world_size = torch.cuda.device_count() | ||
mp.spawn(run, args=(world_size, args), nprocs=world_size, join=True) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -54,7 +54,7 @@ | |
Trompt, | ||
dict(channels=8, num_prompts=2), | ||
None, | ||
4, | ||
3, | ||
id="Trompt", | ||
), | ||
pytest.param( | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's make sure this change does not break the example code.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Confirmed the change doesn't break these scripts across all supported task types: