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/distributed/_shard/api.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,
)
from .sharding_spec import (
ShardingSpec,
ChunkShardingSpec
)
from .sharding_plan i... | 12,214 | 41.12069 | 124 | py |
pytorch | pytorch-main/torch/distributed/_shard/common_op_utils.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.sharded_tensor import ShardedTensor
if len(args) == 0 and (kwargs is None or len(kwa... | 2,116 | 33.145161 | 85 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharder.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... | 911 | 31.571429 | 73 | py |
pytorch | pytorch-main/torch/distributed/_shard/checkpoint/__init__.py | # Keep old package for BC purposes, this file should be removed once
# everything moves to the `torch.distributed.checkpoint` package.
import sys
import torch
import warnings
from torch.distributed.checkpoint import * # noqa: F403
warnings.warn(
"torch.distributed._shard.checkpoint will be deprecated, use torch.d... | 459 | 34.384615 | 103 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharding_plan/api.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:
"""
Representation of a sharding plan, describe... | 3,664 | 41.126437 | 104 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharding_spec/_internals.py | from typing import List, Optional, Tuple
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
#... | 7,881 | 36.533333 | 101 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharding_spec/chunk_sharding_spec.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... | 8,731 | 41.38835 | 100 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharding_spec/api.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... | 9,408 | 38.868644 | 111 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharding_spec/__init__.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
| 279 | 20.538462 | 59 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/embedding.py | # coding=utf-8
import torch
import torch.distributed as dist
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.nn.functional import ... | 11,197 | 36.959322 | 90 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/_common.py | # coding=utf-8
import torch
import torch.distributed as dist
from torch.distributed._shard.sharded_tensor import ShardedTensor
from torch.distributed._shard.sharded_tensor._ops._common import _sharded_op_common
from torch.distributed._shard.sharding_spec import ChunkShardingSpec
from torch.distributed._shard.sharding_... | 13,053 | 36.190883 | 90 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/embedding_bag.py | # coding=utf-8
from typing import cast, List
import torch
import torch.distributed as dist
from torch._C._distributed_c10d import ReduceOp
from torch.distributed._shard.sharded_tensor import ShardedTensor
from torch.distributed._shard.sharding_spec import ChunkShardingSpec
from torch.distributed._shard.sharding_spec.... | 18,277 | 37.238494 | 105 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_tensor/reshard.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,... | 10,786 | 42.321285 | 105 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_tensor/metadata.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:... | 2,891 | 33.843373 | 99 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_tensor/utils.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... | 9,070 | 41.787736 | 118 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_tensor/logger.py | #!/usr/bin/env python3
# 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 logging
from typing import List, Tuple
from torch.distributed._shard.sharded_tens... | 1,123 | 28.578947 | 107 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_tensor/shard.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:
"""
Container which holds the data for a shard as a Tensor and also
the associated metadata... | 2,339 | 38.661017 | 96 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_tensor/api.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
import warnings
from functools import reduce
import weakref
import threading
import torch
import torch... | 50,981 | 40.015286 | 111 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_tensor/__init__.py | # coding=utf-8
import functools
from typing import List
import torch
import torch.distributed._shard.sharding_spec as shard_spec
from .api import (
_CUSTOM_SHARDED_OPS,
_SHARDED_OPS,
Shard,
ShardedTensorBase,
ShardedTensor,
ShardedTensorMetadata,
TensorProperties,
)
from .metadata import ... | 19,570 | 40.818376 | 124 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_tensor/_ops/binary_cmp.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... | 2,641 | 37.289855 | 129 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_tensor/_ops/init.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... | 5,439 | 36.777778 | 106 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_tensor/_ops/tensor_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... | 7,706 | 34.680556 | 104 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_tensor/_ops/misc_ops.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 = `.
@... | 478 | 35.846154 | 82 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_tensor/_ops/__init__.py | import torch.distributed._shard.sharded_tensor._ops.misc_ops
import torch.distributed._shard.sharded_tensor._ops.tensor_ops
from .binary_cmp import equal, allclose
from .init import kaiming_uniform_, normal_, uniform_, constant_
# Import all ChunkShardingSpec ops
from torch.distributed._shard.sharding_spec.chunk_shar... | 480 | 47.1 | 110 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_tensor/_ops/_common.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... | 4,163 | 37.555556 | 80 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_optim/api.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]],
... | 4,183 | 41.693878 | 113 | py |
pytorch | pytorch-main/torch/distributed/_shard/sharded_optim/__init__.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... | 1,857 | 32.781818 | 84 | py |
pytorch | pytorch-main/torch/distributed/_composable/replicate.py | import weakref
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
import torch
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel
from .contract import _get_registry, contract
_ROOT_MODULE_PREFIX = ""
@contract()
def replicate(
module: nn.Module, # NOTE: contract now ... | 5,241 | 36.71223 | 100 | py |
pytorch | pytorch-main/torch/distributed/_composable/contract.py | import uuid
from collections import OrderedDict
from functools import wraps
from typing import Callable, Dict, List, Optional, Type
import torch.nn as nn
from torch.distributed._composable_state import _State
# use state_slot as key for module.__dict__ to avoid coliding with other
# properties.
# TODO: since all com... | 7,710 | 37.363184 | 112 | py |
pytorch | pytorch-main/torch/distributed/_composable/fully_shard.py | from typing import Callable, Iterable, Optional, Union
import torch
import torch.distributed as dist
import torch.nn as nn
from torch.distributed._composable.contract import contract
from torch.distributed._composable_state import _get_module_state, _insert_module_state
from torch.distributed.fsdp._common_utils import... | 4,835 | 36.78125 | 87 | py |
pytorch | pytorch-main/torch/distributed/_composable/checkpoint_activation.py | from contextlib import contextmanager
from functools import partial
from typing import Any, List, Optional, Tuple
from weakref import ref, ReferenceType, WeakKeyDictionary
import torch
import torch.nn as nn
from torch.utils.checkpoint import detach_variable, get_device_states, set_device_states
from .contract import ... | 11,107 | 39.101083 | 101 | py |
pytorch | pytorch-main/torch/distributed/_sharded_tensor/__init__.py | # Keep old package for BC purposes, this file should be removed once
# everything moves to the `torch.distributed._shard` package.
import sys
import torch
import warnings
from torch.distributed._shard.sharded_tensor import * # noqa: F403
warnings.warn(
"torch.distributed._sharded_tensor will be deprecated, use to... | 484 | 36.307692 | 112 | py |
pytorch | pytorch-main/torch/distributed/rpc/backend_registry.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... | 16,369 | 39.925 | 132 | py |
pytorch | pytorch-main/torch/distributed/rpc/constants.py | from datetime import timedelta
from typing import List
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 = _DE... | 829 | 32.2 | 88 | py |
pytorch | pytorch-main/torch/distributed/rpc/server_process_global_profiler.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... | 8,283 | 45.539326 | 120 | py |
pytorch | pytorch-main/torch/distributed/rpc/rref_proxy.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... | 2,649 | 34.333333 | 122 | py |
pytorch | pytorch-main/torch/distributed/rpc/functions.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... | 7,243 | 42.377246 | 90 | py |
pytorch | pytorch-main/torch/distributed/rpc/internal.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
__all__ = ["RPCExecMode", "serialize", "deserialize", "PythonUDF", "RemoteException"]
... | 11,235 | 37.878893 | 103 | py |
pytorch | pytorch-main/torch/distributed/rpc/api.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, TYPE_CHECKING
imp... | 36,814 | 37.834388 | 122 | py |
pytorch | pytorch-main/torch/distributed/rpc/options.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]
__all__ = ["TensorPipeRpcBackendOptions"]
def _to_device(device: DeviceType) -> torch.device:
dev... | 7,044 | 39.722543 | 80 | py |
pytorch | pytorch-main/torch/distributed/rpc/__init__.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()
__all__ = ["is_av... | 9,762 | 37.742063 | 114 | py |
pytorch | pytorch-main/torch/distributed/rpc/_testing/__init__.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... | 471 | 23.842105 | 77 | py |
pytorch | pytorch-main/torch/distributed/rpc/_testing/faulty_agent_backend_registry.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... | 1,686 | 24.953846 | 93 | py |
pytorch | pytorch-main/torch/distributed/_tensor/device_mesh.py | # Copyright (c) Meta Platforms, Inc. and affiliates
import logging
from typing import List, Optional, Tuple, TYPE_CHECKING, Union
import torch
import torch.distributed._functional_collectives as funcol
from torch.distributed.distributed_c10d import (
_find_pg_by_ranks_and_tag,
_get_default_group,
_get_gro... | 19,452 | 37.368836 | 121 | py |
pytorch | pytorch-main/torch/distributed/_tensor/placement_types.py | # Copyright (c) Meta Platforms, Inc. and affiliates
from dataclasses import dataclass
from typing import cast, List, Optional, Sequence, Tuple
import torch
import torch.distributed.distributed_c10d as c10d
from torch.distributed._tensor.device_mesh import DeviceMesh
from torch.fx.passes.shape_prop import TensorMetad... | 17,859 | 34.226824 | 132 | py |
pytorch | pytorch-main/torch/distributed/_tensor/_utils.py | from typing import cast, List, Sequence, Tuple
import torch
from torch._prims_common import ShapeType
from torch.distributed._tensor.device_mesh import DeviceMesh
from torch.distributed._tensor.placement_types import (
_Partial,
Placement,
Replicate,
Shard,
)
def compute_local_shape(
global_shape... | 4,970 | 38.452381 | 90 | py |
pytorch | pytorch-main/torch/distributed/_tensor/api.py | # Copyright (c) Meta Platforms, Inc. and affiliates
import copy
import warnings
from typing import Callable, cast, Optional, Sequence, Tuple
import torch
import torch.distributed._tensor.dispatch as op_dispatch
import torch.distributed._tensor.random as random
import torch.nn as nn
from torch.distributed._tensor._uti... | 24,596 | 41.703125 | 127 | py |
pytorch | pytorch-main/torch/distributed/_tensor/op_schema.py | from dataclasses import dataclass
from typing import Dict, List, Optional, Sequence, Tuple, Union
import torch
from torch.distributed._tensor.placement_types import DTensorSpec
from torch.utils._pytree import tree_map_only
# Common type aliases
ArgsType = Tuple[object, ...]
KwargsType = Dict[str, object]
# ATen op s... | 9,230 | 37.144628 | 117 | py |
pytorch | pytorch-main/torch/distributed/_tensor/sharding_prop.py | from typing import Callable, Dict, Optional, Tuple
import torch
import torch.distributed._tensor.api as dtensor
from torch._ops import OpOverload
from torch._subclasses import FakeTensorMode
from torch.distributed._tensor.device_mesh import DeviceMesh
from torch.distributed._tensor.op_schema import (
DTensorSpec,
... | 12,195 | 41.494774 | 88 | py |
pytorch | pytorch-main/torch/distributed/_tensor/random.py | # Copyright (c) Meta Platforms, Inc. and affiliates
import contextlib
import warnings
from typing import Dict, List, Optional
import torch
import torch.distributed as dist
from torch import Tensor
from torch.distributed._tensor.device_mesh import _get_device_handle, DeviceMesh
from torch.distributed._tensor.placement... | 15,405 | 40.413978 | 145 | py |
pytorch | pytorch-main/torch/distributed/_tensor/dispatch.py | # Copyright (c) Meta Platforms, Inc. and affiliates
import functools
import operator
from typing import Callable, cast, Dict, List, Sequence, Tuple, Union
import torch
import torch.distributed as dist
import torch.distributed._tensor.api as dtensor
import torch.distributed._tensor.random as random
from torch.distribu... | 11,671 | 39.527778 | 92 | py |
pytorch | pytorch-main/torch/distributed/_tensor/redistribute.py | # Copyright (c) Meta Platforms, Inc. and affiliates
from typing import cast, Dict, List, Sequence, Tuple
import torch
import torch.distributed._tensor.api as dtensor
from torch.distributed._tensor.device_mesh import DeviceMesh
from torch.distributed._tensor.placement_types import (
_Partial,
Placement,
Rep... | 9,233 | 37.635983 | 102 | py |
pytorch | pytorch-main/torch/distributed/_tensor/__init__.py | # Copyright (c) Meta Platforms, Inc. and affiliates
from typing import Optional, Sequence
# Import all builtin dist tensor ops
import torch
import torch.distributed._tensor.ops
from torch.distributed._tensor._utils import compute_local_shape
from torch.distributed._tensor.api import distribute_module, distribute_tenso... | 9,131 | 35.674699 | 101 | py |
pytorch | pytorch-main/torch/distributed/_tensor/debug/op_coverage.py | from operator import itemgetter
from functorch.compile import make_boxed_func
import torch
import torch.nn as nn
from torch._functorch.compilers import aot_module
from torch._inductor.decomposition import select_decomp_table
from torch.distributed._tensor import DTensor
inductor_decomps = select_decomp_table()
gra... | 2,938 | 28.09901 | 83 | py |
pytorch | pytorch-main/torch/distributed/_tensor/examples/checkpoint_example.py | """
The following example contains a simple MLP model that uses
different DTensor layouts, and use the checkpointing API to
checkpoint save/load the model.
"""
import os
from typing import cast, List
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.nn as nn
import torch.nn... | 6,117 | 32.431694 | 92 | py |
pytorch | pytorch-main/torch/distributed/_tensor/ops/embedding_ops.py | # Copyright (c) Meta Platforms, Inc. and affiliates
# implement matrix related ops for distributed tensor
import torch
from torch.distributed._tensor.op_schema import OpSchema, OutputSharding
from torch.distributed._tensor.ops.utils import register_prop_rule
from torch.distributed._tensor.placement_types import (
... | 3,843 | 37.44 | 88 | py |
pytorch | pytorch-main/torch/distributed/_tensor/ops/common_rules.py | # Copyright (c) Meta Platforms, Inc. and affiliates
from typing import cast, Dict, List, Optional, Sequence, Tuple
import torch
from torch.distributed._tensor._utils import compute_local_shape
from torch.distributed._tensor.op_schema import OpSchema, OutputSharding
from torch.distributed._tensor.ops.utils import prod
... | 15,291 | 40.554348 | 97 | py |
pytorch | pytorch-main/torch/distributed/_tensor/ops/math_ops.py | # Copyright (c) Meta Platforms, Inc. and affiliates
from typing import cast, Optional, Sequence
import torch
import torch.distributed.distributed_c10d as c10d
from torch.distributed._tensor.op_schema import OpSchema, OutputSharding
from torch.distributed._tensor.ops.common_rules import pointwise_rule, reduction_rule
... | 5,021 | 33.634483 | 86 | py |
pytorch | pytorch-main/torch/distributed/_tensor/ops/utils.py | # Copyright (c) Meta Platforms, Inc. and affiliates
import functools
import operator
from typing import cast, Iterable, List, Sequence, Union
import torch
from torch.distributed._tensor.api import DTensor
from torch.distributed._tensor.placement_types import DTensorSpec, Shard
# convenient wrapper to register shardi... | 3,477 | 32.76699 | 100 | py |
pytorch | pytorch-main/torch/distributed/_tensor/ops/random_ops.py | # Copyright (c) Meta Platforms, Inc. and affiliates
from typing import cast
import torch
from torch.distributed._tensor.op_schema import OpSchema, OutputSharding
from torch.distributed._tensor.ops.utils import register_prop_rule
from torch.distributed._tensor.placement_types import _Partial, DTensorSpec
aten = torch... | 1,758 | 28.813559 | 92 | py |
pytorch | pytorch-main/torch/distributed/_tensor/ops/view_ops.py | # Copyright (c) Meta Platforms, Inc. and affiliates
from dataclasses import dataclass
from typing import Callable, cast, Dict, Iterable, Optional, Sequence, Set, Tuple, Union
import torch
from torch import Tensor
from torch.distributed._tensor._utils import compute_local_shape
from torch.distributed._tensor.api impor... | 23,212 | 33.288035 | 116 | py |
pytorch | pytorch-main/torch/distributed/_tensor/ops/tensor_ops.py | # Copyright (c) Meta Platforms, Inc. and affiliates
from typing import cast, Dict, List, Optional, Sequence, Tuple
import torch
from torch.distributed._tensor._utils import compute_local_shape
from torch.distributed._tensor.device_mesh import DeviceMesh
from torch.distributed._tensor.op_schema import (
OpSchema,
... | 23,581 | 36.670927 | 112 | py |
pytorch | pytorch-main/torch/distributed/_tensor/ops/basic_strategy.py | import itertools
from dataclasses import dataclass
from typing import List, Tuple
from torch.distributed._tensor.device_mesh import DeviceMesh
from torch.distributed._tensor.op_schema import OpStrategy, PlacementStrategy
from torch.distributed._tensor.placement_types import (
_Partial,
DTensorSpec,
Placem... | 6,665 | 35.228261 | 86 | py |
pytorch | pytorch-main/torch/distributed/_tensor/ops/matrix_ops.py | # Copyright (c) Meta Platforms, Inc. and affiliates
# implement matrix related ops for distributed tensor
import torch
from torch.distributed._tensor.op_schema import OpSchema, OutputSharding
from torch.distributed._tensor.ops.common_rules import einop_rule, pointwise_rule
from torch.distributed._tensor.ops.utils imp... | 4,583 | 33.466165 | 87 | py |
pytorch | pytorch-main/torch/distributed/_tensor/ops/pointwise_ops.py | # Copyright (c) Meta Platforms, Inc. and affiliates
import torch
from torch.distributed._tensor.ops.common_rules import (
linear_pointwise_rule,
pointwise_rule,
)
from torch.distributed._tensor.ops.utils import register_prop_rule
aten = torch.ops.aten
# leave the remaining pointwise_ops list here for conven... | 9,721 | 24.925333 | 126 | py |
pytorch | pytorch-main/torch/masked/_ops.py | # -*- coding: utf-8 -*-
import warnings
# A workaround to support both TorchScript and MyPy:
from typing import Any, List, Optional, Tuple, TYPE_CHECKING, Union
import torch
from torch import Tensor
from torch.masked import as_masked_tensor, is_masked_tensor, MaskedTensor
from . import _docs
from torch._prims_common... | 63,473 | 35.126352 | 131 | py |
pytorch | pytorch-main/torch/masked/_docs.py | # -*- coding: utf-8 -*-
# This file is generated, do not modify it!
#
# To update this file, run the update masked docs script as follows:
#
# python tools/update_masked_docs.py
#
# The script must be called from an environment where the development
# version of torch package can be imported and is functional.
#
ama... | 49,492 | 40.978796 | 100 | py |
pytorch | pytorch-main/torch/masked/maskedtensor/core.py | # Copyright (c) Meta Platforms, Inc. and affiliates
import warnings
import torch
from torch.overrides import get_default_nowrap_functions
__all__ = [
"MaskedTensor",
"is_masked_tensor",
]
def is_masked_tensor(a):
r""" Returns True if the input is a MaskedTensor, else False
Args:
a: any in... | 12,377 | 35.839286 | 122 | py |
pytorch | pytorch-main/torch/masked/maskedtensor/creation.py | # Copyright (c) Meta Platforms, Inc. and affiliates
from .core import MaskedTensor
__all__ = [
"as_masked_tensor",
"masked_tensor",
]
""""
These two factory functions are intended to mirror
torch.tensor - guaranteed to be a leaf node
torch.as_tensor - differentiable constructor that preserves the au... | 527 | 23 | 84 | py |
pytorch | pytorch-main/torch/masked/maskedtensor/_ops_refs.py | # Copyright (c) Meta Platforms, Inc. and affiliates
from functools import partial
import torch
from .binary import (
_apply_native_binary,
NATIVE_BINARY_FNS,
NATIVE_INPLACE_BINARY_FNS,
)
from .core import is_masked_tensor, MaskedTensor, _get_data, _masks_match, _maybe_get_mask
from .passthrough import (
... | 16,423 | 33.649789 | 132 | py |
pytorch | pytorch-main/torch/masked/maskedtensor/reductions.py | # Copyright (c) Meta Platforms, Inc. and affiliates
import warnings
import torch
from .core import is_masked_tensor
from .creation import as_masked_tensor, masked_tensor
__all__ = [] # type: ignore[var-annotated]
def _masked_all_all(data, mask=None):
if mask is None:
return data.all()
return data... | 5,562 | 30.971264 | 113 | py |
pytorch | pytorch-main/torch/masked/maskedtensor/binary.py | # Copyright (c) Meta Platforms, Inc. and affiliates
import torch
from .core import _map_mt_args_kwargs, _masks_match, _tensors_match, _wrap_result, is_masked_tensor
__all__ = [] # type: ignore[var-annotated]
BINARY_NAMES = [
"add",
"atan2",
"arctan2",
"bitwise_and",
"bitwise_or",
"bitwise_x... | 5,370 | 26.829016 | 114 | py |
pytorch | pytorch-main/torch/masked/maskedtensor/unary.py | # Copyright (c) Meta Platforms, Inc. and affiliates
import torch
from .core import _map_mt_args_kwargs, _wrap_result
__all__ = [] # type: ignore[var-annotated]
UNARY_NAMES = [
"abs",
"absolute",
"acos",
"arccos",
"acosh",
"arccosh",
"angle",
"asin",
"arcsin",
"asinh",
"... | 4,128 | 20.846561 | 96 | py |
pytorch | pytorch-main/torch/masked/maskedtensor/passthrough.py | # Copyright (c) Meta Platforms, Inc. and affiliates
"""
These are functions that should simply be applied to both mask and data.
Take select or stack as an example. This operation can be applied to
both the mask and data of a MaskedTensor and the result wrapped into
a new MaskedTensor as a result.
"""
import torch
fr... | 1,276 | 28.022727 | 86 | py |
pytorch | pytorch-main/torch/_lazy/ts_backend.py | import torch._C._lazy_ts_backend
def init():
"""Initializes the lazy Torchscript backend"""
torch._C._lazy_ts_backend._init()
| 136 | 18.571429 | 50 | py |
pytorch | pytorch-main/torch/_lazy/extract_compiled_graph.py | import copy
import dataclasses
import itertools
import os
from typing import Any, Callable, Dict, List
import torch
import torch._lazy as lazy
import torch._lazy.metrics as metrics
from torch import fx
from torch._lazy import computation, debug as lazy_debug
from torch._lazy.tensor_factory_functions import tensor_fact... | 8,407 | 36.535714 | 99 | py |
pytorch | pytorch-main/torch/_lazy/computation.py | import torch._C._lazy
import torch._C._lazy_ts_backend
def get_tensors_ts_device_data_node(tensors):
"""Return tensor ids and eager tensors for DeviceData nodes in the
IR for the passed in lazy tensors.
TODO: This API is currently ts backend specific. We are working on
generalizing it to all backends... | 892 | 32.074074 | 78 | py |
pytorch | pytorch-main/torch/_lazy/ir_cache.py | import torch._C._lazy
def dump(dot_file_name: str):
"""Dump TrieCache in the dot format"""
return torch._C._lazy._dump_ir_cache(dot_file_name)
def reset():
"""Clear TrieCache. This is needed in testing to avoid
node reusing between different tests.
"""
return torch._C._lazy._clear_ir_cache()... | 321 | 22 | 58 | py |
pytorch | pytorch-main/torch/_lazy/config.py | import torch._C._lazy
def get_force_fallback():
"""Get the config used to force LTC fallback"""
return torch._C._lazy._get_force_fallback()
def set_force_fallback(configval):
"""Set the config used to force LTC fallback"""
torch._C._lazy._set_force_fallback(configval)
def set_reuse_ir(val: bool):
... | 420 | 23.764706 | 61 | py |
pytorch | pytorch-main/torch/_lazy/closure.py | import os
import threading
from queue import Empty as EmptyQueue, Queue
from torch._lazy.device_context import get_device_context
class ClosureHandler:
def __init__(self):
pass
def run(self, closure):
"""Run closure function
Args:
closure: callable function to run
""... | 5,417 | 39.133333 | 92 | py |
pytorch | pytorch-main/torch/_lazy/device_context.py | import threading
from typing import Any, Dict
import torch._C._lazy
class DeviceContext:
_CONTEXTS: Dict[str, Any] = dict()
_CONTEXTS_LOCK = threading.Lock()
def __init__(self, device):
self.device = device
def get_device_context(device=None):
if device is None:
device = torch._C._... | 634 | 23.423077 | 58 | py |
pytorch | pytorch-main/torch/_lazy/metrics.py | import torch._C._lazy
def reset():
"""Resets all metric counters."""
torch._C._lazy._reset_metrics()
def counter_names():
"""Retrieves all the currently active counter names."""
return torch._C._lazy._counter_names()
def counter_value(name: str):
"""Return the value of the counter with the spe... | 518 | 22.590909 | 67 | py |
pytorch | pytorch-main/torch/_lazy/__init__.py | import threading
import torch._C._lazy
from torch.utils._pytree import tree_flatten, tree_unflatten
from .closure import add_step_closure, run_step_closures
def mark_step(device: str = "", wait=False):
"""Triggers a mark step, which amounts to
- collecting a group of 'live' lazy tensors to index into the co... | 1,783 | 30.857143 | 104 | py |
pytorch | pytorch-main/torch/_lazy/tensor_factory_functions.py | import torch
"""
tensor_factory_functions defines the list of torch functions that create tensors.
The list is grabbed by searching thru native_functions.yaml by the following
regular expression:
cat native_functions.yaml | grep 'func:' | grep -v "Tensor.*->" | grep "[-]>.*Tensor"
It's possible that new tensor fac... | 1,367 | 26.918367 | 87 | py |
pytorch | pytorch-main/torch/_lazy/debug.py | import torch._C._lazy
def render_ir_graph(tensors):
"""Return a text dump of the LTC IR graph in dot format for the tensors.
The text can be processed by tools like dot to be rendered in pdf,png etc."""
return torch._C._lazy._get_tensors_dot(tensors)
def dump_ir(tensors, ir_format):
"""Return a dump... | 711 | 31.363636 | 81 | py |
pytorch | pytorch-main/torch/linalg/__init__.py | # -*- coding: utf-8 -*-
import sys
import torch
from torch._C import _add_docstr, _linalg # type: ignore[attr-defined]
LinAlgError = torch._C._LinAlgError # type: ignore[attr-defined]
Tensor = torch.Tensor
common_notes = {
"experimental_warning": """This function is "experimental" and it may change in a futur... | 113,473 | 38.871398 | 132 | py |
pytorch | pytorch-main/torch/csrc/lazy/test_mnist.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import os
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
import torch._lazy
import torch._lazy.ts_backend
import torch._lazy.metrics
torch._lazy.ts_backend.init()
class Net(nn.Modul... | 2,712 | 30.546512 | 75 | py |
pytorch | pytorch-main/torch/csrc/jit/tensorexpr/codegen_external.py | #!/usr/bin/env python3
import argparse
from torchgen.gen import parse_native_yaml, FileManager
import torchgen.model as model
def num_leading_spaces(line: str) -> int:
return len(line) - len(line.lstrip())
def deindent(code: str) -> str:
lines = code.split('\n')
min_leading_spaces = min(map(num_leading_spa... | 3,797 | 37.363636 | 124 | py |
pytorch | pytorch-main/torch/jit/_recursive.py | import inspect
import torch
import types
import collections
import textwrap
import functools
import warnings
import sys
from typing import Dict, List, Set, Type
import torch._jit_internal as _jit_internal
from torch._sources import fake_range
from torch.jit.frontend import get_default_args, get_jit_class_def, get_jit_... | 41,587 | 43.101803 | 121 | py |
pytorch | pytorch-main/torch/jit/supported_ops.py | import torch.jit
from torch.jit._builtins import _find_builtin
import inspect
import textwrap
# this file is for generating documentation using sphinx autodoc
# > help(torch.jit.supported_ops) will also give a nice listed of the
# supported ops programmatically
def _hidden(name):
return name.startswith('_') and no... | 10,354 | 30.861538 | 127 | py |
pytorch | pytorch-main/torch/jit/annotations.py | import ast
import dis
import enum
import inspect
import re
import builtins
import torch
import warnings
from .._jit_internal import List, Tuple, is_tuple, is_list, Dict, is_dict, Optional, \
is_optional, _qualified_name, Any, Future, is_future, _Await, is_await, is_ignored_fn, Union, is_union
from .._jit_internal i... | 17,223 | 36.200864 | 158 | py |
pytorch | pytorch-main/torch/jit/_dataclass_impls.py | # Functions for synthesizing magic methods for JIT-compiled dataclasses
import os
from functools import partial
from torch._jit_internal import is_optional, FAKE_FILENAME_PREFIX
from torch._sources import ParsedDef, SourceContext
from typing import Callable, Dict, List
import ast
import dataclasses
import inspect
def ... | 6,300 | 40.728477 | 118 | py |
pytorch | pytorch-main/torch/jit/_logging.py | import torch
add_stat_value = torch.ops.prim.AddStatValue
set_logger = torch._C._logging_set_logger
LockingLogger = torch._C.LockingLogger
AggregationType = torch._C.AggregationType
NoopLogger = torch._C.NoopLogger
time_point = torch.ops.prim.TimePoint
| 256 | 22.363636 | 44 | py |
pytorch | pytorch-main/torch/jit/_serialization.py | """Serialization
This module contains functionality for serializing TorchScript modules, notably:
* torch.jit.save
* torch.jit.load
This is not intended to be imported directly; please use the exposed
functionalities in `torch.jit`.
"""
import os
import pathlib
import torch
from torch.jit._recursive import w... | 9,208 | 32.732601 | 129 | py |
pytorch | pytorch-main/torch/jit/generate_bytecode.py | from torch._C import _compile_graph_to_code_table, _generate_upgraders_graph
from typing import List
def format_bytecode(table):
# given a nested tuple, convert it to nested list
def listify(content):
if not isinstance(content, tuple):
return content
return [listify(i) for i in cont... | 1,035 | 33.533333 | 84 | py |
pytorch | pytorch-main/torch/jit/_decomposition_utils.py | import torch
from torch._ops import OpOverload, OpOverloadPacket
def _register_decomposition(op: OpOverload, graph: torch._C.Graph):
assert not isinstance(op, OpOverloadPacket), f"Must pass specific op overload, not overload packet, found {op}"
assert isinstance(op, OpOverload)
torch._C._jit_register_deco... | 360 | 39.111111 | 115 | py |
pytorch | pytorch-main/torch/jit/_shape_functions.py | from typing import List, Any, Optional, Union, Dict, Callable, Tuple
import math
number = Union[int, float]
# flake8: noqa
###
# There are generated files that depend on this file
# To re-generate, please run from the root of the repo:
# python torchgen/shape_functions/gen_jit_shape_functions.py
# How to test:
# Afte... | 43,728 | 36.121392 | 291 | py |
pytorch | pytorch-main/torch/jit/_freeze.py | """Freezing
This is not intended to be imported directly; please use the exposed
functionalities in `torch.jit`.
"""
from typing import Optional, List
import torch
from torch.jit._script import RecursiveScriptModule, ScriptModule
def freeze(mod, preserved_attrs: Optional[List[str]] = None, optimize_numerics: bool ... | 9,335 | 41.436364 | 115 | py |
pytorch | pytorch-main/torch/jit/_ir_utils.py | import torch
from typing import Union
class _InsertPoint:
def __init__(self, insert_point_graph: torch._C.Graph, insert_point: Union[torch._C.Node, torch._C.Block]):
self.insert_point = insert_point
self.g = insert_point_graph
self.guard = None
def __enter__(self):
self.prev_in... | 616 | 31.473684 | 111 | py |
pytorch | pytorch-main/torch/jit/quantized.py | from torch import Tensor, _VF # noqa: F401
from torch.nn.utils.rnn import PackedSequence
import torch
import warnings
from typing import List, Optional, Tuple
class QuantizedLinear(torch.jit.ScriptModule):
__constants__ = ['scale', 'zero_point']
def __init__(self, other):
super().__init__()
... | 25,546 | 43.198962 | 130 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.