Last active
April 23, 2024 03:14
-
-
Save zhuhaozhe/ad9938694bc7fae8b66d376f4dffc6c9 to your computer and use it in GitHub Desktop.
sgd benchmark
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
import torch | |
from torch.optim.sgd import _single_tensor_sgd, _fused_sgd | |
import copy | |
device='cpu' | |
dtype=torch.float | |
import os | |
TENSOR_SIZE = (int(os.getenv('TENSOR_SIZE', 512 * 512)), ) | |
NPARAM = int(os.getenv("NPARAM", 4)) | |
kwargs = {} | |
kwargs['params'] = [torch.randn(TENSOR_SIZE, device=device, dtype=dtype) for _ in range(NPARAM)] | |
kwargs['d_p_list'] = [torch.randn(TENSOR_SIZE, device=device, dtype=dtype) for _ in range(NPARAM)] | |
kwargs['momentum_buffer_list'] = [torch.randn(TENSOR_SIZE, device=device, dtype=dtype) for _ in range(NPARAM)] | |
kwargs['grad_scale'] = None | |
kwargs['found_inf'] = None | |
kwargs['momentum'] = 0.1 | |
kwargs['lr'] = 0.1 | |
kwargs['dampening'] = 0.1 | |
kwargs['has_sparse_grad'] = False | |
kwargs['nesterov'] = True | |
kwargs['maximize'] = False | |
kwargs['weight_decay'] = 0.01 | |
kwargs_a = copy.deepcopy(kwargs) | |
kwargs_b = copy.deepcopy(kwargs) | |
kwargs_b['grads'] = kwargs_b.pop('d_p_list') | |
a = torch.ones(256 * 1024 * 1024 // 4, dtype=torch.float) | |
b = torch.ones(256 * 1024 * 1024 // 4, dtype=torch.float) | |
def cache_flush(): | |
# We assume the cache size is <= 512MB here. | |
# a = torch.ones(256 * 1024 * 1024 // 4, dtype=torch.float) | |
# b = torch.ones(256 * 1024 * 1024 // 4, dtype=torch.float) | |
# a, b are initialized out of this function to avoid allocate memory every time | |
global a, b | |
a += b | |
import time | |
def bench(fn, kwargs, warmup=100, bench_iters=100): | |
for _ in range(warmup): | |
cache_flush() | |
fn(**kwargs) | |
end_time = 0 | |
for _ in range(bench_iters): | |
cache_flush() | |
start_time = time.time() | |
fn(**kwargs) | |
end_time += (time.time() - start_time) | |
print(f"{fn.__name__} time: {end_time:.4f} seconds") | |
bench(_single_tensor_sgd, kwargs_a) | |
bench(_fused_sgd, kwargs_b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment