repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
ELLE | ELLE-main/fairseq-0.9.0/fairseq/tasks/multilingual_translation.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from collections import OrderedDict
import os
import torch
from fairseq import options, utils
from fairseq.data import (
Dictionary,
... | 16,648 | 43.755376 | 116 | py |
ELLE | ELLE-main/fairseq-0.9.0/fairseq/tasks/translation_lev.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from fairseq.utils import new_arange
from fairseq.tasks import register_task
from fairseq.tasks.translation import TranslationTa... | 6,412 | 39.847134 | 87 | py |
ELLE | ELLE-main/fairseq-0.9.0/fairseq/tasks/translation_moe.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from fairseq import modules, utils
from fairseq.tasks import register_task
from fairseq.tasks.translation import TranslationTask... | 8,872 | 41.252381 | 110 | py |
ELLE | ELLE-main/fairseq-0.9.0/fairseq/tasks/fairseq_task.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
from fairseq import tokenizer
from fairseq.data import (
data_utils,
FairseqDataset,
iterators,
... | 11,175 | 37.143345 | 104 | py |
ELLE | ELLE-main/fairseq-0.9.0/docs/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# fairseq documentation build configuration file, created by
# sphinx-quickstart on Fri Aug 17 21:45:30 2018.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# au... | 4,235 | 30.849624 | 80 | py |
ELLE | ELLE-main/fairseq-0.9.0/fairseq_cli/eval.py | #!/usr/bin/env python3 -u
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Train a new model on one or across multiple GPUs.
"""
import collections
import math
import random
import numpy... | 13,895 | 37.175824 | 104 | py |
ELLE | ELLE-main/fairseq-0.9.0/fairseq_cli/eval_batch.py | #!/usr/bin/env python3 -u
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Train a new model on one or across multiple GPUs.
"""
import collections
import math
import random
import os
imp... | 13,159 | 37.144928 | 104 | py |
ELLE | ELLE-main/fairseq-0.9.0/fairseq_cli/train_pnn_gpt.py | #!/usr/bin/env python3 -u
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Train a new model on one or across multiple GPUs.
"""
import collections
import math
import random
import os
imp... | 24,718 | 39.589491 | 212 | py |
ELLE | ELLE-main/apex/setup.py | import torch
from torch.utils import cpp_extension
from setuptools import setup, find_packages
import subprocess
import sys
import warnings
import os
# ninja build does not work unless include_dirs are abs path
this_dir = os.path.dirname(os.path.abspath(__file__))
def get_cuda_bare_metal_version(cuda_dir):
raw_o... | 31,006 | 61.263052 | 290 | py |
ELLE | ELLE-main/apex/examples/dcgan/main_amp.py | from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchv... | 10,518 | 37.250909 | 114 | py |
ELLE | ELLE-main/apex/examples/simple/distributed/distributed_data_parallel.py | import torch
import argparse
import os
from apex import amp
# FOR DISTRIBUTED: (can also use torch.nn.parallel.DistributedDataParallel instead)
from apex.parallel import DistributedDataParallel
parser = argparse.ArgumentParser()
# FOR DISTRIBUTED: Parse for the local_rank argument, which will be supplied
# automatica... | 2,548 | 37.621212 | 88 | py |
ELLE | ELLE-main/apex/examples/imagenet/main_amp.py | import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvi... | 21,139 | 37.860294 | 239 | py |
ELLE | ELLE-main/apex/tests/L0/run_optimizers/test_dist_adam.py | import argparse
import random
import sys
import torch
from torch.nn.parallel import DistributedDataParallel as DDP
from apex import amp
from apex.optimizers import FusedAdam
from apex.contrib.optimizers.distributed_fused_adam import DistributedFusedAdam
class TestModel(torch.nn.Module):
def __init__(self, args)... | 5,922 | 31.190217 | 125 | py |
ELLE | ELLE-main/apex/tests/L0/run_optimizers/test_fused_optimizer.py | import unittest
import os
import random
import torch
import apex
from itertools import product
class TestFusedOptimizer(unittest.TestCase):
def setUp(self, max_abs_diff=1e-3, max_rel_diff=1, iters=7):
self.max_abs_diff = max_abs_diff
self.max_rel_diff = max_rel_diff
self.iters = iters
... | 10,488 | 37.704797 | 90 | py |
ELLE | ELLE-main/apex/tests/L0/run_optimizers/test_lamb.py | import unittest
import os
import torch
from torch.optim import Optimizer
import apex
from apex.multi_tensor_apply import multi_tensor_applier
from itertools import product
class RefLAMB(Optimizer):
r"""Implements Lamb algorithm.
It has been proposed in `Large Batch Optimization for Deep Learning: Training BE... | 11,093 | 39.937269 | 122 | py |
ELLE | ELLE-main/apex/tests/L0/run_amp/test_larc.py | import unittest
import torch
from torch import nn
from torch.nn import Parameter
from apex import amp
from apex.parallel.LARC import LARC
from utils import common_init
class MyModel(torch.nn.Module):
def __init__(self, unique):
super(MyModel, self).__init__()
self.weight0 = Parameter(
... | 1,339 | 23.814815 | 80 | py |
ELLE | ELLE-main/apex/tests/L0/run_amp/test_multi_tensor_scale.py | import unittest
import functools as ft
import itertools as it
from apex import amp
import torch
from torch import nn
import torch.nn.functional as F
from utils import common_init, HALF, FLOAT,\
ALWAYS_HALF, ALWAYS_FLOAT, MATCH_INPUT
try:
import amp_C
from amp_C import multi_tensor_scale
from apex.multi_t... | 4,573 | 35.015748 | 109 | py |
ELLE | ELLE-main/apex/tests/L0/run_amp/test_cache.py | import unittest
import functools as ft
import itertools as it
from apex import amp
from apex.amp import _amp_state
import torch
from torch import nn
import torch.nn.functional as F
from utils import common_init, HALF, FLOAT,\
ALWAYS_HALF, ALWAYS_FLOAT, MATCH_INPUT
def get_reference_grad(i, w, ops):
# Creati... | 4,833 | 34.028986 | 98 | py |
ELLE | ELLE-main/apex/tests/L0/run_amp/test_multi_tensor_axpby.py | import unittest
import functools as ft
import itertools as it
from apex import amp
import torch
from torch import nn
import torch.nn.functional as F
from math import floor
from utils import common_init, HALF, FLOAT,\
ALWAYS_HALF, ALWAYS_FLOAT, MATCH_INPUT
try:
import amp_C
from amp_C import multi_tensor_axp... | 7,231 | 38.955801 | 111 | py |
ELLE | ELLE-main/apex/tests/L0/run_amp/test_basic_casts.py | import unittest
import functools as ft
import itertools as it
from apex import amp
import torch
from torch import nn
import torch.nn.functional as F
from utils import common_init, HALF, FLOAT,\
ALWAYS_HALF, ALWAYS_FLOAT, MATCH_INPUT
def run_layer_test(test_case, fns, expected, input_shape, test_backward=True):
... | 5,085 | 34.319444 | 92 | py |
ELLE | ELLE-main/apex/tests/L0/run_amp/test_fused_sgd.py | import unittest
import functools as ft
import itertools as it
from apex import amp
from apex.amp import _amp_state
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import Parameter
from utils import common_init, HALF, FLOAT,\
ALWAYS_HALF, ALWAYS_FLOAT, MATCH_INPUT
try:
import a... | 39,261 | 48.386164 | 261 | py |
ELLE | ELLE-main/apex/tests/L0/run_amp/test_promotion.py | import unittest
import itertools as it
from apex import amp
import torch
from torch import nn
import torch.nn.functional as F
from utils import common_init, HALF, FLOAT, DTYPES
class TestPromotion(unittest.TestCase):
def setUp(self):
self.handle = amp.init(enabled=True)
common_init(self)
de... | 2,558 | 32.671053 | 73 | py |
ELLE | ELLE-main/apex/tests/L0/run_amp/test_multiple_models_optimizers_losses.py | import unittest
import functools as ft
import itertools as it
from apex import amp
from apex.amp import _amp_state
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import Parameter
from utils import common_init, HALF, FLOAT,\
ALWAYS_HALF, ALWAYS_FLOAT, MATCH_INPUT
class MyModel(to... | 36,499 | 46.837484 | 255 | py |
ELLE | ELLE-main/apex/tests/L0/run_amp/utils.py | import torch
HALF = 'torch.cuda.HalfTensor'
FLOAT = 'torch.cuda.FloatTensor'
DTYPES = [torch.half, torch.float]
ALWAYS_HALF = {torch.float: HALF,
torch.half: HALF}
ALWAYS_FLOAT = {torch.float: FLOAT,
torch.half: FLOAT}
MATCH_INPUT = {torch.float: FLOAT,
torch.half: HALF}... | 512 | 22.318182 | 57 | py |
ELLE | ELLE-main/apex/tests/L0/run_amp/test_rnn.py | import unittest
from apex import amp
import random
import torch
from torch import nn
from utils import common_init, HALF
class TestRnnCells(unittest.TestCase):
def setUp(self):
self.handle = amp.init(enabled=True)
common_init(self)
def tearDown(self):
self.handle._deactivate()
d... | 4,506 | 37.521368 | 87 | py |
ELLE | ELLE-main/apex/tests/L0/run_amp/test_add_param_group.py | import unittest
import functools as ft
import itertools as it
from apex import amp
from apex.amp import _amp_state
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import Parameter
from utils import common_init, HALF, FLOAT,\
ALWAYS_HALF, ALWAYS_FLOAT, MATCH_INPUT
class MyModel(to... | 5,831 | 38.14094 | 102 | py |
ELLE | ELLE-main/apex/tests/L0/run_amp/test_checkpointing.py | import unittest
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from apex import amp
from utils import common_init, FLOAT
class MyModel(torch.nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 3, 1, 1)
... | 11,836 | 43.16791 | 107 | py |
ELLE | ELLE-main/apex/tests/L0/run_amp/test_multi_tensor_l2norm.py | import unittest
import functools as ft
import itertools as it
from apex import amp
import torch
from torch import nn
import torch.nn.functional as F
from utils import common_init, HALF, FLOAT,\
ALWAYS_HALF, ALWAYS_FLOAT, MATCH_INPUT
try:
import amp_C
from amp_C import multi_tensor_l2norm
from apex.multi_t... | 2,719 | 29.909091 | 100 | py |
ELLE | ELLE-main/apex/tests/L0/run_pyprof_nvtx/test_pyprof_nvtx.py | import inspect
import os
import torch
import torch.nn.functional as F
import unittest
from apex import pyprof
pyprof.nvtx.init()
# TODO: add tests for:
# F.bilinear, F.l1_loss, F.multilabel_soft_margin_loss, F.multi_margin_loss
class TestPyProfNvtx(unittest.TestCase):
def __init__(self, testName, dtype=torch.fl... | 27,141 | 50.502846 | 160 | py |
ELLE | ELLE-main/apex/tests/L0/run_fused_layer_norm/test_fused_layer_norm.py | import unittest
import os
import random
import torch
import apex
from torch.autograd import Variable
class TestFusedLayerNorm(unittest.TestCase):
def setUp(self):
# bias and weight are set to 0 and 1 respectively, so no need to copy parameters from cpu module to the gpu one
self.module_cp... | 1,748 | 39.674419 | 121 | py |
ELLE | ELLE-main/apex/tests/L0/run_fp16util/test_fp16util.py | import unittest
import torch
import torch.nn as nn
from apex.fp16_utils import FP16Model
class DummyBlock(nn.Module):
def __init__(self):
super(DummyBlock, self).__init__()
self.conv = nn.Conv2d(10, 10, 2)
self.bn = nn.BatchNorm2d(10, affine=True)
def forward(self, x):
retu... | 2,051 | 26 | 86 | py |
ELLE | ELLE-main/apex/tests/L0/run_mlp/test_mlp.py | """Tests for c++ MLP"""
import unittest
from time import time
import numpy as np
import torch
from torch import nn
from apex.mlp import MLP
batch_size = 1024
mlp_sizes = [480, 1024, 1024, 512, 256, 1]
num_iters = 10
class TestMLP(unittest.TestCase):
def test_creation(self):
MLP(mlp_sizes)
def test... | 8,427 | 37.484018 | 112 | py |
ELLE | ELLE-main/apex/tests/distributed/amp_master_params/amp_master_params.py | import torch
import argparse
import os
from apex import amp
# FOR DISTRIBUTED: (can also use torch.nn.parallel.DistributedDataParallel instead)
from apex.parallel import DistributedDataParallel
parser = argparse.ArgumentParser()
# FOR DISTRIBUTED: Parse for the local_rank argument, which will be supplied
# automatica... | 2,799 | 38.43662 | 103 | py |
ELLE | ELLE-main/apex/tests/distributed/amp_master_params/compare.py | import torch
model_params_rank0 = torch.load("rank0model.pth",
map_location = lambda storage, loc: storage.cuda(0))
model_params_rank1 = torch.load("rank1model.pth",
map_location = lambda storage, loc: storage.cuda(0))
master_params_rank0 = torch.load("rank0m... | 1,531 | 51.827586 | 104 | py |
ELLE | ELLE-main/apex/tests/distributed/synced_batchnorm/two_gpu_test_different_batch_size.py | import torch
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel as DDP
from apex.parallel import SyncBatchNorm as ApexSyncBatchNorm
import argparse
import os
import numpy as np
var_batch = 16
def compare(desc, inp1, inp2, error= 1e-5):
a = inp1.clone().detach().cpu().numpy()
b = inp2... | 5,322 | 32.477987 | 99 | py |
ELLE | ELLE-main/apex/tests/distributed/synced_batchnorm/test_batchnorm1d.py | import torch
import apex
model = apex.parallel.SyncBatchNorm(4).cuda()
model.weight.data.uniform_()
model.bias.data.uniform_()
data = torch.rand((8,4)).cuda()
model_ref = torch.nn.BatchNorm1d(4).cuda()
model_ref.load_state_dict(model.state_dict())
data_ref = data.clone()
output = model(data)
output_ref = model_ref(d... | 484 | 24.526316 | 59 | py |
ELLE | ELLE-main/apex/tests/distributed/synced_batchnorm/test_groups.py | import torch
import numpy as np
import apex
import syncbn
import os
import argparse
import torch.optim as optim
def compare(desc, inp1, inp2, error):
a = inp1.clone().detach().cpu().numpy()
b = inp2.clone().detach().cpu().numpy()
close = np.allclose(a,b, error, error)
if not close:
print(desc, ... | 6,690 | 34.973118 | 209 | py |
ELLE | ELLE-main/apex/tests/distributed/synced_batchnorm/single_gpu_unit_test.py | import torch
import numpy as np
import apex
if True:
print("using setup tools")
import syncbn
else:
print("using jit")
from torch.utils.cpp_extension import load
syncbn = load(name='syncbn', sources=['../../csrc/syncbn.cpp', '../../csrc/welford.cu'])
def compare(desc, inp1, inp2, error):
a = in... | 7,208 | 44.05625 | 209 | py |
ELLE | ELLE-main/apex/tests/distributed/synced_batchnorm/two_gpu_unit_test.py | import torch
import numpy as np
import apex
import syncbn
import os
import argparse
import torch.optim as optim
def compare(desc, inp1, inp2, error):
a = inp1.clone().detach().cpu().numpy()
b = inp2.clone().detach().cpu().numpy()
close = np.allclose(a,b, error, error)
if not close:
print(desc, ... | 6,616 | 35.558011 | 209 | py |
ELLE | ELLE-main/apex/tests/distributed/synced_batchnorm/python_single_gpu_unit_test.py | import torch
import numpy as np
import apex
def compare(desc, inp1, inp2, error):
a = inp1.clone().detach().cpu().numpy()
b = inp2.clone().detach().cpu().numpy()
close = np.allclose(a,b, error, error)
if not close:
print(desc, close)
z = a - b
index = (np.abs(z) >= error + error... | 4,004 | 34.758929 | 209 | py |
ELLE | ELLE-main/apex/tests/distributed/DDP/ddp_race_condition_test.py | import torch
import torch.distributed as dist
from torch.nn import Parameter
from torch.nn import Module
from apex.parallel import DistributedDataParallel as DDP
import argparse
import os
parser = argparse.ArgumentParser(description='allreduce hook example')
parser.add_argument("--local_rank", default=0, type=int)
ar... | 2,424 | 33.642857 | 95 | py |
ELLE | ELLE-main/apex/tests/L1/common/compare.py | import argparse
import torch
parser = argparse.ArgumentParser(description='Compare')
parser.add_argument('--opt-level', type=str)
parser.add_argument('--keep-batchnorm-fp32', type=str, default=None)
parser.add_argument('--loss-scale', type=str, default=None)
parser.add_argument('--fused-adam', action='store_true')
par... | 2,231 | 33.338462 | 101 | py |
ELLE | ELLE-main/apex/tests/L1/common/main_amp.py | import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvi... | 19,169 | 35.375712 | 235 | py |
ELLE | ELLE-main/apex/docs/source/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# PyTorch documentation build configuration file, created by
# sphinx-quickstart on Fri Dec 23 13:31:47 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# au... | 8,119 | 31.610442 | 79 | py |
ELLE | ELLE-main/apex/apex/__init__.py | # May help avoid undefined symbol errors https://pytorch.org/cppdocs/notes/faq.html#undefined-symbol-errors-from-pytorch-aten
import torch
import warnings
if torch.distributed.is_available():
from . import parallel
from . import amp
from . import fp16_utils
# For optimizers and normalization there is no Python f... | 851 | 39.571429 | 125 | py |
ELLE | ELLE-main/apex/apex/amp/scaler.py | import torch
from ..multi_tensor_apply import multi_tensor_applier
from ._amp_state import _amp_state, master_params, maybe_print
from itertools import product
def scale_check_overflow_python(model_grad, master_grad, scale, check_overflow=False):
# Exception handling for 18.04 compatibility
if check_overflow:
... | 10,494 | 47.142202 | 110 | py |
ELLE | ELLE-main/apex/apex/amp/_process_optimizer.py | import types
from ..fp16_utils import master_params_to_model_params
from ..multi_tensor_apply import multi_tensor_applier
from ._amp_state import maybe_print
import torch
from ..optimizers import FusedSGD
class AmpOptimizerState(object):
def __init__(self):
pass
def _master_params_to_model_params(self):... | 20,747 | 41.342857 | 115 | py |
ELLE | ELLE-main/apex/apex/amp/_amp_state.py | # This is a "header object" that allows different amp modules to communicate.
# I'm a C++ guy, not a python guy. I decided this approach because it seemed most C++-like.
# But apparently it's ok:
# http://effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm
import os
import torch
TORCH_MAJOR = int(torc... | 2,008 | 27.7 | 92 | py |
ELLE | ELLE-main/apex/apex/amp/utils.py | from . import compat
import functools
import itertools
import torch
def is_cuda_enabled():
return torch.version.cuda is not None
def get_cuda_version():
return tuple(int(x) for x in torch.version.cuda.split('.'))
def is_fp_tensor(x):
if is_nested(x):
# Fast-fail version of all(is_fp_tensor)
... | 7,222 | 33.232227 | 86 | py |
ELLE | ELLE-main/apex/apex/amp/opt.py | import contextlib
import warnings
from .scaler import LossScaler, master_params
from ._amp_state import maybe_print
import numpy as np
class OptimWrapper(object):
def __init__(self, optimizer, amp_handle, num_loss):
self._optimizer = optimizer
self._amp_handle = amp_handle
self._num_loss ... | 3,446 | 32.144231 | 80 | py |
ELLE | ELLE-main/apex/apex/amp/amp.py | from . import compat, rnn_compat, utils, wrap
from .handle import AmpHandle, NoOpHandle
from .lists import functional_overrides, torch_overrides, tensor_overrides
from ._amp_state import _amp_state
from .frontend import *
import functools
import itertools
import torch
_DECORATOR_HANDLE = None
_USER_CAST_REGISTRY = ... | 7,266 | 39.825843 | 101 | py |
ELLE | ELLE-main/apex/apex/amp/compat.py | import torch
# True for post-0.4, when Variables/Tensors merged.
def variable_is_tensor():
v = torch.autograd.Variable()
return isinstance(v, torch.Tensor)
def tensor_is_variable():
x = torch.Tensor()
return type(x) == torch.autograd.Variable
# False for post-0.4
def tensor_is_float_tensor():
x =... | 1,393 | 28.659574 | 77 | py |
ELLE | ELLE-main/apex/apex/amp/wrap.py | from . import compat
from . import utils
from ._amp_state import _amp_state
from . import rnn_compat
import functools
import torch
def make_cast_wrapper(orig_fn, cast_fn, handle,
try_caching=False):
@functools.wraps(orig_fn)
def wrapper(*args, **kwargs):
if not handle.is_active(... | 11,242 | 39.588448 | 89 | py |
ELLE | ELLE-main/apex/apex/amp/_initialize.py | import torch
from torch._six import string_classes
import functools
import numpy as np
import sys
from types import MethodType
import warnings
from ._amp_state import _amp_state, warn_or_err, container_abcs
from .handle import disable_casts
from .scaler import LossScaler
from ._process_optimizer import _process_optimiz... | 11,606 | 42.965909 | 111 | py |
ELLE | ELLE-main/apex/apex/amp/frontend.py | import torch
from ._initialize import _initialize
from ._amp_state import _amp_state, warn_or_err, maybe_print
from collections import OrderedDict
class Properties(object):
"""
This class has two purposes: to establish a set of default properties,
and to route setting of these attributes through __setattr... | 21,267 | 47.009029 | 115 | py |
ELLE | ELLE-main/apex/apex/amp/rnn_compat.py | from . import utils, wrap
import torch
_VF = torch._C._VariableFunctions
RNN_NAMES = ['rnn_relu', 'rnn_tanh', 'gru', 'lstm']
def _gen_VF_wrapper(name):
def wrapper(*args, **kwargs):
return getattr(_VF, name)(*args, **kwargs)
return wrapper
# Some python magic to generate an object that has the rnn ce... | 1,995 | 35.962963 | 79 | py |
ELLE | ELLE-main/apex/apex/amp/handle.py | import contextlib
import warnings
import sys
import torch
from . import utils
from .opt import OptimWrapper
from .scaler import LossScaler
from ._amp_state import _amp_state, master_params, maybe_print
if torch.distributed.is_available():
from ..parallel.LARC import LARC
# There's no reason to expose the notion... | 12,066 | 41.79078 | 118 | py |
ELLE | ELLE-main/apex/apex/amp/lists/functional_overrides.py |
# TODO: think about the following two. They do weird things.
# - torch.nn.utils.clip_grad (but it should always be fp32 anyway)
# - torch.nn.utils.weight_norm
# Notes:
# F.instance_norm uses batch_norm internally. Which correctly handles
# fp16 in/out with fp32 weights. So we shouldn't do anything for
# either of... | 2,248 | 26.765432 | 96 | py |
ELLE | ELLE-main/apex/apex/amp/lists/tensor_overrides.py | from .. import compat
from . import torch_overrides
import importlib
import torch
# if compat.variable_is_tensor() and not compat.tensor_is_variable():
MODULE = torch.Tensor
# else:
# MODULE = torch.autograd.Variable
FP16_FUNCS = compat.filter_attrs(MODULE, [
'__matmul__',
])
FP32_FUNCS = compat.filter_at... | 1,402 | 20.921875 | 72 | py |
ELLE | ELLE-main/apex/apex/amp/lists/torch_overrides.py | import torch
from .. import utils
MODULE = torch
FP16_FUNCS = [
# Low level functions wrapped by torch.nn layers.
# The wrapper layers contain the weights which are then passed in as a parameter
# to these functions.
'conv1d',
'conv2d',
'conv3d',
'conv_transpose1d',
'conv_transpose2d'... | 2,082 | 16.956897 | 84 | py |
ELLE | ELLE-main/apex/apex/normalization/fused_layer_norm.py | import math
import torch
import numbers
from torch.nn.parameter import Parameter
from torch.nn import init
from torch.nn import functional as F
import importlib
global fused_layer_norm_cuda
fused_layer_norm_cuda = None
class FusedLayerNormAffineFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, in... | 6,612 | 38.837349 | 102 | py |
ELLE | ELLE-main/apex/apex/fp16_utils/fp16_optimizer.py | import torch
from torch import nn
from torch.autograd import Variable
from torch.nn.parameter import Parameter
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from ..amp._amp_state import _amp_state, maybe_print
from ..amp.scaler import LossScaler
from ..multi_tensor_apply import multi_tensor... | 27,769 | 49.036036 | 425 | py |
ELLE | ELLE-main/apex/apex/fp16_utils/fp16util.py | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
class tofp16(nn.Module):
"""
Utility module that implements::
def forward(self, input):
return input.half()
"""
def __init__(self):
... | 7,141 | 36.989362 | 337 | py |
ELLE | ELLE-main/apex/apex/fp16_utils/loss_scaler.py | import torch
# item() is a recent addition, so this helps with backward compatibility.
def to_python_float(t):
if hasattr(t, 'item'):
return t.item()
else:
return t[0]
class LossScaler:
"""
Class that manages a static loss scale. This class is intended to interact with
:class:`FP1... | 7,568 | 39.475936 | 326 | py |
ELLE | ELLE-main/apex/apex/parallel/multiproc.py | import torch
import sys
import subprocess
def docstring_hack():
"""
Multiproc file which will launch a set of processes locally for multi-gpu
usage: python -m apex.parallel.multiproc main.py ...
"""
pass
argslist = list(sys.argv)[1:]
world_size = torch.cuda.device_count()
if '--world-size' in arg... | 884 | 23.583333 | 77 | py |
ELLE | ELLE-main/apex/apex/parallel/optimized_sync_batchnorm.py | import torch
from torch.nn.modules.batchnorm import _BatchNorm
from torch.nn import functional as F
import syncbn
from .optimized_sync_batchnorm_kernel import SyncBatchnormFunction
class SyncBatchNorm(_BatchNorm):
"""
synchronized batch normalization module extented from `torch.nn.BatchNormNd`
with the a... | 4,364 | 49.755814 | 252 | py |
ELLE | ELLE-main/apex/apex/parallel/optimized_sync_batchnorm_kernel.py | import torch
from torch.autograd.function import Function
import syncbn
from apex.parallel import ReduceOp
class SyncBatchnormFunction(Function):
@staticmethod
def forward(ctx, input, z, weight, bias, running_mean, running_variance, eps, track_running_stats = True, momentum = 1.0, process_group = None, chann... | 5,467 | 44.566667 | 189 | py |
ELLE | ELLE-main/apex/apex/parallel/LARC.py | import torch
from torch import nn
from torch.nn.parameter import Parameter
class LARC(object):
"""
:class:`LARC` is a pytorch implementation of both the scaling and clipping variants of LARC,
in which the ratio between gradient and parameter magnitudes is used to calculate an adaptive
local learning r... | 4,018 | 36.212963 | 225 | py |
ELLE | ELLE-main/apex/apex/parallel/distributed.py | import torch
import torch.distributed as dist
from torch.nn.modules import Module
from torch.autograd import Variable
from collections import OrderedDict
from itertools import chain
import copy
import importlib
from ..multi_tensor_apply import multi_tensor_applier
imported_flatten_impl = False
def import_flatten_impl... | 30,651 | 46.89375 | 496 | py |
ELLE | ELLE-main/apex/apex/parallel/__init__.py | import torch
if hasattr(torch.distributed, 'ReduceOp'):
ReduceOp = torch.distributed.ReduceOp
elif hasattr(torch.distributed, 'reduce_op'):
ReduceOp = torch.distributed.reduce_op
else:
ReduceOp = torch.distributed.deprecated.reduce_op
from .distributed import DistributedDataParallel, Reducer
# This is tri... | 3,667 | 37.208333 | 162 | py |
ELLE | ELLE-main/apex/apex/parallel/sync_batchnorm.py | import torch
from torch.nn.modules.batchnorm import _BatchNorm
from torch.nn import functional as F
from .sync_batchnorm_kernel import SyncBatchnormFunction
from apex.parallel import ReduceOp
class SyncBatchNorm(_BatchNorm):
"""
synchronized batch normalization module extented from ``torch.nn.BatchNormNd``
... | 6,532 | 47.392593 | 228 | py |
ELLE | ELLE-main/apex/apex/parallel/sync_batchnorm_kernel.py | import torch
from torch.autograd.function import Function
from apex.parallel import ReduceOp
class SyncBatchnormFunction(Function):
@staticmethod
def forward(ctx, input, weight, bias, running_mean, running_variance, eps, process_group, world_size):
torch.cuda.nvtx.range_push("sync_BN_fw")
# ... | 3,761 | 41.75 | 106 | py |
ELLE | ELLE-main/apex/apex/RNN/cells.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .RNNBackend import RNNCell
from torch.nn._functions.thnn import rnnFusedPointwise as fusedBackend
import math
class mLSTMRNNCell(RNNCell):
"""
mLSTMRNNCell
"""
def __init__(self, input_size, hidden_size, bias = False, output_... | 2,550 | 29.011765 | 156 | py |
ELLE | ELLE-main/apex/apex/RNN/RNNBackend.py | import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import math
def is_iterable(maybe_iterable):
return isinstance(maybe_iterable, list) or isinstance(maybe_iterable, tuple)
def flatten_list(tens_list):
"""
flatten_list
"""
if not is_iterable(... | 11,578 | 30.636612 | 126 | py |
ELLE | ELLE-main/apex/apex/RNN/models.py | import torch
from torch.nn._functions.rnn import LSTMCell, RNNReLUCell, RNNTanhCell, GRUCell
from .RNNBackend import bidirectionalRNN, stackedRNN, RNNCell
from .cells import mLSTMRNNCell, mLSTMCell
def toRNNBackend(inputRNN, num_layers, bidirectional=False, dropout = 0):
"""
:class:`toRNNBackend`
"""
... | 2,137 | 37.872727 | 129 | py |
ELLE | ELLE-main/apex/apex/pyprof/nvtx/nvmarker.py | """
This file intercepts (monkey patches) the following functions and adds NVTX markers.
torch.*
torch.Tensor.*
torch.nn.functional.*
torch.nn.*.forward
The NVTX markers (one or more) contain the following information
call trace (a list of file_name:line_number)
extra_repr() from torch.nn modules
module/class n... | 6,153 | 26.596413 | 636 | py |
ELLE | ELLE-main/apex/apex/pyprof/examples/operators.py | #!/usr/bin/env python3
"""
This file checks all Python operators.
"""
import sys
import torch
import torch.cuda.profiler as profiler
import operator
import inspect
#Import and initialize pyprof
from apex import pyprof
pyprof.nvtx.init()
X = 1024
Y = 1024
fa = torch.rand(X, Y).cuda()
fb = torch.rand(X, Y).cuda()
fc... | 3,439 | 22.561644 | 158 | py |
ELLE | ELLE-main/apex/apex/pyprof/examples/simple.py | #!/usr/bin/env python3
"""
This simple file provides an example of how to
- import the pyprof library and initialize it
- use the emit_nvtx context manager
- start and stop the profiler
Only kernels within profiler.start and profiler.stop calls are profiled.
To profile
$ nvprof -f -o simple.sql --profile-from-star... | 791 | 19.307692 | 72 | py |
ELLE | ELLE-main/apex/apex/pyprof/examples/lenet.py | #!/usr/bin/env python3
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.cuda.profiler as profiler
import torch.optim as optim
from apex import pyprof
pyprof.nvtx.init()
class LeNet5(nn.Module):
def __init__(self):
super(LeNet5, self).__init__()
# 1 input image channel, 6 output ch... | 1,679 | 24.454545 | 70 | py |
ELLE | ELLE-main/apex/apex/pyprof/examples/imagenet/imagenet.py | #!/usr/bin/env python3
"""
Example to run pyprof with imagenet models.
"""
import sys
import torch
import torch.nn as nn
import torchvision.models as models
import torch.cuda.profiler as profiler
import argparse
from apex import pyprof
from apex.optimizers import FusedAdam
def parseArgs():
parser = argparse.Argume... | 4,109 | 29.220588 | 530 | py |
ELLE | ELLE-main/apex/apex/pyprof/examples/jit/jit_trace_method.py | #!/usr/bin/env python3
import torch
import torch.cuda.profiler as profiler
from apex import pyprof
class Foo(torch.nn.Module):
def __init__(self, size):
super(Foo, self).__init__()
self.n = torch.nn.Parameter(torch.ones(size))
self.m = torch.nn.Parameter(torch.ones(size))
def forward(... | 817 | 21.108108 | 53 | py |
ELLE | ELLE-main/apex/apex/pyprof/examples/jit/jit_script_function.py | #!/usr/bin/env python3
import torch
import torch.cuda.profiler as profiler
from apex import pyprof
#The following creates an object "foo" of type ScriptModule
#The new object has a function called "forward"
@torch.jit.script
def foo(x, y):
return torch.sigmoid(x) + y
#Initialize pyprof after the JIT step
pyprof.nv... | 620 | 19.032258 | 59 | py |
ELLE | ELLE-main/apex/apex/pyprof/examples/jit/jit_trace_function.py | #!/usr/bin/env python3
import torch
import torch.cuda.profiler as profiler
from apex import pyprof
def foo(x, y):
return torch.sigmoid(x) + y
x = torch.zeros(4,4).cuda()
y = torch.ones(4,4).cuda()
#JIT the function using tracing
#This returns an object of type ScriptModule with a forward method.
traced_foo = torch... | 675 | 20.806452 | 67 | py |
ELLE | ELLE-main/apex/apex/pyprof/examples/jit/jit_script_method.py | #!/usr/bin/env python3
import torch
import torch.cuda.profiler as profiler
from apex import pyprof
class Foo(torch.jit.ScriptModule):
def __init__(self, size):
super(Foo, self).__init__()
self.n = torch.nn.Parameter(torch.ones(size))
self.m = torch.nn.Parameter(torch.ones(size))
@torc... | 689 | 20.5625 | 53 | py |
ELLE | ELLE-main/apex/apex/pyprof/examples/apex/fused_layer_norm.py | import torch
import fused_layer_norm_cuda
from apex.normalization import FusedLayerNorm
from apex import pyprof
pyprof.nvtx.init()
pyprof.nvtx.wrap(fused_layer_norm_cuda, 'forward')
pyprof.nvtx.wrap(fused_layer_norm_cuda, 'backward')
pyprof.nvtx.wrap(fused_layer_norm_cuda, 'forward_affine')
pyprof.nvtx.wrap(fused_laye... | 790 | 26.275862 | 69 | py |
ELLE | ELLE-main/apex/apex/pyprof/examples/apex/fused_adam.py | import torch
import fused_adam_cuda
from apex.optimizers import FusedAdam, FP16_Optimizer
from apex import pyprof
pyprof.nvtx.init()
pyprof.nvtx.wrap(fused_adam_cuda, 'adam')
model = torch.nn.Linear(10, 20).cuda().half()
criterion = torch.nn.CrossEntropyLoss().cuda()
optimizer = FusedAdam(model.parameters())
optimize... | 546 | 25.047619 | 61 | py |
ELLE | ELLE-main/apex/apex/pyprof/examples/custom_func_module/custom_module.py | #!/usr/bin/env python3
import torch
import torch.cuda.profiler as profiler
from apex import pyprof
pyprof.nvtx.init()
class Foo(torch.nn.Module):
def __init__(self, size):
super(Foo, self).__init__()
self.n = torch.nn.Parameter(torch.ones(size))
self.m = torch.nn.Parameter(torch.ones(size)... | 601 | 20.5 | 53 | py |
ELLE | ELLE-main/apex/apex/pyprof/examples/custom_func_module/custom_function.py | #!/usr/bin/env python3
import torch
import torch.cuda.profiler as profiler
from apex import pyprof
#Initialize pyprof
pyprof.nvtx.init()
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, in1, in2):
out = in1 + in2 #This could be a custom C/C++ function.
return out
@staticmethod
def backward... | 762 | 21.441176 | 58 | py |
ELLE | ELLE-main/apex/apex/pyprof/examples/user_annotation/resnet.py | #!/usr/bin/env python3
"""
An example showing use of nested NVTX markers.
"""
import torch
import torch.nn as nn
import torch.cuda.profiler as profiler
import torch.cuda.nvtx as nvtx
from apex import pyprof
pyprof.nvtx.init()
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution wi... | 5,660 | 25.208333 | 90 | py |
ELLE | ELLE-main/apex/apex/pyprof/parse/nvvp.py | import sys
class NVVP(object):
"""
This class gets kernel information from the SQL (nvvp) database.
"""
driverT = "CUPTI_ACTIVITY_KIND_DRIVER"
runtimeT = "CUPTI_ACTIVITY_KIND_RUNTIME"
kernelT = "CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL"
markerT = "CUPTI_ACTIVITY_KIND_MARKER"
stringT = "StringTable"
def __init_... | 8,803 | 30.109541 | 192 | py |
ELLE | ELLE-main/apex/apex/pyprof/parse/parse.py | #!/usr/bin/env python3
"""
Parse the SQL db and print a dictionary for every kernel.
"""
import sys
import argparse
from tqdm import tqdm
from .db import DB
from .kernel import Kernel
from .nvvp import NVVP
def parseArgs():
parser = argparse.ArgumentParser(prog=sys.argv[0], description="Parse SQL (nvvp) db.")
par... | 2,907 | 22.642276 | 156 | py |
ELLE | ELLE-main/apex/apex/pyprof/parse/kernel.py | import cxxfilt, struct, binascii
#Helper functions
def demangle(name):
"""
Demangle a C++ string
"""
return cxxfilt.demangle(name)
def encode_object_id(pid, tid):
"""
Given process id (pid) and thread id (tid), return the object id.
object id = pid (little endian 4 bytes) + tid (little endian 8 bytes)
"""
o... | 5,286 | 24.056872 | 175 | py |
ELLE | ELLE-main/apex/apex/pyprof/prof/embedding.py | from collections import OrderedDict
from .utility import Utility
from .base import OperatorLayerBase
class Embedding(OperatorLayerBase):
def __init__(self, d):
marker = eval(d.argMarker[0])
mod = marker['mod']
op = marker['op']
args = marker['args']
self.marker = marker
self.mod_ = mod
self.op_ = op
... | 1,409 | 18.583333 | 105 | py |
ELLE | ELLE-main/apex/apex/pyprof/prof/pooling.py | from .collections import OrderedDict
from .utility import Utility
# Work in progress.
#poolFuncs = ["max_pool2d_with_indices_forward", "max_pool2d_with_indices"]
class MaxPool2d(object):
def parse(marker):
def convert2Tuple(arg):
assert (arg['type'] in ["int", "tuple"])
if arg['type'] == "int":
return ... | 1,459 | 23.333333 | 75 | py |
ELLE | ELLE-main/apex/apex/pyprof/prof/reduction.py | from collections import OrderedDict
from .utility import Utility
from .base import OperatorLayerBase
class Mean(OperatorLayerBase):
def __init__(self, d):
marker = eval(d.argMarker[0])
mod = marker['mod']
op = marker['op']
args = marker['args']
self.marker = marker
self.mod_ = mod
self.op_ = op
self... | 2,788 | 17.470199 | 76 | py |
ELLE | ELLE-main/apex/apex/pyprof/prof/base.py | from abc import ABC, abstractmethod
class OperatorLayerBase(ABC):
"""
Base class for all layers and operators.
Every derived class should have the following functions.
"""
@abstractmethod
def tc(self):
"""
Tensor core usage by the kernel.
Return "1" (yes), "0" (no, but possible), "-" (not applicable)
""... | 742 | 14.479167 | 64 | py |
ELLE | ELLE-main/apex/apex/pyprof/prof/randomSample.py | from collections import OrderedDict
from .utility import Utility
from .base import OperatorLayerBase
class RandPerm(OperatorLayerBase):
def __init__(self, d):
marker = eval(d.argMarker[0])
mod = marker['mod']
op = marker['op']
args = marker['args']
self.marker = marker
self.mod_ = mod
self.op_ = op
... | 817 | 17.590909 | 64 | py |
ELLE | ELLE-main/apex/apex/pyprof/prof/softmax.py | from collections import OrderedDict
from .utility import Utility
from .base import OperatorLayerBase
class Softmax(OperatorLayerBase):
def __init__(self, d):
marker = eval(d.argMarker[0])
mod = marker['mod']
op = marker['op']
args = marker['args']
self.marker = marker
self.mod_ = mod
self.op_ = op
s... | 2,190 | 17.887931 | 61 | py |
ELLE | ELLE-main/apex/apex/pyprof/prof/activation.py | from collections import OrderedDict
from .utility import Utility
from .base import OperatorLayerBase
class Activation(OperatorLayerBase):
"""
This class handles the various activation functions.
"""
ops = ["celu", "elu", "elu_", "hardshrink", "hardtanh", "hardtanh_", "leaky_relu", "leaky_relu_", "logsigmoid", "pr... | 1,520 | 22.045455 | 272 | py |
ELLE | ELLE-main/apex/apex/pyprof/prof/prof.py | #!/usr/bin/env python3
"""
This script reads the output (Python dictionary) created by parse.py.
For every kernel (line) in the input it determines
module / class name e.g. torch.nn.functional
operator name e.g. linear
kernel parameters e.g. GEMM M, N, K, datatype
bytes
flops
tensor core usage
direction (fprop,... | 4,967 | 18.330739 | 108 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.