python_code
stringlengths
0
1.02M
repo_name
stringlengths
9
48
file_path
stringlengths
5
114
from .graph_module import GraphModule from .graph import Graph from .node import Node from ._symbolic_trace import symbolic_trace from ._compatibility import compatibility import copy from typing import Callable, Dict, List, NamedTuple, Optional, Set import torch __all__ = ['Match', 'replace_pattern'] @compatibility...
pytorch-master
torch/fx/subgraph_rewriter.py
from .graph_module import GraphModule from .graph import Graph from .node import Argument, Node, Target, map_arg, map_aggregate from .proxy import Proxy from ._symbolic_trace import Tracer from ._compatibility import compatibility import torch.fx.traceback as fx_traceback from typing import Any, Dict, Iterator, List, O...
pytorch-master
torch/fx/interpreter.py
import builtins import copy import functools import inspect import math import os import warnings from itertools import chain from types import CodeType, FunctionType, ModuleType from typing import ( Any, Callable, Dict, List, NamedTuple, Optional, Set, Tuple, Type, Union, ) imp...
pytorch-master
torch/fx/_symbolic_trace.py
# Nodes represent a definition of a value in our graph of operators. from typing import TYPE_CHECKING, Union, Callable, Any, Tuple, List, Optional, Dict, Set from ._compatibility import compatibility from .immutable_collections import immutable_dict, immutable_list import torch import builtins import types import warni...
pytorch-master
torch/fx/node.py
from typing import Any, Dict import textwrap _BACK_COMPAT_OBJECTS : Dict[Any, None] = {} _MARKED_WITH_COMATIBLITY : Dict[Any, None] = {} def compatibility(is_backward_compatible : bool): if is_backward_compatible: def mark_back_compat(fn): docstring = textwrap.dedent(getattr(fn, '__doc__', No...
pytorch-master
torch/fx/_compatibility.py
import torch import torch.fx import warnings import functools import builtins from typing import Any, Callable, Dict, Optional, Union def embedding_override(self, input): return torch.empty(*input.shape, self.weight.shape[-1], device='meta') def nn_layernorm_override(self, input): return input def torch_r...
pytorch-master
torch/fx/experimental/meta_tracer.py
from enum import Enum from typing import NamedTuple, Dict, List, Set from torch.fx.node import Node, map_arg class Partition: """Partition class contains all the information about an individual partition. It also provides necessary methods for manipulation the partition. """ def __init__(self, parti...
pytorch-master
torch/fx/experimental/partitioner_utils.py
import ast import inspect import textwrap import copy import functools from types import FunctionType from typing import cast, Union, Callable, Dict, Optional, Any from torch.fx._symbolic_trace import Tracer from torch.fx.graph import Graph from torch._sources import normalize_source_lines import torch class AST_Rewri...
pytorch-master
torch/fx/experimental/rewriter.py
import re from typing import Callable, Dict, Optional, Set, Union import torch.fx from torch.fx.node import map_arg from torch.fx.passes.split_module import split_module class FoldedGraphModule(torch.fx.GraphModule): """ FoldedGraphModule is a GraphModule which also contains another `const_subgraph_modul...
pytorch-master
torch/fx/experimental/const_fold.py
import operator from typing import Dict, List, Set, NamedTuple, Tuple import torch from torch.fx.passes.graph_manipulation import get_size_of_all_nodes from torch.fx.experimental.partitioner_utils import ( Partition, Device, PartitionerConfig, get_partition_to_latency_mapping, get_latency_of_partit...
pytorch-master
torch/fx/experimental/accelerator_partitioner.py
import operator from typing import Any, Callable, Dict, Tuple, Optional import torch import torch.fx import torch.fx as fx from torch.fx import Transformer, Proxy from torch.fx.node import Argument, Target, Node, map_aggregate from torch.fx.operator_schemas import ( normalize_module, normalize_function, cr...
pytorch-master
torch/fx/experimental/normalize.py
import torch.fx as fx from torch.fx.node import Argument, Target from torch.nn.utils.fusion import fuse_conv_bn_eval from typing import Type, Dict, Any, Tuple, Iterable, Optional, List, cast import torch import torch.nn as nn import torch.nn.functional as F from torch.fx.passes.shape_prop import ShapeProp import copy f...
pytorch-master
torch/fx/experimental/optimization.py
class Equality: def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def __str__(self): return f'{self.lhs} = {self.rhs}' def __repr__(self): return f'{self.lhs} = {self.rhs}' def __eq__(self, other): if isinstance(other, Equality): return se...
pytorch-master
torch/fx/experimental/refinement_types.py
from functools import reduce import torch import operator from torch.fx.tensor_type import Dyn, is_consistent, TensorType, is_more_precise from typing import Callable, Dict from torch.fx.node import Target, Node from torch.nn.modules.batchnorm import BatchNorm2d from torch.nn.modules.conv import Conv2d from torch.fx.ex...
pytorch-master
torch/fx/experimental/graph_gradual_typechecker.py
pytorch-master
torch/fx/experimental/__init__.py
from torch.fx.experimental.graph_gradual_typechecker import Refine from torch.fx.tensor_type import TensorType from torch.fx.experimental.unification import Var, unify # type: ignore[attr-defined] def infer_symbolic_types_single_pass(traced): """ Calls our symbolic inferencer once. """ r = Refine(tra...
pytorch-master
torch/fx/experimental/unify_refinements.py
import torch from torch.fx.node import Node from torch.fx._symbolic_trace import symbolic_trace from torch.fx.passes.tools_common import legalize_graph import itertools import operator from typing import Dict, List def split_result_tensors(result: torch.Tensor, inputs: List[torch.Tensor]) -> List[torch.Tensor]: ...
pytorch-master
torch/fx/experimental/merge_matmul.py
import torch.fx as fx def set_trace(gm: fx.GraphModule) -> fx.GraphModule: """ Sets a breakpoint in `gm`'s generated python code. It drops into pdb when `gm` gets run. Args: gm: graph module to insert breakpoint. It is then recompiled for it to take effect. Returns: th...
pytorch-master
torch/fx/experimental/debug.py
import torch import torch.fx import inspect from typing import Any, Dict, Optional, Tuple from torch.fx.node import Argument, Target from torch._jit_internal import boolean_dispatched from torch.fx.operator_schemas import _torchscript_type_to_python_type from torch.fx import Transformer class AnnotateTypesWithSchema(...
pytorch-master
torch/fx/experimental/schema_type_annotation.py
import torch import torch.utils._pytree as pytree from typing import Dict, Any, List, Type import operator try: import sympy # type: ignore[import] HAS_SYMPY = True except ImportError: HAS_SYMPY = False aten = torch.ops.aten __all__ = [ "has_symbolic_sizes_strides", "create_contiguous", "is_symbolic...
pytorch-master
torch/fx/experimental/symbolic_shapes.py
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import contextlib import functools from typing import Any, Dict, Optional, Tuple, Callable, Union import torch fro...
pytorch-master
torch/fx/experimental/proxy_tensor.py
from functools import partial from .multipledispatch import dispatch # type: ignore[import] namespace = dict() # type: ignore[var-annotated] dispatch = partial(dispatch, namespace=namespace)
pytorch-master
torch/fx/experimental/unification/dispatch.py
# type: ignore[attr-defined] from .core import unify, reify # noqa: F403 from .more import unifiable # noqa: F403 from .variable import var, isvar, vars, variables, Var # noqa: F403
pytorch-master
torch/fx/experimental/unification/__init__.py
from collections.abc import Iterator # type: ignore[import] from functools import partial from .unification_tools import assoc # type: ignore[import] from .utils import transitive_get as walk from .variable import isvar from .dispatch import dispatch ################ # Reificiation # ################ @dispatch(Ite...
pytorch-master
torch/fx/experimental/unification/core.py
import collections import operator from functools import reduce from collections.abc import Mapping __all__ = ('merge', 'merge_with', 'valmap', 'keymap', 'itemmap', 'valfilter', 'keyfilter', 'itemfilter', 'assoc', 'dissoc', 'assoc_in', 'update_in', 'get_in') def _get_factory(f, kwargs): fact...
pytorch-master
torch/fx/experimental/unification/unification_tools.py
from contextlib import contextmanager from .utils import hashable from .dispatch import dispatch _global_logic_variables = set() # type: ignore[var-annotated] _glv = _global_logic_variables class Var(object): """ Logic Variable """ _id = 1 def __new__(cls, *token): if len(token) == 0: ...
pytorch-master
torch/fx/experimental/unification/variable.py
from .core import unify, reify # type: ignore[attr-defined] from .dispatch import dispatch def unifiable(cls): """ Register standard unify and reify operations on class This uses the type and __dict__ or __slots__ attributes to define the nature of the term See Also: >>> class A(object): ... ...
pytorch-master
torch/fx/experimental/unification/more.py
def hashable(x): try: hash(x) return True except TypeError: return False def transitive_get(key, d): """ Transitive dict.get >>> d = {1: 2, 2: 3, 3: 4} >>> d.get(1) 2 >>> transitive_get(1, d) 4 """ while hashable(key) and key in d: key = d[key] ...
pytorch-master
torch/fx/experimental/unification/utils.py
from .core import unify, reify # type: ignore[attr-defined] from .variable import isvar from .utils import _toposort, freeze from .unification_tools import groupby, first # type: ignore[import] class Dispatcher(object): def __init__(self, name): self.name = name self.funcs = dict() self....
pytorch-master
torch/fx/experimental/unification/match.py
from warnings import warn import inspect from .conflict import ordering, ambiguities, super_signature, AmbiguityWarning from .utils import expand_tuples from .variadic import Variadic, isvariadic import itertools as itl class MDNotImplementedError(NotImplementedError): """ A NotImplementedError for multiple dispa...
pytorch-master
torch/fx/experimental/unification/multipledispatch/dispatcher.py
import six from .utils import typename class VariadicSignatureType(type): # checking if subclass is a subclass of self def __subclasscheck__(cls, subclass): other_type = (subclass.variadic_type if isvariadic(subclass) else (subclass,)) return subclass is cls or all( ...
pytorch-master
torch/fx/experimental/unification/multipledispatch/variadic.py
from .core import dispatch from .dispatcher import (Dispatcher, halt_ordering, restart_ordering, MDNotImplementedError)
pytorch-master
torch/fx/experimental/unification/multipledispatch/__init__.py
import inspect import sys from .dispatcher import Dispatcher, MethodDispatcher global_namespace = dict() # type: ignore[var-annotated] def dispatch(*types, **kwargs): """ Dispatch function on the types of the inputs Supports dispatch on all non-keyword arguments. Collects implementations based on the f...
pytorch-master
torch/fx/experimental/unification/multipledispatch/core.py
from .utils import _toposort, groupby from .variadic import isvariadic class AmbiguityWarning(Warning): pass def supercedes(a, b): """ A is consistent and strictly more specific than B """ if len(a) < len(b): # only case is if a is empty and b is variadic return not a and len(b) == 1 and...
pytorch-master
torch/fx/experimental/unification/multipledispatch/conflict.py
from collections import OrderedDict def raises(err, lamda): try: lamda() return False except err: return True def expand_tuples(L): """ >>> expand_tuples([1, (2, 3)]) [(1, 2), (1, 3)] >>> expand_tuples([1, 2]) [(1, 2)] """ if not L: return [()] ...
pytorch-master
torch/fx/experimental/unification/multipledispatch/utils.py
# -*- coding: utf-8 -*- from torch.fx.experimental.migrate_gradual_types.operation import op_add, op_sub, op_mul, op_div, \ op_mod, op_gt, op_lt, op_neq, op_eq from torch.fx.tensor_type import TensorType, Dyn class Constraint: pass class Conj(Constraint): def __init__(self, conjuncts): """ ...
pytorch-master
torch/fx/experimental/migrate_gradual_types/constraint.py
# mypy: ignore-errors import copy import itertools from torch.fx.experimental.migrate_gradual_types.constraint_generator import BinConstraintT, MAX_TENSOR_RANK from torch.fx.experimental.migrate_gradual_types.constraint import T, BinConstraintD, Conj, Constraint, DVar, TVar, \ Transpose from torch.fx.experimental.m...
pytorch-master
torch/fx/experimental/migrate_gradual_types/constraint_transformation.py
from torch.fx.experimental.migrate_gradual_types.constraint import TVar, DVar, BinConstraintD, \ BVar from torch.fx.experimental.migrate_gradual_types.operation import op_leq def gen_tvar(curr): """ Generate a tensor variable :param curr: The current counter :return: a tensor variable and the upda...
pytorch-master
torch/fx/experimental/migrate_gradual_types/util.py
pytorch-master
torch/fx/experimental/migrate_gradual_types/__init__.py
# -*- coding: utf-8 -*- op_add = '+' op_sub = '-' op_mul = '*' op_div = '/' op_eq = '=' op_neq = '!=' op_imp = '=>' op_matching = '⊳' op_consistency = '~' op_precision = '⊑' op_leq = '≤' op_lt = '<' op_gt = '>' op_mod = '%'
pytorch-master
torch/fx/experimental/migrate_gradual_types/operation.py
from torch.fx.experimental.migrate_gradual_types.constraint import Conj, Disj, T, F, BinConstraintT, BVar, is_bool_expr from torch.fx.experimental.migrate_gradual_types.constraint import BinConstraintD, TVar, DVar from torch.fx.experimental.migrate_gradual_types.constraint import Prod, is_algebraic_expression, is_dim f...
pytorch-master
torch/fx/experimental/migrate_gradual_types/transform_to_z3.py
try: import z3 # type: ignore[import] HAS_Z3 = True # dynamic type dyn = z3.DeclareSort('Dyn') dyn_type = z3.Const('dyn', dyn) # dimension dim = z3.Datatype('dim') dim.declare('dim', ('0', z3.IntSort()), ('1', z3.IntSort())) dim = dim.create() # tensors tensor_type = z3.Da...
pytorch-master
torch/fx/experimental/migrate_gradual_types/z3_types.py
import torch import operator from typing import Callable, Dict, Iterable from torch.fx._symbolic_trace import _assert_is_none from torch.fx.experimental.migrate_gradual_types.constraint import ApplyBroadcasting, CalcProduct, \ Disj, TGreatestUpperBound, CalcMaxPool, CalcConv, Conj, BinConstraintT, CanReshape, BinC...
pytorch-master
torch/fx/experimental/migrate_gradual_types/constraint_generator.py
from typing import Any, Callable, Tuple, Dict, Optional import logging import torch import torch.fx from torch.fx.node import map_arg from torch.fx._compatibility import compatibility from .shape_prop import ShapeProp from .split_utils import split_by_tags from .tools_common import ( Tensors, TensorOrTensors,...
pytorch-master
torch/fx/passes/net_min_base.py
from torch.fx.graph_module import GraphModule from typing import Any, Callable, Dict, List, Tuple, Type import torch import torch.nn as nn from torch.fx._compatibility import compatibility __all__ = ['default_matching', 'extract_attrs_for_lowering', 'lift_lowering_attrs_to_nodes'] # Matching method matches the attri...
pytorch-master
torch/fx/passes/param_fetch.py
from typing import List, Tuple, Union, Dict, Any, Set, Mapping import collections from dataclasses import dataclass import torch import torch.fx from torch.fx.node import _get_qualified_name from torch.fx._compatibility import compatibility __all__ = ['get_acc_ops_name', 'get_node_target', 'is_node_output_tensor', 'F...
pytorch-master
torch/fx/passes/tools_common.py
from dataclasses import dataclass, field from typing import List, Optional, Dict import torch.fx from torch.fx.graph import map_arg from .tools_common import NodeList, NodeSet from torch.fx._compatibility import compatibility from torch.fx.passes.utils import lift_subgraph_as_module, HolderModule __all__ = ['getattr_...
pytorch-master
torch/fx/passes/split_utils.py
import torch import torch.fx import traceback from torch.fx.node import Node, map_aggregate from typing import Any, Tuple, NamedTuple, Optional, Dict from torch.fx._compatibility import compatibility __all__ = ['TensorMetadata', 'ShapeProp'] @compatibility(is_backward_compatible=True) class TensorMetadata(NamedTuple...
pytorch-master
torch/fx/passes/shape_prop.py
import torch from torch.fx.graph_module import GraphModule from typing import Callable, List, Dict, Any, Optional from torch.fx._compatibility import compatibility import inspect __all__ = ['Partition', 'split_module'] @compatibility(is_backward_compatible=True) class Partition: def __init__(self, name: str): ...
pytorch-master
torch/fx/passes/split_module.py
import torch from torch.fx import Node from torch.fx._compatibility import compatibility from torch._subclasses.fake_tensor import FakeTensorMode, FakeTensor from torch.utils._pytree import tree_map from torch.multiprocessing.reductions import StorageWeakRef import _operator from enum import Enum import itertools from...
pytorch-master
torch/fx/passes/reinplace.py
from . import graph_drawer from . import graph_manipulation from . import net_min_base from . import operator_support from . import param_fetch from . import reinplace from . import shape_prop from . import split_module from . import split_utils from . import splitter_base from . import tools_common
pytorch-master
torch/fx/passes/__init__.py
from functools import wraps from inspect import unwrap from typing import Callable, List # for callables which modify object inplace and return something other than # the object on which they act def inplace_wrapper(fn: Callable) -> Callable: """ Convenience wrapper for passes which modify an object inplace. ...
pytorch-master
torch/fx/passes/pass_manager.py
import torch.fx from torch.fx import Node from torch.fx._compatibility import compatibility from torch._subclasses.fake_tensor import FakeTensorMode __all__ = ['FakeTensorProp'] @compatibility(is_backward_compatible=False) class FakeTensorProp(torch.fx.Interpreter): """ Execute an FX graph Node-by-Node and re...
pytorch-master
torch/fx/passes/fake_tensor_prop.py
import abc import typing as t import torch import torch.fx from torch.fx._compatibility import compatibility from .shape_prop import TensorMetadata from .tools_common import get_node_target, CALLABLE_NODE_OPS __all__ = ['OperatorSupportBase', 'OperatorSupport', 'create_op_support', 'chain', 'OpSupports'] # fx.Node....
pytorch-master
torch/fx/passes/operator_support.py
from typing import Any, Dict, List, NamedTuple, Optional import torch from torch.fx._compatibility import compatibility from torch.fx.graph import Graph from torch.fx.graph_module import GraphModule from torch.fx.node import ( map_arg, Node, Target, ) from torch.fx.passes.shape_prop import ShapeProp __all...
pytorch-master
torch/fx/passes/graph_manipulation.py
from __future__ import absolute_import, division, print_function, unicode_literals import hashlib import torch import torch.fx from typing import Dict, Any, TYPE_CHECKING from torch.fx.node import _get_qualified_name, _format_arg from torch.fx.passes.shape_prop import TensorMetadata from torch.fx._compatibility import...
pytorch-master
torch/fx/passes/graph_drawer.py
import argparse from collections import defaultdict from dataclasses import dataclass from typing import NamedTuple, Sequence, Iterable, Any, List, Dict, Optional, Tuple import logging import torch from torch.fx.passes.graph_manipulation import get_size_of_node from torch.fx.node import map_arg from torch.fx._compatib...
pytorch-master
torch/fx/passes/splitter_base.py
from typing import Dict, List, Set, Iterable, Optional from torch.fx.passes.utils.fuser_utils import fuse_by_partitions from torch.fx.passes.tools_common import NodeList from torch.fx.graph_module import GraphModule from torch.fx.node import Node, _get_qualified_name from torch.fx.passes.operator_support import Opera...
pytorch-master
torch/fx/passes/infra/partitioner.py
from . import pass_manager
pytorch-master
torch/fx/passes/infra/__init__.py
import abc from collections import namedtuple from typing import Optional from torch.fx.graph_module import GraphModule from torch.fx._compatibility import compatibility __all__ = ['PassResult', 'PassBase'] @compatibility(is_backward_compatible=False) class PassResult(namedtuple("PassResult", ["graph_module", "modi...
pytorch-master
torch/fx/passes/infra/pass_base.py
import inspect from queue import Queue from functools import wraps from typing import Callable, Dict, List import torch.nn as nn from torch.fx.graph_module import GraphModule from torch.fx._compatibility import compatibility from torch.fx.passes.infra.pass_base import PassResult __all__ = ['inplace_wrapper', 'pass_re...
pytorch-master
torch/fx/passes/infra/pass_manager.py
pytorch-master
torch/fx/passes/backends/__init__.py
import torch from torch.fx.passes.infra.partitioner import CapabilityBasedPartitioner from torch.fx.passes.operator_support import OperatorSupport from torch.fx.passes.tools_common import CALLABLE_NODE_OPS from torch.fx.passes.fake_tensor_prop import FakeTensorProp from torch.utils._pytree import tree_map import opera...
pytorch-master
torch/fx/passes/backends/cudagraphs.py
from typing import Dict import torch from torch.nn import Module from torch._ops import OpOverload from torch.fx import GraphModule from torch.fx.node import Node, _get_qualified_name from torch.fx.passes.operator_support import OperatorSupport from torch.fx.passes.tools_common import CALLABLE_NODE_OPS from torch.fx....
pytorch-master
torch/fx/passes/backends/nvfuser.py
pytorch-master
torch/fx/passes/tests/__init__.py
import unittest from ..pass_manager import ( inplace_wrapper, PassManager, these_before_those_pass_constraint, this_before_that_pass_constraint, ) class TestPassManager(unittest.TestCase): def test_pass_manager_builder(self) -> None: passes = [lambda x: 2 * x for _ in range(10)] p...
pytorch-master
torch/fx/passes/tests/test_pass_manager.py
from .common import lift_subgraph_as_module, HolderModule, compare_graphs
pytorch-master
torch/fx/passes/utils/__init__.py
from torch.nn import Module from torch.fx.graph_module import GraphModule from torch.fx.graph import Graph from torch.fx.passes.utils.matcher_utils import SubgraphMatcher from torch.fx._compatibility import compatibility __all__ = ['HolderModule', 'lift_subgraph_as_module', 'compare_graphs'] @compatibility(is_backw...
pytorch-master
torch/fx/passes/utils/common.py
from dataclasses import dataclass, field from collections import defaultdict import copy import torch.library from torch.fx.graph import Graph from torch.fx.node import Node from torch.fx._compatibility import compatibility from typing import Dict, List, Set __all__ = ['SubgraphMatcher', 'InternalMatch'] pseudo = to...
pytorch-master
torch/fx/passes/utils/matcher_utils.py
import copy from queue import SimpleQueue from typing import List, Dict, Tuple import torch.fx from torch.fx.graph_module import GraphModule from torch.fx.graph import Graph from torch.fx.node import Node from torch.fx.passes.tools_common import NodeList, NodeSet, legalize_graph from torch.fx.passes.utils import lift_...
pytorch-master
torch/fx/passes/utils/fuser_utils.py
pytorch-master
torch/fx/passes/dialect/__init__.py
from typing import Dict, Tuple, Any import torch from torch.fx.passes.infra.pass_base import PassBase, PassResult from torch.utils._pytree import tree_flatten from torch.fx import GraphModule, Graph from torch.fx import Node aten = torch.ops.aten # stateful ops are banned from CSE rand_ops = set([aten.dropout, ate...
pytorch-master
torch/fx/passes/dialect/common/cse_pass.py
pytorch-master
torch/fx/passes/dialect/common/__init__.py
from __future__ import annotations from typing import Any, Union, Sequence, Optional, Tuple, List, Callable, Type, overload from enum import Enum from functools import reduce, cmp_to_key import operator import weakref import torch # nvFuser imports are conditional on being compiled with CUDA if hasattr(torch._C, "_n...
pytorch-master
torch/_prims_common/__init__.py
import torch from torch._prims_common import ( Number, NumberType, TensorLike, TensorLikeType, ELEMENTWISE_TYPE_PROMOTION_KIND, ) import torch._prims_common as utils from torch.utils._pytree import tree_flatten, tree_unflatten from typing import Callable, Sequence, Union, Tuple, NamedTuple import i...
pytorch-master
torch/_prims_common/wrappers.py
import io import multiprocessing.queues from multiprocessing.reduction import ForkingPickler import pickle class ConnectionWrapper(object): """Proxy class for _multiprocessing.Connection which uses ForkingPickler to serialize objects""" def __init__(self, conn): self.conn = conn def send(sel...
pytorch-master
torch/multiprocessing/queue.py
import sys __all__ = ['register_after_fork'] if sys.platform == 'win32' or sys.version_info < (3, 7): import multiprocessing.util as _util def _register(func): def wrapper(arg): func() _util.register_after_fork(_register, wrapper) else: import os def _register(func): ...
pytorch-master
torch/multiprocessing/_atfork.py
""" torch.multiprocessing is a wrapper around the native :mod:`multiprocessing` module. It registers custom reducers, that use shared memory to provide shared views on the same data in different processes. Once the tensor/storage is moved to shared_memory (see :func:`~torch.Tensor.share_memory_`), it will be possible t...
pytorch-master
torch/multiprocessing/__init__.py
from typing import Optional import multiprocessing import multiprocessing.connection import signal import sys import warnings from . import _prctl_pr_set_pdeathsig # type: ignore[attr-defined] class ProcessException(Exception): __slots__ = ["error_index", "error_pid"] def __init__(self, msg: str, error_in...
pytorch-master
torch/multiprocessing/spawn.py
import torch import torch.utils.hooks from torch._namedtensor_internals import check_serializing_named_tensor import os import threading import multiprocessing from multiprocessing.util import register_after_fork from multiprocessing.reduction import ForkingPickler from typing import Union try: # Early load resour...
pytorch-master
torch/multiprocessing/reductions.py
import multiprocessing.pool import multiprocessing.util as util from .queue import SimpleQueue def clean_worker(*args, **kwargs): import gc multiprocessing.pool.worker(*args, **kwargs) # Regular multiprocessing workers don't fully clean up after themselves, # so we have to explicitly trigger garbage ...
pytorch-master
torch/multiprocessing/pool.py
import torch from torch.fx import GraphModule from torch.nn import Module from torch.fx.passes.backends.cudagraphs import partition_cudagraphs from torch.multiprocessing.reductions import StorageWeakRef from torch.utils._pytree import tree_map import torchdynamo # type: ignore[import] from torchdynamo.optimizations.tr...
pytorch-master
torch/cuda/_dynamo_graphs.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...
pytorch-master
torch/cuda/streams.py
pytorch-master
torch/cuda/error.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']
pytorch-master
torch/cuda/comm.py
import collections import contextlib import warnings from typing import Any, Dict, Union, Tuple import torch from . import is_initialized, _get_device_index, _lazy_init from ._memory_viz import segments as _segments, memory as _memory from torch.types import Device from torch import _C __all__ = ["caching_allocator...
pytorch-master
torch/cuda/memory.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<return...
pytorch-master
torch/cuda/jiterator.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...
pytorch-master
torch/cuda/nccl.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...
pytorch-master
torch/cuda/__init__.py
import torch from typing import cast, 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_al...
pytorch-master
torch/cuda/random.py
import pickle import sys import os import io import subprocess from typing import Dict, Any __all__ = ["format_flamegraph", "segments", "memory", "compare", "stats", "Bytes"] def _frame_fmt(f): i = f['line'] fname = f['filename'].split('/')[-1] func = f['name'] return f'{fname}:{i}:{func}' def format_...
pytorch-master
torch/cuda/_memory_viz.py
# The Tensor classes are added to this module by python_tensor.cpp
pytorch-master
torch/cuda/sparse.py
from contextlib import contextmanager try: from torch._C import _nvtx except ImportError: class _NVTXStub(object): @staticmethod def _fail(*args, **kwargs): raise RuntimeError("NVTX functions not installed. Are you sure you have a CUDA build?") rangePushA = _fail ra...
pytorch-master
torch/cuda/nvtx.py
import gc import torch from ._utils import _dummy_type if not hasattr(torch._C, '_CudaStreamBase'): # Define dummy base classes torch._C.__dict__['_CUDAGraph'] = _dummy_type('_CUDAGraph') torch._C.__dict__['_graph_pool_handle'] = _dummy_type('_graph_pool_handle') torch._C.__dict__['_cuda_isCurrentStr...
pytorch-master
torch/cuda/graphs.py
import tempfile import contextlib from . import cudart, check_error DEFAULT_FLAGS = [ "gpustarttimestamp", "gpuendtimestamp", "gridsize3d", "threadblocksize", "streamid", "enableonstart 0", "conckerneltrace", ] def init(output_file, flags=None, output_mode='key_value'): rt = cudart()...
pytorch-master
torch/cuda/profiler.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...
pytorch-master
torch/cuda/_utils.py
import torch import functools import collections try: import numpy as np HAS_NUMPY = True except ModuleNotFoundError: np = None # type: ignore[assignment] from torch._six import string_classes from typing import Any class autocast(torch.amp.autocast_mode.autocast): r""" See :class:`torch.autocast...
pytorch-master
torch/cuda/amp/autocast_mode.py
import torch from collections import defaultdict, abc import warnings from enum import Enum from typing import Any, Dict, List, Optional, Tuple from .common import amp_definitely_not_available class _MultiDeviceReplicator(object): """ Lazily serves copies of a tensor to requested devices. Copies are cached p...
pytorch-master
torch/cuda/amp/grad_scaler.py
from .autocast_mode import autocast, custom_fwd, custom_bwd # noqa: F401 from .grad_scaler import GradScaler # noqa: F401
pytorch-master
torch/cuda/amp/__init__.py
import torch from importlib.util import find_spec def amp_definitely_not_available(): return not (torch.cuda.is_available() or find_spec('torch_xla'))
pytorch-master
torch/cuda/amp/common.py