python_code stringlengths 0 1.02M | repo_name stringlengths 9 48 | file_path stringlengths 5 114 |
|---|---|---|
from contextlib import contextmanager
import types
# The idea for this parameter is that we forbid bare assignment
# to torch.backends.<cudnn|mkldnn>.enabled and friends when running our
# test suite, where it's very easy to forget to undo the change
# later.
__allow_nonbracketed_mutation_flag = True
def disable_globa... | pytorch-master | torch/backends/__init__.py |
import torch
from functools import lru_cache as _lru_cache
def is_built() -> bool:
r"""Returns whether PyTorch is built with MPS support. Note that this
doesn't necessarily mean MPS is available; just that if this PyTorch
binary were run a machine with working MPS drivers and devices, we
would be able ... | pytorch-master | torch/backends/mps/__init__.py |
import hashlib
import json
from typing import Dict, Tuple
import coremltools as ct # type: ignore[import]
import torch
from coremltools.converters.mil.input_types import TensorType # type: ignore[import]
from coremltools.converters.mil.mil import types # type: ignore[import]
from coremltools.models.neural_network i... | pytorch-master | torch/backends/_coreml/preprocess.py |
pytorch-master | torch/backends/_coreml/__init__.py | |
import sys
import torch
from typing import Union
def is_built():
r"""Returns whether PyTorch is built with CUDA support. Note that this
doesn't necessarily mean CUDA is available; just that if this PyTorch
binary were run a machine with working CUDA drivers and devices, we
would be able to use it.""... | pytorch-master | torch/backends/cuda/__init__.py |
import sys
import torch
import types
from typing import List
# This function should correspond to the enums present in c10/core/QEngine.h
def _get_qengine_id(qengine: str) -> int:
if qengine == 'none' or qengine == '' or qengine is None:
ret = 0
elif qengine == 'fbgemm':
ret = 1
elif qengin... | pytorch-master | torch/backends/quantized/__init__.py |
import torch
def is_available():
r"""Returns whether PyTorch is built with MKL support."""
return torch._C.has_mkl
VERBOSE_OFF = 0
VERBOSE_ON = 1
class verbose(object):
"""
On-demand oneMKL verbosing functionality
To make it easier to debug performance issues, oneMKL can dump verbose
messages ... | pytorch-master | torch/backends/mkl/__init__.py |
import sys
import torch
import types
class _XNNPACKEnabled(object):
def __get__(self, obj, objtype):
return torch._C._is_xnnpack_enabled()
def __set__(self, obj, val):
raise RuntimeError("Assignment not supported")
class XNNPACKEngine(types.ModuleType):
def __init__(self, m, name):
... | pytorch-master | torch/backends/xnnpack/__init__.py |
import sys
import torch
from contextlib import contextmanager
from torch.backends import ContextProp, PropModule, __allow_nonbracketed_mutation
def is_available():
r"""Returns whether PyTorch is built with MKL-DNN support."""
return torch._C.has_mkldnn
VERBOSE_OFF = 0
VERBOSE_ON = 1
VERBOSE_ON_CREATION = 2
cl... | pytorch-master | torch/backends/mkldnn/__init__.py |
pytorch-master | torch/backends/xeon/__init__.py | |
"""
This is a script for launching PyTorch inference on Intel(R) Xeon(R) Scalable Processors with optimal configurations.
Single instance inference, multi-instance inference are enabled.
Note: term "instance" here doesn't refer to a cloud instance. This script is executed as a single process. It invokes
multiple "inst... | pytorch-master | torch/backends/xeon/run_cpu.py |
pytorch-master | torch/backends/_nnapi/__init__.py | |
import sys
import enum
import struct
import array
import logging
import functools
from typing import (
Tuple,
NamedTuple,
List,
Optional,
)
import torch
# TODO: Add type annotations
# TODO: Check tensor types for ops
LOG = logging.getLogger("nnapi_serialize")
class NNAPI_OperandCode(object):
... | pytorch-master | torch/backends/_nnapi/serializer.py |
from typing import Optional, List
import torch
from torch.backends._nnapi.serializer import _NnapiSerializer
ANEURALNETWORKS_PREFER_LOW_POWER = 0
ANEURALNETWORKS_PREFER_FAST_SINGLE_ANSWER = 1
ANEURALNETWORKS_PREFER_SUSTAINED_SPEED = 2
class NnapiModule(torch.nn.Module):
"""Torch Module that wraps an NNAPI Compi... | pytorch-master | torch/backends/_nnapi/prepare.py |
import torch
def is_available():
r"""Returns whether PyTorch is built with OpenMP support."""
return torch._C.has_openmp
| pytorch-master | torch/backends/openmp/__init__.py |
import sys
import os
import torch
import warnings
from contextlib import contextmanager
from torch.backends import ContextProp, PropModule, __allow_nonbracketed_mutation
try:
from torch._C import _cudnn
except ImportError:
_cudnn = None # type: ignore[assignment]
# Write:
#
# torch.backends.cudnn.enabled =... | pytorch-master | torch/backends/cudnn/__init__.py |
import torch.cuda
try:
from torch._C import _cudnn
except ImportError:
# Uses of all the functions below should be guarded by torch.backends.cudnn.is_available(),
# so it's safe to not emit any checks here.
_cudnn = None # type: ignore[assignment]
def get_cudnn_mode(mode):
if mode == 'RNN_RELU':... | pytorch-master | torch/backends/cudnn/rnn.py |
import functools
from enum import Enum
from typing import Callable, List, Optional, Tuple
import torch
import torch._prims_common as utils
import torch.nn.functional as F
from torch import Tensor
from torch._decomp import register_decomposition
from torch._prims_common.wrappers import out_wrapper
from torch.utils._pyt... | pytorch-master | torch/_decomp/decompositions.py |
import inspect
from collections import defaultdict
from functools import wraps
from itertools import chain
from typing import Callable, Dict, NamedTuple, Sequence, Tuple, Union
import torch
import torch._ops
import torch.library
from torch.utils._pytree import tree_map
__all__ = ["decomposition_table", "register_deco... | pytorch-master | torch/_decomp/__init__.py |
import types
import math
from torch._six import inf
from functools import wraps
import warnings
import weakref
from collections import Counter
from bisect import bisect_right
from .optimizer import Optimizer
__all__ = ['LambdaLR', 'MultiplicativeLR', 'StepLR', 'MultiStepLR', 'ConstantLR', 'LinearLR',
'Expo... | pytorch-master | torch/optim/lr_scheduler.py |
import torch
from torch import Tensor
from .optimizer import Optimizer
from typing import List, Optional
__all__ = ['RMSprop', 'rmsprop']
class RMSprop(Optimizer):
r"""Implements RMSprop algorithm.
.. math::
\begin{aligned}
&\rule{110mm}{0.4pt} ... | pytorch-master | torch/optim/rmsprop.py |
import torch
from . import _functional as F
from .optimizer import Optimizer
__all__ = ['SparseAdam']
class SparseAdam(Optimizer):
r"""Implements lazy version of Adam algorithm suitable for sparse tensors.
In this variant, only moments that show up in the gradient get updated, and
only those portions of ... | pytorch-master | torch/optim/sparse_adam.py |
import torch
from torch import Tensor
from .optimizer import Optimizer
from typing import List, Optional
__all__ = ['Rprop', 'rprop']
class Rprop(Optimizer):
r"""Implements the resilient backpropagation algorithm.
.. math::
\begin{aligned}
&\rule{110mm}{0.4pt} ... | pytorch-master | torch/optim/rprop.py |
import torch
from torch import Tensor
from .optimizer import Optimizer, required, _use_grad_for_differentiable
from typing import List, Optional
__all__ = ['SGD', 'sgd']
class SGD(Optimizer):
r"""Implements stochastic gradient descent (optionally with momentum).
.. math::
\begin{aligned}
&... | pytorch-master | torch/optim/sgd.py |
"""
:mod:`torch.optim` is a package implementing various optimization algorithms.
Most commonly used methods are already supported, and the interface is general
enough, so that more sophisticated ones can be also easily integrated in the
future.
"""
from .adadelta import Adadelta
from .adagrad import Adagrad
from .ada... | pytorch-master | torch/optim/__init__.py |
import torch
from torch import Tensor
from .optimizer import Optimizer
from typing import List, Optional
__all__ = ['Adamax', 'adamax']
class Adamax(Optimizer):
r"""Implements Adamax algorithm (a variant of Adam based on infinity norm).
.. math::
\begin{aligned}
&\rule{110mm}{0.4pt} ... | pytorch-master | torch/optim/adamax.py |
import torch
from torch import Tensor
from .optimizer import Optimizer
from typing import List, Optional
__all__ = ['Adagrad', 'adagrad']
class Adagrad(Optimizer):
r"""Implements Adagrad algorithm.
.. math::
\begin{aligned}
&\rule{110mm}{0.4pt} ... | pytorch-master | torch/optim/adagrad.py |
import math
import torch
from torch import Tensor
from .optimizer import Optimizer
from typing import List, Optional
__all__ = ['AdamW', 'adamw']
class AdamW(Optimizer):
r"""Implements AdamW algorithm.
.. math::
\begin{aligned}
&\rule{110mm}{0.4pt} ... | pytorch-master | torch/optim/adamw.py |
import itertools
import math
from copy import deepcopy
import warnings
import torch
from torch.nn import Module
from torch.optim.lr_scheduler import _LRScheduler
__all__ = ['AveragedModel', 'update_bn', 'SWALR']
class AveragedModel(Module):
r"""Implements averaged model for Stochastic Weight Averaging (SWA).
... | pytorch-master | torch/optim/swa_utils.py |
import torch
from functools import reduce
from .optimizer import Optimizer
__all__ = ['LBFGS']
def _cubic_interpolate(x1, f1, g1, x2, f2, g2, bounds=None):
# ported from https://github.com/torch/optim/blob/master/polyinterp.lua
# Compute bounds of interpolation area
if bounds is not None:
xmin_bou... | pytorch-master | torch/optim/lbfgs.py |
import math
import torch
from torch import Tensor
from .optimizer import Optimizer
from typing import List, Optional
__all__ = ['RAdam', 'radam']
class RAdam(Optimizer):
r"""Implements RAdam algorithm.
.. math::
\begin{aligned}
&\rule{110mm}{0.4pt} ... | pytorch-master | torch/optim/radam.py |
import math
import torch
from torch import Tensor
from .optimizer import Optimizer
from typing import List, Optional
__all__ = ['Adam', 'adam']
class Adam(Optimizer):
r"""Implements Adam algorithm.
.. math::
\begin{aligned}
&\rule{110mm}{0.4pt} ... | pytorch-master | torch/optim/adam.py |
from collections import defaultdict, abc as container_abcs
import torch
from copy import deepcopy
from itertools import chain
import warnings
import functools
__all__ = ['Optimizer']
class _RequiredParameter(object):
"""Singleton class representing a required parameter for an Optimizer."""
def __repr__(self):... | pytorch-master | torch/optim/optimizer.py |
import math
import torch
from torch import Tensor
from .optimizer import Optimizer
from typing import List, Optional
__all__ = ['NAdam', 'nadam']
class NAdam(Optimizer):
r"""Implements NAdam algorithm.
.. math::
\begin{aligned}
&\rule{110mm}{0.4pt} ... | pytorch-master | torch/optim/nadam.py |
import math
import torch
from torch import Tensor
from .optimizer import Optimizer
from typing import List, Optional
__all__ = ['ASGD', 'asgd']
class ASGD(Optimizer):
"""Implements Averaged Stochastic Gradient Descent.
It has been proposed in `Acceleration of stochastic approximation by
averaging`_.
... | pytorch-master | torch/optim/asgd.py |
r"""Functional interface"""
import math
from torch import Tensor
from typing import List
from .adadelta import adadelta # type: ignore[attr-defined] # noqa: F401
from .adagrad import adagrad, _make_sparse # type: ignore[attr-defined] # noqa: F401
from .adam import adam # type: ignore[attr-defined] # noqa: F401
from... | pytorch-master | torch/optim/_functional.py |
import torch
from torch import Tensor
from .optimizer import Optimizer
from typing import List, Optional
__all__ = ['Adadelta', 'adadelta']
class Adadelta(Optimizer):
r"""Implements Adadelta algorithm.
.. math::
\begin{aligned}
&\rule{110mm}{0.4pt} ... | pytorch-master | torch/optim/adadelta.py |
"""
:mod:`torch.optim._multi_tensor` is a package implementing various optimization algorithms.
Most commonly used methods are already supported, and the interface is general
enough, so that more sophisticated ones can be also easily integrated in the
future.
"""
from functools import partialmethod
from torch import op... | pytorch-master | torch/optim/_multi_tensor/__init__.py |
from typing import NamedTuple, Callable, Any, Tuple, List, Dict, Type, cast, Optional, TypeVar
import functools
from collections import namedtuple, OrderedDict
T = TypeVar('T')
S = TypeVar('S')
"""
Contains utility functions for working with nested python data structures.
A *pytree* is Python nested data structure. ... | pytorch-master | torch/utils/_pytree.py |
import logging
from typing import Callable, Generic, List
from typing_extensions import ParamSpec
logger = logging.getLogger(__name__)
P = ParamSpec("P")
class CallbackRegistry(Generic[P]):
def __init__(self, name: str):
self.name = name
self.callback_list: List[Callable[P, None]] = []
def ... | pytorch-master | torch/utils/_cuda_trace.py |
import torch
from collections import OrderedDict
import weakref
import warnings
from typing import Any
class RemovableHandle(object):
"""A handle which provides the capability to remove a hook."""
id: int
next_id: int = 0
def __init__(self, hooks_dict: Any) -> None:
self.hooks_dict_ref = wea... | pytorch-master | torch/utils/hooks.py |
import collections
Entry = collections.namedtuple('Entry', 'version, hash')
def update_hash(seed, value):
# Good old boost::hash_combine
# https://www.boost.org/doc/libs/1_35_0/doc/html/boost/hash_combine_id241013.html
return seed ^ (hash(value) + 0x9e3779b9 + (seed << 6) + (seed >> 2))
def hash_sourc... | pytorch-master | torch/utils/_cpp_extension_versioner.py |
import functools
import torch
from typing import Iterator, TypeVar
from dataclasses import dataclass
from contextlib import contextmanager
T = TypeVar('T')
# This file has all the logic to dedupe logic between torch dispatch and
# torch function modes
#
# Specifically, it has the helper functions for enable_ and push... | pytorch-master | torch/utils/_mode_utils.py |
import torch
import warnings
import weakref
from typing import Any, Iterable, List, Tuple
__all__ = [
"checkpoint", "checkpoint_sequential", "CheckpointFunction",
"check_backward_validity", "detach_variable", "get_device_states",
"set_device_states",
]
def detach_variable(inputs: Tuple[Any, ...]) -> Tuple... | pytorch-master | torch/utils/checkpoint.py |
#!/usr/bin/env python3
import sys
import pickle
import struct
import pprint
import zipfile
import fnmatch
from typing import Any, IO, BinaryIO, Union
class FakeObject(object):
def __init__(self, module, name, args):
self.module = module
self.name = name
self.args = args
# NOTE: We ... | pytorch-master | torch/utils/show_pickle.py |
import os
import time
class FileBaton:
'''A primitive, file-based synchronization utility.'''
def __init__(self, lock_file_path, wait_seconds=0.1):
'''
Creates a new :class:`FileBaton`.
Args:
lock_file_path: The path to the file used for locking.
wait_seconds:... | pytorch-master | torch/utils/file_baton.py |
"""
Freeze Python packages.
Freezing makes it possible to ship arbitrary Python modules as part of a C++
library. The Python source of the module is compiled to bytecode and written
to `.c` files, to be imported by Python's built-in FrozenImporter.
In a normal Python installation, FrozenImporter is only used to boots... | pytorch-master | torch/utils/_freeze.py |
# torchvision imports tqdm from here.
from torch.hub import tqdm, load_state_dict_from_url as load_url # noqa: F401
| pytorch-master | torch/utils/model_zoo.py |
import argparse
import glob
import os
from pathlib import Path
from zipfile import ZipFile
# Exclude some standard library modules to:
# 1. Slim down the final zipped file size
# 2. Remove functionality we don't want to support.
DENY_LIST = [
# Interface to unix databases
"dbm",
# ncurses bindings (termina... | pytorch-master | torch/utils/_zip.py |
from __future__ import print_function
# Unlike the rest of the PyTorch this file must be python2 compliant.
# This script outputs relevant system environment info
# Run it with `python collect_env.py`.
import datetime
import locale
import re
import subprocess
import sys
import os
from collections import namedtuple
t... | pytorch-master | torch/utils/collect_env.py |
import torch._C
def format_time(time_us=None, time_ms=None, time_s=None):
'''Defines how to format time'''
assert sum([time_us is not None, time_ms is not None, time_s is not None]) == 1
US_IN_SECOND = 1e6
US_IN_MS = 1e3
if time_us is None:
if time_ms is not None:
time_us = t... | pytorch-master | torch/utils/throughput_benchmark.py |
from typing import Any
import torch
import enum
from torch._C import _from_dlpack
from torch._C import _to_dlpack as to_dlpack
class DLDeviceType(enum.IntEnum):
# Enums as in DLPack specification (aten/src/ATen/dlpack.h)
kDLCPU = 1,
kDLGPU = 2,
kDLCPUPinned = 3,
kDLOpenCL = 4,
kDLVulkan = 7,... | pytorch-master | torch/utils/dlpack.py |
import os.path as _osp
import sys
from .throughput_benchmark import ThroughputBenchmark
from ._crash_handler import enable_minidumps, disable_minidumps, enable_minidumps_on_exceptions
# Set the module for a given object for nicer printing
def set_module(obj, mod):
if not isinstance(mod, str):
raise TypeEr... | pytorch-master | torch/utils/__init__.py |
#!/usr/bin/env python3
from typing import Any, TypeVar, Optional, Tuple, List, NamedTuple, Union, Sequence, Dict, Callable
import textwrap
import torch
from torch._C import TupleType, ListType
from torch.jit._recursive import wrap_cpp_module
T = TypeVar("T")
MAX_RAW_TENSOR_SIZE = 16
class InflatableArg(NamedTuple):... | pytorch-master | torch/utils/bundled_inputs.py |
import os
import sys
import pathlib
import torch
DEFAULT_MINIDUMP_DIR = "/tmp/pytorch_crashes"
if sys.platform == "win32":
DEFAULT_MINIDUMP_DIR = str(pathlib.Path.home() / "AppData" / "pytorch_crashes")
def enable_minidumps(directory=DEFAULT_MINIDUMP_DIR):
if directory == DEFAULT_MINIDUMP_DIR:
pathli... | pytorch-master | torch/utils/_crash_handler.py |
import torch
class MkldnnLinear(torch.jit.ScriptModule):
def __init__(self, dense_module, dtype):
super(MkldnnLinear, self).__init__()
self.register_buffer('weight', dense_module.weight.to_mkldnn(dtype))
if dense_module.bias is not None:
# Bias can be fp32 or bf16 for OneDNN bf... | pytorch-master | torch/utils/mkldnn.py |
import contextlib
from typing import Iterator, Set
import functools
import warnings
from torch.utils._mode_utils import _enable_mode, _ModeInfo, _wrap_init, _restore_mode
from torch._C import _get_torch_dispatch_mode, _set_torch_dispatch_mode
from dataclasses import dataclass
@dataclass
class TorchDispatchModeInfo(_... | pytorch-master | torch/utils/_python_dispatch.py |
import copy
import glob
import importlib
import importlib.abc
import os
import re
import shlex
import setuptools
import subprocess
import sys
import sysconfig
import warnings
import collections
import torch
import torch._appdirs
from .file_baton import FileBaton
from ._cpp_extension_versioner import ExtensionVersioner... | pytorch-master | torch/utils/cpp_extension.py |
"""
This module contains utility method for mobile model optimization and lint.
"""
import torch
from enum import Enum
from torch._C import MobileOptimizerType
from typing import Optional, Set, List, AnyStr
class LintCode(Enum):
BUNDLED_INPUT = 1
REQUIRES_GRAD = 2
DROPOUT = 3
BATCHNORM = 4
def optimi... | pytorch-master | torch/utils/mobile_optimizer.py |
from torch.utils.benchmark.utils.common import * # noqa: F403
from torch.utils.benchmark.utils.timer import * # noqa: F403
from torch.utils.benchmark.utils.compare import * # noqa: F403
from torch.utils.benchmark.utils.fuzzer import * # noqa: F403
from torch.utils.benchmark.utils.valgrind_wrapper.timer_interface im... | pytorch-master | torch/utils/benchmark/__init__.py |
import numpy as np
import torch
from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedTensor
_MIN_DIM_SIZE = 16
_MAX_DIM_SIZE = 16 * 1024 ** 2
_POW_TWO_SIZES = tuple(2 ** i for i in range(
int(np.log2(_MIN_DIM_SIZE)),
int(np.log2(_MAX_DIM_SIZE)) + 1,
))
class BinaryOpFuzzer(Fuzze... | pytorch-master | torch/utils/benchmark/op_fuzzers/binary.py |
import numpy as np
import torch
from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedSparseTensor
_MIN_DIM_SIZE = 16
_MAX_DIM_SIZE = 16 * 1024 ** 2
_POW_TWO_SIZES = tuple(2 ** i for i in range(
int(np.log2(_MIN_DIM_SIZE)),
int(np.log2(_MAX_DIM_SIZE)) + 1,
))
class BinaryOpSparse... | pytorch-master | torch/utils/benchmark/op_fuzzers/sparse_binary.py |
import numpy as np
import torch
from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedSparseTensor
_MIN_DIM_SIZE = 16
_MAX_DIM_SIZE = 16 * 1024 ** 2
_POW_TWO_SIZES = tuple(2 ** i for i in range(
int(np.log2(_MIN_DIM_SIZE)),
int(np.log2(_MAX_DIM_SIZE)) + 1,
))
class UnaryOpSparseFu... | pytorch-master | torch/utils/benchmark/op_fuzzers/sparse_unary.py |
pytorch-master | torch/utils/benchmark/op_fuzzers/__init__.py | |
import math
import torch
from torch.utils import benchmark
from torch.utils.benchmark import FuzzedParameter, FuzzedTensor, ParameterAlias
__all__ = ['SpectralOpFuzzer']
MIN_DIM_SIZE = 16
MAX_DIM_SIZE = 16 * 1024
def power_range(upper_bound, base):
return (base ** i for i in range(int(math.log(upper_bound, bas... | pytorch-master | torch/utils/benchmark/op_fuzzers/spectral.py |
import numpy as np
import torch
from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedTensor
_MIN_DIM_SIZE = 16
_MAX_DIM_SIZE = 16 * 1024 ** 2
_POW_TWO_SIZES = tuple(2 ** i for i in range(
int(np.log2(_MIN_DIM_SIZE)),
int(np.log2(_MAX_DIM_SIZE)) + 1,
))
class UnaryOpFuzzer(Fuzzer... | pytorch-master | torch/utils/benchmark/op_fuzzers/unary.py |
"""Timer class based on the timeit.Timer class, but torch aware."""
import enum
import timeit
import textwrap
from typing import overload, Any, Callable, Dict, List, NoReturn, Optional, Tuple, Type, Union
import torch
from torch.utils.benchmark.utils import common, cpp_jit
from torch.utils.benchmark.utils._stubs impor... | pytorch-master | torch/utils/benchmark/utils/timer.py |
pytorch-master | torch/utils/benchmark/utils/__init__.py | |
from typing import Optional, Tuple, Union
from numbers import Number
import torch
from torch.utils.benchmark import FuzzedTensor
import math
class FuzzedSparseTensor(FuzzedTensor):
def __init__(
self,
name: str,
size: Tuple[Union[str, int], ...],
min_elements: Optional[int] = None,
... | pytorch-master | torch/utils/benchmark/utils/sparse_fuzzer.py |
"""Base shared classes and utilities."""
import collections
import contextlib
import dataclasses
import os
import shutil
import tempfile
import textwrap
import time
from typing import cast, Any, DefaultDict, Dict, Iterable, Iterator, List, Optional, Tuple
import uuid
import torch
__all__ = ["TaskSpec", "Measurement... | pytorch-master | torch/utils/benchmark/utils/common.py |
import functools
import itertools as it
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
__all__ = [
"Fuzzer",
"FuzzedParameter", "ParameterAlias",
"FuzzedTensor",
]
_DISTRIBUTIONS = (
"loguniform",
"uniform",
)
class FuzzedParameter(object)... | pytorch-master | torch/utils/benchmark/utils/fuzzer.py |
"""JIT C++ strings into executables."""
import atexit
import os
import re
import shutil
import textwrap
import threading
from typing import Any, List, Optional
import torch
from torch.utils.benchmark.utils._stubs import CallgrindModuleType, TimeitModuleType
from torch.utils.benchmark.utils.common import _make_temp_dir... | pytorch-master | torch/utils/benchmark/utils/cpp_jit.py |
"""Display class to aggregate and print the results of many measurements."""
import collections
import enum
import itertools as it
from typing import DefaultDict, List, Optional, Tuple
from torch.utils.benchmark.utils import common
from torch import tensor as _tensor
__all__ = ["Colorize", "Compare"]
BEST = "\033[92... | pytorch-master | torch/utils/benchmark/utils/compare.py |
import sys
from typing import Any, Callable, Dict, TYPE_CHECKING
if TYPE_CHECKING or sys.version_info >= (3, 8):
from typing import runtime_checkable, Protocol
else:
from typing_extensions import runtime_checkable, Protocol
class TimerClass(Protocol):
"""This is the portion of the `timeit.Timer` API use... | pytorch-master | torch/utils/benchmark/utils/_stubs.py |
"""Intermediate layer between `Timer` and `valgrind`."""
import collections
import enum
import dataclasses
import itertools as it
import os
import pickle
import re
import shutil
import subprocess
import sys
import textwrap
from typing import (
cast, Any, Callable, DefaultDict, Dict, Generator, List, NamedTuple,
... | pytorch-master | torch/utils/benchmark/utils/valgrind_wrapper/timer_interface.py |
pytorch-master | torch/utils/benchmark/utils/valgrind_wrapper/__init__.py | |
"""Example use of Timer and op fuzzers to measure kernel performance.
$ python -m examples.op_benchmark
"""
import numpy as np
import torch
from torch.utils.benchmark import Timer
from torch.utils.benchmark.op_fuzzers.binary import BinaryOpFuzzer
from torch.utils.benchmark.op_fuzzers.unary import UnaryOpFuzzer
_ME... | pytorch-master | torch/utils/benchmark/examples/op_benchmark.py |
pytorch-master | torch/utils/benchmark/examples/__init__.py | |
"""Trivial use of Timer API:
$ python -m examples.simple_timeit
"""
import torch
import torch.utils.benchmark as benchmark_utils
def main():
timer = benchmark_utils.Timer(
stmt="x + y",
globals={"x": torch.ones((4, 8)), "y": torch.ones((1, 8))},
label="Broadcasting add (4x8)",
)
... | pytorch-master | torch/utils/benchmark/examples/simple_timeit.py |
"""Example of the Timer and Fuzzer APIs:
$ python -m examples.fuzzer
"""
import sys
import torch.utils.benchmark as benchmark_utils
def main():
add_fuzzer = benchmark_utils.Fuzzer(
parameters=[
[
benchmark_utils.FuzzedParameter(
name=f"k{i}",
... | pytorch-master | torch/utils/benchmark/examples/fuzzer.py |
# -*- coding: utf-8 -*-
"""End-to-end example to test a PR for regressions:
$ python -m examples.end_to_end --pr 39850
$ python -m examples.end_to_end --pr 39967
$ python -m examples.end_to_end --pr 39744
NOTE:
This example assumes that you have and environment prefixed with
`ref_`, and another prefixed with `pr_... | pytorch-master | torch/utils/benchmark/examples/end_to_end.py |
import argparse
import datetime
import itertools as it
import multiprocessing
import multiprocessing.dummy
import os
import queue
import pickle
import shutil
import subprocess
import sys
import tempfile
import threading
import time
from typing import Tuple, Dict
from . import blas_compare_setup
MIN_RUN_TIME = 1
NUM_... | pytorch-master | torch/utils/benchmark/examples/blas_compare.py |
import collections
import os
import shutil
import subprocess
try:
# no type stub for conda command line interface
import conda.cli.python_api # type: ignore[import]
from conda.cli.python_api import Commands as conda_commands
except ImportError:
# blas_compare.py will fail to import these when it's ins... | pytorch-master | torch/utils/benchmark/examples/blas_compare_setup.py |
"""Microbenchmarks for the torch.fft module"""
from argparse import ArgumentParser
from collections import namedtuple
from collections.abc import Iterable
import torch
import torch.fft
from torch.utils import benchmark
from torch.utils.benchmark.op_fuzzers.spectral import SpectralOpFuzzer
def _dim_options(ndim):
... | pytorch-master | torch/utils/benchmark/examples/spectral_ops_fuzz_test.py |
"""Example of Timer and Compare APIs:
$ python -m examples.compare
"""
import pickle
import sys
import time
import torch
import torch.utils.benchmark as benchmark_utils
class FauxTorch(object):
"""Emulate different versions of pytorch.
In normal circumstances this would be done with multiple processes
... | pytorch-master | torch/utils/benchmark/examples/compare.py |
"""Example use of Timer and sparse op fuzzers to measure kernel performance.
$ python -m examples.sparse.op_benchmark
"""
import numpy as np
import torch
from torch.utils.benchmark import Timer
from torch.utils.benchmark.op_fuzzers.sparse_unary import UnaryOpSparseFuzzer
from torch.utils.benchmark.op_fuzzers.sparse_... | pytorch-master | torch/utils/benchmark/examples/sparse/op_benchmark.py |
"""Example of the Timer and Sparse Fuzzer APIs:
$ python -m examples.sparse.fuzzer
"""
import sys
import torch.utils.benchmark as benchmark_utils
def main():
add_fuzzer = benchmark_utils.Fuzzer(
parameters=[
[
benchmark_utils.FuzzedParameter(
name=f"k{i}",... | pytorch-master | torch/utils/benchmark/examples/sparse/fuzzer.py |
"""Example of Timer and Compare APIs:
$ python -m examples.sparse.compare
"""
import pickle
import sys
import time
import torch
import torch.utils.benchmark as benchmark_utils
class FauxTorch(object):
"""Emulate different versions of pytorch.
In normal circumstances this would be done with multiple proces... | pytorch-master | torch/utils/benchmark/examples/sparse/compare.py |
from torch._C import _set_backcompat_broadcast_warn
from torch._C import _get_backcompat_broadcast_warn
from torch._C import _set_backcompat_keepdim_warn
from torch._C import _get_backcompat_keepdim_warn
class Warning(object):
def __init__(self, setter, getter):
self.setter = setter
self.getter = ... | pytorch-master | torch/utils/backcompat/__init__.py |
__version__ = '1.0.0'
| pytorch-master | torch/utils/hipify/version.py |
import collections
import os
import re
import subprocess
from .constants import (API_BLAS, API_C10, API_CAFFE2, API_DRIVER, API_FFT,
API_PYTORCH, API_RAND, API_ROCTX, API_RTC, API_RUNTIME,
API_SPARSE, CONV_CACHE, CONV_CONTEXT, CONV_D3D9,
CONV_D3D1... | pytorch-master | torch/utils/hipify/cuda_to_hip_mappings.py |
""" Constants for annotations in the mapping.
The constants defined here are used to annotate the mapping tuples in cuda_to_hip_mappings.py.
They are based on
https://github.com/ROCm-Developer-Tools/HIP/blob/master/hipify-clang/src/Statistics.h
and fall in three categories: 1) type of mapping, 2) API of mapping, 3) uns... | pytorch-master | torch/utils/hipify/constants.py |
from .version import __version__
| pytorch-master | torch/utils/hipify/__init__.py |
#!/usr/bin/env python3
""" The Python Hipify script.
##
# Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
# 2017-2018 Advanced Micro Devices, Inc. and
# Facebook Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obta... | pytorch-master | torch/utils/hipify/hipify_python.py |
pytorch-master | torch/utils/bottleneck/__init__.py | |
import argparse
import cProfile
import pstats
import sys
import os
from typing import Dict
import torch
from torch.autograd import profiler
from torch.utils.collect_env import get_env_info
def redirect_argv(new_argv):
sys.argv[:] = new_argv[:]
def compiled_with_cuda(sysinfo):
if sysinfo.cuda_compiled_versi... | pytorch-master | torch/utils/bottleneck/__main__.py |
pytorch-master | torch/utils/jit/__init__.py | |
from contextlib import contextmanager
from typing import Any, List, Tuple, cast
import random
import torch
import time
from torch.utils.benchmark import Timer
def extract_ir(filename: str) -> List[str]:
BEGIN = "<GRAPH_EXPORT>"
END = "</GRAPH_EXPORT>"
pfx = None
current = ""
graphs = []
with op... | pytorch-master | torch/utils/jit/log_extract.py |
from collections import OrderedDict
import contextlib
from typing import Dict, Any
from tensorboard.compat.proto.config_pb2 import RunMetadata
from tensorboard.compat.proto.graph_pb2 import GraphDef
from tensorboard.compat.proto.step_stats_pb2 import StepStats, DeviceStepStats
from tensorboard.compat.proto.versions_pb... | pytorch-master | torch/utils/tensorboard/_pytorch_graph.py |
from typing import Optional
from tensorboard.compat.proto.node_def_pb2 import NodeDef
from tensorboard.compat.proto.attr_value_pb2 import AttrValue
from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto
def attr_value_proto(dtype, shape, s):
"""Creates a dict of objects matching
https://github... | pytorch-master | torch/utils/tensorboard/_proto_graph.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.