-
Notifications
You must be signed in to change notification settings - Fork 26
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
[Feature] Add GradScaler for ZeroOptim #196
Draft
nijkah
wants to merge
6
commits into
EleutherAI:main
Choose a base branch
from
nijkah:grad_scaler
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Conversation
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
Valid Test script import os
import torch, time, gc
import torch.multiprocessing as mp
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torchvision import datasets, transforms, models
from torch.utils.data import DataLoader, DistributedSampler
import torch.nn as nn
from oslo.torch.utils import get_free_port, set_seed
from oslo.torch.distributed.parallel_context import ParallelContext
from oslo.torch.nn.parallel.data_parallel.zero import ZeroRedundancyOptimizer as OsloZeroRedundancyOptimizer
from oslo.torch.nn.parallel.data_parallel.grad_scaler import DynamicGradScaler
from torch.distributed.optim import ZeroRedundancyOptimizer
def setup(rank, world_size):
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = "12345"
os.environ["RANK"] = str(rank)
os.environ["LOCAL_RANK"] = str(rank)
os.environ["WORLD_SIZE"] = str(world_size)
os.environ["LOCAL_WORLD_SIZE"] = str(world_size)
def cleanup():
dist.destroy_process_group()
def main_print(args):
if dist.get_rank() != 0:
return
print(args)
# Timing utilities
start_time = None
def start_timer():
global start_time
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated()
torch.cuda.synchronize()
start_time = time.time()
def end_timer_and_print(local_msg):
torch.cuda.synchronize()
end_time = time.time()
if dist.get_rank() != 0:
return
print("\n" + local_msg)
print("Total execution time = {:.3f} sec".format(end_time - start_time))
print("Max memory used by tensors = {} bytes".format(torch.cuda.max_memory_allocated()))
def make_model(in_size, out_size, num_layers):
layers = []
for _ in range(num_layers - 1):
layers.append(torch.nn.Linear(in_size, in_size))
layers.append(torch.nn.ReLU())
layers.append(torch.nn.Linear(in_size, out_size))
return torch.nn.Sequential(*tuple(layers))
def train(rank, world_size):
print(f"Running oslo DDP example on rank {rank}.")
setup(rank, world_size)
parallel_context = ParallelContext.from_torch(data_parallel_size=world_size)
epochs = 10
use_zero = True
use_oslo = True
if use_oslo:
use_zero = False
local_rank = torch.distributed.get_rank()
# Define the data transformation
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
set_seed(42)
# Load the CIFAR10 dataset
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
val_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
train_sampler = DistributedSampler(train_dataset, num_replicas=world_size, rank=rank)
train_loader = DataLoader(train_dataset, num_workers=4, batch_size=16, sampler=train_sampler)
val_loader = DataLoader(val_dataset, num_workers=4, batch_size=64)
model = models.resnet50(weights=models.resnet.ResNet50_Weights.IMAGENET1K_V2)
model.fc = nn.Linear(2048, 10) # CIFAR10 has 10 classes
net = model.to(rank)
model = DDP(net, device_ids=[rank])
loss_fn = nn.CrossEntropyLoss()
if use_zero:
opt = ZeroRedundancyOptimizer(
model.parameters(),
optimizer_class=torch.optim.AdamW,
lr=1e-4
)
elif use_oslo:
opt = OsloZeroRedundancyOptimizer(
torch.optim.AdamW(model.parameters(), lr=1e-4),
parallel_context=parallel_context,
overlap_communication=True,
)
else:
opt = torch.optim.AdamW(model.parameters(), lr=1e-4)
if use_oslo:
scaler = DynamicGradScaler(growth_interval=2000)
else:
scaler = torch.cuda.amp.GradScaler()
start_timer()
for epoch in range(epochs):
for idx, (input, target) in enumerate(train_loader):
opt.zero_grad() # set_to_none=True here can modestly improve performance
with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=True):
output = net(input.half().to(rank))
assert output.dtype is torch.float16
loss = loss_fn(output, target.to(rank))
if (idx % 20) == 0 and rank == 0:
print('epoch', epoch, 'idx:', idx, 'loss:', loss)
assert loss.dtype is torch.float32
scaler.scale(loss).backward()
scaler.step(opt)
scaler.update()
# print('rank:', rank, 'param:', net[0].weight)
end_timer_and_print("Default precision:")
def main(world_size):
mp.spawn(train, args=(world_size,), nprocs=world_size, join=True)
if __name__ == "__main__":
main(2) |
Please modify this to non-draft pr when you are done :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Add GradScaler for ZeroOptim
Numerical Precision is not tested yet.
Description
Test Script