python_code stringlengths 0 1.02M | repo_name stringlengths 9 48 | file_path stringlengths 5 114 |
|---|---|---|
import ast
import sys
from typing import List, Optional, Tuple
from ._importlib import _resolve_name
class _ExtractModuleReferences(ast.NodeVisitor):
"""
Extract the list of global variables a block of code will read and write
"""
@classmethod
def run(cls, src: str, package: str) -> List[Tuple[s... | pytorch-master | torch/package/find_file_dependencies.py |
"""isort:skip_file"""
from pickle import ( # type: ignore[attr-defined]
_compat_pickle,
_extension_registry,
_getattribute,
_Pickler,
EXT1,
EXT2,
EXT4,
GLOBAL,
Pickler,
PicklingError,
STACK_GLOBAL,
)
from struct import pack
from types import FunctionType
from .importer impo... | pytorch-master | torch/package/_package_pickler.py |
import _warnings
import os.path
# note: implementations
# copied from cpython's import code
# _zip_searchorder defines how we search for a module in the Zip
# archive: we first search for a package __init__, then for
# non-package .pyc, and .py entries. The .pyc entries
# are swapped by initzipimport() if we run in ... | pytorch-master | torch/package/_importlib.py |
import os.path
from glob import glob
from typing import cast
import torch
from torch.types import Storage
# because get_storage_from_record returns a tensor!?
class _HasStorage(object):
def __init__(self, storage):
self._storage = storage
def storage(self):
return self._storage
class Direct... | pytorch-master | torch/package/_directory_reader.py |
from collections import deque
from typing import List, Set
class DiGraph:
"""Really simple unweighted directed graph data structure to track dependencies.
The API is pretty much the same as networkx so if you add something just
copy their API.
"""
def __init__(self):
# Dict of node -> di... | pytorch-master | torch/package/_digraph.py |
import sys
from typing import Any, Callable, Iterable, List, Tuple
__all__ = ["trace_dependencies"]
def trace_dependencies(
callable: Callable[[Any], Any], inputs: Iterable[Tuple[Any, ...]]
) -> List[str]:
"""Trace the execution of a callable in order to determine which modules it uses.
Args:
ca... | pytorch-master | torch/package/analyze/trace_dependencies.py |
from typing import Dict, List
from ..package_exporter import PackagingError
__all__ = ["find_first_use_of_broken_modules"]
def find_first_use_of_broken_modules(exc: PackagingError) -> Dict[str, List[str]]:
"""
Find all broken modules in a PackagingError, and for each one, return the
dependency path in w... | pytorch-master | torch/package/analyze/find_first_use_of_broken_modules.py |
from .find_first_use_of_broken_modules import find_first_use_of_broken_modules
from .trace_dependencies import trace_dependencies
| pytorch-master | torch/package/analyze/__init__.py |
from types import ModuleType
from typing import Any
from .._mangling import is_mangled
def is_from_package(obj: Any) -> bool:
"""
Return whether an object was loaded from a package.
Note: packaged objects from externed modules will return ``False``.
"""
if type(obj) == ModuleType:
return... | pytorch-master | torch/package/analyze/is_from_package.py |
#!/usr/bin/env python3
## @package process
# Module doxygen.process
# Script to insert preamble for doxygen and regen API docs
import os
import shutil
# Module caffe2...caffe2.python.control_test
def insert(originalfile, first_line, description):
with open(originalfile, 'r') as f:
f1 = f.readline()
... | pytorch-master | docs/caffe2/process.py |
# -*- 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
# autogenerated file.
#
# A... | pytorch-master | docs/source/conf.py |
"""
This script will generate input-out plots for all of the activation
functions. These are for use in the documentation, and potentially in
online tutorials.
"""
from pathlib import Path
import torch
import matplotlib
from matplotlib import pyplot as plt
matplotlib.use("Agg")
# Create a directory for the images,... | pytorch-master | docs/source/scripts/build_activation_images.py |
"""
This script will generate default values of quantization configs.
These are for use in the documentation.
"""
import torch
from torch.ao.quantization.backend_config import get_native_backend_config_dict
from torch.ao.quantization.backend_config.utils import (
entry_to_pretty_str,
remove_boolean_dispatch_fr... | pytorch-master | docs/source/scripts/build_quantization_configs.py |
"""
This script generates a CSV table with all ATen operators
supported by `torch.onnx.export`. The generated table is included by
docs/source/onnx_supported_aten_list.rst.
"""
import os
from torch.onnx import _onnx_supported_ops
# Constants
BUILD_DIR = "build"
AUTO_GEN_ATEN_OPS_CSV_FILE = "auto_gen_aten_op_list.csv"... | pytorch-master | docs/source/scripts/onnx/build_onnx_supported_aten_op_csv_table.py |
# -*- 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
# autogenerated file.
#
# A... | pytorch-master | docs/cpp/source/conf.py |
import torch
import torchvision
from torch.backends._coreml.preprocess import (
CompileSpec,
TensorSpec,
CoreMLComputeUnit,
)
def mobilenetv2_spec():
return {
"forward": CompileSpec(
inputs=(
TensorSpec(
shape=[1, 3, 224, 224],
),... | pytorch-master | ios/TestApp/benchmark/coreml_backend.py |
import torch
import torchvision
from torch.utils.mobile_optimizer import optimize_for_mobile
model = torchvision.models.mobilenet_v2(pretrained=True)
model.eval()
example = torch.rand(1, 3, 224, 224)
traced_script_module = torch.jit.trace(model, example)
optimized_scripted_module = optimize_for_mobile(traced_script_mo... | pytorch-master | ios/TestApp/benchmark/trace_model.py |
import torch
import torchvision
import yaml
model = torchvision.models.mobilenet_v2(pretrained=True)
model.eval()
example = torch.rand(1, 3, 224, 224)
traced_script_module = torch.jit.trace(model, example)
ops = torch.jit.export_opnames(traced_script_module)
with open('mobilenetv2.yaml', 'w') as output:
yaml.dump(... | pytorch-master | ios/TestApp/custom_build/custom_build.py |
#!/usr/bin/env python3
from __future__ import print_function
import os
CPUINFO_SOURCES = {
None: [
"init.c",
"api.c",
"cache.c",
],
"defined(__linux__)": [
"linux/multiline.c",
"linux/cpulist.c",
"linux/mockfile.c",
"linux/smallfile.c",
"lin... | pytorch-master | third_party/generate-cpuinfo-wrappers.py |
#!/usr/bin/env python3
import argparse
import os
mydir = os.path.dirname(__file__)
licenses = {'LICENSE', 'LICENSE.txt', 'LICENSE.rst', 'COPYING.BSD'}
def collect_license(current):
collected = {}
for root, dirs, files in os.walk(current):
license = list(licenses & set(files))
if license:
... | pytorch-master | third_party/build_bundled.py |
#!/usr/bin/env python3
from __future__ import print_function
import collections
import os
import sys
BANNER = "Auto-generated by generate-wrappers.py script. Do not modify"
WRAPPER_SRC_NAMES = {
"PROD_SCALAR_PORTABLE_MICROKERNEL_SRCS": None,
"PROD_SCALAR_AARCH32_MICROKERNEL_SRCS" : "defined(__arm__)",
"PR... | pytorch-master | third_party/generate-xnnpack-wrappers.py |
#!/usr/bin/env python3
import argparse
import ast
from caffe2.python.model_helper import ModelHelper
from caffe2.python.predictor import mobile_exporter
from caffe2.python import workspace, brew
def parse_kwarg(kwarg_str):
key, value = kwarg_str.split('=')
try:
value = ast.literal_eval(value)
ex... | pytorch-master | binaries/bench_gen/bench_gen.py |
"""Scribe Uploader for Pytorch Benchmark Data
Currently supports data in pytest-benchmark format but can be extended.
New fields can be added just by modifying the schema in this file, schema
checking is only here to encourage reusing existing fields and avoiding typos.
"""
import argparse
import time
import json
im... | pytorch-master | benchmarks/upload_scribe.py |
import argparse
import json
from collections import namedtuple
Result = namedtuple("Result", ["name", "base_time", "diff_time"])
def construct_name(fwd_bwd, test_name):
bwd = 'backward' in fwd_bwd
suite_name = fwd_bwd.replace('-backward', '')
return '{suite}[{test}]:{fwd_bwd}'.format(suite=suite_name, tes... | pytorch-master | benchmarks/compare-fastrnn-results.py |
import torch
import argparse
from common import SubTensor, WithTorchFunction, SubWithTorchFunction # noqa: F401
Tensor = torch.tensor
NUM_REPEATS = 1000000
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Run the torch.add for a given class a given number of times."
)
pa... | pytorch-master | benchmarks/overrides_benchmark/pyspybench.py |
import torch
import time
import argparse
from common import SubTensor, WithTorchFunction, SubWithTorchFunction
NUM_REPEATS = 1000
NUM_REPEAT_OF_REPEATS = 1000
def bench(t1, t2):
bench_times = []
for _ in range(NUM_REPEAT_OF_REPEATS):
time_start = time.time()
for _ in range(NUM_REPEATS):
... | pytorch-master | benchmarks/overrides_benchmark/bench.py |
import torch
NUM_REPEATS = 1000
NUM_REPEAT_OF_REPEATS = 1000
class SubTensor(torch.Tensor):
pass
class WithTorchFunction:
def __init__(self, data, requires_grad=False):
if isinstance(data, torch.Tensor):
self._tensor = data
return
self._tensor = torch.tensor(data, r... | pytorch-master | benchmarks/overrides_benchmark/common.py |
from caffe2.python import workspace, core
import numpy as np
from utils import NUM_LOOP_ITERS
workspace.GlobalInit(['caffe2'])
def add_blob(ws, blob_name, tensor_size):
blob_tensor = np.random.randn(*tensor_size).astype(np.float32)
ws.FeedBlob(blob_name, blob_tensor)
class C2SimpleNet(object):
"""
T... | pytorch-master | benchmarks/framework_overhead_benchmark/C2Module.py |
import time
from collections import namedtuple
from torch.utils import ThroughputBenchmark
NUM_LOOP_ITERS = 1000
BenchmarkConfig = namedtuple('BenchmarkConfig', 'num_warmup_iters num_iters')
ModuleConfig = namedtuple('ModuleConfig', 'pt_fn c2_op num_params graph_mode')
def ms_to_us(time_ms):
return (time_ms * 1e3... | pytorch-master | benchmarks/framework_overhead_benchmark/utils.py |
import torch
from utils import NUM_LOOP_ITERS
def add_tensors_loop(x, y):
z = torch.add(x, y)
for i in range(NUM_LOOP_ITERS):
z = torch.add(z, x)
return z
class SimpleAddModule(torch.nn.Module):
def __init__(self, add_op):
super(SimpleAddModule, self).__init__()
self.add_op = a... | pytorch-master | benchmarks/framework_overhead_benchmark/SimpleAddModule.py |
from utils import ms_to_us, benchmark_module, BenchmarkConfig, ModuleConfig
import argparse
from C2Module import C2SimpleNet
from SimpleAddModule import SimpleAddModule, add_tensors_loop
from pt_wrapper_module import WrapperModule
""" Framework overhead benchmark script.
Benchmark framework overhead.
Currently suppor... | pytorch-master | benchmarks/framework_overhead_benchmark/framework_overhead_benchmark.py |
import torch
class WrapperModule(object):
""" Wraps the instance of wrapped_type.
For graph_mode traces the instance of wrapped_type.
Randomaly initializes num_params tensors with single float element.
Args:
wrapped_type:
- Object type to be wrapped.
Expects the wrap... | pytorch-master | benchmarks/framework_overhead_benchmark/pt_wrapper_module.py |
import pytest
import torch
from .fuser import set_fuser
from .runner import get_nn_runners
@pytest.fixture(scope='class')
def modeldef(request, net_name, executor, fuser):
set_fuser(fuser, executor)
# Given a 'net_name' provided by generate_tests, build the thing
name, rnn_creator, context = get_nn_runner... | pytorch-master | benchmarks/fastrnns/test_bench.py |
import pytest # noqa: F401
default_rnns = ['cudnn', 'aten', 'jit', 'jit_premul', 'jit_premul_bias', 'jit_simple',
'jit_multilayer', 'py']
default_cnns = ['resnet18', 'resnet18_jit', 'resnet50', 'resnet50_jit']
all_nets = default_rnns + default_cnns
def pytest_generate_tests(metafunc):
# ... | pytorch-master | benchmarks/fastrnns/conftest.py |
from collections import namedtuple
from functools import partial
import torch
import torchvision.models as cnn
from .factory import (dropoutlstm_creator, imagenet_cnn_creator,
layernorm_pytorch_lstm_creator, lnlstm_creator,
lstm_creator, lstm_multilayer_creator,
... | pytorch-master | benchmarks/fastrnns/runner.py |
import torch
def set_fuser(fuser_name, executor_name):
assert fuser_name in ['te', 'old', 'none', 'default']
if fuser_name == 'te':
torch._C._jit_set_profiling_executor(True)
torch._C._get_graph_executor_optimize(True)
torch._C._jit_override_can_fuse_on_cpu(False)
torch._C._jit_... | pytorch-master | benchmarks/fastrnns/fuser.py |
import torch
import torch.nn as nn
from torch.nn import Parameter
import torch.jit as jit
import warnings
from collections import namedtuple
from typing import List, Tuple
from torch import Tensor
import numbers
'''
Some helper classes for writing custom TorchScript LSTMs.
Goals:
- Classes are easy to read, use, and ... | pytorch-master | benchmarks/fastrnns/custom_lstms.py |
import argparse
import subprocess
import sys
import time
import torch
import datetime
from .runner import get_nn_runners
def run_rnn(name, rnn_creator, nloops=5,
seqLength=100, numLayers=1, inputSize=512, hiddenSize=512,
miniBatch=64, device='cuda', seed=None):
def run_iter(modeldef):
... | pytorch-master | benchmarks/fastrnns/profile.py |
from .cells import * # noqa: F403
from .factory import * # noqa: F403
# (output, next_state) = cell(input, state)
seqLength = 100
numLayers = 2
inputSize = 512
hiddenSize = 512
miniBatch = 64
| pytorch-master | benchmarks/fastrnns/__init__.py |
import argparse
import torch
import torch.nn as nn
from .factory import pytorch_lstm_creator, varlen_pytorch_lstm_creator
from .runner import get_nn_runners
def barf():
import pdb
pdb.set_trace()
def assertEqual(tensor, expected, threshold=0.001):
if isinstance(tensor, list) or isinstance(tensor, tuple... | pytorch-master | benchmarks/fastrnns/test.py |
import torch
@torch.jit.script
def fn(x, scale, shift):
return scale * x / shift
@torch.jit.script
def recurrent(x, scale, shift):
y = x
for i in range(100):
y = fn(y, scale, shift)
return y
x = torch.randn(2, 2, device='cuda')
scale = torch.randn(2, 2, device='cuda', requires_grad=True)
s... | pytorch-master | benchmarks/fastrnns/scratch.py |
import torch
from collections import namedtuple
from typing import List, Tuple
from torch import Tensor
from .cells import lstm_cell, premul_lstm_cell, premul_lstm_cell_no_bias, flat_lstm_cell
# list[list[T]] -> list[T]
def flatten_list(lst):
result = []
for inner in lst:
result.extend(inner)
re... | pytorch-master | benchmarks/fastrnns/factory.py |
import argparse
from collections import namedtuple
import torch
import gc
import sys
import json
import copy
import time
from torch.autograd.profiler import record_function
from .fuser import set_fuser
from .runner import get_nn_runners
BenchResult = namedtuple('BenchResult', [
'name', 'avg_fwd', 'std_fwd', 'inf... | pytorch-master | benchmarks/fastrnns/bench.py |
import torch
from typing import Tuple
from torch import Tensor
def milstm_cell(x, hx, cx, w_ih, w_hh, alpha, beta_i, beta_h, bias):
Wx = x.mm(w_ih.t())
Uz = hx.mm(w_hh.t())
# Section 2.1 in https://arxiv.org/pdf/1606.06630.pdf
gates = (alpha * Wx * Uz + beta_i * Wx + beta_h * Uz + bias)
# Same a... | pytorch-master | benchmarks/fastrnns/cells.py |
import torch
from torch.utils.data import Dataset
def collate_sentences_lm(samples):
if len(samples) == 0:
return {}
id = torch.LongTensor([s["id"] for s in samples])
src_tokens = torch.stack([s["source"] for s in samples], 0)
tgt_tokens = torch.stack([s["target"] for s in samples], 0)
n... | pytorch-master | benchmarks/distributed/pipeline/benchmark_dataset.py |
import argparse
import math
import os
import time
from benchmark_dataset import BenchmarkLMDataset, collate_sentences_lm
import torch
from torch.distributed import rpc
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.distributed.pipeline.sync import Pipe
from torch.distributed.pipeline.sync.ut... | pytorch-master | benchmarks/distributed/pipeline/pipe.py |
#!/usr/bin/env python3
#
# Measure distributed training iteration time.
#
# This program performs a sweep over a) a number of model architectures, and
# b) an increasing number of processes. This produces a 1-GPU baseline,
# an 8-GPU baseline (if applicable), as well as measurements for however
# many processes can par... | pytorch-master | benchmarks/distributed/ddp/benchmark.py |
#!/usr/bin/env python3
#
# Computes difference between measurements produced by ./benchmark.py.
#
import argparse
import json
import numpy as np
def load(path):
with open(path, 'r') as f:
return json.load(f)
def main():
parser = argparse.ArgumentParser(description='PyTorch distributed benchmark di... | pytorch-master | benchmarks/distributed/ddp/diff.py |
import functools
import torch
import torch.distributed as dist
import torch.nn as nn
class PythonDDP(nn.Module):
"""
Python only implementation for DistributedDataParallel module.
Unlike the production DistributedDataParallel which relies on many C++ core
utils to manage gradient distribution and redu... | pytorch-master | benchmarks/distributed/ddp/compare/python_ddp.py |
"""
A simple tool to compare the performance of different impls of
DistributedDataParallel on resnet50, three flavors:
1. DistributedDataParallel, which has a python wrapper and C++ core to do
gradient distribution and reduction. It's current production version.
2. PythonDDP with async gradient reduction.
3. Pyth... | pytorch-master | benchmarks/distributed/ddp/compare/compare_ddp.py |
import torch
RPC_SPARSE = "rpc_sparse"
RPC_DENSE = "rpc_dense"
def sparse_tensor_to_rpc_format(sparse_tensor):
r"""
A helper function creates a list containing the indices, values, and size
of a coalesced sparse tensor.
Args:
sparse_tensor (torch.Tensor): sparse_coo_tensor represented as a li... | pytorch-master | benchmarks/distributed/rpc/parameter_server/utils.py |
import argparse
import json
import os
from pathlib import Path
from data import data_map
from metrics.ProcessedMetricsPrinter import ProcessedMetricsPrinter
from models import model_map
from server import server_map
from trainer import (
criterion_map,
ddp_hook_map,
ddp_model_map,
hook_state_map,
i... | pytorch-master | benchmarks/distributed/rpc/parameter_server/launcher.py |
import statistics
import pandas as pd
from tabulate import tabulate
class ProcessedMetricsPrinter:
def print_data_frame(self, name, processed_metrics):
print(f"metrics for {name}")
data_frame = self.get_data_frame(processed_metrics)
print(tabulate(data_frame, showindex=False, headers=dat... | pytorch-master | benchmarks/distributed/rpc/parameter_server/metrics/ProcessedMetricsPrinter.py |
from .CPUMetric import CPUMetric
from .CUDAMetric import CUDAMetric
class MetricsLogger:
def __init__(self, rank=None):
self.rank = rank
self.metrics = {}
def record_start(self, type, key, name, cuda):
if type in self.metrics and key in self.metrics[type]:
raise RuntimeEr... | pytorch-master | benchmarks/distributed/rpc/parameter_server/metrics/MetricsLogger.py |
import time
from .MetricBase import MetricBase
class CPUMetric(MetricBase):
def __init__(self, name: str):
self.name = name
self.start = None
self.end = None
def record_start(self):
self.start = time.time()
def record_end(self):
self.end = time.time()
def el... | pytorch-master | benchmarks/distributed/rpc/parameter_server/metrics/CPUMetric.py |
from abc import ABC, abstractmethod
class MetricBase(ABC):
def __init__(self, name):
self.name = name
self.start = None
self.end = None
@abstractmethod
def record_start(self):
return
@abstractmethod
def record_end(self):
return
@abstractmethod
def... | pytorch-master | benchmarks/distributed/rpc/parameter_server/metrics/MetricBase.py |
import torch
from .MetricBase import MetricBase
class CUDAMetric(MetricBase):
def __init__(self, rank: int, name: str):
self.rank = rank
self.name = name
self.start = None
self.end = None
def record_start(self):
self.start = torch.cuda.Event(enable_timing=True)
... | pytorch-master | benchmarks/distributed/rpc/parameter_server/metrics/CUDAMetric.py |
import functools
import threading
import time
from abc import ABC, abstractmethod
from metrics.MetricsLogger import MetricsLogger
from utils import sparse_rpc_format_to_tensor, sparse_tensor_to_rpc_format
import torch
import torch.distributed.rpc as rpc
class ParameterServerBase(ABC):
PARAMETER_SERVER_BATCH_ME... | pytorch-master | benchmarks/distributed/rpc/parameter_server/server/server.py |
from .server import AverageBatchParameterServer, AverageParameterServer
server_map = {
"AverageParameterServer": AverageParameterServer,
"AverageBatchParameterServer": AverageBatchParameterServer
}
| pytorch-master | benchmarks/distributed/rpc/parameter_server/server/__init__.py |
from .DummyModel import DummyModel
model_map = {
"DummyModel": DummyModel
}
| pytorch-master | benchmarks/distributed/rpc/parameter_server/models/__init__.py |
import torch.nn as nn
import torch.nn.functional as F
class DummyModel(nn.Module):
def __init__(
self,
num_embeddings: int,
embedding_dim: int,
dense_input_size: int,
dense_output_size: int,
dense_layers_count: int,
sparse: bool
):
r"""
A... | pytorch-master | benchmarks/distributed/rpc/parameter_server/models/DummyModel.py |
import random
import numpy as np
import torch
from torch.utils.data import Dataset
class DummyData(Dataset):
def __init__(
self,
max_val: int,
sample_count: int,
sample_length: int,
sparsity_percentage: int
):
r"""
A data class that generates random d... | pytorch-master | benchmarks/distributed/rpc/parameter_server/data/DummyData.py |
from .DummyData import DummyData
data_map = {
"DummyData": DummyData
}
| pytorch-master | benchmarks/distributed/rpc/parameter_server/data/__init__.py |
def preprocess_dummy_data(rank, data):
r"""
A function that moves the data from CPU to GPU
for DummyData class.
Args:
rank (int): worker rank
data (list): training examples
"""
for i in range(len(data)):
data[i][0] = data[i][0].cuda(rank)
data[i][1] = data[i][1].c... | pytorch-master | benchmarks/distributed/rpc/parameter_server/trainer/preprocess_data.py |
from utils import process_bucket_with_remote_server
import torch
import torch.distributed as c10d
def allreduce_hook(state, bucket):
r"""
A ddp communication hook that uses the process_group allreduce implementation.
Args:
state (object): maintains state during the training process
bucket... | pytorch-master | benchmarks/distributed/rpc/parameter_server/trainer/hooks.py |
import torch.nn as nn
def cel(rank):
r"""A function that creates a CrossEntropyLoss
criterion for training.
Args:
rank (int): worker rank
"""
return nn.CrossEntropyLoss().cuda(rank)
| pytorch-master | benchmarks/distributed/rpc/parameter_server/trainer/criterions.py |
from .criterions import cel
from .ddp_models import basic_ddp_model
from .hook_states import BasicHookState
from .hooks import allreduce_hook, hybrid_hook, rpc_hook, sparse_rpc_hook
from .iteration_steps import basic_iteration_step
from .preprocess_data import preprocess_dummy_data
from .trainer import DdpTrainer
crit... | pytorch-master | benchmarks/distributed/rpc/parameter_server/trainer/__init__.py |
def basic_iteration_step(self, ddp_model, criterion, optimizer, hook_state, epoch, index, batch):
r"""
A function that performs an iteration of training.
Args:
ddp_model (nn.Module): distributed data parallel model
criterion (nn.Module): loss function to measure model
optimizer (opti... | pytorch-master | benchmarks/distributed/rpc/parameter_server/trainer/iteration_steps.py |
from torch.nn.parallel import DistributedDataParallel as DDP
def basic_ddp_model(self, rank, model, process_group, hook_state, hook):
r"""
A function that creates a ddp_model and hook_state objects.
The ddp model is initialized with a single device id and
the process group. The ddp_model also register... | pytorch-master | benchmarks/distributed/rpc/parameter_server/trainer/ddp_models.py |
import functools
import time
from abc import ABC, abstractmethod
from metrics.MetricsLogger import MetricsLogger
import torch
class TrainerBase(ABC):
BATCH_LEVEL_METRIC = "batch_level_metric"
BATCH_ALL = "batch_all"
FORWARD_METRIC = "forward_metric"
FORWARD_PASS = "forward_pass"
BACKWARD_METRIC... | pytorch-master | benchmarks/distributed/rpc/parameter_server/trainer/trainer.py |
class BasicHookState:
def __init__(self, cref, process_group):
r"""
A class that holds state information that is needed by the communication hook
during the training algorithm.
Args:
cref (DdpTrainer): reference to the self keyword of the trainer instance
pro... | pytorch-master | benchmarks/distributed/rpc/parameter_server/trainer/hook_states.py |
import random
import time
import torch
import torch.distributed.rpc as rpc
from torch.distributed.rpc import rpc_sync
from agent import AgentBase
class ObserverBase:
def __init__(self):
r"""
Inits observer class
"""
self.id = rpc.get_worker_info().id
def set_state(self, stat... | pytorch-master | benchmarks/distributed/rpc/rl/observer.py |
import numpy as np
import time
import torch
import torch.distributed.rpc as rpc
from agent import AgentBase
from observer import ObserverBase
COORDINATOR_NAME = "coordinator"
AGENT_NAME = "agent"
OBSERVER_NAME = "observer{}"
EPISODE_STEPS = 100
class CoordinatorBase:
def __init__(self, batch_size, batch, stat... | pytorch-master | benchmarks/distributed/rpc/rl/coordinator.py |
from functools import reduce
import time
import threading
import torch
from torch.distributions import Categorical
import torch.distributed.rpc as rpc
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
OBSERVER_NAME = "observer{}"
class Policy(nn.Module):
def __init__(self, in_fe... | pytorch-master | benchmarks/distributed/rpc/rl/agent.py |
import argparse
import os
import time
import json
import torch.distributed.rpc as rpc
import torch.multiprocessing as mp
from coordinator import CoordinatorBase
COORDINATOR_NAME = "coordinator"
AGENT_NAME = "agent"
OBSERVER_NAME = "observer{}"
TOTAL_EPISODES = 10
TOTAL_EPISODE_STEPS = 100
def str2bool(v):
if... | pytorch-master | benchmarks/distributed/rpc/rl/launcher.py |
from . import benchmark
import numpy as np
class MatMulBench(benchmark.Benchmark):
def __init__(self, mode, device, dtype, B, M, N, K):
super().__init__(mode, device, dtype)
self.B = B
self.M = M
self.N = N
self.K = K
self.d1 = self.rand([B, M, N], device=device, dt... | pytorch-master | benchmarks/tensorexpr/matmul.py |
# This is a copy of rnn_attention from MLPerf, with some common sizes hardcoded
# for benchmarking and some control flow stripped out.
# https://github.com/mlperf/training/blob/master/rnn_translator/pytorch/seq2seq/models/attention.py
from . import benchmark
import torch
class BahdanauAttention(benchmark.Benchmark):... | pytorch-master | benchmarks/tensorexpr/attention.py |
import contextlib
import numpy as np
import os
import time
from . import tensor_engine
import torch
import json
class Benchmark(object):
def __init__(self, mode, device, dtype):
self.mode = mode
self.deterministic = False
self.device = device
self.dtype = dtype
self.output_... | pytorch-master | benchmarks/tensorexpr/benchmark.py |
from . import benchmark
import torch
class RNNEltwise(benchmark.Benchmark):
def __init__(self, mode, device, dtype, b, hs):
super().__init__(mode, device, dtype)
self.b = b
self.hs = hs
self.input = self.rand(
[b, 4 * hs], device=device, dtype=dtype, requires_grad=self.r... | pytorch-master | benchmarks/tensorexpr/rnn_eltwise.py |
from . import benchmark
class ReduceBench(benchmark.Benchmark):
def __init__(self, mode, device, dtype, case, M, N, K, skip_input_transform):
super().__init__(mode, device, dtype)
self.case = case
self.M = M
self.N = N
self.K = K
self._set_skip_input_transform(skip_... | pytorch-master | benchmarks/tensorexpr/reduction.py |
from . import benchmark
import numpy as np
import torch
class Concat2D2InputBench(benchmark.Benchmark):
def __init__(self, mode, device, dtype, I1_D1, I1_D2, I2_D1, I2_D2, concat_dim):
super().__init__(mode, device, dtype)
self.I1_D1 = I1_D1
self.I1_D2 = I1_D2
self.I2_D1 = I2_D1
... | pytorch-master | benchmarks/tensorexpr/concat.py |
tensor_engine = None
def unsupported(func):
def wrapper(self):
return func(self)
wrapper.is_supported = False
return wrapper
def is_supported(method):
if hasattr(method, "is_supported"):
return method.is_supported
return True
def set_engine_mode(mode):
global tensor_engine... | pytorch-master | benchmarks/tensorexpr/tensor_engine.py |
from . import benchmark
class PoolingBench(benchmark.Benchmark):
def __init__(self, case, mode, device, dtype, kernel_size, N, C, H, W):
super().__init__(mode, device)
self.case = case
self.kernel_size = kernel_size
self.N = N
self.C = C
self.H = H
self.W = ... | pytorch-master | benchmarks/tensorexpr/pooling.py |
from . import benchmark
import itertools
import numpy as np
import torch
import scipy.special
# A template class for elementwise operations.
# A derived class will override the class instance to customize its behavior.
class ElementBench(benchmark.Benchmark):
# List of customization class variables.
op_str = N... | pytorch-master | benchmarks/tensorexpr/elementwise.py |
import torch
import torch._C._te as te
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import argparse
class kernel_arena_scope(object):
def __enter__(self):
self.scope = te.KernelScope()
def __exit__(self, typ, val, traceback):
self.sco... | pytorch-master | benchmarks/tensorexpr/microbenchmarks.py |
import torch
class TorchTensorEngine(object):
def rand(self, shape, device=None, dtype=None, requires_grad=False):
return torch.rand(shape, device=device, dtype=dtype, requires_grad=requires_grad)
def randn(self, shape, device=None, dtype=None, requires_grad=False):
return torch.randn(shape, ... | pytorch-master | benchmarks/tensorexpr/pt_engine.py |
from . import benchmark
import torch
class SwishBench(benchmark.Benchmark):
def __init__(self, mode, device, dtype, M, N):
super().__init__(mode, device, dtype)
self.M = M
self.N = N
self.data = self.rand([M, N], device=device, dtype=dtype, requires_grad=self.requires_grad)
... | pytorch-master | benchmarks/tensorexpr/swish.py |
from . import benchmark
class ConvImplBench(benchmark.Benchmark):
def __init__(self, case, mode, device, dtype, kernel_size, N, iC, H, W, oC):
super().__init__(mode, device, dtype)
self.case = case
self.kernel_size = kernel_size
self.N = N
self.iC = iC
self.H = H
... | pytorch-master | benchmarks/tensorexpr/conv.py |
from . import benchmark
from . import tensor_engine
class NormalizationBench(benchmark.Benchmark):
def __init__(self, mode, device, dtype, N, C, H, W):
super().__init__(mode, device, dtype)
self.N = N
self.C = C
self.H = H
self.W = W
self.data = self.nchw_rand(
... | pytorch-master | benchmarks/tensorexpr/normalization.py |
from . import benchmark
import itertools
import numpy as np
import torch
class BroadcastMulBench(benchmark.Benchmark):
def __init__(self, mode, device, dtype, case, M, N, K):
super().__init__(mode, device, dtype)
self.case = case
self.M = M
self.N = N
self.K = K
if... | pytorch-master | benchmarks/tensorexpr/broadcast.py |
from . import benchmark
import scipy.special
class SoftmaxBench(benchmark.Benchmark):
def __init__(self, mode, device, dtype, M, N):
super().__init__(mode, device, dtype)
self.M = M
self.N = N
self.dtype = dtype
self.inputs = [self.randn(
[M, N], device=device, ... | pytorch-master | benchmarks/tensorexpr/softmax.py |
import argparse
import itertools
from . import benchmark
import os
from . import tensor_engine
from . import attention # noqa: F401
from . import broadcast # noqa: F401
from . import concat # noqa: F401
# from . import conv # noqa: F401
from . import elementwise # noqa: F401
from . impor... | pytorch-master | benchmarks/tensorexpr/__main__.py |
import torch
from pyarkbench import Benchmark, Timer, default_args
use_new = True
class Basic(Benchmark):
def benchmark(self):
x = [torch.ones(200, 200) for i in range(30)]
with Timer() as big1:
torch.save(x, "big_tensor.zip", _use_new_zipfile_serialization=use_new)
with Timer... | pytorch-master | benchmarks/serialization/simple_measurement.py |
"""Basic runner for the instruction count microbenchmarks.
The contents of this file are placeholders, and will be replaced by more
expressive and robust components (e.g. better runner and result display
components) in future iterations. However this allows us to excercise the
underlying benchmark generation infrastru... | pytorch-master | benchmarks/instruction_counts/main.py |
pytorch-master | benchmarks/instruction_counts/core/__init__.py | |
"""Type annotations for various benchmark objects."""
from typing import Any, Dict, Optional, Tuple, Union
from core.api import AutoLabels, TimerArgs, GroupedBenchmark
# =============================================================================
# == Benchmark schema ===============================================... | pytorch-master | benchmarks/instruction_counts/core/types.py |
"""Key enums and structs used to handle data flow within the benchmark."""
import dataclasses
import enum
import itertools as it
import re
import textwrap
from typing import Dict, List, Optional, Set, Tuple, Union, TYPE_CHECKING
from worker.main import WorkerTimerArgs
if TYPE_CHECKING:
# Benchmark utils are only ... | pytorch-master | benchmarks/instruction_counts/core/api.py |
import atexit
import shutil
import re
import textwrap
from typing import List, Optional, Tuple
from torch.utils.benchmark import _make_temp_dir
from core.api import GroupedBenchmark, TimerArgs
from core.types import Definition, FlatIntermediateDefinition, Label
_TEMPDIR: Optional[str] = None
def get_temp_dir() -> s... | pytorch-master | benchmarks/instruction_counts/core/utils.py |
"""Logic for converting human-readable benchmarks into executable form.
This is mostly string manipulation, with just a bit of importlib magic.
"""
import importlib.abc
import importlib.util
import itertools as it
import os
import re
import textwrap
from typing import List, Optional, Tuple, TYPE_CHECKING
import uuid
... | pytorch-master | benchmarks/instruction_counts/core/expand.py |
"""Run benchmarks while handling parallelism, isolation, and fault tolerance."""
import math
import multiprocessing
import subprocess
import textwrap
import threading
import time
from typing import Dict, List, Optional, Set, Tuple, Union
from execution.work import PYTHON_CMD, SHELL, InProgress, WorkOrder
from worker.m... | pytorch-master | benchmarks/instruction_counts/execution/runner.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.