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/torch/_export/db/examples/pytree_flatten.py | import torch
from torch._export.db.case import export_case, SupportLevel
from torch.utils import _pytree as pytree
@export_case(
example_inputs=({1: torch.randn(3, 2), 2: torch.randn(3, 2)},),
support_level=SupportLevel.SUPPORTED,
)
def pytree_flatten(x):
"""
Pytree from PyTorch cannot be captured by... | 399 | 22.529412 | 67 | py |
pytorch | pytorch-main/torch/_export/passes/replace_view_ops_with_view_copy_ops_pass.py | from typing import Dict, Optional, Set
import torch
from torch._ops import OpOverload, OpOverloadPacket, HigherOrderOperator
from torch._export.error import InternalError
from torch._export.pass_base import ExportPassBase
__all__ = ["ReplaceViewOpsWithViewCopyOpsPass"]
_NON_FUNCTIONAL_OPS_TO_FUNCTIONAL_OPS: Dict[O... | 2,650 | 35.819444 | 87 | py |
pytorch | pytorch-main/torch/_export/passes/functionalize_side_effectful_ops_pass.py | import copy
from typing import Dict, Optional, Tuple, List
import torch
from torch._export.pass_base import ExportPassBase, PassResult, Argument
from torch._export.pass_infra.node_metadata import NodeMetadata
from torch._export.pass_infra.proxy_value import ProxyValue
from torch._ops import OpOverload
aten = torch.op... | 3,234 | 33.052632 | 103 | py |
pytorch | pytorch-main/torch/_export/passes/add_runtime_assertions_for_constraints_pass.py | from dataclasses import dataclass
import copy
import math
import operator
import traceback
from collections import OrderedDict
from functools import partial
from typing import Dict, List, NamedTuple, Tuple
import sympy
import torch
import torch.fx
from torch.fx.experimental.symbolic_shapes import SymInt
from torch._e... | 11,482 | 40.454874 | 128 | py |
pytorch | pytorch-main/torch/_export/passes/replace_sym_size_ops_pass.py | from typing import Dict
import torch
from torch.fx.passes.infra.pass_base import PassBase, PassResult
replacements: Dict[torch._ops.OpOverloadPacket, torch._ops.OpOverload] = {
torch.ops.aten.sym_size: torch.ops.aten.sym_size.int,
torch.ops.aten.sym_stride: torch.ops.aten.sym_stride.int,
torch.ops.aten.sy... | 1,004 | 33.655172 | 74 | py |
pytorch | pytorch-main/torch/_export/passes/const_prop_pass.py | import torch
from torch.ao.quantization.fx._decomposed import quantized_decomposed_lib # noqa: F401
from torch._subclasses.fake_tensor import FakeTensor
from torch._export.pass_base import ExportPassBase, ProxyValue
__all__ = ["ConstPropPass"]
class ConstPropPass(ExportPassBase):
"""
Performs constant foldi... | 2,324 | 36.5 | 87 | py |
pytorch | pytorch-main/torch/amp/autocast_mode.py | import torch
import functools
import warnings
from typing import Any, Optional
from torch.types import _dtype
__all__ = ['autocast_decorator', 'autocast']
def autocast_decorator(autocast_instance, func):
@functools.wraps(func)
def decorate_autocast(*args, **kwargs):
with autocast_instance:
... | 20,281 | 50.477157 | 130 | py |
pytorch | pytorch-main/torch/signal/windows/windows.py | # -*- coding: utf-8 -*-
from typing import Optional, Iterable
import torch
from math import sqrt
from torch import Tensor
from torch._torch_docs import factory_common_args, parse_kwargs, merge_dicts
__all__ = [
'bartlett',
'blackman',
'cosine',
'exponential',
'gaussian',
'general_cosine',
... | 22,988 | 27.772215 | 132 | py |
pytorch | pytorch-main/torch/cuda/streams.py | import ctypes
import torch
from ._utils import _dummy_type
if not hasattr(torch._C, '_CudaStreamBase'):
# Define dummy base classes
torch._C.__dict__['_CudaStreamBase'] = _dummy_type('_CudaStreamBase')
torch._C.__dict__['_CudaEventBase'] = _dummy_type('_CudaEventBase')
class Stream(torch._C._CudaStreamB... | 8,273 | 34.51073 | 98 | py |
pytorch | pytorch-main/torch/cuda/_utils.py | import torch
from typing import Any
# The _get_device_index has been moved to torch.utils._get_device_index
from torch._utils import _get_device_index as _torch_get_device_index
def _get_device_index(device: Any, optional: bool = False,
allow_cpu: bool = False) -> int:
r"""Gets the device in... | 2,111 | 41.24 | 94 | py |
pytorch | pytorch-main/torch/cuda/memory.py | import collections
import contextlib
import ctypes
import warnings
import pickle
import sys
import os
from typing import Any, Dict, Union, Tuple, Optional
import torch
from . import is_initialized, _get_device_index, _lazy_init, _get_nvml_device_index
from ._utils import _dummy_type
from ._memory_viz import segments... | 32,101 | 39.027431 | 108 | py |
pytorch | pytorch-main/torch/cuda/comm.py | # The functions here have been moved to torch.nn.parallel.comm
from torch.nn.parallel.comm import broadcast, broadcast_coalesced, reduce_add, \
reduce_add_coalesced, scatter, gather
__all__ = ['broadcast', 'broadcast_coalesced', 'reduce_add', 'reduce_add_coalesced', 'scatter', 'gather']
| 293 | 48 | 105 | py |
pytorch | pytorch-main/torch/cuda/nccl.py | import collections
import warnings
import torch.cuda
from typing import Optional, Sequence, Union
__all__ = ['all_reduce', 'reduce', 'broadcast', 'all_gather', 'reduce_scatter']
SUM = 0 # ncclRedOp_t
def is_available(tensors):
if not hasattr(torch._C, '_nccl_all_reduce'):
warnings.warn('PyTorch is no... | 3,946 | 33.622807 | 114 | py |
pytorch | pytorch-main/torch/cuda/nvtx.py | from contextlib import contextmanager
try:
from torch._C import _nvtx
except ImportError:
class _NVTXStub:
@staticmethod
def _fail(*args, **kwargs):
raise RuntimeError("NVTX functions not installed. Are you sure you have a CUDA build?")
rangePushA = _fail
rangePop =... | 2,317 | 24.472527 | 99 | py |
pytorch | pytorch-main/torch/cuda/_sanitizer.py | r"""
This module introduces CUDA Sanitizer, a tool for detecting synchronization errors
between kernels ran on different streams. It stores information on accesses to tensors
to determine if they are synchronized or not. When enabled in a python program and a
possible data race is detected, a detailed warning will be p... | 22,356 | 35.059677 | 98 | py |
pytorch | pytorch-main/torch/cuda/jiterator.py | import torch
from torch import Tensor
from typing import Callable, List
import re
__all__ : List[str] = []
class _CodeParser:
def __init__(self, code_string: str):
optional_ws = r"\s*"
required_ws = r"\s+"
template_params = r"(?P<template_params>\<.+\>)"
return_type = r"(?P<retur... | 6,593 | 38.48503 | 122 | py |
pytorch | pytorch-main/torch/cuda/random.py | import torch
from typing import Iterable, List, Union
from . import _lazy_init, _lazy_call, device_count, current_device
from .. import Tensor
__all__ = ['get_rng_state', 'get_rng_state_all',
'set_rng_state', 'set_rng_state_all',
'manual_seed', 'manual_seed_all',
'seed', 'seed_all', 'i... | 5,240 | 30.957317 | 93 | py |
pytorch | pytorch-main/torch/cuda/__init__.py | r"""
This package adds support for CUDA tensor types, that implement the same
function as CPU tensors, but they utilize GPUs for computation.
It is lazily initialized, so you can always import it, and use
:func:`is_available()` to determine if your system supports CUDA.
:ref:`cuda-semantics` has more details about wo... | 43,400 | 34.779885 | 127 | py |
pytorch | pytorch-main/torch/cuda/_memory_viz.py | import pickle
import sys
import os
import io
import subprocess
import json
from functools import lru_cache
from typing import Any
from itertools import groupby
import base64
import warnings
cache = lru_cache(None)
__all__ = ["format_flamegraph", "segments", "memory", "compare"]
def _frame_fmt(f, full_filename=False)... | 24,996 | 38.427445 | 130 | py |
pytorch | pytorch-main/torch/cuda/profiler.py | import tempfile
import torch
import contextlib
from . import cudart, check_error
__all__ = ["init", "start", "stop", "profile"]
DEFAULT_FLAGS = [
"gpustarttimestamp",
"gpuendtimestamp",
"gridsize3d",
"threadblocksize",
"streamid",
"enableonstart 0",
"conckerneltrace",
]
def init(output_f... | 1,611 | 28.309091 | 121 | py |
pytorch | pytorch-main/torch/cuda/graphs.py | import gc
import torch
from ._utils import _dummy_type
from torch.utils._pytree import tree_flatten as _tree_flatten
from torch.utils._pytree import tree_unflatten as _tree_unflatten
if not hasattr(torch._C, '_CudaStreamBase'):
# Define dummy base classes
torch._C.__dict__['_CUDAGraph'] = _dummy_type('_CUDAGr... | 20,666 | 46.077449 | 126 | py |
pytorch | pytorch-main/torch/cuda/amp/autocast_mode.py | import torch
import functools
import collections
try:
import numpy as np
HAS_NUMPY = True
except ModuleNotFoundError:
np = None # type: ignore[assignment]
from typing import Any
__all__ = ["autocast", "custom_fwd", "custom_bwd"]
class autocast(torch.amp.autocast_mode.autocast):
r"""
See :class:`t... | 4,998 | 38.992 | 115 | py |
pytorch | pytorch-main/torch/cuda/amp/grad_scaler.py | from collections import defaultdict, abc
from enum import Enum
from typing import Any, Dict, List, Optional, Tuple, cast
import inspect
import warnings
import torch
from .common import amp_definitely_not_available
__all__ = ["OptState", "GradScaler"]
class _MultiDeviceReplicator:
"""
Lazily serves copies of... | 27,724 | 46.231687 | 120 | py |
pytorch | pytorch-main/torch/cuda/amp/common.py | import torch
from importlib.util import find_spec
__all__ = ["amp_definitely_not_available"]
def amp_definitely_not_available():
return not (torch.cuda.is_available() or find_spec('torch_xla'))
| 200 | 24.125 | 68 | py |
pytorch | pytorch-main/torch/backends/__init__.py | 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... | 1,781 | 29.724138 | 119 | py |
pytorch | pytorch-main/torch/backends/quantized/__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... | 1,864 | 30.610169 | 90 | py |
pytorch | pytorch-main/torch/backends/openmp/__init__.py | import torch
def is_available():
r"""Returns whether PyTorch is built with OpenMP support."""
return torch._C.has_openmp
| 131 | 17.857143 | 64 | py |
pytorch | pytorch-main/torch/backends/mkl/__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:
"""
On-demand oneMKL verbosing functionality
To make it easier to debug performance issues, oneMKL can dump verbose
messages containi... | 1,726 | 33.54 | 104 | py |
pytorch | pytorch-main/torch/backends/xnnpack/__init__.py | import sys
import torch
import types
class _XNNPACKEnabled:
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):
super(... | 671 | 25.88 | 81 | py |
pytorch | pytorch-main/torch/backends/cuda/__init__.py | import sys
import torch
import contextlib
from enum import IntEnum
from typing import Union
__all__ = ["is_built", "cuFFTPlanCacheAttrContextProp", "cuFFTPlanCache", "cuFFTPlanCacheManager",
"cuBLASModule", "preferred_linalg_library", "cufft_plan_cache", "matmul", "SDPBackend", "enable_flash_sdp",
... | 9,471 | 35.291188 | 129 | py |
pytorch | pytorch-main/torch/backends/mkldnn/__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
c... | 2,821 | 34.275 | 107 | py |
pytorch | pytorch-main/torch/backends/_coreml/preprocess.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... | 4,138 | 31.590551 | 117 | py |
pytorch | pytorch-main/torch/backends/mps/__init__.py | import torch
from functools import lru_cache as _lru_cache
from ...library import Library as _Library
__all__ = ["is_built", "is_available", "is_macos13_or_newer"]
def is_built() -> bool:
r"""Returns whether PyTorch is built with MPS support. Note that this
doesn't necessarily mean MPS is available; just tha... | 1,423 | 34.6 | 99 | py |
pytorch | pytorch-main/torch/backends/opt_einsum/__init__.py | from typing import Any
import warnings
import sys
from functools import lru_cache as _lru_cache
from contextlib import contextmanager
from torch.backends import ContextProp, PropModule, __allow_nonbracketed_mutation
try:
import opt_einsum as _opt_einsum # type: ignore[import]
except ImportError:
_opt_einsum =... | 3,428 | 33.29 | 118 | py |
pytorch | pytorch-main/torch/backends/cpu/__init__.py | import torch
__all__ = ["get_cpu_capability", ]
def get_cpu_capability() -> str:
r"""Returns cpu capability as a string value.
Possible values:
- "DEFAULT"
- "VSX"
- "Z VECTOR"
- "NO AVX"
- "AVX2"
- "AVX512"
"""
return torch._C._get_cpu_capability()
| 294 | 15.388889 | 49 | py |
pytorch | pytorch-main/torch/backends/_nnapi/serializer.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:
FLOAT32 ... | 79,940 | 37.194458 | 120 | py |
pytorch | pytorch-main/torch/backends/_nnapi/prepare.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... | 6,330 | 35.595376 | 110 | py |
pytorch | pytorch-main/torch/backends/cudnn/__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 =... | 6,302 | 37.432927 | 121 | py |
pytorch | pytorch-main/torch/backends/cudnn/rnn.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':... | 1,944 | 31.966102 | 120 | py |
pytorch | pytorch-main/torch/backends/xeon/run_cpu.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... | 35,171 | 49.245714 | 129 | py |
pytorch | pytorch-main/torch/_custom_op/autograd.py | import torch
import torch.utils._pytree as pytree
from collections import namedtuple
import functools
# NOTE [CustomOp autograd kernel indirection]
# We register `inner` as the autograd kernel for this custom_op.
# `inner` either calls the autograd formula registered by the user,
# or goes into an `autograd_not_imple... | 10,450 | 42.00823 | 88 | py |
pytorch | pytorch-main/torch/_custom_op/functional.py | import torch
from torch.library import Library
from torch._ops import OpOverload
from torchgen.model import FunctionSchema, OperatorName, SchemaKind, BaseTy, BaseType
from torch._C import _ExcludeDispatchKeyGuard, DispatchKeySet, DispatchKey
from .autograd import autograd_not_implemented
import torch.utils._pytree as p... | 7,648 | 42.95977 | 98 | py |
pytorch | pytorch-main/torch/_custom_op/impl.py | import contextlib
import dataclasses
import functools
import inspect
import typing
import weakref
from torchgen.model import FunctionSchema, OperatorName, SchemaKind
import torch
import torch._C as _C
import torch.library as library
from .autograd import autograd_kernel_indirection, construct_autograd_kernel
"""
Th... | 34,841 | 38.148315 | 114 | py |
pytorch | pytorch-main/torch/_higher_order_ops/out_dtype.py |
import torch
import torch.utils._pytree as pytree
from torch.fx.experimental.proxy_tensor import (
disable_proxy_modes_tracing,
ProxyTorchDispatchMode,
track_tensor_tree,
)
from torch.utils._python_dispatch import (
_get_current_dispatch_mode,
_pop_mode_temporarily,
)
from torch._C import DispatchK... | 6,870 | 35.743316 | 92 | py |
pytorch | pytorch-main/torch/_higher_order_ops/wrap.py | from torch._ops import HigherOrderOperator
from torch.utils.checkpoint import checkpoint
from itertools import count
import inspect
uid = count(1)
# Used for testing the HigherOrderOperator mechanism
class Wrap(HigherOrderOperator):
def __init__(self):
super().__init__("wrap")
def __call__(self, func... | 5,846 | 42.634328 | 111 | py |
pytorch | pytorch-main/torch/futures/__init__.py | from __future__ import annotations
from typing import cast, Callable, Generic, List, Optional, Type, TypeVar, Union
import torch
__all__ = ['Future', 'collect_all', 'wait_all']
T = TypeVar("T")
S = TypeVar("S")
class _PyFutureMeta(type(torch._C.Future), type(Generic)): # type: ignore[misc, no-redef]
pass
c... | 14,392 | 44.119122 | 102 | py |
pytorch | pytorch-main/torch/func/__init__.py | from torch._functorch.eager_transforms import (
grad_and_value,
vjp,
jvp,
jacrev,
jacfwd,
hessian,
functionalize,
linearize
)
from torch._functorch.apis import grad
from torch._functorch.functional_call import functional_call, stack_module_state
from torch._functorch.batch_norm_replaceme... | 401 | 25.8 | 83 | py |
pytorch | pytorch-main/torch/autograd/profiler_util.py | import itertools
import torch
from torch.autograd import DeviceType
from collections import defaultdict, namedtuple
from operator import attrgetter
from typing import Any, Dict, List, Tuple, Optional
import bisect
import math
__all__ = ["EventList", "FormattedTimesMixin", "Interval", "Kernel", "FunctionEvent", "Fun... | 35,216 | 36.867742 | 112 | py |
pytorch | pytorch-main/torch/autograd/gradcheck.py | import torch
from torch.types import _TensorOrTensors
import torch.testing
from torch.overrides import is_tensor_like
import collections
from itertools import product
import warnings
from typing import Callable, Union, Optional, Iterable, List, Tuple, Dict
from torch._vmap_internals import vmap, _vmap
import functools
... | 86,622 | 49.568009 | 132 | py |
pytorch | pytorch-main/torch/autograd/functional.py | import torch
from typing import Tuple, List
from . import forward_ad as fwAD
from torch._vmap_internals import _vmap
__all__ = ["vjp", "jvp", "jacobian", "hessian", "hvp", "vhp"]
# Utility functions
def _as_tuple_nocheck(x):
if isinstance(x, tuple):
return x
elif isinstance(x, list):
return ... | 51,035 | 48.597668 | 129 | py |
pytorch | pytorch-main/torch/autograd/graph.py | import torch
import contextlib
from typing import Callable, Any, Dict, Tuple, Optional, Sequence, List, Set
from torch.utils.hooks import RemovableHandle
from torch.utils._python_dispatch import TorchDispatchMode
from collections import defaultdict
import weakref
import abc
__all__ = [
"saved_tensors_hooks",
"... | 21,870 | 37.43761 | 118 | py |
pytorch | pytorch-main/torch/autograd/forward_ad.py | import torch
import os
from .grad_mode import _DecoratorContextManager
from collections import namedtuple
from typing import Any
__all__ = ["UnpackedDualTensor", "enter_dual_level", "exit_dual_level", "make_dual", "unpack_dual", "dual_level"]
# Global variable used to make the python API simpler to use
_current_leve... | 7,589 | 36.95 | 115 | py |
pytorch | pytorch-main/torch/autograd/anomaly_mode.py | import torch
import warnings
from typing import Any
__all__ = ["detect_anomaly", "set_detect_anomaly"]
class detect_anomaly:
r"""Context-manager that enable anomaly detection for the autograd engine.
This does two things:
- Running the forward pass with detection enabled will allow the backward
... | 4,812 | 39.788136 | 91 | py |
pytorch | pytorch-main/torch/autograd/variable.py | import torch
from torch._C import _ImperativeEngine as ImperativeEngine
__all__ = ["VariableMeta", "Variable"]
class VariableMeta(type):
def __instancecheck__(cls, other):
return isinstance(other, torch.Tensor)
class Variable(torch._C._LegacyVariableBase, metaclass=VariableMeta): # type: ignore[misc]... | 364 | 23.333333 | 91 | py |
pytorch | pytorch-main/torch/autograd/grad_mode.py | import torch
from typing import Any, Optional
from torch.utils._contextlib import _DecoratorContextManager
__all__ = ['no_grad', 'enable_grad', 'set_grad_enabled',
'inference_mode', 'set_multithreading_enabled']
class no_grad(_DecoratorContextManager):
r"""Context-manager that disabled gradient calcul... | 11,887 | 34.592814 | 117 | py |
pytorch | pytorch-main/torch/autograd/function.py | import torch
import torch._C as _C
from torch._C import _functions
import torch._functorch as _functorch
import torch.utils.hooks as hooks
import functools
import warnings
from collections import OrderedDict
from typing import Any, List, Optional, Tuple
from torch._functorch.autograd_function import custom_function_cal... | 31,387 | 42.115385 | 126 | py |
pytorch | pytorch-main/torch/autograd/__init__.py | """
``torch.autograd`` provides classes and functions implementing automatic
differentiation of arbitrary scalar valued functions. It requires minimal
changes to the existing code - you only need to declare :class:`Tensor` s
for which gradients should be computed with the ``requires_grad=True`` keyword.
As of now, we o... | 20,125 | 50.081218 | 119 | py |
pytorch | pytorch-main/torch/autograd/profiler.py | from typing import Any, Dict, List, Optional
from collections import defaultdict
from warnings import warn
import torch
import torch.cuda
from torch._C._profiler import _ExperimentalConfig
from torch._C import _get_privateuse1_backend_name
from torch.autograd import (
_disable_profiler,
_enable_profiler,
... | 40,088 | 41.512195 | 113 | py |
pytorch | pytorch-main/torch/autograd/profiler_legacy.py | import torch
import torch.cuda
from torch.autograd.profiler_util import (
EventList, FunctionEvent, MEMORY_EVENT_NAME,
_filter_name, _filter_stack_entry, _rewrite_name
)
from torch.autograd import (
DeviceType, ProfilerConfig, ProfilerState,
_disable_profiler_legacy, _enable_profiler_legacy,
)
import ... | 11,336 | 36.79 | 95 | py |
pytorch | pytorch-main/torch/autograd/_functions/tensor.py | from functools import reduce
import warnings
import torch
import torch._utils
from ..function import Function
class Type(Function):
@staticmethod
def forward(ctx, i, dest_type):
warnings.warn("torch.autograd._functions.Type is deprecated as of PyTorch 2.1, please use "
"torch.te... | 1,987 | 35.145455 | 99 | py |
pytorch | pytorch-main/torch/optim/lr_scheduler.py | import types
import math
from torch import inf
from functools import wraps, partial
import warnings
import weakref
from collections import Counter
from bisect import bisect_right
from .optimizer import Optimizer
__all__ = ['LambdaLR', 'MultiplicativeLR', 'StepLR', 'MultiStepLR', 'ConstantLR', 'LinearLR',
'... | 74,972 | 42.187212 | 132 | py |
pytorch | pytorch-main/torch/optim/swa_utils.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
from torch.utils._foreach_utils import _get_foreach_kernels_supported_devices
__all__ = [
'AveragedModel',
'update_bn',
'SWALR',
'get_ema_mul... | 16,573 | 42.846561 | 113 | py |
pytorch | pytorch-main/torch/optim/_functional.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... | 3,319 | 40.5 | 97 | py |
pytorch | pytorch-main/torch/optim/sgd.py | import torch
from torch import Tensor
from .optimizer import (Optimizer, required, _use_grad_for_differentiable, _default_to_fused_or_foreach,
_differentiable_doc, _foreach_doc, _maximize_doc)
from typing import List, Optional
__all__ = ['SGD', 'sgd']
class SGD(Optimizer):
def __init__(sel... | 13,789 | 40.914894 | 124 | py |
pytorch | pytorch-main/torch/optim/radam.py | import math
import torch
from torch import Tensor
from .optimizer import (Optimizer, _use_grad_for_differentiable, _get_value, _dispatch_sqrt, _stack_if_compiling,
_default_to_fused_or_foreach, _differentiable_doc, _foreach_doc)
from typing import List, Optional
__all__ = ["RAdam", "radam"]
... | 14,481 | 37.721925 | 122 | py |
pytorch | pytorch-main/torch/optim/lbfgs.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... | 17,249 | 35.163522 | 91 | py |
pytorch | pytorch-main/torch/optim/nadam.py | import torch
from torch import Tensor
from .optimizer import (Optimizer, _use_grad_for_differentiable, _get_value, _dispatch_sqrt, _stack_if_compiling,
_differentiable_doc, _foreach_doc, _default_to_fused_or_foreach)
from typing import List, Optional
__all__ = ['NAdam', 'nadam']
class NAdam(Op... | 15,004 | 44.607903 | 132 | py |
pytorch | pytorch-main/torch/optim/asgd.py | import torch
from torch import Tensor
from .optimizer import (Optimizer, _use_grad_for_differentiable, _get_value, _default_to_fused_or_foreach,
_differentiable_doc, _foreach_doc, _maximize_doc)
from torch._utils import is_compiling
from typing import List, Optional
__all__ = ["ASGD", "asgd"]
... | 10,567 | 29.810496 | 112 | py |
pytorch | pytorch-main/torch/optim/adamax.py | import torch
from torch import Tensor
from .optimizer import (Optimizer, _use_grad_for_differentiable, _get_value, _stack_if_compiling,
_default_to_fused_or_foreach, _differentiable_doc, _maximize_doc, _foreach_doc)
from typing import List, Optional
__all__ = ["Adamax", "adamax"]
class Adama... | 12,516 | 35.492711 | 130 | py |
pytorch | pytorch-main/torch/optim/adam.py | from typing import List, Optional
import torch
from torch import Tensor
from .optimizer import (Optimizer, _use_grad_for_differentiable, _get_value, _stack_if_compiling,
_dispatch_sqrt, _default_to_fused_or_foreach, _capturable_doc,
_differentiable_doc, _foreach_doc, _fu... | 26,833 | 43.574751 | 119 | py |
pytorch | pytorch-main/torch/optim/adamw.py | import torch
from torch import Tensor
from .optimizer import (Optimizer, _use_grad_for_differentiable, _get_value, _dispatch_sqrt,
_stack_if_compiling, _capturable_doc, _differentiable_doc, _foreach_doc,
_fused_doc, _maximize_doc, _default_to_fused_or_foreach)
from typing... | 26,054 | 39.023041 | 113 | py |
pytorch | pytorch-main/torch/optim/__init__.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 also be easily integrated in the
future.
"""
from .adadelta import Adadelta
from .adagrad import Adagrad
from .ada... | 834 | 20.410256 | 78 | py |
pytorch | pytorch-main/torch/optim/sparse_adam.py | import torch
from . import _functional as F
from .optimizer import Optimizer, _maximize_doc
__all__ = ['SparseAdam']
class SparseAdam(Optimizer):
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, maximize: bool = False):
if not 0.0 < lr:
raise ValueError("Invalid learning rate:... | 7,367 | 45.339623 | 119 | py |
pytorch | pytorch-main/torch/optim/rmsprop.py | import torch
from torch import Tensor
from .optimizer import (Optimizer, _default_to_fused_or_foreach, _use_grad_for_differentiable,
_differentiable_doc, _foreach_doc, _maximize_doc)
from typing import List, Optional
__all__ = ["RMSprop", "rmsprop"]
class RMSprop(Optimizer):
def __init__(... | 14,416 | 37.964865 | 129 | py |
pytorch | pytorch-main/torch/optim/adagrad.py | import torch
from torch import Tensor
from .optimizer import (Optimizer, _use_grad_for_differentiable, _get_value,
_default_to_fused_or_foreach, _differentiable_doc, _foreach_doc, _maximize_doc)
from typing import List, Optional
__all__ = ["Adagrad", "adagrad"]
class Adagrad(Optimizer):
... | 13,726 | 35.314815 | 114 | py |
pytorch | pytorch-main/torch/optim/optimizer.py | from collections import OrderedDict, defaultdict, abc as container_abcs
import torch
from copy import deepcopy
from itertools import chain
import warnings
import functools
import math
from typing import Any, Callable, Dict, List, Tuple, Optional
from torch import Tensor
import torch.utils.hooks as hooks
from torch.ut... | 28,894 | 46.446634 | 137 | py |
pytorch | pytorch-main/torch/optim/rprop.py | import torch
from torch import Tensor
from .optimizer import (Optimizer, _use_grad_for_differentiable, _default_to_fused_or_foreach,
_differentiable_doc, _foreach_doc, _maximize_doc)
from typing import List, Optional
__all__ = ["Rprop", "rprop"]
class Rprop(Optimizer):
def __init__(
... | 12,028 | 36.126543 | 108 | py |
pytorch | pytorch-main/torch/optim/adadelta.py | import torch
from torch import Tensor
from .optimizer import (Optimizer, _use_grad_for_differentiable, _default_to_fused_or_foreach,
_differentiable_doc, _foreach_doc, _maximize_doc)
from typing import List, Optional
__all__ = ["Adadelta", "adadelta"]
class Adadelta(Optimizer):
def __ini... | 10,822 | 34.485246 | 110 | py |
pytorch | pytorch-main/torch/optim/_multi_tensor/__init__.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... | 1,010 | 33.862069 | 91 | py |
pytorch | pytorch-main/torch/_dynamo/convert_frame.py | import functools
import itertools
import logging
import os
import random
import types
import weakref
from typing import Dict, Optional, Set
import torch
import torch._logging
from torch._guards import tracing
from torch._utils_internal import signpost_event
from torch.fx.experimental.symbolic_shapes import (
Const... | 19,741 | 32.68942 | 108 | py |
pytorch | pytorch-main/torch/_dynamo/codegen.py | import collections
import dataclasses
import re
import sys
import types
from typing import List
import torch.nn
from . import utils
from .bytecode_transformation import (
create_call_function,
create_dup_top,
create_instruction,
create_load_global,
create_rot_n,
Instruction,
)
from .exc import... | 13,089 | 35.260388 | 86 | py |
pytorch | pytorch-main/torch/_dynamo/config_utils.py | import contextlib
import copy
import pickle
import unittest
from types import FunctionType, ModuleType
from typing import Any, Dict, Set
from unittest import mock
# Types saved/loaded in configs
CONFIG_TYPES = (int, float, bool, type(None), str, list, set, tuple, dict)
def install_config_module(module):
"""
... | 7,316 | 30.813043 | 87 | py |
pytorch | pytorch-main/torch/_dynamo/skipfiles.py | import _collections_abc
import _weakrefset
import abc
import collections
import contextlib
import copy
import copyreg
import dataclasses
import enum
import functools
import glob
import importlib
import inspect
import linecache
import logging
import multiprocessing
import operator
import os
import posixpath
import rando... | 6,187 | 23.851406 | 85 | py |
pytorch | pytorch-main/torch/_dynamo/eval_frame.py | from __future__ import annotations
import contextlib
import dataclasses
import dis
import functools
import inspect
import logging
import os
import sys
import textwrap
import threading
import traceback
import types
import warnings
import weakref
from enum import Enum
from os.path import dirname, join
from typing import... | 47,320 | 35.261303 | 124 | py |
pytorch | pytorch-main/torch/_dynamo/logging.py | import itertools
import logging
from torch.hub import _Faketqdm, tqdm
# Disable progress bar by default, not in dynamo config because otherwise get a circular import
disable_progress = True
# Return all loggers that torchdynamo/torchinductor is responsible for
def get_loggers():
return [
logging.getLogg... | 1,548 | 25.706897 | 95 | py |
pytorch | pytorch-main/torch/_dynamo/utils.py | import atexit
import collections
import contextlib
import copy
import cProfile
import dataclasses
import datetime
import dis
import enum
import functools
import gc
import inspect
import itertools
import logging
import math
import operator
import os
import pstats
import sys
import textwrap
import time
import types
impor... | 53,299 | 29.526919 | 129 | py |
pytorch | pytorch-main/torch/_dynamo/bytecode_transformation.py | import copy
import dataclasses
import dis
import itertools
import sys
import types
from typing import Any, Dict, List, Optional, Tuple
from .bytecode_analysis import (
get_indexof,
propagate_line_nums,
remove_extra_line_nums,
stacksize_analysis,
)
@dataclasses.dataclass
class InstructionExnTabEntry:
... | 37,790 | 33.959297 | 95 | py |
pytorch | pytorch-main/torch/_dynamo/testing.py | import contextlib
import dis
import functools
import logging
import os.path
import re
import sys
import types
import unittest
from unittest.mock import patch
import torch
from torch import fx
from torch._dynamo.output_graph import OutputGraph
from . import config, eval_frame, optimize_assert, reset, utils
from .bytec... | 10,669 | 28.393939 | 88 | py |
pytorch | pytorch-main/torch/_dynamo/test_minifier_common.py | import dataclasses
import io
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
import traceback
from unittest.mock import patch
import torch
import torch._dynamo
import torch._dynamo.test_case
from torch.utils._traceback import report_compile_source_on_error
@dataclasses.d... | 9,518 | 38.012295 | 107 | py |
pytorch | pytorch-main/torch/_dynamo/types.py | import dataclasses
import sys
import types
from typing import (
Any,
Callable,
Dict,
List,
NamedTuple,
Optional,
OrderedDict,
Protocol,
Union,
)
if sys.version_info >= (3, 11):
from torch._C._dynamo import eval_frame
DynamoFrameType = eval_frame._PyInterpreterFrame
else:
... | 1,729 | 18.885057 | 75 | py |
pytorch | pytorch-main/torch/_dynamo/exc.py | import os
import textwrap
from enum import auto, Enum
from traceback import extract_stack, format_exc, format_list, FrameSummary
from typing import cast, List
from . import config
from .config import is_fbcode
from .utils import counters, format_bytecode
if is_fbcode():
from torch.fb.exportdb.logging import expo... | 7,644 | 27.632959 | 118 | py |
pytorch | pytorch-main/torch/_dynamo/source.py | import collections
import dataclasses
import enum
from typing import Any, Optional, Union
from torch._guards import ChainedSource, GuardSource, Source
from . import utils
from .bytecode_transformation import create_call_function, create_instruction
from .utils import enum_repr
# It shouldn't be supported to construc... | 14,987 | 29.401623 | 106 | py |
pytorch | pytorch-main/torch/_dynamo/guards.py | import ast
import builtins
import collections
import dataclasses
import enum
import functools
import importlib
import itertools
import logging
import math
import os
import re
import sys
import types
import weakref
from inspect import currentframe, getframeinfo
from typing import Any, Callable, Dict, List, Optional, Set... | 47,038 | 38.42917 | 187 | py |
pytorch | pytorch-main/torch/_dynamo/config.py | import inspect
import os
import re
import sys
import tempfile
from os.path import abspath, dirname
import torch
from . import external_utils
# to configure logging for dynamo, aot, and inductor
# use the following API in the torch._logging module
# torch._logging.set_logs(dynamo=<level>, aot=<level>, inductor<level>... | 11,437 | 38.171233 | 112 | py |
pytorch | pytorch-main/torch/_dynamo/mutation_guard.py | import functools
import weakref
import torch.nn
from torch.nn import Module
from .utils import ExactWeakKeyDictionary, is_lazy_module
class MutationTracker:
db = ExactWeakKeyDictionary()
def __init__(self):
self.mutation_count = 0
self.watchers = []
def on_mutation(self, name):
... | 3,247 | 25.622951 | 86 | py |
pytorch | pytorch-main/torch/_dynamo/allowed_functions.py | import builtins
import collections
import copy
import functools
import inspect
import itertools
import math
import operator
import types
import warnings
from typing import cast, Dict, Optional, Set
import torch
from torch.fx._symbolic_trace import is_fx_tracing
from . import config
from .external_utils import is_comp... | 10,112 | 31.413462 | 105 | py |
pytorch | pytorch-main/torch/_dynamo/symbolic_convert.py | import collections
import contextlib
import copy
import dataclasses
import dis
import functools
import importlib
import inspect
import itertools
import linecache
import logging
import operator
import sys
import traceback
import types
import typing
import weakref
from collections.abc import Sized
from typing import Any,... | 89,756 | 35.876335 | 121 | py |
pytorch | pytorch-main/torch/_dynamo/comptime.py | # This file establishes the public comptime interface to Dynamo.
# This allows Dynamo users to execute arbitrary Python code while
# Dynamo is symbolically evaluating their original programs.
#
# The goal of the public API is to give users rope, without actually
# leaking private implementation details of Dynamo.
impo... | 11,130 | 31.546784 | 86 | py |
pytorch | pytorch-main/torch/_dynamo/replay_record.py | import dataclasses
from dataclasses import field
from types import CodeType, ModuleType
from typing import Any, Dict
try:
import dill
except ImportError:
dill = None
@dataclasses.dataclass
class ModuleRecord:
module: ModuleType
accessed_attrs: Dict[str, Any] = field(default_factory=dict)
@dataclass... | 3,564 | 28.708333 | 87 | py |
pytorch | pytorch-main/torch/_dynamo/profiler.py | import dataclasses
import os
from typing import Any, List
import torch
from .utils import print_once
@dataclasses.dataclass
class ProfileMetrics:
microseconds: float = 0.0
operators: int = 0
fusions: int = 0
graphs: int = 0
def __iadd__(self, other: "ProfileMetrics"):
self.microseconds ... | 5,953 | 31.535519 | 86 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.