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

Fix GradScaler import on torch >= 2.3.0 #620

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
12 changes: 10 additions & 2 deletions benchmarks/benchmark_optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import torch
import torchvision
from packaging import version
from torch import nn as nn
from torch.nn import functional as F
from torch.utils.data import Dataset
Expand All @@ -16,6 +17,13 @@
from hivemind.optim.optimizer import Optimizer
from hivemind.utils.crypto import RSAPrivateKey

torch_version = torch.__version__.split("+")[0]

if version.parse(torch_version) >= version.parse("2.3.0"):
from torch.amp import GradScaler, autocast
else:
from torch.cuda.amp import GradScaler, autocast


@dataclass(frozen=True)
class TrainingArguments:
Expand Down Expand Up @@ -98,7 +106,7 @@ def run_trainer(batch_size: int, batch_time: float, client_mode: bool, verbose:
grad_scaler = hivemind.GradScaler()
else:
# check that hivemind.Optimizer supports regular PyTorch grad scaler as well
grad_scaler = torch.cuda.amp.GradScaler(enabled=args.use_amp)
grad_scaler = GradScaler(enabled=args.use_amp)

prev_time = time.perf_counter()

Expand All @@ -107,7 +115,7 @@ def run_trainer(batch_size: int, batch_time: float, client_mode: bool, verbose:

batch = torch.randint(0, len(X_train), (batch_size,))

with torch.cuda.amp.autocast() if args.use_amp else nullcontext():
with autocast() if args.use_amp else nullcontext():
loss = F.cross_entropy(model(X_train[batch].to(args.device)), y_train[batch].to(args.device))
grad_scaler.scale(loss).backward()

Expand Down
Loading