python_code
stringlengths
0
1.02M
repo_name
stringlengths
9
48
file_path
stringlengths
5
114
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. import collections import copy import enum import inspect import io import logging from itertools import chain from typin...
pytorch-master
torch/distributed/optim/zero_redundancy_optimizer.py
from typing import List, Dict, Optional, Tuple import torch import torch.optim._functional as F from torch import Tensor __all__ : List[str] = [] # Define a TorchScript compatible Functional Adamax Optimizer # where we use these optimizer in a functional way. # Instead of using the `param.grad` when updating paramet...
pytorch-master
torch/distributed/optim/functional_adamax.py
from collections import abc, defaultdict import logging from typing import Dict, List, Optional, Union import torch from torch.cuda import FloatTensor # type: ignore[attr-defined] from torch.cuda.amp.grad_scaler import GradScaler, OptState, _MultiDeviceReplicator from torch.distributed.distributed_c10d import Process...
pytorch-master
torch/distributed/fsdp/sharded_grad_scaler.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. # Copyright (c) Tongzhou Wang # Licensed under the MIT License. import contextlib from typing import Any, Dict, Generator, List import torch...
pytorch-master
torch/distributed/fsdp/flatten_params_wrapper.py
import collections import contextlib import copy import functools import itertools import math import traceback import warnings from contextlib import contextmanager from dataclasses import dataclass from enum import Enum, auto from typing import ( Any, Callable, Dict, Generator, Iterable, Itera...
pytorch-master
torch/distributed/fsdp/fully_sharded_data_parallel.py
import copy import functools from typing import ( Any, Dict, Iterable, Iterator, List, NamedTuple, Optional, Sequence, Tuple, Union, ) import torch import torch.distributed as dist # Import the entire FSDP file to avoid circular imports import torch.distributed.fsdp.fully_sharde...
pytorch-master
torch/distributed/fsdp/_optim_utils.py
from .flat_param import FlatParameter from .fully_sharded_data_parallel import ( BackwardPrefetch, CPUOffload, FullStateDictConfig, FullyShardedDataParallel, LocalStateDictConfig, MixedPrecision, OptimStateKeyType, ShardingStrategy, StateDictType, ) from .wrap import ParamExecOrderWr...
pytorch-master
torch/distributed/fsdp/__init__.py
import contextlib from itertools import accumulate, chain from typing import ( Dict, Generator, Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple, Union, ) import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor __all__ = [ "Flat...
pytorch-master
torch/distributed/fsdp/flat_param.py
import contextlib import functools from dataclasses import dataclass, field from typing import Any, Callable, Dict, Generator, List, Optional, Tuple import torch __all__ = ["TracingConfig"] @dataclass class TracingConfig: """ Configurations used in ``ParamExecOrderWrapPolicy`` for symbolic tracing of a...
pytorch-master
torch/distributed/fsdp/_symbolic_trace.py
import bisect import itertools import math from typing import Any, Dict, List, Tuple, Optional import torch import torch.distributed as dist import torch.nn.functional as F from torch.distributed import distributed_c10d from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._shard.sha...
pytorch-master
torch/distributed/fsdp/shard_utils.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. import contextlib from dataclasses import dataclass from typing import ( Any, Callable, Dict, Generator, Optional, Set...
pytorch-master
torch/distributed/fsdp/wrap.py
from collections import OrderedDict import dataclasses from typing import Any, Callable, Dict, List, Set, Tuple, Union import torch from torch.nn.modules.batchnorm import _BatchNorm from torch.nn.parallel.scatter_gather import _is_namedtuple # type: ignore[attr-defined] from torch.nn.utils.rnn import PackedSequence ...
pytorch-master
torch/distributed/fsdp/_utils.py
from dataclasses import dataclass from typing import List, Union, Optional from functools import reduce from torch.distributed.remote_device import _remote_device @dataclass class ShardMetadata(object): """ Represents a shard of the overall Tensor including its offsets, lengths and device placement. ...
pytorch-master
torch/distributed/_shard/metadata.py
import functools from inspect import signature from .common_op_utils import _basic_validation """ Common utilities to register ops on ShardedTensor, ReplicatedTensor and PartialTensor. """ def _register_op(op, func, op_table): """ Performs basic validation and registers the provided op in the given op_tab...
pytorch-master
torch/distributed/_shard/op_registry_utils.py
import abc import torch.nn as nn class Sharder(abc.ABC): """ This is an interface which allows user to create more advanced sharding strategies that are not easily be composed by the `ShardingSpec`. :class:`torch.distributed._shard.sharding_plan.ShardingPlan` could take an object of the `Shard...
pytorch-master
torch/distributed/_shard/sharder.py
from .api import ( _replicate_tensor, _shard_tensor, load_with_process_group, shard_module, shard_parameter, )
pytorch-master
torch/distributed/_shard/__init__.py
import torch from torch.utils._pytree import tree_map from typing import Optional def _basic_validation(op, args=(), kwargs=None): """ Common validation across all ops go in here. """ from torch.distributed._shard.partial_tensor import _PartialTensor from torch.distributed._shard.replicated_tensor ...
pytorch-master
torch/distributed/_shard/common_op_utils.py
import torch import torch.distributed as dist from torch.distributed._shard.sharded_tensor.api import ShardedTensor from torch.distributed import distributed_c10d from torch.overrides import get_default_nowrap_functions _REPLICATED_WITH_NON_TENSOR_ALLOWLIST = [ # List of ops where if parameters are a combination ...
pytorch-master
torch/distributed/_shard/replicated_tensor.py
from contextlib import contextmanager import torch import torch.distributed as dist import torch.nn as nn from torch.distributed import distributed_c10d from torch.distributed._shard.sharded_tensor import ( ShardedTensor, _PartialTensor ) from .replicated_tensor import ReplicatedTensor from .sharding_spec impor...
pytorch-master
torch/distributed/_shard/api.py
import functools from typing import Callable, Dict, TYPE_CHECKING import torch import torch.distributed as dist import torch.distributed._shard.sharding_spec as shard_spec from torch.distributed import distributed_c10d from torch.distributed.nn.functional import ( reduce_scatter, ) from torch.distributed._shard.co...
pytorch-master
torch/distributed/_shard/partial_tensor.py
import torch from torch.distributed._shard.metadata import ShardMetadata from typing import Sequence def narrow_tensor_by_index(tensor: torch.Tensor, offsets: Sequence[int], sizes: Sequence[int]) -> torch.Tensor: """ Narrow the tensor according to ``offsets`` and ``sizes``. """ narrowed_tensor = tensor...
pytorch-master
torch/distributed/_shard/_utils.py
import io from dataclasses import dataclass, field from typing import Dict, List, Tuple, Union, Optional, Sequence, Any import torch from torch.distributed._shard.sharded_tensor import ( ShardedTensor, ) from torch.distributed._shard.sharded_tensor.metadata import TensorProperties @dataclass class ChunkStorageMet...
pytorch-master
torch/distributed/_shard/checkpoint/metadata.py
import os import operator import pickle from typing import List, Optional, Union, cast import torch from torch import Tensor from torch.futures import Future from pathlib import Path from .metadata import ( BytesReadRequest, BytesWriteRequest, Metadata, TensorReadRequest, TensorWriteRequest, ) fro...
pytorch-master
torch/distributed/_shard/checkpoint/filesystem.py
import io from typing import Any, Dict, List, Tuple, Optional, Union import torch import torch.distributed as dist from torch import Tensor from torch.distributed._shard.sharded_tensor import ( ShardedTensor, ) from .metadata import ( Metadata, BytesWriteRequest, TensorWriteRequest, ) from .reshardi...
pytorch-master
torch/distributed/_shard/checkpoint/state_dict_saver.py
from .metadata import ( BytesReadRequest, BytesWriteRequest, TensorStorageMetadata, BytesStorageMetadata, ChunkStorageMetadata, Metadata, TensorReadRequest, TensorWriteRequest, ) from .state_dict_loader import load_state_dict from .state_dict_saver import save_state_dict from .storage im...
pytorch-master
torch/distributed/_shard/checkpoint/__init__.py
import hashlib import io from typing import List, Tuple, Dict import torch from torch import Tensor from torch.distributed._shard.sharded_tensor import ( ShardedTensor, ) from torch.distributed._shard.sharding_spec import ( ShardMetadata, ) from torch.distributed._shard.sharding_spec._internals import ( _...
pytorch-master
torch/distributed/_shard/checkpoint/resharding.py
from typing import Dict, Tuple, Any import traceback as tb WRAPPED_EXCEPTION = Tuple[BaseException, tb.StackSummary] def _wrap_exception(exc: BaseException) -> WRAPPED_EXCEPTION: return (exc, tb.extract_tb(exc.__traceback__)) def _is_wrapped_exception(obj: Any) -> bool: if not isinstance(obj, tuple): ...
pytorch-master
torch/distributed/_shard/checkpoint/api.py
import io from typing import Any, Dict, List, Tuple, Optional, cast from torch.distributed._shard.metadata import ShardMetadata from torch.distributed._shard.sharded_tensor.shard import Shard import torch import torch.distributed as dist from torch import Tensor from torch.distributed._shard.sharded_tensor import ( ...
pytorch-master
torch/distributed/_shard/checkpoint/state_dict_loader.py
from typing import List, Callable, Optional, Union, TypeVar, Dict, Any, cast import torch.distributed as dist from .api import ( CheckpointException, _wrap_exception, _is_wrapped_exception, WRAPPED_EXCEPTION ) import torch from torch.distributed._shard.sharded_tensor import ( ShardedTensor, ) fro...
pytorch-master
torch/distributed/_shard/checkpoint/utils.py
import abc from typing import List, Union from torch.futures import Future from .metadata import ( BytesReadRequest, BytesWriteRequest, Metadata, TensorReadRequest, TensorWriteRequest, ) class StorageWriter(abc.ABC): """ Interface used by ``save_state_dict`` to write to storage. A su...
pytorch-master
torch/distributed/_shard/checkpoint/storage.py
from dataclasses import dataclass, field from enum import Enum from typing import List import torch from torch.distributed._shard.metadata import ShardMetadata class MEM_FORMAT_ENCODING(Enum): TORCH_CONTIGUOUS_FORMAT = 0 TORCH_CHANNELS_LAST = 1 TORCH_PRESERVE_FORMAT = 2 @dataclass class TensorProperties(...
pytorch-master
torch/distributed/_shard/sharded_tensor/metadata.py
# coding=utf-8 import copy import functools from typing import List import torch import torch.distributed._shard.sharding_spec as shard_spec from torch.distributed._shard.partial_tensor import _PartialTensor from .api import ( _CUSTOM_SHARDED_OPS, _SHARDED_OPS, Shard, ShardedTensorBase, ShardedTe...
pytorch-master
torch/distributed/_shard/sharded_tensor/__init__.py
import copy from typing import List, Tuple import torch import torch.distributed as dist from torch._C._distributed_c10d import ( ProcessGroup, ) import torch.distributed._shard.sharding_spec as shard_spec from torch.distributed._shard.sharding_spec._internals import ( get_split_size, get_chunked_dim_size,...
pytorch-master
torch/distributed/_shard/sharded_tensor/reshard.py
from __future__ import annotations # type: ignore[attr-defined] from dataclasses import dataclass from typing import ( Callable, Dict, List, Optional, Sequence, Tuple, cast, ) import copy from functools import reduce import weakref import threading import torch import torch.distributed as ...
pytorch-master
torch/distributed/_shard/sharded_tensor/api.py
from dataclasses import dataclass from typing import List import torch from torch.distributed._shard.metadata import ShardMetadata from torch.distributed.remote_device import _remote_device @dataclass class Shard(object): """ Container which holds the data for a shard as a Tensor and also the associated ...
pytorch-master
torch/distributed/_shard/sharded_tensor/shard.py
import collections.abc import copy from typing import Optional, List, Sequence import torch from torch.distributed import distributed_c10d from torch.distributed import rpc from torch.distributed._shard.sharding_spec._internals import ( check_tensor, validate_non_overlapping_shards_metadata, ) from torch.dist...
pytorch-master
torch/distributed/_shard/sharded_tensor/utils.py
import torch from torch.distributed._shard.sharded_tensor import ( _sharded_op_impl, ) # This is used by `_apply()` within module.py to set new # parameters after apply a certain method, we should follow # the future behavior of overwriting the existing tensor # instead of doing in-place change using `.data = `. @...
pytorch-master
torch/distributed/_shard/sharded_tensor/_ops/misc_ops.py
import copy import torch from torch.distributed._shard.sharded_tensor import ( _sharded_op_impl, Shard, ShardedTensor, ) from ._common import ( _register_sharded_op_on_local_shards, ) from torch.distributed._shard.common_op_utils import _register_default_op # Tensor properties access _register_default...
pytorch-master
torch/distributed/_shard/sharded_tensor/_ops/tensor_ops.py
import functools from torch.distributed._shard.sharded_tensor import ( _sharded_op_impl, Shard, ShardedTensor, ) from torch.distributed._shard.common_op_utils import _basic_validation def _sharded_op_common(op, early_stop_func, extra_check): """ Inject sharded tensor op registration with common log...
pytorch-master
torch/distributed/_shard/sharded_tensor/_ops/_common.py
import torch.distributed._shard.sharded_tensor._ops.chunk import torch.distributed._shard.sharded_tensor._ops.elementwise_ops import torch.distributed._shard.sharded_tensor._ops.math_ops import torch.distributed._shard.sharded_tensor._ops.matrix_ops import torch.distributed._shard.sharded_tensor._ops.tensor_ops import ...
pytorch-master
torch/distributed/_shard/sharded_tensor/_ops/__init__.py
import torch import torch.distributed as dist import torch.distributed.distributed_c10d as distributed_c10d from torch.distributed._shard.sharded_tensor import ( ShardedTensor, _sharded_op_impl ) def _communicate_result(result, pg): # Gather results from all ranks. if result: result_tensor = to...
pytorch-master
torch/distributed/_shard/sharded_tensor/_ops/binary_cmp.py
import torch from torch.distributed._shard.sharded_tensor import ( _sharded_op_impl, ShardedTensor, ) from torch.distributed._shard.sharding_spec import ChunkShardingSpec def register_chunk_op(op): @_sharded_op_impl(op) def sharded_chunk(types, args=(), kwargs=None, pg=None): """ Handl...
pytorch-master
torch/distributed/_shard/sharded_tensor/_ops/chunk.py
import torch from ._common import ( _register_sharded_op_on_local_shards, ) _register_sharded_op_on_local_shards(torch.nn.functional.gelu) _register_sharded_op_on_local_shards(torch.nn.functional.relu) _register_sharded_op_on_local_shards(torch.nn.functional.dropout) _register_sharded_op_on_local_shards(torch.Ten...
pytorch-master
torch/distributed/_shard/sharded_tensor/_ops/elementwise_ops.py
import torch from torch import Tensor from torch.distributed._shard.sharded_tensor import ShardedTensor, _sharded_op_impl from torch.distributed._shard.replicated_tensor import ReplicatedTensor from torch.distributed._shard._utils import narrow_tensor def binary_math_op_impl(op, types, args=(), kwargs=None, pg=None):...
pytorch-master
torch/distributed/_shard/sharded_tensor/_ops/math_ops.py
import torch import torch.distributed._shard.sharded_tensor as sharded_tensor from torch.distributed._shard.sharded_tensor import ( _sharded_op_impl, ) def validate_param(param, param_name): if param is None: raise ValueError(f"param: {param_name} shouldn't be None!") @_sharded_op_impl(torch.nn.init.u...
pytorch-master
torch/distributed/_shard/sharded_tensor/_ops/init.py
import copy import torch from torch.distributed._shard.sharded_tensor import ( Shard, ShardedTensor, ) from ._common import ( _register_sharded_op_on_local_shards, ) def sharded_type_as_check(*args, **kwargs): """ Perform extra checks for the sharded_type_as op such as the input needs to be ...
pytorch-master
torch/distributed/_shard/sharded_tensor/_ops/matrix_ops.py
from .api import ( ShardingPlan, ShardingPlanner )
pytorch-master
torch/distributed/_shard/sharding_plan/__init__.py
import abc import torch.nn as nn from dataclasses import dataclass from typing import Dict, List, Optional, Union from torch.distributed._shard.sharder import Sharder from torch.distributed._shard.sharding_spec import ShardingSpec @dataclass class ShardingPlan(object): """ Representation of a sharding plan, ...
pytorch-master
torch/distributed/_shard/sharding_plan/api.py
from .api import ( DevicePlacementSpec, EnumerableShardingSpec, PlacementSpec, ShardingSpec, _infer_sharding_spec_from_shards_metadata, ) from .chunk_sharding_spec import ( ChunkShardingSpec, ) from torch.distributed._shard.metadata import ShardMetadata
pytorch-master
torch/distributed/_shard/sharding_spec/__init__.py
from typing import List from torch.distributed._shard.metadata import ShardMetadata def _check_shard_metadata_pair_overlap(shard1: ShardMetadata, shard2: ShardMetadata): """ Checks if two shards overlap. """ # For each dim of each shard, check if one shard resides on the other # end of second sha...
pytorch-master
torch/distributed/_shard/sharding_spec/_internals.py
from abc import ABC, abstractmethod from dataclasses import dataclass import functools from typing import Callable, Dict, List, TYPE_CHECKING import torch from ._internals import ( check_tensor, get_chunked_dim_size, get_split_size, validate_non_overlapping_shards_metadata ) from torch.distributed._sh...
pytorch-master
torch/distributed/_shard/sharding_spec/api.py
from dataclasses import dataclass import torch import torch.distributed._shard.sharded_tensor.metadata as sharded_tensor_meta from torch.distributed._shard.metadata import ShardMetadata from torch.distributed._shard.sharded_tensor.shard import Shard from torch.distributed._shard.sharded_tensor.utils import ( _parse...
pytorch-master
torch/distributed/_shard/sharding_spec/chunk_sharding_spec.py
# coding=utf-8 import torch import torch.distributed as dist from ._common import ( _communicate_size_to_each_rank, _handle_col_wise_sharding_base, _handle_row_wise_lookup_distribute, _handle_max_norm_col_wise, ) from torch.distributed._shard.sharding_spec import ChunkShardingSpec from torch.distribute...
pytorch-master
torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/embedding.py
from typing import List import torch import torch.distributed as dist from torch.autograd import Function from torch.distributed.nn.functional import ( _all_gather_base, all_to_all_single, ) from torch.distributed._shard.partial_tensor import _PartialTensor from torch.distributed._shard.sharded_tensor import (...
pytorch-master
torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/linear.py
# coding=utf-8 from typing import List import torch import torch.distributed as dist from torch.distributed._shard.sharding_spec import ChunkShardingSpec from torch.distributed._shard.sharded_tensor._ops._common import _sharded_op_common from torch.distributed._shard.sharded_tensor import ( ShardedTensor, ) from ...
pytorch-master
torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/_common.py
pytorch-master
torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__init__.py
# coding=utf-8 from typing import List, cast import torch import torch.distributed as dist from torch._C._distributed_c10d import ( ReduceOp, ) from ._common import ( _communicate_list_to_each_rank, _communicate_size_to_each_rank, _handle_col_wise_sharding_base, _handle_row_wise_lookup_distribute,...
pytorch-master
torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/embedding_bag.py
import torch from torch import Tensor from torch.distributed._shard.sharded_tensor import ( ShardedTensor, ) from torch.distributed._shard.sharding_spec import ChunkShardingSpec from torch.distributed._shard.sharding_spec.api import custom_sharding_spec_op from torch.distributed._shard.sharded_tensor._ops.math_ops ...
pytorch-master
torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/math_ops.py
import copy import math import torch import torch.distributed as dist from torch.distributed._shard.sharded_tensor import ( ShardedTensor, ) from torch.distributed._shard.sharding_spec._internals import ( get_chunk_sharding_params, ) from torch.distributed.nn.functional import ( all_reduce, ) from ._commo...
pytorch-master
torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/matrix_ops.py
import torch from ._common import ( _register_sharded_op_on_local_tensor, ) def sharded_softmax(args, kwargs, pg): input = args[0] dim = kwargs['dim'] sharding_dim = input.sharding_spec().dim ndims = input.dim() if dim == sharding_dim or dim + ndims == sharding_dim or sharding_dim + ndims == di...
pytorch-master
torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/softmax.py
from typing import Iterator, Tuple, Union from .api import ShardedOptimizer import torch.nn as nn from torch.distributed._shard.sharded_tensor import ( ShardedTensor ) def named_params_with_sharded_tensor( module: nn.Module, prefix: str = '', recurse: bool = True, ) -> Iterator[Tuple[str, Union[nn.Pa...
pytorch-master
torch/distributed/_shard/sharded_optim/__init__.py
from typing import List, Union, Mapping, Dict, Any import torch.optim as optim from torch import Tensor from torch.distributed._shard.sharded_tensor import ShardedTensor class ShardedOptimizer(optim.Optimizer): def __init__( self, named_params: Mapping[str, Union[Tensor, ShardedTensor]], ...
pytorch-master
torch/distributed/_shard/sharded_optim/api.py
import argparse import io import os import random import shlex import subprocess import time import numpy as np import torch import torch.nn as nn import torch.distributed as dist import torch.distributed.autograd as dist_autograd import torch.distributed.rpc as rpc import torch.multiprocessing as mp import torch.opti...
pytorch-master
torch/distributed/benchmarks/benchmark_ddp_rpc.py
import functools def async_execution(fn): r""" A decorator for a function indicating that the return value of the function is guaranteed to be a :class:`~torch.futures.Future` object and this function can run asynchronously on the RPC callee. More specifically, the callee extracts the :class:`~tor...
pytorch-master
torch/distributed/rpc/functions.py
from typing import Dict, List, Optional, Union import torch from torch._C._distributed_rpc import _TensorPipeRpcBackendOptionsBase from . import constants as rpc_contants DeviceType = Union[int, str, torch.device] def _to_device(device: DeviceType) -> torch.device: device = torch.device(device) if device.t...
pytorch-master
torch/distributed/rpc/options.py
import collections import copyreg import io import pickle import sys import threading import traceback from enum import Enum import torch import torch.distributed as dist from torch._C._distributed_rpc import _get_current_rpc_agent # Thread local tensor tables to store tensors while pickling torch.Tensor # objects _...
pytorch-master
torch/distributed/rpc/internal.py
from datetime import timedelta from torch._C._distributed_rpc import ( _DEFAULT_INIT_METHOD, _DEFAULT_NUM_WORKER_THREADS, _DEFAULT_RPC_TIMEOUT_SEC, _UNSET_RPC_TIMEOUT, ) # For any RpcAgent. DEFAULT_RPC_TIMEOUT_SEC: float = _DEFAULT_RPC_TIMEOUT_SEC DEFAULT_INIT_METHOD: str = _DEFAULT_INIT_METHOD DEFAU...
pytorch-master
torch/distributed/rpc/constants.py
from datetime import timedelta import logging import os import threading import warnings from typing import Generator, Tuple from urllib.parse import urlparse import torch import torch.distributed as dist logger = logging.getLogger(__name__) _init_counter = 0 _init_counter_lock = threading.Lock() def is_availabl...
pytorch-master
torch/distributed/rpc/__init__.py
__all__ = ["shutdown", "get_worker_info", "remote", "rpc_sync", "rpc_async", "RRef", "AllGatherStates", "method_factory", "new_method"] import collections import contextlib import functools import inspect import logging import threading from typing import Dict, Generic, TypeVar, Set, Any import torch from ...
pytorch-master
torch/distributed/rpc/api.py
from functools import partial from . import functions from . import rpc_async import torch from .constants import UNSET_RPC_TIMEOUT from torch.futures import Future def _local_invoke(rref, func_name, args, kwargs): return getattr(rref.local_value(), func_name)(*args, **kwargs) @functions.async_execution def _lo...
pytorch-master
torch/distributed/rpc/rref_proxy.py
#!/usr/bin/python3 import itertools import torch from torch.autograd.profiler_legacy import profile from typing import List from . import ( _disable_server_process_global_profiler, _enable_server_process_global_profiler, ) __all__: List[str] = [] class _server_process_global_profile(profile): """ I...
pytorch-master
torch/distributed/rpc/server_process_global_profiler.py
from contextlib import contextmanager from typing import cast import logging from . import api from . import TensorPipeAgent logger = logging.getLogger(__name__) @contextmanager def _group_membership_management(store, name, is_join): token_key = "RpcGroupManagementToken" join_or_leave = "join" if is_join else...
pytorch-master
torch/distributed/rpc/_utils.py
__all__ = ["init_backend", "backend_registered", "construct_rpc_backend_options", "register_backend", "BackendType", "BackendValue"] import collections import enum from typing import cast, Dict, List, Set, Tuple import torch import torch.distributed as dist from ._utils import _group_membership_management, _update_gr...
pytorch-master
torch/distributed/rpc/backend_registry.py
import torch def is_available(): return hasattr(torch._C, "_faulty_agent_init") if is_available() and not torch._C._faulty_agent_init(): raise RuntimeError("Failed to initialize torch.distributed.rpc._testing") if is_available(): # Registers FAULTY_TENSORPIPE RPC backend. from . import faulty_agen...
pytorch-master
torch/distributed/rpc/_testing/__init__.py
#!/usr/bin/env python3 import torch.distributed as dist import torch.distributed.rpc as rpc def _faulty_tensorpipe_construct_rpc_backend_options_handler( rpc_timeout, init_method, num_worker_threads, messages_to_fail, messages_to_delay, num_fail_sends, **kwargs ): from . import FaultyT...
pytorch-master
torch/distributed/rpc/_testing/faulty_agent_backend_registry.py
import torch import warnings from typing import Any __all__ = ["detect_anomaly", "set_detect_anomaly"] class detect_anomaly(object): 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...
pytorch-master
torch/autograd/anomaly_mode.py
import torch from typing import Callable, Any class saved_tensors_hooks(): """Context-manager that sets a pair of pack / unpack hooks for saved tensors. Use this context-manager to define how intermediary results of an operation should be packed before saving, and unpacked on retrieval. In that conte...
pytorch-master
torch/autograd/graph.py
import torch 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_level = -1 de...
pytorch-master
torch/autograd/forward_ad.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...
pytorch-master
torch/autograd/__init__.py
import torch from torch._six import with_metaclass class VariableMeta(type): def __instancecheck__(cls, other): return isinstance(other, torch.Tensor) # mypy doesn't understand torch._six.with_metaclass class Variable(with_metaclass(VariableMeta, torch._C._LegacyVariableBase)): # type: ignore[misc] ...
pytorch-master
torch/autograd/variable.py
import torch from typing import Tuple, List from . import forward_ad as fwAD from torch._vmap_internals import _vmap # Utility functions def _as_tuple_nocheck(x): if isinstance(x, tuple): return x elif isinstance(x, list): return tuple(x) else: return x, def _as_tuple(inp, arg_nam...
pytorch-master
torch/autograd/functional.py
import sys import torch import functools import inspect from typing import Any, Callable, TypeVar, cast __all__ = ['no_grad', 'enable_grad', 'set_grad_enabled', 'inference_mode'] # Used for annotating the decorator usage of 'no_grad' and 'enable_grad'. # See https://mypy.readthedocs.io/en/latest/generics....
pytorch-master
torch/autograd/grad_mode.py
import itertools import torch from torch.autograd import DeviceType from collections import defaultdict, namedtuple from operator import attrgetter from typing import Dict, List, Tuple, Optional import bisect import math class EventList(list): """A list of Events (for pretty printing)""" def __init__(self,...
pytorch-master
torch/autograd/profiler_util.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 ...
pytorch-master
torch/autograd/profiler_legacy.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 ...
pytorch-master
torch/autograd/gradcheck.py
from typing import Any, Dict, List, Optional from warnings import warn import torch import torch.cuda from torch._C._autograd import _ExperimentalConfig from torch.autograd import ( _disable_profiler, _enable_profiler, _kineto_step, _prepare_profiler, _ProfilerResult, _supported_activities, ...
pytorch-master
torch/autograd/profiler.py
import torch import torch._C as _C from torch._C import _functions import torch.utils.hooks as hooks from torch._six import with_metaclass import functools import warnings from collections import OrderedDict from typing import Any, List, Optional # Formerly known as: _ContextMethodMixin class FunctionCtx(object): ...
pytorch-master
torch/autograd/function.py
from .tensor import * # noqa: F403
pytorch-master
torch/autograd/_functions/__init__.py
from functools import reduce import torch import torch._utils from ..function import Function class Type(Function): @staticmethod def forward(ctx, i, dest_type): ctx.input_type = type(i) ctx.input_device = -1 if not i.is_cuda else i.get_device() return i.type(dest_type) @staticme...
pytorch-master
torch/autograd/_functions/tensor.py
from functools import reduce def maybe_view(tensor, size, check_same_size=True): if check_same_size and tensor.size() == size: return tensor return tensor.contiguous().view(size) def maybe_unexpand(tensor, old_size, check_same_size=True): if check_same_size and tensor.size() == old_size: ...
pytorch-master
torch/autograd/_functions/utils.py
from typing import Callable, Any, Tuple, List, Dict, Type, NamedTuple from torch.utils._pytree import PyTree, TreeSpec, LeafSpec from collections import namedtuple FlattenFuncSpec = Callable[[PyTree, TreeSpec], List] SUPPORTED_NODES: Dict[Type[Any], Any] = {} def register_pytree_flatten_spec(typ: Any, flatten_fn_spec...
pytorch-master
torch/fx/_pytree.py
import torch import torch.nn as nn import torch.overrides from torch.nn.modules.module import _addindent from torch.package import PackageImporter, PackageExporter import linecache from typing import Type, Dict, List, Any, Union, Optional, Set from .graph import Graph, _PyTreeCodeGen, _is_from_torch, _custom_builtins, ...
pytorch-master
torch/fx/graph_module.py
import torch import inspect import numbers import types import typing import enum import warnings from typing import Any, Callable, Dict, List, Optional, Tuple, NamedTuple, cast, TYPE_CHECKING from torch._jit_internal import boolean_dispatched from ._compatibility import compatibility from torch._ops import OpOverloadP...
pytorch-master
torch/fx/operator_schemas.py
import dis import torch import inspect import operator import traceback from .graph import magic_methods, reflectable_magic_methods, Graph from typing import Tuple, Dict, Optional, Iterable, Any, Iterator, Callable from .node import Target, Node, Argument, base_types, map_aggregate from ._compatibility import compatib...
pytorch-master
torch/fx/proxy.py
import traceback from contextlib import contextmanager from typing import Optional, List from ._compatibility import compatibility __all__ = ['override_stack_trace', 'append_stack_trace', 'format_stack', 'is_stack_trace_overridden'] current_stack: List[str] = [] is_overridden = False @compatibility(is_backward_com...
pytorch-master
torch/fx/traceback.py
from .node import Node, Argument, Target, map_arg, _type_repr, _get_qualified_name import torch.utils._pytree as pytree from . import _pytree as fx_pytree from ._compatibility import compatibility import contextlib from typing import TYPE_CHECKING, Callable, Any, List, Dict, NamedTuple, Optional, Tuple, Set, FrozenSet...
pytorch-master
torch/fx/graph.py
from torch.fx.experimental.unification import Var # type: ignore[attr-defined] from ._compatibility import compatibility @compatibility(is_backward_compatible=False) class TensorType: """ TensorType defines a type for tensors, which consists of a list of dimensions. Example: class M(torch.nn.Mod...
pytorch-master
torch/fx/tensor_type.py
r''' FX is a toolkit for developers to use to transform ``nn.Module`` instances. FX consists of three main components: a **symbolic tracer,** an **intermediate representation**, and **Python code generation**. A demonstration of these components in action: :: import torch # Simple module for demonstration ...
pytorch-master
torch/fx/__init__.py
from typing import Any, Dict, Tuple, List from ._compatibility import compatibility from torch.utils._pytree import Context, _register_pytree_node _help_mutation = """\ If you are attempting to modify the kwargs or args of a torch.fx.Node object, instead create a new copy of it and assign the copy to the node: ne...
pytorch-master
torch/fx/immutable_collections.py
from torch.fx.proxy import Proxy from ._compatibility import compatibility @compatibility(is_backward_compatible=False) def annotate(val, type): # val could be either a regular value (not tracing) # or fx.Proxy (tracing) if isinstance(val, Proxy): if val.node.type: raise RuntimeError(f"...
pytorch-master
torch/fx/annotate.py