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
pytorch
pytorch-main/benchmarks/sparse/spmv.py
import argparse import sys import torch from .utils import gen_sparse_csr, gen_sparse_coo, gen_sparse_coo_and_csr, Event def test_sparse_csr(m, nnz, test_count): start_timer = Event(enable_timing=True) stop_timer = Event(enable_timing=True) csr = gen_sparse_csr((m, m), nnz) vector = torch.randn(m, dty...
3,103
28.846154
80
py
pytorch
pytorch-main/benchmarks/sparse/utils.py
import torch import functools import random import operator import numpy as np import time # shim for torch.cuda.Event when running on cpu class Event: def __init__(self, enable_timing): pass def record(self): self.time = time.perf_counter() def elapsed_time(self, end_event): asse...
1,510
26.472727
72
py
pytorch
pytorch-main/benchmarks/sparse/benchmark_semi_structured_sparsity.py
import random import torch import torch.utils.benchmark as benchmark from torch import nn from tqdm import tqdm import pandas as pd import argparse from torch.sparse import to_sparse_semi_structured torch.set_printoptions( precision=2, threshold=None, edgeitems=16, linewidth=480, profile=None, ...
6,544
25.605691
87
py
pytorch
pytorch-main/benchmarks/sparse/spmm.py
import argparse import sys import torch from utils import gen_sparse_csr, gen_sparse_coo, Event def test_sparse_csr(m, n, k, nnz, test_count): start_timer = Event(enable_timing=True) stop_timer = Event(enable_timing=True) csr = gen_sparse_csr((m, k), nnz) mat = torch.randn(k, n, dtype=torch.double) ...
3,310
30.235849
117
py
pytorch
pytorch-main/benchmarks/sparse/dlmc/utils.py
import torch from pathlib import Path from scipy import sparse import math def to_coo_scipy(x): indices_1 = x._indices().numpy() values_1 = x._values().numpy() return sparse.coo_matrix((values_1, (indices_1[0], indices_1[1])), shape=x.shape) def sparse_grad_output(a, b): ...
7,129
34.65
112
py
pytorch
pytorch-main/benchmarks/sparse/dlmc/matmul_bench.py
# Sparse benchmarks # This benchmark is for sparse matmul performance test. # They exist for comparing the performance of sparse matrix routines # `sparse @ vector`, `sparse @ sparse` and `sparse @ dense` with different backends (CPU/CUDA) # and with other frameworks such as scipy. import sys import argparse import ...
4,502
34.456693
111
py
pytorch
pytorch-main/benchmarks/fuser/run_benchmarks.py
import click import sys import time import torch import inspect import itertools torch.set_num_threads(1) torch._C._debug_set_fusion_group_inlining(False) def rand(*shape): return torch.rand(*shape).mul(16).add(1) # ------------------------------------------------------------------------------ # Shape test cas...
7,039
20.141141
87
py
pytorch
pytorch-main/benchmarks/fastrnns/test_bench.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...
1,557
31.458333
87
py
pytorch
pytorch-main/benchmarks/fastrnns/test.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, tuple)): for t, e ...
5,836
35.710692
84
py
pytorch
pytorch-main/benchmarks/fastrnns/profile.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): ...
4,632
33.066176
100
py
pytorch
pytorch-main/benchmarks/fastrnns/cells.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...
3,635
29.049587
129
py
pytorch
pytorch-main/benchmarks/fastrnns/custom_lstms.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 ...
17,544
37.730684
132
py
pytorch
pytorch-main/benchmarks/fastrnns/runner.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, ...
3,051
40.243243
106
py
pytorch
pytorch-main/benchmarks/fastrnns/factory.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...
17,382
35.82839
128
py
pytorch
pytorch-main/benchmarks/fastrnns/bench.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...
10,481
36.170213
124
py
pytorch
pytorch-main/benchmarks/fastrnns/scratch.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...
1,048
19.173077
60
py
pytorch
pytorch-main/benchmarks/fastrnns/fuser.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_...
1,455
39.444444
57
py
pytorch
pytorch-main/benchmarks/record_function_benchmark/record_function_bench.py
import argparse import sys import torch import torch.utils.benchmark as benchmark_utils try: from benchmarks.fastrnns.factory import lstm_creator except ImportError: from caffe2.benchmarks.fastrnns.factory import lstm_creator from torchvision.models import resnet50 def prepare_lstm_jit(bench_args): mod...
3,678
34.375
102
py
pytorch
pytorch-main/benchmarks/cpp/tensorexpr/bench_ops.py
import timeit import torch import torch.nn.functional as F torch._C._jit_override_can_fuse_on_cpu(True) torch._C._debug_set_fusion_group_inlining(False) torch.set_num_threads(1) def hardswish(x): return x * torch.clamp(x + 3.0, 0.0, 6.0) / 6.0 unary_ops = [ hardswish, torch._C._nn.hardswish, torch....
2,677
24.264151
120
py
pytorch
pytorch-main/benchmarks/distributed/pipeline/benchmark_dataset.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...
1,700
28.842105
79
py
pytorch
pytorch-main/benchmarks/distributed/pipeline/pipe.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...
8,749
31.051282
111
py
pytorch
pytorch-main/benchmarks/distributed/ddp/benchmark.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...
9,501
32.108014
101
py
pytorch
pytorch-main/benchmarks/distributed/rpc/parameter_server/utils.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...
2,093
29.347826
82
py
pytorch
pytorch-main/benchmarks/distributed/rpc/parameter_server/launcher.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...
18,184
29.057851
117
py
pytorch
pytorch-main/benchmarks/distributed/rpc/parameter_server/trainer/hooks.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...
3,301
32.353535
91
py
pytorch
pytorch-main/benchmarks/distributed/rpc/parameter_server/trainer/ddp_models.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...
886
35.958333
74
py
pytorch
pytorch-main/benchmarks/distributed/rpc/parameter_server/trainer/criterions.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)
212
18.363636
50
py
pytorch
pytorch-main/benchmarks/distributed/rpc/parameter_server/trainer/trainer.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...
8,590
31.418868
102
py
pytorch
pytorch-main/benchmarks/distributed/rpc/parameter_server/models/DummyModel.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...
1,208
34.558824
120
py
pytorch
pytorch-main/benchmarks/distributed/rpc/parameter_server/metrics/CUDAMetric.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) ...
907
26.515152
62
py
pytorch
pytorch-main/benchmarks/distributed/rpc/parameter_server/data/DummyData.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...
1,676
29.490909
82
py
pytorch
pytorch-main/benchmarks/distributed/rpc/parameter_server/server/server.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...
12,143
32.362637
78
py
pytorch
pytorch-main/benchmarks/distributed/rpc/rl/coordinator.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...
5,447
37.914286
103
py
pytorch
pytorch-main/benchmarks/distributed/rpc/rl/agent.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...
6,005
34.329412
103
py
pytorch
pytorch-main/benchmarks/distributed/rpc/rl/launcher.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...
8,828
40.257009
118
py
pytorch
pytorch-main/benchmarks/distributed/rpc/rl/observer.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...
2,249
30.25
106
py
pytorch
pytorch-main/benchmarks/overrides_benchmark/pyspybench.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...
773
25.689655
87
py
pytorch
pytorch-main/benchmarks/overrides_benchmark/common.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...
804
22.676471
70
py
pytorch
pytorch-main/benchmarks/overrides_benchmark/bench.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): ...
1,660
23.426471
76
py
pytorch
pytorch-main/benchmarks/instruction_counts/definitions/setup.py
"""Define some common setup blocks which benchmarks can reuse.""" import enum from core.api import GroupedSetup from core.utils import parse_stmts _TRIVIAL_2D = GroupedSetup( r"x = torch.ones((4, 4))", r"auto x = torch::ones({4, 4});" ) _TRIVIAL_3D = GroupedSetup( r"x = torch.ones((4, 4, 4))", r"a...
1,617
30.72549
91
py
pytorch
pytorch-main/benchmarks/instruction_counts/definitions/standard.py
"""Default set of benchmarks. Parser notes: `parse_stmts`: - Width for the left (Python) column MUST be 40 characters. - The column separator is " | ", not "|". Whitespace matters. `GroupedVariants`: - `Setup` and `Global_Setup` (case insensitive) are reserved keywords to pop...
14,570
51.039286
127
py
pytorch
pytorch-main/benchmarks/instruction_counts/worker/main.py
"""File invoked through subprocess to actually carry out measurements. `worker/main.py` is deliberately isolated from the rest of the benchmark infrastructure. Other parts of the benchmark rely on this file, but `worker/` has only one Python file and does not import ANYTHING from the rest of the benchmark suite. The r...
6,910
35.566138
91
py
pytorch
pytorch-main/benchmarks/instruction_counts/core/expand.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 ...
9,391
35.403101
103
py
pytorch
pytorch-main/benchmarks/instruction_counts/core/utils.py
import atexit import shutil import re import textwrap from typing import List, Optional, Tuple from torch.utils.benchmark.utils.common import _make_temp_dir from core.api import GroupedBenchmark, TimerArgs from core.types import Definition, FlatIntermediateDefinition, Label _TEMPDIR: Optional[str] = None def get_te...
3,541
34.42
94
py
pytorch
pytorch-main/benchmarks/instruction_counts/core/api.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 ...
15,531
35.980952
97
py
pytorch
pytorch-main/benchmarks/instruction_counts/execution/work.py
"""Handle the details of subprocess calls and retries for a given benchmark run.""" import dataclasses import json import os import pickle import signal import subprocess import time from typing import List, Optional, Union, TYPE_CHECKING import uuid from core.api import AutoLabels from core.types import Label from co...
6,540
29.142857
98
py
pytorch
pytorch-main/benchmarks/instruction_counts/execution/runner.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...
10,254
38.594595
88
py
pytorch
pytorch-main/benchmarks/functional_autograd_benchmark/vision_models.py
import torch from torch import Tensor import torchvision_models as models from utils import check_for_functorch, extract_weights, load_weights, GetterReturnType from typing import cast has_functorch = check_for_functorch() def get_resnet18(device: torch.device) -> GetterReturnType: N = 32 model = models.re...
3,965
31.77686
105
py
pytorch
pytorch-main/benchmarks/functional_autograd_benchmark/torchvision_models.py
# Taken from https://github.com/pytorch/vision # So that we don't need torchvision to be installed import torch from torch import nn from torch.nn import functional as F from torch.jit.annotations import Dict from collections import OrderedDict try: from scipy.optimize import linear_sum_assignment scipy_avail...
33,791
41.029851
119
py
pytorch
pytorch-main/benchmarks/functional_autograd_benchmark/ppl_models.py
import torch from torch import Tensor import torch.distributions as dist from utils import GetterReturnType def get_simple_regression(device: torch.device) -> GetterReturnType: N = 10 K = 10 loc_beta = 0. scale_beta = 1. beta_prior = dist.Normal(loc_beta, scale_beta) X = torch.rand(N, K + 1...
3,345
34.221053
102
py
pytorch
pytorch-main/benchmarks/functional_autograd_benchmark/utils.py
import torch from collections import defaultdict from torch import nn, Tensor from typing import List, Tuple, Dict, Union, Callable # Type helpers InputsType = Union[Tensor, Tuple[Tensor, ...]] # A Getter takes in a device and returns a callable and the inputs to that callable GetterReturnType = Tuple[Callable[..., ...
4,088
35.837838
102
py
pytorch
pytorch-main/benchmarks/functional_autograd_benchmark/audio_text_models.py
import torch from torch import nn, Tensor import torchaudio_models as models from utils import check_for_functorch, extract_weights, load_weights, GetterReturnType has_functorch = check_for_functorch() def get_wav2letter(device: torch.device) -> GetterReturnType: N = 10 input_frames = 700 vocab_size =...
5,058
35.65942
114
py
pytorch
pytorch-main/benchmarks/functional_autograd_benchmark/torchaudio_models.py
# Taken from https://github.com/pytorch/audio/blob/master/torchaudio/models/wav2letter.py # So that we don't need torchaudio to be installed import torch from torch import Tensor from torch import nn import torch.nn.functional as F import math from collections import OrderedDict from typing import Tuple, Optional __...
24,715
43.694394
120
py
pytorch
pytorch-main/benchmarks/functional_autograd_benchmark/functional_autograd_benchmark.py
import torch from torch.autograd import functional import time from argparse import ArgumentParser from collections import defaultdict from typing import NamedTuple, Callable, List, Any try: import functorch as ft has_functorch = True print(f"Found functorch: {ft.__version__}") except ImportError: has...
10,148
35.246429
117
py
pytorch
pytorch-main/benchmarks/tensorexpr/concat.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 ...
4,027
33.135593
110
py
pytorch
pytorch-main/benchmarks/tensorexpr/__main__.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...
11,877
34.885196
118
py
pytorch
pytorch-main/benchmarks/tensorexpr/benchmark.py
import contextlib import numpy as np import os import time from . import tensor_engine import torch import json class Benchmark: def __init__(self, mode, device, dtype): self.mode = mode self.deterministic = False self.device = device self.dtype = dtype self.output_type = "...
10,914
34.096463
100
py
pytorch
pytorch-main/benchmarks/tensorexpr/microbenchmarks.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: def __enter__(self): self.scope = te.KernelScope() def __exit__(self, typ, val, traceback): self.scope = Non...
8,591
32.302326
122
py
pytorch
pytorch-main/benchmarks/tensorexpr/broadcast.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...
9,685
31.286667
100
py
pytorch
pytorch-main/benchmarks/tensorexpr/rnn_eltwise.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...
3,224
29.424528
95
py
pytorch
pytorch-main/benchmarks/tensorexpr/swish.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) ...
1,374
25.960784
99
py
pytorch
pytorch-main/benchmarks/tensorexpr/attention.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):...
2,871
30.56044
99
py
pytorch
pytorch-main/benchmarks/tensorexpr/elementwise.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...
7,720
32.424242
101
py
pytorch
pytorch-main/benchmarks/tensorexpr/pt_engine.py
import torch class TorchTensorEngine: 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, device=d...
2,296
29.223684
90
py
pytorch
pytorch-main/benchmarks/dynamo/summarize_perf.py
import logging import os import re from collections import defaultdict import click import pandas as pd from tabulate import tabulate def gmean(s): return s.product() ** (1 / len(s)) def find_csv_files(path, perf_compare): """ Recursively search for all CSV files in directory and subdirectories whose ...
4,460
29.765517
119
py
pytorch
pytorch-main/benchmarks/dynamo/check_hf_bert_perf_csv.py
import argparse import sys import textwrap import pandas as pd def check_hf_bert_perf_csv(filename): """ Basic performance checking. """ df = pd.read_csv(filename) failed = [] for _, row in df.iterrows(): model_name = row["name"] speedup = row["speedup"] # Reduce fro...
1,195
26.181818
124
py
pytorch
pytorch-main/benchmarks/dynamo/test.py
import os import unittest from .common import parse_args, run from .torchbench import setup_torchbench_cwd, TorchBenchmarkRunner try: # fbcode only from aiplatform.utils.sanitizer_status import is_asan_or_tsan except ImportError: def is_asan_or_tsan(): return False class TestDynamoBenchmark(un...
1,236
26.488889
70
py
pytorch
pytorch-main/benchmarks/dynamo/parse_logs.py
import csv import os import re import sys # This script takes the logs produced by the benchmark scripts (e.g., # torchbench.py) and parses it into a CSV file that summarizes what # is failing and why. It is kept separate from the benchmark script # emitting a more structured output as it is often more convenient # t...
5,801
28.30303
118
py
pytorch
pytorch-main/benchmarks/dynamo/huggingface.py
#!/usr/bin/env python3 import importlib import logging import os import re import subprocess import sys import warnings import torch from common import BenchmarkRunner, download_retry_decorator, main, reset_rng_state from torch._dynamo.testing import collect_results from torch._dynamo.utils import clone_inputs log =...
21,447
31.795107
117
py
pytorch
pytorch-main/benchmarks/dynamo/benchmarks.py
#!/usr/bin/env python3 import argparse import os from typing import Set # Note - hf and timm have their own version of this, torchbench does not # TOOD(voz): Someday, consolidate all the files into one runner instead of a shim like this... def model_names(filename: str) -> Set[str]: names = set() with open(f...
2,948
27.631068
94
py
pytorch
pytorch-main/benchmarks/dynamo/torchbench.py
#!/usr/bin/env python3 import gc import importlib import logging import os import re import sys import warnings from os.path import abspath, exists import torch try: from .common import BenchmarkRunner, main except ImportError: from common import BenchmarkRunner, main from torch._dynamo.testing import collec...
13,450
28.177874
91
py
pytorch
pytorch-main/benchmarks/dynamo/check_graph_breaks.py
import argparse import os import sys import textwrap import pandas as pd def get_field(csv, model_name: str, field: str): try: return csv.loc[csv["name"] == model_name][field].item() except Exception as e: return None def check_graph_breaks(actual_csv, expected_csv, expected_filename): ...
2,441
27.395349
101
py
pytorch
pytorch-main/benchmarks/dynamo/training_loss.py
import argparse import inspect import os import sys import time from datetime import timedelta import torch import torch._dynamo from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer torch.backends.cuda.matmul...
6,523
30.669903
106
py
pytorch
pytorch-main/benchmarks/dynamo/check_accuracy.py
import argparse import os import sys import textwrap import pandas as pd def get_field(csv, model_name: str, field: str): try: return csv.loc[csv["name"] == model_name][field].item() except Exception as e: return None def check_accuracy(actual_csv, expected_csv, expected_filename): fail...
2,386
27.082353
101
py
pytorch
pytorch-main/benchmarks/dynamo/runner.py
#!/usr/bin/env python3 """ A wrapper over the benchmark infrastructure to generate commonly used commands, parse results and generate csv/graphs. The script works on manually written TABLE (see below). We can add more commands in the future. One example usage is -> python benchmarks/runner.py --suites=torchbench --i...
53,234
34.395612
132
py
pytorch
pytorch-main/benchmarks/dynamo/common.py
#!/usr/bin/env python3 from __future__ import annotations import argparse import collections import contextlib import copy import csv import functools import importlib import itertools import logging import os import pathlib import random import shutil import signal import subprocess import sys import time from contex...
123,240
34.805055
132
py
pytorch
pytorch-main/benchmarks/dynamo/distributed.py
import argparse import logging import os from functools import partial import torch import torch._dynamo as dynamo import torch.utils._pytree as pytree from torch._dynamo.testing import reduce_to_scalar_loss from torch.nn.parallel import DistributedDataParallel as DDP from torch.profiler import profile, ProfilerActivi...
5,627
30.79661
93
py
pytorch
pytorch-main/benchmarks/dynamo/timm_models.py
#!/usr/bin/env python3 import importlib import logging import os import re import subprocess import sys import warnings import torch from common import BenchmarkRunner, download_retry_decorator, main from torch._dynamo.testing import collect_results, reduce_to_scalar_loss from torch._dynamo.utils import clone_inputs ...
10,356
28.847262
88
py
pytorch
pytorch-main/benchmarks/dynamo/dist_util.py
import argparse import functools import importlib import os import torch import torch.distributed as dist import torch.nn as nn from torch._dynamo.testing import reduce_to_scalar_loss from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, ...
4,163
26.946309
83
py
pytorch
pytorch-main/benchmarks/dynamo/ci_expected_accuracy/update_expected.py
""" Update commited CSV files used as reference points by dynamo/inductor CI. Currently only cares about graph breaks, so only saves those columns. Hardcodes a list of job names and artifacts per job, but builds the lookup by querying github sha and finding associated github actions workflow ID and CI jobs, downloadi...
4,828
33.248227
116
py
pytorch
pytorch-main/benchmarks/dynamo/microbenchmarks/bench_mm_fusion.py
# flake8: noqa import torch import torch._dynamo import torch._inductor.config import triton from prettytable import PrettyTable # torch._inductor.config.debug = True torch._inductor.config.triton.dense_indexing = True torch.manual_seed(0) # The flag below controls whether to allow TF32 on matmul. torch.backends.cu...
3,079
24.454545
66
py
pytorch
pytorch-main/benchmarks/dynamo/microbenchmarks/operator_inp_utils.py
import functools import logging import math import os from collections import Counter, defaultdict from functools import partial from typing import Any, Dict, Generator, Iterable, Tuple import torch from torch.testing import make_tensor from torch.utils._python_dispatch import TorchDispatchMode from torch.utils._pytre...
10,709
30.22449
88
py
pytorch
pytorch-main/benchmarks/dynamo/microbenchmarks/microbench.py
#!/usr/bin/env python3 import argparse import inspect import sys import numpy as np import tabulate import torch import torch._inductor from torch._dynamo.backends.cudagraphs import cudagraphs_inner from torch._dynamo.testing import same from torch._inductor.compile_fx import compile_fx from torch._inductor.utils imp...
5,460
29.853107
87
py
pytorch
pytorch-main/benchmarks/dynamo/microbenchmarks/inductor_cpu_atomic.py
import itertools import torch import torch._dynamo from benchmark_helper import time_with_torch_timer @torch._dynamo.optimize("inductor", nopython=True) def inductor_scatter_add(dst, src, index): return torch.scatter_add(dst, 1, index, src) def torch_scatter_add(dst, src, index): return torch.scatter_add(d...
2,806
34.531646
129
py
pytorch
pytorch-main/benchmarks/dynamo/microbenchmarks/matmul_relu.py
import torch import torch._dynamo import torch._inductor.config as inductor_config from benchmark_helper import time_with_torch_timer inductor_config.triton.mm = "triton" @torch._dynamo.optimize("inductor", nopython=True) def inductor_mm(a, b): return torch.mm(a, b) def torch_mm_relu(a, b): return torch.n...
2,765
26.386139
81
py
pytorch
pytorch-main/benchmarks/dynamo/microbenchmarks/utils.py
import math import torch def rounded_linspace(low, high, steps, div): ret = torch.linspace(low, high, steps) ret = (ret.int() + div - 1) // div * div ret = torch.unique(ret) return list(map(int, ret)) def powspace(start, stop, pow, step): start = math.log(start, pow) stop = math.log(stop, p...
488
23.45
60
py
pytorch
pytorch-main/benchmarks/dynamo/microbenchmarks/inductor_bmm.py
import torch import torch._dynamo import torch._dynamo.config import torch._inductor.config as config from benchmark_helper import time_with_torch_timer @torch._dynamo.optimize("inductor", nopython=True) def inductor_aten_bmm(a, b): return torch.bmm(a, b) @torch._dynamo.optimize("inductor", nopython=True) def ...
1,702
26.467742
86
py
pytorch
pytorch-main/benchmarks/dynamo/microbenchmarks/tensor_layout_mini_benchmark.py
import torch from torch._inductor import ir from torch._inductor.utils import do_bench def to_channels_last(x): assert x.dim() == 4 # NCHW -> NHWC stride_order = [3, 0, 2, 1] y = x.clone().as_strided( x.shape, ir.FlexibleLayout.stride_ordered(x.shape, stride_order), ) y.copy_(...
1,619
22.823529
88
py
pytorch
pytorch-main/benchmarks/dynamo/microbenchmarks/operatorbench.py
#!/usr/bin/env python3 import click import numpy as np import torch from operator_inp_utils import OperatorInputsLoader from torch._dynamo.backends.cudagraphs import cudagraphs_inner from torch._dynamo.testing import same from torch._inductor.compile_fx import compile_fx from torch._inductor.decomposition import decom...
8,810
31.274725
110
py
pytorch
pytorch-main/benchmarks/dynamo/microbenchmarks/inductor_mm.py
import torch import torch._dynamo import torch._dynamo.config import torch._inductor.config as config import triton from benchmark_helper import time_with_torch_timer # The flag below controls whether to allow TF32 on matmul. This flag defaults to True. torch.backends.cuda.matmul.allow_tf32 = True # The flag below co...
5,644
40.814815
111
py
pytorch
pytorch-main/benchmarks/dynamo/microbenchmarks/benchmark_helper.py
from torch.utils.benchmark import Timer def time_with_torch_timer(fn, args, kwargs=None, iters=100): kwargs = kwargs or {} env = {"args": args, "kwargs": kwargs, "fn": fn} fn_call = "fn(*args, **kwargs)" # Measure end-to-end time timer = Timer(stmt=f"{fn_call}", globals=env) tt = timer.timeit...
343
23.571429
60
py
pytorch
pytorch-main/benchmarks/dynamo/_onnx/patch.py
from torch.utils import _pytree as pytree def patch_non_tensor_outputs(correct_result, new_result, fp64_outputs): """Patch non-tensor outputs to make them comparable with the correct result. ONNX model always returns a flat tuple of tensors, but the PyTorch model outputs `correct_result` and `fp64_output...
1,949
33.821429
88
py
pytorch
pytorch-main/benchmarks/dynamo/_onnx/reporter.py
from __future__ import annotations import argparse import collections import dataclasses import io import logging import pathlib import random import re from typing import Dict, List, Optional, Sequence, Tuple import pandas as pd from torch.onnx._internal.fx import diagnostics log = logging.getLogger(__name__) lo...
14,828
34.476077
167
py
pytorch
pytorch-main/benchmarks/transformer/sdp.py
import torch import itertools import numpy as np import random import argparse from pathlib import Path import torch.utils.benchmark as benchmark from dataclasses import dataclass from typing import Optional, List from pprint import pprint from torch.backends.cuda import sdp_kernel from tqdm import tqdm from prettytabl...
10,661
29.726225
121
py
pytorch
pytorch-main/benchmarks/transformer/better_transformer_vs_mha_functional.py
""" Tests the performance of torch.nn.MultiheadAttention's fast path (BetterTransformer) vs the slow path (torch.nn.functional.multi_head_attention) To run this script install these dependencies: pip install tqdm pip install prettytable """ import torch import random import numpy as np from pprint import pprint impo...
6,896
34.188776
108
py
pytorch
pytorch-main/benchmarks/transformer/sdp_backwards.py
import torch import numpy as np import random import torch.utils.benchmark as benchmark from torch.profiler import profile, record_function, ProfilerActivity class CompositeMHA(torch.nn.Module): def __init__(self, num_heads, in_proj_weight, in_proj_bias, out_proj): super().__init__() self.in_proj_...
6,272
32.190476
108
py
pytorch
pytorch-main/benchmarks/framework_overhead_benchmark/C2Module.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: """ This modu...
1,564
36.261905
82
py
pytorch
pytorch-main/benchmarks/framework_overhead_benchmark/pt_wrapper_module.py
import torch class WrapperModule: """ 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 wrapped_type...
1,939
43.090909
132
py
pytorch
pytorch-main/benchmarks/framework_overhead_benchmark/utils.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...
1,227
34.085714
78
py
pytorch
pytorch-main/benchmarks/framework_overhead_benchmark/SimpleAddModule.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().__init__() self.add_op = add_op def forwar...
368
20.705882
39
py