jasonfan commited on
Commit
f08da31
·
verified ·
1 Parent(s): 0b7b58d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/cuda/amp/__init__.py +13 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/cuda/amp/autocast_mode.py +110 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/cuda/amp/common.py +11 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/cuda/amp/grad_scaler.py +38 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/cuda/tunable.py +802 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/__init__.py +168 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_checkpointable.py +37 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/__init__.py +3 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/checkpoint_activation.py +134 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/contract.py +259 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/fsdp/__init__.py +3 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/fsdp/fully_shard.py +8 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/replicate.py +254 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/replicate_with_fsdp.py +408 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable_state.py +46 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_dist2.py +183 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_functional_collectives.py +1251 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_functional_collectives_impl.py +117 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_local_tensor/__init__.py +1965 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_local_tensor/_c10d.py +1060 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_mesh_layout.py +309 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_pycute/__init__.py +74 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_pycute/int_tuple.py +269 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_pycute/layout.py +470 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_pycute/typing.py +42 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_serialization.py +158 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/__init__.py +1 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/_utils.py +32 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/api.py +305 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/checkpoint/__init__.py +19 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/common_op_utils.py +64 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/metadata.py +63 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/op_registry_utils.py +41 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_optim/__init__.py +53 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_optim/api.py +102 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/__init__.py +490 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__init__.py +13 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/_ops/_common.py +115 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/_ops/binary_cmp.py +78 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/_ops/init.py +164 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/_ops/misc_ops.py +12 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/_ops/tensor_ops.py +222 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/api.py +1368 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/logger.py +35 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/logging_handlers.py +16 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/metadata.py +94 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/reshard.py +243 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/shard.py +61 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/utils.py +325 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharder.py +29 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/cuda/amp/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pyrefly: ignore [deprecated]
2
+ from .autocast_mode import autocast, custom_bwd, custom_fwd
3
+ from .common import amp_definitely_not_available
4
+ from .grad_scaler import GradScaler
5
+
6
+
7
+ __all__ = [
8
+ "amp_definitely_not_available",
9
+ "autocast",
10
+ "custom_bwd",
11
+ "custom_fwd",
12
+ "GradScaler",
13
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/cuda/amp/autocast_mode.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ import sys
4
+ from typing import Any
5
+ from typing_extensions import deprecated
6
+
7
+ import torch
8
+
9
+
10
+ __all__ = ["autocast", "custom_fwd", "custom_bwd"]
11
+
12
+
13
+ @deprecated(
14
+ "`torch.cuda.amp.autocast(args...)` is deprecated. "
15
+ "Please use `torch.amp.autocast('cuda', args...)` instead.",
16
+ category=FutureWarning,
17
+ )
18
+ class autocast(torch.amp.autocast_mode.autocast):
19
+ r"""See :class:`torch.autocast`.
20
+
21
+ ``torch.cuda.amp.autocast(args...)`` is deprecated. Please use ``torch.amp.autocast("cuda", args...)`` instead.
22
+ """
23
+
24
+ # TODO: remove this conditional once we stop supporting Python < 3.13
25
+ # Prior to Python 3.13, inspect.signature could not retrieve the correct
26
+ # signature information for classes decorated with @deprecated (unless
27
+ # the __new__ static method was explicitly defined);
28
+ #
29
+ # However, this issue has been fixed in Python 3.13 and later versions.
30
+ if sys.version_info < (3, 13):
31
+
32
+ def __new__(
33
+ cls,
34
+ enabled: bool = True,
35
+ dtype: torch.dtype = torch.float16,
36
+ cache_enabled: bool = True,
37
+ ):
38
+ return super().__new__(cls)
39
+
40
+ def __init_subclass__(cls):
41
+ pass
42
+
43
+ def __init__(
44
+ self,
45
+ enabled: bool = True,
46
+ dtype: torch.dtype = torch.float16,
47
+ cache_enabled: bool = True,
48
+ ):
49
+ if torch._jit_internal.is_scripting():
50
+ self._enabled = enabled
51
+ self.device = "cuda"
52
+ self.fast_dtype = dtype
53
+ return
54
+ super().__init__(
55
+ "cuda", enabled=enabled, dtype=dtype, cache_enabled=cache_enabled
56
+ )
57
+
58
+ def __enter__(self):
59
+ if torch._jit_internal.is_scripting():
60
+ return self
61
+ return super().__enter__()
62
+
63
+ # TODO: discuss a unified TorchScript-friendly API for autocast
64
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any): # type: ignore[override]
65
+ if torch._jit_internal.is_scripting():
66
+ return
67
+ return super().__exit__(exc_type, exc_val, exc_tb)
68
+
69
+ def __call__(self, func):
70
+ if torch._jit_internal.is_scripting():
71
+ return func
72
+ return super().__call__(func)
73
+
74
+
75
+ # Preserved only for BC reasons
76
+ @deprecated(
77
+ "`torch.cuda.amp.autocast_mode._cast(value, dtype)` is deprecated. "
78
+ "Please use `torch.amp.autocast_mode._cast(value, 'cuda', dtype)` instead.",
79
+ category=FutureWarning,
80
+ )
81
+ def _cast(value, dtype):
82
+ return torch.amp.autocast_mode._cast(value, "cuda", dtype)
83
+
84
+
85
+ @deprecated(
86
+ "`torch.cuda.amp.custom_fwd(args...)` is deprecated. "
87
+ "Please use `torch.amp.custom_fwd(args..., device_type='cuda')` instead.",
88
+ category=FutureWarning,
89
+ )
90
+ def custom_fwd(fwd=None, *, cast_inputs=None):
91
+ """
92
+ ``torch.cuda.amp.custom_fwd(args...)`` is deprecated. Please use
93
+ ``torch.amp.custom_fwd(args..., device_type='cuda')`` instead.
94
+ """
95
+ return functools.partial(torch.amp.custom_fwd, device_type="cuda")(
96
+ fwd=fwd, cast_inputs=cast_inputs
97
+ )
98
+
99
+
100
+ @deprecated(
101
+ "`torch.cuda.amp.custom_bwd(args...)` is deprecated. "
102
+ "Please use `torch.amp.custom_bwd(args..., device_type='cuda')` instead.",
103
+ category=FutureWarning,
104
+ )
105
+ def custom_bwd(bwd):
106
+ """
107
+ ``torch.cuda.amp.custom_bwd(args...)`` is deprecated. Please use
108
+ ``torch.amp.custom_bwd(args..., device_type='cuda')`` instead.
109
+ """
110
+ return functools.partial(torch.amp.custom_bwd, device_type="cuda")(bwd)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/cuda/amp/common.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from importlib.util import find_spec
3
+
4
+ import torch
5
+
6
+
7
+ __all__ = ["amp_definitely_not_available"]
8
+
9
+
10
+ def amp_definitely_not_available():
11
+ return not (torch.cuda.is_available() or find_spec("torch_xla"))
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/cuda/amp/grad_scaler.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing_extensions import deprecated
2
+
3
+ import torch
4
+
5
+ # We need to keep this unused import for BC reasons
6
+ from torch.amp.grad_scaler import OptState # noqa: F401
7
+
8
+
9
+ __all__ = ["GradScaler"]
10
+
11
+
12
+ class GradScaler(torch.amp.GradScaler):
13
+ r"""
14
+ See :class:`torch.amp.GradScaler`.
15
+ ``torch.cuda.amp.GradScaler(args...)`` is deprecated. Please use ``torch.amp.GradScaler("cuda", args...)`` instead.
16
+ """
17
+
18
+ @deprecated(
19
+ "`torch.cuda.amp.GradScaler(args...)` is deprecated. "
20
+ "Please use `torch.amp.GradScaler('cuda', args...)` instead.",
21
+ category=FutureWarning,
22
+ )
23
+ def __init__(
24
+ self,
25
+ init_scale: float = 2.0**16,
26
+ growth_factor: float = 2.0,
27
+ backoff_factor: float = 0.5,
28
+ growth_interval: int = 2000,
29
+ enabled: bool = True,
30
+ ) -> None:
31
+ super().__init__(
32
+ "cuda",
33
+ init_scale=init_scale,
34
+ growth_factor=growth_factor,
35
+ backoff_factor=backoff_factor,
36
+ growth_interval=growth_interval,
37
+ enabled=enabled,
38
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/cuda/tunable.py ADDED
@@ -0,0 +1,802 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ This module exposes a TunableOp interface.
3
+
4
+ Some operations, such as GEMMs, could be implemented using more than one library
5
+ or more than one technique. For example, a GEMM could be implemented for CUDA or
6
+ ROCm using either the blas or blasLt libraries. Further, ROCm's rocblas and
7
+ hipblaslt libraries allow the user to query for all possible algorithms and then
8
+ choose one. How does one know which implementation is the fastest and should be
9
+ chosen? That's what TunableOp provides.
10
+
11
+ Enabling TunableOp and Tuning Separately
12
+ ========================================
13
+
14
+ The TunableOp feature is enabled separately from enabling the tuning phase
15
+ itself. Enabling TunableOp means that PyTorch will replace any standard
16
+ operators with their Tunable implementations. Any call to a TunableOp first
17
+ checks whether it has already been tuned for the given operator inputs. If so,
18
+ it will immediately call the tuned operation; no further tuning will take place
19
+ even when the tuning setting is enabled. Instead if no tuning result is found,
20
+ and tuning is enabled, the TunableOp will benchmark every registered
21
+ implementation of that operator for the given set of inputs and select the
22
+ fastest.
23
+
24
+ File Input and Output
25
+ =====================
26
+
27
+ The first time any TunableOp is invoked, the internal database of tuned
28
+ operations will be prepared by attempting to read the results from the given
29
+ file. The default filename is 'tunableop_results.csv'. To support tuning when
30
+ multiple GPUs are used across multiple processes, the GPU device ordinal is
31
+ automatically inserted into the filename to avoid multiple processes overwriting
32
+ the same file.
33
+
34
+ If tuning is enabled and new tunings are discovered during the course of your
35
+ workload, it will also write out to this same filename with all tunings, both
36
+ the ones it read in at startup as well as the new ones found at runtime. This
37
+ can be used, for example, to build up a tunings file across many workloads by
38
+ reusing the same file. The output file is automatically created when the
39
+ application terminates. This behavior can be controlled by the C++ and Python
40
+ APIs but not the environment variables.
41
+
42
+ Assuming you specified a filename, you'll end up with a CSV file with contents
43
+ like so::
44
+
45
+ Validator,PT_VERSION,2.2.0
46
+ Validator,ROCM_VERSION,6.0.0.0-12969-1544e39
47
+ Validator,HIPBLASLT_VERSION,0.6.0-a9c5cc7
48
+ Validator,ROCBLAS_VERSION,4.0.0-72e57364-dirty
49
+ GemmTunableOp_float_NT,nt_25088_4096_64,Gemm_Hipblaslt_1219,1.262
50
+ GemmTunableOp_float_NT,nt_4096_4096_64,Gemm_Rocblas_1216,0.033
51
+
52
+ Note the "Validator" lines. If you change a library version, or ROCm version, or
53
+ PyTorch version, TunableOp will detect this and reject the tunings file because
54
+ the prior tunings are likely affected by other software changes.
55
+
56
+ The remaining lines are the tuned solutions for each TunableOp encountered
57
+ during your execution. Each line consists of 4 comma-separated fields: operator
58
+ name, operator parameters, solution name, and average execution time. The
59
+ execution time is an optional field. The CSV file can be edited, but with
60
+ caution. For example, the solution name (field 3) can be changed to "Default"
61
+ and it will fall back to the original PyTorch untuned implementation. Or, in the
62
+ case of ROCm's hipBLAS or hipBLASLt libraries, if you know the specific solution
63
+ index you can override the solution that TunableOp selected by replacing the
64
+ value. The operator name and parameters (fields 1 and 2) are internally named
65
+ and should not be modified. In the case of GemmTunableOp, field 1 indicates the
66
+ datatype and whether the inputs are transposed (T) or not (N) and field 2
67
+ indicates the M, N, K input shapes.
68
+
69
+ There is an option to enable verbose output but it is only recommended for
70
+ debugging purposes. This will produce a lot of diagnostic messages but may be
71
+ useful to see if TunableOp is being used at all. Otherwise, TunableOp is
72
+ completely silent, besides file output, unless there is a warning or error
73
+ during its use. The verbose option is only available by setting the environment
74
+ variable PYTORCH_TUNABLEOP_VEROBSE=1.
75
+
76
+ A Note on Tuning Behavior, Warmup, and Cache Effects
77
+ ====================================================
78
+
79
+ Tuning an operator consists of iterating through the list or registered
80
+ implementations and profiling each one. The profile is established by running a
81
+ single implementation in a loop multiple times and taking the average execution
82
+ time. There is also an optional warmup phase prior to tuning that can help with
83
+ reaching stable power states by the hardware. During tuning of a workload the
84
+ various hardware caches will more likely produce hits than when not tuning.
85
+ There are options for flushing the instruction cache and rotate the input tensors
86
+ which might help produce a more faithful profile of the tuned operator as if the
87
+ operator were run within a larger workload instead of in a tight, repetitive loop.
88
+
89
+ By default, each possible solution for a given operator will be run for either
90
+ 100 iterations or as many iterations that can be run within 30ms, whichever is
91
+ smaller, and its average execution will be calculated. The fastest solution
92
+ among all that were successfully profiled will be chosen. A profile might fail
93
+ if the given solution doesn't achieve the same accuracy as the default
94
+ implementation or if the solution returns an error code.
95
+
96
+ Current Tunable Operators
97
+ =========================
98
+
99
+ TunableGemm for ROCm
100
+ --------------------
101
+
102
+ Currently only a TunableGemm for ROCm is implemented. Note that CUDA builds of
103
+ PyTorch will function correctly when using TunableOp but the only solution
104
+ available to CUDA builds is the 'Default' implementation i.e. the original
105
+ cuBLAS default, now called through TunableOp. Any call to at::cuda::blas::gemm()
106
+ or ::bgemm() will be routed through TunableOp when enabled. Calling gemm() for a
107
+ given set of input arguments (transa, transb, m, n, k) will attempt to use the
108
+ fastest available implementation across both rocblas and hipblaslt.
109
+
110
+ Offline Tuning
111
+ ==============
112
+
113
+ Motivation
114
+ ----------
115
+ There are several use cases for offline tuning.
116
+
117
+ One use case involves a workload with a high-memory utilization, where regular tuning might lead to running out of memory.
118
+
119
+ Another use case is for compute-intensive workloads. In such cases, it is more resource-efficient to collect
120
+ the GEMMs for the workload once and then tune repeatedly with different tuning parameters or libraries.
121
+
122
+ Workflow
123
+ --------
124
+ There are basically two steps:
125
+ 1) Set the environment variables to collect the untuned GEMM and this will generate ``tunableop_untuned0.csv``:
126
+
127
+ .. code-block:: bash
128
+
129
+ export PYTORCH_TUNABLEOP_ENABLED=1
130
+ export PYTORCH_TUNABLEOP_TUNING=0
131
+ export PYTORCH_TUNABLEOP_RECORD_UNTUNED=1
132
+ ...
133
+
134
+ 2) Run a Python script that reads the ``tunableop_untuned0.csv`` and generates the ``tunableop_results0.csv``, like this:
135
+
136
+ .. code-block:: python
137
+
138
+ import torch.cuda.tunable as tunable
139
+ import os
140
+
141
+ os.putenv("PYTORCH_TUNABLEOP_ENABLED", "1")
142
+ os.putenv("PYTORCH_TUNABLEOP_TUNING", "1")
143
+ os.putenv("PYTORCH_TUNABLEOP_RECORD_UNTUNED", "0")
144
+ tunable.tune_gemm_in_file("tunableop_untuned0.csv")
145
+
146
+
147
+ It is also possible to take multiple untuned files and distribute the GEMMs for tuning to multiple GPUs
148
+ within a single node. In the first step, the GEMMs are first gathered and duplicate GEMMs are eliminated.
149
+ Next, the GEMMs are distributed to different GPUs for tuning. After all GEMMs are tuned, the results from
150
+ all the GPUs are then gathered into a single file whose base filename has ``_full0`` appended to it
151
+ (for example ``tunableop_results_full0.csv``). Finally, this new file, containing the gathered results, will be
152
+ duplicated N times, once for each GPU as convenience to the user will run the workload with the tuned
153
+ configuration on N GPUs.
154
+
155
+ .. code-block:: python
156
+
157
+ if __name__ == "__main__":
158
+ num_gpus = 8 # number of GPUs that will be used during the tuning process
159
+ tunable.mgpu_tune_gemm_in_file("tunableop_untuned?.csv", num_gpus)
160
+
161
+ Note that the usage of the ``mgpu_tune_gemm_in_file`` API is different from its single GPU counterpart
162
+ (``tune_gemm_in_file``). The body of the Python script that calls the API must be wrapped in ``main()`` as shown
163
+ due to the use of concurrent futures module. The argument to ``mgpu_tune_gemm_in_file`` must contain a wild card
164
+ expression (``?`` or ``*``) to generate the list of untuned files containing the GEMMs to be processed. The ``num_gpus``
165
+ must between 1 and the total number of GPUs available.
166
+
167
+ Tuning Context
168
+ ==============
169
+
170
+ The behavior of TunableOp is currently manipulated through environment
171
+ variables, the C++ interface of at::cuda::tunable::getTuningContext(), or the
172
+ torch.cuda.tunable python interfaces. The environment variables take precedence
173
+ over any setting you manipulate using the C++ or Python APIs.
174
+
175
+ Environment Variable Interface
176
+ ------------------------------
177
+ Environment variables are cached the first time they are read. You cannot use the
178
+ environment variable interface programmatically since the settings become fixed.
179
+ Use the C++ or Python APIs instead.
180
+
181
+ """
182
+
183
+ import concurrent.futures
184
+ import glob
185
+ import multiprocessing as mp
186
+ import os
187
+ import shutil
188
+ import warnings
189
+ from typing import Optional
190
+
191
+ import torch
192
+
193
+
194
+ __all__ = [
195
+ "enable",
196
+ "is_enabled",
197
+ "tuning_enable",
198
+ "tuning_is_enabled",
199
+ "record_untuned_enable",
200
+ "record_untuned_is_enabled",
201
+ "set_max_tuning_duration",
202
+ "get_max_tuning_duration",
203
+ "set_max_tuning_iterations",
204
+ "get_max_tuning_iterations",
205
+ "set_filename",
206
+ "get_filename",
207
+ "get_results",
208
+ "get_validators",
209
+ "read_file",
210
+ "tune_gemm_in_file",
211
+ "mgpu_tune_gemm_in_file",
212
+ "set_rotating_buffer_size",
213
+ "get_rotating_buffer_size",
214
+ "set_numerical_check_tolerances",
215
+ ]
216
+
217
+
218
+ def enable(val: bool = True) -> None:
219
+ r"""This is the big on/off switch for all TunableOp implementations."""
220
+ torch._C._cuda_tunableop_enable(val) # type: ignore[attr-defined]
221
+
222
+
223
+ def is_enabled() -> bool:
224
+ r"""Returns whether the TunableOp feature is enabled."""
225
+ return torch._C._cuda_tunableop_is_enabled() # type: ignore[attr-defined]
226
+
227
+
228
+ def tuning_enable(val: bool = True) -> None:
229
+ r"""Enable tuning of TunableOp implementations.
230
+
231
+ When enabled, if a tuned entry isn't found, run the tuning step and record
232
+ the entry.
233
+ """
234
+ torch._C._cuda_tunableop_tuning_enable(val) # type: ignore[attr-defined]
235
+
236
+
237
+ def tuning_is_enabled() -> bool:
238
+ r"""Returns whether TunableOp implementations can be tuned."""
239
+ return torch._C._cuda_tunableop_tuning_is_enabled() # type: ignore[attr-defined]
240
+
241
+
242
+ def record_untuned_enable(val: bool = True) -> None:
243
+ r"""Enable recording untuned of TunableOp perations for offline tuning.
244
+
245
+ When enabled, if a tuned entry isn't found, write it to the untuned file.
246
+ """
247
+ torch._C._cuda_record_untuned_enable(val) # type: ignore[attr-defined]
248
+
249
+
250
+ def record_untuned_is_enabled() -> bool:
251
+ r"""Returns whether TunableOp operations are recorded for offline tuning."""
252
+ return torch._C._cuda_record_untuned_is_enabled() # type: ignore[attr-defined]
253
+
254
+
255
+ def set_max_tuning_duration(duration: int) -> None:
256
+ r"""Set max time in milliseconds to spend tuning a given solution.
257
+
258
+ If both max tuning duration and iterations are set, the smaller of the two
259
+ will be honored. At minimum 1 tuning iteration will always be run.
260
+ """
261
+ torch._C._cuda_tunableop_set_max_tuning_duration(duration) # type: ignore[attr-defined]
262
+
263
+
264
+ def get_max_tuning_duration() -> int:
265
+ r"""Get max time to spend tuning a given solution."""
266
+ return torch._C._cuda_tunableop_get_max_tuning_duration() # type: ignore[attr-defined]
267
+
268
+
269
+ def set_max_tuning_iterations(iterations: int) -> None:
270
+ r"""Set max number of iterations to spend tuning a given solution.
271
+
272
+ If both max tuning duration and iterations are set, the smaller of the two
273
+ will be honored. At minimum 1 tuning iteration will always be run.
274
+ """
275
+ torch._C._cuda_tunableop_set_max_tuning_iterations(iterations) # type: ignore[attr-defined]
276
+
277
+
278
+ def get_max_tuning_iterations() -> int:
279
+ r"""Get max iterations to spend tuning a given solution."""
280
+ return torch._C._cuda_tunableop_get_max_tuning_iterations() # type: ignore[attr-defined]
281
+
282
+
283
+ def set_filename(filename: str, insert_device_ordinal: bool = False) -> None:
284
+ r"""Set the filename to use for input/output of tuning results.
285
+
286
+ If :attr:`insert_device_ordinal` is ``True`` then the current device ordinal
287
+ will be added to the given filename automatically. This can be used in a
288
+ 1-process-per-gpu scenario to ensure all processes write to a separate file.
289
+ """
290
+ torch._C._cuda_tunableop_set_filename(filename, insert_device_ordinal) # type: ignore[attr-defined]
291
+
292
+
293
+ def get_filename() -> str:
294
+ r"""Get the results filename."""
295
+ return torch._C._cuda_tunableop_get_filename() # type: ignore[attr-defined]
296
+
297
+
298
+ def get_results() -> tuple[str, str, str, float]:
299
+ r"""Return all TunableOp results."""
300
+ return torch._C._cuda_tunableop_get_results() # type: ignore[attr-defined]
301
+
302
+
303
+ def get_validators() -> tuple[str, str]:
304
+ r"""Return the TunableOp validators."""
305
+ return torch._C._cuda_tunableop_get_validators() # type: ignore[attr-defined]
306
+
307
+
308
+ def read_file(filename: Optional[str] = None) -> bool:
309
+ r"""Read results from a TunableOp CSV file.
310
+
311
+ If :attr:`filename` is not given, ``get_filename()`` is called.
312
+ """
313
+ if filename is None:
314
+ filename = get_filename()
315
+ return torch._C._cuda_tunableop_read_file(filename) # type: ignore[attr-defined]
316
+
317
+
318
+ def set_rotating_buffer_size(buffer_size: int) -> None:
319
+ r"""Set rotating buffer size to this value in MB, if the buffer size is greater than zero.
320
+
321
+ If less than zero, query L2 cache size. If equal to zero, means deactivate rotating buffer.
322
+ """
323
+ return torch._C._cuda_tunableop_set_rotating_buffer_size(buffer_size) # type: ignore[attr-defined]
324
+
325
+
326
+ def get_rotating_buffer_size() -> int:
327
+ r"""Get the rotating buffer size in kilobytes."""
328
+ return torch._C._cuda_tunableop_get_rotating_buffer_size() # type: ignore[attr-defined]
329
+
330
+
331
+ def set_numerical_check_tolerances(
332
+ enable: bool, atol: float = 1e-5, rtol: float = 1e-5
333
+ ) -> None:
334
+ r"""Set the atol and rtol values in numeric check"""
335
+ return torch._C._cuda_tunableop_set_numerical_check_tolerances(enable, atol, rtol) # type: ignore[attr-defined]
336
+
337
+
338
+ def tune_gemm_in_file(filename: str) -> None:
339
+ r"""tune GEMM in file."""
340
+
341
+ assert is_enabled()
342
+ assert tuning_is_enabled()
343
+
344
+ deviceid = torch.cuda.current_device()
345
+
346
+ with open(filename) as file:
347
+ for line in file:
348
+ if line.startswith(("Gemm", "ScaledGemm")):
349
+ _process_single_offline_gemm(line, deviceid)
350
+
351
+
352
+ def _gather_unique_untuned_gemm_from_files(filename_pattern: str) -> set[str]:
353
+ r"""Process multiple untuned results file and return a set with duplicates removed."""
354
+ unique_gemm_entries = set() # set will avoid duplicates
355
+
356
+ for file_path in glob.glob(filename_pattern):
357
+ with open(file_path) as file:
358
+ for line in file:
359
+ if line.startswith(("Gemm", "ScaledGemm")):
360
+ unique_gemm_entries.add(line)
361
+
362
+ return unique_gemm_entries
363
+
364
+
365
+ def _gather_tunableop_results() -> None:
366
+ r"""Gather results from multiple tunableop results file and create a single file."""
367
+ gemm_lines = set()
368
+ validator_lines = []
369
+
370
+ # Need to allow for the possibility that results filename was
371
+ # set with the Python API instead of with environment variable.
372
+ # Also possible that results filename was not set at all.
373
+ # There are several test cases to check, but ultimately we
374
+ # need a glob-able expression
375
+ results_filename = get_filename() # Note empty string could be returned here
376
+
377
+ if (
378
+ results_filename is not None and results_filename != ""
379
+ ): # Case were the Python API was used to set the filename
380
+ dot_pos = results_filename.find(".")
381
+ if dot_pos != -1 and dot_pos > 0:
382
+ # Replace the character just to the left of the dot
383
+ filename_pattern = (
384
+ results_filename[: dot_pos - 1] + "?" + results_filename[dot_pos:]
385
+ )
386
+ else:
387
+ filename_pattern = "" # Needed to make linter happy
388
+ else: # Case where the environment variable was used to set the filename.
389
+ results_filename_env = os.getenv("PYTORCH_TUNABLEOP_FILENAME")
390
+ if results_filename_env is None or results_filename_env == "":
391
+ filename_pattern = "tunableop_results?.csv"
392
+ elif "%d" in results_filename_env:
393
+ filename_pattern = results_filename_env.replace("%d", "?")
394
+ else:
395
+ filename_pattern = results_filename_env.replace(".", "?.")
396
+
397
+ assert "?" in filename_pattern
398
+
399
+ FirstFile = False
400
+ matching_files = glob.glob(filename_pattern)
401
+ num_matching_files = len(matching_files)
402
+ for file_path in matching_files:
403
+ with open(file_path) as file:
404
+ for line in file:
405
+ if line.startswith("Validator"):
406
+ if not (FirstFile):
407
+ # Only read Validator from first file
408
+ validator_lines.append(line)
409
+ else:
410
+ gemm_lines.add(line)
411
+
412
+ FirstFile = True
413
+
414
+ output_file = filename_pattern.replace("?", "_full0")
415
+
416
+ with open(output_file, "w") as out_file:
417
+ for line in validator_lines:
418
+ out_file.write(line)
419
+ for line in gemm_lines:
420
+ out_file.write(line)
421
+
422
+ # Create num_matching_copies of the results file
423
+ for i in range(1, num_matching_files):
424
+ duplicate_file = output_file.replace("0", str(i))
425
+ shutil.copy(output_file, duplicate_file)
426
+
427
+
428
+ def _create_matrices(
429
+ m: int,
430
+ n: int,
431
+ k: int,
432
+ lda: int,
433
+ ldb: int,
434
+ ldc: int,
435
+ transA: bool,
436
+ transB: bool,
437
+ dtypeA: torch.dtype,
438
+ deviceid: str,
439
+ dtypeB: Optional[torch.dtype] = None,
440
+ randn: bool = True,
441
+ subMatrix: bool = False,
442
+ ) -> tuple[torch.Tensor, torch.Tensor]:
443
+ r"""Helper function for _process_single_offline_gemm.
444
+ Creates matrices that are then consumed by one of the Torch GEMM APIs.
445
+ """
446
+ # Fill parameters set for use with ScaledGEMM
447
+ fillA = 0.25
448
+ fillB = 0.75
449
+
450
+ if dtypeB is None:
451
+ dtypeB = dtypeA
452
+
453
+ if subMatrix:
454
+ # User reference for understanding leading dimension:
455
+ # https://github.com/Reference-LAPACK/lapack/blob/master/BLAS/SRC/dgemm.f
456
+ # TO DO: According to lines 108 - 133, there is no lower bound on rowsA,
457
+ # but there is a restriction on rowsB. Using this formula for now as it
458
+ # seems to work for all UTs.
459
+ rowsA = rowsB = max(ldc, k)
460
+
461
+ if randn:
462
+ matA = torch.randn(rowsA, lda, dtype=dtypeA, device=deviceid)
463
+ matB = torch.randn(rowsB, ldb, dtype=dtypeA, device=deviceid)
464
+ else:
465
+ matA = torch.full((rowsA, lda), fillA, dtype=dtypeB, device=deviceid)
466
+ matB = torch.full((rowsB, ldb), fillB, dtype=dtypeB, device=deviceid)
467
+
468
+ subA = matA[:k, :m].t() if transA else matA[:m, :k]
469
+ subB = matB[:n, :k].t() if transB else matB[:k, :n]
470
+ return subA, subB
471
+ else:
472
+ if randn:
473
+ matA = (
474
+ torch.rand(k, m, dtype=dtypeA, device=deviceid).t()
475
+ if transA
476
+ else torch.rand(m, k, dtype=dtypeA, device=deviceid)
477
+ )
478
+ matB = (
479
+ torch.rand(n, k, dtype=dtypeB, device=deviceid).t()
480
+ if transB
481
+ else torch.rand(k, n, dtype=dtypeB, device=deviceid)
482
+ )
483
+ else:
484
+ matA = (
485
+ torch.full((k, m), fillA, dtype=dtypeA, device=deviceid).t()
486
+ if transA
487
+ else torch.full((m, k), fillA, dtype=dtypeA, device=deviceid)
488
+ )
489
+ matB = (
490
+ torch.full((n, k), fillB, dtype=dtypeB, device=deviceid).t()
491
+ if transB
492
+ else torch.full((k, n), fillB, dtype=dtypeB, device=deviceid)
493
+ )
494
+ return matA, matB
495
+
496
+
497
+ def _create_batch_matrices(
498
+ m: int,
499
+ n: int,
500
+ k: int,
501
+ b: int,
502
+ lda: int,
503
+ ldb: int,
504
+ ldc: int,
505
+ transA: bool,
506
+ transB: bool,
507
+ dtype: torch.dtype,
508
+ deviceid: str,
509
+ subMatrix: bool = False,
510
+ ) -> tuple[torch.Tensor, torch.Tensor]:
511
+ r"""Helper function for _process_single_offline_gemm.
512
+ Creates batch matrices that are then consumed by one of the Torch GEMM APIs.
513
+ Similar to _create_matrices but for 3D batch matrices.
514
+ """
515
+ if subMatrix:
516
+ # User reference for understanding leading dimension:
517
+ # https://github.com/Reference-LAPACK/lapack/blob/master/BLAS/SRC/dgemm.f
518
+ # TO DO: According to lines 108 - 133, there is no lower bound on rowsA,
519
+ # but there is a restriction on rowsB. Using this formula for now as it
520
+ # seems to work for all UTs.
521
+ rowsA = rowsB = max(ldc, k)
522
+
523
+ matA = torch.randn(b, rowsA, lda, dtype=dtype, device=deviceid)
524
+ matB = torch.randn(b, rowsB, ldb, dtype=dtype, device=deviceid)
525
+
526
+ subA = matA[:b, :k, :m].transpose(1, 2) if transA else matA[:b, :m, :k]
527
+ subB = matB[:b, :n, :k].transpose(1, 2) if transB else matB[:b, :k, :n]
528
+ return subA, subB
529
+ else:
530
+ matA = (
531
+ torch.rand(b, k, m, dtype=dtype, device=deviceid)
532
+ if transA
533
+ else torch.rand(b, m, k, dtype=dtype, device=deviceid)
534
+ )
535
+ matB = (
536
+ torch.rand(b, n, k, dtype=dtype, device=deviceid)
537
+ if transB
538
+ else torch.rand(b, k, n, dtype=dtype, device=deviceid)
539
+ )
540
+ matA = matA.transpose(1, 2) if transA else matA
541
+ matB = matB.transpose(1, 2) if transB else matB
542
+ return matA, matB
543
+
544
+
545
+ def _process_single_offline_gemm(untuned_gemm_line: str, gpu_id: int) -> None:
546
+ r"""Process a single untuned GEMM."""
547
+
548
+ deviceid = "cuda:" + str(gpu_id)
549
+
550
+ dtype_dict = {
551
+ "float": torch.float32,
552
+ "tf32": torch.float32,
553
+ "double": torch.float64,
554
+ "BFloat16": torch.bfloat16,
555
+ "Half": torch.half,
556
+ "c10::complex<double>": torch.complex128,
557
+ "c10::complex<float>": torch.complex64,
558
+ "Float8_e4m3fn": torch.float8_e4m3fn,
559
+ "Float8_e5m2": torch.float8_e5m2,
560
+ "Float8_e4m3fnuz": torch.float8_e4m3fnuz,
561
+ "Float8_e5m2fnuz": torch.float8_e5m2fnuz,
562
+ }
563
+
564
+ untuned_gemm = untuned_gemm_line.strip().split(",")[:]
565
+
566
+ underscore_count = untuned_gemm[0].count("_")
567
+
568
+ # Initialize dtype to make linter happy
569
+ dtype = None
570
+ dtypeA = None
571
+ dtypeB = None
572
+ dtypeC = None
573
+
574
+ # Extract BLAS parameters
575
+ if underscore_count == 2:
576
+ [op_sig, data_type, layout] = untuned_gemm[0].split("_")
577
+ transB = layout[0] == "T"
578
+ transA = layout[1] == "T"
579
+ dtype = dtype_dict.get(data_type)
580
+ if data_type == "tf32":
581
+ torch.backends.cuda.matmul.allow_tf32 = True
582
+ else:
583
+ torch.backends.cuda.matmul.allow_tf32 = False
584
+
585
+ else: # ScaledGEMM
586
+ count = untuned_gemm[0].count("_")
587
+ assert count in [6, 7]
588
+ untuned_gemm_temp = untuned_gemm[0].split("_")
589
+ # dtypeC = might not be FP8 type, keep track
590
+ # of the number of underscores
591
+ op_sig = untuned_gemm_temp[0]
592
+ data_typeA = untuned_gemm_temp[1] + "_" + untuned_gemm_temp[2]
593
+ data_typeB = untuned_gemm_temp[3] + "_" + untuned_gemm_temp[4]
594
+ if count == 7:
595
+ data_typeC = untuned_gemm_temp[5] + "_" + untuned_gemm_temp[6]
596
+ else:
597
+ data_typeC = untuned_gemm_temp[5]
598
+ transB = untuned_gemm_temp[count][0] == "T"
599
+ transA = untuned_gemm_temp[count][1] == "T"
600
+ dtypeA = dtype_dict.get(data_typeA)
601
+ dtypeB = dtype_dict.get(data_typeB)
602
+ dtypeC = dtype_dict.get(data_typeC)
603
+
604
+ untuned_gemm_temp = untuned_gemm[1].split("_")
605
+ [n, m, k] = [int(g) for g in untuned_gemm_temp[1:4]]
606
+ if op_sig == "GemmStridedBatchedTunableOp":
607
+ assert untuned_gemm_temp[6] == "ld"
608
+ [ldb, lda, ldc] = [int(g) for g in untuned_gemm_temp[7:10]]
609
+ else:
610
+ assert untuned_gemm_temp[4] == "ld"
611
+ [ldb, lda, ldc] = [int(g) for g in untuned_gemm_temp[5:8]]
612
+
613
+ # Detect subMatrix case
614
+ if all(item in [n, m, k] for item in [lda, ldb, ldc]):
615
+ subMatrix = False
616
+ else:
617
+ subMatrix = True
618
+
619
+ if op_sig == "GemmTunableOp":
620
+ # Warnings for unsupported cases:
621
+ if m == 1 or n == 1 or k == 1:
622
+ if (not transA) and (not transB):
623
+ pass # case is supported
624
+ elif transA and n == 1:
625
+ pass # case is supported
626
+ else:
627
+ warnings.warn(
628
+ "Offline tuning is not supported for this GEMM. Use online tuning instead. "
629
+ + f"Skipped tuning for: {untuned_gemm[1]}",
630
+ stacklevel=2,
631
+ )
632
+ return
633
+
634
+ # Resolve linter issue
635
+ if dtype is None or not isinstance(dtype, torch.dtype):
636
+ raise TypeError(f"dtype must be a torch.dtype, but got {dtype}")
637
+
638
+ matA, matB = _create_matrices(
639
+ m, n, k, lda, ldb, ldc, transA, transB, dtype, deviceid, subMatrix=subMatrix
640
+ )
641
+ torch.mm(matA, matB)
642
+
643
+ elif op_sig == "GemmStridedBatchedTunableOp":
644
+ # Warnings for unsupported cases:
645
+ if m == 1 or n == 1 or k == 1:
646
+ warnings.warn(
647
+ "Offline tuning is not support for this GEMM. Use online tuning instead. "
648
+ + f"Skipped tuning for: {untuned_gemm[1]}",
649
+ stacklevel=2,
650
+ )
651
+ return
652
+
653
+ [b] = [int(g) for g in untuned_gemm_temp[5:6]]
654
+
655
+ # Resolve linter issue
656
+ if dtype is None or not isinstance(dtype, torch.dtype):
657
+ raise TypeError(f"dtype must be a torch.dtype, but got {dtype}")
658
+
659
+ matA, matB = _create_batch_matrices(
660
+ m,
661
+ n,
662
+ k,
663
+ b,
664
+ lda,
665
+ ldb,
666
+ ldc,
667
+ transA,
668
+ transB,
669
+ dtype,
670
+ deviceid,
671
+ subMatrix=subMatrix,
672
+ )
673
+ torch.bmm(matA, matB)
674
+ elif op_sig == "ScaledGemmTunableOp":
675
+ # Only combination supported by PyTorch
676
+ assert transB is True
677
+ assert transA is False
678
+
679
+ # Resolve linter issue
680
+ if dtypeA is None or not isinstance(dtypeA, torch.dtype):
681
+ raise TypeError(f"dtype must be a torch.dtype, but got {dtypeA}")
682
+
683
+ matA, matB = _create_matrices(
684
+ m,
685
+ n,
686
+ k,
687
+ lda,
688
+ ldb,
689
+ ldc,
690
+ transA,
691
+ transB,
692
+ dtypeA,
693
+ deviceid,
694
+ dtypeB=dtypeB,
695
+ randn=False,
696
+ subMatrix=subMatrix,
697
+ )
698
+
699
+ assert untuned_gemm_temp[8] == "rw"
700
+ if untuned_gemm_temp[9] == "1":
701
+ rowwise = True
702
+ else:
703
+ rowwise = False
704
+ if rowwise:
705
+ scaleA = (
706
+ torch.ones((1, m), device=deviceid)
707
+ if transA
708
+ else torch.ones((m, 1), device=deviceid)
709
+ )
710
+ scaleB = (
711
+ torch.ones((1, n), device=deviceid)
712
+ if transB
713
+ else torch.ones((n, 1), device=deviceid)
714
+ )
715
+ else:
716
+ scaleA = torch.tensor(0.8, device=deviceid)
717
+ scaleB = torch.tensor(0.9, device=deviceid)
718
+
719
+ assert untuned_gemm_temp[10] == "bias"
720
+ if untuned_gemm_temp[11] == "None": # no bias vector
721
+ torch._scaled_mm(
722
+ matA, matB, scale_a=scaleA, scale_b=scaleB, out_dtype=dtypeC
723
+ )
724
+ else: # bias vector present
725
+ fillbias = 0.10
726
+ bias_dtype = dtype_dict.get(untuned_gemm_temp[11])
727
+ bias = (
728
+ torch.full((n,), fillbias, dtype=bias_dtype, device=deviceid)
729
+ if transB
730
+ else torch.full((m,), fillbias, dtype=bias_dtype, device=deviceid)
731
+ )
732
+ torch._scaled_mm(
733
+ matA, matB, scale_a=scaleA, scale_b=scaleB, out_dtype=dtypeC, bias=bias
734
+ )
735
+
736
+ elif op_sig == "GemmAndBiasTunableOp":
737
+ # y = x*A^T + b
738
+ assert transA != transB
739
+
740
+ # Resolve linter issue
741
+ if dtype is None or not isinstance(dtype, torch.dtype):
742
+ raise TypeError(f"dtype must be a torch.dtype, but got {dtype}")
743
+
744
+ bias = torch.rand(n, dtype=dtype, device=deviceid)
745
+
746
+ X, matA = _create_matrices(
747
+ m, n, k, lda, ldb, ldc, transA, transB, dtype, deviceid, subMatrix=subMatrix
748
+ )
749
+ matA = matA.t()
750
+ torch.nn.functional.linear(X, matA, bias)
751
+ else:
752
+ warnings.warn(f"error: unknown op {op_sig}", stacklevel=2)
753
+
754
+
755
+ def _check_tuning_assertions() -> None:
756
+ r"""Helper function for multi-GPU tuning case. Need to check that TunableOp feature
757
+ is enabled and that tuning is enabled.
758
+ """
759
+
760
+ if is_enabled() is False:
761
+ warnings.warn("TunableOp was disabled. Trying to enable now.", stacklevel=2)
762
+ enable(True)
763
+ assert is_enabled() is True
764
+ assert tuning_is_enabled() is True
765
+ assert record_untuned_is_enabled() is False
766
+
767
+
768
+ def mgpu_tune_gemm_in_file(filename_pattern: str, num_gpus: int) -> None:
769
+ r"""Process one or more files and distribute work over one or more GPUs."""
770
+ unique_gemm_entries = _gather_unique_untuned_gemm_from_files(filename_pattern)
771
+
772
+ total_gpus = torch.cuda.device_count()
773
+
774
+ assert 1 <= num_gpus <= total_gpus
775
+
776
+ mp_context = mp.get_context("spawn")
777
+
778
+ futures = [] # empty list to hold futures
779
+
780
+ # GEMM are assigned to GPUs in a round robin manner
781
+ h = 0
782
+ with concurrent.futures.ProcessPoolExecutor(
783
+ max_workers=num_gpus,
784
+ mp_context=mp_context,
785
+ initializer=_check_tuning_assertions,
786
+ ) as executor:
787
+ # The workers are a separate process. TunableOp will be
788
+ # enabled in the child processes if PYTORCH_TUNABLEOP_ENABLED=1
789
+ # In the initializer, we also try to enable TunableOP if th
790
+ # environment variable was NOT set.
791
+
792
+ for line in unique_gemm_entries:
793
+ future = executor.submit(_process_single_offline_gemm, line, h)
794
+ futures.append(future)
795
+ h = (h + 1) % num_gpus
796
+
797
+ for future in concurrent.futures.as_completed(futures):
798
+ future.result()
799
+
800
+ torch.cuda.synchronize()
801
+
802
+ _gather_tunableop_results()
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/__init__.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+ import pdb
4
+ import sys
5
+ import traceback
6
+ import typing
7
+ from datetime import timedelta
8
+
9
+ import torch
10
+
11
+
12
+ log = logging.getLogger(__name__)
13
+
14
+
15
+ def is_available() -> bool:
16
+ """
17
+ Return ``True`` if the distributed package is available.
18
+
19
+ Otherwise,
20
+ ``torch.distributed`` does not expose any other APIs. Currently,
21
+ ``torch.distributed`` is available on Linux, MacOS and Windows. Set
22
+ ``USE_DISTRIBUTED=1`` to enable it when building PyTorch from source.
23
+ Currently, the default value is ``USE_DISTRIBUTED=1`` for Linux and Windows,
24
+ ``USE_DISTRIBUTED=0`` for MacOS.
25
+ """
26
+ return hasattr(torch._C, "_c10d_init")
27
+
28
+
29
+ if is_available() and not torch._C._c10d_init():
30
+ raise RuntimeError("Failed to initialize torch.distributed")
31
+
32
+ # Custom Runtime Errors thrown from the distributed package
33
+ DistError = torch._C._DistError
34
+ DistBackendError = torch._C._DistBackendError
35
+ DistNetworkError = torch._C._DistNetworkError
36
+ DistStoreError = torch._C._DistStoreError
37
+ QueueEmptyError = torch._C._DistQueueEmptyError
38
+
39
+ if is_available():
40
+ from torch._C._distributed_c10d import (
41
+ _broadcast_coalesced,
42
+ _compute_bucket_assignment_by_size,
43
+ _ControlCollectives,
44
+ _DEFAULT_FIRST_BUCKET_BYTES,
45
+ _make_nccl_premul_sum,
46
+ _register_builtin_comm_hook,
47
+ _register_comm_hook,
48
+ _StoreCollectives,
49
+ _test_python_store,
50
+ _verify_params_across_processes,
51
+ Backend as _Backend,
52
+ BuiltinCommHookType,
53
+ DebugLevel,
54
+ FileStore,
55
+ get_debug_level,
56
+ GradBucket,
57
+ Logger,
58
+ PrefixStore,
59
+ ProcessGroup as ProcessGroup,
60
+ Reducer,
61
+ set_debug_level,
62
+ set_debug_level_from_env,
63
+ Store,
64
+ TCPStore,
65
+ Work as _Work,
66
+ )
67
+
68
+ class _DistributedPdb(pdb.Pdb):
69
+ """
70
+ Supports using PDB from inside a multiprocessing child process.
71
+
72
+ Usage:
73
+ _DistributedPdb().set_trace()
74
+ """
75
+
76
+ def interaction(self, *args, **kwargs):
77
+ _stdin = sys.stdin
78
+ try:
79
+ with open("/dev/stdin") as sys.stdin:
80
+ pdb.Pdb.interaction(self, *args, **kwargs)
81
+ finally:
82
+ sys.stdin = _stdin
83
+
84
+ _breakpoint_cache: dict[int, typing.Any] = {}
85
+
86
+ def breakpoint(rank: int = 0, skip: int = 0, timeout_s=3600):
87
+ """
88
+ Set a breakpoint, but only on a single rank. All other ranks will wait for you to be
89
+ done with the breakpoint before continuing.
90
+
91
+ Args:
92
+ rank (int): Which rank to break on. Default: ``0``
93
+ skip (int): Skip the first ``skip`` calls to this breakpoint. Default: ``0``.
94
+ """
95
+ if skip > 0:
96
+ key = hash(str(traceback.format_exc()))
97
+ counter = _breakpoint_cache.get(key, 0) + 1
98
+ _breakpoint_cache[key] = counter
99
+ if counter <= skip:
100
+ log.warning("Skip the breakpoint, counter=%d", counter)
101
+ return
102
+
103
+ # avoid having the default timeout (if short) interrupt your debug session
104
+ if timeout_s is not None:
105
+ for group in torch.distributed.distributed_c10d._pg_map:
106
+ torch.distributed.distributed_c10d._set_pg_timeout(
107
+ timedelta(seconds=timeout_s), group
108
+ )
109
+
110
+ if get_rank() == rank:
111
+ pdb = _DistributedPdb()
112
+ pdb.message(
113
+ "\n!!! ATTENTION !!!\n\n"
114
+ f"Type 'up' to get to the frame that called dist.breakpoint(rank={rank})\n"
115
+ )
116
+ pdb.set_trace()
117
+ # If Meta/Python keys are in the TLS, we want to make sure that we ignore them
118
+ # and hit the (default) CPU/CUDA implementation of barrier.
119
+ meta_in_tls = torch._C._meta_in_tls_dispatch_include()
120
+ guard = torch._C._DisableTorchDispatch() # type: ignore[attr-defined]
121
+ torch._C._set_meta_in_tls_dispatch_include(False)
122
+ try:
123
+ barrier()
124
+ finally:
125
+ torch._C._set_meta_in_tls_dispatch_include(meta_in_tls)
126
+ del guard
127
+
128
+ if sys.platform != "win32":
129
+ from torch._C._distributed_c10d import HashStore
130
+
131
+ from .device_mesh import DeviceMesh, init_device_mesh
132
+
133
+ # Variables prefixed with underscore are not auto imported
134
+ # See the comment in `distributed_c10d.py` above `_backend` on why we expose
135
+ # this.
136
+ # pyrefly: ignore [deprecated]
137
+ from .distributed_c10d import * # noqa: F403
138
+ from .distributed_c10d import ( # pyrefly: ignore # deprecated; pyrefly: ignore [deprecated]
139
+ _all_gather_base,
140
+ _coalescing_manager,
141
+ _CoalescingManager,
142
+ _create_process_group_wrapper,
143
+ _get_process_group_name,
144
+ _rank_not_in_group,
145
+ _reduce_scatter_base,
146
+ _time_estimator,
147
+ get_node_local_rank,
148
+ )
149
+ from .remote_device import _remote_device
150
+ from .rendezvous import (
151
+ _create_store_from_options,
152
+ register_rendezvous_handler,
153
+ rendezvous,
154
+ )
155
+
156
+ set_debug_level_from_env()
157
+
158
+ else:
159
+ # This stub is sufficient to get
160
+ # python test/test_public_bindings.py -k test_correct_module_names
161
+ # working even when USE_DISTRIBUTED=0. Feel free to add more
162
+ # stubs as necessary.
163
+ # We cannot define stubs directly because they confuse pyre
164
+
165
+ class _ProcessGroupStub:
166
+ pass
167
+
168
+ sys.modules["torch.distributed"].ProcessGroup = _ProcessGroupStub # type: ignore[attr-defined]
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_checkpointable.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ from typing_extensions import Protocol, runtime_checkable
3
+
4
+ import torch
5
+
6
+
7
+ @runtime_checkable
8
+ class _Checkpointable(Protocol): # noqa: PYI046
9
+ """
10
+ Interface for checkpointable objects.
11
+ Implemented as a protocol, implicit subtyping is supported so subclasses do not need to inherit this explicitly.
12
+ This is to allow arbitrary objects/tensor subclasses to hook into DCP seamlessly through implementing the interface.
13
+ """
14
+
15
+ def __create_write_items__(self, fqn: str, object: object) -> list[object]:
16
+ """
17
+ Return a list of WriteItems based on object's contents.
18
+ """
19
+ raise NotImplementedError(
20
+ "_Checkpointable._create_write_items is not implemented"
21
+ )
22
+
23
+ def __create_chunk_list__(self) -> list[object]:
24
+ """
25
+ Return a list of `ChunkStorageMetadata` based on object's contents.
26
+ """
27
+ raise NotImplementedError(
28
+ "_Checkpointable._create_chunk_list is not implemented"
29
+ )
30
+
31
+ def __get_tensor_shard__(self, index: int) -> torch.Tensor:
32
+ """
33
+ Return a 'torch.Tensor' shard based on 'MetadataIndex'.
34
+ """
35
+ raise NotImplementedError(
36
+ "_Checkpointable._get_tensor_shard is not implemented"
37
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .checkpoint_activation import checkpoint
2
+ from .contract import _get_registry, contract
3
+ from .replicate import replicate
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/checkpoint_activation.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from collections.abc import Generator
3
+ from contextlib import AbstractContextManager, contextmanager, nullcontext
4
+ from typing import Any
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from torch.utils.checkpoint import (
9
+ _checkpoint_without_reentrant_generator,
10
+ _DEFAULT_DETERMINISM_MODE,
11
+ )
12
+
13
+ from .contract import _State, contract
14
+
15
+
16
+ @contextmanager
17
+ def _no_hook(module: nn.Module, user_ctx: AbstractContextManager | None = None):
18
+ r"""
19
+ Disable hooks installed by checkpoint to avoid unintentional recursion
20
+ during backward recomputation.
21
+ """
22
+
23
+ with user_ctx if user_ctx else nullcontext():
24
+ orig_enable_hook = checkpoint.state(module).enable_hook
25
+ checkpoint.state(module).enable_hook = False
26
+ try:
27
+ yield
28
+ finally:
29
+ checkpoint.state(module).enable_hook = orig_enable_hook
30
+
31
+
32
+ class _CheckpointState(_State):
33
+ enable_hook: bool = False
34
+ _ac_generator: Generator[None, None, None] | None
35
+
36
+
37
+ @contract(_CheckpointState)
38
+ def checkpoint(module: nn.Module, **kwargs) -> nn.Module:
39
+ r"""
40
+ This is a composable activation checkpointing API. Unlike functional
41
+ activation checkpointing APIs, this one does not require changing model
42
+ source code. Unlike ``nn.Module`` wrapper activation checkpointing APIs,
43
+ this one does not modify model structure or fully-qualified names either.
44
+ Under the hood, it registers activation checkpointing logic as pre- and
45
+ post-forward hooks. Hence, this API can be easily applied to any model or
46
+ sub-modules in the model.
47
+
48
+ Args:
49
+ module (nn.Module): the target model or sub-module to apply activation
50
+ checkpointing.
51
+
52
+ Example::
53
+ >>> # xdoctest: +SKIP
54
+ >>> import torch.nn as nn
55
+ >>>
56
+ >>> class MyModel(nn.Module):
57
+ >>> def __init__(self) -> None:
58
+ >>> super().__init__()
59
+ >>> self.l1 = nn.Linear(10, 10)
60
+ >>> self.l2 = nn.Linear(10, 10)
61
+ >>>
62
+ >>> def forward(self, x):
63
+ >>> return self.l2(self.l1(x))
64
+ >>>
65
+ >>> model = MyModel()
66
+ >>> checkpoint(model.l1) # apply activation checkpointing only to l1
67
+ >>> model(torch.zeros(2, 10)).sum().backward()
68
+
69
+ """
70
+ torch._C._log_api_usage_once("torch.distributed.checkpoint")
71
+
72
+ use_reentrant = kwargs.pop("use_reentrant", False)
73
+ if use_reentrant:
74
+ raise NotImplementedError(
75
+ "use_reentrant=True is not supported in composable checkpoint. "
76
+ "Please use torch.utils.checkpoint.checkpoint instead."
77
+ )
78
+ preserve_rng_state = kwargs.pop("preserve_rng_state", True)
79
+ user_context_fns = kwargs.pop("context_fn", None)
80
+ determinism_check = kwargs.pop("determinism_check", _DEFAULT_DETERMINISM_MODE)
81
+ debug = kwargs.pop("debug", False)
82
+ early_stop = kwargs.pop("early_stop", True)
83
+
84
+ if kwargs:
85
+ raise ValueError(
86
+ "Unexpected keyword arguments: " + ",".join(arg for arg in kwargs)
87
+ )
88
+
89
+ def forward_pre_hook(
90
+ module: nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any]
91
+ ) -> None:
92
+ if checkpoint.state(module).enable_hook:
93
+
94
+ def context_fns():
95
+ if user_context_fns is not None:
96
+ ctx1, ctx2 = user_context_fns()
97
+ return ctx1, _no_hook(module, ctx2)
98
+ else:
99
+ return nullcontext(), _no_hook(module)
100
+
101
+ gen = _checkpoint_without_reentrant_generator(
102
+ module,
103
+ preserve_rng_state,
104
+ context_fns,
105
+ determinism_check,
106
+ debug,
107
+ early_stop,
108
+ *args,
109
+ **kwargs,
110
+ )
111
+ checkpoint.state(module)._ac_generator = gen
112
+ next(gen)
113
+
114
+ def forward_hook(module: nn.Module, inputs: tuple[Any, ...], output: Any) -> Any:
115
+ if checkpoint.state(module).enable_hook:
116
+ try:
117
+ gen = checkpoint.state(module)._ac_generator
118
+ assert gen is not None
119
+ next(gen)
120
+ except StopIteration:
121
+ pass
122
+ else:
123
+ raise RuntimeError(
124
+ "Expected non-reentrant activation checkpoint generator to be exhausted, but it was not!"
125
+ )
126
+
127
+ # Ensure that we no longer hold on to the generator. always_call=True helps ensure we
128
+ # clear this even in the case of exception in fwd pass.
129
+ checkpoint.state(module)._ac_generator = None
130
+
131
+ checkpoint.state(module).enable_hook = True
132
+ module.register_forward_pre_hook(forward_pre_hook, with_kwargs=True)
133
+ module.register_forward_hook(forward_hook, prepend=True, always_call=True)
134
+ return module
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/contract.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import uuid
3
+ from collections import OrderedDict
4
+ from collections.abc import Callable
5
+ from functools import wraps
6
+ from typing import Concatenate, Generic, Protocol
7
+ from typing_extensions import ParamSpec, TypeVar
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from torch.distributed._composable_state import _State
12
+ from torch.distributed.utils import _get_root_modules
13
+
14
+
15
+ _T = TypeVar("_T", covariant=True)
16
+ _P = ParamSpec("_P")
17
+
18
+
19
+ def generate_state_key(string="__composable_api_state_key"):
20
+ return f"{string}_{str(uuid.uuid4())}"
21
+
22
+
23
+ STATE_KEY = generate_state_key()
24
+ REGISTRY_KEY = generate_state_key()
25
+
26
+
27
+ # TODO: we can add additional info to RegistryItem to share across APIs. E.g.,
28
+ # we can add args and kwargs here, and then we can detect whether fully_shard
29
+ # is combined with reentrant activation checkpointing and error out with a clear
30
+ # message.
31
+ class RegistryItem:
32
+ pass
33
+
34
+
35
+ _TState = TypeVar("_TState", bound="_State", covariant=True)
36
+ _M = TypeVar("_M", nn.Module, list[nn.Module])
37
+
38
+
39
+ class _ContractFn(Protocol, Generic[_P, _T, _TState]):
40
+ def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _T: ...
41
+
42
+ def state(self, module: nn.Module) -> _TState: ...
43
+
44
+
45
+ def contract(
46
+ state_cls: type[_TState] = _State, # type: ignore[assignment]
47
+ ) -> Callable[
48
+ [Callable[Concatenate[_M, _P], _M]],
49
+ _ContractFn[Concatenate[_M, _P], _M, _TState],
50
+ ]:
51
+ r"""
52
+ Decorate a function as a composable distributed API, where the first
53
+ argument of the function must be an :class:`nn.Module` instance or sequence
54
+ of :class:`nn.Module` instances.
55
+
56
+ The decorator verifies that the decorated function does not modify
57
+ fully-qualified names (FQNs) for parameters, buffers, or modules. The
58
+ decorated function can return different module instances than the input
59
+ modules; the FQN invariant will be enforced following the input order.
60
+
61
+ When a function ``func`` is decorated by ``@contract()``, a
62
+ ``.state(module: nn.Module)`` method will be installed to the decorated
63
+ function. Then you can retrieve and modify the state on a module by calling
64
+ ``func.state(module)``.
65
+
66
+ Example::
67
+ >>> # xdoctest: +SKIP
68
+ >>> import torch.nn as nn
69
+ >>>
70
+ >>> class MyModel(nn.Module):
71
+ >>> def __init__(self) -> None:
72
+ >>> super().__init__()
73
+ >>> self.l1 = nn.Linear(10, 10)
74
+ >>> self.l2 = nn.Linear(10, 10)
75
+ >>>
76
+ >>> def forward(self, x):
77
+ >>> return self.l2(self.l1(x))
78
+ >>>
79
+ >>> @contract()
80
+ >>> def my_feature(module: nn.Module) -> nn.Module:
81
+ >>> my_feature.state(module).some_state = "any value"
82
+ >>> return module
83
+ >>>
84
+ >>> model = MyModel()
85
+ >>> my_feature(model.l1)
86
+ >>> assert my_feature.state(model.l1).some_state == "any value"
87
+ >>> my_feature(model.l2)
88
+ >>> model(torch.randn(2, 10)).sum().backward()
89
+ """
90
+
91
+ # wraps will make functions decorated with contract() pickleable - needed for integration with torch.package
92
+ @wraps(state_cls) # type: ignore[arg-type]
93
+ def inner(
94
+ func: Callable[Concatenate[_M, _P], _M],
95
+ ) -> _ContractFn[Concatenate[_M, _P], _M, _TState]:
96
+ @wraps(func)
97
+ def wrapper(
98
+ module: _M,
99
+ *args: _P.args,
100
+ **kwargs: _P.kwargs,
101
+ ) -> _M:
102
+ inp_module = module
103
+ modules: list[nn.Module]
104
+ if isinstance(module, nn.Module):
105
+ modules = [module]
106
+ else:
107
+ # If the user passes a sequence of modules, then we assume that
108
+ # we only need to insert the state object on the root modules
109
+ # (i.e. those without a parent) among the passed-in modules.
110
+ # pyrefly: ignore [no-matching-overload]
111
+ modules = _get_root_modules(list(module))
112
+ state = state_cls() # shared across all modules
113
+ registry_item = RegistryItem() # shared across all modules
114
+
115
+ # `func` is allowed to return different module instances than the
116
+ # input modules as long as FQNs are preserved following the input
117
+ # module order
118
+ all_orig_named_params: list[dict[str, nn.Parameter]] = []
119
+ all_orig_named_buffers: list[dict[str, torch.Tensor]] = []
120
+ all_orig_named_modules: list[dict[str, nn.Module]] = []
121
+
122
+ # pyrefly: ignore [bad-assignment]
123
+ for module in modules:
124
+ default_all_state: dict[Callable, _State] = OrderedDict()
125
+ default_registry: dict[str, RegistryItem] = OrderedDict()
126
+ all_state: dict[Callable, _State] = module.__dict__.setdefault( # type: ignore[call-overload]
127
+ STATE_KEY, default_all_state
128
+ )
129
+ if not isinstance(all_state, dict):
130
+ raise AssertionError(
131
+ f"Distributed composable API states corrupted: {all_state}"
132
+ )
133
+ registry: dict[str, RegistryItem] = module.__dict__.setdefault( # type: ignore[call-overload]
134
+ REGISTRY_KEY, default_registry
135
+ )
136
+ if not isinstance(registry, dict):
137
+ raise AssertionError(
138
+ f"Distributed composable API registry corrupted: {registry}"
139
+ )
140
+ if func in all_state or func.__name__ in registry:
141
+ raise AssertionError(
142
+ "Each distinct composable distributed API can only be applied to a "
143
+ f"module once. {func.__name__} has already been applied to the "
144
+ f"following module:\n{module}"
145
+ )
146
+ all_state.setdefault(func, state)
147
+ registry.setdefault(func.__name__, registry_item)
148
+
149
+ # pyrefly: ignore [missing-attribute]
150
+ all_orig_named_params.append(OrderedDict(module.named_parameters()))
151
+ # pyrefly: ignore [missing-attribute]
152
+ all_orig_named_buffers.append(OrderedDict(module.named_buffers()))
153
+ # pyrefly: ignore [missing-attribute]
154
+ all_orig_named_modules.append(OrderedDict(module.named_modules()))
155
+
156
+ updated = func(inp_module, *args, **kwargs)
157
+ if updated is None:
158
+ updated = inp_module # type: ignore[assignment]
159
+ updated_modules: list[nn.Module]
160
+ if isinstance(updated, nn.Module):
161
+ updated_modules = [updated]
162
+ else:
163
+ updated_modules = _get_root_modules(list(inp_module)) # type: ignore[arg-type, call-overload]
164
+
165
+ all_new_named_params: list[dict[str, nn.Parameter]] = []
166
+ all_new_named_buffers: list[dict[str, torch.Tensor]] = []
167
+ all_new_named_modules: list[dict[str, nn.Module]] = []
168
+ # pyrefly: ignore [bad-assignment]
169
+ for module in updated_modules:
170
+ # pyrefly: ignore [missing-attribute]
171
+ all_new_named_params.append(OrderedDict(module.named_parameters()))
172
+ # pyrefly: ignore [missing-attribute]
173
+ all_new_named_buffers.append(OrderedDict(module.named_buffers()))
174
+ # pyrefly: ignore [missing-attribute]
175
+ all_new_named_modules.append(OrderedDict(module.named_modules()))
176
+
177
+ num_orig_modules = len(all_orig_named_modules)
178
+ num_new_modules = len(all_new_named_modules)
179
+ if num_orig_modules != num_new_modules:
180
+ raise AssertionError(
181
+ f"{func.__name__} should return the same number of modules as input modules"
182
+ f"Inputs: {num_orig_modules} modules\n"
183
+ f"Outputs: {num_new_modules} modules"
184
+ )
185
+
186
+ def check_fqn(orig_fqns: list[str], new_fqns: list[str], check_key: str):
187
+ if orig_fqns == new_fqns:
188
+ return
189
+
190
+ orig_fqn_set, new_fqn_set = set(orig_fqns), set(new_fqns)
191
+ orig_only = orig_fqn_set - new_fqn_set
192
+ new_only = new_fqn_set - orig_fqn_set
193
+ if len(orig_only) or len(new_only):
194
+ raise RuntimeError(
195
+ f"{check_key}"
196
+ "Composable distributed API implementations cannot modify FQNs.\n"
197
+ f"FQNs only in original: {orig_only}\n"
198
+ f"FQNs only in new: {new_only}"
199
+ )
200
+ else:
201
+ raise RuntimeError(
202
+ f"{check_key}"
203
+ "Composable distributed API implementations cannot modify "
204
+ "the order of FQNs.\n"
205
+ f"Original FQNs: {orig_only}\n"
206
+ f"New FQNs: {new_only}"
207
+ )
208
+
209
+ for orig_named_params, new_named_params in zip(
210
+ all_orig_named_params, all_new_named_params
211
+ ):
212
+ check_fqn(
213
+ list(orig_named_params.keys()),
214
+ list(new_named_params.keys()),
215
+ "Checking parameters: ",
216
+ )
217
+ for orig_named_buffers, new_named_buffers in zip(
218
+ all_orig_named_buffers, all_new_named_buffers
219
+ ):
220
+ check_fqn(
221
+ list(orig_named_buffers.keys()),
222
+ list(new_named_buffers.keys()),
223
+ "Checking buffers: ",
224
+ )
225
+ for orig_named_modules, new_named_modules in zip(
226
+ all_orig_named_modules, all_new_named_modules
227
+ ):
228
+ check_fqn(
229
+ list(orig_named_modules.keys()),
230
+ list(new_named_modules.keys()),
231
+ "Checking modules: ",
232
+ )
233
+
234
+ # TODO: verify that installed distributed paradigms are compatible with
235
+ # each other.
236
+
237
+ # pyrefly: ignore [bad-return]
238
+ return updated
239
+
240
+ def get_state(module: nn.Module) -> _State:
241
+ return module.__dict__.setdefault( # type: ignore[call-overload]
242
+ STATE_KEY,
243
+ {}, # TODO(@yhcharles): this is a temporary fix, need a better way
244
+ ).get(func) # type: ignore[call-overload]
245
+
246
+ wrapper.state = get_state # type: ignore[attr-defined]
247
+
248
+ return wrapper # type: ignore[return-value]
249
+
250
+ return inner # type: ignore[return-value]
251
+
252
+
253
+ def _get_registry(module: nn.Module) -> dict[str, RegistryItem] | None:
254
+ r"""
255
+ Get an ``OrderedDict`` of composable APIs that have been applied to the
256
+ ``module``, indexed by the API name. If no API has been applied, then this
257
+ returns ``None``.
258
+ """
259
+ return getattr(module, REGISTRY_KEY, None)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/fsdp/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from torch.distributed.fsdp import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
2
+
3
+ from .fully_shard import FSDPModule, fully_shard, register_fsdp_forward_method
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/fsdp/fully_shard.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # TODO: For backward compatibility, we are importing the public objects
2
+ # originally from this file.
3
+ from torch.distributed.fsdp import ( # noqa: F401
4
+ FSDPModule,
5
+ fully_shard,
6
+ register_fsdp_forward_method,
7
+ UnshardHandle,
8
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/replicate.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import weakref
3
+ from collections.abc import Iterable
4
+ from typing import Any, NoReturn
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from torch.distributed._composable_state import _State
9
+ from torch.nn.parallel import DistributedDataParallel
10
+
11
+ from .contract import _get_registry, contract
12
+
13
+
14
+ _ROOT_MODULE_PREFIX = ""
15
+
16
+
17
+ class _ReplicateState(_State):
18
+ _ddp_weakref: weakref.ref
19
+
20
+ def __init__(self) -> None:
21
+ super().__init__()
22
+ self.module: nn.Module = nn.ParameterList()
23
+ self.has_initialized: bool = False
24
+ self._param_list: nn.ParameterList = nn.ParameterList()
25
+ # TODO(@fegin): this variable is originally create for testing, we
26
+ # should remove this if possible.
27
+ self._orig_module = self.module
28
+ self._param_names: list[str] = []
29
+ self._no_sync: bool = False
30
+ self._init_args: tuple[Any, ...] | None = None
31
+ self._init_kwargs: dict[str, Any] = {}
32
+ self._comm_hook_args: list[Any] = []
33
+
34
+ def _collect_params(
35
+ self,
36
+ module: nn.Module,
37
+ ignored_modules: set[nn.Module],
38
+ ignored_params: set[nn.Parameter],
39
+ prefix: str = _ROOT_MODULE_PREFIX,
40
+ ) -> None:
41
+ # skip if managed by fully_sharded API
42
+ if _is_fully_sharded(module):
43
+ return
44
+
45
+ # if a module is ignored, all descendants of the module are ignored.
46
+ if module in ignored_modules:
47
+ return
48
+
49
+ recurse_prefix = (
50
+ f"{prefix}." if prefix != _ROOT_MODULE_PREFIX else _ROOT_MODULE_PREFIX
51
+ )
52
+
53
+ for n, p in module.named_parameters(recurse=False):
54
+ if p not in ignored_params:
55
+ self._param_list.append(p)
56
+ self._param_names.append(f"{recurse_prefix}{n}")
57
+
58
+ for name, child_module in module.named_children():
59
+ self._collect_params(
60
+ child_module,
61
+ ignored_modules,
62
+ ignored_params,
63
+ prefix=f"{recurse_prefix}{name}",
64
+ )
65
+
66
+ def lazy_init(self) -> None:
67
+ @torch._disable_dynamo(recursive=True)
68
+ def _lazy_init():
69
+ assert self._init_args is not None
70
+ self.init(*self._init_args, **self._init_kwargs)
71
+ self.register_comm_hook()
72
+ self._init_args = ()
73
+ self._init_kwargs = {}
74
+
75
+ _lazy_init()
76
+
77
+ def init(
78
+ self,
79
+ module: nn.Module,
80
+ ignored_modules: set[nn.Module],
81
+ **kwargs,
82
+ ) -> None:
83
+ if self.has_initialized:
84
+ return
85
+
86
+ self.has_initialized = True
87
+ self.module = module
88
+ ignored_params = {p for m in ignored_modules for p in m.parameters()}
89
+ for submodule in module.modules():
90
+ if _is_fully_sharded(submodule):
91
+ ignored_params.update(submodule.parameters())
92
+ from torch.distributed.tensor.parallel.ddp import _localize_dtensor
93
+
94
+ _localize_dtensor(module, ignored_params=ignored_params)
95
+ self._collect_params(module, ignored_modules, ignored_params)
96
+
97
+ if "device_id" in kwargs:
98
+ # replicate() supports a small usability enhancement where
99
+ # user can pass in device_id as a Union[int, torch.device] even for
100
+ # CPU devices so users don't have to change code for CPU/GPU runs.
101
+ # We derive the right device_ids to feed into DDP to support this.
102
+ if kwargs["device_id"] is not None:
103
+ device_id = kwargs["device_id"]
104
+ # Convert to device_ids that DDP expects.
105
+ if isinstance(device_id, torch.device) and device_id.type == "cpu":
106
+ # CPU modules receive device_ids None
107
+ kwargs["device_ids"] = None
108
+ else:
109
+ # GPU modules expect device_ids=[cuda_device]
110
+ kwargs["device_ids"] = [device_id]
111
+ else:
112
+ kwargs["device_ids"] = None
113
+ kwargs.pop("device_id")
114
+
115
+ self._ddp = DistributedDataParallel(self._param_list, **kwargs)
116
+ # Weakref to the DDP instance is currently only used for testing.
117
+ replicate.state(self.module)._ddp_weakref = weakref.ref(self._ddp)
118
+
119
+ def register_comm_hook(self) -> None:
120
+ for comm_args, comm_kwargs in self._comm_hook_args:
121
+ self._ddp.register_comm_hook(*comm_args, **comm_kwargs)
122
+ self._comm_hook_args.clear()
123
+
124
+ def record_init_args(self, *args, **kwargs) -> None:
125
+ self._init_args = args
126
+ self._init_kwargs = kwargs
127
+
128
+ def forward_pre_hook(
129
+ self, module: nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any]
130
+ ) -> Any:
131
+ if self._init_args or self._init_kwargs:
132
+ self.lazy_init()
133
+ self._ddp.require_backward_grad_sync = not self._no_sync
134
+ return self._ddp._pre_forward(*args, **kwargs)
135
+
136
+ def forward_post_hook(
137
+ self,
138
+ module: nn.Module,
139
+ input: tuple[torch.Tensor],
140
+ output: torch.Tensor,
141
+ ) -> torch.Tensor:
142
+ return self._ddp._post_forward(output)
143
+
144
+
145
+ def unimplemented_deepcopy(*args: Any, **kwargs: Any) -> NoReturn:
146
+ raise AssertionError(
147
+ "DDP does not support deepcopy. Please use state dict for serialization."
148
+ )
149
+
150
+
151
+ # Follow the same pattern as FSDP/fully_shard
152
+ class DDP:
153
+ def __new__(cls, *args, **kwargs):
154
+ """
155
+ Override ``__new__`` to remove the DDP class and directly construct
156
+ the original class for cases like indexing into a container module.
157
+ """
158
+ # Use index 2 since 0 is the dynamically constructed `DDP<...>` class
159
+ # and index 1 is the `DDP` class itself
160
+ orig_cls = cls.__mro__[2]
161
+ return orig_cls.__new__(orig_cls, *args, **kwargs)
162
+
163
+ def set_requires_gradient_sync(self, requires_gradient_sync: bool) -> None:
164
+ """
165
+ Sets if the module should sync gradients. This can be used to implement
166
+ gradient accumulation without communication.
167
+
168
+ Args:
169
+ requires_gradient_sync (bool): Whether to reduce gradients for the
170
+ module's parameters.
171
+ """
172
+ replicate.state(self)._no_sync = not requires_gradient_sync # type: ignore[arg-type]
173
+
174
+ def register_comm_hook(self, *args, **kwargs) -> None:
175
+ replicate.state(self)._comm_hook_args.append((args, kwargs)) # type: ignore[arg-type]
176
+
177
+
178
+ @contract(state_cls=_ReplicateState)
179
+ def replicate(
180
+ module: nn.Module,
181
+ ignored_modules: Iterable[torch.nn.Module] | None = None,
182
+ **kwargs,
183
+ ) -> nn.Module:
184
+ r"""Replicates a module
185
+
186
+ Args:
187
+ module (torch.nn.Module): module to replicate
188
+
189
+ Example::
190
+ >>> # xdoctest: +REQUIRES(module:torch._C._distributed_c10d)
191
+ >>> module = nn.Linear(3, 3)
192
+ >>> replicate(module)
193
+ """
194
+ torch._C._log_api_usage_once("torch.distributed.replicate")
195
+
196
+ # TODO(fegin): using kwargs is not a good idea if we would like to make
197
+ # replicate a formal API to replace DDP.
198
+ if "device_id" in kwargs:
199
+ if not isinstance(kwargs["device_id"], (int, torch.device)):
200
+ raise RuntimeError(
201
+ "Expected device_id to be int or torch.device, "
202
+ f"but got {type(kwargs['device_id'])}"
203
+ )
204
+
205
+ if _is_fully_sharded(module):
206
+ raise RuntimeError(
207
+ "Cannot apply `replicate()` on a Module already managed by `fully_shard`"
208
+ )
209
+
210
+ if ignored_modules is None:
211
+ ignored_modules = {}
212
+ else:
213
+ ignored_modules = set(ignored_modules)
214
+
215
+ state = replicate.state(module)
216
+ module.register_forward_pre_hook(state.forward_pre_hook, with_kwargs=True)
217
+ device_mesh = kwargs.get("device_mesh")
218
+ if device_mesh is not None:
219
+ root_mesh = device_mesh._get_root_mesh()
220
+ # if a root mesh is not the same as device_mesh,
221
+ # meaning the device_mesh is sliced out from the root mesh.
222
+ if root_mesh != device_mesh:
223
+ # TODO: This is a temporary work around to enable DDP + TP.
224
+ # We should do the logic in DDP so that the 2D implementation is
225
+ # sound and the state_dict works out of the box.
226
+ #
227
+ # This won't conflict with what is done in DDP class as the module
228
+ # replicate is going to pass is NOT the original module.
229
+ from torch.distributed.tensor.parallel.ddp import (
230
+ _localize_dtensor,
231
+ _reconstruct_dtensor,
232
+ )
233
+
234
+ module.register_forward_pre_hook(_reconstruct_dtensor)
235
+ module.register_forward_hook(_localize_dtensor)
236
+
237
+ module.register_forward_hook(state.forward_post_hook) # type: ignore[arg-type]
238
+
239
+ state.record_init_args(module, ignored_modules, **kwargs)
240
+
241
+ # Place DDP leftmost for highest priority in the method resolution order
242
+ cls = module.__class__
243
+ dct = {"__deepcopy__": unimplemented_deepcopy}
244
+ new_cls = type(f"DDP{cls.__name__}", (DDP, cls), dct)
245
+ module.__class__ = new_cls
246
+ return module
247
+
248
+
249
+ def _is_fully_sharded(module: nn.Module) -> bool:
250
+ r"""Check if module is marked with fully_shard."""
251
+ registry = _get_registry(module)
252
+ if registry is None:
253
+ return False
254
+ return "fully_shard" in registry
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable/replicate_with_fsdp.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ from typing import overload
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+ import torch.nn as nn
10
+ from torch.distributed._composable_state import _get_module_state, _insert_module_state
11
+ from torch.distributed.device_mesh import _get_device_handle
12
+ from torch.distributed.fsdp._fully_shard._fsdp_api import (
13
+ MixedPrecisionPolicy,
14
+ OffloadPolicy,
15
+ )
16
+ from torch.distributed.fsdp._fully_shard._fsdp_common import (
17
+ DDPMeshInfo,
18
+ detect_compiled_autograd,
19
+ )
20
+ from torch.distributed.fsdp._fully_shard._fsdp_init import (
21
+ _get_device_from_mesh,
22
+ _get_managed_states,
23
+ _init_default_fully_shard_mesh,
24
+ _move_states_to_device,
25
+ )
26
+ from torch.distributed.fsdp._fully_shard._fsdp_param_group import FSDPParamGroup
27
+ from torch.distributed.fsdp._fully_shard._fsdp_state import (
28
+ _register_group_forward_hooks,
29
+ FSDPState,
30
+ )
31
+ from torch.distributed.fsdp._fully_shard._fully_shard import (
32
+ _unimplemented_deepcopy,
33
+ FSDPModule,
34
+ )
35
+ from torch.distributed.tensor import DeviceMesh, init_device_mesh
36
+ from torch.distributed.utils import _get_root_modules
37
+
38
+ from .contract import _get_registry, contract
39
+
40
+
41
+ cls_to_replicate_cls: dict[type, type] = {}
42
+
43
+ _ROOT_MODULE_PREFIX = ""
44
+
45
+ logger = logging.getLogger("torch.distributed._composable.replicate_with_fsdp")
46
+
47
+
48
+ class _ReplicateStateContext:
49
+ """This has state shared across Replicate states."""
50
+
51
+ def __init__(self) -> None:
52
+ # All Replicate states in the root state's module tree
53
+ self.all_states: list[_ReplicateState] = []
54
+ # Iteration's forward root runs the once-per-forward logic; this root
55
+ # may not be the overall root set by lazy initialization in cases where
56
+ # only a submodule runs forward (e.g. encoder-only for eval)
57
+ self.iter_forward_root: _ReplicateState | None = None
58
+ # Final callback should only be queued once per backward
59
+ self.post_backward_final_callback_queued: bool = False
60
+ # Whether to finalize backward in this backward's final callback
61
+ self.is_last_backward: bool = True
62
+ # Optional user-provided event recorded after optimizer for the
63
+ # all-gather streams to wait on in the root pre-forward
64
+ self.post_optim_event: torch.Event | None = None
65
+
66
+
67
+ def _get_module_replicate_state(module: nn.Module) -> _ReplicateState | None:
68
+ """Checks if module state is ReplicateState"""
69
+ state = _get_module_state(module)
70
+ if isinstance(state, _ReplicateState):
71
+ return state
72
+ return None
73
+
74
+
75
+ class _ReplicateState(FSDPState):
76
+ """
77
+ Replicate state functionality is adapted from FSDP state.
78
+ In the future, could experiment with inheriting from it instead.
79
+ """
80
+
81
+ def __init__(self) -> None:
82
+ super().__init__()
83
+ self._state_ctx = _ReplicateStateContext() # type: ignore[assignment]
84
+
85
+ # Define a separate init since `__init__` is called in the contract
86
+ def init(
87
+ self,
88
+ modules: tuple[nn.Module, ...],
89
+ device: torch.device,
90
+ mp_policy: MixedPrecisionPolicy,
91
+ auto_reshard_after_forward: bool = False,
92
+ ) -> None:
93
+ for module in modules:
94
+ _insert_module_state(module, self)
95
+ self._modules = modules
96
+ # pyrefly: ignore [read-only]
97
+ self._device = device
98
+ self._device_handle = _get_device_handle(device.type)
99
+ self._mp_policy = mp_policy
100
+ self._auto_reshard_after_forward = auto_reshard_after_forward
101
+ if len(modules) == 1:
102
+ self._pre_forward_hook_handle = modules[0].register_forward_pre_hook(
103
+ self._pre_forward, prepend=True, with_kwargs=True
104
+ )
105
+ self._post_forward_hook_handle = modules[0].register_forward_hook(
106
+ self._post_forward, prepend=False
107
+ )
108
+ else:
109
+ hook_handle = _register_group_forward_hooks(
110
+ modules,
111
+ self._pre_forward,
112
+ self._post_forward,
113
+ self._modules_to_run_forward,
114
+ )
115
+ self._pre_forward_hook_handle = hook_handle
116
+ self._post_forward_hook_handle = hook_handle
117
+
118
+ def _lazy_init(self) -> None:
119
+ """
120
+ Lazy initialization represents when all modules' parallelisms have
121
+ finalized (e.g. Replicate has been applied to all desired modules). This
122
+ means that we can determine which state is the root, and we do so by
123
+ the 1st state to run forward.
124
+ """
125
+ if self._is_root is not None:
126
+ return # no-op: already initialized
127
+ self._is_root = True
128
+ if len(self._modules) > 1:
129
+ raise RuntimeError(
130
+ f"Replicate requires a single root module but got {self._modules}"
131
+ )
132
+ detect_compiled_autograd()
133
+ root_module = self._modules[0]
134
+ visited_states: set[_ReplicateState] = set()
135
+ for module_name, module in root_module.named_modules():
136
+ if (state := _get_module_replicate_state(module)) is None:
137
+ continue
138
+ if module is not root_module:
139
+ if state not in visited_states and state._is_root is not None:
140
+ raise RuntimeError(
141
+ "Replicate state has already been lazily initialized for "
142
+ f"{module_name}\nReplicate requires running forward through "
143
+ "the root module first"
144
+ )
145
+ state._is_root = False
146
+ self._state_ctx.all_states.append(state)
147
+ # pyrefly: ignore [bad-argument-type]
148
+ visited_states.add(state)
149
+ if self._fsdp_param_group and self._auto_reshard_after_forward:
150
+ # For the root, do not reshard after forward since for training,
151
+ # the parameters would be freed and all-gathered immediately
152
+ self._fsdp_param_group.post_forward_mesh_info = None
153
+ self._init_fqns()
154
+ self._init_shared_state()
155
+ # Run parameter group lazy inits after initializing FQNs for improved
156
+ # error messages
157
+ for state in self._state_ctx.all_states: # type: ignore[assignment]
158
+ if state._fsdp_param_group: # type: ignore[union-attr]
159
+ state._fsdp_param_group.lazy_init() # type: ignore[union-attr]
160
+
161
+
162
+ def replicate_impl(
163
+ module,
164
+ mesh: DeviceMesh,
165
+ *,
166
+ device_id: int | torch.device | None = None,
167
+ mp_policy: MixedPrecisionPolicy = MixedPrecisionPolicy(),
168
+ offload_policy: OffloadPolicy = OffloadPolicy(),
169
+ ignored_params: set[nn.Parameter] | None = None,
170
+ ):
171
+ torch._C._log_api_usage_once("torch.distributed._composable.replicate_with_fsdp")
172
+ if isinstance(module, (nn.ModuleList, nn.ModuleDict)):
173
+ raise ValueError(
174
+ f"replicate does not support containers that do not implement forward: {module}"
175
+ )
176
+
177
+ mesh = mesh or _init_default_fully_shard_mesh()
178
+ if mesh.ndim != 1:
179
+ raise ValueError(f"replicate expects a 1D DeviceMesh but got {mesh}")
180
+
181
+ else:
182
+ if mesh.mesh_dim_names is None:
183
+ raise AssertionError(
184
+ "Please init the 2D mesh for HSDP with mesh_dim_names specified"
185
+ )
186
+ mesh_info = DDPMeshInfo(mesh, replicate_mesh_dim=0)
187
+ device = _get_device_from_mesh(mesh)
188
+
189
+ post_forward_mesh_info = None
190
+
191
+ arg_module = module
192
+ modules = (
193
+ (module,) if isinstance(module, nn.Module) else tuple(_get_root_modules(module))
194
+ )
195
+ state = replicate.state(modules[0]) # type: ignore[attr-defined] # see [1]
196
+ state.init(modules, device, mp_policy)
197
+
198
+ managed_modules = _get_managed_modules(modules, ignored_params)
199
+ params, buffers = _get_managed_states(managed_modules, ignored_params)
200
+
201
+ _move_states_to_device(params, buffers, device)
202
+ if params:
203
+ state._fsdp_param_group = FSDPParamGroup(
204
+ params,
205
+ modules,
206
+ mesh_info, # type: ignore[arg-type]
207
+ post_forward_mesh_info,
208
+ device,
209
+ None,
210
+ mp_policy,
211
+ offload_policy,
212
+ )
213
+
214
+ # Place Replicate leftmost for highest priority in the method resolution order
215
+ for module in modules:
216
+ cls = module.__class__
217
+ new_cls = cls_to_replicate_cls.get(cls)
218
+ if not new_cls:
219
+ dct = {"__deepcopy__": _unimplemented_deepcopy}
220
+ new_cls = type(f"Replicate{cls.__name__}", (ReplicateModule, cls), dct)
221
+ cls_to_replicate_cls[cls] = new_cls
222
+ module.__class__ = new_cls
223
+ return arg_module
224
+
225
+
226
+ @overload
227
+ # pyrefly: ignore [inconsistent-overload]
228
+ def replicate(
229
+ module: nn.Module,
230
+ *,
231
+ mesh: DeviceMesh | None = ...,
232
+ mp_policy: MixedPrecisionPolicy = ...,
233
+ offload_policy: OffloadPolicy = ...,
234
+ ignored_params: set[nn.Parameter] | None = ...,
235
+ ) -> ReplicateModule: ...
236
+
237
+
238
+ @overload
239
+ # pyrefly: ignore [inconsistent-overload]
240
+ def replicate(
241
+ module: list[nn.Module],
242
+ *,
243
+ mesh: DeviceMesh | None = ...,
244
+ mp_policy: MixedPrecisionPolicy = ...,
245
+ offload_policy: OffloadPolicy = ...,
246
+ ignored_params: set[nn.Parameter] | None = ...,
247
+ ) -> list[ReplicateModule]: ...
248
+
249
+
250
+ @contract(state_cls=_ReplicateState) # type: ignore[misc]
251
+ def replicate(
252
+ module: nn.Module,
253
+ *,
254
+ mesh: DeviceMesh | None = None,
255
+ mp_policy: MixedPrecisionPolicy = MixedPrecisionPolicy(),
256
+ offload_policy: OffloadPolicy = OffloadPolicy(),
257
+ ignored_params: set[nn.Parameter] | None = None,
258
+ ):
259
+ r"""Replicates a module
260
+
261
+ Args:
262
+ module (torch.nn.Module): module to replicate
263
+
264
+ Example::
265
+ >>> # xdoctest: +REQUIRES(module:torch._C._distributed_c10d)
266
+ >>> module = nn.Linear(3, 3)
267
+ >>> replicate(module)
268
+ """
269
+
270
+ if not is_composable_with_replicate(module):
271
+ raise RuntimeError(
272
+ "Cannot apply `replicate()` on a Module already managed by `fully_shard`"
273
+ )
274
+
275
+ if mesh is None:
276
+ mesh = replicate_mesh()
277
+
278
+ return replicate_impl(
279
+ module,
280
+ mesh,
281
+ mp_policy=mp_policy,
282
+ offload_policy=offload_policy,
283
+ ignored_params=ignored_params,
284
+ )
285
+
286
+
287
+ class ReplicateModule(FSDPModule):
288
+ def __new__(cls, *args, **kwargs):
289
+ """
290
+ Override ``__new__`` to remove the FSDP class and directly construct
291
+ the original class for cases like indexing into a container module.
292
+ """
293
+ # Use index 2 since 0 is the dynamically constructed `FSDP<...>` class
294
+ # and index 1 is the `FSDPModule` class itself
295
+ orig_cls = cls.__mro__[3]
296
+ self = orig_cls.__new__(orig_cls, *args, **kwargs)
297
+ self.__init__(*args, **kwargs)
298
+ return self
299
+
300
+
301
+ def _get_managed_modules(
302
+ root_modules: tuple[nn.Module, ...],
303
+ ignored_params: set[nn.Parameter] | None = None,
304
+ ) -> list[nn.Module]:
305
+ modules: list[nn.Module] = []
306
+ root_modules_set = set(root_modules)
307
+ # Track visisted modules to avoid visiting shared modules multiple times
308
+ visited_modules: set[nn.Module] = set()
309
+
310
+ def dfs(module: nn.Module) -> None:
311
+ """
312
+ Runs a DFS to collect managed modules, not recursing into modules with
313
+ a non-composable API or ``replicate`` already applied.
314
+ """
315
+ if not is_composable_with_replicate(module):
316
+ return
317
+ elif (
318
+ module not in root_modules_set
319
+ and _get_module_replicate_state(module) is not None
320
+ ):
321
+ return # nested `fully_shard` module
322
+ visited_modules.add(module)
323
+ for submodule in module.children():
324
+ if submodule not in visited_modules:
325
+ dfs(submodule)
326
+ modules.append(module)
327
+
328
+ for root_module in root_modules:
329
+ dfs(root_module)
330
+
331
+ if ignored_params is None:
332
+ return modules
333
+
334
+ adjusted_modules = _adjust_managed_modules(modules, ignored_params)
335
+ return adjusted_modules
336
+
337
+
338
+ def is_composable_with_replicate(module: nn.Module) -> bool:
339
+ """Checks if replicate can be applied with module"""
340
+ registry = _get_registry(module)
341
+ if registry is None:
342
+ return True
343
+ # Registry keys by function name
344
+ return "fully_shard" not in registry
345
+
346
+
347
+ def replicate_mesh():
348
+ """Creates a device mesh for replicate if the user doesn't provide one"""
349
+ if not dist.distributed_c10d.is_initialized():
350
+ dist.distributed_c10d.init_process_group()
351
+ default_pg = dist.distributed_c10d._get_default_group()
352
+ device = torch._C._get_accelerator()
353
+ mesh = init_device_mesh(
354
+ device.type,
355
+ mesh_shape=(default_pg.size(),),
356
+ mesh_dim_names=("replicate",),
357
+ )
358
+ return mesh
359
+
360
+
361
+ def _adjust_managed_modules(
362
+ modules: list[nn.Module], ignored_params: set[nn.Parameter]
363
+ ) -> list[nn.Module]:
364
+ """
365
+ Adjust the given list of managed modules by removing those with all parameters ignored.
366
+ """
367
+ ignore_decision: dict[nn.Module, bool] = {}
368
+ new_modules = []
369
+ for module in modules:
370
+ ignored = _ignore_module(module, ignored_params, ignore_decision)
371
+ if not ignored:
372
+ new_modules.append(module)
373
+ return new_modules
374
+
375
+
376
+ def _ignore_module(
377
+ module: nn.Module,
378
+ ignored_params: set[nn.Parameter],
379
+ ignore_decision: dict[nn.Module, bool],
380
+ ) -> bool:
381
+ """
382
+ Decide if it is safe to ignore a module for applying replicate.
383
+ """
384
+ if module in ignore_decision:
385
+ return ignore_decision[module]
386
+
387
+ if len(list(module.buffers(recurse=False))) > 0:
388
+ # Cannot ignore a module with any buffer
389
+ ignore_decision[module] = False
390
+ return False
391
+
392
+ for _, param in module.named_parameters(recurse=False):
393
+ if param not in ignored_params:
394
+ # at least one param is not ignored. So this module shouldn't be.
395
+ ignore_decision[module] = False
396
+ return False
397
+
398
+ # Need to consider descendants of module
399
+ for child in list(module.children()):
400
+ ignore_child = _ignore_module(child, ignored_params, ignore_decision)
401
+ if not ignore_child:
402
+ # Cannot ignore module if one of its children is not ignored
403
+ ignore_decision[module] = False
404
+ return False
405
+
406
+ # Safe to ignore module
407
+ ignore_decision[module] = True
408
+ return True
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_composable_state.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import weakref
2
+ from typing import cast
3
+
4
+ import torch.nn as nn
5
+
6
+
7
+ class _State:
8
+ pass
9
+
10
+
11
+ _module_state_mapping: weakref.WeakKeyDictionary[
12
+ nn.Module, weakref.ReferenceType[_State]
13
+ ] = weakref.WeakKeyDictionary()
14
+
15
+
16
+ def _insert_module_state(module: nn.Module, state: _State) -> None:
17
+ global _module_state_mapping
18
+ if module in _module_state_mapping:
19
+ raise AssertionError(f"Inserting {module} more than once.")
20
+ _module_state_mapping[module] = weakref.ref(state)
21
+
22
+
23
+ def _get_module_state(module: nn.Module) -> _State | None:
24
+ """
25
+ Return the ``_State`` in ``model``.
26
+
27
+ Given a ``module``, this API finds out if the module is also a ``_State``
28
+ instance or if the module is managed by a composable API. If the module
29
+ is also a ``_State``, ``module`` will be casted to ``_State` and returned.
30
+ If it is managed by a composable API, the corresponding ``_State`` will
31
+ be returned.
32
+ """
33
+ global _module_state_mapping
34
+ if isinstance(module, _State):
35
+ # pyrefly: ignore [redundant-cast]
36
+ return cast(_State, module)
37
+ else:
38
+ # https://github.com/pytorch/pytorch/issues/107054
39
+ if module in _module_state_mapping:
40
+ state_ref = _module_state_mapping[module]
41
+ state = state_ref()
42
+ if state is None:
43
+ raise AssertionError("State has already been garbage collected")
44
+ return state
45
+ else:
46
+ return None
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_dist2.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This is an experimental new API for PyTorch Distributed. This is actively in development and subject to change or deletion entirely.
3
+
4
+ This is intended as a proving ground for more flexible and object oriented distributed APIs.
5
+ """
6
+
7
+ from collections.abc import Generator
8
+ from contextlib import contextmanager
9
+ from datetime import timedelta
10
+ from typing import Protocol
11
+
12
+ import torch
13
+ from torch._C._distributed_c10d import (
14
+ _current_process_group,
15
+ _set_process_group,
16
+ ProcessGroup,
17
+ ReduceOp,
18
+ Store,
19
+ )
20
+ from torch.distributed.rendezvous import rendezvous
21
+
22
+
23
+ _BACKENDS: dict[str, "ProcessGroupFactory"] = {}
24
+
25
+ __all__ = [
26
+ "ProcessGroup",
27
+ "ReduceOp",
28
+ "ProcessGroupFactory",
29
+ "register_backend",
30
+ "new_group",
31
+ "current_process_group",
32
+ "process_group",
33
+ ]
34
+
35
+
36
+ class ProcessGroupFactory(Protocol):
37
+ """Protocol for process group factories."""
38
+
39
+ def __call__(
40
+ self,
41
+ store: Store,
42
+ rank: int,
43
+ world_size: int,
44
+ timeout: timedelta,
45
+ device: torch.device,
46
+ **kwargs: object,
47
+ ) -> ProcessGroup: ...
48
+
49
+
50
+ def register_backend(name: str, func: ProcessGroupFactory) -> None:
51
+ """
52
+ Register a new process group backend.
53
+
54
+ Args:
55
+ name: The name of the backend.
56
+ func: The function to create the process group.
57
+ """
58
+ if name in _BACKENDS:
59
+ raise ValueError(f"Backend {name} already registered")
60
+
61
+ _BACKENDS[name] = func
62
+
63
+
64
+ def _gloo_factory(
65
+ store: Store,
66
+ rank: int,
67
+ world_size: int,
68
+ timeout: timedelta,
69
+ device: torch.device,
70
+ **kwargs: object,
71
+ ) -> ProcessGroup:
72
+ from torch.distributed import ProcessGroupGloo
73
+
74
+ if len(kwargs) != 0:
75
+ raise AssertionError("Gloo backend received unexpected kwargs")
76
+
77
+ backend_class = ProcessGroupGloo(store, rank, world_size, timeout)
78
+ backend_class._set_sequence_number_for_group()
79
+
80
+ pg = ProcessGroup(store, rank, world_size)
81
+ pg._set_default_backend(ProcessGroup.BackendType.GLOO)
82
+
83
+ # register devices
84
+ pg._register_backend(device, ProcessGroup.BackendType.GLOO, backend_class)
85
+ pg._register_backend(
86
+ torch.device("cpu"), ProcessGroup.BackendType.GLOO, backend_class
87
+ )
88
+ if torch.cuda.is_available():
89
+ pg._register_backend(
90
+ torch.device("cuda"), ProcessGroup.BackendType.GLOO, backend_class
91
+ )
92
+ return pg
93
+
94
+
95
+ def _nccl_factory(
96
+ store: Store,
97
+ rank: int,
98
+ world_size: int,
99
+ timeout: timedelta,
100
+ device: torch.device,
101
+ **kwargs: object,
102
+ ) -> ProcessGroup:
103
+ from torch.distributed import ProcessGroupNCCL
104
+
105
+ opts = ProcessGroupNCCL.Options()
106
+ opts._timeout = timeout
107
+ for k, v in kwargs.items():
108
+ if not hasattr(opts, k):
109
+ raise KeyError(f"Unknown option {k}")
110
+ setattr(opts, k, v)
111
+
112
+ backend_class = ProcessGroupNCCL(store, rank, world_size, opts)
113
+ backend_class._set_sequence_number_for_group()
114
+ backend_class.eager_connect_single_device(device)
115
+
116
+ pg = ProcessGroup(store, rank, world_size)
117
+ pg._set_default_backend(ProcessGroup.BackendType.NCCL)
118
+ pg._register_backend(device, ProcessGroup.BackendType.NCCL, backend_class)
119
+
120
+ return pg
121
+
122
+
123
+ register_backend("gloo", _gloo_factory)
124
+ register_backend("nccl", _nccl_factory)
125
+
126
+
127
+ def new_group(
128
+ backend: str,
129
+ timeout: timedelta,
130
+ device: str | torch.device,
131
+ **kwargs: object,
132
+ ) -> ProcessGroup:
133
+ """
134
+ Create a new process group with the given backend and options. This group is
135
+ independent and will not be globally registered and thus not usable via the
136
+ standard torch.distributed.* APIs.
137
+
138
+ Args:
139
+ backend: The backend to use for the process group.
140
+ timeout: The timeout for collective operations.
141
+ device: The device to use for the process group.
142
+ **kwargs: All remaining arguments are passed to the backend constructor.
143
+ See the backend specific documentation for details.
144
+
145
+ Returns:
146
+ A new process group.
147
+ """
148
+ if backend not in _BACKENDS:
149
+ raise ValueError(f"Backend {backend} not registered")
150
+
151
+ device = torch.device(device)
152
+
153
+ store, rank, world_size = next(iter(rendezvous("env://")))
154
+ store.set_timeout(timeout)
155
+
156
+ return _BACKENDS[backend](store, rank, world_size, timeout, device, **kwargs)
157
+
158
+
159
+ def current_process_group() -> ProcessGroup:
160
+ """
161
+ Get the current process group. Thread local method.
162
+
163
+ Returns:
164
+ The current process group.
165
+ """
166
+ return _current_process_group()
167
+
168
+
169
+ @contextmanager
170
+ def process_group(pg: ProcessGroup) -> Generator[None, None, None]:
171
+ """
172
+ Context manager for process groups. Thread local method.
173
+
174
+ Args:
175
+ pg: The process group to use.
176
+ """
177
+ prev_pg = current_process_group()
178
+
179
+ _set_process_group(pg)
180
+ try:
181
+ yield
182
+ finally:
183
+ _set_process_group(prev_pg)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_functional_collectives.py ADDED
@@ -0,0 +1,1251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import sys
4
+ import warnings
5
+ from typing import Any, cast, TYPE_CHECKING, Union
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+ import torch.distributed.distributed_c10d as c10d
10
+ from torch.distributed.device_mesh import DeviceMesh
11
+ from torch.fx.experimental.proxy_tensor import get_proxy_mode
12
+
13
+ from . import _functional_collectives_impl as fun_col_impl
14
+
15
+
16
+ try:
17
+ from torch.utils._cxx_pytree import tree_map_only
18
+ except ImportError:
19
+ from torch.utils._pytree import tree_map_only # type: ignore[no-redef]
20
+
21
+
22
+ try:
23
+ from torch.compiler import is_dynamo_compiling as is_torchdynamo_compiling
24
+ except Exception:
25
+ warnings.warn(
26
+ "Unable to import torchdynamo util `is_torchdynamo_compiling`, so won't support torchdynamo correctly",
27
+ stacklevel=2,
28
+ )
29
+
30
+ def is_torchdynamo_compiling(): # type: ignore[misc]
31
+ return False
32
+ return False
33
+
34
+
35
+ """
36
+ New traceable, functional collectives.
37
+ RFC: https://github.com/pytorch/pytorch/issues/93173
38
+
39
+ compiler: trace these ops with plain-old-data schemas, then choose how to lower them.
40
+ eager: execute these 'functional' ops which in eager return AsyncCollectiveTensor subclasses,
41
+ automatically calling .wait() on underlying/hidden async 'work' obj only when fed to
42
+ a downstream op.
43
+
44
+ Issues:
45
+ * Where should these ops live? Couldn't `import torch` if putting these ops in existing torch.distributed files
46
+ * Proper support for eager requires inplace ops. We should explore having it as an option for the API.
47
+ """
48
+
49
+ """
50
+ Functional collectives are asynchronous only and we perform implicit stream synchronization
51
+ on behalf of the user.
52
+
53
+ We use AsyncCollectiveTensor to wrap the result tensor of a collective and it lets us witness
54
+ first usage of the tensor and insert cross stream sync at the right place.
55
+
56
+ The above are the easy bits, the hard one is how we match the Work object returned by
57
+ c10d and the tensor AsyncCollectiveTensor wraps. We alloc the tensor inside the collective
58
+ op implementation (see ``clone()`` call in ``_all_reduce``) and then it's handled by the
59
+ dispatcher which might call other implementations that are allowed to change the returned
60
+ tensor - even return a tensor with a different shape (see ``torch.vmap``).
61
+
62
+ This means the caller of our ops receives a Tensor that is not guaranteed to be the same
63
+ allocated by our implementations and that makes pairing The AsyncTensor to the original
64
+ tensor a lot harder. This pairing is needed so we can lookup the Work object to use.
65
+
66
+ Originally, we tried WeakKeyDictionary to map from Tensor to Work, but because Tensor's
67
+ identity is not stable across dispatch, the op caller would end up with a different Tensor
68
+ instance that would not match any in the dictionary.
69
+
70
+ With Tensor identity out of the question, we decided use the tensor data pointer, which
71
+ should be stable across all the Tensor changes done during dispatch.
72
+
73
+ We have a dictionary of tensor::data_ptr -> Work that we insert right after we call into c10d.
74
+
75
+ We use this dictionary when AsyncCollectiveTensor is used to invoke Work::wait()
76
+
77
+ Finally, we setup a finalizer against the tensor wrapper to observe it getting collected so we
78
+ can clean up stale entries in the dictionary.
79
+
80
+ To eliminate the possibility of races we have a global version counter that is used by the finalizer.
81
+
82
+ As a wise man said once: Don't cross the streams (https://www.youtube.com/watch?v=wyKQe_i9yyo)
83
+
84
+ """
85
+
86
+ """
87
+ Functional collectives can accept any of these types to describe the ranks participating in collectives.
88
+
89
+ The different types will be desugared to a canonical format
90
+ """
91
+ RANK_TYPES = Union[
92
+ list[int],
93
+ list[list[int]],
94
+ dist.ProcessGroup,
95
+ DeviceMesh,
96
+ tuple["dist.tensor.DeviceMesh", int],
97
+ c10d.GroupName,
98
+ ]
99
+
100
+
101
+ """
102
+ User facing APIs for functional collectives
103
+ -------------------------------------------
104
+
105
+ These apis are called by user code and expected to work both in eager execution and compilation,
106
+ but there are significant differences to how the two modes are implemented underneath.
107
+
108
+ Eager execution is 'optimized' using a tensor subclass that schedules the synchronization (via wait_tensor() op)
109
+ just before the tensor is first used. Compiled tracing currently relies on the compiler to perform this optimization,
110
+ and cannot yet correctly trace the AsyncTensor wrapper class. In the future, these paths may be unified
111
+ if sufficient subclass support is added in dynamo.
112
+
113
+ Example: all_reduce is an entrypoint API, and other collectives follow a similar pattern.
114
+
115
+ Here's how it works under torch.compile/dynamo:
116
+ all_reduce(...)
117
+ |--> _expand_group(...) - desugars processgroup into canonical/traceable format
118
+ |--> c10d_functional.all_reduce(...) - dynamo captures this op call, doesn't trace deeper
119
+ |--> _maybe_wrap_tensor(...) - wait_tensor() op is immediately called, no AsyncTensor subclass needed
120
+
121
+ And under eager execution:
122
+ all_reduce(...)
123
+ |--> _expand_group(...) - same as above, but less critical for eager
124
+ |--> c10d_functional.all_reduce(...) - dispatches to real kernel OR records op in trace
125
+ |--> _maybe_wrap_tensor(...) - AsyncTensor wrapper applied to returned tensor,
126
+ which issues wait_tensor() at the time of first use
127
+ """
128
+
129
+
130
+ def wait_tensor(tensor):
131
+ """
132
+ Wait on a tensor returned by the collectives ops.
133
+
134
+ Waiting follows device semantics, which means blocking on CPU and synchronizing streams on CUDA.
135
+ """
136
+ return torch.ops._c10d_functional.wait_tensor(tensor) # type: ignore[attr-defined]
137
+
138
+
139
+ def broadcast(self: torch.Tensor, src: int, group: RANK_TYPES, tag: str = ""):
140
+ """
141
+ Broadcasts the tensor to all processes in the given process group.
142
+
143
+ Args:
144
+ src (int): Source rank
145
+ group (ProcessGroup or List[int]): The process group to work on.
146
+ tag (str, optional): A unique identifier for the collective. Default: empty string
147
+ """
148
+ group_name = _resolve_group_name(group, tag)
149
+ tensor = torch.ops._c10d_functional.broadcast(self, src, group_name)
150
+ return _maybe_wrap_tensor(tensor)
151
+
152
+
153
+ def all_reduce(self: torch.Tensor, reduceOp: str, group: RANK_TYPES, tag: str = ""):
154
+ """
155
+ Reduces the tensor data across all machines in such a way that all get
156
+ the final result.
157
+
158
+ The input tensor is left unmodified.
159
+
160
+ Group can be one of:
161
+ List[int]: ranks participating in the collective.
162
+ List[List[int]]: 2D mesh of ranks taking part of this collective in MPMD.
163
+ ProcessGroup: Will perform a collective using the ranks and tag of the PG.
164
+ DeviceMesh: Do a SPMD collective over all ranks of the mesh
165
+ (DeviceMesh, int): Do a MPMD collective over one dimension of the DeviceMesh
166
+
167
+ :: N.B. If you pass a PG or a 1D list to perform a MPMD collective, the compiler won't be able to recover
168
+ that information and perform collective algebraic optimization. Use other forms of input for that.
169
+ """
170
+ group_name = _resolve_group_name(group, tag)
171
+ tensor = torch.ops._c10d_functional.all_reduce(self, reduceOp.lower(), group_name)
172
+ return _maybe_wrap_tensor(tensor)
173
+
174
+
175
+ def all_gather_tensor(
176
+ self: torch.Tensor,
177
+ gather_dim: int,
178
+ group: RANK_TYPES,
179
+ tag: str = "",
180
+ ) -> torch.Tensor:
181
+ """
182
+ Gather tensor data across from all machines and concatenate over ``gather_dim``.
183
+
184
+ Note that it currently only supports gather_dim = 0.
185
+
186
+ The input tensor is left unmodified.
187
+ Group can be one of:
188
+ List[int]: ranks participating in the collective.
189
+ List[List[int]]: 2D mesh of ranks taking part of this collective in MPMD.
190
+ ProcessGroup: Will perform a collective using the ranks and tag of the PG.
191
+ DeviceMesh: Do a SPMD collective over all ranks of the mesh
192
+ (DeviceMesh, int): Do a MPMD collective over one dimension of the DeviceMesh
193
+
194
+ :: N.B. If you pass a PG or a 1D list to perform a MPMD collective, the compiler won't be able to recover
195
+ that information and perform collective algebraic optimization. Use other forms of input for that.
196
+ """
197
+ if not self.is_contiguous():
198
+ raise AssertionError("Tensor must be contiguous for all_gather_tensor")
199
+ group_name = _resolve_group_name(group, tag)
200
+ group_size = c10d._get_group_size_by_name(group_name)
201
+ tensor = torch.ops._c10d_functional.all_gather_into_tensor(
202
+ self, group_size, group_name
203
+ )
204
+ res = _maybe_wrap_tensor(tensor)
205
+ # TODO this should be done inside AsyncCollectiveTensor to delay the wait() call
206
+ if gather_dim != 0:
207
+ # torch.cat access the data so we already need to wait here, first do wait
208
+ # and then chunk + cat avoid us going through ACT dispatching logic again
209
+ if isinstance(res, AsyncCollectiveTensor):
210
+ res = res.wait() # type: ignore[attr-defined]
211
+ res = torch.cat(torch.chunk(res, group_size, dim=0), dim=gather_dim)
212
+ return res
213
+
214
+
215
+ def all_gather_tensor_autograd(
216
+ self: torch.Tensor,
217
+ gather_dim: int,
218
+ group: RANK_TYPES,
219
+ tag: str = "",
220
+ ):
221
+ """
222
+ Gather tensor data across from all machines and concatenate over ``gather_dim``.
223
+
224
+ Note that it currently only supports gather_dim = 0.
225
+
226
+ This function is the same as all_gather_tensor but will propagate the
227
+ backwards gradient across workers.
228
+
229
+ See all_gather_tensor for more details on usage.
230
+ """
231
+ group_name = _resolve_group_name(group, tag)
232
+ group_size = c10d._get_group_size_by_name(group_name)
233
+
234
+ tensor = torch.ops._c10d_functional_autograd.all_gather_into_tensor(
235
+ self, group_size, group_name
236
+ )
237
+ res = _FromTorchTensor.apply(tensor)
238
+ # TODO this should be done inside AsyncCollectiveTensor to delay the wait() call
239
+ if gather_dim != 0:
240
+ # torch.cat access the data so we already need to wait here, first do wait
241
+ # and then chunk + cat avoid us going through ACT dispatching logic again
242
+ if isinstance(res, AsyncCollectiveTensor):
243
+ res = res.wait() # type: ignore[attr-defined]
244
+ res = torch.cat(torch.chunk(res, group_size, dim=0), dim=gather_dim)
245
+ return res
246
+
247
+
248
+ def reduce_scatter_tensor(
249
+ self: torch.Tensor,
250
+ reduceOp: str,
251
+ scatter_dim: int,
252
+ group: RANK_TYPES,
253
+ tag: str = "",
254
+ ):
255
+ """
256
+ Reduces the tensor data across all machines in such a way that all get
257
+ the final result, then scatter the results to corresponding ranks.
258
+
259
+
260
+ The input tensor is left unmodified.
261
+ Group can be one of:
262
+ List[int]: ranks participating in the collective.
263
+ List[List[int]]: 2D mesh of ranks taking part of this collective in MPMD.
264
+ ProcessGroup: Will perform a collective using the ranks and tag of the PG.
265
+ DeviceMesh: Do a SPMD collective over all ranks of the mesh
266
+ (DeviceMesh, int): Do a MPMD collective over one dimension of the DeviceMesh
267
+ :: N.B. If you pass a PG or a 1D list to perform a MPMD collective, the compiler won't be able to recover
268
+ that information and perform collective algebraic optimization. Use other forms of input for that.
269
+ """
270
+ group_name = _resolve_group_name(group, tag)
271
+ group_size = c10d._get_group_size_by_name(group_name)
272
+
273
+ if self.size(scatter_dim) % group_size != 0:
274
+ raise AssertionError(
275
+ f"input dimension 0 ({self.size(0)} must be a multiple of group_size {group_size})"
276
+ )
277
+ if scatter_dim != 0:
278
+ tensor_list = torch.chunk(self, group_size, dim=scatter_dim)
279
+ self = torch.cat(tensor_list)
280
+
281
+ tensor = torch.ops._c10d_functional.reduce_scatter_tensor(
282
+ self,
283
+ reduceOp.lower(),
284
+ group_size,
285
+ group_name, # type: ignore[possibly-undefined]
286
+ )
287
+ res = _maybe_wrap_tensor(tensor)
288
+ return res
289
+
290
+
291
+ def reduce_scatter_tensor_autograd(
292
+ self: torch.Tensor,
293
+ reduceOp: str,
294
+ scatter_dim: int,
295
+ group: RANK_TYPES,
296
+ tag: str = "",
297
+ ):
298
+ """
299
+ Reduces the tensor data across all machines in such a way that all get
300
+ the final result, then scatter the results to corresponding ranks.
301
+
302
+ This function is the same as reduce_scatter_tensor but will propagate the
303
+ backwards gradient across workers.
304
+
305
+ Currently only the "sum" reduceOp is supported.
306
+
307
+ See reduce_scatter_tensor for more details on usage.
308
+ """
309
+
310
+ group_name = _resolve_group_name(group, tag)
311
+ group_size = c10d._get_group_size_by_name(group_name)
312
+
313
+ if self.size(scatter_dim) % group_size != 0:
314
+ raise AssertionError(
315
+ f"input dimension 0 ({self.size(0)} must be a multiple of group_size {group_size}"
316
+ )
317
+ if scatter_dim != 0:
318
+ tensor_list = torch.chunk(self, group_size, dim=scatter_dim)
319
+ self = torch.cat(tensor_list)
320
+
321
+ tensor = torch.ops._c10d_functional_autograd.reduce_scatter_tensor(
322
+ self,
323
+ reduceOp.lower(),
324
+ group_size,
325
+ group_name, # type: ignore[possibly-undefined]
326
+ )
327
+ res = _FromTorchTensor.apply(tensor)
328
+ return res
329
+
330
+
331
+ def all_reduce_coalesced(
332
+ self: list[torch.Tensor], reduceOp: str, group: RANK_TYPES, tag: str = ""
333
+ ) -> list[torch.Tensor]:
334
+ """
335
+ Reduces a list of tensors across all machines in such a way that all get
336
+ the final result.
337
+
338
+ The all tensors in the input list are left unmodified.
339
+
340
+ Group can be one of:
341
+ List[int]: ranks participating in the collective.
342
+ List[List[int]]: 2D mesh of ranks taking part of this collective in MPMD.
343
+ ProcessGroup: Will perform a collective using the ranks and tag of the PG.
344
+ DeviceMesh: Do a SPMD collective over all ranks of the mesh
345
+ (DeviceMesh, int): Do a MPMD collective over one dimension of the DeviceMesh
346
+
347
+ :: N.B. If you pass a PG or a 1D list to perform a MPMD collective, the compiler won't be able to recover
348
+ that information and perform collective algebraic optimization. Use other forms of input for that.
349
+ """
350
+ group_name = _resolve_group_name(group, tag)
351
+ tensor_list = torch.ops._c10d_functional.all_reduce_coalesced( # type: ignore[attr-defined]
352
+ self,
353
+ reduceOp.lower(),
354
+ group_name,
355
+ )
356
+ return list(map(_maybe_wrap_tensor, tensor_list))
357
+
358
+
359
+ def all_gather_into_tensor_coalesced(
360
+ self: list[torch.Tensor], group: RANK_TYPES, tag: str = ""
361
+ ) -> list[torch.Tensor]:
362
+ """
363
+ Gather a list of tensors across from all machines.
364
+
365
+ Note that it currently only supports gather_dim = 0.
366
+
367
+ The input tensor is left unmodified.
368
+ Group can be one of:
369
+ List[int]: ranks participating in the collective.
370
+ List[List[int]]: 2D mesh of ranks taking part of this collective in MPMD.
371
+ ProcessGroup: Will perform a collective using the ranks and tag of the PG.
372
+ DeviceMesh: Do a SPMD collective over all ranks of the mesh
373
+ (DeviceMesh, int): Do a MPMD collective over one dimension of the DeviceMesh
374
+
375
+ :: N.B. If you pass a PG or a 1D list to perform a MPMD collective, the compiler won't be able to recover
376
+ that information and perform collective algebraic optimization. Use other forms of input for that.
377
+ """
378
+ group_name = _resolve_group_name(group, tag)
379
+ group_size = c10d._get_group_size_by_name(group_name)
380
+ tensor_list = torch.ops._c10d_functional.all_gather_into_tensor_coalesced( # type: ignore[attr-defined]
381
+ self,
382
+ group_size,
383
+ group_name,
384
+ )
385
+ return list(map(_maybe_wrap_tensor, tensor_list))
386
+
387
+
388
+ def reduce_scatter_tensor_coalesced(
389
+ inputs: list[torch.Tensor],
390
+ reduceOp: str,
391
+ scatter_dim: list[int],
392
+ group: RANK_TYPES,
393
+ tag: str = "",
394
+ ) -> list[torch.Tensor]:
395
+ """
396
+ Reduces a list of tensors across all machines in such a way that all get
397
+ the final result, then scatter the results to corresponding ranks.
398
+
399
+ The input tensors are left unmodified.
400
+ Group can be one of:
401
+ List[int]: ranks participating in the collective.
402
+ List[List[int]]: 2D mesh of ranks taking part of this collective in MPMD.
403
+ ProcessGroup: Will perform a collective using the ranks and tag of the PG.
404
+ DeviceMesh: Do a SPMD collective over all ranks of the mesh
405
+ (DeviceMesh, int): Do a MPMD collective over one dimension of the DeviceMesh
406
+
407
+ :: N.B. If you pass a PG or a 1D list to perform a MPMD collective, the compiler won't be able to recover
408
+ that information and perform collective algebraic optimization. Use other forms of input for that.
409
+ """
410
+ group_name = _resolve_group_name(group, tag)
411
+ group_size = c10d._get_group_size_by_name(group_name)
412
+
413
+ if len(scatter_dim) != len(inputs):
414
+ raise AssertionError(
415
+ f"Length of scatter_dim ({len(scatter_dim)}) must equal length of inputs ({len(inputs)})"
416
+ )
417
+ for idx, (dim, tensor) in enumerate(zip(scatter_dim, inputs)):
418
+ if tensor.size(dim) % group_size != 0:
419
+ raise AssertionError(
420
+ f"input dimension {dim} ({tensor.size(dim)} must be a multiple of group_size {group_size} for tensor at index {idx}"
421
+ )
422
+ if dim != 0:
423
+ tensor_list = torch.chunk(tensor, group_size, dim=dim)
424
+ inputs[idx] = torch.cat(tensor_list)
425
+
426
+ tensor_list = torch.ops._c10d_functional.reduce_scatter_tensor_coalesced( # type: ignore[attr-defined]
427
+ inputs,
428
+ reduceOp.lower(),
429
+ group_size,
430
+ group_name, # type: ignore[possibly-undefined]
431
+ )
432
+
433
+ return list(map(_maybe_wrap_tensor, tensor_list))
434
+
435
+
436
+ # This is a bit unsafe: it checks if the first argument in the schema reports as a non-mutable alias.
437
+ # Today, this maps 1:1 with "aten ops that are views".
438
+ def _is_view_op(tgt):
439
+ if not isinstance(tgt, torch._ops.OpOverload):
440
+ raise AssertionError(f"Expected torch._ops.OpOverload, got {type(tgt)}")
441
+ # Don't apply the view optimization to any `CompositeImplicitAutograd` ops.
442
+ # See issue: https://github.com/pytorch/pytorch/issues/133421
443
+ if torch._C._dispatch_has_kernel_for_dispatch_key(
444
+ tgt.name(), torch.DispatchKey.CompositeImplicitAutograd
445
+ ):
446
+ return False
447
+ schema = tgt._schema
448
+ if len(schema.arguments) > 0:
449
+ first_arg = schema.arguments[0]
450
+ # check if op is a view
451
+ return first_arg.alias_info is not None and not first_arg.alias_info.is_write
452
+
453
+
454
+ def all_to_all_single(
455
+ self: torch.Tensor,
456
+ output_split_sizes: list[int] | None,
457
+ input_split_sizes: list[int] | None,
458
+ group: RANK_TYPES,
459
+ tag: str = "",
460
+ ) -> torch.Tensor:
461
+ """
462
+ Each process splits input tensor and then scatters the split list
463
+ to all processes in a group. Then concatenate the received tensors from all
464
+ the processes in the group and return single output tensor.
465
+
466
+ Group can be one of:
467
+ List[int]: ranks participating in the collective.
468
+ List[List[int]]: 2D mesh of ranks taking part of this collective in MPMD.
469
+ ProcessGroup: Will perform a collective using the ranks and tag of the PG.
470
+ DeviceMesh: Do a SPMD collective over all ranks of the mesh
471
+ (DeviceMesh, int): Do a MPMD collective over one dimension of the DeviceMesh
472
+
473
+ :: N.B. If you pass a PG or a 1D list to perform a MPMD collective, the compiler won't be able to recover
474
+ that information and perform collective algebraic optimization. Use other forms of input for that.
475
+ """
476
+ if output_split_sizes is not None:
477
+ if not all(
478
+ isinstance(size, (int, torch.SymInt)) for size in output_split_sizes
479
+ ):
480
+ raise AssertionError(
481
+ f"All output_split_sizes must be int or SymInt, got {output_split_sizes}"
482
+ )
483
+ if input_split_sizes is not None:
484
+ if not all(isinstance(size, (int, torch.SymInt)) for size in input_split_sizes):
485
+ raise AssertionError(
486
+ f"All input_split_sizes must be int or SymInt, got {input_split_sizes}"
487
+ )
488
+ group_name = _resolve_group_name(group, tag)
489
+ group_size = c10d._get_group_size_by_name(group_name)
490
+ if output_split_sizes is None or input_split_sizes is None:
491
+ if not (output_split_sizes is None and input_split_sizes is None):
492
+ raise AssertionError(
493
+ "output_split_sizes and input_split_sizes must either be "
494
+ "specified together or both set to None"
495
+ )
496
+ output_split_sizes = [self.shape[0] // group_size] * group_size
497
+ input_split_sizes = output_split_sizes
498
+ tensor = torch.ops._c10d_functional.all_to_all_single( # type: ignore[attr-defined]
499
+ self,
500
+ output_split_sizes,
501
+ input_split_sizes,
502
+ group_name,
503
+ )
504
+ return _maybe_wrap_tensor(tensor)
505
+
506
+
507
+ def all_to_all_single_autograd(
508
+ self: torch.Tensor,
509
+ output_split_sizes: list[int] | None,
510
+ input_split_sizes: list[int] | None,
511
+ group: RANK_TYPES,
512
+ tag: str = "",
513
+ ) -> torch.Tensor:
514
+ """
515
+ Same as all_to_all_single but supports autograd.
516
+ """
517
+ if output_split_sizes is not None:
518
+ if not all(
519
+ isinstance(size, (int, torch.SymInt)) for size in output_split_sizes
520
+ ):
521
+ raise AssertionError(
522
+ f"All output_split_sizes must be int or SymInt, got {output_split_sizes}"
523
+ )
524
+ if input_split_sizes is not None:
525
+ if not all(isinstance(size, (int, torch.SymInt)) for size in input_split_sizes):
526
+ raise AssertionError(
527
+ f"All input_split_sizes must be int or SymInt, got {input_split_sizes}"
528
+ )
529
+
530
+ group_name = _resolve_group_name(group, tag)
531
+ group_size = c10d._get_group_size_by_name(group_name)
532
+ if output_split_sizes is None or input_split_sizes is None:
533
+ if not (output_split_sizes is None and input_split_sizes is None):
534
+ raise AssertionError(
535
+ "output_split_sizes and input_split_sizes must either be "
536
+ "specified together or both set to None"
537
+ )
538
+ output_split_sizes = [self.shape[0] // group_size] * group_size
539
+ input_split_sizes = output_split_sizes
540
+ tensor = torch.ops._c10d_functional_autograd.all_to_all_single( # type: ignore[attr-defined]
541
+ self,
542
+ output_split_sizes,
543
+ input_split_sizes,
544
+ group_name,
545
+ )
546
+ return _FromTorchTensor.apply(tensor)
547
+
548
+
549
+ def permute_tensor(
550
+ self: torch.Tensor,
551
+ src_dst: list[int],
552
+ group: RANK_TYPES,
553
+ tag: str = "",
554
+ ) -> torch.Tensor:
555
+ """
556
+ Permutes the elements of the tensor according to the given source/destination pairs. `src_dst` should
557
+ be defined such that src_dst[m] == n means m sends to n.
558
+
559
+ Group can be one of:
560
+ List[int]: ranks participating in the collective.
561
+ List[List[int]]: 2D mesh of ranks taking part of this collective in MPMD.
562
+ ProcessGroup: Will perform a collective using the ranks and tag of the PG.
563
+ DeviceMesh: Do a SPMD collective over all ranks of the mesh
564
+ (DeviceMesh, int): Do a MPMD collective over one
565
+ """
566
+ t, rankset, group_size = _expand_group(group, tag)
567
+ local_pg = c10d._find_or_create_pg_by_ranks_and_tag(t, rankset, group_size)
568
+
569
+ output_split_sizes = [0] * group_size
570
+ input_split_sizes = [0] * group_size
571
+ for src, dst in enumerate(src_dst):
572
+ if src == dist.get_rank(local_pg):
573
+ input_split_sizes[dst] = self.numel()
574
+ if dst == dist.get_rank(local_pg):
575
+ output_split_sizes[src] = self.numel()
576
+
577
+ return all_to_all_single(self, output_split_sizes, input_split_sizes, group, tag)
578
+
579
+
580
+ class AsyncCollectiveTensor(torch.Tensor):
581
+ r"""
582
+ A Tensor wrapper subclass that is used to trigger a call to wait
583
+ prior to first use of the underlying tensor.
584
+ Use it inside functional collective pytorch wrappers like the following:
585
+ def functional_collective(self, group, tag):
586
+ tag, rankset, group_size = _expand_group(group, tag)
587
+ tensor = torch.ops.c10d_functional.{collective}(self, tag, rankset, group_size)
588
+ return _maybe_wrap_tensor(tensor)
589
+ """
590
+
591
+ elem: torch.Tensor
592
+ completed: bool
593
+
594
+ __slots__ = ["elem", "completed"]
595
+
596
+ @staticmethod
597
+ def __new__(cls, elem: torch.Tensor):
598
+ r = torch.Tensor._make_wrapper_subclass(
599
+ cls,
600
+ elem.size(),
601
+ strides=elem.stride(),
602
+ storage_offset=elem.storage_offset(),
603
+ dtype=elem.dtype,
604
+ layout=elem.layout,
605
+ device=elem.device,
606
+ requires_grad=elem.requires_grad,
607
+ )
608
+ r.elem = elem
609
+ r.completed = False
610
+ return r
611
+
612
+ def __tensor_flatten__(self):
613
+ return ["elem"], None
614
+
615
+ def tolist(self):
616
+ return self.trigger_wait().tolist()
617
+
618
+ @staticmethod
619
+ def __tensor_unflatten__(inner_tensors, meta, outer_size, outer_stride):
620
+ if meta is not None:
621
+ raise AssertionError(
622
+ "meta must be None for AsyncCollectiveTensor unflatten"
623
+ )
624
+ elem = inner_tensors["elem"]
625
+ return AsyncCollectiveTensor(elem)
626
+
627
+ def __coerce_same_metadata_as_tangent__(
628
+ self, expected_metadata: Any, expected_type: type | None = None
629
+ ):
630
+ if expected_type is not torch.Tensor:
631
+ return None
632
+
633
+ return self.trigger_wait()
634
+
635
+ def __repr__(self) -> str: # type: ignore[override]
636
+ return f"AsyncCollectiveTensor({self.trigger_wait()})"
637
+
638
+ def trigger_wait(self):
639
+ if not self.completed:
640
+ out = wait_tensor(self.elem)
641
+ self.completed = True
642
+ return out
643
+ else:
644
+ return self.elem
645
+
646
+ def wait(self) -> torch.Tensor:
647
+ return wait_tensor(self.elem)
648
+
649
+ def _get_acs_underlying_tensor(self):
650
+ """This method enables _functional_collectives_impl to test if a tensor is an ACS"""
651
+ return self.elem
652
+
653
+ @classmethod
654
+ def __torch_dispatch__(cls, func, types, args=(), kwargs=None): # type: ignore[override]
655
+ if func is torch.ops.aten.view.default:
656
+ # Fast handle aten.view as a lot of view related op goes to aten.view
657
+ # eventually, this avoids pytree slowdown
658
+ # pyrefly: ignore [index-error]
659
+ res = func(args[0].elem, args[1])
660
+ wrapper_res = AsyncCollectiveTensor(res)
661
+ return wrapper_res
662
+
663
+ is_view_op = _is_view_op(func)
664
+
665
+ def unwrap(e: AsyncCollectiveTensor):
666
+ # wait_tensor is idepotent and will do stream sync only once
667
+ if not is_view_op:
668
+ return e.trigger_wait()
669
+ return e.elem
670
+
671
+ def wrap(e: torch.Tensor):
672
+ # wait_tensor is idepotent and will do stream sync only once
673
+ if isinstance(e, AsyncCollectiveTensor):
674
+ raise AssertionError(
675
+ "Cannot wrap an AsyncCollectiveTensor inside another AsyncCollectiveTensor"
676
+ )
677
+ res = AsyncCollectiveTensor(e)
678
+ return res
679
+
680
+ unwrapped_args = tree_map_only(AsyncCollectiveTensor, unwrap, args)
681
+ unwrapped_kwargs = tree_map_only(AsyncCollectiveTensor, unwrap, kwargs)
682
+
683
+ # we don't wrap the result as it doesn't need to be waited on.
684
+ out = func(*unwrapped_args, **unwrapped_kwargs)
685
+
686
+ # View ops dont require a sync, so we should re-wrap the outputs.
687
+ if is_view_op:
688
+ out = tree_map_only(torch.Tensor, wrap, out)
689
+
690
+ return out
691
+
692
+ def numpy(self): # type: ignore[override]
693
+ return self.wait().numpy()
694
+
695
+
696
+ """
697
+ Utils and infrastructure for tracing support
698
+ """
699
+
700
+
701
+ def _expand_group(group: RANK_TYPES, tag: str = "") -> tuple[str, list[int], int]:
702
+ """
703
+ _expand_group desugars the different RANK_TYPES types into a canonical format that is traceable.
704
+
705
+ By having this be part of the explicit eager codepath, we avoid having to specialize behavior inside
706
+ torchdynamo and can still interoperate with processgroup objects or other untraceable forms.
707
+ """
708
+ # had to define this hack _inside_ expand_group to avoid
709
+ # graph_break [('torch.* op returned non-Tensor int
710
+ # caused by 'cast_*` functions being treated as 'torch.*' ops (iiuc)
711
+ if TYPE_CHECKING:
712
+
713
+ def cast_listlistint(x):
714
+ return cast(list[list[int]], x)
715
+
716
+ def cast_listint(x):
717
+ return cast(list[int], x)
718
+
719
+ else:
720
+ # fake cast op for use at runtime since dynamo doesn't support real cast
721
+ # also, dynamo didn't like encountering 'typing' objects ()
722
+ # NotImplementedError: argument of type: <class 'typing._GenericAlias'>
723
+ def cast_listlistint(x):
724
+ return x
725
+
726
+ def cast_listint(x):
727
+ return x
728
+
729
+ rankset: list[int]
730
+ if isinstance(group, list):
731
+ if isinstance(group[0], list):
732
+ nested_list = cast_listlistint(group)
733
+ rankset = []
734
+ group_size = -1
735
+ for rs in nested_list:
736
+ rankset.extend(rs)
737
+ if group_size != -1 and group_size != len(rs):
738
+ raise ValueError(
739
+ f"group sizes must be identical found {group_size} and {len(rs)}"
740
+ )
741
+ group_size = len(rs)
742
+ else:
743
+ rankset = cast_listint(group)
744
+ group_size = len(rankset)
745
+ elif isinstance(group, dist.ProcessGroup):
746
+ rankset = dist.get_process_group_ranks(group)
747
+ group_size = len(rankset)
748
+ tag = tag or c10d._get_group_tag(group)
749
+ elif isinstance(group, DeviceMesh):
750
+ if group.ndim != 1:
751
+ raise AssertionError(
752
+ "Only 1D mesh is supported, pass in (DeviceMesh, int) together if mesh > 1D"
753
+ )
754
+ # TODO: it should run collective in the whole mesh instead of dim 0
755
+ pg = group.get_group()
756
+ rankset = dist.get_process_group_ranks(pg)
757
+ group_size = len(rankset)
758
+ tag = tag or c10d._get_group_tag(pg)
759
+ elif isinstance(group, tuple):
760
+ if (
761
+ len(group) == 2
762
+ and isinstance(group[0], DeviceMesh)
763
+ and isinstance(group[1], int)
764
+ ):
765
+ dmesh = group[0]
766
+ dim = group[1]
767
+ pg = dmesh.get_group(dim)
768
+ rankset = dist.get_process_group_ranks(pg)
769
+ group_size = len(rankset)
770
+ tag = tag or c10d._get_group_tag(pg)
771
+ else:
772
+ raise ValueError("Invalid tuple for group must be (DeviceMesh, int)")
773
+ else:
774
+ raise ValueError(
775
+ "Invalid type for group, must be one of List, Processgroup, DeviceMesh or (DeviceMesh, int)."
776
+ )
777
+
778
+ return (tag, rankset, group_size)
779
+
780
+
781
+ def _resolve_group_name(group: RANK_TYPES, tag: str = "") -> c10d.GroupName:
782
+ """
783
+ Given group in RANK_TYPES, return the group name.
784
+ """
785
+ # `tag` will be deprecated. See details in:
786
+ # https://github.com/pytorch/pytorch/issues/93173#issuecomment-1907095208
787
+ if isinstance(group, dist.ProcessGroup):
788
+ return group.group_name
789
+ elif isinstance(group, str):
790
+ # In some cases Dynamo doesn't like tracing through NewType constructors
791
+ # - so use a cast instead (the actual newtype representation is
792
+ # literally the underlying type so this is fine). I haven't been able to
793
+ # reproduce it in isolation (see T247631668).
794
+ return cast(c10d.GroupName, group) # c10d.GroupName(group)
795
+ elif isinstance(group, DeviceMesh):
796
+ if group.ndim != 1:
797
+ raise AssertionError(
798
+ "Only 1D mesh is supported, pass in (DeviceMesh, int) together if mesh > 1D"
799
+ )
800
+ return group._dim_group_names[0]
801
+ elif isinstance(group, tuple):
802
+ if (
803
+ len(group) == 2
804
+ and isinstance(group[0], DeviceMesh)
805
+ and isinstance(group[1], int)
806
+ ):
807
+ dmesh = group[0]
808
+ dim = group[1]
809
+ return dmesh._dim_group_names[dim]
810
+ else:
811
+ raise ValueError("Invalid tuple for group must be (DeviceMesh, int)")
812
+ elif isinstance(group, list):
813
+ if not is_torchdynamo_compiling():
814
+ warnings.warn(
815
+ "The combination of ranks + tag as process group "
816
+ "identifier has been deprecated. Please switch to "
817
+ "using ProcessGroup, DeviceMesh, or group name instead.",
818
+ FutureWarning,
819
+ stacklevel=3,
820
+ )
821
+ # pyrefly: ignore [redundant-cast]
822
+ return c10d._resolve_group_name_by_ranks_and_tag(cast(list[int], group), tag)
823
+ else:
824
+ raise ValueError(f"Unsupported group type: {type(group)}, {group}")
825
+
826
+
827
+ class _FromTorchTensor(torch.autograd.Function):
828
+ """
829
+ _FromTorchTensor allows autograd to propagate from a normal Tensor to an
830
+ AsyncCollectiveTensor.
831
+ """
832
+
833
+ @staticmethod
834
+ def forward( # type: ignore[override]
835
+ ctx, # pyre-ignore[2]: Parameter must be annotated.
836
+ input: torch.Tensor,
837
+ ) -> torch.Tensor:
838
+ return _maybe_wrap_tensor(input)
839
+
840
+ @staticmethod
841
+ def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor: # type: ignore[override]
842
+ return grad_output
843
+
844
+
845
+ def _are_we_tracing() -> bool:
846
+ if is_torchdynamo_compiling():
847
+ return True
848
+ # If fake mode is turned on, we are almost definitely compiling/tracing.
849
+ if torch._C._get_dispatch_mode(torch._C._TorchDispatchModeKey.FAKE) is not None:
850
+ return True
851
+ # See Note [enable_python_dispatcher in dynamo]
852
+ if torch._C._dispatch_tls_is_dispatch_key_included(
853
+ torch._C.DispatchKey.PythonDispatcher
854
+ ):
855
+ return True
856
+ return get_proxy_mode() is not None
857
+
858
+
859
+ def _maybe_wrap_tensor(self) -> torch.Tensor:
860
+ if _are_we_tracing():
861
+ return wait_tensor(self)
862
+ res = AsyncCollectiveTensor(self)
863
+ return cast(torch.Tensor, res)
864
+
865
+
866
+ @contextlib.contextmanager
867
+ def allow_inflight_collective_as_graph_input_ctx(value: bool = True):
868
+ """
869
+ Context manager to temporarily set whether inflight collectives are allowed as torch.compile graph inputs.
870
+ Common use case is when the collective is issued in eager (with `async_op=True`) but waited in compiled region:
871
+ ```
872
+ def all_reduce_eager(x):
873
+ y = x * x
874
+ req = dist.all_reduce(y, op=dist.ReduceOp.SUM, async_op=True)
875
+ return y
876
+
877
+
878
+ @torch.compile(fullgraph=True)
879
+ def all_reduce_wait_compiled(y):
880
+ torch.ops.c10d_functional.wait_tensor(y)
881
+ return y * y
882
+
883
+
884
+ x = torch.ones(1280, 1280, device="cuda") + self.rank
885
+ # the context manager ensures that `wait_tensor(y)` will wait on the correct work object
886
+ with allow_inflight_collective_as_graph_input_ctx():
887
+ y = all_reduce_eager(x)
888
+ z = all_reduce_wait_compiled(y)
889
+ ```
890
+ With this context manager, when a collective is called, under the hood the work object of the collective
891
+ will be registered in the work registry, and the wait_tensor() in compiled region called on
892
+ the output tensor of the collective will wait on the correct work object.
893
+ """
894
+ previous = torch._C._distributed_c10d._allow_inflight_collective_as_graph_input()
895
+
896
+ try:
897
+ torch._C._distributed_c10d._set_allow_inflight_collective_as_graph_input(value)
898
+ yield
899
+ finally:
900
+ torch._C._distributed_c10d._set_allow_inflight_collective_as_graph_input(
901
+ previous
902
+ )
903
+
904
+
905
+ def _make_all_gather_out_tensor(input, group_size):
906
+ out_size = list(input.size())
907
+ if len(out_size) == 0:
908
+ out_size.append(group_size)
909
+ else:
910
+ out_size[0] *= group_size
911
+ out_tensor = input.new_empty(out_size)
912
+ return out_tensor
913
+
914
+
915
+ def _all_gather_into_tensor_coalesced_meta(self, tag, rankset, group_size):
916
+ return [_make_all_gather_out_tensor(t, group_size) for t in self]
917
+
918
+
919
+ # We now register meta kernels to deal with tracing
920
+ def _broadcast_meta(self, *args):
921
+ return torch.empty_like(self)
922
+
923
+
924
+ def _all_reduce_meta(self, *args):
925
+ return torch.empty_like(self)
926
+
927
+
928
+ def _wait_tensor_meta(self, *args):
929
+ return torch.empty_like(self)
930
+
931
+
932
+ def _all_gather_into_tensor_meta(shard, tag, rankset, group_size):
933
+ return _make_all_gather_out_tensor(shard, group_size)
934
+
935
+
936
+ def _reduce_scatter_tensor_meta(input, reduce_op, tag, rankset, group_size):
937
+ out_size = list(input.size())
938
+ out_size[0] //= group_size
939
+ return input.new_empty(out_size)
940
+
941
+
942
+ def _all_reduce_coalesced_meta(self, *args):
943
+ return [torch.empty_like(t) for t in self]
944
+
945
+
946
+ def _all_reduce__meta(inp, *args):
947
+ return inp
948
+
949
+
950
+ def _broadcast__meta(inp, *args):
951
+ return inp
952
+
953
+
954
+ def _all_reduce_coalesced__meta(inputs, *args):
955
+ return inputs
956
+
957
+
958
+ def _reduce_scatter_tensor_coalesced_meta(inputs, reduceOp, tag, rankset, group_size):
959
+ def mk_out_tensor(input):
960
+ out_size = list(input.size())
961
+ out_size[0] //= group_size
962
+ out_tensor = input.new_empty(out_size)
963
+ return out_tensor
964
+
965
+ return [mk_out_tensor(t) for t in inputs]
966
+
967
+
968
+ # NB: We often say all_to_all has dynamic output size, but this is not
969
+ # technically true: instead, what typically happens is you manually
970
+ # communicate the output_split_sizes ahead of time (which is dynamic),
971
+ # but then you pass those sizes explicitly, and the all to all itself
972
+ # isn't dynamic, it just follows the specified output splits
973
+ def _all_to_all_single_meta(
974
+ input, output_split_sizes, input_split_sizes, *args, **kwargs
975
+ ):
976
+ if output_split_sizes is None:
977
+ return input.new_empty(input.size())
978
+ else:
979
+ for s in output_split_sizes:
980
+ torch._check(s >= 0)
981
+ out_size = list(input.size())
982
+ out_size[0] = sum(output_split_sizes)
983
+ return input.new_empty(out_size)
984
+
985
+
986
+ def _all_gather_into_tensor_out_native_meta(input, group_size, group_name, *, out):
987
+ return _make_all_gather_out_tensor(input, group_size)
988
+
989
+
990
+ def _all_gather_into_tensor_native_meta(input, group_size, group_name):
991
+ return _make_all_gather_out_tensor(input, group_size)
992
+
993
+
994
+ def _all_gather_into_tensor_coalesced_native_meta(inputs, group_size, group_name):
995
+ return [
996
+ _all_gather_into_tensor_native_meta(input, group_size, group_name)
997
+ for input in inputs
998
+ ]
999
+
1000
+
1001
+ def _reduce_scatter_tensor_native_meta(inp, reduce_op, group_size, group_name):
1002
+ shape = list(inp.size())
1003
+ shape[0] //= group_size
1004
+ return inp.new_empty(shape)
1005
+
1006
+
1007
+ def _reduce_scatter_tensor_out_native_meta(
1008
+ inp, reduce_op, group_size, group_name, *, out
1009
+ ):
1010
+ shape = list(inp.size())
1011
+ shape[0] //= group_size
1012
+ return inp.new_empty(shape)
1013
+
1014
+
1015
+ def _reduce_scatter_tensor_coalesced_native_meta(
1016
+ inputs, reduce_op, group_size, group_name
1017
+ ):
1018
+ return [
1019
+ _reduce_scatter_tensor_native_meta(inp, reduce_op, group_size, group_name)
1020
+ for inp in inputs
1021
+ ]
1022
+
1023
+
1024
+ # Library MUST be defined at module scope or it doesn't work
1025
+ lib_impl = torch.library.Library("_c10d_functional", "IMPL")
1026
+ lib_impl.impl("all_reduce", _all_reduce_meta, "Meta")
1027
+ lib_impl.impl("all_reduce_", _all_reduce__meta, "Meta")
1028
+ lib_impl.impl("all_reduce_coalesced", _all_reduce_coalesced_meta, "Meta")
1029
+ lib_impl.impl("all_reduce_coalesced_", _all_reduce_coalesced__meta, "Meta")
1030
+ lib_impl.impl("wait_tensor", _wait_tensor_meta, "Meta")
1031
+ lib_impl.impl(
1032
+ "all_gather_into_tensor_out", _all_gather_into_tensor_out_native_meta, "Meta"
1033
+ )
1034
+ lib_impl.impl("all_gather_into_tensor", _all_gather_into_tensor_native_meta, "Meta")
1035
+ lib_impl.impl(
1036
+ "all_gather_into_tensor_coalesced",
1037
+ _all_gather_into_tensor_coalesced_native_meta,
1038
+ "Meta",
1039
+ )
1040
+ lib_impl.impl("reduce_scatter_tensor", _reduce_scatter_tensor_native_meta, "Meta")
1041
+ lib_impl.impl(
1042
+ "reduce_scatter_tensor_out", _reduce_scatter_tensor_out_native_meta, "Meta"
1043
+ )
1044
+ lib_impl.impl(
1045
+ "reduce_scatter_tensor_coalesced",
1046
+ _reduce_scatter_tensor_coalesced_native_meta,
1047
+ "Meta",
1048
+ )
1049
+ lib_impl.impl("all_to_all_single", _all_to_all_single_meta, "Meta")
1050
+ lib_impl.impl("broadcast", _broadcast_meta, "Meta")
1051
+ lib_impl.impl("broadcast_", _broadcast__meta, "Meta")
1052
+
1053
+ # mark these ops has side effect so that they won't be removed by DCE
1054
+ torch.fx.node.has_side_effect(torch.ops._c10d_functional.wait_tensor.default) # type: ignore[has-type]
1055
+ torch.fx.node.has_side_effect(torch.ops._c10d_functional.wait_tensor) # type: ignore[has-type]
1056
+
1057
+ # Register legacy ops for backward compatibility
1058
+ # TODO(yifu): remove these in functional collective beta release
1059
+ legacy_lib = torch.library.Library("c10d_functional", "DEF")
1060
+ legacy_lib_impl = torch.library.Library("c10d_functional", "IMPL")
1061
+ ops_defs = [
1062
+ "broadcast(Tensor self, int src, str tag, int[] ranks, int group_size) -> Tensor",
1063
+ "all_reduce(Tensor self, str reduceOp, str tag, int[] ranks, int group_size) -> Tensor",
1064
+ "all_reduce_coalesced(Tensor[] self, str reduceOp, str tag, int[] ranks, int group_size) -> Tensor[]",
1065
+ "wait_tensor(Tensor self) -> Tensor",
1066
+ "all_gather_into_tensor(Tensor shard, str tag, int[] ranks, int group_size) -> Tensor",
1067
+ "all_gather_into_tensor_coalesced(Tensor[] input, str tag, int[] ranks, int group_size) -> Tensor[]",
1068
+ "reduce_scatter_tensor(Tensor input, str reduceOp, str tag, int[] ranks, int group_size) -> Tensor",
1069
+ "reduce_scatter_tensor_coalesced(Tensor[] inputs, str reduceOp, str tag, int[] ranks, int group_size) -> Tensor[]",
1070
+ "all_to_all_single(Tensor input, SymInt[]? output_split_sizes, SymInt[]? input_split_sizes, str tag, int[] ranks, int group_size) -> Tensor", # noqa: B950
1071
+ ]
1072
+
1073
+ my_module = sys.modules[__name__]
1074
+ for op_def in ops_defs:
1075
+ op_name = op_def[0 : op_def.index("(")]
1076
+ backend_impl = getattr(fun_col_impl, f"_{op_name}")
1077
+ legacy_lib.define(op_def, tags=torch.Tag.pt2_compliant_tag)
1078
+ legacy_lib_impl.impl(op_name, backend_impl, "CompositeImplicitAutograd")
1079
+
1080
+
1081
+ """
1082
+ Dynamo Remappings allow seamless translation from non-functional collectives of supportable form into
1083
+ functional collective calls followed by inplace copy ops, allowing them to be traced into a functional graph.
1084
+
1085
+ We implement this by writing a decomposition and teaching dynamo how to associate it to a corresponding op via
1086
+ the mapping dict below.
1087
+
1088
+ These schemas intentionally match torch.distributed.distributed_c10d.* ops that we are trying to remap from
1089
+ """
1090
+
1091
+
1092
+ def all_gather_tensor_inplace(
1093
+ output_tensor: torch.Tensor,
1094
+ input_tensor: torch.Tensor,
1095
+ group=None, # TODO add a type,
1096
+ async_op: bool = False,
1097
+ tag: str = "",
1098
+ gather_dim: int = 0,
1099
+ ):
1100
+ if async_op:
1101
+ raise AssertionError(
1102
+ "Can't remap async version of inplace op to functional collective"
1103
+ )
1104
+
1105
+ group = group or dist.group.WORLD
1106
+ if group is None:
1107
+ raise AssertionError("group cannot be None")
1108
+
1109
+ return output_tensor.copy_(all_gather_tensor(input_tensor, gather_dim, group, tag))
1110
+
1111
+
1112
+ def reduce_scatter_tensor_inplace(
1113
+ output: torch.Tensor,
1114
+ input: torch.Tensor,
1115
+ op: str = "sum", # TODO type is actually c10d ReduceOp. is this ok?
1116
+ group=None, # TODO add a type
1117
+ async_op: bool = False,
1118
+ scatter_dim: int = 0,
1119
+ tag: str = "",
1120
+ ):
1121
+ if async_op:
1122
+ raise AssertionError(
1123
+ "Can't remap async version of inplace op to functional collective"
1124
+ )
1125
+
1126
+ group = group or dist.group.WORLD
1127
+ if group is None:
1128
+ raise AssertionError("group cannot be None")
1129
+
1130
+ return output.copy_(reduce_scatter_tensor(input, op, scatter_dim, group, tag))
1131
+
1132
+
1133
+ REDUCE_OP_TO_STR = {
1134
+ dist.ReduceOp.SUM: "sum",
1135
+ dist.ReduceOp.AVG: "avg",
1136
+ dist.ReduceOp.PRODUCT: "product",
1137
+ dist.ReduceOp.MIN: "min",
1138
+ dist.ReduceOp.MAX: "max",
1139
+ dist.ReduceOp.BAND: "band",
1140
+ dist.ReduceOp.BOR: "bor",
1141
+ dist.ReduceOp.BXOR: "bxor",
1142
+ }
1143
+
1144
+
1145
+ def all_reduce_inplace(
1146
+ tensor: torch.Tensor,
1147
+ op: str = "sum",
1148
+ group=None,
1149
+ async_op: bool = False,
1150
+ tag: str = "",
1151
+ ):
1152
+ if async_op:
1153
+ raise AssertionError(
1154
+ "Can't remap async version of inplace op to functional collective"
1155
+ )
1156
+
1157
+ group = group or dist.group.WORLD
1158
+ if group is None:
1159
+ raise AssertionError("group cannot be None")
1160
+
1161
+ return tensor.copy_(all_reduce(tensor, op, group, tag))
1162
+
1163
+
1164
+ def all_to_all_inplace(
1165
+ output: torch.Tensor,
1166
+ input: torch.Tensor,
1167
+ output_split_sizes=None,
1168
+ input_split_sizes=None,
1169
+ group=None,
1170
+ async_op=False,
1171
+ tag: str = "",
1172
+ ):
1173
+ if async_op:
1174
+ raise AssertionError(
1175
+ "Can't remap async version of inplace op to functional collective"
1176
+ )
1177
+
1178
+ group = group or dist.group.WORLD
1179
+ if group is None:
1180
+ raise AssertionError("group cannot be None")
1181
+
1182
+ return output.copy_(
1183
+ all_to_all_single(
1184
+ input,
1185
+ output_split_sizes,
1186
+ input_split_sizes,
1187
+ group,
1188
+ tag,
1189
+ )
1190
+ )
1191
+
1192
+
1193
+ def all_gather_inplace(
1194
+ tensor_list: list[torch.Tensor],
1195
+ tensor: torch.Tensor,
1196
+ group=None,
1197
+ async_op=False,
1198
+ tag: str = "",
1199
+ ):
1200
+ if async_op:
1201
+ raise AssertionError(
1202
+ "Can't remap async version of inplace op to functional collective"
1203
+ )
1204
+ if tensor.dim() != 0 and not all(t.size(0) == tensor.size(0) for t in tensor_list):
1205
+ raise AssertionError("Remapping variable size all_gather is not yet supported")
1206
+
1207
+ group = group or dist.group.WORLD
1208
+ if group is None:
1209
+ raise AssertionError("group cannot be None")
1210
+
1211
+ output = all_gather_tensor(tensor, 0, group, tag)
1212
+
1213
+ # Use aten.slice instead of aten.split because the latter causes
1214
+ # tensor.shape(0) to be unnecessarily baked in when it's a SymInt.
1215
+ output_splits = []
1216
+ offset = 0
1217
+ for t in tensor_list:
1218
+ is_scalar = t.dim() == 0
1219
+ t_offset = 1 if is_scalar else t.size(0)
1220
+ # pyrefly: ignore [unsupported-operation]
1221
+ out = output[offset] if is_scalar else output[offset : offset + t_offset]
1222
+ output_splits.append(out)
1223
+ # pyrefly: ignore [unsupported-operation]
1224
+ offset += t_offset
1225
+ for dst, src in zip(tensor_list, output_splits):
1226
+ dst.copy_(src)
1227
+ return tensor_list
1228
+
1229
+
1230
+ from torch.distributed.distributed_c10d import ( # pyrefly: ignore # deprecated; pyrefly: ignore [deprecated]
1231
+ _all_gather_base as legacy_all_gather_base,
1232
+ _reduce_scatter_base as legacy_reduce_scatter_base,
1233
+ all_gather as legacy_all_gather,
1234
+ all_gather_into_tensor as legacy_allgather,
1235
+ all_reduce as legacy_allreduce,
1236
+ all_to_all_single as legacy_all_to_all_single,
1237
+ reduce_scatter_tensor as legacy_reducescatter,
1238
+ )
1239
+
1240
+
1241
+ # This dict should contain sets of functions that dynamo is allowed to remap.
1242
+ # Functions in this set should accept the same args/kwargs 1:1 as their mapping.
1243
+ traceable_collective_remaps = {
1244
+ legacy_allgather: all_gather_tensor_inplace, # type: ignore[has-type]
1245
+ legacy_reducescatter: reduce_scatter_tensor_inplace, # type: ignore[has-type]
1246
+ legacy_allreduce: all_reduce_inplace, # type: ignore[has-type]
1247
+ legacy_all_to_all_single: all_to_all_inplace, # type: ignore[has-type]
1248
+ legacy_all_gather: all_gather_inplace, # type: ignore[has-type]
1249
+ legacy_reduce_scatter_base: reduce_scatter_tensor_inplace, # type: ignore[has-type]
1250
+ legacy_all_gather_base: all_gather_tensor_inplace, # type: ignore[has-type]
1251
+ }
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_functional_collectives_impl.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.distributed.distributed_c10d as c10d
5
+
6
+
7
+ """
8
+ This file contains the op impls for the legacy (c10d_functional) functional collectives.
9
+ These impls simply call into the native (_c10d_functional) functional collectives.
10
+ """
11
+
12
+
13
+ def _broadcast(input, src, tag, ranks, group_size):
14
+ group_name = c10d._resolve_group_name_by_ranks_and_tag(ranks, tag)
15
+ return torch.ops._c10d_functional.broadcast(
16
+ input,
17
+ src,
18
+ group_name,
19
+ )
20
+
21
+
22
+ def _all_reduce(input, reduce_op, tag, ranks, group_size):
23
+ group_name = c10d._resolve_group_name_by_ranks_and_tag(ranks, tag)
24
+ return torch.ops._c10d_functional.all_reduce(
25
+ input,
26
+ reduce_op,
27
+ group_name,
28
+ )
29
+
30
+
31
+ def _all_reduce_coalesced(inputs, reduce_op, tag, ranks, group_size):
32
+ group_name = c10d._resolve_group_name_by_ranks_and_tag(ranks, tag)
33
+ return torch.ops._c10d_functional.all_reduce_coalesced(
34
+ inputs,
35
+ reduce_op,
36
+ group_name,
37
+ )
38
+
39
+
40
+ def _all_gather_into_tensor(input, tag, ranks, group_size):
41
+ group_name = c10d._resolve_group_name_by_ranks_and_tag(ranks, tag)
42
+ return torch.ops._c10d_functional.all_gather_into_tensor(
43
+ input,
44
+ group_size,
45
+ group_name,
46
+ )
47
+
48
+
49
+ def _all_gather_into_tensor_coalesced(input, tag, ranks, group_size):
50
+ group_name = c10d._resolve_group_name_by_ranks_and_tag(ranks, tag)
51
+ return torch.ops._c10d_functional.all_gather_into_tensor_coalesced(
52
+ input,
53
+ group_size,
54
+ group_name,
55
+ )
56
+
57
+
58
+ def _reduce_scatter_tensor(
59
+ input: torch.Tensor,
60
+ reduce_op: str,
61
+ tag: str,
62
+ ranks: list[int],
63
+ group_size: int,
64
+ ):
65
+ group_name = c10d._resolve_group_name_by_ranks_and_tag(ranks, tag)
66
+ return torch.ops._c10d_functional.reduce_scatter_tensor(
67
+ input,
68
+ reduce_op,
69
+ group_size,
70
+ group_name,
71
+ )
72
+
73
+
74
+ def _reduce_scatter_tensor_coalesced(
75
+ inputs: list[torch.Tensor],
76
+ reduce_op: str,
77
+ tag: str,
78
+ ranks: list[int],
79
+ group_size: int,
80
+ ):
81
+ group_name = c10d._resolve_group_name_by_ranks_and_tag(ranks, tag)
82
+ return torch.ops._c10d_functional.reduce_scatter_tensor_coalesced(
83
+ inputs,
84
+ reduce_op,
85
+ group_size,
86
+ group_name,
87
+ )
88
+
89
+
90
+ def _all_to_all_single(
91
+ input: torch.Tensor,
92
+ output_split_sizes: list[int] | None,
93
+ input_split_sizes: list[int] | None,
94
+ tag: str,
95
+ ranks: list[int],
96
+ group_size: int,
97
+ ):
98
+ if output_split_sizes is None or input_split_sizes is None:
99
+ if not (output_split_sizes is None and input_split_sizes is None):
100
+ raise AssertionError(
101
+ "output_split_sizes and input_split_sizes must either be "
102
+ "specified together or both set to None"
103
+ )
104
+ output_split_sizes = [input.shape[0] // group_size] * group_size
105
+ input_split_sizes = output_split_sizes
106
+
107
+ group_name = c10d._resolve_group_name_by_ranks_and_tag(ranks, tag)
108
+ return torch.ops._c10d_functional.all_to_all_single(
109
+ input,
110
+ output_split_sizes,
111
+ input_split_sizes,
112
+ group_name,
113
+ )
114
+
115
+
116
+ def _wait_tensor(tensor: torch.Tensor) -> torch.Tensor:
117
+ return torch.ops._c10d_functional.wait_tensor(tensor)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_local_tensor/__init__.py ADDED
@@ -0,0 +1,1965 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ast import Call
2
+
3
+ from torch._ops import OpOverload
4
+
5
+
6
+ """
7
+ A LocalTensor is a tensor subclass which simulates a tensor that is
8
+ distributed across SPMD ranks. A LocalTensor might be size N, but in fact
9
+ there are world_size shards/replicas of it stored internally. When you do a
10
+ plain PyTorch operation on it, we apply the operation to each shard; when you
11
+ do a collective, we do the mathematically equivalent operation on the local
12
+ shards. A LocalTensor is associated with a list of ranks which specify
13
+ which ranks it holds local tensors for.
14
+
15
+ NB, this is NOT a DataParallel like abstraction where you can run operations
16
+ on multiple different GPUs. It is intended purely for *debugging* purposes,
17
+ the overhead is almost certainly too high to keep eight GPUs (even the C++
18
+ autograd needs multithreading to keep up!) (It might potentially be possible
19
+ to trace through this with torch.compile and then compile it with CUDA graphs
20
+ but this is currently a non-goal.)
21
+
22
+ We do not directly handling MPMD. However in practice even in SPMD you may
23
+ encounter divergence in behavior per rank (for example, uneven sharding
24
+ across ranks). To support scenarios like this, we provide a helper decorator
25
+ that allows you to run a function with no side effects for each LocalTensor
26
+ shard and combine results back into LocalTensor or LocalIntNode.
27
+
28
+ NB: This is a torch dispatch Tensor subclass, as we want to assume that autograd
29
+ is SPMD, so we run it once, and dispatch the inner autograd calls to the individual
30
+ local shards.
31
+
32
+ NOTE ABOUT MESH: This subclass requires collectives that are issued to it to
33
+ respect a DeviceMesh like abstraction. The reason for this is that when
34
+ DTensor issues us a collective for a particular rank, you will be asked to do
35
+ this on a specific process group which involves some ranks. However, this
36
+ will only be for the LOCAL PG that this particular rank is participating in;
37
+ there will be a bunch of other PGs for other nodes that you don't get to see.
38
+ We need to be able to reverse engineer all of the collectives that don't
39
+ involve the current local rank here to actually issue them. This can be done
40
+ two ways: (1) looking at the participating local ranks in the PG and computing
41
+ the complement which specifies all the other collectives you have to run, or
42
+ (2) retrieving the device mesh axis corresponding to the PG for this rank, and
43
+ then running all the fibers for this.
44
+ """
45
+
46
+ import contextlib
47
+ import copy
48
+ import functools
49
+ import operator
50
+ import os
51
+ import sys
52
+ import threading
53
+ from collections import defaultdict
54
+ from collections.abc import Callable, Generator, Sequence
55
+ from types import TracebackType
56
+ from typing import Any, Optional, ParamSpec, TypeVar, Union
57
+
58
+
59
+ try:
60
+ import numpy as np
61
+
62
+ HAS_NUMPY = True
63
+ except ModuleNotFoundError:
64
+ HAS_NUMPY = False
65
+ np = None # type: ignore[assignment]
66
+
67
+ import torch
68
+ import torch.distributed as dist
69
+ from torch import Size, SymBool, SymInt, Tensor
70
+ from torch._C import DispatchKey, DispatchKeySet, ScriptObject
71
+ from torch._export.wrappers import mark_subclass_constructor_exportable_experimental
72
+ from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
73
+ from torch.distributed import DeviceMesh, ProcessGroup
74
+ from torch.distributed._functional_collectives import AsyncCollectiveTensor
75
+ from torch.distributed.distributed_c10d import _get_default_group
76
+ from torch.fx.experimental._constant_symnode import ConstantIntNode
77
+ from torch.nested._internal.nested_int import NestedIntNode
78
+ from torch.utils import _pytree as pytree
79
+ from torch.utils._mode_utils import no_dispatch
80
+ from torch.utils._python_dispatch import (
81
+ _get_current_dispatch_mode_stack,
82
+ return_and_correct_aliasing,
83
+ TorchDispatchMode,
84
+ )
85
+ from torch.utils.checkpoint import get_device_states, set_device_states
86
+
87
+
88
+ _R = TypeVar("_R")
89
+ _P = ParamSpec("_P")
90
+
91
+ not_implemented_log = torch._logging.getArtifactLogger(__name__, "not_implemented")
92
+
93
+
94
+ from . import _c10d
95
+
96
+
97
+ def _is_in_fake_tensor_mode() -> bool:
98
+ return any(
99
+ isinstance(mode, FakeTensorMode) for mode in _get_current_dispatch_mode_stack()
100
+ )
101
+
102
+
103
+ def _reduce_multidim_lists(
104
+ lists_to_reduce: list[Any], reduce_func: Callable[[list[Any]], Any]
105
+ ) -> Any:
106
+ """
107
+ Reduces a list of multi-dimensional lists, assuming they all have
108
+ the exact same shape.
109
+
110
+ Args:
111
+ lists_to_reduce (list): A list where each item is a multi-dimensional
112
+ list (e.g., [md_list_1, md_list_2, ...]).
113
+ All inner md_lists must have the same shape.
114
+ reduce_func (callable): A function that takes an iterable (list) of
115
+ values and returns a single reduced value.
116
+ For example: sum, max, min, or
117
+ lambda x: sum(x) / len(x) for mean.
118
+
119
+ Returns:
120
+ A single multi-dimensional list of the same shape as the inputs,
121
+ where each value is the result of the reduce_func.
122
+
123
+ Raises:
124
+ ValueError: If the input list is empty or if shapes are inconsistent
125
+ (which may also raise IndexError or TypeError).
126
+ """
127
+ if not lists_to_reduce:
128
+ raise ValueError("Input 'lists_to_reduce' cannot be empty.")
129
+
130
+ # Get the first list to inspect its structure (shape)
131
+ first_list = lists_to_reduce[0]
132
+
133
+ # Check if the first element of this list is *also* a list.
134
+ # This determines if we are at the base case or need to recurse.
135
+ if isinstance(first_list[0], list):
136
+ # --- RECURSIVE STEP ---
137
+ # The elements are lists, so we need to go one level deeper.
138
+
139
+ # We find the number of sub-lists from the first list.
140
+ # (e.g., for [[1,2], [3,4]], this is 2)
141
+ num_sublists = len(first_list)
142
+
143
+ result = []
144
+ # Iterate by the index of the sub-lists (e.g., i = 0, then i = 1)
145
+ for i in range(num_sublists):
146
+ # Build a new list to pass to the recursive call.
147
+ # This list will contain the i-th sublist from *each* of the
148
+ # input lists.
149
+ # e.g., if lists_to_reduce = [ L1, L2 ] and i = 0,
150
+ # this creates [ L1[0], L2[0] ]
151
+ sublists_to_reduce = [l[i] for l in lists_to_reduce]
152
+
153
+ # Recurse and append the result
154
+ result.append(_reduce_multidim_lists(sublists_to_reduce, reduce_func))
155
+ return result
156
+ else:
157
+ # --- BASE CASE ---
158
+ # The elements are values (int, float, etc.), not lists.
159
+ # We are at the innermost dimension.
160
+
161
+ # Find the number of values in the innermost list.
162
+ # (e.g., for [1, 2], this is 2)
163
+ num_values = len(first_list)
164
+
165
+ result = []
166
+ # Iterate by the index of the values (e.g., i = 0, then i = 1)
167
+ for i in range(num_values):
168
+ # Get the values at this specific position (i) from *all*
169
+ # input lists.
170
+ # e.g., if lists_to_reduce = [ [1,2], [10,20] ] and i = 0,
171
+ # this creates [ 1, 10 ]
172
+ values_at_pos = [l[i] for l in lists_to_reduce]
173
+
174
+ # Apply the user-provided reduction function to this list of values
175
+ # and append the single result.
176
+ result.append(reduce_func(values_at_pos))
177
+ return result
178
+
179
+
180
+ def _is_inplace_op(op: OpOverload | Callable[..., Any]) -> bool:
181
+ return (
182
+ isinstance(op, OpOverload)
183
+ # Not precise heuristic to detect inplace operation
184
+ and op._schema.name[-1] == "_"
185
+ # Strengthen the heuristic to check that the first argument and return value are a write
186
+ and len(op._schema.arguments) > 0
187
+ and op._schema.arguments[0].is_write
188
+ and len(op._schema.returns) > 0
189
+ and op._schema.returns[0].is_write
190
+ )
191
+
192
+
193
+ def _int_on_rank(i: "int | LocalIntNode | ConstantIntNode", r: int) -> int:
194
+ if isinstance(i, LocalIntNode):
195
+ return i._local_ints[r]
196
+ elif isinstance(i, ConstantIntNode):
197
+ return i.val
198
+ elif isinstance(i, int):
199
+ return i
200
+ else:
201
+ raise AssertionError(type(i))
202
+
203
+
204
+ def _check_for_subclass(flat_args: Sequence[object]) -> bool:
205
+ return any(_check_for_subclass_arg(x) for x in flat_args)
206
+
207
+
208
+ def _check_for_subclass_arg(x: object) -> bool:
209
+ return (
210
+ not isinstance(x, LocalTensor)
211
+ and isinstance(x, Tensor)
212
+ and type(x)
213
+ not in (
214
+ Tensor,
215
+ FakeTensor,
216
+ torch.nn.Parameter,
217
+ torch.nn.Buffer,
218
+ )
219
+ )
220
+
221
+
222
+ def _map_to_rank_local_val(val: Any, rank: int) -> Any:
223
+ if isinstance(val, LocalTensor):
224
+ return val._local_tensors[rank]
225
+ if isinstance(val, SymInt):
226
+ if isinstance(val.node, LocalIntNode):
227
+ return val.node._local_ints[rank]
228
+ if isinstance(val.node, ConstantIntNode):
229
+ return val.node.val
230
+ return val
231
+
232
+
233
+ def _collect_accelerator_rng_states() -> dict[int, torch.Tensor]:
234
+ """
235
+ Collects RNG state from all available acceleator devices.
236
+
237
+ Returns:
238
+ List of RNG state tensors, one for each accelerator device.
239
+ Returns empty list if accelerator is not available.
240
+ """
241
+ if not torch.accelerator.is_available():
242
+ return {}
243
+
244
+ if torch.accelerator.is_available():
245
+ device_idx = torch.accelerator.current_device_index()
246
+ with torch.accelerator.device_index(device_idx):
247
+ return {device_idx: torch.get_device_module().get_rng_state()}
248
+
249
+ return {}
250
+
251
+
252
+ def _set_accelerator_rng_states(rng_states: dict[int, torch.Tensor]) -> None:
253
+ """
254
+ Sets RNG state for all accelerator devices from a list of states.
255
+
256
+ Args:
257
+ rng_states: List of RNG state tensors to restore.
258
+ """
259
+ if not torch.accelerator.is_available():
260
+ return
261
+
262
+ if torch.accelerator.is_available():
263
+ for device_idx, device_rng_state in rng_states.items():
264
+ with torch.accelerator.device_index(device_idx):
265
+ torch.get_device_module().set_rng_state(device_rng_state)
266
+
267
+
268
+ def _get_rng_state() -> tuple[torch.Tensor, dict[int, torch.Tensor]]:
269
+ """
270
+ Gets CPU and accelerator (e.g., CUDA, XPU device) rng states from all devices.
271
+ """
272
+ return (torch.get_rng_state(), _collect_accelerator_rng_states())
273
+
274
+
275
+ def _set_rng_state(
276
+ cpu_state: torch.Tensor, accelerator_states: dict[int, torch.Tensor]
277
+ ) -> None:
278
+ """
279
+ Sets CPU and accelerator (e.g., CUDA, XPU device) rng states for all devices. If
280
+ the list of accelerator states is shorter than the number of devices only the
281
+ first len(accelerator_states) devices will get their rng state set.
282
+ """
283
+ torch.set_rng_state(cpu_state)
284
+ _set_accelerator_rng_states(accelerator_states)
285
+
286
+
287
+ def _combine_int_rank_results(rank_results: dict[int, int]) -> int | torch.SymInt:
288
+ any_v = next(iter(rank_results.values()))
289
+
290
+ if all(v == any_v for v in rank_results.values()):
291
+ return any_v
292
+
293
+ return torch.SymInt(LocalIntNode(rank_results))
294
+
295
+
296
+ def _combine_any_rank_results(rank_results: dict[int, Any]) -> Any:
297
+ any_v = next(iter(rank_results.values()))
298
+
299
+ if isinstance(any_v, Tensor):
300
+ # pyrefly: ignore [bad-argument-type, bad-argument-count]
301
+ return LocalTensor(rank_results)
302
+
303
+ if isinstance(any_v, int):
304
+ return _combine_int_rank_results(rank_results)
305
+
306
+ if isinstance(any_v, torch.device):
307
+ assert all(v.type == any_v.type for v in rank_results.values()), (
308
+ "device type should be the same"
309
+ )
310
+ # Just use the first device - the device type is what matters,
311
+ # and LocalTensorMode runs on a single physical device anyway
312
+ return any_v
313
+
314
+ assert all(v == any_v for v in rank_results.values()), (
315
+ "Non Tensor or int rank results must be equal for all ranks"
316
+ )
317
+
318
+ return any_v
319
+
320
+
321
+ def _combine_rank_results(rank_results: dict[int, Any], default: Any | None) -> Any:
322
+ rank_ids = rank_results.keys()
323
+ rank_value = rank_results[next(iter(rank_ids))]
324
+
325
+ if isinstance(rank_value, (list, tuple)):
326
+ max_rank_result_len = max(len(v) for v in rank_results.values())
327
+ ret_list = []
328
+ for i in range(max_rank_result_len):
329
+ rank_col_results = {
330
+ r: v[i] if i < len(v) else default for r, v in rank_results.items()
331
+ }
332
+ ret_list.append(_combine_any_rank_results(rank_col_results))
333
+ return type(rank_value)(ret_list)
334
+ else:
335
+ return _combine_any_rank_results(rank_results)
336
+
337
+
338
+ def _zero_sized_like(tensor: torch.Tensor, dim: int) -> torch.Tensor:
339
+ tensor_size = list(tensor.size())
340
+ tensor_size[dim] = 0
341
+ empty_tensor = torch.empty(*tensor_size, dtype=tensor.dtype, device=tensor.device)
342
+ return empty_tensor
343
+
344
+
345
+ def _for_each_rank_run_func(
346
+ func: OpOverload | Callable[..., Any],
347
+ ranks: frozenset[int],
348
+ args: Sequence[Any],
349
+ kwargs: dict[str, Any],
350
+ *,
351
+ alias: bool = True,
352
+ ) -> Any:
353
+ flat_args, args_spec = pytree.tree_flatten((args, kwargs))
354
+ flat_args = [
355
+ a.wait() if isinstance(a, AsyncCollectiveTensor) else a for a in flat_args
356
+ ]
357
+
358
+ lm = enabled_local_tensor_mode()
359
+ use_per_rank_rng = lm is not None and len(lm._per_rank_rng_states) > 0
360
+
361
+ global_rng_state = None if use_per_rank_rng else _get_rng_state()
362
+
363
+ flat_rank_rets = {}
364
+
365
+ default_value: Tensor | None = None
366
+ for r in sorted(ranks):
367
+ if use_per_rank_rng:
368
+ assert lm is not None
369
+ if r in lm._per_rank_rng_states:
370
+ _set_rng_state(*lm._per_rank_rng_states[r])
371
+ else:
372
+ assert global_rng_state is not None
373
+ _set_rng_state(*global_rng_state)
374
+
375
+ rank_flat_args = [_map_to_rank_local_val(a, r) for a in flat_args]
376
+ rank_args, rank_kwargs = pytree.tree_unflatten(rank_flat_args, args_spec)
377
+ if func is torch.ops.aten.hash_tensor.default and rank_args[0].numel() == 0:
378
+ # Special case for empty tensors, hash_tensor returns an empty tensor
379
+ rank_ret = torch.empty(0, dtype=torch.uint64, device=rank_args[0].device)
380
+ else:
381
+ rank_ret = func(*rank_args, **rank_kwargs)
382
+ flat_rank_rets[r] = rank_ret
383
+
384
+ if use_per_rank_rng:
385
+ assert lm is not None
386
+ lm._per_rank_rng_states[r] = _get_rng_state()
387
+
388
+ if default_value is None and func is torch.ops.aten.split.Tensor:
389
+ # If split happens over the dimension smaller than the number of chunks
390
+ # it is possible that some ranks will produce shorter lists of chunks.
391
+ # In order to make the result across all ranks of the same length we
392
+ # append empty tensors (zero size on the split dimension).
393
+ tensor = rank_flat_args[0]
394
+ split_dim = 0 if len(rank_flat_args) < 3 else rank_flat_args[2]
395
+ default_value = _zero_sized_like(tensor, split_dim)
396
+
397
+ if _is_inplace_op(func):
398
+ alias = False
399
+ # For the in-place ops return self
400
+ ret = args[0]
401
+ if isinstance(func, OpOverload) and torch.Tag.inplace_view in func.tags:
402
+ # Ensure that wrapper tensor size is synchronized with its local tensors
403
+ ret._sync_meta()
404
+ else:
405
+ ret = _combine_rank_results(flat_rank_rets, default_value)
406
+
407
+ if alias:
408
+ return return_and_correct_aliasing(func, args, kwargs, ret)
409
+ else:
410
+ return ret
411
+
412
+
413
+ def _get_extra_dispatch_keys(t: torch.Tensor) -> DispatchKeySet:
414
+ extra_dispatch_keys = torch._C.DispatchKeySet.from_raw_repr(0)
415
+ if torch._C._dispatch_keys(t).has(torch._C.DispatchKey.Conjugate):
416
+ extra_dispatch_keys = extra_dispatch_keys.add(torch._C.DispatchKey.Conjugate)
417
+ if torch._C._dispatch_keys(t).has(torch._C.DispatchKey.Negative):
418
+ extra_dispatch_keys = extra_dispatch_keys.add(torch._C.DispatchKey.Negative)
419
+ return extra_dispatch_keys
420
+
421
+
422
+ class LocalIntNode:
423
+ """
424
+ Like a LocalTensor, but for an int. We can't use a 0D tensor to represent this
425
+ because often only a SymInt is accepted where we wish to use this.
426
+ """
427
+
428
+ def __new__(cls, local_ints: dict[int, int]) -> "ConstantIntNode | LocalIntNode": # type: ignore[misc]
429
+ if len(set(local_ints.values())) == 1:
430
+ return ConstantIntNode(next(iter(local_ints.values())))
431
+ return super().__new__(cls)
432
+
433
+ def __init__(self, local_ints: dict[int, int]):
434
+ self._local_ints = local_ints
435
+
436
+ def maybe_as_int(self) -> int | None:
437
+ return None
438
+
439
+ def is_int(self) -> bool:
440
+ return True
441
+
442
+ def is_float(self) -> bool:
443
+ return False
444
+
445
+ def is_bool(self) -> bool:
446
+ return False
447
+
448
+ def is_nested_int(self) -> bool:
449
+ return False
450
+
451
+ def clone(self) -> "LocalIntNode":
452
+ return self
453
+
454
+ def _str(self) -> str:
455
+ return f"LocalIntNode({self._local_ints})"
456
+
457
+ def __str__(self) -> str:
458
+ return self._str()
459
+
460
+ def __repr__(self) -> str:
461
+ return self._str()
462
+
463
+ def _graph_repr(self) -> str:
464
+ return self._str()
465
+
466
+ def is_symbolic(self) -> bool:
467
+ return False
468
+
469
+ def is_constant(self) -> bool:
470
+ return False
471
+
472
+ def sym_max(
473
+ self, other: "int | LocalIntNode | ConstantIntNode"
474
+ ) -> "LocalIntNode | ConstantIntNode":
475
+ return LocalIntNode(
476
+ {
477
+ r: max(self._local_ints[r], _int_on_rank(other, r))
478
+ for r in self._local_ints
479
+ }
480
+ )
481
+
482
+ def sym_sum(self, other: Any) -> "LocalIntNode | ConstantIntNode":
483
+ t = LocalIntNode(dict.fromkeys(self._local_ints, 0))
484
+ for o in other:
485
+ t = t.add(o)
486
+ return t
487
+
488
+ def neg(self) -> "LocalIntNode | ConstantIntNode":
489
+ return LocalIntNode({r: -self._local_ints[r] for r in self._local_ints})
490
+
491
+ def add(
492
+ self, other: "int | LocalIntNode | ConstantIntNode"
493
+ ) -> "LocalIntNode | ConstantIntNode":
494
+ return LocalIntNode(
495
+ {r: self._local_ints[r] + _int_on_rank(other, r) for r in self._local_ints}
496
+ )
497
+
498
+ def sub(
499
+ self, other: "int | LocalIntNode | ConstantIntNode"
500
+ ) -> "LocalIntNode | ConstantIntNode":
501
+ return LocalIntNode(
502
+ {r: self._local_ints[r] - _int_on_rank(other, r) for r in self._local_ints}
503
+ )
504
+
505
+ def mul(
506
+ self, other: "int | LocalIntNode | ConstantIntNode"
507
+ ) -> "LocalIntNode | ConstantIntNode":
508
+ return LocalIntNode(
509
+ {r: self._local_ints[r] * _int_on_rank(other, r) for r in self._local_ints}
510
+ )
511
+
512
+ def floordiv(
513
+ self, other: "int | LocalIntNode | ConstantIntNode"
514
+ ) -> "LocalIntNode | ConstantIntNode":
515
+ return LocalIntNode(
516
+ {r: self._local_ints[r] // _int_on_rank(other, r) for r in self._local_ints}
517
+ )
518
+
519
+ def mod(
520
+ self, other: "int | LocalIntNode | ConstantIntNode"
521
+ ) -> "LocalIntNode | ConstantIntNode":
522
+ return LocalIntNode(
523
+ {r: self._local_ints[r] % _int_on_rank(other, r) for r in self._local_ints}
524
+ )
525
+
526
+ def int_floordiv(
527
+ self, other: "int | LocalIntNode | ConstantIntNode"
528
+ ) -> "LocalIntNode | ConstantIntNode":
529
+ return LocalIntNode(
530
+ {r: self._local_ints[r] // _int_on_rank(other, r) for r in self._local_ints}
531
+ )
532
+
533
+ def eq(self, other: "int | LocalIntNode | ConstantIntNode") -> bool | SymBool:
534
+ r = {self._local_ints[r] == _int_on_rank(other, r) for r in self._local_ints}
535
+ return torch._C._get_constant_bool_symnode(len(r) == 1 and next(iter(r)))
536
+
537
+ def ne(self, other: "int | LocalIntNode | ConstantIntNode") -> bool | SymBool:
538
+ r = {self._local_ints[r] != _int_on_rank(other, r) for r in self._local_ints}
539
+ return torch._C._get_constant_bool_symnode(len(r) > 1 or next(iter(r)))
540
+
541
+ def ge(self, other: "int | LocalIntNode | ConstantIntNode") -> bool | SymBool:
542
+ r = {self._local_ints[r] >= _int_on_rank(other, r) for r in self._local_ints}
543
+ assert len(r) == 1, (self, other)
544
+ return torch._C._get_constant_bool_symnode(next(iter(r)))
545
+
546
+ def gt(self, other: "int | LocalIntNode | ConstantIntNode") -> bool | SymBool:
547
+ r = {self._local_ints[r] > _int_on_rank(other, r) for r in self._local_ints}
548
+ assert len(r) == 1, (self, other)
549
+ return torch._C._get_constant_bool_symnode(next(iter(r)))
550
+
551
+ def lt(self, other: "int | LocalIntNode | ConstantIntNode") -> bool | SymBool:
552
+ r = {self._local_ints[r] < _int_on_rank(other, r) for r in self._local_ints}
553
+ assert len(r) == 1, (self, other)
554
+ return torch._C._get_constant_bool_symnode(next(iter(r)))
555
+
556
+ def wrap_int(self, num: int) -> "LocalIntNode | ConstantIntNode":
557
+ return ConstantIntNode(num)
558
+
559
+
560
+ class _LocalDeviceHandle:
561
+ """
562
+ Wrapper around device module (e.g., torch.cuda) with automatic LocalTensor semantics.
563
+
564
+ This class wraps device modules and automatically handles per-rank operations in
565
+ LocalTensor mode:
566
+ - get_rng_state() returns a LocalTensor with per-rank states
567
+ - set_rng_state(LocalTensor) sets per-rank states
568
+
569
+ When not in LocalTensor mode, it delegates directly to the underlying device handle.
570
+ """
571
+
572
+ def __init__(self, device_handle, device_type: str):
573
+ """
574
+ Initialize the local device handle wrapper.
575
+
576
+ Args:
577
+ device_handle: The underlying device module (e.g., torch.cuda)
578
+ device_type: Device type string (e.g., "cuda", "cpu")
579
+ """
580
+ self._device_handle = device_handle
581
+ self._device_type = device_type
582
+
583
+ def get_rng_state(self):
584
+ """
585
+ Get RNG state, automatically returning LocalTensor in LocalTensor mode.
586
+
587
+ Returns:
588
+ LocalTensor in LocalTensor mode, regular Tensor otherwise
589
+ """
590
+ lm = enabled_local_tensor_mode()
591
+ if not lm:
592
+ return self._device_handle.get_rng_state()
593
+
594
+ original_state = _get_rng_state()
595
+ per_rank_states = {}
596
+
597
+ try:
598
+ for rank in lm.ranks:
599
+ # We need to set-then-get instead of directly copying lm._per_rank_rng_states[rank]
600
+ # because they have different structures:
601
+ # - lm._per_rank_rng_states[rank] is a tuple: (cpu_state, {device_idx: cuda_state})
602
+ # - self._device_handle.get_rng_state() returns just the device-specific tensor
603
+ # So we temporarily restore the full RNG state (CPU + all CUDA devices) for this rank,
604
+ # then extract only the specific device's state tensor that we need.
605
+ if rank in lm._per_rank_rng_states:
606
+ _set_rng_state(*lm._per_rank_rng_states[rank])
607
+
608
+ per_rank_states[rank] = self._device_handle.get_rng_state()
609
+ finally:
610
+ _set_rng_state(*original_state)
611
+
612
+ # pyrefly: ignore [bad-argument-type, bad-argument-count]
613
+ return LocalTensor(per_rank_states)
614
+
615
+ def set_rng_state(self, state):
616
+ """
617
+ Set RNG state, automatically handling LocalTensor input.
618
+
619
+ Args:
620
+ state: Regular Tensor or LocalTensor with per-rank states
621
+ """
622
+ if isinstance(state, LocalTensor):
623
+ lm = enabled_local_tensor_mode()
624
+ assert lm is not None
625
+
626
+ # Similar to get_rng_state but in reverse: we need to convert from
627
+ # device-specific tensor format to full state tuple format.
628
+ # - state._local_tensors[rank] contains just the device-specific RNG state tensor
629
+ # - lm._per_rank_rng_states[rank] needs a tuple: (cpu_state, {device_idx: cuda_state})
630
+ # So we set the device's state with the rank-specific tensor, then _get_rng_state()
631
+ # captures both CPU and CUDA states into the tuple format that _per_rank_rng_states expects.
632
+ for rank, rank_state in state._local_tensors.items():
633
+ self._device_handle.set_rng_state(rank_state.to("cpu"))
634
+ lm._per_rank_rng_states[rank] = _get_rng_state()
635
+ else:
636
+ self._device_handle.set_rng_state(state.to("cpu"))
637
+
638
+ def __getattr__(self, name):
639
+ """Delegate all other attributes to the underlying device module."""
640
+ return getattr(self._device_handle, name)
641
+
642
+
643
+ class _LocalOffsetBasedRNGTracker:
644
+ """
645
+ LocalTensor-specific RNG tracker for DTensor random operations.
646
+
647
+ This class manages per-rank RNG states when running in LocalTensor mode,
648
+ using _LocalPhiloxState to track different offsets for each virtual rank.
649
+ It is instantiated and used by OffsetBasedRNGTracker when in LocalTensor mode.
650
+
651
+ Much of this is derived from OffsetBasedRNGTracker:
652
+ https://github.com/pytorch/pytorch/blob/402c46503002f98ccfc023a733081fb0719223a1/torch/distributed/tensor/_random.py#L182
653
+ """
654
+
655
+ def __init__(self, device_type: str = "cuda"):
656
+ """Initialize the LocalTensor RNG tracker."""
657
+ from torch.distributed.device_mesh import _get_device_handle
658
+
659
+ self._device_type = device_type
660
+ self._device_handle = _LocalDeviceHandle(
661
+ _get_device_handle(device_type), device_type
662
+ )
663
+ self.distribute_region_enabled = True
664
+ self._device_mesh = None
665
+
666
+ @property
667
+ def _device(self):
668
+ return torch.device(self._device_type, torch.cuda.current_device())
669
+
670
+ def _set_pre_op_offset(self, state, spec) -> None:
671
+ """Compute and set per-rank offsets before the random operation."""
672
+ from torch.distributed.tensor._ops.utils import prod
673
+ from torch.distributed.tensor._utils import (
674
+ _compute_local_shape_and_global_offset,
675
+ )
676
+ from torch.distributed.tensor.placement_types import Shard
677
+
678
+ lm = enabled_local_tensor_mode()
679
+ assert lm is not None
680
+
681
+ state._per_rank_offsets = {}
682
+
683
+ for rank in lm.ranks:
684
+ # compute this rank's coordinate in the mesh
685
+ mesh_coords = []
686
+ for mesh_dim_idx in range(spec.mesh.ndim):
687
+ mesh_dim_size = spec.mesh.size(mesh_dim_idx)
688
+ # calculate rank's coordinate in this mesh dimension
689
+ num_chunks_after = 1
690
+ for j in range(mesh_dim_idx + 1, spec.mesh.ndim):
691
+ num_chunks_after *= spec.mesh.size(j)
692
+ coord = (rank // num_chunks_after) % mesh_dim_size
693
+ mesh_coords.append(coord)
694
+
695
+ # compute shard offset based on placements
696
+ from torch.distributed.tensor._random import (
697
+ _calc_first_shard_size,
698
+ _calc_shard_info,
699
+ _calc_shard_linear_idx,
700
+ )
701
+
702
+ # Compute shard index and total number of shards on each tensor dim
703
+ shard_idx_by_dim, total_num_shards_by_dim = _calc_shard_info(
704
+ mesh_coords, spec
705
+ )
706
+
707
+ # compute shard linear index
708
+ shard_linear_idx = _calc_shard_linear_idx(
709
+ shard_idx_by_dim, total_num_shards_by_dim
710
+ )
711
+
712
+ # get current offset for this rank
713
+ current_offset = int(
714
+ state._per_rank_states[rank][8:].view(dtype=torch.int64).item()
715
+ )
716
+
717
+ local_shape = _calc_first_shard_size(spec)
718
+ # compute local size
719
+ local_size = prod(local_shape)
720
+
721
+ # compute new offset (must be multiple of 4)
722
+ offset_incr = (shard_linear_idx * local_size + 3) // 4 * 4
723
+ state._per_rank_offsets[rank] = current_offset + offset_incr
724
+
725
+ def _set_post_op_offset(self, state, spec, old_offset) -> None:
726
+ """Set per-rank offsets after the random operation."""
727
+ from torch.distributed.tensor._ops.utils import prod
728
+
729
+ lm = enabled_local_tensor_mode()
730
+ assert lm is not None
731
+
732
+ dtensor_shape = spec.shape
733
+ numel = prod(dtensor_shape)
734
+ # offset must be multiple of 4
735
+ numel = (numel + 3) // 4 * 4
736
+
737
+ if not hasattr(state, "_per_rank_offsets"):
738
+ state._per_rank_offsets = {}
739
+
740
+ # handle LocalIntNode old_offset (different values per rank)
741
+ if isinstance(old_offset, SymInt) and isinstance(old_offset.node, LocalIntNode):
742
+ for rank in lm.ranks:
743
+ rank_old_offset = old_offset.node._local_ints[rank]
744
+ state._per_rank_offsets[rank] = rank_old_offset + numel
745
+ else:
746
+ # same old_offset for all ranks
747
+ old_offset_int = (
748
+ int(old_offset) if isinstance(old_offset, SymInt) else old_offset
749
+ )
750
+ for rank in lm.ranks:
751
+ state._per_rank_offsets[rank] = old_offset_int + numel
752
+
753
+ @contextlib.contextmanager
754
+ def _distribute_region(self, spec, generator=None):
755
+ """Context manager for LocalTensor mode distribute region."""
756
+ lm = enabled_local_tensor_mode()
757
+ assert lm is not None
758
+
759
+ # get base state
760
+ if generator is not None:
761
+ base_state_tensor = generator.get_state()
762
+ per_rank_states = {rank: base_state_tensor.clone() for rank in lm.ranks}
763
+ # pyrefly: ignore [bad-argument-type, bad-argument-count]
764
+ base_state_tensor = LocalTensor(per_rank_states)
765
+ else:
766
+ base_state_tensor = self._device_handle.get_rng_state()
767
+
768
+ state = _LocalPhiloxState(base_state_tensor)
769
+
770
+ if self.distribute_region_enabled:
771
+ # sync to rank 0's state if no explicit generator
772
+ if generator is None:
773
+ any_rank_state = lm._any_local_rng_state()
774
+ any_rank_cpu, any_rank_cuda = any_rank_state
775
+
776
+ if self._device.type == "cuda":
777
+ assert self._device.index in any_rank_cuda
778
+ any_rank_device_state = any_rank_cuda[self._device.index]
779
+ else:
780
+ any_rank_device_state = any_rank_cpu
781
+
782
+ from torch.distributed.tensor._random import _PhiloxState
783
+
784
+ any_rank_philox = _PhiloxState(any_rank_device_state)
785
+ state.seed = any_rank_philox.seed
786
+ state.offset = any_rank_philox.offset
787
+
788
+ old_offset = state.offset
789
+ self._set_pre_op_offset(state, spec)
790
+ state.apply_to_local_tensor_mode(self._device_handle)
791
+
792
+ try:
793
+ yield
794
+ finally:
795
+ self._set_post_op_offset(state, spec, old_offset)
796
+ state.apply_to_local_tensor_mode(self._device_handle)
797
+ else:
798
+ yield
799
+
800
+ # maybe reset generator to rank 0's state
801
+ if generator is not None:
802
+ rank_0_state = state._per_rank_states[0]
803
+ generator.set_state(rank_0_state)
804
+
805
+
806
+ _LOCAL_TENSOR_ATTR_PREFIX = "_local_tensor_"
807
+
808
+
809
+ def _is_local_tensor_attr(attr: str) -> bool:
810
+ return attr.startswith(_LOCAL_TENSOR_ATTR_PREFIX)
811
+
812
+
813
+ def _to_local_tensor_attr(rank: int) -> str:
814
+ return f"{_LOCAL_TENSOR_ATTR_PREFIX}{rank}"
815
+
816
+
817
+ def _from_local_tensor_attr(attr: str) -> int:
818
+ if not _is_local_tensor_attr(attr):
819
+ raise AssertionError(f"Invalid local tensor attr {attr}")
820
+ return int(attr[len(_LOCAL_TENSOR_ATTR_PREFIX) :])
821
+
822
+
823
+ def _all_elements_same(values: list[Any]) -> bool:
824
+ if not values:
825
+ return True
826
+ first_value = values[0]
827
+ return all(value == first_value for value in values)
828
+
829
+
830
+ def _compute_local_tensor_meta(
831
+ local_tensors: dict[int, torch.Tensor],
832
+ ) -> tuple[
833
+ list[torch.SymInt | int],
834
+ list[torch.SymInt | int],
835
+ torch.device,
836
+ torch.dtype,
837
+ torch.layout,
838
+ DispatchKeySet,
839
+ ]:
840
+ """
841
+ Computes the meta information for a LocalTensor from its local tensors.
842
+ """
843
+ it = iter(local_tensors.values())
844
+ first_local_tensor = next(it)
845
+
846
+ first_shape = first_local_tensor.shape
847
+ first_stride = first_local_tensor.stride()
848
+ dtype = first_local_tensor.dtype
849
+ device = first_local_tensor.device
850
+ layout = first_local_tensor.layout
851
+
852
+ extra_dispatch_keys = _get_extra_dispatch_keys(first_local_tensor)
853
+
854
+ # Assert that all tensors have the same dtype, layout and dispatch keys. Due
855
+ # to uneven sharding, it is possible that tensors will have different shapes.
856
+ for local_tensor in it:
857
+ assert dtype == local_tensor.dtype, (
858
+ "Tensors representing LocalTensor shards must have the same dtype"
859
+ )
860
+ assert layout == local_tensor.layout, (
861
+ "Tensors representing LocalTensor shards must have the same layout"
862
+ )
863
+ assert extra_dispatch_keys == _get_extra_dispatch_keys(local_tensor), (
864
+ "Tensors representing LocalTensor shards must have the same set of extra dispatch keys"
865
+ )
866
+
867
+ # Compute shape/stride. We allow for non-SPMD'ness here
868
+ local_shapes: dict[int, dict[int, int]] = defaultdict(dict) # dim => rank => size
869
+ local_strides: dict[int, dict[int, int]] = defaultdict(dict) # dim => rank => size
870
+ for r, local_tensor in local_tensors.items():
871
+ for d, size in enumerate(local_tensor.shape):
872
+ local_shapes[d][r] = size
873
+ local_strides[d][r] = local_tensor.stride(d)
874
+ shape = [
875
+ (
876
+ first_shape[d]
877
+ if _all_elements_same(list(local_shapes[d].values()))
878
+ else torch.SymInt(LocalIntNode(local_shapes[d]))
879
+ )
880
+ for d in range(len(first_shape))
881
+ ]
882
+ strides = [
883
+ (
884
+ first_stride[d]
885
+ if _all_elements_same(list(local_strides[d].values()))
886
+ else torch.SymInt(LocalIntNode(local_strides[d]))
887
+ )
888
+ for d in range(len(first_shape))
889
+ ]
890
+ return shape, strides, device, dtype, layout, extra_dispatch_keys
891
+
892
+
893
+ class LocalTensor(torch.Tensor):
894
+ """
895
+ LocalTensor is a Tensor subclass that simulates a tensor distributed across multiple SPMD
896
+ (Single Program, Multiple Data) ranks. Each LocalTensor instance internally holds a mapping from
897
+ global rank ids to their corresponding local Tensor shards.Operations performed on a LocalTensor
898
+ are applied independently to each local shard, mimicking distributed computation. Collectives
899
+ and other distributed operations are handled by mapping them to the local shards as appropriate.
900
+
901
+ Note:
902
+ This class is primarily intended for debugging and simulating distributed tensor computations
903
+ on a single process.
904
+
905
+ """
906
+
907
+ # Map from global rank to the local tensor.
908
+ _local_tensors: dict[int, torch.Tensor]
909
+ # Precomputed for speed set of keys from the local tensor map.
910
+ _ranks: frozenset[int]
911
+ _size: list[torch.SymInt | int]
912
+ __slots__ = ["_local_tensors", "_ranks", "_size"]
913
+
914
+ @staticmethod
915
+ @torch._disable_dynamo
916
+ def __new__(
917
+ cls,
918
+ local_tensors: dict[int, torch.Tensor],
919
+ requires_grad: bool = False,
920
+ ) -> "LocalTensor":
921
+ if any(t.requires_grad for t in local_tensors.values()):
922
+ raise AssertionError(
923
+ "Internal local_tensors require grad, but we will ignore those autograd graph. "
924
+ "Make a custom autograd function and make sure you detach the inner tensors."
925
+ )
926
+
927
+ (shape, strides, device, dtype, layout, extra_dispatch_keys) = (
928
+ _compute_local_tensor_meta(local_tensors)
929
+ )
930
+
931
+ r = torch.Tensor._make_wrapper_subclass(
932
+ cls,
933
+ shape,
934
+ strides=strides,
935
+ dtype=dtype,
936
+ device=device,
937
+ layout=layout,
938
+ # In place ops potentially change local tensor sizes (e.g. resize_). While
939
+ # executing an in-place op the return value must be the same as "self" input
940
+ # otherwise we can introduce errors due to tensor identity changes. Hence we
941
+ # need to be able to update wrapper subclass sizes after in-place ops. This
942
+ # dispatch policy allows us to do that.
943
+ dispatch_sizes_strides_policy="sizes",
944
+ requires_grad=requires_grad,
945
+ _extra_dispatch_keys=extra_dispatch_keys,
946
+ )
947
+
948
+ local_tensors = {
949
+ r: v if not isinstance(v, AsyncCollectiveTensor) else v.wait()
950
+ for r, v in local_tensors.items()
951
+ }
952
+ r._local_tensors = local_tensors
953
+ r._ranks = frozenset(local_tensors.keys())
954
+ r._size = shape
955
+ return r
956
+
957
+ @torch._disable_dynamo
958
+ @mark_subclass_constructor_exportable_experimental # type: ignore[misc]
959
+ def __init__(self, *args: Any, **kwargs: Any):
960
+ super().__init__()
961
+
962
+ def __deepcopy__(self, memo: dict[Any, Any] | None) -> "LocalTensor":
963
+ local_tensors_copy = {
964
+ r: copy.deepcopy(t, memo) for r, t in self._local_tensors.items()
965
+ }
966
+ # pyrefly: ignore [bad-argument-type, bad-argument-count]
967
+ return LocalTensor(local_tensors_copy, self.requires_grad)
968
+
969
+ def __repr__(self) -> str: # type: ignore[override]
970
+ parts = []
971
+ for k, v in self._local_tensors.items():
972
+ # pyrefly: ignore [bad-argument-type]
973
+ parts.append(f" {k}: {v}")
974
+ tensors_str = ",\n".join(parts)
975
+ return f"LocalTensor(\n{tensors_str}\n)"
976
+
977
+ def __getattr__(self, name: str) -> Any:
978
+ if _is_local_tensor_attr(name):
979
+ rank = _from_local_tensor_attr(name)
980
+ if rank not in self._ranks:
981
+ raise AttributeError(f"Local tensor has no knowledge of rank {rank}")
982
+ return self._local_tensors[rank]
983
+ return object.__getattribute__(self, name)
984
+
985
+ def __tensor_flatten__(self) -> tuple[list[str], tuple[Any, ...]]:
986
+ """
987
+ protocol to inform how to flatten a DTensor to local tensor
988
+ for PT2 tracing
989
+ """
990
+ local_tensor_attrs = [_to_local_tensor_attr(r) for r in self._ranks]
991
+ return local_tensor_attrs, ()
992
+
993
+ @staticmethod
994
+ def __tensor_unflatten__(
995
+ inner_tensors: dict[str, Any],
996
+ flatten_spec: tuple[Any, ...],
997
+ outer_size: torch.Size,
998
+ outer_stride: tuple[int, ...],
999
+ ) -> "LocalTensor":
1000
+ assert flatten_spec is not None, (
1001
+ "Expecting spec to be not None from `__tensor_flatten__` return value!"
1002
+ )
1003
+ local_tensors = {
1004
+ _from_local_tensor_attr(a): t for a, t in inner_tensors.items()
1005
+ }
1006
+ # pyrefly: ignore [bad-argument-type, bad-argument-count]
1007
+ return LocalTensor(local_tensors)
1008
+
1009
+ @classmethod
1010
+ @torch._disable_dynamo
1011
+ def __torch_dispatch__( # type: ignore[override]
1012
+ cls,
1013
+ func: Any,
1014
+ types: tuple[Any, ...],
1015
+ args: tuple[Any, ...] = (),
1016
+ kwargs: dict[str, Any] | None = None,
1017
+ ) -> Any:
1018
+ if kwargs is None:
1019
+ kwargs = {}
1020
+
1021
+ # This is horribly inefficient
1022
+ flat_args, args_spec = pytree.tree_flatten((args, kwargs))
1023
+ local_tensor = None
1024
+ for arg in flat_args:
1025
+ if isinstance(arg, LocalTensor):
1026
+ local_tensor = arg
1027
+ break
1028
+
1029
+ assert local_tensor is not None, (
1030
+ "At least one of the arguments must be a LocalTensor"
1031
+ )
1032
+
1033
+ # Check for unrecognized tensor subclasses (but allow regular tensors and scalars)
1034
+ has_unrecognized_types = _check_for_subclass(flat_args)
1035
+ if has_unrecognized_types:
1036
+ unrecognized_types = [
1037
+ type(x) for x in flat_args if _check_for_subclass_arg(x)
1038
+ ]
1039
+ not_implemented_log.debug(
1040
+ "LocalTensor unrecognized subclass(es): %s", unrecognized_types
1041
+ )
1042
+ return NotImplemented
1043
+
1044
+ with LocalTensorMode(local_tensor._ranks):
1045
+ return func(*args, **kwargs)
1046
+
1047
+ def numpy(self, *, force: bool = False) -> Any:
1048
+ if HAS_NUMPY:
1049
+ return self.reconcile().numpy(force=force)
1050
+ else:
1051
+ raise RuntimeError("Numpy is not available")
1052
+
1053
+ def contiguous(
1054
+ self,
1055
+ memory_format: torch.memory_format = torch.contiguous_format,
1056
+ ) -> torch.Tensor:
1057
+ # pyrefly: ignore [bad-argument-type]
1058
+ return LocalTensor(
1059
+ # pyrefly: ignore [bad-argument-count]
1060
+ {
1061
+ r: t.contiguous(memory_format=memory_format)
1062
+ for r, t in self._local_tensors.items()
1063
+ }
1064
+ )
1065
+
1066
+ def is_contiguous(
1067
+ self,
1068
+ memory_format: torch.memory_format = torch.contiguous_format,
1069
+ ) -> bool:
1070
+ return all(
1071
+ t.is_contiguous(memory_format=memory_format)
1072
+ for t in self._local_tensors.values()
1073
+ )
1074
+
1075
+ def tolist(self) -> list[Any]:
1076
+ """
1077
+ Try to reconcile, if successful convert to list, otherwise if dtype is integer,
1078
+ convert to list of local integers.
1079
+ """
1080
+ equal_obj = self._equal_local_tensors()
1081
+ if isinstance(equal_obj, torch.Tensor):
1082
+ return equal_obj.tolist()
1083
+ if isinstance(equal_obj, torch.Size):
1084
+ if not self.dtype.is_floating_point and not self.dtype.is_complex:
1085
+ ranks = sorted(self._ranks)
1086
+ local_lists = [self._local_tensors[r].tolist() for r in ranks]
1087
+ return _reduce_multidim_lists(
1088
+ local_lists,
1089
+ lambda values: torch.SymInt(
1090
+ LocalIntNode(dict(zip(ranks, values, strict=True)))
1091
+ ),
1092
+ )
1093
+
1094
+ raise RuntimeError("Cannot convert local tensor to list")
1095
+
1096
+ def reconcile(self) -> torch.Tensor:
1097
+ """
1098
+ Reconciles the LocalTensor into a single torch.Tensor by ensuring all local
1099
+ shards are identical and returning a detached clone of one of them.
1100
+
1101
+ Note:
1102
+ This method is useful for extracting a representative tensor from a LocalTensor
1103
+ when all shards are expected to be the same, such as after a collective operation
1104
+ that synchronizes all ranks.
1105
+ """
1106
+
1107
+ # Force all local tensor shards across ranks to be the same
1108
+ equal_obj = self._equal_local_tensors()
1109
+ assert isinstance(equal_obj, torch.Tensor), (
1110
+ "LocalTensor shards must be the same to reconcile"
1111
+ )
1112
+ cl = equal_obj.clone().detach()
1113
+ cl.requires_grad_(self.requires_grad)
1114
+ return cl
1115
+
1116
+ def _equal_local_tensors(self) -> torch.Tensor | torch.Size | None:
1117
+ it = iter(self._local_tensors.values())
1118
+ t1 = next(it)
1119
+ if all(t2.equal(t1) for t2 in it):
1120
+ return t1
1121
+ if all(t2.shape == t1.shape for t2 in it):
1122
+ return t1.shape
1123
+ return None
1124
+
1125
+ def _sync_meta(self) -> None:
1126
+ with no_dispatch():
1127
+ (shape, strides, device, dtype, layout, extra_dispatch_keys) = (
1128
+ _compute_local_tensor_meta(self._local_tensors)
1129
+ )
1130
+ self._size = shape
1131
+
1132
+
1133
+ # If set to `True` the LocalTensorMode stack will be created for the whole process,
1134
+ # otherwise it will be created for each thread.
1135
+ _PROCESS_MODE: bool = True
1136
+ _PROCESS_LOCAL_TENSOR_MODE: list["LocalTensorMode"] = []
1137
+ # When running under local runner each thread must create its own local tensor mode
1138
+ # so that they do not interfere with each other.
1139
+ _THREAD_LOCAL_TENSOR_MODE: threading.local = threading.local()
1140
+
1141
+
1142
+ def get_local_tensor_mode_list() -> list["LocalTensorMode"]:
1143
+ global _PROCESS_MODE
1144
+ if _PROCESS_MODE:
1145
+ global _PROCESS_LOCAL_TENSOR_MODE
1146
+ return _PROCESS_LOCAL_TENSOR_MODE
1147
+ global _THREAD_LOCAL_TENSOR_MODE
1148
+ if not hasattr(_THREAD_LOCAL_TENSOR_MODE, "value"):
1149
+ _THREAD_LOCAL_TENSOR_MODE.value = []
1150
+ return _THREAD_LOCAL_TENSOR_MODE.value
1151
+
1152
+
1153
+ class LocalTensorMode(TorchDispatchMode):
1154
+ """
1155
+ A TorchDispatchMode that simulates SPMD (Single Program, Multiple Data) execution
1156
+ for LocalTensor objects across a set of ranks.
1157
+
1158
+ LocalTensorMode enables PyTorch operations to be transparently applied to each
1159
+ local shard of a LocalTensor, as if they were distributed across multiple ranks.
1160
+ When active, this mode intercepts tensor operations and dispatches them to each
1161
+ rank's local tensor, collecting and wrapping the results as LocalTensors. It also
1162
+ handles collective operations by mapping them to local implementations.
1163
+
1164
+ This mode is primarily intended for debugging and simulating distributed tensor
1165
+ computations on a single process, rather than for high-performance distributed
1166
+ training. It maintains a stack of active modes, patches DeviceMesh coordinate
1167
+ resolution, and provides utilities for temporarily disabling the mode or mapping
1168
+ functions over ranks.
1169
+ """
1170
+
1171
+ # What ranks this local tensor mode is operating over
1172
+ def __init__(self, ranks: int | frozenset[int]):
1173
+ if isinstance(ranks, int):
1174
+ # assume is world size
1175
+ self.ranks = frozenset(range(ranks))
1176
+ else:
1177
+ assert isinstance(ranks, frozenset)
1178
+ self.ranks = ranks
1179
+ self._disable = True
1180
+ self._old_get_coordinate = None
1181
+ self._old_get_rank = None
1182
+ self._old_get_local_rank = None
1183
+ self._old_torch_manual_seed: Any = None
1184
+ self._old_torch_initial_seed: Any = None
1185
+ self._per_rank_rng_states: dict[
1186
+ int, tuple[torch.Tensor, dict[int, torch.Tensor]]
1187
+ ] = {}
1188
+
1189
+ self.enable_()
1190
+
1191
+ def __enter__(self) -> "LocalTensorMode":
1192
+ self.enable_()
1193
+ get_local_tensor_mode_list().append(self)
1194
+
1195
+ # _distribute_region will compute correct per-shard offsets
1196
+ # but we want all ranks to start with the same state
1197
+ if not _is_in_fake_tensor_mode():
1198
+ cpu_state, cuda_states = _get_rng_state()
1199
+ for rank in self.ranks:
1200
+ self._per_rank_rng_states[rank] = (
1201
+ cpu_state.clone(),
1202
+ {idx: state.clone() for idx, state in cuda_states.items()},
1203
+ )
1204
+
1205
+ return super().__enter__()
1206
+
1207
+ def __exit__(
1208
+ self,
1209
+ exc_type: type[BaseException] | None,
1210
+ exc_val: BaseException | None,
1211
+ exc_tb: TracebackType | None,
1212
+ ) -> None:
1213
+ self.disable_()
1214
+ get_local_tensor_mode_list().pop()
1215
+ super().__exit__(exc_type, exc_val, exc_tb)
1216
+
1217
+ def __torch_dispatch__(
1218
+ self,
1219
+ func: Any,
1220
+ types: tuple[Any, ...],
1221
+ args: tuple[Any, ...] = (),
1222
+ kwargs: dict[str, Any] | None = None,
1223
+ ) -> Any:
1224
+ if kwargs is None:
1225
+ kwargs = {}
1226
+
1227
+ flat_args, args_spec = pytree.tree_flatten((args, kwargs))
1228
+
1229
+ # Find all LocalTensor arguments to determine ranks
1230
+ local_tensors = [a for a in flat_args if isinstance(a, LocalTensor)]
1231
+
1232
+ # Check for unrecognized tensor subclasses (but allow regular tensors and scalars)
1233
+ has_unrecognized_types = _check_for_subclass(flat_args)
1234
+ if has_unrecognized_types:
1235
+ unrecognized_types = [
1236
+ type(x) for x in flat_args if _check_for_subclass_arg(x)
1237
+ ]
1238
+ not_implemented_log.debug(
1239
+ "LocalTensorMode unrecognized subclass(es): %s", unrecognized_types
1240
+ )
1241
+ return NotImplemented
1242
+
1243
+ # Factory functions convert into LocalTensor, so we don't have to
1244
+ # transmute a Tensor into a LocalTensor if mutation happens...
1245
+ # But if you do an operation on a Tensor, do NOT wrap it into a
1246
+ # LocalTensor. This helps prevent accidents when you're doing Tensor
1247
+ # operations on the inner non-wrapped tensors.
1248
+ if not local_tensors:
1249
+ if self._disable or any(isinstance(a, Tensor) for a in flat_args):
1250
+ return func(*args, **kwargs)
1251
+
1252
+ # For LocalTensors, verify they have compatible ranks
1253
+ for a in flat_args:
1254
+ if isinstance(a, LocalTensor):
1255
+ assert a._ranks <= self.ranks, (
1256
+ f"Input LocalTensor {a} must be configured for a subset of the LocalTensorMode ranks {self.ranks}"
1257
+ )
1258
+
1259
+ if func.overloadpacket == torch.ops.aten.dim:
1260
+ return len(args[0]._size)
1261
+ if func.overloadpacket == torch.ops.aten.sym_size:
1262
+ return tuple(args[0]._size)
1263
+
1264
+ if func.namespace == "c10d":
1265
+ if func is torch.ops.c10d.allreduce_.default:
1266
+ return _c10d._local_all_reduce_(*args, **kwargs)
1267
+ elif func is torch.ops.c10d.allreduce_coalesced_.default:
1268
+ return _c10d._local_allreduce_coalesced_(*args, **kwargs)
1269
+ elif func is torch.ops.c10d.reduce_scatter_tensor_coalesced_.default:
1270
+ return _c10d._local_reduce_scatter_tensor_coalesced_(*args, **kwargs)
1271
+ elif func is torch.ops.c10d.scatter_.default:
1272
+ return _c10d._local_scatter_(*args, **kwargs)
1273
+ elif func is torch.ops.c10d.broadcast_.default:
1274
+ return _c10d._local_broadcast_(*args, **kwargs)
1275
+ elif func is torch.ops.c10d.allgather_.default:
1276
+ return _c10d._local_all_gather_(*args, **kwargs)
1277
+ elif func is torch.ops.c10d.allgather_into_tensor_coalesced_.default:
1278
+ return _c10d._local_allgather_into_tensor_coalesced_(*args, **kwargs)
1279
+ elif func is torch.ops.c10d._allgather_base_.default:
1280
+ return _c10d._local_allgather_base_(*args, **kwargs)
1281
+ elif func is torch.ops.c10d._reduce_scatter_base_.default:
1282
+ return _c10d._local_reduce_scatter_base_(*args, **kwargs)
1283
+ elif func is torch.ops.c10d.gather_.default:
1284
+ return _c10d._local_gather_(*args, **kwargs)
1285
+ elif func is torch.ops.c10d.alltoall_.default:
1286
+ return _c10d._local_alltoall_(*args, **kwargs)
1287
+ elif func is torch.ops.c10d.alltoall_base_.default:
1288
+ return _c10d._local_alltoall_base_(*args, **kwargs)
1289
+ elif func is torch.ops.c10d.barrier.default:
1290
+ return _c10d._local_barrier(*args, **kwargs)
1291
+ elif func is torch.ops.c10d.monitored_barrier_.default:
1292
+ return _c10d._local_monitored_barrier_(*args, **kwargs)
1293
+ elif func is torch.ops.c10d.send.default:
1294
+ return _c10d._local_send(*args, **kwargs)
1295
+ elif func is torch.ops.c10d.recv_.default:
1296
+ return _c10d._local_recv_(*args, **kwargs)
1297
+ elif func is torch.ops.c10d.recv_any_source_.default:
1298
+ return _c10d._local_recv_any_source_(*args, **kwargs)
1299
+ raise NotImplementedError(f"{func} not implemented")
1300
+
1301
+ if func.namespace == "_c10d_functional" or func.namespace == "_dtensor":
1302
+ if func is torch.ops._dtensor.shard_dim_alltoall.default:
1303
+ return _c10d._local_functional_shard_dim_alltoall(*args, **kwargs)
1304
+ elif func is torch.ops._c10d_functional.all_gather_into_tensor.default:
1305
+ return _c10d._local_functional_all_gather_into_tensor(*args, **kwargs)
1306
+ elif func is torch.ops._c10d_functional.reduce_scatter_tensor.default:
1307
+ return _c10d._local_functional_reduce_scatter_tensor(*args, **kwargs)
1308
+ elif func is torch.ops._c10d_functional.all_to_all_single.default:
1309
+ return _c10d._local_functional_all_to_all_single(*args, **kwargs)
1310
+ else:
1311
+ with LocalTensorMode(self.ranks):
1312
+ return func._op_dk(
1313
+ DispatchKey.CompositeExplicitAutograd, *args, **kwargs
1314
+ )
1315
+
1316
+ if func.namespace == "profiler":
1317
+ return func(*args, **kwargs)
1318
+
1319
+ if func.namespace == "_c10d_functional_autograd":
1320
+ raise NotImplementedError(f"{func} not implemented")
1321
+
1322
+ if func.namespace == "symm_mem":
1323
+ raise NotImplementedError(f"{func} not implemented")
1324
+
1325
+ return _for_each_rank_run_func(func, self.ranks, args, kwargs, alias=True)
1326
+
1327
+ def disable_(self):
1328
+ if self._disable:
1329
+ return
1330
+
1331
+ self._unpatch_device_mesh()
1332
+ self._unpatch_random_functions()
1333
+ self._disable = True
1334
+
1335
+ def enable_(self):
1336
+ if not self._disable:
1337
+ return
1338
+
1339
+ self._patch_device_mesh()
1340
+ self._patch_random_functions()
1341
+ self._disable = False
1342
+
1343
+ @contextlib.contextmanager
1344
+ def disable(self) -> Generator[None, None, None]:
1345
+ """
1346
+ Disables LocalTensorMode temporarily. Primarily is intended to be used to perform
1347
+ rank specific computations and merge results back before enabling LocalTensorMode back.
1348
+ """
1349
+
1350
+ # don't unpatch again if already disabled
1351
+ if self._disable:
1352
+ try:
1353
+ yield
1354
+ finally:
1355
+ # re-disable if the yield messed
1356
+ # with the state
1357
+ self.disable_()
1358
+ return
1359
+
1360
+ self.disable_()
1361
+ try:
1362
+ yield
1363
+ finally:
1364
+ self.enable_()
1365
+
1366
+ def rank_map(self, cb: Callable[[int], Tensor]) -> LocalTensor:
1367
+ """
1368
+ Creates a LocalTensor instance by mapping rank id to ids local shard.
1369
+ """
1370
+
1371
+ with self.disable():
1372
+ # pyrefly: ignore [bad-argument-type, bad-argument-count]
1373
+ return LocalTensor({r: cb(r) for r in self.ranks})
1374
+
1375
+ def tensor_map(
1376
+ self, tensor: LocalTensor, cb: Callable[[int, Tensor], Tensor | None]
1377
+ ) -> LocalTensor:
1378
+ """
1379
+ Creates a LocalTensor instance by mapping rank id to ids local shard.
1380
+ """
1381
+
1382
+ with self.disable():
1383
+ results = {}
1384
+ for r in self.ranks:
1385
+ if r in tensor._local_tensors:
1386
+ m = cb(r, tensor._local_tensors[r])
1387
+ if m is not None:
1388
+ results[r] = m
1389
+ # pyrefly: ignore [bad-argument-type, bad-argument-count]
1390
+ return LocalTensor(results)
1391
+
1392
+ def _any_local_rng_state(self) -> tuple[torch.Tensor, dict[int, torch.Tensor]]:
1393
+ return self._per_rank_rng_states[next(iter(self.ranks))]
1394
+
1395
+ def _patch_device_mesh(self) -> None:
1396
+ assert self._old_get_coordinate is None
1397
+ assert self._old_get_rank is None
1398
+ assert self._old_get_local_rank is None
1399
+ self._old_get_coordinate = DeviceMesh.get_coordinate # type: ignore[assignment]
1400
+ self._old_get_rank = DeviceMesh.get_rank # type: ignore[assignment]
1401
+ self._old_get_local_rank = DeviceMesh.get_local_rank # type: ignore[assignment]
1402
+ DeviceMesh.get_coordinate = _LocalDeviceMesh.get_coordinate # type: ignore[method-assign]
1403
+ DeviceMesh.get_rank = _LocalDeviceMesh.get_rank # type: ignore[method-assign]
1404
+ DeviceMesh.get_local_rank = _LocalDeviceMesh.get_local_rank # type: ignore[method-assign]
1405
+
1406
+ def _unpatch_device_mesh(self) -> None:
1407
+ assert self._old_get_coordinate is not None
1408
+ assert self._old_get_rank is not None
1409
+ assert self._old_get_local_rank is not None
1410
+ DeviceMesh.get_coordinate = self._old_get_coordinate
1411
+ DeviceMesh.get_rank = self._old_get_rank
1412
+ DeviceMesh.get_local_rank = self._old_get_local_rank
1413
+ # pyrefly: ignore [bad-assignment]
1414
+ self._old_get_coordinate = None
1415
+ # pyrefly: ignore [bad-assignment]
1416
+ self._old_get_rank = None
1417
+ # pyrefly: ignore [bad-assignment]
1418
+ self._old_get_local_rank = None
1419
+
1420
+ def _patch_random_functions(self) -> None:
1421
+ import torch.random
1422
+ from torch.distributed.tensor import _random as dtensor_random
1423
+
1424
+ if self._old_torch_manual_seed is None:
1425
+ self._old_torch_manual_seed = torch.random.manual_seed
1426
+ torch.random.manual_seed = _LocalRandom.torch_manual_seed
1427
+ torch.manual_seed = _LocalRandom.torch_manual_seed
1428
+
1429
+ if self._old_torch_initial_seed is None:
1430
+ self._old_torch_initial_seed = torch.random.initial_seed
1431
+ torch.random.initial_seed = _LocalRandom.torch_initial_seed
1432
+ torch.initial_seed = _LocalRandom.torch_initial_seed
1433
+
1434
+ def _unpatch_random_functions(self) -> None:
1435
+ import torch.random
1436
+ from torch.distributed.tensor import _random as dtensor_random
1437
+
1438
+ if self._old_torch_manual_seed is not None:
1439
+ torch.random.manual_seed = self._old_torch_manual_seed
1440
+ torch.manual_seed = self._old_torch_manual_seed
1441
+ self._old_torch_manual_seed = None
1442
+
1443
+ if self._old_torch_initial_seed is not None:
1444
+ torch.random.initial_seed = self._old_torch_initial_seed
1445
+ torch.initial_seed = self._old_torch_initial_seed
1446
+ self._old_torch_initial_seed = None
1447
+
1448
+
1449
+ class _LocalRandom:
1450
+ """
1451
+ Holds implementations of random functionality that must be patched while running
1452
+ under LocalTensorMode.
1453
+ """
1454
+
1455
+ @staticmethod
1456
+ def torch_manual_seed(seed) -> torch._C.Generator:
1457
+ """LocalTensor-aware version of torch.random.manual_seed."""
1458
+ if (
1459
+ (lm := enabled_local_tensor_mode())
1460
+ and isinstance(seed, torch.SymInt)
1461
+ and isinstance(seed.node, LocalIntNode)
1462
+ ):
1463
+ from torch.random import _manual_seed_impl
1464
+
1465
+ for rank in sorted(lm.ranks):
1466
+ rank_seed = seed.node._local_ints[rank]
1467
+ _manual_seed_impl(rank_seed)
1468
+ lm._per_rank_rng_states[rank] = _get_rng_state()
1469
+ return torch.random.default_generator
1470
+ from torch.random import _manual_seed_impl
1471
+
1472
+ result = _manual_seed_impl(seed)
1473
+
1474
+ if lm is not None and len(lm._per_rank_rng_states) > 0:
1475
+ cpu_state, cuda_states = _get_rng_state()
1476
+ for rank in lm.ranks:
1477
+ lm._per_rank_rng_states[rank] = (
1478
+ cpu_state.clone(),
1479
+ {idx: state.clone() for idx, state in cuda_states.items()},
1480
+ )
1481
+
1482
+ return result
1483
+
1484
+ @staticmethod
1485
+ def torch_initial_seed():
1486
+ """LocalTensor-aware version of torch.random.initial_seed."""
1487
+ if lm := enabled_local_tensor_mode():
1488
+ if len(lm._per_rank_rng_states) == 0:
1489
+ return torch.random.default_generator.initial_seed()
1490
+ rank_seeds = {}
1491
+
1492
+ for rank in sorted(lm.ranks):
1493
+ _set_rng_state(*lm._per_rank_rng_states[rank])
1494
+ rank_seeds[rank] = torch.random.default_generator.initial_seed()
1495
+
1496
+ local_int_node = LocalIntNode(rank_seeds)
1497
+ return torch.SymInt(local_int_node)
1498
+
1499
+ return torch.random.default_generator.initial_seed()
1500
+
1501
+
1502
+ # Save the original get_coordinate method before any patching
1503
+
1504
+
1505
+ class _LocalDeviceMesh:
1506
+ """
1507
+ Holds implementations of DeviceMesh functionality that must be patched while running
1508
+ under LocalTensorMode.
1509
+ """
1510
+
1511
+ @staticmethod
1512
+ def get_coordinate(self: DeviceMesh) -> list[int] | None:
1513
+ # NB: In order to support submeshes the code below recreates for each
1514
+ # rank submesh with the same mesh dimensions as current mesh. We are
1515
+ # doing this because when submesh is created it is created for a particular
1516
+ # rank (therefore below we are patching get_rank method). We are trying to
1517
+ # limit the invasiveness of local tensor.
1518
+ lm = enabled_local_tensor_mode()
1519
+ assert lm is not None, "Unexpectedly not in LocalTensorMode"
1520
+
1521
+ coords: list[dict[int, int]] = [{} for _ in range(self.ndim)]
1522
+ for r in lm.ranks:
1523
+ rank_tensor = self._layout.remap_to_tensor(self._rank_map)
1524
+ rank_coords = (rank_tensor == r).nonzero().tolist()
1525
+ assert len(rank_coords) == 1
1526
+ for d, c in enumerate(rank_coords[0][1:]):
1527
+ coords[d][r] = c
1528
+
1529
+ out = [torch.SymInt(LocalIntNode(c)) for c in coords]
1530
+ # The output contains coordinates for each of the ranks with respect to
1531
+ # their meshes formed from root mesh and selecting the same dimensions
1532
+ # as the current mesh.
1533
+ return out # type: ignore[return-value]
1534
+
1535
+ @staticmethod
1536
+ def get_rank(self) -> int | SymInt:
1537
+ lm = enabled_local_tensor_mode()
1538
+ assert lm is not None, "Unexpectedly not in LocalTensorMode"
1539
+ return torch.SymInt(LocalIntNode(local_ints={r: r for r in lm.ranks}))
1540
+
1541
+ @staticmethod
1542
+ def get_local_rank(self, mesh_dim: int | str | None = None) -> int | SymInt:
1543
+ lm = enabled_local_tensor_mode()
1544
+ assert lm is not None, "Unexpectedly not in LocalTensorMode"
1545
+
1546
+ if self.ndim > 1 and mesh_dim is None:
1547
+ raise RuntimeError(
1548
+ f"Found the DeviceMesh have {self.ndim} dimensions",
1549
+ "Optional kwarg `mesh_dim` needs to be specified when device_mesh.ndim > 1.",
1550
+ )
1551
+ elif mesh_dim is None:
1552
+ mesh_dim = 0
1553
+
1554
+ if isinstance(mesh_dim, str):
1555
+ mesh_dim = self._mesh_dim_names.index(mesh_dim)
1556
+
1557
+ # Compute local rank for each global rank
1558
+ # get_coordinate returns a list of SymInt, one per mesh dimension
1559
+ # We need to extract the coordinate for the specified mesh_dim
1560
+ coords = _LocalDeviceMesh.get_coordinate(self)
1561
+ assert coords is not None
1562
+ return coords[mesh_dim]
1563
+
1564
+
1565
+ def reconcile_args(args: Any, kwargs: dict[str, Any] | None = None) -> Any:
1566
+ """
1567
+ Reconciles arguments by converting any LocalTensor instances in the input
1568
+ arguments to their underlying torch.Tensor representation.
1569
+
1570
+ This function is typically used to prepare arguments for functions that
1571
+ expect standard torch.Tensor objects, by flattening the input arguments,
1572
+ replacing LocalTensor instances with their reconciled (standard tensor)
1573
+ versions, and then reconstructing the original argument structure.
1574
+
1575
+ Args:
1576
+ args: Positional arguments, possibly containing LocalTensor instances.
1577
+ kwargs: Keyword arguments, possibly containing LocalTensor instances.
1578
+
1579
+ Returns:
1580
+ Any: The arguments with all LocalTensor instances replaced by their reconciled torch.Tensor equivalents,
1581
+ preserving the original structure.
1582
+ """
1583
+ if kwargs is None:
1584
+ kwargs = {}
1585
+ flat_args, args_spec = pytree.tree_flatten((args, kwargs))
1586
+ reconciled_args = [
1587
+ a.reconcile() if isinstance(a, LocalTensor) else a for a in flat_args
1588
+ ]
1589
+ return pytree.tree_unflatten(reconciled_args, args_spec)
1590
+
1591
+
1592
+ def local_tensor_mode() -> LocalTensorMode | None:
1593
+ """
1594
+ Returns the current active LocalTensorMode if one exists.
1595
+
1596
+ This function checks the global stack of LocalTensorMode instance. If there
1597
+ is at least one LocalTensorMode active, it returns the most recently entered
1598
+ (top of the stack) LocalTensorMode. If no LocalTensorMode is active, it returns None.
1599
+
1600
+ Returns:
1601
+ Optional[LocalTensorMode]: The current LocalTensorMode if active, else None.
1602
+ """
1603
+ local_tensor_mode_list = get_local_tensor_mode_list()
1604
+ if len(local_tensor_mode_list) > 0:
1605
+ return local_tensor_mode_list[-1]
1606
+ return None
1607
+
1608
+
1609
+ def enabled_local_tensor_mode() -> LocalTensorMode | None:
1610
+ """
1611
+ Returns the current active LocalTensorMode only if it's enabled.
1612
+
1613
+ This is a convenience function that combines the common pattern of checking
1614
+ if local_tensor_mode() is not None and not disabled.
1615
+
1616
+ Returns:
1617
+ Optional[LocalTensorMode]: The current LocalTensorMode if active and enabled, else None.
1618
+ """
1619
+ lm = local_tensor_mode()
1620
+ if lm is not None and not lm._disable:
1621
+ return lm
1622
+ return None
1623
+
1624
+
1625
+ def maybe_run_for_local_tensor(func: Callable[_P, _R]) -> Callable[_P, _R]:
1626
+ """
1627
+ Decorator that ensures a function is executed for each local tensor shard
1628
+ when running under LocalTensorMode. If not in LocalTensorMode, the function
1629
+ is executed normally. When in LocalTensorMode, the function is run for each
1630
+ rank, and the results are collected appropriately.
1631
+
1632
+ This decorator is useful for functions that exhibit non-SPMD behavior, such
1633
+ as those requiring rank specific actions. For example, a function that computes
1634
+ offset into input tensor based on rank.
1635
+
1636
+ Note that the function being decorated must not have any side effects and
1637
+ contain operations for a single rank only. For example, wrapping a function
1638
+ that performs a collective operation will not work.
1639
+
1640
+ Args:
1641
+ func (Callable[..., Any]): The function to be decorated.
1642
+
1643
+ Returns:
1644
+ Callable[..., Any]: The wrapped function that handles LocalTensorMode logic.
1645
+ """
1646
+
1647
+ @functools.wraps(func)
1648
+ def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
1649
+ if not (lm := enabled_local_tensor_mode()):
1650
+ return func(*args, **kwargs)
1651
+ ret = None
1652
+ with lm.disable():
1653
+ ret = _for_each_rank_run_func(func, lm.ranks, args, kwargs, alias=False)
1654
+
1655
+ return ret
1656
+
1657
+ return wrapper
1658
+
1659
+
1660
+ def maybe_disable_local_tensor_mode() -> contextlib.AbstractContextManager:
1661
+ """
1662
+ Context manager that disables LocalTensorMode for the duration of the context.
1663
+ """
1664
+ lm = local_tensor_mode()
1665
+ return lm.disable() if lm is not None else contextlib.nullcontext()
1666
+
1667
+
1668
+ def maybe_enable_local_tracker(
1669
+ device_type: str, distribute_region_enabled: bool, spec, generator
1670
+ ):
1671
+ """
1672
+ Returns a context manager for LocalTensor-mode RNG tracking if local tensor mode is enabled.
1673
+
1674
+ Args:
1675
+ device_type: The device type (e.g., "cuda", "cpu")
1676
+ distribute_region_enabled: Whether distribute region is enabled
1677
+ spec: The DTensorSpec
1678
+ generator: Optional torch.Generator
1679
+
1680
+ Returns:
1681
+ Context manager from local_tracker._distribute_region if local tensor mode is enabled,
1682
+ otherwise None.
1683
+ """
1684
+ if enabled_local_tensor_mode():
1685
+ local_tracker = _LocalOffsetBasedRNGTracker(device_type)
1686
+ local_tracker.distribute_region_enabled = distribute_region_enabled
1687
+ return local_tracker._distribute_region(spec, generator)
1688
+
1689
+ return None
1690
+
1691
+
1692
+ def get_generator_seed_for_device_type(device_type: str):
1693
+ """
1694
+ Gets the generator seed for a specific device type, handling LocalTensor mode appropriately.
1695
+
1696
+ Args:
1697
+ device_type: The device type (e.g., "cuda", "cpu")
1698
+
1699
+ Returns:
1700
+ If in LocalTensor mode with per-rank RNG states:
1701
+ - Returns int if all ranks have the same seed
1702
+ - Returns SymInt(LocalIntNode) if ranks have different seeds
1703
+ Otherwise:
1704
+ - Returns int seed from the device's RNG state
1705
+ """
1706
+ if lm := enabled_local_tensor_mode():
1707
+ if len(lm._per_rank_rng_states) == 0:
1708
+ device_module = torch.get_device_module(device_type)
1709
+ return device_module.get_rng_state()[:8].view(torch.int64).item()
1710
+ device_module = torch.get_device_module(device_type)
1711
+
1712
+ original_state = _get_rng_state()
1713
+
1714
+ rank_seeds = {}
1715
+ try:
1716
+ for rank in sorted(lm.ranks):
1717
+ _set_rng_state(*lm._per_rank_rng_states[rank])
1718
+ rank_seeds[rank] = int(
1719
+ device_module.get_rng_state()[:8].view(torch.int64).item()
1720
+ )
1721
+ finally:
1722
+ # restore original state
1723
+ _set_rng_state(*original_state)
1724
+
1725
+ unique_seeds = set(rank_seeds.values())
1726
+ if len(unique_seeds) == 1:
1727
+ return next(iter(unique_seeds))
1728
+ local_int_node = LocalIntNode(rank_seeds)
1729
+ return torch.SymInt(local_int_node)
1730
+ else:
1731
+ device_module = torch.get_device_module(device_type)
1732
+ return device_module.get_rng_state()[:8].view(torch.int64).item()
1733
+
1734
+
1735
+ import threading
1736
+ from queue import Queue
1737
+
1738
+
1739
+ _LOCAL_RUNNER_MODE: "LocalRunnerMode | None" = None
1740
+
1741
+
1742
+ class LocalRunnerMode:
1743
+ """
1744
+ A class for running multiple SPMD functions concurrently, however at any point
1745
+ in time only one function can be running. The main use case for the local runner
1746
+ mode is to enable SPMD functions to be able to use send and recv to communicate
1747
+ with each other. Without local runner mode send and recv are not supported.
1748
+ """
1749
+
1750
+ runner_context = threading.local()
1751
+
1752
+ def __init__(
1753
+ self, ranks: frozenset[int] | int, concurrency: int, fn: Callable[[int], None]
1754
+ ):
1755
+ if isinstance(ranks, int):
1756
+ ranks = frozenset(range(ranks))
1757
+ self._ranks = ranks
1758
+ self._fn = fn
1759
+ self._run_lock = threading.Lock()
1760
+ self._run_id = -1
1761
+ self._run_cond = threading.Condition(self._run_lock)
1762
+
1763
+ self._recv_objects: dict[int, dict[int, Queue]] = {
1764
+ dst: {src: Queue() for src in ranks} for dst in ranks
1765
+ }
1766
+ self._runners = [
1767
+ threading.Thread(target=self._run, args=(i,), name="LocalRunnerMode")
1768
+ for i in range(concurrency)
1769
+ ]
1770
+ self._process_mode = True
1771
+
1772
+ def __enter__(self) -> "LocalRunnerMode":
1773
+ global _LOCAL_RUNNER_MODE
1774
+ assert _LOCAL_RUNNER_MODE is None, "LocalRunnerMode is already running"
1775
+ _LOCAL_RUNNER_MODE = self
1776
+
1777
+ global _PROCESS_MODE
1778
+ self._process_mode = _PROCESS_MODE
1779
+ _PROCESS_MODE = False
1780
+ for r in self._runners:
1781
+ r.start()
1782
+ return self
1783
+
1784
+ def __exit__(
1785
+ self,
1786
+ exc_type: type[BaseException] | None,
1787
+ exc_val: BaseException | None,
1788
+ exc_tb: TracebackType | None,
1789
+ ) -> None:
1790
+ for r in self._runners:
1791
+ r.join()
1792
+ global _LOCAL_RUNNER_MODE
1793
+ _LOCAL_RUNNER_MODE = None
1794
+
1795
+ global _PROCESS_MODE
1796
+ _PROCESS_MODE = self._process_mode
1797
+
1798
+ def _run(self, id: int) -> None:
1799
+ LocalRunnerMode.runner_context.id = id
1800
+ # Only one thread can run at a time, hence must acquire the lock
1801
+ try:
1802
+ self._acquire_run_lock()
1803
+ self._fn(id)
1804
+ finally:
1805
+ self._release_run_lock()
1806
+
1807
+ def _acquire_run_lock(self) -> None:
1808
+ self._run_lock.acquire()
1809
+ self._run_id = LocalRunnerMode.runner_context.id
1810
+
1811
+ def _release_run_lock(self) -> None:
1812
+ self._run_id = -1
1813
+ self._run_lock.release()
1814
+
1815
+ def _assert_holds_run_lock(self) -> None:
1816
+ assert self._run_id == LocalRunnerMode.runner_context.id, (
1817
+ "Calling thread does not hold the run lock"
1818
+ )
1819
+
1820
+ def _get_recv_object(self, src: int, dst: int) -> object | None:
1821
+ peers = [src] if src != -1 else list(self._ranks)
1822
+ recv_objects = self._recv_objects[dst]
1823
+
1824
+ for p in peers:
1825
+ if not recv_objects[p].empty():
1826
+ return recv_objects[p].get()
1827
+
1828
+ return None
1829
+
1830
+ def _signal_send(self, src: int, dst: int, obj: object) -> None:
1831
+ assert obj is not None, "Cannot signal None"
1832
+ # Only a single thread a time executes so it is safe to mutate
1833
+ # read objects queue (executing thread is already holding the lock)
1834
+ self._recv_objects[dst][src].put(obj)
1835
+ # Signal directly condition variable since the calling thread is already
1836
+ # holding the lock
1837
+ self._run_cond.notify_all()
1838
+
1839
+ def _wait_recv(self, src: int, dst: int, post: Callable[[object], None]) -> None:
1840
+ # Wait for the object to be available
1841
+ while True:
1842
+ obj = self._get_recv_object(src, dst)
1843
+ if obj is not None:
1844
+ post(obj)
1845
+ # Note that we are not releasing the lock here, since the thread
1846
+ # will continue to run and therefore must hold the lock
1847
+ return
1848
+ self._run_cond.wait()
1849
+
1850
+ @staticmethod
1851
+ def current() -> "LocalRunnerMode":
1852
+ global _LOCAL_RUNNER_MODE
1853
+ assert _LOCAL_RUNNER_MODE is not None, "LocalRunnerMode is not enabled"
1854
+ return _LOCAL_RUNNER_MODE
1855
+
1856
+
1857
+ class _LocalPhiloxState:
1858
+ """
1859
+ LocalTensor-aware version of _PhiloxState that manages per-rank RNG states.
1860
+ This class handles the case where the generator state is a LocalTensor, allowing
1861
+ different offsets and seeds for different virtual ranks.
1862
+
1863
+ Note: This is designed to be used as a drop-in replacement for _PhiloxState
1864
+ when working with LocalTensors in the DTensor random ops implementation.
1865
+ """
1866
+
1867
+ def __init__(self, state: torch.Tensor):
1868
+ assert isinstance(state, LocalTensor), (
1869
+ "_LocalPhiloxState requires a LocalTensor"
1870
+ )
1871
+ self._local_tensor = state
1872
+ self._per_rank_states = {
1873
+ rank: local_state.to("cpu")
1874
+ for rank, local_state in state._local_tensors.items()
1875
+ }
1876
+
1877
+ @property
1878
+ def state(self):
1879
+ return LocalTensor(self._per_rank_states) # type: ignore[name-defined]
1880
+
1881
+ @property
1882
+ def offset(self) -> int | SymInt:
1883
+ from torch.distributed.tensor._random import _PhiloxState
1884
+
1885
+ offsets = {}
1886
+ for rank, state in self._per_rank_states.items():
1887
+ rank_philox = _PhiloxState(state)
1888
+ offsets[rank] = rank_philox.offset
1889
+
1890
+ if len(set(offsets.values())) == 1:
1891
+ return next(iter(offsets.values()))
1892
+ # pyrefly: ignore [bad-argument-type, bad-argument-count]
1893
+ return SymInt(LocalIntNode(offsets))
1894
+
1895
+ @offset.setter
1896
+ def offset(self, offset: int | SymInt) -> None:
1897
+ from torch.distributed.tensor._random import _PhiloxState
1898
+
1899
+ if isinstance(offset, SymInt) and isinstance(offset.node, LocalIntNode):
1900
+ for rank, state in self._per_rank_states.items():
1901
+ rank_offset = offset.node._local_ints[rank]
1902
+ rank_philox = _PhiloxState(state)
1903
+ rank_philox.offset = rank_offset
1904
+ else:
1905
+ offset_int = int(offset) if isinstance(offset, SymInt) else offset
1906
+ for state in self._per_rank_states.values():
1907
+ rank_philox = _PhiloxState(state)
1908
+ rank_philox.offset = offset_int
1909
+
1910
+ @property
1911
+ def seed(self) -> int | SymInt:
1912
+ from torch.distributed.tensor._random import _PhiloxState
1913
+
1914
+ seeds = {}
1915
+ for rank, state in self._per_rank_states.items():
1916
+ rank_philox = _PhiloxState(state)
1917
+ seeds[rank] = rank_philox.seed
1918
+
1919
+ if len(set(seeds.values())) == 1:
1920
+ return next(iter(seeds.values()))
1921
+ return SymInt(LocalIntNode(seeds))
1922
+
1923
+ @seed.setter
1924
+ def seed(self, seed: int | SymInt) -> None:
1925
+ from torch.distributed.tensor._random import _PhiloxState
1926
+
1927
+ if isinstance(seed, SymInt) and isinstance(seed.node, LocalIntNode):
1928
+ for rank, state in self._per_rank_states.items():
1929
+ rank_seed = seed.node._local_ints[rank]
1930
+ rank_philox = _PhiloxState(state)
1931
+ rank_philox.seed = rank_seed
1932
+ else:
1933
+ seed_int = int(seed) if isinstance(seed, SymInt) else seed
1934
+ for state in self._per_rank_states.values():
1935
+ rank_philox = _PhiloxState(state)
1936
+ rank_philox.seed = seed_int
1937
+
1938
+ def apply_to_local_tensor_mode(self, device_handle) -> None:
1939
+ """
1940
+ Apply per-rank RNG states to the LocalTensorMode's tracked states.
1941
+ This updates both the device RNG state and the LocalTensorMode's _per_rank_rng_states.
1942
+
1943
+ Args:
1944
+ device_handle: The device handle to use for setting RNG state (_LocalDeviceHandle)
1945
+ """
1946
+ if not enabled_local_tensor_mode():
1947
+ return
1948
+
1949
+ assert hasattr(self, "_per_rank_offsets")
1950
+
1951
+ for rank in sorted(self._per_rank_states.keys()):
1952
+ offset_value = self._per_rank_offsets[rank]
1953
+ if isinstance(offset_value, SymInt):
1954
+ if isinstance(offset_value.node, LocalIntNode):
1955
+ offset_value = offset_value.node._local_ints[rank]
1956
+ else:
1957
+ offset_value = int(offset_value)
1958
+
1959
+ offset_tensor = torch.tensor(
1960
+ [offset_value], dtype=torch.uint64, device="cpu"
1961
+ ).view(torch.uint8)
1962
+ self._per_rank_states[rank][8:] = offset_tensor
1963
+
1964
+ # pyrefly: ignore [bad-argument-type, bad-argument-count]
1965
+ device_handle.set_rng_state(LocalTensor(self._per_rank_states))
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_local_tensor/_c10d.py ADDED
@@ -0,0 +1,1060 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import math
3
+ import operator
4
+ from collections.abc import Callable, Sequence
5
+ from datetime import timedelta
6
+
7
+ import torch
8
+ from torch._C import ScriptObject
9
+ from torch._C._distributed_c10d import FakeWork, PythonCallbackWork
10
+ from torch.distributed._mesh_layout import _MeshLayout
11
+ from torch.distributed.distributed_c10d import (
12
+ _check_op,
13
+ _get_default_group,
14
+ _resolve_process_group,
15
+ GroupName,
16
+ ProcessGroup,
17
+ ReduceOp,
18
+ Work,
19
+ )
20
+
21
+
22
+ # NOTE: Most of the c10d collectives often take a Tensor[] (or Tensor[][])
23
+ # when you would expect Tensor (or Tensor[]). In fact, there will only ever
24
+ # be one Tensor in this case; the old signature was to support dispatching a
25
+ # collective on multiple devices (ala DataParallel) but we don't support that
26
+ # API anymore. Note that we are not 100% consistent about this; some more
27
+ # modern collectives like _allgather_base_ got rid of the unnecessary list.
28
+ # When in doubt, consult the code that dispatches to the collective on the PG
29
+ # in distributed_c10d.py e.g., work = group.allgather([tensor_list], [tensor],
30
+ # opts) indicates its always a list.
31
+
32
+
33
+ def _gcd_list(numbers: Sequence[int]) -> int:
34
+ return 0 if not numbers else functools.reduce(math.gcd, numbers)
35
+
36
+
37
+ def _indices_to_layout(indices: list[int]) -> tuple[tuple[int, ...], tuple[int, ...]]:
38
+ # Base case: A single index represents a point, not a dimension.
39
+ if len(indices) <= 1:
40
+ return (), ()
41
+
42
+ # The smallest stride is likely the GCD of the differences between consecutive indices.
43
+ # For a sorted, unique list, all differences will be positive.
44
+ diffs = [indices[i] - indices[i - 1] for i in range(1, len(indices))]
45
+ last_stride = _gcd_list(diffs)
46
+
47
+ assert last_stride != 0, (
48
+ # This case should not be reached if indices are unique and sorted.
49
+ "Cannot determine stride; indices may not be unique."
50
+ )
51
+
52
+ # Identify the starting index of each "row" in the last dimension.
53
+ # An index starts a new row if the preceding index (index - stride) is not present.
54
+ indices_set = set(indices)
55
+ higher_dim_indices = [indices[0]]
56
+ for index in indices[1:]:
57
+ if (index - last_stride) not in indices_set:
58
+ higher_dim_indices.append(index)
59
+
60
+ # From the number of rows, we can deduce the shape of the last dimension.
61
+ assert len(indices) % len(higher_dim_indices) == 0, (
62
+ "Indices do not form a regular grid. "
63
+ f"Found {len(higher_dim_indices)} subgroups for {len(indices)} total elements."
64
+ )
65
+ last_shape = len(indices) // len(higher_dim_indices)
66
+
67
+ # Recurse on the higher-dimensional indices (the start of each row).
68
+ higher_shapes, higher_strides = _indices_to_layout(higher_dim_indices)
69
+
70
+ # Combine the results from the recursion with the current dimension's results.
71
+ final_shapes = higher_shapes + (last_shape,)
72
+ final_strides = higher_strides + (last_stride,)
73
+
74
+ return final_shapes, final_strides
75
+
76
+
77
+ def _prepare_collective_groups(
78
+ process_group_so: ScriptObject | ProcessGroup,
79
+ ) -> tuple[list[int], list[int], int]:
80
+ process_group = (
81
+ ProcessGroup.unbox(process_group_so)
82
+ if isinstance(process_group_so, ScriptObject)
83
+ else process_group_so
84
+ )
85
+
86
+ ranks = torch.distributed.get_process_group_ranks(process_group)
87
+ assert ranks
88
+ # TODO: We can handle permutations but the layout inference algorithm will
89
+ # lose the permutation so we will have to reapply it
90
+ assert ranks == sorted(ranks), ranks
91
+ offset = ranks[0]
92
+ ranks = [r - offset for r in ranks]
93
+
94
+ shape, strides = _indices_to_layout(ranks)
95
+ layout = _MeshLayout(shape, strides)
96
+
97
+ global_pg = _get_default_group()
98
+ group_offsets = layout.complement(global_pg.size()).all_ranks_from_zero()
99
+
100
+ return ranks, group_offsets, offset
101
+
102
+
103
+ # NB: There are two flavors of the collectives: regular and functional. Regular collectives
104
+ # allocate outputs to write the result to, accept process group and support async ops (return
105
+ # work object). Functional collectives expect the implementation to allocate outputs, accept
106
+ # process group name that must be resolved and do not support async ops (return output).
107
+ def _local_functional_all_gather_into_tensor(
108
+ tensor: torch.Tensor, group_size: int, group_name: GroupName
109
+ ) -> torch.Tensor:
110
+ # "all_gather_into_tensor(Tensor input, int group_size, str group_name) -> Tensor"
111
+ from . import LocalTensor
112
+
113
+ ranks, group_offsets, offset = _prepare_collective_groups(
114
+ _resolve_process_group(group_name)
115
+ )
116
+
117
+ assert isinstance(tensor, LocalTensor), "Input tensor must be a LocalTensor"
118
+ output_local_tensors: dict[int, torch.Tensor] = {}
119
+
120
+ for group_offset in group_offsets:
121
+ group_ranks = [group_offset + r for r in ranks]
122
+
123
+ group_tensors = []
124
+ if not all(rank in tensor._local_tensors for rank in group_ranks):
125
+ continue
126
+
127
+ for rank in group_ranks:
128
+ group_tensors.append(tensor._local_tensors[rank])
129
+
130
+ gathered_tensor = torch.cat(group_tensors, dim=0)
131
+
132
+ for rank in group_ranks:
133
+ output_local_tensors[rank] = gathered_tensor.clone()
134
+
135
+ # pyrefly: ignore [bad-argument-type, bad-argument-count]
136
+ output = LocalTensor(output_local_tensors)
137
+
138
+ return output
139
+
140
+
141
+ def _local_functional_reduce_scatter_tensor(
142
+ tensor: torch.Tensor, reduce_op: str, group_size: int, group_name: GroupName
143
+ ) -> torch.Tensor:
144
+ # "reduce_scatter_tensor(Tensor input, str reduce_op, int group_size, str group_name) -> Tensor"
145
+ from . import _zero_sized_like, LocalTensor
146
+
147
+ ranks, group_offsets, offset = _prepare_collective_groups(
148
+ _resolve_process_group(group_name)
149
+ )
150
+
151
+ assert isinstance(tensor, LocalTensor), "Input tensor must be a LocalTensor"
152
+ output_local_tensors: dict[int, torch.Tensor] = {}
153
+
154
+ for group_offset in group_offsets:
155
+ group_ranks = [group_offset + r for r in ranks]
156
+
157
+ group_tensors = []
158
+ if not all(rank in tensor._local_tensors for rank in group_ranks):
159
+ continue
160
+
161
+ for rank in group_ranks:
162
+ group_tensors.append(tensor._local_tensors[rank])
163
+
164
+ reduced_tensor = _local_reduce(reduce_op, group_tensors)
165
+
166
+ scattered_tensor = torch.split(
167
+ reduced_tensor,
168
+ reduced_tensor.size(0) // len(group_ranks),
169
+ dim=0,
170
+ )
171
+
172
+ for i, rank in enumerate(group_ranks):
173
+ if i < len(scattered_tensor):
174
+ output_local_tensors[rank] = scattered_tensor[i].clone()
175
+ else:
176
+ output_local_tensors[rank] = _zero_sized_like(reduced_tensor, 0)
177
+
178
+ # pyrefly: ignore [bad-argument-type, bad-argument-count]
179
+ output = LocalTensor(output_local_tensors)
180
+
181
+ return output
182
+
183
+
184
+ def _local_functional_shard_dim_alltoall(
185
+ tensor: torch.Tensor, gather_dim: int, shard_dim: int, group_name: GroupName
186
+ ) -> torch.Tensor:
187
+ # "shard_dim_alltoall(Tensor input, int gather_dim, int shard_dim, str group_name) -> Tensor"
188
+ from . import _zero_sized_like, LocalTensor
189
+
190
+ ranks, group_offsets, offset = _prepare_collective_groups(
191
+ _resolve_process_group(group_name)
192
+ )
193
+
194
+ assert isinstance(tensor, LocalTensor), "Input tensor must be a LocalTensor"
195
+ output_local_tensors: dict[int, torch.Tensor] = {}
196
+
197
+ for group_offset in group_offsets:
198
+ group_ranks = [group_offset + r for r in ranks]
199
+
200
+ group_tensors = []
201
+ if not all(rank in tensor._local_tensors for rank in group_ranks):
202
+ continue
203
+
204
+ for rank in group_ranks:
205
+ group_tensors.append(tensor._local_tensors[rank])
206
+
207
+ gathered_tensor = torch.cat(group_tensors, dim=gather_dim)
208
+
209
+ split_tensor = torch.split(
210
+ gathered_tensor,
211
+ gathered_tensor.size(shard_dim) // len(group_ranks),
212
+ dim=shard_dim,
213
+ )
214
+
215
+ for i, rank in enumerate(group_ranks):
216
+ if i < len(split_tensor):
217
+ output_local_tensors[rank] = split_tensor[i].clone()
218
+ else:
219
+ output_local_tensors[rank] = _zero_sized_like(
220
+ gathered_tensor, shard_dim
221
+ )
222
+
223
+ # pyrefly: ignore [bad-argument-type, bad-argument-count]
224
+ output = LocalTensor(output_local_tensors)
225
+
226
+ return output
227
+
228
+
229
+ def _local_functional_all_to_all_single(
230
+ tensor: torch.Tensor,
231
+ output_split_sizes: list[torch.SymInt],
232
+ input_split_sizes: list[torch.SymInt],
233
+ group_name: GroupName,
234
+ ) -> torch.Tensor:
235
+ # "all_to_all_single(Tensor input, SymInt[] output_split_sizes, SymInt[] input_split_sizes, str group_name) -> Tensor"
236
+ from . import LocalIntNode, LocalTensor
237
+
238
+ ranks, group_offsets, offset = _prepare_collective_groups(
239
+ _resolve_process_group(group_name)
240
+ )
241
+
242
+ assert isinstance(tensor, LocalTensor), "Input tensor must be a LocalTensor"
243
+
244
+ split_local_sizes: dict[int, list[int]] = {}
245
+ for input_split_size in input_split_sizes:
246
+ if isinstance(input_split_size, torch.SymInt) and isinstance(
247
+ input_split_size.node, LocalIntNode
248
+ ):
249
+ local_ints = dict(input_split_size.node._local_ints.items())
250
+ else:
251
+ local_ints = {rank: int(input_split_size) for rank in tensor._local_tensors}
252
+ for rank, split_size in local_ints.items():
253
+ if rank not in split_local_sizes:
254
+ split_local_sizes[rank] = []
255
+ split_local_sizes[rank].append(split_size)
256
+
257
+ split_local_tensors: dict[int, list[torch.Tensor]] = {}
258
+
259
+ for rank, split_sizes in split_local_sizes.items():
260
+ split_local_tensors[rank] = list(
261
+ torch.split(tensor._local_tensors[rank], split_sizes)
262
+ )
263
+
264
+ output_local_tensors: dict[int, torch.Tensor] = {}
265
+
266
+ for group_offset in group_offsets:
267
+ group_ranks = [group_offset + r for r in ranks]
268
+
269
+ if not all(rank in split_local_tensors for rank in group_ranks):
270
+ continue
271
+
272
+ for i, dst in enumerate(group_ranks):
273
+ splits = []
274
+ for j, src in enumerate(group_ranks):
275
+ splits.append(split_local_tensors[src][i])
276
+ output_local_tensors[dst] = torch.cat(splits)
277
+
278
+ # pyrefly: ignore [bad-argument-type, bad-argument-count]
279
+ output = LocalTensor(output_local_tensors)
280
+
281
+ return output
282
+
283
+
284
+ def _local_broadcast_(
285
+ tensors: list[torch.Tensor],
286
+ process_group_so: ScriptObject,
287
+ root_rank: int,
288
+ root_tensor: int,
289
+ async_op: bool = True,
290
+ timeout: int = -1,
291
+ ) -> tuple[list[torch.Tensor], ScriptObject]:
292
+ # "broadcast_(Tensor[] tensors, __torch__.torch.classes.c10d.ProcessGroup process_group, "
293
+ # "int root_rank, int root_tensor, bool async_op=True, int timeout=-1) -> (Tensor[], __torch__.torch.classes.c10d.Work)"
294
+ from . import LocalTensor
295
+
296
+ assert len(tensors) == 1
297
+ assert root_tensor == 0
298
+ tensor = tensors[0]
299
+
300
+ ranks, group_offsets, offset = _prepare_collective_groups(process_group_so)
301
+
302
+ # We're going to assume SPMD where for every rank group the root_rank is
303
+ # the same relative to others
304
+ relative_root_rank = root_rank - offset
305
+
306
+ assert isinstance(tensor, LocalTensor), "Input tensor must be a LocalTensor"
307
+
308
+ for group_offset in group_offsets:
309
+ # For the tensors in this group [group_offset + r for r in ranks]
310
+ # perform the broadcast on them
311
+ group_ranks = [group_offset + r for r in ranks]
312
+ if not all(rank in tensor._local_tensors for rank in group_ranks):
313
+ continue
314
+
315
+ source_rank = group_offset + relative_root_rank
316
+ source_tensor = tensor._local_tensors[source_rank]
317
+
318
+ # Broadcast the source tensor to all ranks in this group
319
+ for rank in group_ranks:
320
+ if source_rank != rank:
321
+ tensor._local_tensors[rank].copy_(source_tensor)
322
+
323
+ work = FakeWork()
324
+ work_so = Work.boxed(work)
325
+ return (tensors, work_so)
326
+
327
+
328
+ def _local_reduce(
329
+ reduce_op: ReduceOp | str,
330
+ tensors: list[torch.Tensor],
331
+ ) -> torch.Tensor:
332
+ if reduce_op == ReduceOp.SUM or reduce_op == "sum":
333
+ op = operator.add
334
+ elif reduce_op == ReduceOp.AVG or reduce_op == "avg":
335
+ op = None
336
+ elif reduce_op == ReduceOp.PRODUCT or reduce_op == "product":
337
+ op = operator.mul
338
+ elif reduce_op == ReduceOp.MIN or reduce_op == "min":
339
+ op = torch.minimum
340
+ elif reduce_op == ReduceOp.MAX or reduce_op == "max":
341
+ op = torch.maximum
342
+ elif reduce_op == ReduceOp.BAND or reduce_op == "band":
343
+ op = torch.bitwise_and
344
+ elif reduce_op == ReduceOp.BOR or reduce_op == "bor":
345
+ op = torch.bitwise_or
346
+ elif reduce_op == ReduceOp.BXOR or reduce_op == "bxor":
347
+ op = torch.bitwise_xor
348
+ elif reduce_op == ReduceOp.PREMUL_SUM or reduce_op == "premul_sum":
349
+ raise NotImplementedError("PREMUL_SUM: need to add binding for scaling factor")
350
+ else:
351
+ raise NotImplementedError(f"ReduceOp {reduce_op} not implemented")
352
+
353
+ if reduce_op == ReduceOp.AVG or reduce_op == "avg":
354
+ return functools.reduce(operator.add, tensors) / len(tensors)
355
+ else:
356
+ assert op is not None
357
+ return functools.reduce(op, tensors)
358
+
359
+
360
+ def _local_all_reduce_(
361
+ tensors: list[torch.Tensor],
362
+ process_group_so: ScriptObject,
363
+ reduce_op_so: ScriptObject,
364
+ sparse_indices: torch.Tensor | None = None,
365
+ async_op: bool = True,
366
+ timeout: int = -1,
367
+ ) -> tuple[list[torch.Tensor], ScriptObject]:
368
+ # "allreduce_(Tensor[] tensors, __torch__.torch.classes.c10d.ProcessGroup process_group, "
369
+ # "__torch__.torch.classes.c10d.ReduceOp reduce_op, Tensor? sparse_indices, bool async_op=True, "
370
+ # "int timeout=-1) -> (Tensor[], __torch__.torch.classes.c10d.Work)");
371
+ from . import LocalTensor
372
+
373
+ assert len(tensors) == 1
374
+ tensor = tensors[0]
375
+ reduce_op = reduce_op_so.op() # type: ignore[attr-defined]
376
+
377
+ ranks, group_offsets, _offset = _prepare_collective_groups(process_group_so)
378
+
379
+ assert isinstance(tensor, LocalTensor), "Input tensor must be a LocalTensor"
380
+
381
+ for group_offset in group_offsets:
382
+ # For the tensors in this group [group_offset + r for r in ranks]
383
+ # perform the allreduce on them
384
+ group_ranks = [group_offset + r for r in ranks]
385
+ if not all(rank in tensor._local_tensors for rank in group_ranks):
386
+ continue
387
+
388
+ # Collect tensors from the specified ranks in this group
389
+ group_tensors = []
390
+ for rank in group_ranks:
391
+ group_tensors.append(tensor._local_tensors[rank])
392
+
393
+ # Perform the reduction operation
394
+ reduced_tensor = _local_reduce(reduce_op, group_tensors)
395
+
396
+ # Update all tensors in the group with the reduced result
397
+ for rank in group_ranks:
398
+ tensor._local_tensors[rank].copy_(reduced_tensor)
399
+
400
+ work = FakeWork()
401
+ work_so = Work.boxed(work)
402
+ return (tensors, work_so)
403
+
404
+
405
+ def _local_allreduce_coalesced_(
406
+ tensors: list[torch.Tensor],
407
+ process_group_so: ScriptObject,
408
+ reduce_op_so: ScriptObject,
409
+ async_op: bool = True,
410
+ timeout: int = -1,
411
+ ) -> ScriptObject:
412
+ # "allreduce_coalesced_(Tensor[] tensors, __torch__.torch.classes.c10d.ProcessGroup process_group, "
413
+ # "__torch__.torch.classes.c10d.ReduceOp reduce_op, bool async_op=True, int timeout=-1) -> __torch__.torch.classes.c10d.Work"
414
+ from . import LocalTensor
415
+
416
+ reduce_op = reduce_op_so.op() # type: ignore[attr-defined]
417
+ ranks, group_offsets, _offset = _prepare_collective_groups(process_group_so)
418
+
419
+ for group_offset in group_offsets:
420
+ # For the tensors in this group [group_offset + r for r in ranks]
421
+ # perform the allreduce on all tensors together
422
+ group_ranks = [group_offset + r for r in ranks]
423
+
424
+ # For each tensor, perform the reduction operation
425
+ for tensor in tensors:
426
+ assert isinstance(tensor, LocalTensor), "Input tensor must be a LocalTensor"
427
+ if not all(rank in tensor._local_tensors for rank in group_ranks):
428
+ continue
429
+ # Collect tensors from the specified ranks in this group
430
+ group_tensors = []
431
+ for rank in group_ranks:
432
+ group_tensors.append(tensor._local_tensors[rank])
433
+
434
+ # Perform the reduction operation
435
+ reduced_tensor = _local_reduce(reduce_op, group_tensors)
436
+
437
+ # Update all tensors in the group with the reduced result
438
+ for rank in group_ranks:
439
+ tensor._local_tensors[rank].copy_(reduced_tensor)
440
+
441
+ work = FakeWork()
442
+ work_so = Work.boxed(work)
443
+ return work_so
444
+
445
+
446
+ def _local_reduce_scatter_tensor_coalesced_(
447
+ output_tensors: list[torch.Tensor],
448
+ input_tensors: list[torch.Tensor],
449
+ process_group_so: ScriptObject,
450
+ reduce_op_so: ScriptObject,
451
+ async_op: bool = True,
452
+ timeout: int = -1,
453
+ ) -> ScriptObject:
454
+ # "reduce_scatter_tensor_coalesced_(Tensor[] outputs, Tensor[] inputs, "
455
+ # "__torch__.torch.classes.c10d.ProcessGroup process_group, "
456
+ # "__torch__.torch.classes.c10d.ReduceOp reduce_op, bool async_op=True, "
457
+ # "int timeout=-1) -> __torch__.torch.classes.c10d.Work"
458
+
459
+ from . import LocalTensor
460
+
461
+ reduce_op = reduce_op_so.op() # type: ignore[attr-defined]
462
+ ranks, group_offsets, _offset = _prepare_collective_groups(process_group_so)
463
+
464
+ for group_offset in group_offsets:
465
+ # For the tensors in this group [group_offset + r for r in ranks]
466
+ # perform the allreduce on all tensors together
467
+ group_ranks = [group_offset + r for r in ranks]
468
+
469
+ # For each tensor, perform the reduction operation
470
+ for input_tensor, output_tensor in zip(input_tensors, output_tensors):
471
+ assert isinstance(input_tensor, LocalTensor), (
472
+ "Input tensor must be a LocalTensor"
473
+ )
474
+ assert isinstance(output_tensor, LocalTensor), (
475
+ "Output tensor must be a LocalTensor"
476
+ )
477
+ if not all(rank in input_tensor._local_tensors for rank in group_ranks):
478
+ continue
479
+ if not all(rank in output_tensor._local_tensors for rank in group_ranks):
480
+ continue
481
+
482
+ # Collect tensors from the specified ranks in this group
483
+ group_inputs = []
484
+ for rank in group_ranks:
485
+ group_inputs.append(input_tensor._local_tensors[rank])
486
+
487
+ # Perform the reduction operation
488
+ reduced_input = _local_reduce(reduce_op, group_inputs)
489
+
490
+ reduced_input_splits = torch.split(
491
+ reduced_input, reduced_input.size(0) // len(group_ranks), dim=0
492
+ )
493
+
494
+ # Update all tensors in the group with the reduced result
495
+ for i, rank in enumerate(group_ranks):
496
+ output_tensor._local_tensors[rank].copy_(reduced_input_splits[i])
497
+
498
+ work = FakeWork()
499
+ work_so = Work.boxed(work)
500
+ return work_so
501
+
502
+
503
+ def _local_allgather_base_(
504
+ output_tensor: torch.Tensor,
505
+ input_tensor: torch.Tensor,
506
+ process_group_so: ScriptObject,
507
+ async_op: bool = True,
508
+ timeout: int = -1,
509
+ ) -> tuple[torch.Tensor, ScriptObject]:
510
+ # "_allgather_base_(Tensor output_tensor, Tensor input_tensor, __torch__.torch.classes.c10d.ProcessGroup
511
+ # process_group, bool async_op=True, int timeout=-1) -> (Tensor, __torch__.torch.classes.c10d.Work)");
512
+ from . import LocalTensor
513
+
514
+ ranks, group_offsets, _offset = _prepare_collective_groups(process_group_so)
515
+
516
+ assert isinstance(output_tensor, LocalTensor), "Output tensor must be a LocalTensor"
517
+ assert isinstance(input_tensor, LocalTensor), "Input tensor must be a LocalTensor"
518
+
519
+ for group_offset in group_offsets:
520
+ group_ranks = [group_offset + r for r in ranks]
521
+
522
+ if not all(rank in input_tensor._local_tensors for rank in group_ranks):
523
+ continue
524
+ if not all(rank in output_tensor._local_tensors for rank in group_ranks):
525
+ continue
526
+
527
+ gathered_tensors = []
528
+ for rank_i in group_ranks:
529
+ gathered_tensors.append(input_tensor._local_tensors[rank_i])
530
+
531
+ gathered_tensor = torch.cat(gathered_tensors, dim=0)
532
+
533
+ for rank_i in group_ranks:
534
+ output_tensor._local_tensors[rank_i].copy_(gathered_tensor)
535
+
536
+ work = FakeWork()
537
+ work_so = Work.boxed(work)
538
+ return output_tensor, work_so
539
+
540
+
541
+ def _local_reduce_scatter_base_( # type: ignore[no-untyped-def]
542
+ output_tensor: torch.Tensor,
543
+ input_tensor: torch.Tensor,
544
+ process_group_so: ScriptObject,
545
+ reduce_op_so: ScriptObject,
546
+ async_op: bool = True,
547
+ timeout: int = -1,
548
+ ) -> tuple[torch.Tensor, ScriptObject]:
549
+ # "_reduce_scatter_base_(Tensor output_tensor, Tensor input_tensor,
550
+ # __torch__.torch.classes.c10d.ProcessGroup process_group, __torch__.torch.classes.c10d.ReduceOp reduce_op,
551
+ # bool async_op=True, int timeout=-1) -> (Tensor, __torch__.torch.classes.c10d.Work)"
552
+
553
+ from . import LocalTensor
554
+
555
+ reduce_op = reduce_op_so.op() # type: ignore[attr-defined]
556
+ ranks, group_offsets, _offset = _prepare_collective_groups(process_group_so)
557
+
558
+ assert isinstance(output_tensor, LocalTensor), "Output tensor must be a LocalTensor"
559
+ assert isinstance(input_tensor, LocalTensor), "Input tensor must be a LocalTensor"
560
+
561
+ for group_offset in group_offsets:
562
+ group_ranks = [group_offset + r for r in ranks]
563
+ if not all(rank in input_tensor._local_tensors for rank in group_ranks):
564
+ continue
565
+ if not all(rank in output_tensor._local_tensors for rank in group_ranks):
566
+ continue
567
+
568
+ gathered_tensors = []
569
+ for rank_i in group_ranks:
570
+ gathered_tensors.append(input_tensor._local_tensors[rank_i])
571
+
572
+ reduced_tensor = _local_reduce(reduce_op, gathered_tensors)
573
+
574
+ scattered_tensor = torch.split(
575
+ reduced_tensor,
576
+ reduced_tensor.size(0) // len(group_ranks),
577
+ dim=0,
578
+ )
579
+
580
+ for i, rank_i in enumerate(group_ranks):
581
+ output_tensor._local_tensors[rank_i].copy_(scattered_tensor[i].clone())
582
+
583
+ work = FakeWork()
584
+ work_so = Work.boxed(work)
585
+ return output_tensor, work_so
586
+
587
+
588
+ def _local_all_gather_(
589
+ output_tensors: list[list[torch.Tensor]],
590
+ input_tensors: list[torch.Tensor],
591
+ process_group_so: ScriptObject,
592
+ async_op: bool = True,
593
+ timeout: int = -1,
594
+ ) -> tuple[list[list[torch.Tensor]], ScriptObject]:
595
+ # "allgather_(Tensor[][] output_tensors, Tensor[] input_tensors, "
596
+ # "__torch__.torch.classes.c10d.ProcessGroup process_group, bool async_op=True, "
597
+ # "int timeout=-1) -> (Tensor[][], __torch__.torch.classes.c10d.Work)");
598
+
599
+ from . import LocalTensor
600
+
601
+ assert len(output_tensors) == 1
602
+ assert len(input_tensors) == 1
603
+
604
+ input_tensor = input_tensors[0]
605
+ # pyrefly: ignore [bad-assignment]
606
+ output_tensors = output_tensors[0]
607
+
608
+ ranks, group_offsets, _offset = _prepare_collective_groups(process_group_so)
609
+
610
+ for i in range(len(output_tensors)):
611
+ assert isinstance(output_tensors[i], LocalTensor), (
612
+ "Output tensor must be a LocalTensor"
613
+ )
614
+
615
+ for group_offset in group_offsets:
616
+ # For the tensors in this group [group_offset + r for r in ranks]
617
+ # perform the all_gather on them
618
+ group_ranks = [group_offset + r for r in ranks]
619
+
620
+ # For each rank in the group, gather from their input tensor
621
+ for i, rank_i in enumerate(group_ranks):
622
+ # allgather object happens to create pure tensor, so we special case it here
623
+ source_tensor = input_tensor
624
+ if isinstance(input_tensor, LocalTensor):
625
+ source_tensor = input_tensor._local_tensors[rank_i]
626
+ # pyrefly: ignore [missing-attribute]
627
+ output_tensors[i].copy_(source_tensor)
628
+
629
+ work = FakeWork()
630
+ work_so = Work.boxed(work)
631
+ # pyrefly: ignore [bad-return]
632
+ return ([output_tensors], work_so)
633
+
634
+
635
+ def _local_allgather_into_tensor_coalesced_(
636
+ output_tensors: list[torch.Tensor],
637
+ input_tensors: list[torch.Tensor],
638
+ process_group_so: ScriptObject,
639
+ async_op: bool = True,
640
+ ) -> ScriptObject:
641
+ # "allgather_into_tensor_coalesced_(Tensor[] outputs, Tensor[] inputs, "
642
+ # "__torch__.torch.classes.c10d.ProcessGroup process_group, bool async_op=True) "
643
+ # "-> __torch__.torch.classes.c10d.Work"
644
+ from . import LocalTensor
645
+
646
+ ranks, group_offsets, _offset = _prepare_collective_groups(process_group_so)
647
+
648
+ # Each output tensor should be sized to hold all gathered inputs
649
+ # outputs[i] will contain all inputs[i] from all ranks
650
+ assert len(output_tensors) == len(input_tensors), (
651
+ f"Number of outputs ({len(output_tensors)}) must match number of inputs ({len(input_tensors)})"
652
+ )
653
+
654
+ for group_offset in group_offsets:
655
+ # For the tensors in this group [group_offset + r for r in ranks]
656
+ # perform the allgather_into_tensor on them
657
+ group_ranks = [group_offset + r for r in ranks]
658
+
659
+ # For each input/output pair
660
+ for input_tensor, output_tensor in zip(input_tensors, output_tensors):
661
+ assert isinstance(input_tensor, LocalTensor), (
662
+ "Input tensor must be a LocalTensor"
663
+ )
664
+ assert isinstance(output_tensor, LocalTensor), (
665
+ "Output tensor must be a LocalTensor"
666
+ )
667
+
668
+ if not all(rank in input_tensor._local_tensors for rank in group_ranks):
669
+ continue
670
+ if not all(rank in output_tensor._local_tensors for rank in group_ranks):
671
+ continue
672
+
673
+ # Gather input_tensor from all ranks into output_tensor
674
+ # The output should be a concatenation of all inputs along the first dimension
675
+ gathered_tensors = []
676
+ for rank in group_ranks:
677
+ gathered_tensors.append(input_tensor._local_tensors[rank])
678
+
679
+ # Concatenate along first dimension and copy to output
680
+ if gathered_tensors:
681
+ concatenated = torch.cat(gathered_tensors, dim=0)
682
+ for rank in group_ranks:
683
+ output_tensor._local_tensors[rank].copy_(concatenated)
684
+
685
+ work = FakeWork()
686
+ work_so = Work.boxed(work)
687
+ return work_so
688
+
689
+
690
+ def _local_gather_(
691
+ output_tensors: list[list[torch.Tensor]],
692
+ input_tensors: list[torch.Tensor],
693
+ process_group_so: ScriptObject,
694
+ root_rank: int,
695
+ async_op: bool = True,
696
+ timeout: int = -1,
697
+ ) -> ScriptObject:
698
+ # "gather_(Tensor[][] output_tensors, Tensor[] input_tensors, "
699
+ # "__torch__.torch.classes.c10d.ProcessGroup process_group, int root_rank, "
700
+ # "bool async_op=True, int timeout=-1) -> __torch__.torch.classes.c10d.Work"
701
+ raise NotImplementedError(
702
+ "LocalTensor does not support MPMD operations like gather "
703
+ "(only root rank receives data). Use SPMD collective operations like allgather instead."
704
+ )
705
+
706
+
707
+ def _local_scatter_(
708
+ output_tensors: list[torch.Tensor],
709
+ input_tensors: list[list[torch.Tensor]],
710
+ process_group_so: ScriptObject,
711
+ root_rank: int,
712
+ async_op: bool = True,
713
+ timeout: int = -1,
714
+ ) -> tuple[list[torch.Tensor], ScriptObject]:
715
+ # "scatter_(Tensor[] output_tensors, Tensor[][] input_tensors, "
716
+ # "__torch__.torch.classes.c10d.ProcessGroup process_group, int root_rank, "
717
+ # "bool async_op=True, int timeout=-1) -> (Tensor[], __torch__.torch.classes.c10d.Work)");
718
+
719
+ from . import LocalTensor
720
+
721
+ assert len(output_tensors) == 1
722
+ assert len(input_tensors) == 1
723
+ output_tensor = output_tensors[0]
724
+ # pyrefly: ignore [bad-assignment]
725
+ input_tensors = input_tensors[0]
726
+
727
+ ranks, group_offsets, offset = _prepare_collective_groups(process_group_so)
728
+
729
+ # We're going to assume SPMD where for every rank group the root_rank is
730
+ # the same relative to others
731
+ relative_root_rank = root_rank - offset
732
+
733
+ assert isinstance(output_tensor, LocalTensor), "Output tensor must be a LocalTensor"
734
+ assert len(ranks) == len(input_tensors), (ranks, input_tensors)
735
+
736
+ for group_offset in group_offsets:
737
+ # For the tensors in this group [group_offset + r for r in ranks]
738
+ # perform the scatter on them
739
+ group_ranks = [group_offset + r for r in ranks]
740
+ if not all(rank in output_tensor._local_tensors for rank in group_ranks):
741
+ continue
742
+
743
+ # Root rank scatters its input tensors to all ranks in this group
744
+ for i, rank in enumerate(group_ranks):
745
+ input_tensor = input_tensors[i]
746
+ assert isinstance(input_tensor, LocalTensor)
747
+ # Each rank i gets the i-th input tensor from the root
748
+ source_tensor = input_tensor._local_tensors[
749
+ group_offset + relative_root_rank
750
+ ]
751
+ output_tensor._local_tensors[rank].copy_(source_tensor)
752
+
753
+ work = FakeWork()
754
+ work_so = Work.boxed(work)
755
+ return (output_tensors, work_so)
756
+
757
+
758
+ def _local_alltoall_(
759
+ output_tensors: list[torch.Tensor],
760
+ input_tensors: list[torch.Tensor],
761
+ process_group_so: ScriptObject,
762
+ async_op: bool = True,
763
+ timeout: int = -1,
764
+ ) -> tuple[list[torch.Tensor], ScriptObject]:
765
+ # "alltoall_(Tensor[] output_tensors, Tensor[] input_tensors, "
766
+ # "__torch__.torch.classes.c10d.ProcessGroup process_group, bool async_op=True, "
767
+ # "int timeout=-1) -> (Tensor[], __torch__.torch.classes.c10d.Work)";
768
+
769
+ from . import LocalTensor
770
+
771
+ ranks, group_offsets, _offset = _prepare_collective_groups(process_group_so)
772
+
773
+ assert len(input_tensors) == len(output_tensors) == len(ranks), (
774
+ f"Number of input tensors ({len(input_tensors)}), "
775
+ f"output tensors ({len(output_tensors)}), and ranks ({len(ranks)}) must match"
776
+ )
777
+
778
+ for group_offset in group_offsets:
779
+ # For the tensors in this group [group_offset + r for r in ranks]
780
+ # perform the alltoall on them
781
+ group_ranks = [group_offset + r for r in ranks]
782
+
783
+ # In alltoall, rank i sends input_tensors[j] to rank j and receives into output_tensors[i] from rank j
784
+ for i, rank_i in enumerate(group_ranks):
785
+ output_tensor = output_tensors[i]
786
+ assert isinstance(output_tensor, LocalTensor), (
787
+ "Output tensor must be a LocalTensor"
788
+ )
789
+
790
+ if not all(rank in output_tensor._local_tensors for rank in group_ranks):
791
+ continue
792
+
793
+ for j, rank_j in enumerate(group_ranks):
794
+ input_tensor = input_tensors[j]
795
+ assert isinstance(input_tensor, LocalTensor), (
796
+ "Input tensor must be a LocalTensor"
797
+ )
798
+
799
+ if not all(rank in input_tensor._local_tensors for rank in group_ranks):
800
+ continue
801
+
802
+ # Rank i's j-th input tensor goes to rank j's i-th output tensor
803
+ source_tensor = input_tensor._local_tensors[rank_i]
804
+ output_tensor._local_tensors[rank_j].copy_(source_tensor)
805
+
806
+ work = FakeWork()
807
+ work_so = Work.boxed(work)
808
+ return (output_tensors, work_so)
809
+
810
+
811
+ def _local_alltoall_base_(
812
+ output_tensor: torch.Tensor,
813
+ input_tensor: torch.Tensor,
814
+ process_group_so: ScriptObject,
815
+ output_split_sizes: list[int],
816
+ input_split_sizes: list[int],
817
+ async_op: bool = True,
818
+ timeout: int = -1,
819
+ ) -> ScriptObject:
820
+ # "alltoall_base_(Tensor output, Tensor input, __torch__.torch.classes.c10d.ProcessGroup process_group, "
821
+ # "int[] output_split_sizes, int[] input_split_sizes, bool async_op=True, int timeout=-1) -> __torch__.torch.classes.c10d.Work";
822
+
823
+ from . import LocalTensor
824
+
825
+ ranks, group_offsets, _offset = _prepare_collective_groups(process_group_so)
826
+
827
+ assert isinstance(input_tensor, LocalTensor), "Input tensor must be a LocalTensor"
828
+ assert isinstance(output_tensor, LocalTensor), "Output tensor must be a LocalTensor"
829
+ # Convert split sizes to lists if they aren't already
830
+ if output_split_sizes is not None:
831
+ output_split_sizes = list(output_split_sizes)
832
+ if input_split_sizes is not None:
833
+ input_split_sizes = list(input_split_sizes)
834
+
835
+ for group_offset in group_offsets:
836
+ # For the tensors in this group [group_offset + r for r in ranks]
837
+ # perform the alltoall_base on them
838
+ group_ranks = [group_offset + r for r in ranks]
839
+
840
+ if not all(rank in input_tensor._local_tensors for rank in group_ranks):
841
+ continue
842
+ if not all(rank in output_tensor._local_tensors for rank in group_ranks):
843
+ continue
844
+
845
+ for i, rank_i in enumerate(group_ranks):
846
+ # Split input tensor from rank_i according to input_split_sizes
847
+ rank_tensor = input_tensor._local_tensors[rank_i]
848
+
849
+ if input_split_sizes is not None and len(input_split_sizes) > 0:
850
+ # Split the input tensor
851
+ input_splits = torch.split(rank_tensor, input_split_sizes, dim=0)
852
+ else:
853
+ # No split sizes specified, split evenly
854
+ split_size = rank_tensor.size(0) // len(group_ranks)
855
+ input_splits = torch.split(rank_tensor, split_size, dim=0)
856
+
857
+ # Send each split to the corresponding rank
858
+ for j, rank_j in enumerate(group_ranks):
859
+ if j < len(input_splits):
860
+ split_tensor = input_splits[j]
861
+
862
+ # Determine where to place this split in the output tensor
863
+ if output_split_sizes is not None and len(output_split_sizes) > 0:
864
+ # Calculate offset based on output split sizes
865
+ output_offset = sum(output_split_sizes[:i]) if i > 0 else 0
866
+ end_offset = (
867
+ output_offset + output_split_sizes[i]
868
+ if i < len(output_split_sizes)
869
+ else output_tensor._local_tensors[rank_j].size(0)
870
+ )
871
+ else:
872
+ # No output split sizes, use even splits
873
+ split_size = output_tensor._local_tensors[rank_j].size(
874
+ 0
875
+ ) // len(group_ranks)
876
+ output_offset = i * split_size
877
+ end_offset = min(
878
+ (i + 1) * split_size,
879
+ output_tensor._local_tensors[rank_j].size(0),
880
+ )
881
+
882
+ # Copy the split to the appropriate section of the output tensor
883
+ output_section = output_tensor._local_tensors[rank_j][
884
+ output_offset:end_offset
885
+ ]
886
+ if output_section.numel() > 0:
887
+ # Reshape split_tensor to match output_section if necessary
888
+ if split_tensor.size() != output_section.size():
889
+ split_tensor = split_tensor.view(output_section.size())
890
+ output_section.copy_(split_tensor)
891
+
892
+ work = FakeWork()
893
+ work_so = Work.boxed(work)
894
+ return work_so
895
+
896
+
897
+ def _local_barrier(
898
+ tensor: torch.Tensor,
899
+ process_group_so: ScriptObject,
900
+ device_ids: list[int],
901
+ async_op: bool = True,
902
+ timeout: int = -1,
903
+ ) -> ScriptObject:
904
+ # "barrier(Tensor tensor, __torch__.torch.classes.c10d.ProcessGroup process_group, "
905
+ # "int[] device_ids, bool async_op=True, int timeout=-1) -> __torch__.torch.classes.c10d.Work";
906
+
907
+ from . import LocalTensor
908
+
909
+ # Barrier is a synchronization primitive - in local simulation,
910
+ # we don't need to do any actual work since all "ranks" are in the same process
911
+ # Just validate that the tensor is a LocalTensor
912
+ assert isinstance(tensor, LocalTensor)
913
+
914
+ # In a real distributed setting, barrier would synchronize all processes
915
+ # In local simulation, this is essentially a no-op since all ranks are local
916
+ work = FakeWork()
917
+ work_so = Work.boxed(work)
918
+ return work_so
919
+
920
+
921
+ def _local_monitored_barrier_(
922
+ tensor: torch.Tensor,
923
+ process_group_so: ScriptObject,
924
+ device_ids: list[int],
925
+ timeout: int,
926
+ wait_all_ranks: bool,
927
+ ) -> None:
928
+ # "monitored_barrier_(Tensor tensor, __torch__.torch.classes.c10d.ProcessGroup process_group, "
929
+ # "int[] device_ids, int timeout, bool wait_all_ranks) -> ()";
930
+
931
+ from . import LocalTensor
932
+
933
+ # Monitored barrier is a synchronization primitive with monitoring - in local simulation,
934
+ # we don't need to do any actual work since all "ranks" are in the same process
935
+ # Just validate that the tensor is a LocalTensor
936
+ assert isinstance(tensor, LocalTensor)
937
+
938
+ # In a real distributed setting, monitored barrier would synchronize all processes
939
+ # and provide monitoring capabilities. In local simulation, this is essentially a no-op
940
+ # since all ranks are local and no actual synchronization is needed
941
+ return
942
+
943
+
944
+ def _local_send(
945
+ tensors: list[torch.Tensor],
946
+ process_group_so: ScriptObject,
947
+ dst: int,
948
+ tag: int,
949
+ ) -> ScriptObject:
950
+ # "send(Tensor[] tensors, __torch__.torch.classes.c10d.ProcessGroup process_group, "
951
+ # "int dst, int tag) -> __torch__.torch.classes.c10d.Work";
952
+
953
+ from . import LocalRunnerMode, LocalTensor
954
+
955
+ assert len(tensors) == 1
956
+ tensor = tensors[0]
957
+
958
+ assert isinstance(tensor, LocalTensor), "Input tensor must be a Tensor"
959
+ src = int(tensor.__src_rank__)
960
+
961
+ LocalRunnerMode.current()._signal_send(src, dst, tensor._local_tensors[src])
962
+
963
+ work = FakeWork()
964
+ work_so = Work.boxed(work)
965
+ return work_so
966
+
967
+
968
+ def _local_recv_(
969
+ tensors: list[torch.Tensor],
970
+ process_group_so: ScriptObject,
971
+ src: int,
972
+ tag: int,
973
+ ) -> ScriptObject:
974
+ # "recv_(Tensor[] tensors, __torch__.torch.classes.c10d.ProcessGroup process_group, "
975
+ # "int src, int tag) -> __torch__.torch.classes.c10d.Work";
976
+ from . import LocalRunnerMode, LocalTensor
977
+
978
+ assert len(tensors) == 1
979
+ tensor = tensors[0]
980
+
981
+ assert isinstance(tensor, LocalTensor), "Input tensor must be a Tensor"
982
+ dst = int(tensor.__src_rank__)
983
+
984
+ def _recv_and_store(timeout: timedelta) -> bool:
985
+ def _wait_and_store(obj: object) -> None:
986
+ assert isinstance(obj, torch.Tensor), "Expected to receive a Tensor"
987
+ assert isinstance(tensor, LocalTensor), "Input tensor must be a Tensor"
988
+ tensor._local_tensors[dst] = obj
989
+
990
+ LocalRunnerMode.current()._wait_recv(src, dst, _wait_and_store)
991
+ return True
992
+
993
+ work = PythonCallbackWork(_recv_and_store)
994
+ work_so = Work.boxed(work)
995
+ return work_so
996
+
997
+
998
+ def _local_recv_any_source_(
999
+ tensors: list[torch.Tensor], process_group_so: ScriptObject, tag: int
1000
+ ) -> ScriptObject:
1001
+ # "recv_any_source_(Tensor[] tensors, __torch__.torch.classes.c10d.ProcessGroup process_group, "
1002
+ # "int tag) -> __torch__.torch.classes.c10d.Work";
1003
+
1004
+ return _local_recv_(tensors, process_group_so, -1, tag)
1005
+
1006
+
1007
+ def _attach_rank(tensor: torch.Tensor, rank: int) -> torch.Tensor:
1008
+ """
1009
+ Attaches rank as an attribute to given tensor so that the send or recv implementation
1010
+ knows which rank initiates the operation (note under local tensor mode ).
1011
+ """
1012
+ from torch.distributed.tensor import DTensor
1013
+
1014
+ if isinstance(tensor, DTensor):
1015
+ tensor = tensor._local_tensor
1016
+
1017
+ tensor.__src_rank__ = rank # type: ignore[attr-defined]
1018
+ return tensor
1019
+
1020
+
1021
+ def local_p2p_op(
1022
+ dst: torch.SymInt,
1023
+ tensor: torch.Tensor,
1024
+ op: Callable[[torch.Tensor, int], Work | None],
1025
+ ) -> Work | None | list[Work | None]:
1026
+ """
1027
+ Runs a point-to-point (P2P) operation for all combinations of source and destination ranks.
1028
+ """
1029
+ _check_op(op)
1030
+
1031
+ from . import LocalIntNode
1032
+
1033
+ assert isinstance(dst.node, LocalIntNode), (
1034
+ "Expected 'dst' to be a LocalIntNode where the value is the destination rank and key is the source rank"
1035
+ )
1036
+
1037
+ w = []
1038
+ for s, d in dst.node._local_ints.items():
1039
+ tensor = _attach_rank(tensor, s)
1040
+ w.append(op(tensor, d))
1041
+ return w
1042
+
1043
+
1044
+ def wait_all(work: Work | None | list[Work | None]) -> None:
1045
+ """
1046
+ Waits for all work objects in the input to complete.
1047
+
1048
+ A single Work object, None, or a list of Work objects (possibly containing None).
1049
+ If None, does nothing. If a single Work, waits for it to complete. If a list, waits
1050
+ for each non-None Work in the list to complete.
1051
+ """
1052
+
1053
+ if work is None:
1054
+ return
1055
+ if isinstance(work, Work):
1056
+ work = [work]
1057
+ for w in work:
1058
+ if w is None:
1059
+ continue
1060
+ w.wait()
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_mesh_layout.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Definition of CuTe inspired Layouts for DeviceMesh internal bookkeeping and functions to manipulate them
3
+ """
4
+
5
+ import math
6
+ from collections.abc import Iterator
7
+ from dataclasses import dataclass
8
+ from itertools import product
9
+
10
+ import torch
11
+ from torch.distributed._pycute import (
12
+ as_tuple,
13
+ coalesce,
14
+ complement,
15
+ composition,
16
+ flatten,
17
+ IntTuple,
18
+ is_int,
19
+ is_tuple,
20
+ Layout,
21
+ match_structure,
22
+ )
23
+
24
+
25
+ @dataclass(frozen=True, init=True)
26
+ class _MeshLayout(Layout):
27
+ """
28
+ Utility class for representing an integer layout by borrowing ideas from CuTe Layout Algebra.
29
+ See https://docs.nvidia.com/cutlass/media/docs/cpp/cute/02_layout_algebra.html for more details.
30
+
31
+ Each layout is represented as a list of sizes and strides. We use it as a way for mechanical bookkeeping
32
+ of the integers such as ranks in a SPMD mesh, and the transformation on top of it.
33
+
34
+ Lots of methods of layout like coalesce, composition, complement, etc. are borrowed from pycute.
35
+ https://github.com/NVIDIA/cutlass/blob/6dd13d42784ee5bfa232d2441e6b9a021c5c6290/python/pycute/layout.py#L137,L257
36
+
37
+ Note this is a CuTe-inspired layout, because CuTe uses co-lexicographic way in linearization while PyTorch
38
+ is using lexicographic. So even though the CuTe documentation can still be referenced, the implementation will be
39
+ different from that of PyCute's.
40
+ """
41
+
42
+ # pyrefly: ignore [bad-override]
43
+ shape: IntTuple
44
+ # pyrefly: ignore [bad-override]
45
+ stride: IntTuple
46
+
47
+ def __post_init__(self) -> None:
48
+ if not is_tuple(self.shape) and not is_int(self.shape):
49
+ raise TypeError(f"shape must be a tuple or int, got {type(self.shape)}")
50
+ if not is_tuple(self.stride) and not is_int(self.stride):
51
+ raise TypeError(f"stride must be a tuple or int, got {type(self.stride)}")
52
+ if not match_structure(self.shape, self.stride):
53
+ raise ValueError(
54
+ f"sizes {self.shape} and strides {self.stride} don't match"
55
+ )
56
+
57
+ @property
58
+ def sizes(self) -> IntTuple:
59
+ return self.shape
60
+
61
+ @property
62
+ def strides(self) -> IntTuple:
63
+ return self.stride
64
+
65
+ @property
66
+ def sizes_and_strides(self) -> Iterator[tuple[int, int]]:
67
+ return zip(flatten(self.shape), flatten(self.stride))
68
+
69
+ @property
70
+ def top_level_sizes(self) -> tuple[int, ...]:
71
+ return tuple(self[i].numel() for i in range(len(self)))
72
+
73
+ def numel(self) -> int:
74
+ return math.prod(flatten(self.shape))
75
+
76
+ # # operator [] (get-i like tuples)
77
+ def __getitem__(self, i: int) -> "_MeshLayout":
78
+ if i < -len(self) or i >= len(self):
79
+ raise IndexError(
80
+ f"Dim {i} is out of range for layout with {len(self)} dimensions. "
81
+ f"Expected dim to be in range [{-len(self)}, {len(self) - 1}]."
82
+ )
83
+ layout = super().__getitem__(i)
84
+ return _MeshLayout(layout.shape, layout.stride)
85
+
86
+ def nest(self) -> "_MeshLayout":
87
+ return _MeshLayout((self.shape,), (self.stride,))
88
+
89
+ def coalesce(self) -> "_MeshLayout":
90
+ """
91
+ A layout is represented by (sizes):(strides), e.g. (3,2):(4,2).
92
+ Two consecutive dimensions can be "merged" into one if their
93
+ strides are contiguous/multiplicative (i.e., the inner stride * inner size
94
+ equals the next stride), we perform this kind of merge inside coalesce.
95
+
96
+ Example 1 (simple): (3,2):(2,1)
97
+ - inner dimension: has stride=1, size=2
98
+ - outer dimension: stride = inner_stride * inner_size = 2
99
+ → coalesced = (6:1) # acts like a flat 1D array of length 6
100
+
101
+ Example 2 (non-coalescible): (3,2):(4,1)
102
+ - inner dimension: stride=1, size=2 → 2*1 = 2
103
+ - outer dimension: stride=4, mismatch (≠ 2)
104
+ → cannot merge; result stays (3,2):(4,1)
105
+ """
106
+ layout = coalesce(self)
107
+ return _MeshLayout(layout.shape, layout.stride)
108
+
109
+ def composition(self, layout: "_MeshLayout") -> "_MeshLayout":
110
+ """
111
+ By-dimension composition allows one layout to "select from" or "filter through" another layout.
112
+ Think of it as function composition: (self ∘ layout)(input) = self(layout(input))
113
+ between two layouts. This function is a wrapper of pycute's composition.
114
+
115
+ Mental model about how to understand the composition logic:
116
+ - The LEFT layout (self) defines the "output space" - what indices are possible
117
+ - The RIGHT layout (layout parameter) acts as a "selector" - which specific indices to pick
118
+ - The composition only generates indices that the left layout could originally produce,
119
+ but the right layout determines which indices to be picked.
120
+ - The stride of the composition layout will not be smaller than the stride of the right layout,
121
+ because when picking the indices the composition will at least follow the the right layout's stride
122
+ to move forward.
123
+
124
+ Example:
125
+ self = (6,2):(2,1) # sizes=(6,2), strides=(2,1)
126
+ layout = (3:2) # sizes=(3,), stride=(2,)
127
+ self o layout = (3:2)
128
+
129
+ Returns:
130
+ Layout being composed.
131
+ """
132
+ result = composition(self, layout)
133
+ return _MeshLayout(result.shape, result.stride)
134
+
135
+ def complement(self, world_size: int) -> "_MeshLayout":
136
+ """
137
+ Compute the "complement layout" relative to a given world_size.
138
+ A complement layout fills in the "missing" factor so that: self repeat a layout of complement(self, world_size)
139
+ will get a complete world_size. We use ⊗ to denote the repeat operation.
140
+
141
+ Example:
142
+ self = (4:1) # size=4, stride=1
143
+ world_size = 8
144
+ Then:
145
+ complete needed factor = 8 / 4 = 2
146
+ complement(self, 8) = (2:1)
147
+
148
+ Together they form:
149
+ (4:1) ⊗ (2:1) = (4,2):(2,1)
150
+ which has world_size = 4 * 2 = 8, as required.
151
+
152
+ In distributed terms, complement() is often used to derive the "other"
153
+ rank grouping when splitting processes into 2D meshes.
154
+
155
+ For a visualized explanation, see https://x.com/ezyang/status/1962364978393981433/
156
+ """
157
+ layout = complement(self, world_size)
158
+ return _MeshLayout(layout.shape, layout.stride)
159
+
160
+ def splice(self, start: int, end: int, layout: "_MeshLayout") -> "_MeshLayout":
161
+ sizes = list(as_tuple(self.sizes))
162
+ strides = list(as_tuple(self.strides))
163
+ sizes[start:end] = list(as_tuple(layout.sizes))
164
+ strides[start:end] = list(as_tuple(layout.strides))
165
+ return _MeshLayout(tuple(sizes), tuple(strides))
166
+
167
+ def all_ranks_from_zero(self) -> list[int]:
168
+ """
169
+ This function computes the all ranks specified by the layout staring from zero.
170
+
171
+ How it works:
172
+ 1. we enumerates every possible coordinate (like a nested for-loop).
173
+ If sizes = (2, 3), we get the following coordinates:
174
+ (0,0), (0,1), (0,2), (1,0), (1,1), (1,2)
175
+
176
+ 2. For each coordinate, we compute a linear rank index as:
177
+ all_ranks_from_zero = sum(coord[i] * strides[i] for i in range(ndim))
178
+
179
+ Example A:
180
+ sizes = (2, 3) # 2 rows, 3 cols
181
+ strides = (3, 1) # row-major layout
182
+ coords = (0,0) -> 0*3 + 0*1 = 0
183
+ (0,1) -> 0*3 + 1*1 = 1
184
+ (0,2) -> 0*3 + 2*1 = 2
185
+ (1,0) -> 1*3 + 0*1 = 3
186
+ (1,1) -> 1*3 + 1*1 = 4
187
+ (1,2) -> 1*3 + 2*1 = 5
188
+ result = [0, 1, 2, 3, 4, 5]
189
+
190
+ Example B:
191
+ sizes = (2, 3)
192
+ strides = (1, 2) # non-standard / strided layout
193
+ coords = (0,0) -> 0*1 + 0*2 = 0
194
+ (0,1) -> 0*1 + 1*2 = 2
195
+ (0,2) -> 0*1 + 2*2 = 4
196
+ (1,0) -> 1*1 + 0*2 = 1
197
+ (1,1) -> 1*1 + 1*2 = 3
198
+ (1,2) -> 1*1 + 2*2 = 5
199
+ result = [0, 2, 4, 1, 3, 5]
200
+ """
201
+ return [
202
+ sum(c * s for c, s in zip(coord, flatten(self.strides)))
203
+ for coord in product(*(range(s) for s in flatten(self.sizes)))
204
+ ]
205
+
206
+ def global_ranks(self, world_size: int) -> list[list[int]]:
207
+ """
208
+ Build global ranks specified by the layout via two-level ranks composition.
209
+
210
+ The nested list forms the Cartesian product of all ranks for one layout and offset
211
+ regarding filling up the world_size with the layout.
212
+ The final global ranks are the addition of these two. The result is a
213
+ list of lists: one sublist per layout. This rank list will be used to build
214
+ the communicator underlying the layout and the given `world_size`.
215
+
216
+ Example:
217
+ world_size = 16
218
+ self.size = 4
219
+ self.stride = 1
220
+ ranks = [0, 1, 2, 3]
221
+ offsets = [0, 4, 8, 12]
222
+ result = [
223
+ [0+0, 0+1, 0+2, 0+3], # → [0, 1, 2, 3]
224
+ [4+0, 4+1, 4+2, 4+3], # → [4, 5, 6, 7]
225
+ [8+0, 8+1, 8+2, 8+3], # → [8, 9, 10,11]
226
+ [12+0, 12+1, 12+2, 12+3], # → [12,13,14,15]
227
+ ]
228
+ """
229
+ return [
230
+ [offset + rank for rank in self.all_ranks_from_zero()]
231
+ for offset in self.complement(world_size).all_ranks_from_zero()
232
+ ]
233
+
234
+ def check_non_overlap(self) -> bool:
235
+ """
236
+ Check if the layout has any overlap between the ranks it generates. If there is overlap,
237
+ we return False, otherwise True.
238
+
239
+ The layout is supposed to be injective i.e, aside from indice 0, indices from each
240
+ dim of the layout must be non-overlapping.
241
+
242
+ Example 1 - Valid (no overlap):
243
+ Layout: sizes=(2,3), strides=(6,1)
244
+ - Dim 1: stride=1, span=3*1=3, covers indices [0,1,2]
245
+ - Dim 0: stride=6, span=2*6=12, covers indices [0,6]
246
+ → No overlap since 6 > 3
247
+
248
+ Example 2 - Invalid (overlap):
249
+ Layout: sizes=(2,3), strides=(2,1)
250
+ - Dim 1: stride=1, span=3*1=3, covers indices [0,1,2]
251
+ - Dim 0: stride=2, span=2*2=4, covers indices [0,2]
252
+ → Overlap! stride=2 < span=3, so indices [0,2] are duplicated
253
+
254
+ Example 3 - Invalid (overlap):
255
+ Layout: sizes=(4,2), strides=(1,1)
256
+ - Dim 1: stride=1, span=4, covers indices [0,1,2,3]
257
+ - Dim 0: stride=1, span=2, covers indices [0,1]
258
+ → Overlap! stride is same for two dims, so indices [0,2] are duplicated
259
+
260
+ Returns:
261
+ bool: True if no overlap, False if overlap detected
262
+ """
263
+ ranks = self.all_ranks_from_zero()
264
+ return len(ranks) == len(set(ranks))
265
+
266
+ def remap_to_tensor(self, rank_map: torch.Tensor) -> torch.Tensor:
267
+ """
268
+ Leverage layout as an index for mesh tensor that re-maps the indexes after layout
269
+ transformation to actual device ranks.
270
+
271
+ With this method, the cute layout serves as the backend of indices bookkeeping for the
272
+ mesh tensor when it comes to flatten, unflatten and slicing operations. The actual mesh
273
+ tensor still represents the actual device assignment and ranks. We need this function
274
+ to specify device allocation and create backend for a mesh. Although any transform of mesh tensors
275
+ can be treated as a view or subset of mesh tensor, we do need to use the actual view or
276
+ sub-tensor for DeviceMesh and its backend creation.
277
+
278
+ The shape of the `rank_map` must be 1D and contiguous.
279
+
280
+ Examples:
281
+
282
+ Case 1 - Consecutive ranks, full world:
283
+ original_mesh_tensor = [[0,1],[2,3]] # 2x2 mesh, ranks 0-3
284
+ world_size = 4
285
+ layout = Layout(2:2)
286
+ Return: [[0,2],[1,3]]
287
+
288
+ Case 2 - Non-consecutive ranks:
289
+ original_mesh_tensor = [[10,20],[30,40]] # custom rank assignment
290
+ world_size = 4
291
+ layout = Layout(2:2)
292
+ Return: [[[10,30],[20,40]]]
293
+
294
+ Args:
295
+ rank_map: The concrete mesh tensor with actual device ranks
296
+
297
+ Returns:
298
+ torch.Tensor: A tensor representing the actual device allocation from rank_map
299
+ """
300
+ assert rank_map.ndim == 1
301
+ assert rank_map.is_contiguous()
302
+ assert rank_map.numel() >= self.cosize()
303
+
304
+ complement_layout = self.complement(rank_map.numel())
305
+
306
+ return rank_map.as_strided(
307
+ flatten(complement_layout.sizes) + flatten(self.sizes),
308
+ flatten(complement_layout.strides) + flatten(self.strides),
309
+ ).reshape(-1, *self.top_level_sizes)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_pycute/__init__.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #################################################################################################
2
+ #
3
+ # Copyright (c) 2023 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
+ # SPDX-License-Identifier: BSD-3-Clause
5
+ #
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted provided that the following conditions are met:
8
+ #
9
+ # 1. Redistributions of source code must retain the above copyright notice, this
10
+ # list of conditions and the following disclaimer.
11
+ #
12
+ # 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ # this list of conditions and the following disclaimer in the documentation
14
+ # and/or other materials provided with the distribution.
15
+ #
16
+ # 3. Neither the name of the copyright holder nor the names of its
17
+ # contributors may be used to endorse or promote products derived from
18
+ # this software without specific prior written permission.
19
+ #
20
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+ #
31
+ #################################################################################################
32
+
33
+ from .int_tuple import (
34
+ as_tuple,
35
+ crd2crd,
36
+ crd2idx,
37
+ elem_scale,
38
+ flatten,
39
+ has_none,
40
+ idx2crd,
41
+ inner_product,
42
+ IntTuple,
43
+ is_int,
44
+ is_tuple,
45
+ match_structure,
46
+ product,
47
+ shape_div,
48
+ signum,
49
+ slice_,
50
+ suffix_product,
51
+ tuple_max,
52
+ )
53
+ from .layout import (
54
+ coalesce,
55
+ complement,
56
+ composition,
57
+ cosize,
58
+ filter,
59
+ is_layout,
60
+ Layout,
61
+ LayoutBase,
62
+ left_inverse,
63
+ logical_divide,
64
+ logical_product,
65
+ make_layout,
66
+ right_inverse,
67
+ size,
68
+ slice_and_offset,
69
+ tiled_divide,
70
+ tiled_product,
71
+ zipped_divide,
72
+ zipped_product,
73
+ )
74
+ from .typing import Integer
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_pycute/int_tuple.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #################################################################################################
2
+ #
3
+ # Copyright (c) 2023 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
+ # SPDX-License-Identifier: BSD-3-Clause
5
+ #
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted provided that the following conditions are met:
8
+ #
9
+ # 1. Redistributions of source code must retain the above copyright notice, this
10
+ # list of conditions and the following disclaimer.
11
+ #
12
+ # 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ # this list of conditions and the following disclaimer in the documentation
14
+ # and/or other materials provided with the distribution.
15
+ #
16
+ # 3. Neither the name of the copyright holder nor the names of its
17
+ # contributors may be used to endorse or promote products derived from
18
+ # this software without specific prior written permission.
19
+ #
20
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+ #
31
+ #################################################################################################
32
+
33
+ """
34
+ Functions for manipulating IntTuples
35
+ """
36
+
37
+ from functools import reduce
38
+ from itertools import chain
39
+ from typing import TypeAlias
40
+ from typing_extensions import TypeIs
41
+
42
+ from .typing import Integer
43
+
44
+
45
+ # Type aliases for better readability
46
+ IntTuple: TypeAlias = int | tuple["IntTuple", ...]
47
+
48
+
49
+ def is_int(x: object) -> TypeIs[int]:
50
+ return isinstance(x, Integer)
51
+
52
+
53
+ def is_tuple(x: object) -> TypeIs[tuple]:
54
+ return isinstance(x, tuple)
55
+
56
+
57
+ def as_tuple(x: IntTuple) -> tuple[IntTuple, ...]:
58
+ if is_int(x):
59
+ return (x,)
60
+ return x
61
+
62
+
63
+ def match_structure(a: IntTuple, b: IntTuple) -> bool:
64
+ if is_int(a) and is_int(b):
65
+ return True
66
+ if is_tuple(a) and is_tuple(b):
67
+ return len(a) == len(b) and all(match_structure(x, y) for x, y in zip(a, b))
68
+ return False
69
+
70
+
71
+ def flatten(t: IntTuple) -> tuple[int, ...]:
72
+ if is_tuple(t):
73
+ if len(t) == 0:
74
+ return ()
75
+ else:
76
+ return tuple(i for a in t for i in flatten(a))
77
+ else:
78
+ return (t,)
79
+
80
+
81
+ def signum(a: int) -> int:
82
+ return bool(a > 0) - bool(a < 0)
83
+
84
+
85
+ def product(a: IntTuple) -> int:
86
+ if is_tuple(a):
87
+ return reduce(lambda val, elem: val * product(elem), a, 1)
88
+ else:
89
+ return a
90
+
91
+
92
+ def inner_product(a: IntTuple, b: IntTuple) -> int:
93
+ if is_tuple(a) and is_tuple(b): # tuple tuple
94
+ assert len(a) == len(b)
95
+ return sum(inner_product(x, y) for x, y in zip(a, b))
96
+ else: # "int" "int"
97
+ assert not is_tuple(a) and not is_tuple(b)
98
+ return a * b
99
+
100
+
101
+ def tuple_max(a: IntTuple) -> int:
102
+ if is_tuple(a):
103
+ return max(tuple_max(x) for x in a)
104
+ else:
105
+ return a
106
+
107
+
108
+ def elem_scale(a: IntTuple, b: IntTuple) -> IntTuple:
109
+ if is_tuple(a):
110
+ if is_tuple(b): # tuple tuple
111
+ assert len(a) == len(b)
112
+ return tuple(elem_scale(x, y) for x, y in zip(a, b))
113
+ else: # tuple "int"
114
+ raise AssertionError("Invalid combination: tuple with int")
115
+ else:
116
+ if is_tuple(b): # "int" tuple
117
+ return elem_scale(a, product(b))
118
+ else: # "int" "int"
119
+ return a * b
120
+
121
+
122
+ # Inclusive prefix ceil div with output congruent to input a
123
+ def shape_div(a: IntTuple, b: IntTuple) -> IntTuple:
124
+ if is_tuple(a):
125
+ if is_tuple(b): # tuple tuple
126
+ assert len(a) == len(b)
127
+ return tuple(shape_div(x, y) for x, y in zip(a, b))
128
+ else: # tuple "int"
129
+ # r = [shape_div(a[0],b)] + [shape_div(a[i],b := shape_div(b, product(a[i-1]))) for i in range(1,len(a))]
130
+ r = []
131
+ for v in a:
132
+ r.append(shape_div(v, b))
133
+ b = shape_div(b, product(v))
134
+ return tuple(r)
135
+ else:
136
+ if is_tuple(b): # "int" tuple
137
+ return shape_div(a, product(b))
138
+ else: # "int" "int"
139
+ assert a % b == 0 or b % a == 0
140
+ return (a + b - 1) // b
141
+
142
+
143
+ # Exclusive suffix product with output congruent to input a (lexicographic)
144
+ def suffix_product(a: IntTuple, init: IntTuple = 1) -> IntTuple:
145
+ # TODO: With all these length asserts, may want to create a zip_strict wrapper.
146
+ if is_tuple(a):
147
+ if is_tuple(init): # tuple tuple
148
+ assert len(a) == len(init)
149
+ return tuple(suffix_product(x, i) for x, i in zip(a, init))
150
+ else: # tuple "int"
151
+ # Process from right to left for lexicographic ordering
152
+ # r = [prefix_product(a[len(a)-1],init)] +
153
+ # [prefix_product(a[i],init := init * product(a[i+1])) for i in range(len(a)-1,0)].reverse()
154
+ r = []
155
+
156
+ # Calculate products from right to left, appending to list
157
+ for i in range(len(a) - 1, -1, -1):
158
+ r.append(suffix_product(a[i], init))
159
+ init = init * product(a[i])
160
+
161
+ # Reverse to get correct lexicographic order
162
+ r.reverse()
163
+ return tuple(r)
164
+ else:
165
+ if is_tuple(init): # "int" tuple
166
+ raise AssertionError("Invalid combination: int with tuple init")
167
+ else: # "int" "int"
168
+ return init
169
+
170
+
171
+ def idx2crd(idx: IntTuple, shape: IntTuple, stride: IntTuple | None = None) -> IntTuple:
172
+ if stride is None:
173
+ stride = suffix_product(shape)
174
+
175
+ if is_tuple(idx):
176
+ if is_tuple(shape) and is_tuple(stride): # tuple tuple tuple
177
+ assert len(idx) == len(shape) and len(stride) == len(shape)
178
+ return tuple(idx2crd(i, s, d) for i, s, d in zip(idx, shape, stride))
179
+ else: # tuple "int" "int"
180
+ raise AssertionError("Invalid combination: tuple with int stride")
181
+ else:
182
+ if is_tuple(shape) and is_tuple(stride): # "int" tuple tuple
183
+ assert len(shape) == len(stride)
184
+ return tuple(idx2crd(idx, s, d) for s, d in zip(shape, stride))
185
+ else: # "int" "int" "int"
186
+ assert not is_tuple(shape) and not is_tuple(stride)
187
+ return (idx // stride) % shape # all are ints after type checks
188
+
189
+
190
+ def crd2idx(
191
+ crd: IntTuple | None, shape: IntTuple, stride: IntTuple | None = None
192
+ ) -> int:
193
+ if stride is None:
194
+ stride = suffix_product(shape)
195
+
196
+ if is_tuple(crd):
197
+ if is_tuple(shape) and is_tuple(stride): # tuple tuple tuple
198
+ assert len(crd) == len(shape) and len(stride) == len(shape)
199
+ return sum(crd2idx(c, s, d) for c, s, d in zip(crd, shape, stride))
200
+ else: # tuple "int" "int"
201
+ raise AssertionError(f"Invalid combination: crd={crd}, shape={shape}")
202
+ else:
203
+ if crd is None:
204
+ crd = 0
205
+
206
+ if is_tuple(shape) and is_tuple(stride): # "int" tuple tuple
207
+ assert len(shape) == len(stride)
208
+ result = 0
209
+ # Process from right to left for lexicographic ordering
210
+ for i in range(len(shape) - 1, 0, -1):
211
+ result += crd2idx(crd % product(shape[i]), shape[i], stride[i])
212
+ crd = crd // product(shape[i])
213
+ if len(shape) > 0:
214
+ result += crd2idx(crd, shape[0], stride[0])
215
+ return result
216
+ else: # "int" "int" "int"
217
+ assert not is_tuple(shape) and not is_tuple(stride)
218
+ return crd * stride # all are ints after type checks
219
+
220
+
221
+ # Transform crd into the dst_shape's iteration space
222
+ def crd2crd(
223
+ crd: IntTuple, dst_shape: IntTuple, src_shape: IntTuple | None = None
224
+ ) -> IntTuple:
225
+ if is_tuple(crd):
226
+ if is_tuple(dst_shape): # tuple tuple
227
+ assert len(crd) == len(dst_shape)
228
+ return tuple(crd2crd(x, y) for x, y in zip(crd, dst_shape))
229
+ else: # tuple "int"
230
+ # Ambiguous unless we have src_shape
231
+ assert src_shape is not None
232
+ return crd2idx(crd, src_shape)
233
+ else:
234
+ if is_tuple(dst_shape): # "int" tuple
235
+ return idx2crd(crd, dst_shape)
236
+ else: # "int" "int"
237
+ assert crd < dst_shape
238
+ return crd
239
+
240
+
241
+ # Filter trg according to crd: keep only elements of trg that are paired with None
242
+ def slice_(crd: None | tuple | int, trg: tuple | int) -> tuple | int:
243
+ if is_tuple(crd):
244
+ if is_tuple(trg): # tuple tuple
245
+ assert len(crd) == len(trg)
246
+ # match C++ behavior of `filter_tuple` using `tuple_cat(...)`
247
+ return tuple(
248
+ chain(
249
+ *filter( # type: ignore[arg-type] # filter returns Iterator which is compatible
250
+ lambda x: x != (),
251
+ [slice_(c, s) for c, s in zip(crd, trg)],
252
+ )
253
+ )
254
+ )
255
+ else:
256
+ raise AssertionError("Invalid combination: tuple crd with int trg")
257
+ elif crd is None:
258
+ # match C++ behavior `return cute::tuple<B>{b};`
259
+ return (trg,)
260
+ else:
261
+ return ()
262
+
263
+
264
+ # Determine if None appears at any of an int_tuples' terminals
265
+ def has_none(a: None | tuple | int) -> bool:
266
+ if is_tuple(a):
267
+ return any(has_none(v) for v in a)
268
+ else:
269
+ return a is None
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_pycute/layout.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #################################################################################################
2
+ #
3
+ # Copyright (c) 2023 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
+ # SPDX-License-Identifier: BSD-3-Clause
5
+ #
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted provided that the following conditions are met:
8
+ #
9
+ # 1. Redistributions of source code must retain the above copyright notice, this
10
+ # list of conditions and the following disclaimer.
11
+ #
12
+ # 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ # this list of conditions and the following disclaimer in the documentation
14
+ # and/or other materials provided with the distribution.
15
+ #
16
+ # 3. Neither the name of the copyright holder nor the names of its
17
+ # contributors may be used to endorse or promote products derived from
18
+ # this software without specific prior written permission.
19
+ #
20
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+ #
31
+ #################################################################################################
32
+
33
+ """
34
+ Definition of CuTe Layouts and functions to manipulate them which works with the order
35
+ of lexicographic instead of co-lexicographic as implemented in the original layout.py
36
+ """
37
+
38
+ from itertools import chain
39
+ from typing import TypeAlias
40
+ from typing_extensions import Self, TypeIs
41
+
42
+ from .int_tuple import (
43
+ crd2idx,
44
+ flatten,
45
+ has_none,
46
+ IntTuple,
47
+ is_int,
48
+ is_tuple,
49
+ product,
50
+ slice_,
51
+ suffix_product,
52
+ )
53
+
54
+
55
+ # Type aliases
56
+ CoordinateType: TypeAlias = (
57
+ int | IntTuple | tuple[object, ...] | None
58
+ ) # Input for slice_ and crd2idx functions
59
+
60
+
61
+ class LayoutBase:
62
+ pass
63
+
64
+
65
+ def is_layout(x: object) -> TypeIs["Layout"]:
66
+ return isinstance(x, LayoutBase)
67
+
68
+
69
+ class Layout(LayoutBase):
70
+ def __init__(self, _shape: IntTuple, _stride: IntTuple | None = None) -> None:
71
+ self.shape = _shape
72
+ if _stride is None:
73
+ self.stride = suffix_product(self.shape)
74
+ else:
75
+ self.stride = _stride
76
+
77
+ # operator ==
78
+ def __eq__(self, other: object) -> bool:
79
+ if not isinstance(other, Layout):
80
+ return False
81
+ return self.shape == other.shape and self.stride == other.stride
82
+
83
+ # operator len(L) (len [rank] like tuples)
84
+ def __len__(self) -> int:
85
+ if is_tuple(self.shape):
86
+ return len(self.shape)
87
+ else:
88
+ return 1
89
+
90
+ # operator () (map coord to idx)
91
+ def __call__(self, *args: CoordinateType) -> Self | int:
92
+ """
93
+ Map a logical coordinate to a linear index (Coord has no Underscore slice operators)
94
+ OR
95
+ Slice the layout and return the sublayout (Coord has an Underscore slice op)
96
+
97
+ Follow the same behavior of `Layout::operator(Coord const&)` in cute C++
98
+ """
99
+ if has_none(args):
100
+ if len(args) == 1:
101
+ return Layout(slice_(args[0], self.shape), slice_(args[0], self.stride))
102
+ else:
103
+ return Layout(slice_(args, self.shape), slice_(args, self.stride))
104
+ else:
105
+ if len(args) == 1:
106
+ return crd2idx(args[0], self.shape, self.stride) # type: ignore[arg-type]
107
+ else:
108
+ return crd2idx(args, self.shape, self.stride) # type: ignore[arg-type]
109
+
110
+ # operator [] (get-i like tuples)
111
+ def __getitem__(self, i: int) -> Self:
112
+ if is_tuple(self.shape):
113
+ return Layout(self.shape[i], self.stride[i]) # type: ignore[index]
114
+ else:
115
+ assert i == 0
116
+ return Layout(self.shape, self.stride)
117
+
118
+ # size(layout) Size of the domain
119
+ def size(self) -> int:
120
+ return product(self.shape)
121
+
122
+ # cosize(layout) Size of the codomain
123
+ def cosize(self) -> int:
124
+ return self(self.size() - 1) + 1 # type: ignore[operator]
125
+
126
+ # print and str
127
+ def __str__(self) -> str:
128
+ return f"{self.shape}:{self.stride}"
129
+
130
+ # error msgs and representation
131
+ def __repr__(self) -> str:
132
+ return f"Layout({self.shape},{self.stride})"
133
+
134
+
135
+ # Type aliases
136
+ LayoutOrIntTuple: TypeAlias = Layout | IntTuple
137
+ LayoutProfile: TypeAlias = tuple[object, ...] | Layout | None
138
+ LayoutInput: TypeAlias = Layout | IntTuple | tuple[object, ...] | None
139
+
140
+
141
+ # Make Layout from a list of layouts (each layout it's own mode in the result)
142
+ def make_layout(*layouts: Layout | tuple[Layout, ...]) -> Layout:
143
+ if len(layouts) == 1 and not is_layout(layouts[0]):
144
+ layouts = layouts[0]
145
+
146
+ shape, stride = zip(*((a.shape, a.stride) for a in layouts)) # type: ignore[union-attr]
147
+ return Layout(shape, stride)
148
+
149
+
150
+ # Size of the domain
151
+ def size(layout: LayoutOrIntTuple) -> int:
152
+ if is_layout(layout):
153
+ return layout.size()
154
+ return product(layout)
155
+
156
+
157
+ # Size of the codomain
158
+ def cosize(layout: Layout) -> int:
159
+ return layout.cosize()
160
+
161
+
162
+ # Layout coalesce -- flatten and combine as many modes as possible while preserving the int-to-int function
163
+ def coalesce(layout: Layout, profile: LayoutProfile = None) -> Layout:
164
+ if is_tuple(profile):
165
+ assert len(layout) >= len(profile)
166
+ return make_layout(
167
+ chain(
168
+ (coalesce(layout[i], profile[i]) for i in range(len(profile))), # type: ignore[arg-type]
169
+ (layout[i] for i in range(len(profile), len(layout))),
170
+ )
171
+ )
172
+
173
+ result_shape = [1]
174
+ result_stride = [0]
175
+ # Since we now follow lexicographic order, we need to process from right to left.
176
+ # And to make implementation more efficient, we append to the end of list and reverse it in the end.
177
+ for shape, stride in zip(
178
+ reversed(flatten(layout.shape)), reversed(flatten(layout.stride))
179
+ ):
180
+ # skip their shape-1s
181
+ if shape == 1:
182
+ continue
183
+ # replace our shape-1 with anything
184
+ elif result_shape[-1] == 1:
185
+ result_shape[-1] = shape
186
+ result_stride[-1] = stride
187
+ # merge modes if the shape*stride match
188
+ elif result_shape[-1] * result_stride[-1] == stride:
189
+ result_shape[-1] = result_shape[-1] * shape
190
+ # append a new mode
191
+ else:
192
+ result_shape.append(shape)
193
+ result_stride.append(stride)
194
+
195
+ if len(result_shape) == 1:
196
+ return Layout(result_shape[0], result_stride[0])
197
+ else:
198
+ result_shape.reverse()
199
+ result_stride.reverse()
200
+ return Layout(tuple(result_shape), tuple(result_stride))
201
+
202
+
203
+ # Layout filter -- replace all stride-0 modes with size-1 and then coalesce to remove them
204
+ def filter(layout: Layout, profile: LayoutProfile = None) -> Layout:
205
+ if is_tuple(profile):
206
+ assert len(layout) >= len(profile)
207
+ return make_layout(
208
+ chain(
209
+ (filter(layout[i], profile[i]) for i in range(len(profile))), # type: ignore[arg-type]
210
+ (layout[i] for i in range(len(profile), len(layout))),
211
+ )
212
+ )
213
+
214
+ result_shape = []
215
+ result_stride = []
216
+ for shape, stride in zip(flatten(layout.shape), flatten(layout.stride)):
217
+ # skip their shape-1s and stride-0s
218
+ if not (shape == 1 or stride == 0):
219
+ result_shape.append(shape)
220
+ result_stride.append(stride)
221
+
222
+ if len(result_shape) == 0:
223
+ return Layout(1, 0)
224
+ else:
225
+ return coalesce(Layout(tuple(result_shape), tuple(result_stride)))
226
+
227
+
228
+ # Layout composition
229
+ # Use tuples-of-layouts to perform this operation by-mode and None as no-op
230
+ def composition(layoutA: Layout, layoutB: LayoutInput) -> Layout:
231
+ if layoutB is None:
232
+ return layoutA
233
+ elif is_int(layoutB):
234
+ return composition(layoutA, Layout(layoutB))
235
+ elif is_tuple(layoutB):
236
+ assert len(layoutA) >= len(layoutB)
237
+ return make_layout(
238
+ chain(
239
+ (composition(layoutA[i], layoutB[i]) for i in range(len(layoutB))), # type: ignore[arg-type]
240
+ (layoutA[i] for i in range(len(layoutB), len(layoutA))),
241
+ )
242
+ )
243
+ elif is_tuple(layoutB.shape):
244
+ return make_layout(composition(layoutA, layoutB_i) for layoutB_i in layoutB) # type: ignore[arg-type, attr-defined]
245
+
246
+ if layoutB.stride == 0:
247
+ return Layout(layoutB.shape, 0)
248
+ else:
249
+ result_shape = []
250
+ result_stride = []
251
+ rest_shape = layoutB.shape
252
+ rest_stride = layoutB.stride
253
+ flat_A = coalesce(layoutA)
254
+ # when left layout is multi-dimensional sublayout, aka, self = (a,b,...,c):(x,y,...,z), layout = s:d,
255
+ # for integral s and d means that we want:
256
+ # (1) “remove” the first d elements from left, starting from rightmost. (This will increase the stride.)
257
+ # (2) “keep” the first s of those strided elements. (This does not affect the stride.)
258
+ # For example, if self = (6,2):(2,1), layout = (3:2)
259
+ # Step 1: remove the first 2 elements from self with stride increase, i.e., (6,2):(2,1) -> (6,1):(2,2)
260
+ # Step 2: keep the first 3 of those strided elements, i.e., (6,1):(2,2) -> (3,1):(2,2)
261
+ # Because we are going lexicographically, we go through left layout from right to left.
262
+ for curr_shape, curr_stride in zip(
263
+ reversed(flatten(flat_A.shape)[1:]), reversed(flatten(flat_A.stride)[1:])
264
+ ):
265
+ assert curr_shape % rest_stride == 0 or rest_stride % curr_shape == 0 # type: ignore[operator]
266
+ new_shape = min(max(1, curr_shape // rest_stride), rest_shape) # type: ignore[operator]
267
+
268
+ if new_shape != 1:
269
+ result_shape.append(new_shape) # Append to end, will reverse later
270
+ result_stride.append(rest_stride * curr_stride)
271
+
272
+ rest_shape = rest_shape // new_shape # type: ignore[operator]
273
+ rest_stride = -(
274
+ -rest_stride // curr_shape # type: ignore[operator]
275
+ ) # Python exclusive impl: "//" is always floor div so == ceil_div(abs(rest_stride), curr_shape) * signum(rest_stride)
276
+
277
+ # When left has single-size sublayout or reach the last sublayout, aka, left = a:b, layout = s:d,
278
+ # the result is rather trivial: left o layout = a:b o s:d = s:(b*d).
279
+ # For example, if self = (6:2), layout = (3:2), the result is (3:(2*2)) = (3:4).
280
+ if rest_shape != 1 or len(result_shape) == 0:
281
+ result_shape.append(rest_shape) # Append to end, will reverse later
282
+ result_stride.append(rest_stride * flatten(flat_A.stride)[0])
283
+
284
+ # Reverse the lists because we build lists in reverse order (append to end), this way it is more efficient.
285
+ result_shape.reverse()
286
+ result_stride.reverse()
287
+
288
+ if len(result_shape) == 1:
289
+ return Layout(result_shape[0], result_stride[0]) # type: ignore[arg-type]
290
+ else:
291
+ return Layout(tuple(result_shape), tuple(result_stride)) # type: ignore[arg-type]
292
+
293
+
294
+ # Layout complement
295
+ def complement(layout: LayoutOrIntTuple, max_idx: int = 1) -> Layout:
296
+ if is_int(layout):
297
+ return complement(Layout(layout))
298
+
299
+ result_shape = []
300
+ result_stride = []
301
+ current_idx = 1
302
+
303
+ sorted_DS = sorted(zip(flatten(layout.stride), flatten(layout.shape))) # type: ignore[union-attr]
304
+ for stride, shape in sorted_DS:
305
+ if stride == 0 or shape == 1:
306
+ continue
307
+
308
+ in_bound = current_idx <= shape * stride
309
+ # To support symbolic value which can't be evaluated now
310
+ assert (type(in_bound) is not bool) or in_bound
311
+
312
+ result_shape.append(stride // current_idx)
313
+ result_stride.append(current_idx)
314
+ current_idx = shape * stride
315
+
316
+ result_shape.append((max_idx + current_idx - 1) // current_idx) # ceil_div
317
+ result_stride.append(current_idx)
318
+ # This is different from original pycute implementation, because we want to follow the lexicographic order here
319
+ # where the right-most dimension is the innermost dimension (smallest stride).
320
+ result_shape.reverse()
321
+ result_stride.reverse()
322
+
323
+ return coalesce(Layout(tuple(result_shape), tuple(result_stride)))
324
+
325
+
326
+ # Layout right inverse
327
+ def right_inverse(layout: LayoutOrIntTuple | None) -> Layout | None:
328
+ if layout is None:
329
+ return None
330
+ elif is_int(layout):
331
+ return Layout(layout)
332
+
333
+ result_shape = []
334
+ result_stride = []
335
+ current_idx = 1
336
+
337
+ flat_shape = flatten(layout.shape) # type: ignore[union-attr]
338
+ flat_stride = flatten(layout.stride) # type: ignore[union-attr]
339
+ sorted_DSA = sorted(zip(flat_stride, flat_shape, suffix_product(flat_shape))) # type: ignore[arg-type]
340
+ for stride, shape, rstride in sorted_DSA:
341
+ if shape == 1:
342
+ continue
343
+ if current_idx != stride:
344
+ break
345
+
346
+ result_shape.append(shape)
347
+ result_stride.append(rstride)
348
+ current_idx = shape * stride
349
+
350
+ result_shape.reverse()
351
+ result_stride.reverse()
352
+ return coalesce(Layout(tuple(result_shape), tuple(result_stride)))
353
+
354
+
355
+ # Layout left inverse
356
+ def left_inverse(layout: LayoutOrIntTuple | None) -> Layout | None:
357
+ if layout is None:
358
+ return None
359
+ elif is_int(layout):
360
+ return Layout(layout)
361
+ return right_inverse(make_layout(complement(layout), layout)) # type: ignore[arg-type]
362
+
363
+
364
+ # Split a layout by the composition of B and the "rest"
365
+ # Use tuples-of-layouts to perform this operation by-mode and None as no-op
366
+ def logical_divide(layoutA: Layout, layoutB: LayoutInput) -> Layout:
367
+ if layoutB is None:
368
+ return layoutA
369
+ elif is_int(layoutB):
370
+ return logical_divide(layoutA, Layout(layoutB))
371
+ elif is_tuple(layoutB):
372
+ assert len(layoutA) >= len(layoutB)
373
+ return make_layout(
374
+ chain(
375
+ (
376
+ logical_divide(layoutA[i], layoutB[i]) # type: ignore[arg-type]
377
+ for i in range(len(layoutB))
378
+ ),
379
+ (layoutA[i] for i in range(len(layoutB), len(layoutA))),
380
+ )
381
+ )
382
+
383
+ return composition(
384
+ layoutA,
385
+ make_layout(layoutB, complement(layoutB, size(layoutA))),
386
+ )
387
+
388
+
389
+ # Reproduce a layoutA over a layoutB
390
+ # Use tuples-of-layouts to perform this operation by-mode and None as no-op
391
+ def logical_product(layoutA: Layout, layoutB: LayoutInput) -> Layout:
392
+ if layoutB is None:
393
+ return layoutA
394
+ elif is_int(layoutB):
395
+ return logical_divide(layoutA, Layout(layoutB))
396
+ elif is_tuple(layoutB):
397
+ assert len(layoutA) >= len(layoutB)
398
+ return make_layout(
399
+ chain(
400
+ (
401
+ logical_product(layoutA[i], layoutB[i]) # type: ignore[arg-type]
402
+ for i in range(len(layoutB))
403
+ ),
404
+ (layoutA[i] for i in range(len(layoutB), len(layoutA))),
405
+ )
406
+ )
407
+
408
+ return make_layout(
409
+ layoutA,
410
+ composition(complement(layoutA, size(layoutA) * cosize(layoutB)), layoutB),
411
+ )
412
+
413
+
414
+ # Gather the modes from a hierarchical logical_divide or logical_product
415
+ def hier_unzip(
416
+ splitter: object,
417
+ layoutA: Layout,
418
+ layoutB: LayoutInput,
419
+ ) -> Layout:
420
+ if layoutB is None:
421
+ return make_layout(Layout(1, 0), layoutA)
422
+ elif is_tuple(layoutB):
423
+ assert len(layoutA) >= len(layoutB)
424
+ # A layout with shape ((A,a),(B,b),(C,c))
425
+ split = make_layout(
426
+ hier_unzip(splitter, layoutA[i], layoutB[i]) # type: ignore[arg-type]
427
+ for i in range(len(layoutB))
428
+ )
429
+ # Gather to shape ((A,B,C,...),(a,b,c,...,y,z))
430
+ return make_layout(
431
+ make_layout(split[i][0] for i in range(len(layoutB))), # type: ignore[arg-type]
432
+ make_layout(
433
+ chain( # type: ignore[arg-type]
434
+ (split[i][1] for i in range(len(layoutB))),
435
+ (layoutA[i] for i in range(len(layoutB), len(layoutA))),
436
+ )
437
+ ),
438
+ )
439
+
440
+ # splitter must return a rank-2 layout
441
+ return splitter(layoutA, layoutB) # type: ignore[operator]
442
+
443
+
444
+ # Apply logical divide hierarchically and gather the split modes into two modes
445
+ def zipped_divide(layoutA: Layout, layoutB: LayoutInput) -> Layout:
446
+ return hier_unzip(logical_divide, layoutA, layoutB)
447
+
448
+
449
+ # Perform logical divide hierarchically and gather tiles (B-layouts) into a new mode
450
+ def tiled_divide(layoutA: Layout, layoutB: LayoutInput) -> Layout:
451
+ result = zipped_divide(layoutA, layoutB)
452
+ return make_layout([result[0]] + [result[1][i] for i in range(len(result[1]))]) # type: ignore[arg-type]
453
+
454
+
455
+ # Apply logical product hierarchically and gather the split modes into two modes
456
+ def zipped_product(layoutA: Layout, layoutB: LayoutInput) -> Layout:
457
+ return hier_unzip(logical_product, layoutA, layoutB)
458
+
459
+
460
+ # Perform logical product hierarchically and gather tiles (B-layouts) into a new mode
461
+ def tiled_product(layoutA: Layout, layoutB: LayoutInput) -> Layout:
462
+ result = zipped_product(layoutA, layoutB)
463
+ return make_layout([result[0]] + [result[1][i] for i in range(len(result[1]))]) # type: ignore[arg-type]
464
+
465
+
466
+ def slice_and_offset(crd: tuple[object, ...], layout: Layout) -> tuple[Layout, int]:
467
+ return (
468
+ Layout(slice_(crd, layout.shape), slice_(crd, layout.stride)),
469
+ crd2idx(crd, layout.shape, layout.stride), # type: ignore[arg-type]
470
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_pycute/typing.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #################################################################################################
2
+ #
3
+ # Copyright (c) 2023 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
+ # SPDX-License-Identifier: BSD-3-Clause
5
+ #
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted provided that the following conditions are met:
8
+ #
9
+ # 1. Redistributions of source code must retain the above copyright notice, this
10
+ # list of conditions and the following disclaimer.
11
+ #
12
+ # 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ # this list of conditions and the following disclaimer in the documentation
14
+ # and/or other materials provided with the distribution.
15
+ #
16
+ # 3. Neither the name of the copyright holder nor the names of its
17
+ # contributors may be used to endorse or promote products derived from
18
+ # this software without specific prior written permission.
19
+ #
20
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+ #
31
+ #################################################################################################
32
+
33
+ from abc import ABC
34
+
35
+
36
+ class Integer(ABC): # noqa: B024 # Uses __subclasshook__ instead of abstract methods
37
+ @classmethod
38
+ def __subclasshook__(cls, c: type) -> bool:
39
+ if c in [bool, float]:
40
+ return False
41
+
42
+ return issubclass(c, int)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_serialization.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ from dataclasses import dataclass
3
+ from io import BufferedIOBase
4
+ from typing import Any
5
+
6
+ import torch
7
+ import torch._weights_only_unpickler as _weights_only_unpickler
8
+ from torch.serialization import _load, _save, DEFAULT_PROTOCOL, MAP_LOCATION
9
+
10
+
11
+ __all__: list[str] = []
12
+
13
+
14
+ @dataclass
15
+ class _Entry:
16
+ key: str
17
+ is_storage: bool
18
+ length: int
19
+
20
+
21
+ _weights_only_unpickler._add_safe_globals([_Entry])
22
+
23
+
24
+ class _PseudoZipFile:
25
+ def __init__(self) -> None:
26
+ self.records: dict[str, tuple[object, int]] = {}
27
+
28
+ def write_record(self, key: str, data: object, length: int) -> None:
29
+ self.records[key] = (data, length)
30
+
31
+ def write_to(self, f: BufferedIOBase) -> None:
32
+ entries = []
33
+ for key, (data, length) in self.records.items():
34
+ entries.append(
35
+ _Entry(
36
+ key=key,
37
+ is_storage=isinstance(data, torch.UntypedStorage),
38
+ length=length,
39
+ )
40
+ )
41
+
42
+ pickle.dump(entries, f, protocol=DEFAULT_PROTOCOL)
43
+
44
+ for data, _ in self.records.values():
45
+ if isinstance(data, bytes):
46
+ f.write(data)
47
+ elif isinstance(data, str):
48
+ f.write(data.encode("utf-8"))
49
+ elif isinstance(data, torch.UntypedStorage):
50
+ data._write_file(f, False, False, 1)
51
+ else:
52
+ raise TypeError(f"unknown type: {type(data)}")
53
+
54
+ def read_from(self, f: BufferedIOBase) -> None:
55
+ entries = _weights_only_unpickler.load(f)
56
+
57
+ for entry in entries:
58
+ data = f.read(entry.length)
59
+ if entry.is_storage:
60
+ if entry.length == 0:
61
+ storage = torch.UntypedStorage(0)
62
+ else:
63
+ storage = torch.frombuffer(
64
+ data,
65
+ dtype=torch.uint8,
66
+ ).untyped_storage()
67
+
68
+ self.records[entry.key] = (
69
+ storage,
70
+ entry.length,
71
+ )
72
+ else:
73
+ self.records[entry.key] = (data, entry.length)
74
+
75
+ def has_record(self, key: str) -> bool:
76
+ return key in self.records
77
+
78
+ def get_record(self, key: str) -> object:
79
+ return self.records[key][0]
80
+
81
+ def get_storage_from_record(
82
+ self, key: str, _length: int, _type: int
83
+ ) -> torch.Tensor:
84
+ return torch.tensor(self.records[key][0], dtype=torch.uint8)
85
+
86
+ def serialization_id(self) -> str:
87
+ return "torchft"
88
+
89
+
90
+ def _streaming_save(
91
+ obj: object,
92
+ f: BufferedIOBase,
93
+ pickle_module: Any = pickle,
94
+ pickle_protocol: int = DEFAULT_PROTOCOL,
95
+ ) -> None:
96
+ """
97
+ Save the object to a file-like object in a streaming fashion compatible with
98
+ network sockets.
99
+
100
+ This behaves similarly to :func:`torch.save` with a few notable differences:
101
+
102
+ * A non-seekable file like object can be used when loading.
103
+ * No forwards/backwards compatibility is provided for the serialization
104
+ format. This is only intended to be used with a single version of PyTorch
105
+ with transient storage (i.e. sockets or temp files).
106
+ * mmap is not supported
107
+
108
+ See :func:`torch.save` for more details on specific arguments.
109
+ """
110
+
111
+ zip_file = _PseudoZipFile()
112
+ _save(
113
+ obj,
114
+ zip_file=zip_file,
115
+ pickle_module=pickle_module,
116
+ pickle_protocol=pickle_protocol,
117
+ _disable_byteorder_record=False,
118
+ )
119
+ zip_file.write_to(f)
120
+
121
+
122
+ def _streaming_load(
123
+ f: BufferedIOBase,
124
+ map_location: MAP_LOCATION = None,
125
+ pickle_module: Any = None,
126
+ *,
127
+ weights_only: bool = True,
128
+ **pickle_load_args: Any,
129
+ ) -> object:
130
+ """
131
+ Load the object from a file-like object in a streaming fashion compatible with
132
+ network sockets.
133
+
134
+ See :func:`_streaming_save` for more details about the streaming behavior.
135
+
136
+ See :func:`torch.load` for more details on specific arguments.
137
+ """
138
+ if weights_only:
139
+ if pickle_module is not None:
140
+ raise RuntimeError(
141
+ "Can not safely load weights when explicit pickle_module is specified"
142
+ )
143
+ pickle_module = _weights_only_unpickler
144
+ else:
145
+ if pickle_module is None:
146
+ pickle_module = pickle
147
+
148
+ if "encoding" not in pickle_load_args:
149
+ pickle_load_args["encoding"] = "utf-8"
150
+
151
+ zip_file = _PseudoZipFile()
152
+ zip_file.read_from(f)
153
+ return _load(
154
+ zip_file=zip_file,
155
+ map_location=map_location,
156
+ pickle_module=pickle_module,
157
+ **pickle_load_args,
158
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .api import _shard_tensor, load_with_process_group, shard_module, shard_parameter
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/_utils.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence
2
+
3
+ import torch
4
+ from torch.distributed._shard.metadata import ShardMetadata
5
+
6
+
7
+ DEPRECATE_MSG = "Please use DTensor instead and we are deprecating ShardedTensor."
8
+
9
+
10
+ def narrow_tensor_by_index(
11
+ tensor: torch.Tensor,
12
+ offsets: Sequence[int],
13
+ sizes: Sequence[int],
14
+ ) -> torch.Tensor:
15
+ """
16
+ Narrow the tensor according to ``offsets`` and ``sizes``.
17
+ """
18
+ narrowed_tensor = tensor
19
+ for idx, (offset, size) in enumerate(zip(offsets, sizes)):
20
+ if size < tensor.size(idx):
21
+ # Reshape to get shard for this rank and we don't want autograd
22
+ # recording here for the narrow op and 'local_shard' should be a
23
+ # leaf variable in the autograd graph.
24
+ narrowed_tensor = narrowed_tensor.narrow(idx, offset, size)
25
+ return narrowed_tensor
26
+
27
+
28
+ def narrow_tensor(tensor: torch.Tensor, metadata: ShardMetadata) -> torch.Tensor:
29
+ """
30
+ Narrow the tensor according to the metadata
31
+ """
32
+ return narrow_tensor_by_index(tensor, metadata.shard_offsets, metadata.shard_sizes)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/api.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from contextlib import contextmanager
3
+
4
+ import torch
5
+ import torch.distributed as dist
6
+ import torch.nn as nn
7
+ from torch.distributed import distributed_c10d
8
+ from torch.distributed._shard.sharded_tensor import ShardedTensor
9
+
10
+ from .sharder import Sharder
11
+ from .sharding_plan import ShardingPlan
12
+ from .sharding_spec import ChunkShardingSpec, ShardingSpec
13
+
14
+
15
+ def _shard_tensor(
16
+ tensor: torch.Tensor, sharding_spec: ShardingSpec, src_rank=0, process_group=None
17
+ ) -> ShardedTensor:
18
+ """
19
+ Given a :class:`torch.Tensor`, it shards that tensor according to the provided
20
+ ``sharding_spec``. ``src_rank`` denotes the source rank which would be
21
+ used as the ground truth of the data which would be scattered as shards
22
+ across the rest of the ranks.
23
+
24
+ Args:
25
+ tensor (:class:`torch.Tensor`): Tensor needs to be sharded.
26
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
27
+ describing how to shard the Tensor.
28
+
29
+ Keyword args:
30
+ src_rank (int, optional): The source rank which is used as the ground truth of
31
+ the data for the parameter that would be sharded and scattered
32
+ across the rest of the ranks.
33
+ Default: 0.
34
+ process_group (ProcessGroup, optional): The process group to work on. If None,
35
+ the default process group will be used.
36
+
37
+ Returns:
38
+ A :class:`ShardedTensor` sharded from the given tensor.
39
+
40
+ .. warning::
41
+ Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is
42
+ currently supported as the ``sharding_spec``.
43
+ """
44
+ if not tensor.is_contiguous():
45
+ raise ValueError("input tensor is not a contiguous Tensor")
46
+
47
+ pg = (
48
+ process_group
49
+ if process_group is not None
50
+ else distributed_c10d._get_default_group()
51
+ )
52
+ world_size = dist.get_world_size(pg)
53
+ current_rank = dist.get_rank(pg)
54
+
55
+ # Validate src_rank and sharding_spec are same across all ranks.
56
+ gathered_list = [None] * world_size
57
+ dist.all_gather_object(gathered_list, (src_rank, sharding_spec), group=pg)
58
+
59
+ for idx, entry in enumerate(gathered_list):
60
+ if src_rank != entry[0]: # type: ignore[index]
61
+ raise ValueError(
62
+ f"src_rank={src_rank} on rank: {current_rank} does not " # type: ignore[index]
63
+ f"match with src_rank={entry[0]} on rank: {idx}" # type: ignore[index]
64
+ )
65
+ if sharding_spec != entry[1]: # type: ignore[index]
66
+ raise ValueError(
67
+ f"sharding_spec={sharding_spec} on rank: {current_rank} does not " # type: ignore[index]
68
+ f"match with sharding_spec={entry[1]} on rank: {idx}" # type: ignore[index]
69
+ )
70
+
71
+ st = sharding_spec.shard(tensor, src_rank=src_rank, process_group=pg)
72
+
73
+ return st
74
+
75
+
76
+ def shard_parameter(
77
+ module: torch.nn.Module,
78
+ param_name: str,
79
+ sharding_spec: ShardingSpec,
80
+ src_rank=0,
81
+ process_group=None,
82
+ ):
83
+ """
84
+ Given a :class:`torch.nn.Module`, a ``param_name`` for a parameter in that
85
+ module, it shards that parameter according to the provided
86
+ ``sharding_spec``. ``src_rank`` denotes the source rank which would be
87
+ used as the ground truth of the data which would be scattered as shards
88
+ across the rest of the ranks.
89
+
90
+ This method replaces ``module.param_name`` with a
91
+ :class:`torch.distributed._sharded_tensor.ShardedTensor`
92
+
93
+ Args:
94
+ module (:class:`torch.nn.Module`): Module whose parameter needs to be sharded.
95
+ param_name (str): Name of the parameter of ``module`` that needs to be sharded.
96
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
97
+ describing how to shard the Tensor.
98
+
99
+ Keyword args:
100
+ src_rank (int, optional): The source rank which is used as the ground truth of
101
+ the data for the parameter that would be sharded and scattered
102
+ across the rest of the ranks.
103
+ Default: 0.
104
+ process_group (ProcessGroup, optional): The process group to work on. If None,
105
+ the default process group will be used.
106
+
107
+ .. warning::
108
+ Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is
109
+ currently supported as the ``sharding_spec``.
110
+ """
111
+ # Perform some validation first.
112
+ if not hasattr(module, param_name):
113
+ raise AttributeError(f"{module._get_name()} has no attribute `{param_name}`")
114
+
115
+ tensor = getattr(module, param_name)
116
+ if not isinstance(tensor, torch.Tensor):
117
+ raise ValueError(
118
+ f"Expected {type(module).__name__}.{param_name} to be a Tensor, but found {type(tensor).__name__}"
119
+ )
120
+
121
+ if not tensor.is_contiguous():
122
+ raise ValueError(f"param: {param_name} is not a contiguous Tensor")
123
+
124
+ st = _shard_tensor(tensor, sharding_spec, src_rank, process_group)
125
+
126
+ # Replace param with ShardedTensor.
127
+ module.register_parameter(param_name, nn.Parameter(st))
128
+
129
+
130
+ # Tracks the current process group in the load context manager.
131
+ _CURRENT_PROCESS_GROUP: dist.ProcessGroup | None = None
132
+
133
+
134
+ @contextmanager
135
+ def load_with_process_group(process_group):
136
+ """
137
+ Context manager to set the process group with which to load a ShardedTensor.
138
+ """
139
+ global _CURRENT_PROCESS_GROUP
140
+ if _CURRENT_PROCESS_GROUP is not None:
141
+ raise RuntimeError(
142
+ 'ProcessGroup already set by previous "load_with_process_group" '
143
+ "context manager"
144
+ )
145
+ _CURRENT_PROCESS_GROUP = process_group
146
+ try:
147
+ yield process_group
148
+ finally:
149
+ _CURRENT_PROCESS_GROUP = None
150
+
151
+
152
+ def _get_current_process_group():
153
+ """
154
+ Retrieves the current process group set by ``load_with_process_group``.
155
+ If not set, it just returns the default group.
156
+ """
157
+ global _CURRENT_PROCESS_GROUP
158
+ if _CURRENT_PROCESS_GROUP is None:
159
+ return distributed_c10d._get_default_group()
160
+ else:
161
+ return _CURRENT_PROCESS_GROUP
162
+
163
+
164
+ def _reshard_output(
165
+ module: torch.nn.Module, resharding_spec: ShardingSpec
166
+ ) -> torch.nn.Module:
167
+ """
168
+ Hook a module with output resharding in the forward pass according
169
+ to the given ``resharding_spec``.
170
+
171
+ Args:
172
+ module (:class:`torch.nn.Module`): Module whose output needs to be resharded.
173
+ resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`):
174
+ The specification describing how the output of the module will be resharded.
175
+
176
+ Returns:
177
+ A :class:`torch.nn.Module` object with reshard API hooked.
178
+ """
179
+
180
+ def hook_func(_module, _input, output):
181
+ if isinstance(output, ShardedTensor):
182
+ return output.reshard(resharding_spec)
183
+ return output
184
+
185
+ module.register_forward_hook(hook_func)
186
+ return module
187
+
188
+
189
+ def _collect_local_shard(module: torch.nn.Module) -> torch.nn.Module:
190
+ """
191
+ Hook a module with local shards collection in the forward pass.
192
+
193
+ This API is typically used to convert a sharded representation back to data parallel
194
+ representation. In particular, it returns the local tensor for this Shard. If the
195
+ size along the sharding dimension for the local tensor is 1, this dimension is removed
196
+ from the final result. For example a [4, 16] ShardedTensor across 4 ranks is typically
197
+ a local Tensor of size [16] across each rank and not [1, 16] across each rank.
198
+
199
+ Args:
200
+ module (:class:`torch.nn.Module`): Module whose output is ShardedTensor and the
201
+ local tensor value needs to be returned.
202
+
203
+ Returns:
204
+ A :class:`torch.nn.Module` object with collection API hooked.
205
+ """
206
+
207
+ def hook_func(_module, _input, output):
208
+ if isinstance(output, ShardedTensor):
209
+ local_tensor = output.local_tensor()
210
+ # Squeeze the # of dimensions manually, only applicable to ChunkShardingSpec
211
+ sharding_spec = output._sharding_spec
212
+ if (
213
+ isinstance(sharding_spec, ChunkShardingSpec)
214
+ and local_tensor.size(sharding_spec.dim) == 1 # type: ignore[attr-defined, arg-type]
215
+ ):
216
+ local_tensor = local_tensor.squeeze(
217
+ output._sharding_spec.dim # type: ignore[attr-defined]
218
+ )
219
+ return local_tensor
220
+
221
+ module.register_forward_hook(hook_func)
222
+ return module
223
+
224
+
225
+ def shard_module(module: nn.Module, plan: ShardingPlan, src_rank=0, process_group=None):
226
+ """
227
+ Shards a given module according to the provided sharding `plan`. This method
228
+ first shards all the parameters according to the given sharding `plan`. Then if
229
+ `output_plan` and `return_local_tensor` are specified in the sharding `plan`, it
230
+ will tag the output of modules according `output_plan`, convert the module's
231
+ output back to data parallel according to `return_local_tensor`.
232
+
233
+ Needs to be called on all ranks in an SPMD fashion.
234
+
235
+ Args:
236
+ module (:class:`torch.nn.Module`): The module to apply sharding to
237
+ plan (:class:`torch.distributed._shard.sharding_plan.ShardingPlan`):
238
+ The ShardingPlan which specified param name to ShardingSpec to apply to
239
+ each parameter.
240
+
241
+ Keyword args:
242
+ src_rank (int, optional): The source rank which is used as the ground truth of
243
+ the data for the module that would be sharded and scattered across the rest
244
+ of the ranks.
245
+ Default: 0.
246
+ process_group (ProcessGroup, optional): The process group to work on. If None,
247
+ the default process group will be used.
248
+ """
249
+ # record Sharder paths for sanity check on the plan to ensure items in the plan
250
+ # does not conflict with the submodule tree that the Sharder is working with
251
+ sharder_paths = []
252
+ for name, spec in plan.plan.items():
253
+ if isinstance(spec, Sharder):
254
+ sharder_paths.append(name)
255
+
256
+ # shard the parameter according to the ShardingPlan
257
+ for name, spec in plan.plan.items():
258
+ if isinstance(spec, ShardingSpec):
259
+ # if found a sharding spec, try to shard the parameter
260
+ module_path, _, param_name = name.rpartition(".")
261
+
262
+ for sharder_path in sharder_paths:
263
+ if module_path.startswith(sharder_path):
264
+ raise RuntimeError(
265
+ f"ShardingPlan is in-valid, trying to shard a parameter: {name},"
266
+ f" but there's already a Sharder entry for module {sharder_path},"
267
+ f" parameter sharding should not conflict with the submodule tree"
268
+ f" that a Sharder is working with!"
269
+ )
270
+
271
+ mod = module.get_submodule(module_path)
272
+ shard_parameter(
273
+ mod, param_name, spec, src_rank=src_rank, process_group=process_group
274
+ )
275
+ elif isinstance(spec, Sharder):
276
+ parent_mod_path, _, _mod_name = name.rpartition(".")
277
+ if name == "":
278
+ raise KeyError("Module path must not be empty for custom sharder!")
279
+ mod = module.get_submodule(name)
280
+ parent_mod = module.get_submodule(parent_mod_path)
281
+ sharded_mod = spec.shard(mod)
282
+ # swap this submodule with the sharded module
283
+ parent_mod.mod_name = sharded_mod
284
+ else:
285
+ raise TypeError(
286
+ f"Only `ShardingSpec` and `Sharder` are supported to shard '{name}'"
287
+ )
288
+
289
+ # reshard output if there's an entry in `reshard_output` for this module
290
+ if plan.output_plan is not None:
291
+ for module_path, output_spec in plan.output_plan.items():
292
+ if isinstance(output_spec, ShardingSpec):
293
+ mod = module.get_submodule(module_path)
294
+ _reshard_output(mod, output_spec)
295
+ else:
296
+ raise TypeError(
297
+ f"Only `ShardingSpec` is supported as output_plan for '{module_path}'"
298
+ )
299
+ # convert the output back to data parallel for the modules appears in
300
+ # `return_local_tensor` of the plan, we will call `_collect_local_shard`
301
+ # to collect the local tensor for output of modules
302
+ if plan.return_local_tensor is not None:
303
+ for module_path in plan.return_local_tensor:
304
+ mod = module.get_submodule(module_path)
305
+ _collect_local_shard(mod)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/checkpoint/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Keep old package for BC purposes, this file should be removed once
2
+ # everything moves to the `torch.distributed.checkpoint` package.
3
+ import sys
4
+ import warnings
5
+
6
+ import torch
7
+ from torch.distributed.checkpoint import * # noqa: F403
8
+
9
+
10
+ with warnings.catch_warnings():
11
+ warnings.simplefilter("always")
12
+ warnings.warn(
13
+ "`torch.distributed._shard.checkpoint` will be deprecated, "
14
+ "use `torch.distributed.checkpoint` instead",
15
+ DeprecationWarning,
16
+ stacklevel=2,
17
+ )
18
+
19
+ sys.modules["torch.distributed._shard.checkpoint"] = torch.distributed.checkpoint
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/common_op_utils.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ from torch.utils import _pytree as pytree
5
+
6
+
7
+ def _basic_validation(op, args=(), kwargs=None):
8
+ """
9
+ Common validation across all ops go in here.
10
+ """
11
+ from torch.distributed._shard.sharded_tensor import ShardedTensor
12
+
13
+ if len(args) == 0 and (kwargs is None or len(kwargs) == 0):
14
+ raise ValueError(f" No input for '{op.__name__}'!")
15
+
16
+ # Validate types
17
+ has_distributed_tensor = False
18
+
19
+ def is_distributed_tensor(e):
20
+ nonlocal has_distributed_tensor
21
+ if isinstance(e, ShardedTensor):
22
+ has_distributed_tensor = True
23
+
24
+ pytree.tree_map_(is_distributed_tensor, args)
25
+ pytree.tree_map_(is_distributed_tensor, kwargs)
26
+
27
+ if not has_distributed_tensor:
28
+ raise TypeError(
29
+ f"torch function '{op.__name__}', with args: {args} and "
30
+ f"kwargs: {kwargs} are called without any distributed tensor!"
31
+ )
32
+
33
+ # Validate all distributed tensors use the same PG.
34
+ cur_pg: torch.distributed.ProcessGroup | None = None
35
+
36
+ def validate_pg(e):
37
+ nonlocal cur_pg
38
+ if isinstance(e, ShardedTensor):
39
+ if cur_pg is not None and e._process_group is not cur_pg:
40
+ raise RuntimeError(
41
+ "All distributed tensors should use the "
42
+ "same ProcessGroup if used together in an op."
43
+ )
44
+ cur_pg = e._process_group
45
+
46
+ pytree.tree_map_(validate_pg, args)
47
+ pytree.tree_map_(validate_pg, kwargs)
48
+
49
+
50
+ def _register_default_op(op, decorator):
51
+ @decorator(op)
52
+ def tensor_default_op(types, args=(), kwargs=None, pg=None):
53
+ """
54
+ Handles ``__torch_function__`` dispatch for the default tensor ops that
55
+ behave the same as ``torch.Tensor`` such as ``torch.Tensor.shape`` or
56
+ ``torch.Tensor.dtype``. We simply lower to the real op call with
57
+ DisableTorchFunctionSubclass context like ``torch.Tensor.__torch_function__``
58
+ to avoid recursions.
59
+ """
60
+ if kwargs is None:
61
+ kwargs = {}
62
+
63
+ with torch._C.DisableTorchFunctionSubclass():
64
+ return op(*args, **kwargs)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/metadata.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from dataclasses import dataclass
3
+ from functools import reduce
4
+
5
+ from torch.distributed.remote_device import _remote_device
6
+
7
+
8
+ @dataclass
9
+ class ShardMetadata:
10
+ """
11
+ Represents a shard of the overall Tensor including its
12
+ offsets, lengths and device placement.
13
+
14
+ Args:
15
+ shard_offsets(List[int]): Offsets in the original tensor indicating
16
+ the start offsets for this shard. Should have the same rank as
17
+ the original tensor.
18
+ shard_sizes(List[int]): Integers indicating the size of each
19
+ dimension for this shard. Should have the same rank as the
20
+ original tensor.
21
+ placement(:class:`torch.distributed._remote_device`):
22
+ Specifies the placement of this shard.
23
+ """
24
+
25
+ __slots__ = ["shard_offsets", "shard_sizes", "placement"]
26
+
27
+ shard_offsets: list[int]
28
+ shard_sizes: list[int]
29
+ placement: _remote_device | None
30
+
31
+ def __init__(
32
+ self,
33
+ shard_offsets: list[int],
34
+ shard_sizes: list[int],
35
+ placement: str | _remote_device | None = None,
36
+ ):
37
+ self.shard_offsets = shard_offsets
38
+ self.shard_sizes = shard_sizes
39
+ if isinstance(placement, str):
40
+ self.placement = _remote_device(placement)
41
+ else:
42
+ self.placement = placement
43
+ if len(self.shard_offsets) != len(self.shard_sizes):
44
+ raise ValueError(
45
+ f"shard_offsets and shard_sizes should have "
46
+ f"the same number of elements, found {len(self.shard_offsets)} "
47
+ f"and {self.shard_sizes} respectively"
48
+ )
49
+
50
+ for i in range(len(self.shard_offsets)):
51
+ if self.shard_offsets[i] < 0:
52
+ raise ValueError("shard_offsets should be >=0")
53
+ if self.shard_sizes[i] < 0:
54
+ raise ValueError("shard_sizes should be >= 0")
55
+
56
+ def __hash__(self):
57
+ def _hash_reduce(a, b):
58
+ return (a << 8) + hash(b)
59
+
60
+ res = reduce(_hash_reduce, self.shard_offsets, 37)
61
+ res = reduce(_hash_reduce, self.shard_sizes, res)
62
+ res = _hash_reduce(res, self.placement)
63
+ return res
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/op_registry_utils.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ from inspect import signature
4
+
5
+ from .common_op_utils import _basic_validation
6
+
7
+
8
+ """
9
+ Common utilities to register ops on ShardedTensor
10
+ and PartialTensor.
11
+ """
12
+
13
+
14
+ def _register_op(op, func, op_table):
15
+ """
16
+ Performs basic validation and registers the provided op in the given
17
+ op_table.
18
+ """
19
+ if len(signature(func).parameters) != 4:
20
+ raise TypeError(
21
+ f"Custom sharded op function expects signature: "
22
+ f"(types, args, kwargs, process_group), but received "
23
+ f"signature: {signature(func)}"
24
+ )
25
+
26
+ op_table[op] = func
27
+
28
+
29
+ def _decorator_func(wrapped_func, op, op_table):
30
+ """
31
+ Decorator function to register the given ``op`` in the provided
32
+ ``op_table``
33
+ """
34
+
35
+ @functools.wraps(wrapped_func)
36
+ def wrapper(types, args, kwargs, process_group):
37
+ _basic_validation(op, args, kwargs)
38
+ return wrapped_func(types, args, kwargs, process_group)
39
+
40
+ _register_op(op, wrapper, op_table)
41
+ return wrapper
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_optim/__init__.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterator
2
+ from typing import Union
3
+
4
+ import torch.nn as nn
5
+ from torch.distributed._shard.sharded_tensor import ShardedTensor
6
+
7
+ from .api import ShardedOptimizer
8
+
9
+
10
+ def named_params_with_sharded_tensor(
11
+ module: nn.Module,
12
+ prefix: str = "",
13
+ recurse: bool = True,
14
+ ) -> Iterator[tuple[str, nn.Parameter | ShardedTensor]]:
15
+ r"""Returns an iterator over module parameters (together with the
16
+ ShardedTensor parameters), yielding both the name of the parameter
17
+ as well as the parameter itself. This is typically passed to a
18
+ :class:torch.distributed._shard.sharded_optim.ShardedOptimizer
19
+
20
+ Args:
21
+ prefix (str): prefix to prepend to all parameter names.
22
+ recurse (bool): if True, then yields parameters of this module
23
+ and all submodules. Otherwise, yields only parameters that
24
+ are direct members of this module.
25
+
26
+ Yields:
27
+ (str, Union[Tensor, ShardedTensor]): Tuple containing
28
+ the name and parameter (or ShardedTensor parameter)
29
+
30
+ Example::
31
+
32
+ >>> # xdoctest: +SKIP
33
+ >>> model = torch.nn.Linear(*linear_size)
34
+ >>> shard_parameter(model, "weight", spec)
35
+ >>> for name, param in named_params_with_sharded_tensor(model):
36
+ >>> if name in ['weight']:
37
+ >>> print(param.size())
38
+
39
+ """
40
+ modules = module.named_modules(prefix=prefix) if recurse else [(prefix, module)]
41
+
42
+ memo = set()
43
+ for mod_prefix, mod in modules:
44
+ # find all sharded tensor params
45
+ for name, val in vars(mod).items():
46
+ if isinstance(val, ShardedTensor) and val not in memo:
47
+ memo.add(val)
48
+ name = mod_prefix + ("." if mod_prefix else "") + name
49
+ yield name, val
50
+
51
+ # find all nn.Parameters
52
+ for name, val in module.named_parameters():
53
+ yield name, val
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_optim/api.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from collections.abc import Mapping
3
+ from typing import Any
4
+
5
+ import torch.optim as optim
6
+ from torch import Tensor
7
+ from torch.distributed._shard.sharded_tensor import ShardedTensor
8
+
9
+
10
+ class ShardedOptimizer(optim.Optimizer):
11
+ def __init__(
12
+ self,
13
+ named_params: Mapping[str, Tensor | ShardedTensor],
14
+ optimizer_class,
15
+ *optimizer_args,
16
+ **optimizer_kwargs,
17
+ ):
18
+ """
19
+ ShardedOptimizer collects all tensors and local shard tensors of
20
+ ShardedTensor, then use these tensors as ``params`` for optimizers
21
+
22
+ Args:
23
+ named_params (Dict[str, Union[Tensor, ShardedTensor]]) : a Dict
24
+ of parameters, where key is the parameter key, value is either
25
+ Tensor or ShardedTensor parameter.
26
+ optimizer_class (torch.optim.Optimizer): the Optimizer to use
27
+ locally, i.e. torch.optim.SGD, torch.optim.Adagrad, etc.
28
+ *optimizer_args: the arguments to initialize the optimizer.
29
+ **optimizer_kwargs: the key-word arguments to initialize the optimizer.
30
+
31
+ """
32
+ tensors: list[Tensor] = []
33
+ for value in named_params.values():
34
+ if isinstance(value, ShardedTensor):
35
+ tensors.extend(
36
+ local_shard.tensor for local_shard in value.local_shards()
37
+ )
38
+ else:
39
+ tensors.append(value)
40
+
41
+ self.named_params = named_params
42
+ self._optim = optimizer_class(tensors, *optimizer_args, **optimizer_kwargs)
43
+ self.param_groups = self._optim.param_groups
44
+ self.state = self._optim.state
45
+
46
+ def zero_grad(self, set_to_none: bool = True): # type: ignore[override]
47
+ r"""Resets the gradients of all optimized :class:`torch.Tensor` s.
48
+
49
+ Args:
50
+ set_to_none (bool): instead of setting to zero, set the grads to None.
51
+ This will in general have lower memory footprint, and can modestly improve performance.
52
+ However, it changes certain behaviors. For example:
53
+ 1. When the user tries to access a gradient and perform manual ops on it,
54
+ a None attribute or a Tensor full of 0s will behave differently.
55
+ 2. If the user requests ``zero_grad(set_to_none=True)`` followed by a backward pass, ``.grad``\ s
56
+ are guaranteed to be None for params that did not receive a gradient.
57
+ 3. ``torch.optim`` optimizers have a different behavior if the gradient is 0 or None
58
+ (in one case it does the step with a gradient of 0 and in the other it skips
59
+ the step altogether).
60
+ """
61
+ self._optim.zero_grad(set_to_none)
62
+
63
+ def step(self, closure=None):
64
+ r"""Performs a single optimization step (parameter update).
65
+
66
+ Args:
67
+ closure (Callable): A closure that reevaluates the model and
68
+ returns the loss. Optional for most optimizers.
69
+
70
+ .. note::
71
+ Unless otherwise specified, this function should not modify the
72
+ ``.grad`` field of the parameters.
73
+ """
74
+ self._optim.step(closure)
75
+
76
+ def state_dict(self) -> dict[str, Any]:
77
+ """
78
+ Returned state and param_groups will contain parameter keys
79
+ instead of parameter indices like torch.optim.Optimizer.
80
+ This allows for advanced functionality like optimizer re-sharding to be implemented.
81
+ """
82
+ # TODO: implement state_dict
83
+ raise NotImplementedError("ShardedOptimizer state_dict not implemented yet!")
84
+
85
+ def load_state_dict(self, state_dict: Mapping[str, Any]):
86
+ r"""Loads the ShardedOptimizer state.
87
+
88
+ Args:
89
+ state_dict (dict): ShardedOptimizer state. Should be an object returned
90
+ from a call to :meth:`state_dict`.
91
+ """
92
+ # TODO: implement load_state_dict
93
+ raise NotImplementedError(
94
+ "ShardedOptimizer load_state_dict not implemented yet!"
95
+ )
96
+
97
+ def add_param_group(self, param_group: Any):
98
+ r"""Add a new param group"""
99
+ # TODO: implement add_param_group
100
+ raise NotImplementedError(
101
+ "ShardedOptimizer add_param_group not implemented yet!"
102
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/__init__.py ADDED
@@ -0,0 +1,490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ from typing import TYPE_CHECKING
4
+
5
+ import torch
6
+ from torch.distributed._shard.op_registry_utils import _decorator_func
7
+
8
+ from .api import (
9
+ _CUSTOM_SHARDED_OPS,
10
+ _SHARDED_OPS,
11
+ Shard,
12
+ ShardedTensor,
13
+ ShardedTensorBase,
14
+ ShardedTensorMetadata,
15
+ TensorProperties,
16
+ )
17
+ from .metadata import ShardMetadata # noqa: F401
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from torch.distributed._shard.sharding_spec import ShardingSpec
22
+ else:
23
+ ShardingSpec = "ShardingSpec"
24
+
25
+
26
+ def empty(
27
+ sharding_spec: ShardingSpec,
28
+ *size,
29
+ dtype=None,
30
+ layout=torch.strided,
31
+ requires_grad=False,
32
+ pin_memory=False,
33
+ memory_format=torch.contiguous_format,
34
+ process_group=None,
35
+ init_rrefs=False,
36
+ ) -> ShardedTensor:
37
+ """
38
+ Returns a :class:`ShardedTensor` filled with uninitialized data.
39
+ Needs to be called on all ranks in an SPMD fashion.
40
+
41
+ Args:
42
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
43
+ describing how to shard the Tensor.
44
+ size (int...): a sequence of integers defining the shape of the output
45
+ tensor. Can be a variable number of arguments or a collection like a list or tuple.
46
+
47
+ Keyword args:
48
+ dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
49
+ Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
50
+ layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
51
+ Default: ``torch.strided``.
52
+ requires_grad (bool, optional): If autograd should record operations on the
53
+ returned tensor. Default: ``False``.
54
+ pin_memory (bool, optional): If set, returned tensor would be allocated in
55
+ the pinned memory. Works only for CPU tensors. Default: ``False``.
56
+ memory_format (:class:`torch.memory_format`, optional): the desired memory format of
57
+ returned Tensor. Default: ``torch.contiguous_format``.
58
+ process_group (ProcessGroup, optional): The process group to work on. If None,
59
+ the default process group will be used.
60
+ init_rrefs (bool, optional): Whether or not to initialize
61
+ :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
62
+ Need to initialize the RPC Framework if specified as ``True``.
63
+ Default: ``False``.
64
+
65
+ Returns:
66
+ A :class:`ShardedTensor` object on each rank
67
+ """
68
+ return ShardedTensor(
69
+ sharding_spec,
70
+ *size,
71
+ dtype=dtype,
72
+ layout=layout,
73
+ requires_grad=requires_grad,
74
+ pin_memory=pin_memory,
75
+ memory_format=memory_format,
76
+ process_group=process_group,
77
+ init_rrefs=init_rrefs,
78
+ )
79
+
80
+
81
+ def ones(
82
+ sharding_spec: ShardingSpec,
83
+ *size,
84
+ dtype=None,
85
+ layout=torch.strided,
86
+ requires_grad=False,
87
+ pin_memory=False,
88
+ memory_format=torch.contiguous_format,
89
+ process_group=None,
90
+ init_rrefs=False,
91
+ ) -> ShardedTensor:
92
+ """
93
+ Returns a :class:`ShardedTensor` with the scalar value 1.
94
+ Needs to be called on all ranks in an SPMD fashion.
95
+
96
+ Args:
97
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
98
+ describing how to shard the Tensor.
99
+ size (int...): a sequence of integers defining the shape of the output
100
+ tensor. Can be a variable number of arguments or a collection like a list or tuple.
101
+
102
+ Keyword args:
103
+ dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
104
+ Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
105
+ layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
106
+ Default: ``torch.strided``.
107
+ requires_grad (bool, optional): If autograd should record operations on the
108
+ returned tensor. Default: ``False``.
109
+ pin_memory (bool, optional): If set, returned tensor would be allocated in
110
+ the pinned memory. Works only for CPU tensors. Default: ``False``.
111
+ process_group (ProcessGroup, optional): The process group to work on. If None,
112
+ the default process group will be used.
113
+ init_rrefs (bool, optional): Whether or not to initialize
114
+ :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
115
+ Need to initialize the RPC Framework if specified as ``True``.
116
+ Default: ``False``.
117
+
118
+ Returns:
119
+ A :class:`ShardedTensor` object on each rank
120
+ """
121
+ return full(
122
+ sharding_spec,
123
+ size,
124
+ fill_value=1,
125
+ dtype=dtype,
126
+ layout=layout,
127
+ requires_grad=requires_grad,
128
+ pin_memory=pin_memory,
129
+ memory_format=memory_format,
130
+ process_group=process_group,
131
+ init_rrefs=init_rrefs,
132
+ )
133
+
134
+
135
+ def zeros(
136
+ sharding_spec: ShardingSpec,
137
+ *size,
138
+ dtype=None,
139
+ layout=torch.strided,
140
+ requires_grad=False,
141
+ pin_memory=False,
142
+ memory_format=torch.contiguous_format,
143
+ process_group=None,
144
+ init_rrefs=False,
145
+ ) -> ShardedTensor:
146
+ """
147
+ Returns a :class:`ShardedTensor` filled with the scalar value 0.
148
+ Needs to be called on all ranks in an SPMD fashion.
149
+
150
+ Args:
151
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
152
+ describing how to shard the Tensor.
153
+ size (int...): a sequence of integers defining the shape of the output
154
+ tensor. Can be a variable number of arguments or a collection like a list or tuple.
155
+
156
+ Keyword args:
157
+ dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
158
+ Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
159
+ layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
160
+ Default: ``torch.strided``.
161
+ requires_grad (bool, optional): If autograd should record operations on the
162
+ returned tensor. Default: ``False``.
163
+ pin_memory (bool, optional): If set, returned tensor would be allocated in
164
+ the pinned memory. Works only for CPU tensors. Default: ``False``.
165
+ process_group (ProcessGroup, optional): The process group to work on. If None,
166
+ the default process group will be used.
167
+ init_rrefs (bool, optional): Whether or not to initialize
168
+ :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
169
+ Need to initialize the RPC Framework if specified as ``True``.
170
+ Default: ``False``.
171
+
172
+ Returns:
173
+ A :class:`ShardedTensor` object on each rank
174
+ """
175
+ return full(
176
+ sharding_spec,
177
+ size,
178
+ fill_value=0,
179
+ dtype=dtype,
180
+ layout=layout,
181
+ requires_grad=requires_grad,
182
+ pin_memory=pin_memory,
183
+ memory_format=memory_format,
184
+ process_group=process_group,
185
+ init_rrefs=init_rrefs,
186
+ )
187
+
188
+
189
+ def full(
190
+ sharding_spec: ShardingSpec,
191
+ size,
192
+ fill_value,
193
+ *,
194
+ dtype=None,
195
+ layout=torch.strided,
196
+ requires_grad=False,
197
+ pin_memory=False,
198
+ memory_format=torch.contiguous_format,
199
+ process_group=None,
200
+ init_rrefs=False,
201
+ ) -> ShardedTensor:
202
+ """
203
+ Creates a :class:`ShardedTensor` filled with fill_value. The tensor's dtype
204
+ is inferred from fill_value. If dtype is specified, it will override the
205
+ inferred type from fill_value. Needs to be called on all ranks in an SPMD fashion.
206
+ Args:
207
+ sharding_spec (:class:`torch.distributed._sharding_spec.ShardingSpec`): The specification
208
+ describing how to shard the Tensor.
209
+ size (int...): a list, tuple, or `torch.Size` of integers defining the shape of the
210
+ output tensor.
211
+ fill_value (Scalar) - the value to fill the output tensor with.
212
+ Keyword args:
213
+ dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
214
+ Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
215
+ layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
216
+ Default: ``torch.strided``.
217
+ requires_grad (bool, optional): If autograd should record operations on the
218
+ returned tensor. Default: ``False``.
219
+ pin_memory (bool, optional): If set, returned tensor would be allocated in
220
+ the pinned memory. Works only for CPU tensors. Default: ``False``.
221
+ process_group (ProcessGroup, optional): The process group to work on. If None,
222
+ the default process group will be used.
223
+ init_rrefs (bool, optional): Whether or not to initialize
224
+ :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
225
+ Need to initialize the RPC Framework if specified as ``True``.
226
+ Default: ``False``.
227
+ Returns:
228
+ A :class:`ShardedTensor` object on each rank
229
+ """
230
+ sharded_tensor = ShardedTensor(
231
+ sharding_spec,
232
+ *size,
233
+ dtype=dtype,
234
+ layout=layout,
235
+ requires_grad=requires_grad,
236
+ pin_memory=pin_memory,
237
+ memory_format=memory_format,
238
+ process_group=process_group,
239
+ init_rrefs=init_rrefs,
240
+ )
241
+ torch.nn.init.constant_(sharded_tensor, fill_value) # type: ignore[arg-type]
242
+ return sharded_tensor
243
+
244
+
245
+ def rand(
246
+ sharding_spec: ShardingSpec,
247
+ *size,
248
+ dtype=None,
249
+ layout=torch.strided,
250
+ requires_grad=False,
251
+ pin_memory=False,
252
+ memory_format=torch.contiguous_format,
253
+ process_group=None,
254
+ init_rrefs=False,
255
+ ) -> ShardedTensor:
256
+ """
257
+ Creates a :class:`ShardedTensor` filled with random numbers from a uniform distribution
258
+ on the interval :math:`[0, 1)`. The shape of the tensor is defined by the
259
+ variable argument `size`. Needs to be called on all ranks in an SPMD fashion.
260
+
261
+ Args:
262
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
263
+ describing how to shard the Tensor.
264
+ size (int...): a list, tuple, or `torch.Size` of integers defining the shape of the
265
+ output tensor.
266
+
267
+ Keyword args:
268
+ dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
269
+ Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
270
+ layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
271
+ Default: ``torch.strided``.
272
+ requires_grad (bool, optional): If autograd should record operations on the
273
+ returned tensor. Default: ``False``.
274
+ pin_memory (bool, optional): If set, returned tensor would be allocated in
275
+ the pinned memory. Works only for CPU tensors. Default: ``False``.
276
+ process_group (ProcessGroup, optional): The process group to work on. If None,
277
+ the default process group will be used.
278
+ init_rrefs (bool, optional): Whether or not to initialize
279
+ :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
280
+ Need to initialize the RPC Framework if specified as ``True``.
281
+ Default: ``False``.
282
+
283
+ Returns:
284
+ A :class:`ShardedTensor` object on each rank
285
+ """
286
+ sharded_tensor = ShardedTensor(
287
+ sharding_spec,
288
+ *size,
289
+ dtype=dtype,
290
+ layout=layout,
291
+ requires_grad=requires_grad,
292
+ pin_memory=pin_memory,
293
+ memory_format=memory_format,
294
+ process_group=process_group,
295
+ init_rrefs=init_rrefs,
296
+ )
297
+ torch.nn.init.uniform_(sharded_tensor, 0, 1) # type: ignore[arg-type]
298
+ return sharded_tensor
299
+
300
+
301
+ def randn(
302
+ sharding_spec: ShardingSpec,
303
+ *size,
304
+ dtype=None,
305
+ layout=torch.strided,
306
+ requires_grad=False,
307
+ pin_memory=False,
308
+ memory_format=torch.contiguous_format,
309
+ process_group=None,
310
+ init_rrefs=False,
311
+ ) -> ShardedTensor:
312
+ """
313
+ Creates a :class:`ShardedTensor` filled with random numbers from a uniform distribution
314
+ with mean `0` and variance `1` (also called standard normal distribution). The shape
315
+ of the tensor is defined by the variable argument `size`. Needs to be called on all ranks
316
+ in an SPMD fashion.
317
+
318
+ Args:
319
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
320
+ describing how to shard the Tensor.
321
+ size (int...): a list, tuple, or `torch.Size` of integers defining the shape of the
322
+ output tensor.
323
+
324
+ Keyword args:
325
+ dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
326
+ Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
327
+ layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
328
+ Default: ``torch.strided``.
329
+ requires_grad (bool, optional): If autograd should record operations on the
330
+ returned tensor. Default: ``False``.
331
+ pin_memory (bool, optional): If set, returned tensor would be allocated in
332
+ the pinned memory. Works only for CPU tensors. Default: ``False``.
333
+ process_group (ProcessGroup, optional): The process group to work on. If None,
334
+ the default process group will be used.
335
+ init_rrefs (bool, optional): Whether or not to initialize
336
+ :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
337
+ Need to initialize the RPC Framework if specified as ``True``.
338
+ Default: ``False``.
339
+
340
+ Returns:
341
+ A :class:`ShardedTensor` object on each rank
342
+ """
343
+ sharded_tensor = ShardedTensor(
344
+ sharding_spec,
345
+ *size,
346
+ dtype=dtype,
347
+ layout=layout,
348
+ requires_grad=requires_grad,
349
+ pin_memory=pin_memory,
350
+ memory_format=memory_format,
351
+ process_group=process_group,
352
+ init_rrefs=init_rrefs,
353
+ )
354
+ torch.nn.init.normal_(sharded_tensor, 0, 1) # type: ignore[arg-type]
355
+ return sharded_tensor
356
+
357
+
358
+ def init_from_local_shards(
359
+ local_shards: list[Shard], *global_size, process_group=None, init_rrefs=False
360
+ ) -> ShardedTensor:
361
+ """
362
+ Creates an :class:`ShardedTensor` from local shards and the global metadata.
363
+ Needs to be called on all ranks in an SPMD fashion.
364
+
365
+ Args:
366
+ local_shards (List[:class `torch.distributed._shard.sharded_tensor.Shard`]): A list
367
+ of shards that represent the local shards on this rank.
368
+ global_size (int...): a list, tuple, or `torch.Size` of integers defining the
369
+ shape of the overall sharded tensor.
370
+
371
+ Keyword args:
372
+ process_group (ProcessGroup, optional): The process group to work on. If None,
373
+ the default process group will be used.
374
+ init_rrefs (bool, optional): Whether or not to initialize
375
+ :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
376
+ Need to initialize the RPC Framework if specified as ``True``.
377
+ Default: ``False``.
378
+
379
+ Returns:
380
+ A :class:`ShardedTensor` object handle on this rank
381
+
382
+
383
+ Examples:
384
+ Suppose we want construct a sharded tensor on two ranks, global size = (10, 5),
385
+ each shard have a (5, 5) local tensor, we can do it like below:
386
+
387
+ on rank 0:
388
+ >>> # xdoctest: +SKIP("not distributed")
389
+ >>> local_shard_metadata = ShardMetadata(
390
+ >>> shard_offsets=[0, 0],
391
+ >>> shard_lengths=[5, 5],
392
+ >>> placement="rank:0/cuda:0"
393
+ >>> )
394
+ >>> local_shards = [Shard(torch.randn(5, 5), local_shard_metadata)]
395
+ >>> sharded_tensor = init_from_local_shards(local_shards, [10, 5])
396
+
397
+ on rank 1:
398
+ >>> # xdoctest: +SKIP("not distributed")
399
+ >>> local_shard_metadata = ShardMetadata(
400
+ >>> shard_offsets=[5, 0],
401
+ >>> shard_lengths=[5, 5],
402
+ >>> placement="rank:1/cuda:1"
403
+ >>> )
404
+ >>> local_shards = [Shard(torch.randn(5, 5), local_shard_metadata)]
405
+ >>> sharded_tensor = init_from_local_shards(local_shards, [10, 5])
406
+ """
407
+ return ShardedTensor._init_from_local_shards(
408
+ local_shards, *global_size, process_group=process_group, init_rrefs=init_rrefs
409
+ )
410
+
411
+
412
+ def state_dict_hook(module, destination, prefix, local_metadata):
413
+ """
414
+ Hook to add ShardedTensor to Module's ``state_dict``. Needs to be
415
+ registered to the Module using
416
+ :meth:`torch.nn.Module._register_state_dict_hook`.
417
+ """
418
+ for submodule_name, submodule in module.named_modules():
419
+ for attr_name, attr in submodule.__dict__.items():
420
+ if isinstance(attr, ShardedTensor):
421
+ mod_prefix = prefix + submodule_name
422
+ key = mod_prefix + ("." if mod_prefix else "") + attr_name
423
+ destination[key] = attr
424
+
425
+
426
+ def pre_load_state_dict_hook(
427
+ module,
428
+ state_dict,
429
+ prefix,
430
+ local_metadata,
431
+ strict,
432
+ missing_keys,
433
+ unexpected_keys,
434
+ error_msgs,
435
+ ):
436
+ """
437
+ Pre-load state dict hook to add ShardedTensor to the module.
438
+ """
439
+ for submodule_name, submodule in module.named_modules():
440
+ for attr_name in submodule.__dict__:
441
+ mod_prefix = prefix + submodule_name
442
+ key = mod_prefix + ("." if mod_prefix else "") + attr_name
443
+ if key in state_dict:
444
+ if isinstance(state_dict[key], ShardedTensor):
445
+ setattr(submodule, attr_name, state_dict[key])
446
+
447
+
448
+ def custom_sharded_op_impl(func):
449
+ """
450
+ Provides a way for users to write their own custom sharded operator. This
451
+ can be used to override existing ShardedTensor operators or write a new
452
+ one not supported by ShardedTensor. If the operator in question is covered
453
+ by ``__torch_function__`` dispatch and has a ShardedTensor as any of its
454
+ parameters, the function provided will be invoked for that operator.
455
+
456
+ Example::
457
+ >>> # xdoctest: +SKIP
458
+ >>> @custom_sharded_op_impl(torch.nn.functional.linear)
459
+ >>> def my_custom_sharded_linear(types, args, kwargs, process_group):
460
+ >>> ...
461
+ >>> # xdoctest: +SKIP("Undefined variables")
462
+ >>> input = torch.rand(10, 32)
463
+ >>> weight = sharded_tensor.rand(32, 16)
464
+ >>> bias = torch.rand(16)
465
+ >>> # This will call 'my_custom_sharded_linear'
466
+ >>> torch.nn.functional.linear(input, weight, bias)
467
+
468
+ The types, args and kwargs parameters are the same parameters that are
469
+ passed to ``__torch_function__`` dispatch API
470
+ (https://pytorch.org/docs/stable/notes/extending.html#extending-torch).
471
+ There is an additional ``process_group`` parameter which is the
472
+ process_group used for the ShardedTensor and can be used by
473
+ implementations for communications within a sharded implementation.
474
+
475
+ Args:
476
+ func(Callable): Torch function for which we want to provide a sharded
477
+ implementation (ex: torch.nn.functional.linear)
478
+ """
479
+ return functools.partial(_decorator_func, op=func, op_table=_CUSTOM_SHARDED_OPS)
480
+
481
+
482
+ def _sharded_op_impl(func):
483
+ """
484
+ Decorator to register a default sharded op.
485
+ """
486
+ return functools.partial(_decorator_func, op=func, op_table=_SHARDED_OPS)
487
+
488
+
489
+ # Import all builtin sharded ops
490
+ from ._ops import * # noqa: F403
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/_ops/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.distributed._shard.sharded_tensor._ops.misc_ops
2
+ import torch.distributed._shard.sharded_tensor._ops.tensor_ops
3
+
4
+ # Import all ChunkShardingSpec ops
5
+ from torch.distributed._shard.sharding_spec.chunk_sharding_spec_ops.embedding import (
6
+ sharded_embedding,
7
+ )
8
+ from torch.distributed._shard.sharding_spec.chunk_sharding_spec_ops.embedding_bag import (
9
+ sharded_embedding_bag,
10
+ )
11
+
12
+ from .binary_cmp import allclose, equal
13
+ from .init import constant_, kaiming_uniform_, normal_, uniform_
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/_ops/_common.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+
4
+ from torch.distributed._shard.common_op_utils import _basic_validation
5
+ from torch.distributed._shard.sharded_tensor import (
6
+ _sharded_op_impl,
7
+ Shard,
8
+ ShardedTensor,
9
+ )
10
+
11
+
12
+ def _sharded_op_common(op, early_stop_func, extra_check):
13
+ """
14
+ Inject sharded tensor op registration with common logics executed before
15
+ different behaviors are done on either local shards or a local tensor.
16
+
17
+ Example::
18
+ >>> # xdoctest: +SKIP("Undefined variables")
19
+ >>> op = torch.transpose
20
+ >>> @_sharded_op_impl(op)
21
+ >>> @_sharded_op_common(op, early_stop_func, extra_check)
22
+ >>> def sharded_tensor_op(types, args, kwargs, process_group):
23
+ >>> ...
24
+ >>>
25
+ >>> st = sharded_tensor.rand(32, 16)
26
+ >>> st.transpose(1, 2)
27
+ >>> # This will call '_sharded_op_common'
28
+
29
+ Args:
30
+ op: The op to be registered and applied to all shards of the st.
31
+ early_stop_func (Callable, optional): the func for early stop.
32
+ Default: if ``None``, no early stop.
33
+ extra_check (Callable, optional): the func for extra condition check.
34
+ Default: if ``None``, no extra check.
35
+
36
+ Return:
37
+ func (Callable): Torch function for which we want to provide a sharded
38
+ implementation (ex: torch.transpose)
39
+ """
40
+
41
+ def decorator_sharded_func(wrapped_func):
42
+ @functools.wraps(wrapped_func)
43
+ def wrapper(types, args=(), kwargs=None, pg=None):
44
+ _basic_validation(op, args, kwargs)
45
+
46
+ # pyrefly: ignore [index-error]
47
+ st = args[0]
48
+ if kwargs is None:
49
+ kwargs = {}
50
+ if extra_check:
51
+ extra_check(*args, **kwargs)
52
+ if early_stop_func:
53
+ early_stop = early_stop_func(*args, **kwargs)
54
+ if early_stop:
55
+ return st
56
+ return wrapped_func(types, args, kwargs, pg)
57
+
58
+ return wrapper
59
+
60
+ return decorator_sharded_func
61
+
62
+
63
+ def _register_sharded_op_on_local_shards(
64
+ op, early_stop_func=None, extra_check=None, customized_func=None
65
+ ):
66
+ """
67
+ Handles ``__torch_function__`` dispatch for ops which are performed on
68
+ each shard of the sharded tensor such as elementwise op like
69
+ ``torch.nn.functional.gelu`` or ``torch.nn.functional.relu``.
70
+
71
+ For more complicated ops, a customized func can be used to generate
72
+ the new shards and sharded tensor size.
73
+
74
+ This function expects that the original ShardingSpec for the ShardedTensor
75
+ is preserved irrespective of whether or not a customized function is used.
76
+
77
+ Args:
78
+ op: The op to be registered and applied to all shards of the st.
79
+ early_stop_func (Callable, optional): the func for early stop.
80
+ Default: if ``None``, no early stop.
81
+ extra_check (Callable, optional): the func for extra condition check.
82
+ Default: if ``None``, no extra check.
83
+ customized_func (Callable, optional): the func for customized logic
84
+ to generate new shards and sharded tensor size.
85
+ Default: if ``None``, we simply lower to the real op call with
86
+ all local shards of the st.
87
+
88
+ Return:
89
+ func (Callable): registered implementation for sharded op for
90
+ ``__torch_function__`` dispatch.
91
+ """
92
+
93
+ @_sharded_op_impl(op)
94
+ @_sharded_op_common(op, early_stop_func, extra_check)
95
+ def sharded_tensor_op_on_local_shards(types, args=(), kwargs=None, pg=None):
96
+ # pyrefly: ignore [index-error]
97
+ st = args[0]
98
+ st_metadata = st.metadata()
99
+ local_shards = st.local_shards()
100
+ local_shards_new = []
101
+ if customized_func:
102
+ local_shards_new, st_metadata = customized_func(args, kwargs, pg)
103
+ else:
104
+ for local_shard in local_shards:
105
+ args = (local_shard.tensor, *args[1:])
106
+ local_shards_new.append(
107
+ Shard(op(*args, **kwargs), local_shard.metadata)
108
+ )
109
+ return ShardedTensor._init_from_local_shards_and_global_metadata(
110
+ local_shards_new,
111
+ st_metadata,
112
+ process_group=pg,
113
+ init_rrefs=st._init_rrefs,
114
+ sharding_spec=st.sharding_spec(),
115
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/_ops/binary_cmp.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ import torch.distributed as dist
4
+ import torch.distributed.distributed_c10d as distributed_c10d
5
+ from torch.distributed._shard.sharded_tensor import _sharded_op_impl, ShardedTensor
6
+
7
+
8
+ def _communicate_result(result, pg):
9
+ # Gather results from all ranks.
10
+ if result:
11
+ result_tensor = torch.ones(1, device=torch.device(torch.cuda.current_device()))
12
+ else:
13
+ result_tensor = torch.zeros(1, device=torch.device(torch.cuda.current_device()))
14
+
15
+ dist.all_reduce(result_tensor, group=pg)
16
+
17
+ expected_result = torch.ones(
18
+ 1, device=torch.device(torch.cuda.current_device())
19
+ ) * dist.get_world_size(pg)
20
+
21
+ return torch.equal(result_tensor, expected_result)
22
+
23
+
24
+ def binary_cmp(cmp_fun, types, args, kwargs=None, process_group=None):
25
+ if len(args) != 2:
26
+ raise ValueError(f"Expected two arguments for torch.{cmp_fun.__name__}")
27
+
28
+ st1 = args[0]
29
+ st2 = args[1]
30
+ if not (isinstance(st1, ShardedTensor) and isinstance(st2, ShardedTensor)):
31
+ raise TypeError(
32
+ f"Both arguments to torch.{cmp_fun.__name__} need to be of type ShardedTensor"
33
+ )
34
+
35
+ # Verify same PG
36
+ if st1._process_group != st2._process_group:
37
+ return False
38
+
39
+ if distributed_c10d._rank_not_in_group(
40
+ st1._process_group
41
+ ) or distributed_c10d._rank_not_in_group(st2._process_group):
42
+ return distributed_c10d._rank_not_in_group(
43
+ st1._process_group
44
+ ) == distributed_c10d._rank_not_in_group(st2._process_group)
45
+
46
+ # Verify metadata
47
+ if st1.metadata() != st2.metadata():
48
+ return _communicate_result(False, st1._process_group)
49
+
50
+ # Verify number of local shards
51
+ st1_local_shards = st1.local_shards()
52
+ st2_local_shards = st2.local_shards()
53
+ if len(st1_local_shards) != len(st2_local_shards):
54
+ return _communicate_result(False, st1._process_group)
55
+
56
+ # kwargs must be dict-like
57
+ if kwargs is None:
58
+ kwargs = {}
59
+ # Verify each local shard
60
+ for idx in range(len(st1_local_shards)):
61
+ if st1_local_shards[idx].metadata != st2_local_shards[idx].metadata:
62
+ return _communicate_result(False, st1._process_group)
63
+ if not cmp_fun(
64
+ st1_local_shards[idx].tensor, st2_local_shards[idx].tensor, **kwargs
65
+ ):
66
+ return _communicate_result(False, st1._process_group)
67
+
68
+ return _communicate_result(True, st1._process_group)
69
+
70
+
71
+ @_sharded_op_impl(torch.equal)
72
+ def equal(types, args, kwargs, process_group):
73
+ return binary_cmp(torch.equal, types, args, kwargs, process_group)
74
+
75
+
76
+ @_sharded_op_impl(torch.allclose)
77
+ def allclose(types, args, kwargs, process_group):
78
+ return binary_cmp(torch.allclose, types, args, kwargs, process_group)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/_ops/init.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ import torch.distributed._shard.sharded_tensor as sharded_tensor
4
+ from torch.distributed._shard.sharded_tensor import _sharded_op_impl
5
+
6
+
7
+ def validate_param(param, param_name):
8
+ if param is None:
9
+ raise ValueError(f"param: {param_name} shouldn't be None!")
10
+
11
+
12
+ @_sharded_op_impl(torch.nn.init.uniform_)
13
+ def uniform_(types, args=(), kwargs=None, pg=None):
14
+ r"""
15
+ Fills the Tensor in tensor.local_shards with values drawn from the uniform
16
+ distribution :math:`\mathcal{U}(a, b)`.
17
+ Args:
18
+ tensor: tensor sharded across devices
19
+ a: the lower bound of the uniform distribution
20
+ b: the upper bound of the uniform distribution
21
+ """
22
+ validate_param(kwargs, "kwargs")
23
+ # pyrefly: ignore [unsupported-operation]
24
+ sharded_tensor = kwargs["tensor"]
25
+ validate_param(sharded_tensor, "tensor")
26
+ # pyrefly: ignore [unsupported-operation]
27
+ a = kwargs["a"]
28
+ validate_param(a, "a")
29
+ # pyrefly: ignore [unsupported-operation]
30
+ b = kwargs["b"]
31
+ validate_param(b, "b")
32
+
33
+ for shard in sharded_tensor.local_shards():
34
+ torch.nn.init.uniform_(shard.tensor, a=a, b=b)
35
+ return sharded_tensor
36
+
37
+
38
+ @_sharded_op_impl(torch.nn.init.normal_)
39
+ def normal_(types, args=(), kwargs=None, pg=None):
40
+ r"""
41
+ Fills the Tensors in tensor.local_shards with values drawn from the normal
42
+ distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`.
43
+ Args:
44
+ tensor: tensor sharded across devices
45
+ mean: the mean of the normal distribution
46
+ std: the standard deviation of the normal distribution
47
+ """
48
+ validate_param(kwargs, "kwargs")
49
+ # pyrefly: ignore [unsupported-operation]
50
+ sharded_tensor = kwargs["tensor"]
51
+ validate_param(sharded_tensor, "tensor")
52
+ # pyrefly: ignore [unsupported-operation]
53
+ mean = kwargs["mean"]
54
+ validate_param(mean, "mean")
55
+ # pyrefly: ignore [unsupported-operation]
56
+ std = kwargs["std"]
57
+ validate_param(std, "std")
58
+
59
+ for shard in sharded_tensor.local_shards():
60
+ torch.nn.init.normal_(shard.tensor, mean=mean, std=std)
61
+ return sharded_tensor
62
+
63
+
64
+ @_sharded_op_impl(torch.nn.init.kaiming_uniform_)
65
+ def kaiming_uniform_(types, args=(), kwargs=None, pg=None):
66
+ r"""
67
+ Fills the Tensors in tensor.local_shards with values according to the method
68
+ described in `Delving deep into rectifiers: Surpassing human-level
69
+ performance on ImageNet classification` - He, K. et al. (2015), using a
70
+ uniform distribution. The resulting tensor will have values sampled from
71
+ :math:`\mathcal{U}(-\text{bound}, \text{bound})` where
72
+ .. math::
73
+ \text{bound} = \text{gain} \times \sqrt{\frac{3}{\text{fan\_mode}}}
74
+ Also known as He initialization.
75
+ Args:
76
+ tensor: tensor sharded across devices
77
+ a: the negative slope of the rectifier used after this layer (only
78
+ used with ``'leaky_relu'``)
79
+ mode: either ``'fan_in'`` (default) or ``'fan_out'``. Choosing ``'fan_in'``
80
+ preserves the magnitude of the variance of the weights in the
81
+ forward pass. Choosing ``'fan_out'`` preserves the magnitudes in the
82
+ backwards pass.
83
+ nonlinearity: the non-linear function (`nn.functional` name),
84
+ recommended to use only with ``'relu'`` or ``'leaky_relu'`` (default).
85
+ """
86
+ validate_param(kwargs, "kwargs")
87
+ # pyrefly: ignore [unsupported-operation]
88
+ sharded_tensor = kwargs["tensor"]
89
+ validate_param(sharded_tensor, "tensor")
90
+ # pyrefly: ignore [unsupported-operation]
91
+ a = kwargs["a"]
92
+ validate_param(a, "a")
93
+ # pyrefly: ignore [unsupported-operation]
94
+ mode = kwargs["mode"]
95
+ validate_param(mode, "mode")
96
+ # pyrefly: ignore [unsupported-operation]
97
+ nonlinearity = kwargs["nonlinearity"]
98
+ validate_param(nonlinearity, "nonlinearity")
99
+
100
+ for shard in sharded_tensor.local_shards():
101
+ torch.nn.init.kaiming_uniform_(
102
+ shard.tensor, a=a, mode=mode, nonlinearity=nonlinearity
103
+ )
104
+ return sharded_tensor
105
+
106
+
107
+ @_sharded_op_impl(torch.nn.init.constant_)
108
+ def constant_(types, args=(), kwargs=None, pg=None):
109
+ r"""
110
+ Fills the input ShardedTensor with the value \text{val}val.
111
+ Args:
112
+ tensor: tensor sharded across devices
113
+ val: the value to fill the tensor with
114
+ """
115
+ validate_param(kwargs, "kwargs")
116
+ # pyrefly: ignore [unsupported-operation]
117
+ sharded_tensor = kwargs["tensor"]
118
+ validate_param(sharded_tensor, "tensor")
119
+ # pyrefly: ignore [unsupported-operation]
120
+ val = kwargs["val"]
121
+ validate_param(val, "val")
122
+ for shard in sharded_tensor.local_shards():
123
+ torch.nn.init.constant_(shard.tensor, val=val)
124
+ return sharded_tensor
125
+
126
+
127
+ tensor_like_creation_op_map = {
128
+ torch.full_like: sharded_tensor.full,
129
+ torch.empty_like: sharded_tensor.empty,
130
+ torch.zeros_like: sharded_tensor.zeros,
131
+ torch.ones_like: sharded_tensor.ones,
132
+ torch.rand_like: sharded_tensor.rand,
133
+ torch.randn_like: sharded_tensor.randn,
134
+ }
135
+
136
+
137
+ # tensor ops that behave the same as the default tensor
138
+ def register_tensor_creation_op(op):
139
+ @_sharded_op_impl(op)
140
+ def tensor_creation_op(types, args=(), kwargs=None, pg=None):
141
+ """
142
+ Handles ``__torch_function__`` dispatch for tensor creation ops that
143
+ takes a ShardedTensor as argument, such as ``torch.zeros_like`` or
144
+ ``torch.full_like``.
145
+ """
146
+ creation_op = tensor_like_creation_op_map.get(op)
147
+ if creation_op is None:
148
+ raise RuntimeError(f"Tensor creation {op} not supported!")
149
+ if kwargs is None:
150
+ kwargs = {}
151
+
152
+ # pyrefly: ignore [index-error]
153
+ st = args[0]
154
+
155
+ new_st = creation_op(st.sharding_spec(), st.size(), *args[1:], **kwargs) # type: ignore[operator]
156
+ return new_st
157
+
158
+
159
+ register_tensor_creation_op(torch.full_like)
160
+ register_tensor_creation_op(torch.empty_like)
161
+ register_tensor_creation_op(torch.zeros_like)
162
+ register_tensor_creation_op(torch.ones_like)
163
+ register_tensor_creation_op(torch.rand_like)
164
+ register_tensor_creation_op(torch.randn_like)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/_ops/misc_ops.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ from torch.distributed._shard.sharded_tensor import _sharded_op_impl
4
+
5
+
6
+ # This is used by `_apply()` within module.py to set new
7
+ # parameters after apply a certain method, we should follow
8
+ # the future behavior of overwriting the existing tensor
9
+ # instead of doing in-place change using `.data = `.
10
+ @_sharded_op_impl(torch._has_compatible_shallow_copy_type)
11
+ def tensor_has_compatible_shallow_copy_type(types, args=(), kwargs=None, pg=None):
12
+ return False
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/_ops/tensor_ops.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+
4
+ import torch
5
+ from torch.distributed._shard.common_op_utils import _register_default_op
6
+ from torch.distributed._shard.sharded_tensor import (
7
+ _sharded_op_impl,
8
+ Shard,
9
+ ShardedTensor,
10
+ )
11
+
12
+ from ._common import _register_sharded_op_on_local_shards
13
+
14
+
15
+ # Tensor properties access
16
+ _register_default_op(torch.Tensor.shape.__get__, _sharded_op_impl) # type: ignore[attr-defined]
17
+ _register_default_op(torch.Tensor.dtype.__get__, _sharded_op_impl) # type: ignore[attr-defined]
18
+ _register_default_op(torch.Tensor.layout.__get__, _sharded_op_impl) # type: ignore[attr-defined]
19
+ _register_default_op(torch.Tensor.size, _sharded_op_impl)
20
+ _register_default_op(torch.Tensor.dim, _sharded_op_impl)
21
+ _register_default_op(torch.Tensor.ndim.__get__, _sharded_op_impl) # type: ignore[attr-defined]
22
+ _register_default_op(torch.Tensor.is_contiguous, _sharded_op_impl)
23
+ _register_default_op(torch.Tensor.contiguous, _sharded_op_impl)
24
+ _register_default_op(torch.Tensor.is_floating_point, _sharded_op_impl)
25
+
26
+ # __reduce_ex__ to dispatch to get_state/set_state
27
+ _register_default_op(torch.Tensor.__reduce_ex__, _sharded_op_impl)
28
+
29
+ # autograd related properties
30
+ _register_default_op(torch.Tensor.requires_grad.__get__, _sharded_op_impl) # type: ignore[attr-defined]
31
+ # TODO: set grad with a ShardedTensor that consists of all local grads
32
+ _register_default_op(torch.Tensor.grad.__get__, _sharded_op_impl) # type: ignore[union-attr]
33
+ _register_default_op(torch.Tensor.grad_fn.__get__, _sharded_op_impl) # type: ignore[union-attr]
34
+ _register_default_op(torch.Tensor.is_leaf.__get__, _sharded_op_impl) # type: ignore[attr-defined]
35
+
36
+
37
+ # device property is ambiguous as from a global prospective,
38
+ # ShardedTensor.device consists of multiple devices (might even across hosts)
39
+ # We choose to return the current device of the local tensor to represent
40
+ # the device property on each rank
41
+ @_sharded_op_impl(torch.Tensor.device.__get__)
42
+ def tensor_device(types, args=(), kwargs=None, pg=None):
43
+ # pyrefly: ignore [index-error]
44
+ self_st = args[0]
45
+ # Validate types
46
+ if not isinstance(self_st, ShardedTensor):
47
+ raise TypeError("input needs to be a ShardedTensor")
48
+ dev: torch.device
49
+ if self_st._local_shards:
50
+ dev = self_st._local_shards[0].tensor.device
51
+ elif pg and pg._get_backend_name() == "gloo":
52
+ dev = torch.device("cpu")
53
+ else:
54
+ dev = torch.device(torch.cuda.current_device())
55
+ return dev
56
+
57
+
58
+ @_sharded_op_impl(torch.Tensor.is_meta.__get__) # type: ignore[attr-defined]
59
+ def st_is_meta(types, args=(), kwargs=None, pg=None):
60
+ # pyrefly: ignore [index-error]
61
+ return args[0].local_tensor().is_meta
62
+
63
+
64
+ def sharded_type_as_check(*args, **kwargs):
65
+ """
66
+ Perform extra checks for the sharded_type_as op such as the input needs to
67
+ be either a Tensor or ShardedTensor.
68
+
69
+ Args: same as ``torch.Tensor.type_as``.
70
+
71
+ Return: None
72
+ """
73
+ if len(args) < 2:
74
+ raise ValueError("Needs to give a tensor to cast type as!")
75
+ if not isinstance(args[1], torch.Tensor) and not isinstance(args[1], ShardedTensor):
76
+ raise ValueError("Needs to give a Tensor or ShardedTensor to cast type as!")
77
+
78
+
79
+ def same_dtype(*args, **kwargs):
80
+ """
81
+ When the dtype is the same, return the original ShardedTensor.
82
+
83
+ Args: same as ``torch.Tensor.type_as``.
84
+
85
+ Return (bool): Whether to return early or not.
86
+ """
87
+ return args[0].dtype == args[1].dtype
88
+
89
+
90
+ def sharded_type_as(args, kwargs, pg):
91
+ """
92
+ Handles ``__torch_function__`` dispatch for the ``torch.Tensor.type_as`` op.
93
+
94
+ Args: same as ``torch.Tensor.type_as``.
95
+
96
+ Return:
97
+ new_local_shards (List[Shard]): Local shards for the new sharded tensor.
98
+ st_meta (ShardedTensorMetadata): Metadata of the new sharded tensor.
99
+ """
100
+ st = args[0]
101
+ tensor = args[1]
102
+ if isinstance(tensor, ShardedTensor):
103
+ tensor = tensor.local_tensor()
104
+ new_local_shards = [
105
+ Shard(shard.tensor.type_as(tensor), shard.metadata)
106
+ for shard in st.local_shards()
107
+ ]
108
+ st_meta = copy.deepcopy(st._metadata)
109
+ st_meta.tensor_properties.dtype = tensor.dtype
110
+ return new_local_shards, st_meta
111
+
112
+
113
+ _register_sharded_op_on_local_shards(
114
+ torch.Tensor.type_as,
115
+ early_stop_func=same_dtype,
116
+ extra_check=sharded_type_as_check,
117
+ customized_func=sharded_type_as,
118
+ )
119
+
120
+
121
+ def sharded_deepcopy(args, kwargs, pg):
122
+ # NOTE: we directly implement deepcopy magic method
123
+ # instead of using the default tensor.__deepcopy__
124
+ # and implement clone(). This is because the default
125
+ # tensor deepcopy copies every attribute, but the
126
+ # process_group in ShardedTensor cannot be deep copied.
127
+ self_st = args[0]
128
+ new_local_shards = copy.deepcopy(self_st.local_shards())
129
+ new_metadata = copy.deepcopy(self_st.metadata())
130
+ return new_local_shards, new_metadata
131
+
132
+
133
+ _register_sharded_op_on_local_shards(
134
+ torch.Tensor.__deepcopy__,
135
+ customized_func=sharded_deepcopy,
136
+ )
137
+
138
+
139
+ @_sharded_op_impl(torch.Tensor.copy_)
140
+ def sharded_inplace_copy(types, args, kwargs, pg):
141
+ # NOTE: inplace op don't need to rewrap
142
+ kwargs = {} if kwargs is None else kwargs
143
+ self_st = args[0]
144
+ new_st = args[1]
145
+ nonblocking = kwargs.get("non_blocking", False)
146
+ for local_shard, new_shard in zip(self_st.local_shards(), new_st.local_shards()):
147
+ if local_shard.metadata != new_shard.metadata:
148
+ raise RuntimeError(
149
+ "inplace copy can only happen between two ShardedTensor with same metadata!"
150
+ )
151
+ for local_shard, new_shard in zip(self_st.local_shards(), new_st.local_shards()):
152
+ local_shard.tensor.copy_(new_shard.tensor, nonblocking)
153
+
154
+ return self_st
155
+
156
+
157
+ def sharded_clone(args, kwargs, pg):
158
+ self_st = args[0]
159
+ desire_memory_format = kwargs.get("memory_format", None)
160
+ if desire_memory_format and desire_memory_format != torch.preserve_format:
161
+ raise RuntimeError("Only support torch.preserve_format for ShardedTensor!")
162
+ cloned_local_shards = [
163
+ Shard(
164
+ local_shard.tensor.clone(memory_format=desire_memory_format),
165
+ metadata=copy.deepcopy(local_shard.metadata),
166
+ )
167
+ for local_shard in self_st.local_shards()
168
+ ]
169
+ new_metadata = copy.deepcopy(self_st.metadata())
170
+ return cloned_local_shards, new_metadata
171
+
172
+
173
+ _register_sharded_op_on_local_shards(
174
+ torch.Tensor.clone,
175
+ customized_func=sharded_clone,
176
+ )
177
+
178
+
179
+ def sharded_detach(args, kwargs, pg):
180
+ self_st = args[0]
181
+ detached_local_shards = [
182
+ Shard(
183
+ local_shard.tensor.detach(),
184
+ metadata=copy.deepcopy(local_shard.metadata),
185
+ )
186
+ for local_shard in self_st.local_shards()
187
+ ]
188
+ new_metadata = copy.deepcopy(self_st.metadata())
189
+ new_metadata.tensor_properties.requires_grad = False
190
+ return detached_local_shards, new_metadata
191
+
192
+
193
+ _register_sharded_op_on_local_shards(
194
+ torch.Tensor.detach,
195
+ customized_func=sharded_detach,
196
+ )
197
+
198
+
199
+ @_sharded_op_impl(torch.Tensor.requires_grad_)
200
+ def tensor_requires_grad_set(types, args=(), kwargs=None, pg=None):
201
+ # pyrefly: ignore [index-error]
202
+ self_st = args[0]
203
+ # Validate types
204
+ if not isinstance(self_st, ShardedTensor):
205
+ raise TypeError("input needs to be a ShardedTensor")
206
+
207
+ if kwargs is None:
208
+ kwargs = {}
209
+
210
+ requires_grad = args[1] if len(args) > 1 else kwargs.get("requires_grad", True)
211
+ if requires_grad == self_st.requires_grad:
212
+ return self_st
213
+
214
+ for local_shard in self_st.local_shards():
215
+ local_shard.tensor.requires_grad_(requires_grad)
216
+
217
+ # update the wrapper class property
218
+ with torch._C.DisableTorchFunctionSubclass():
219
+ self_st.requires_grad_(requires_grad)
220
+ # update the metadata in the meanwhile
221
+ self_st._metadata.tensor_properties.requires_grad = requires_grad
222
+ return self_st
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/api.py ADDED
@@ -0,0 +1,1368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations # type: ignore[attr-defined]
3
+
4
+ import copy
5
+ import operator
6
+ import threading
7
+ import warnings
8
+ import weakref
9
+ from dataclasses import dataclass
10
+ from functools import reduce
11
+ from typing import cast, TYPE_CHECKING
12
+ from typing_extensions import deprecated
13
+
14
+ import torch
15
+ import torch.distributed as dist
16
+ import torch.distributed._shard.sharding_spec as shard_spec
17
+ from torch._utils import _get_device_module
18
+ from torch.distributed import distributed_c10d, rpc
19
+ from torch.distributed._shard._utils import DEPRECATE_MSG
20
+ from torch.distributed._shard.sharding_spec._internals import (
21
+ check_tensor,
22
+ validate_non_overlapping_shards_metadata,
23
+ )
24
+ from torch.distributed._shard.sharding_spec.api import (
25
+ _dispatch_custom_op,
26
+ _has_custom_op,
27
+ )
28
+ from torch.distributed.remote_device import _remote_device
29
+ from torch.utils import _pytree as pytree
30
+
31
+ from .metadata import ShardedTensorMetadata, TensorProperties
32
+ from .reshard import reshard_local_shard, reshuffle_local_shard
33
+ from .shard import Shard
34
+ from .utils import (
35
+ _flatten_tensor_size,
36
+ _parse_and_validate_remote_device,
37
+ _validate_output_tensor_for_gather,
38
+ build_global_metadata,
39
+ build_metadata_from_local_shards,
40
+ )
41
+
42
+
43
+ if TYPE_CHECKING:
44
+ from collections.abc import Callable, Sequence
45
+
46
+ from torch.distributed._shard.metadata import ShardMetadata
47
+
48
+
49
+ # Tracking for sharded tensor objects.
50
+ _sharded_tensor_lock = threading.Lock()
51
+ _sharded_tensor_current_id = 0
52
+ _sharded_tensor_map: dict[int, weakref.ReferenceType[ShardedTensor]] = {}
53
+
54
+ # Default sharded ops
55
+ _SHARDED_OPS: dict[Callable, Callable] = {}
56
+
57
+ # Customized user ops
58
+ _CUSTOM_SHARDED_OPS: dict[Callable, Callable] = {}
59
+
60
+
61
+ def _register_remote_shards(
62
+ sharded_tensor_id: int, rrefs: list[rpc.RRef[Shard]], rpc_rank: int
63
+ ):
64
+ with _sharded_tensor_lock:
65
+ if sharded_tensor_id not in _sharded_tensor_map:
66
+ raise RuntimeError(
67
+ f"Could not find sharded_tensor_id: {sharded_tensor_id} in map: {_sharded_tensor_map.keys()}"
68
+ )
69
+
70
+ sharded_tensor = _sharded_tensor_map[sharded_tensor_id]()
71
+ if sharded_tensor is None:
72
+ raise RuntimeError("ShardedTensor weakref has been deallocated")
73
+ else:
74
+ sharded_tensor._register_remote_shards(rrefs, rpc_rank)
75
+
76
+
77
+ class ShardedTensorBase(torch.Tensor):
78
+ _sharding_spec: shard_spec.ShardingSpec
79
+ _metadata: ShardedTensorMetadata
80
+ _local_shards: list[Shard]
81
+
82
+ def __new__(cls, sharding_spec: shard_spec.ShardingSpec, *size, **kwargs):
83
+ # Use __new__ to construct a wrapper tensor, for recording tensor
84
+ # properties and logging purposes.
85
+ torch._C._log_api_usage_once("torch.distributed._shard.sharded_tensor")
86
+
87
+ # check sharding spec and build sharded tensor metadata
88
+ if not isinstance(sharding_spec, shard_spec.ShardingSpec):
89
+ raise ValueError(f"Expecting ShardingSpec but got: {type(sharding_spec)}")
90
+
91
+ sizes = _flatten_tensor_size(size)
92
+ dtype = kwargs["dtype"]
93
+ layout = kwargs["layout"]
94
+ pin_memory = kwargs["pin_memory"]
95
+ requires_grad = kwargs["requires_grad"]
96
+
97
+ if dtype is None:
98
+ dtype = torch.get_default_dtype()
99
+
100
+ tensor_properties = TensorProperties(
101
+ dtype, layout, requires_grad, pin_memory=pin_memory
102
+ )
103
+ sharded_tensor_metadata = sharding_spec.build_metadata(
104
+ sizes, tensor_properties=tensor_properties
105
+ )
106
+
107
+ r = torch.Tensor._make_wrapper_subclass(
108
+ cls,
109
+ sizes,
110
+ dtype=dtype,
111
+ layout=layout,
112
+ pin_memory=pin_memory,
113
+ requires_grad=requires_grad,
114
+ )
115
+ # set sharding spec
116
+ r._sharding_spec = sharding_spec
117
+ # set metadata
118
+ r._metadata = sharded_tensor_metadata
119
+ # set local shards
120
+ r._local_shards = []
121
+ return r
122
+
123
+ def metadata(self) -> ShardedTensorMetadata:
124
+ """
125
+ Returns a :class:`ShardedTensorMetadata` object corresponding to the
126
+ metadata for the entire tensor.
127
+ """
128
+ return self._metadata
129
+
130
+ def local_shards(self) -> list[Shard]:
131
+ """
132
+ Returns a list of :class:`Shard' corresponding to the
133
+ local shards for this rank. Returns an empty list if the current rank
134
+ does not host any shards for this Tensor.
135
+ """
136
+ return self._local_shards
137
+
138
+ @classmethod
139
+ def _init_from_local_shards_and_global_metadata(
140
+ cls,
141
+ local_shards: list[Shard],
142
+ sharded_tensor_metadata: ShardedTensorMetadata,
143
+ sharding_spec=None,
144
+ ) -> ShardedTensorBase:
145
+ """
146
+ Initialize a ShardedTensorBase with local shards and a global
147
+ ShardedTensorMetadata built on each rank.
148
+ Warning: This API is experimental and subject to change. It does
149
+ not do cross rank validations, and fully rely on the user
150
+ for the correctness of sharded_tensor_metadata on each rank
151
+ """
152
+ shards_metadata = sharded_tensor_metadata.shards_metadata
153
+ tensor_properties = sharded_tensor_metadata.tensor_properties
154
+
155
+ if len(shards_metadata) == 0:
156
+ raise ValueError("shards_metadata must not be empty!")
157
+
158
+ if tensor_properties.layout != torch.strided:
159
+ raise ValueError("Only torch.strided layout is currently supported")
160
+
161
+ if sharding_spec is None:
162
+ spec = shard_spec._infer_sharding_spec_from_shards_metadata(shards_metadata)
163
+ else:
164
+ spec = sharding_spec
165
+
166
+ sharded_tensor_base = ShardedTensorBase.__new__(
167
+ ShardedTensor,
168
+ spec,
169
+ sharded_tensor_metadata.size,
170
+ dtype=tensor_properties.dtype,
171
+ layout=tensor_properties.layout,
172
+ pin_memory=tensor_properties.pin_memory,
173
+ requires_grad=tensor_properties.requires_grad,
174
+ )
175
+
176
+ # check if shards_metadata have overlap shards
177
+ validate_non_overlapping_shards_metadata(shards_metadata)
178
+
179
+ # check if the shards_metadata is compatible with overall size of the sharded tensor.
180
+ check_tensor(shards_metadata, list(sharded_tensor_metadata.size))
181
+
182
+ # done validation, add local_shards
183
+ sharded_tensor_base._local_shards = local_shards
184
+ return sharded_tensor_base
185
+
186
+ @classmethod
187
+ def __torch_dispatch__(cls, func, types, args=(), kwargs=None): # type: ignore[override]
188
+ raise RuntimeError(
189
+ f"A {cls.__name__} object is being used from c++ while calling {func.__module__}.{func.__name__} "
190
+ "but the there is no custom __torch_dispatch__ implementation for it."
191
+ )
192
+
193
+
194
+ class ShardedTensor(ShardedTensorBase):
195
+ """
196
+ ShardedTensor is an torch.Tensor subclass to represent Tensors that are sharded
197
+ across multiple devices and multiple processes.
198
+
199
+ ShardedTensor is initialized in an SPMD like fashion where each rank
200
+ initializes the ShardedTensor. The ShardedTensor object on each rank
201
+ then only stores the local shard for the Tensor and provides global
202
+ metadata for all the shards.
203
+
204
+ ShardedTensor doesn't provide any Tensor like operations but is a wrapper
205
+ providing the Tensor representing the local shard and the global metadata.
206
+ Using these, users can build their custom distributed._sharded computations
207
+ on top of this primitive. The local shards are all initialized using the
208
+ create_op specified by tensor_init_params.create_op, e.g., torch.ones, or
209
+ torch.empty
210
+
211
+ Args:
212
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
213
+ describing how to shard the Tensor.
214
+ size (int...): a sequence of integers defining the shape of the output
215
+ tensor. Can be a variable number of arguments or a collection like a list or tuple.
216
+
217
+ Keyword args:
218
+ dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
219
+ Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
220
+ layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
221
+ Default: ``torch.strided``.
222
+ requires_grad (bool, optional): If autograd should record operations on the
223
+ returned tensor. Default: ``False``.
224
+ pin_memory (bool, optional): If set, returned tensor would be allocated in
225
+ the pinned memory. Works only for CPU tensors. Default: ``False``.
226
+ memory_format (:class:`torch.memory_format`, optional): the desired memory format of
227
+ returned Tensor. Default: ``torch.contiguous_format``.
228
+ init_rrefs (bool, optional): Whether or not to initialize
229
+ :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
230
+ Need to initialize the RPC Framework if specified as ``True``.
231
+ Default: ``False``.
232
+
233
+ .. note:: ShardedTensor uses collectives to do various operations, i.e. it
234
+ uses all_gather to do cross rank validations. For NCCL-based process
235
+ groups, internal tensor representations of objects must be moved to the
236
+ GPU device before communication takes place. In this case, the device
237
+ used is given by ``torch.cuda.current_device()`` and it is the user's
238
+ responsibility to ensure that this is set so that each rank has an
239
+ individual GPU, via ``torch.cuda.set_device()``
240
+
241
+ """
242
+
243
+ def __new__(cls, sharding_spec: shard_spec.ShardingSpec, *size, **kwargs):
244
+ self = super().__new__(cls, sharding_spec, *size, **kwargs)
245
+ return self
246
+
247
+ def __init__(
248
+ self,
249
+ sharding_spec: shard_spec.ShardingSpec,
250
+ *size,
251
+ dtype=None,
252
+ layout=torch.strided,
253
+ requires_grad=False,
254
+ pin_memory=False,
255
+ memory_format=torch.contiguous_format,
256
+ process_group=None,
257
+ init_rrefs=False,
258
+ ):
259
+ # prepare initialization, initialize fields like
260
+ # _process_group, _local_shards, etc.
261
+ self._prepare_init(process_group=process_group, init_rrefs=init_rrefs)
262
+
263
+ if layout != torch.strided:
264
+ raise ValueError("Only torch.strided layout is currently supported")
265
+
266
+ if memory_format != torch.contiguous_format:
267
+ raise ValueError(
268
+ "Only torch.contiguous_format memory_format is currently supported"
269
+ )
270
+
271
+ self._metadata.tensor_properties.memory_format = memory_format
272
+
273
+ current_rank = dist.get_rank() # global rank
274
+
275
+ for shard_metadata in self._metadata.shards_metadata:
276
+ rank, device = _parse_and_validate_remote_device(
277
+ self._process_group, shard_metadata.placement
278
+ )
279
+ if rank == current_rank:
280
+ local_tensor = _create_tensor_from_params(
281
+ shard_metadata.shard_sizes,
282
+ local_device=device,
283
+ tensor_properties=self._metadata.tensor_properties,
284
+ )
285
+ self._local_shards.append(Shard(local_tensor, shard_metadata))
286
+
287
+ # do post initialization (i.e. register sharded_tensor_id, initialize_rpc)
288
+ self._post_init()
289
+
290
+ def _prepare_init(self, process_group=None, init_rrefs=False):
291
+ self._init_rrefs = init_rrefs
292
+ self._sharded_tensor_id = None
293
+
294
+ self._process_group = self._normalize_pg(process_group)
295
+ self._remote_shards: dict[int, list[rpc.RRef[Shard]]] = {}
296
+
297
+ def _post_init(self):
298
+ # Initialize RPC if available.
299
+ if self._init_rrefs:
300
+ with _sharded_tensor_lock:
301
+ global _sharded_tensor_current_id, _sharded_tensor_map
302
+ # pyrefly: ignore [bad-assignment]
303
+ self._sharded_tensor_id = _sharded_tensor_current_id
304
+ # pyrefly: ignore [unsupported-operation]
305
+ _sharded_tensor_map[self._sharded_tensor_id] = weakref.ref(self)
306
+ _sharded_tensor_current_id += 1
307
+
308
+ if not rpc._is_current_rpc_agent_set():
309
+ raise RuntimeError(
310
+ "RPC Framework needs to be initialized using"
311
+ " torch.distributed.rpc.init_rpc if init_rrefs is set to True"
312
+ )
313
+ self._init_rpc()
314
+
315
+ def __del__(self):
316
+ # Clean up the global map.
317
+ with _sharded_tensor_lock:
318
+ global _sharded_tensor_current_id, _sharded_tensor_map
319
+ if (
320
+ hasattr(self, "_sharded_tensor_id")
321
+ and self._sharded_tensor_id in _sharded_tensor_map
322
+ ):
323
+ _sharded_tensor_map.pop(self._sharded_tensor_id) # type: ignore[call-overload]
324
+
325
+ def _init_rpc(self):
326
+ # Validate PG and RPC ranks match.
327
+ pg_rank = dist.get_rank()
328
+ rpc_rank = rpc.get_worker_info().id
329
+ if pg_rank != rpc_rank:
330
+ raise ValueError(
331
+ f"Default ProcessGroup and RPC ranks must be "
332
+ f"the same for ShardedTensor, found process group rank: "
333
+ f"{pg_rank} and RPC rank: {rpc_rank}"
334
+ )
335
+
336
+ self._remote_shards = {}
337
+
338
+ # Gather all the sharded tensor ids.
339
+ worker_infos = rpc._get_current_rpc_agent().get_worker_infos()
340
+ rank_to_name = {}
341
+ name_to_rank = {}
342
+
343
+ for worker_info in worker_infos:
344
+ rank_to_name[worker_info.id] = worker_info.name
345
+ name_to_rank[worker_info.name] = worker_info.id
346
+
347
+ all_tensor_ids = rpc.api._all_gather(self._sharded_tensor_id)
348
+
349
+ # Share the local shards to the entire world.
350
+ futs = []
351
+ rpc_rank = rpc.get_worker_info().id
352
+ for rank in range(dist.get_world_size()):
353
+ # Skip self.
354
+ if rank == dist.get_rank():
355
+ continue
356
+
357
+ if len(self.local_shards()) != 0:
358
+ rrefs: list[rpc.RRef[Shard]] = [
359
+ rpc.RRef(shard) for shard in self.local_shards()
360
+ ]
361
+ fut = rpc.rpc_async(
362
+ rank,
363
+ _register_remote_shards,
364
+ args=(all_tensor_ids[rank_to_name[rank]], rrefs, rpc_rank),
365
+ )
366
+ futs.append(fut)
367
+
368
+ torch.futures.wait_all(futs)
369
+
370
+ # Barrier for all RPCs to finish on all ranks.
371
+ rpc.api._all_gather(None)
372
+
373
+ def _get_preferred_device(self) -> torch.device:
374
+ """
375
+ Return the preferred device to be used when creating tensors for collectives.
376
+ This method takes into account the associated process group
377
+ """
378
+ backend = dist.get_backend(self._process_group)
379
+ if backend == dist.Backend.NCCL:
380
+ return torch.device(torch.cuda.current_device())
381
+ elif backend == dist.Backend.GLOO:
382
+ return torch.device("cpu")
383
+ else:
384
+ backend_config = dist.BackendConfig(backend)
385
+ for device, backend_str in backend_config.get_device_backend_map().items():
386
+ if backend_str == backend and device != "cpu":
387
+ return torch.device(
388
+ device, _get_device_module(device).current_device()
389
+ )
390
+ return torch.device("cpu")
391
+
392
+ def gather( # type: ignore[override]
393
+ self,
394
+ dst: int = 0,
395
+ out: torch.Tensor | None = None,
396
+ enforce_dtype: bool = False,
397
+ dtype: torch.dtype | None = None,
398
+ ) -> None:
399
+ """
400
+ Creates a full :class:`Tensor` on rank ``dst`` by gathering all shards of the
401
+ sharded tensor.
402
+
403
+ The API needs to be called on all ranks in SPMD fashion. All ranks should have
404
+ the same ``dst``. ``out`` should be a tensor of the same size as the overall
405
+ size of the sharded tensor on ``dst`` and ``None`` on all other ranks.
406
+
407
+ Args:
408
+ dst(int): The rank where full tensor is constructed.
409
+ Default: 0
410
+ out (:class `torch.Tensor`, optional): The output full tensor.
411
+ Must to be provided ONLY on ``dst`` rank.
412
+ Default: ``None``
413
+ enforce_dtype (bool): Deprecated, please use dtype instead. Force the
414
+ gathered tensors to be the same type as input and output.
415
+ dtype (torch.dtype): Force the gathered tensors to be this dtype.
416
+ Default: ``None``
417
+ """
418
+
419
+ def shard_size(shard_md):
420
+ return reduce(operator.mul, shard_md.shard_sizes) # type: ignore[attr-defined]
421
+
422
+ if enforce_dtype:
423
+ warnings.warn(
424
+ "`enforce_dtype` is deprecated. Please use `dtype` instead.",
425
+ FutureWarning,
426
+ stacklevel=2,
427
+ )
428
+
429
+ rank = dist.get_rank(self._process_group)
430
+ full_size = self.metadata().size
431
+ _validate_output_tensor_for_gather(rank, dst, full_size, out)
432
+
433
+ local_shards = self.local_shards()
434
+ world_size = dist.get_world_size(self._process_group)
435
+ rank_sizes = [0 for _ in range(world_size)]
436
+ max_rank_size = 0
437
+ shard_placement: dict[ShardMetadata, tuple[int, int]] = {}
438
+ # collect sizes
439
+ for shard_md in self.metadata().shards_metadata:
440
+ shard_rank = cast(_remote_device, shard_md.placement).rank()
441
+ assert shard_rank is not None
442
+
443
+ shard_placement[shard_md] = (shard_rank, rank_sizes[shard_rank])
444
+ rank_sizes[shard_rank] += shard_size(shard_md)
445
+ max_rank_size = max(max_rank_size, rank_sizes[shard_rank])
446
+
447
+ gather_list: list[torch.Tensor] | None
448
+ if rank == dst:
449
+ assert out is not None
450
+ if enforce_dtype:
451
+ # enforce_dtype is deprecated. Do it for backward compatibility.
452
+ dtype = out.dtype
453
+ # TODO make it as a view of out tensor
454
+ gather_list = [
455
+ torch.empty((max_rank_size,), device=out.device, dtype=dtype)
456
+ for _ in range(world_size)
457
+ ]
458
+ else:
459
+ gather_list = None
460
+
461
+ with torch.no_grad():
462
+ if enforce_dtype and len(local_shards) > 0:
463
+ # enforce_dtype is deprecated. Do it for backward compatibility.
464
+ dtype = local_shards[0].tensor.dtype
465
+ data = torch.empty(
466
+ max_rank_size, device=self._get_preferred_device(), dtype=dtype
467
+ )
468
+
469
+ for shard in local_shards:
470
+ src = shard.tensor.flatten()
471
+ if src.nelement() == 0:
472
+ warnings.warn(
473
+ "Gathering a tensor with zero elements on rank " + str(rank),
474
+ stacklevel=2,
475
+ )
476
+ continue
477
+ shard_offset = shard_placement[shard.metadata][1]
478
+ data[shard_offset : shard_offset + src.numel()].copy_(src)
479
+
480
+ dist.gather(
481
+ tensor=data,
482
+ gather_list=gather_list,
483
+ dst=dst,
484
+ group=self._process_group,
485
+ )
486
+ if rank != dst:
487
+ return
488
+ # In _validate_output_tensor_for_gather, we raise if out == None and rank == dst
489
+ out = cast(torch.Tensor, out)
490
+ assert gather_list is not None
491
+
492
+ full_size = self.metadata().size
493
+ dims = len(full_size)
494
+ for shard_md in self.metadata().shards_metadata:
495
+ rank, rank_offset = shard_placement[shard_md]
496
+ tensor = gather_list[rank]
497
+ tensor = tensor[rank_offset : rank_offset + shard_size(shard_md)]
498
+ tensor = tensor.view(shard_md.shard_sizes)
499
+
500
+ out_narrow_view = out
501
+ for dim in range(dims):
502
+ out_narrow_view = out_narrow_view.narrow(
503
+ dim,
504
+ shard_md.shard_offsets[dim],
505
+ shard_md.shard_sizes[dim],
506
+ )
507
+
508
+ out_narrow_view.copy_(tensor)
509
+
510
+ def cpu(
511
+ self, memory_format=torch.preserve_format, process_group=None
512
+ ) -> ShardedTensor:
513
+ """
514
+ Returns a copy of this object in CPU memory.
515
+
516
+ If this ShardedTensor is already on CPU memory, then no copy is
517
+ performed and original object is returned.
518
+
519
+ .. note:: When moving a ShardedTensor from GPU to CPU, the ShardedTensor might
520
+ need to be managed by a different type of ProcessGroup(i.e. ProcessGroupGloo),
521
+ it is the user's responsibility to explicitly pass in a new process_group that
522
+ is compatible with CPU.
523
+ """
524
+ # TODO: make this a __torch_function__ op once ShardedTensor becomes a
525
+ # torch.Tensor subclass, see https://github.com/pytorch/pytorch/issues/75402
526
+ if (
527
+ memory_format != torch.preserve_format
528
+ and memory_format != torch.contiguous_format
529
+ ):
530
+ raise RuntimeError(
531
+ "Only `torch.contiguous_format` or "
532
+ "`torch.preserve_format` is supported!"
533
+ )
534
+ all_on_cpu = True
535
+ for meta in self.metadata().shards_metadata:
536
+ all_on_cpu &= meta.placement.device().type == "cpu" # type: ignore[union-attr]
537
+
538
+ # if every shard is already on CPU, return the original object
539
+ if all_on_cpu:
540
+ return self
541
+
542
+ # if not, returns a copy of this object on CPU
543
+ list_shards: list[Shard] = []
544
+ # move all local shards to cpu, and change metadata
545
+ for shard in self._local_shards:
546
+ cpu_tensor = shard.tensor.cpu(memory_format=memory_format) # type: ignore[call-arg]
547
+ metadata = copy.deepcopy(shard.metadata)
548
+ metadata.placement._device = torch.device("cpu") # type: ignore[union-attr]
549
+ list_shards.append(Shard(cpu_tensor, metadata))
550
+
551
+ st_meta = copy.deepcopy(self.metadata())
552
+ for meta in st_meta.shards_metadata:
553
+ if meta.placement.device().type != "cpu": # type: ignore[union-attr]
554
+ meta.placement._device = torch.device("cpu") # type: ignore[union-attr]
555
+
556
+ pg = self._process_group if process_group is None else process_group
557
+ st_cpu = ShardedTensor._init_from_local_shards_and_global_metadata(
558
+ list_shards,
559
+ sharded_tensor_metadata=st_meta,
560
+ process_group=pg,
561
+ init_rrefs=self._init_rrefs,
562
+ )
563
+ return st_cpu
564
+
565
+ def cuda(
566
+ self,
567
+ device=None,
568
+ non_blocking=False,
569
+ memory_format=torch.preserve_format,
570
+ process_group=None,
571
+ ) -> ShardedTensor:
572
+ """
573
+ Returns a copy of this object in CUDA memory, if the original ShardedTensor
574
+ is on CPU, we will move the local shard to the current GPU device of each
575
+ process in a SPMD fashion.
576
+ If this ShardedTensor is already on CUDA memory and local shards on each rank are
577
+ already on current device, we still returns a new ShardedTensor object with new
578
+ metadata, but no underlying data movements are performed.
579
+ .. note:: When moving a ShardedTensor from CPU to GPU, the ShardedTensor might
580
+ need to be managed by a different type of ProcessGroup(i.e. ProcessGroupNCCL),
581
+ it is the user's responsibility to explicitly pass in a new process_group that
582
+ is compatible with GPU.
583
+ """
584
+ if (
585
+ memory_format != torch.preserve_format
586
+ and memory_format != torch.contiguous_format
587
+ ):
588
+ raise RuntimeError(
589
+ "Only `torch.contiguous_format` or "
590
+ "`torch.preserve_format` is supported!"
591
+ )
592
+
593
+ if device is not None:
594
+ device = torch.device(device) if isinstance(device, str) else device
595
+ assert (
596
+ isinstance(device, torch.device)
597
+ and device.index == torch.cuda.current_device()
598
+ ), (
599
+ """Only device without device id (e.g. "cpu" or "cuda") is expected for ShardedTensor!"""
600
+ )
601
+
602
+ current_device = torch.device(torch.cuda.current_device())
603
+ # returns a copy of ShardedTensor on CUDA current device
604
+ list_shards: list[Shard] = []
605
+ # move all local shards to current device, and change metadata
606
+ # if local shards already on the current device, there's no
607
+ # real data movement, only the metadata are copied.
608
+ for shard in self._local_shards:
609
+ cuda_tensor = shard.tensor.cuda(
610
+ device=current_device,
611
+ non_blocking=non_blocking,
612
+ memory_format=memory_format,
613
+ ) # type: ignore[call-arg]
614
+ metadata = copy.deepcopy(shard.metadata)
615
+ metadata.placement._device = current_device # type: ignore[union-attr]
616
+
617
+ list_shards.append(Shard(cuda_tensor, metadata))
618
+
619
+ st_meta = copy.deepcopy(self.metadata())
620
+ for meta in st_meta.shards_metadata:
621
+ if meta.placement.device().type != "cuda": # type: ignore[union-attr]
622
+ meta.placement._device = current_device # type: ignore[union-attr]
623
+
624
+ pg = self._process_group if process_group is None else process_group
625
+ # we need to use `init_from_local_shards` to communicate between ranks
626
+ # and update the sharding spec/shards metadata.
627
+ st_cuda = ShardedTensor._init_from_local_shards_and_global_metadata(
628
+ list_shards,
629
+ sharded_tensor_metadata=st_meta,
630
+ process_group=pg,
631
+ init_rrefs=self._init_rrefs,
632
+ )
633
+ return st_cuda
634
+
635
+ def to(self, *args, **kwargs) -> ShardedTensor:
636
+ current_device: torch.device
637
+ if self._local_shards:
638
+ current_device = self._local_shards[0].tensor.device
639
+ elif self._process_group._get_backend_name() == "gloo":
640
+ current_device = torch.device("cpu")
641
+ else:
642
+ current_device = torch.device(torch.cuda.current_device())
643
+ current_dtype = self.dtype
644
+ device_to = current_device
645
+ dtype_to = current_dtype
646
+ if len(args) == 1:
647
+ if isinstance(args[0], torch.dtype):
648
+ dtype_to = args[0]
649
+ elif isinstance(args[0], torch.device):
650
+ device_to = args[0]
651
+ elif isinstance(args[0], (str, int)):
652
+ device_to = torch.device(args[0])
653
+ elif isinstance(args[0], torch.Tensor):
654
+ dtype_to = args[0].dtype
655
+ device_to = args[0].device
656
+ else:
657
+ raise RuntimeError(f"ShardedTensor.to() have wrong arguments: {args}")
658
+ elif len(args) == 2:
659
+ device_to, dtype_to = args
660
+ else:
661
+ dtype_to = kwargs.get("dtype", current_dtype)
662
+ device_to = kwargs.get("device", current_device)
663
+
664
+ device_to = (
665
+ torch.device(device_to) if isinstance(device_to, (str, int)) else device_to
666
+ )
667
+
668
+ if device_to.type == "cuda":
669
+ # if device_to set to cuda, set to current device even
670
+ # if user specify the device index.
671
+ current_idx = torch.cuda.current_device()
672
+ if device_to.index != current_idx:
673
+ warnings.warn(
674
+ "ShardedTensor.to only move tensor to its current device"
675
+ "If you want to put to different device, use `reshard` instead.",
676
+ stacklevel=2,
677
+ )
678
+ device_to = torch.device(current_idx)
679
+
680
+ copy_tensor = kwargs.get("copy", False)
681
+ non_blocking = kwargs.get("non_blocking", False)
682
+ memory_format = kwargs.get("memory_format", torch.preserve_format)
683
+ process_group = kwargs.get("process_group")
684
+
685
+ if (
686
+ not copy_tensor
687
+ and dtype_to == current_dtype
688
+ and device_to == current_device
689
+ ):
690
+ # already have correct dtype and device, return itself
691
+ return self
692
+
693
+ # returns a copy of ShardedTensor on CUDA current device
694
+ list_shards: list[Shard] = []
695
+
696
+ for shard in self._local_shards:
697
+ new_tensor = shard.tensor.to( # type: ignore[call-overload]
698
+ device=device_to,
699
+ dtype=dtype_to,
700
+ non_blocking=non_blocking,
701
+ copy=copy_tensor,
702
+ memory_format=memory_format,
703
+ )
704
+ metadata = copy.deepcopy(shard.metadata)
705
+ if metadata.placement is not None:
706
+ metadata.placement._device = device_to
707
+ list_shards.append(Shard(new_tensor, metadata))
708
+
709
+ # update metadata
710
+ st_meta = copy.deepcopy(self.metadata())
711
+ st_meta.tensor_properties.dtype = dtype_to
712
+ for meta in st_meta.shards_metadata:
713
+ meta.placement._device = device_to # type: ignore[union-attr]
714
+
715
+ pg = self._process_group if process_group is None else process_group
716
+ # we need to use `init_from_local_shards` to communicate between ranks
717
+ # and update the sharding spec/shards metadata.
718
+ st_to = ShardedTensor._init_from_local_shards_and_global_metadata(
719
+ list_shards,
720
+ sharded_tensor_metadata=st_meta,
721
+ process_group=pg,
722
+ init_rrefs=self._init_rrefs,
723
+ )
724
+ return st_to
725
+
726
+ @classmethod
727
+ def _normalize_pg(
728
+ cls, process_group: dist.ProcessGroup | None
729
+ ) -> dist.ProcessGroup:
730
+ if process_group is not None:
731
+ return process_group
732
+ return distributed_c10d._get_default_group()
733
+
734
+ @classmethod
735
+ def _init_from_local_shards(
736
+ cls,
737
+ local_shards: list[Shard],
738
+ *global_size,
739
+ process_group=None,
740
+ init_rrefs=False,
741
+ ):
742
+ # recalc metadata handles special ST creation cases like each rank only has tensor available
743
+ # caller need to provide None on the unknown dimension of the global size
744
+ # We will change None into zeros and go through the same amount of checks as before to create ST
745
+ # and use all_gather to calculate the offsets and global size for metadata
746
+ # It is compatible with the current use case since, conventionally we don't pass None as global size
747
+ # Therefore the old path won't trigger the new feature
748
+ recalc_metadata = False
749
+ for dim in global_size:
750
+ if dim is None:
751
+ recalc_metadata = True
752
+ if recalc_metadata:
753
+ global_size = tuple(
754
+ 0 if dim_size is None else dim_size for dim_size in global_size
755
+ )
756
+ # STEP 1: Validate the Shardmetadatas locally
757
+ process_group = cls._normalize_pg(process_group)
758
+ current_rank = dist.get_rank() # intentional to get global rank
759
+ world_size = dist.get_world_size(process_group)
760
+
761
+ local_sharded_tensor_metadata: ShardedTensorMetadata | None = None
762
+ global_tensor_size = _flatten_tensor_size(global_size)
763
+
764
+ if len(local_shards) > 0:
765
+ local_sharded_tensor_metadata = build_metadata_from_local_shards(
766
+ local_shards, global_tensor_size, current_rank, process_group
767
+ )
768
+
769
+ # STEP 2. Validate metadata across ranks, and build a global sharded tensor
770
+ # metadata by gathering local ShardedTensorMetadata
771
+ gathered_metadatas: list[ShardedTensorMetadata | None] = []
772
+ if world_size > 1:
773
+ gathered_metadatas = [None for _ in range(world_size)]
774
+
775
+ dist.all_gather_object(
776
+ gathered_metadatas, local_sharded_tensor_metadata, group=process_group
777
+ )
778
+ else:
779
+ gathered_metadatas = [local_sharded_tensor_metadata]
780
+
781
+ global_sharded_tensor_metadata = build_global_metadata(
782
+ gathered_metadatas, recalc_metadata=recalc_metadata
783
+ )
784
+ if recalc_metadata:
785
+ # for recalc use cases, we only support rw for now, limit the blast radius
786
+ # will modify here once we support more sharding type
787
+ assert (
788
+ len(local_shards) > 0
789
+ and len(global_sharded_tensor_metadata.shards_metadata) > current_rank
790
+ ), (
791
+ f"# for metadata recalculation, local_shards must be larger than 0 "
792
+ f"actual:{len(local_shards)}, # glb metadata must be greater than any rank id, "
793
+ f"# metadata:{len(global_sharded_tensor_metadata.shards_metadata)}, rank id:{current_rank}"
794
+ )
795
+ local_md = [
796
+ shard_md
797
+ for shard_md in global_sharded_tensor_metadata.shards_metadata
798
+ if shard_md.placement.rank() == current_rank
799
+ ]
800
+ assert len(local_md) == 1, (
801
+ f"should has and only has one metadata for local rank, actual:{local_md}"
802
+ )
803
+ local_shards[0].metadata = local_md[0]
804
+ tensor_properties = global_sharded_tensor_metadata.tensor_properties
805
+
806
+ # STEP 3: Validation done, create the actual ShardedTensor and populate fields
807
+ # prepare initialization
808
+ spec = shard_spec._infer_sharding_spec_from_shards_metadata(
809
+ global_sharded_tensor_metadata.shards_metadata
810
+ )
811
+ sharded_tensor = cls.__new__(
812
+ cls,
813
+ spec,
814
+ global_sharded_tensor_metadata.size,
815
+ dtype=tensor_properties.dtype,
816
+ layout=tensor_properties.layout,
817
+ pin_memory=tensor_properties.pin_memory,
818
+ requires_grad=tensor_properties.requires_grad,
819
+ )
820
+ sharded_tensor._prepare_init(process_group=process_group, init_rrefs=init_rrefs)
821
+
822
+ # attach local_shards to the ShardedTensor created
823
+ sharded_tensor._local_shards = local_shards
824
+
825
+ # run post initialization, i.e. map registration, rpc initialization
826
+ sharded_tensor._post_init()
827
+ return sharded_tensor
828
+
829
+ @classmethod
830
+ @deprecated(DEPRECATE_MSG, category=FutureWarning)
831
+ def _init_from_local_tensor(
832
+ cls,
833
+ local_tensor: torch.Tensor,
834
+ sharding_spec: shard_spec.ShardingSpec,
835
+ *global_size: Sequence[int],
836
+ process_group: dist.ProcessGroup | None = None,
837
+ init_rrefs=False,
838
+ ) -> ShardedTensor:
839
+ """
840
+ Initialize a ShardedTensor given only one local tensor, global sharded tensor
841
+ size and sharding spec on each rank.
842
+
843
+ Args:
844
+ local_tensor (Tensor): Single tensor of local shard stored in each rank.
845
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`):
846
+ The specification describing how to shard the Tensor.
847
+ global_size (Sequence[int]): Size of the sharded tensor.
848
+ process_group (ProcessGroup, optional): The process group to aggregate on.
849
+ Default: None
850
+ init_rrefs (bool, optional): Whether or not to initialize
851
+ :class:`torch.distributed.rpc.RRef`s pointing to remote shards.
852
+ Need to initialize the RPC Framework if specified as ``True``.
853
+ Default: ``False``.
854
+
855
+ Returns:
856
+ A :class:`ShardedTensor` sharded based on the given sharding_spec with local
857
+ tensor stored in the current rank.
858
+
859
+ Examples:
860
+ >>> # xdoctest: +SKIP
861
+ >>> # All tensors below are of torch.int64 type.
862
+ >>> # We have 2 process groups, 2 ranks.
863
+ >>> tensor = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank
864
+ >>> local_tensor = torch.unsqueeze(torch.cat([tensor, tensor + 2]))
865
+ >>> local_tensor
866
+ tensor([[1, 2, 3, 4]]) # Rank 0
867
+ tensor([[3, 4, 5, 6]]) # Rank 1
868
+ >>> sharding_dim = 0
869
+ >>> sharding_spec = ChunkShardingSpec(
870
+ dim=sharding_dim,
871
+ placements=[
872
+ "rank:0/cuda:0",
873
+ "rank:1/cuda:1",
874
+ ],
875
+ )
876
+ >>> st = ShardedTensor._init_from_local_tensor(
877
+ ... local_tensor, sharding_spec, [2, 4]
878
+ ... )
879
+ >>> st
880
+ ShardedTensor(
881
+ ShardedTensorMetadata(
882
+ shards_metadata=[
883
+ ShardMetadata(shard_offsets=[0, 0], shard_sizes=[1, 4], placement=rank:0/cuda:0),
884
+ ShardMetadata(shard_offsets=[1, 0], shard_sizes=[1, 4], placement=rank:1/cuda:1),
885
+ ],
886
+ size=torch.Size([2, 4])
887
+ )
888
+ >>> st.local_tensor()
889
+ tensor([1, 2, 3, 4]) # Rank 0
890
+ tensor([3, 4, 5, 6]) # Rank 1
891
+
892
+ Warning: This API is experimental and subject to change. It lacks of a fully across
893
+ rank validations, and we only validate the local shard on the current rank.
894
+ We fully rely on the user to ensure local tensor is sharded based on the
895
+ sharding spec.
896
+ """
897
+ if not local_tensor.is_contiguous():
898
+ raise ValueError("local_tensor is not a contiguous Tensor.")
899
+
900
+ global_tensor_size = _flatten_tensor_size(global_size)
901
+ tensor_properties = TensorProperties(
902
+ dtype=local_tensor.dtype,
903
+ layout=local_tensor.layout,
904
+ requires_grad=local_tensor.requires_grad,
905
+ memory_format=torch.contiguous_format,
906
+ pin_memory=local_tensor.is_pinned(),
907
+ )
908
+ sharded_tensor_metadata = sharding_spec.build_metadata(
909
+ global_tensor_size, tensor_properties
910
+ )
911
+
912
+ process_group = cls._normalize_pg(process_group)
913
+ current_rank = dist.get_rank() # intentional to get global rank
914
+
915
+ local_shards: list[Shard] = []
916
+ for shard_metadata in sharded_tensor_metadata.shards_metadata:
917
+ rank, _device = _parse_and_validate_remote_device(
918
+ process_group, shard_metadata.placement
919
+ )
920
+ if rank == current_rank:
921
+ local_shards.append(Shard(local_tensor, shard_metadata))
922
+
923
+ # TODO: figure out what the API should behave when some rank have no shard
924
+ # see https://github.com/pytorch/pytorch/issues/7313
925
+ return ShardedTensor._init_from_local_shards_and_global_metadata(
926
+ local_shards,
927
+ sharded_tensor_metadata,
928
+ process_group=process_group,
929
+ init_rrefs=init_rrefs,
930
+ sharding_spec=sharding_spec,
931
+ )
932
+
933
+ @classmethod
934
+ def _init_from_local_shards_and_global_metadata( # type: ignore[override]
935
+ cls,
936
+ local_shards: list[Shard],
937
+ sharded_tensor_metadata: ShardedTensorMetadata,
938
+ process_group=None,
939
+ init_rrefs=False,
940
+ sharding_spec=None,
941
+ ) -> ShardedTensor:
942
+ """
943
+ Initialize a ShardedTensor with local shards and a global
944
+ ShardedTensorMetadata built on each rank.
945
+
946
+ Warning: This API is experimental and subject to change. It does
947
+ not do cross rank validations, and fully rely on the user
948
+ for the correctness of sharded_tensor_metadata on each rank
949
+ """
950
+ process_group = cls._normalize_pg(process_group)
951
+ current_rank = dist.get_rank() # intentional to get global rank
952
+
953
+ shards_metadata = sharded_tensor_metadata.shards_metadata
954
+
955
+ local_shard_metadatas = []
956
+
957
+ # collect local shard metadatas from the global sharded_tensor_metadata
958
+ for shard_metadata in shards_metadata: # type: ignore[attr-defined]
959
+ rank, local_device = _parse_and_validate_remote_device(
960
+ process_group, shard_metadata.placement
961
+ )
962
+
963
+ if current_rank == rank:
964
+ local_shard_metadatas.append(shard_metadata)
965
+
966
+ if len(local_shards) != len(local_shard_metadatas):
967
+ raise RuntimeError(
968
+ f"Number of local shards ({len(local_shards)}) does not match number of local "
969
+ f"shards metadata in sharded_tensor_metadata ({len(local_shard_metadatas)}) "
970
+ f"on rank ({current_rank}) "
971
+ )
972
+
973
+ shards_metadata = sharded_tensor_metadata.shards_metadata
974
+ tensor_properties = sharded_tensor_metadata.tensor_properties
975
+
976
+ if len(shards_metadata) == 0:
977
+ raise ValueError("shards_metadata must not be empty!")
978
+
979
+ if tensor_properties.layout != torch.strided:
980
+ raise ValueError("Only torch.strided layout is currently supported")
981
+
982
+ if sharding_spec is None:
983
+ spec = shard_spec._infer_sharding_spec_from_shards_metadata(shards_metadata)
984
+ else:
985
+ spec = sharding_spec
986
+
987
+ sharded_tensor = ShardedTensor.__new__(
988
+ ShardedTensor,
989
+ spec,
990
+ sharded_tensor_metadata.size,
991
+ dtype=tensor_properties.dtype,
992
+ layout=tensor_properties.layout,
993
+ pin_memory=tensor_properties.pin_memory,
994
+ requires_grad=tensor_properties.requires_grad,
995
+ )
996
+
997
+ def _raise_if_mismatch(expected, actual, prop_name, rank, is_property=False):
998
+ tensor_property_or_metadata = (
999
+ "tensor property" if is_property else "local ShardMetadata"
1000
+ )
1001
+ if expected != actual:
1002
+ raise ValueError(
1003
+ f"Local shards' tensor {prop_name} property is incompatible with "
1004
+ f"{tensor_property_or_metadata} on rank {rank}: "
1005
+ f"{tensor_property_or_metadata} {prop_name}={expected}, "
1006
+ f"local shard tensor {prop_name}={actual}."
1007
+ )
1008
+
1009
+ for shard in local_shards:
1010
+ shard_meta = shard.metadata
1011
+ local_shard_tensor = shard.tensor
1012
+ placement = shard_meta.placement
1013
+ assert placement is not None, "Must specify placement for `Shard`!"
1014
+ rank = placement.rank()
1015
+ local_device = placement.device()
1016
+
1017
+ _raise_if_mismatch(
1018
+ tensor_properties.layout,
1019
+ local_shard_tensor.layout,
1020
+ "layout",
1021
+ rank,
1022
+ True,
1023
+ )
1024
+ if not local_shard_tensor.is_contiguous():
1025
+ raise ValueError(
1026
+ "Only torch.contiguous_format memory_format is currently supported"
1027
+ )
1028
+
1029
+ _raise_if_mismatch(
1030
+ shard_meta.shard_sizes,
1031
+ list(local_shard_tensor.size()),
1032
+ "size",
1033
+ rank,
1034
+ )
1035
+ _raise_if_mismatch(
1036
+ tensor_properties.pin_memory,
1037
+ local_shard_tensor.is_pinned(),
1038
+ "pin_memory",
1039
+ rank,
1040
+ True,
1041
+ )
1042
+ _raise_if_mismatch(local_device, local_shard_tensor.device, "device", rank)
1043
+ _raise_if_mismatch(
1044
+ tensor_properties.dtype,
1045
+ local_shard_tensor.dtype,
1046
+ "dtype",
1047
+ rank,
1048
+ True,
1049
+ )
1050
+ _raise_if_mismatch(
1051
+ tensor_properties.requires_grad,
1052
+ local_shard_tensor.requires_grad,
1053
+ "requires_grad",
1054
+ rank,
1055
+ True,
1056
+ )
1057
+
1058
+ # check if shards_metadata have overlap shards
1059
+ validate_non_overlapping_shards_metadata(shards_metadata)
1060
+
1061
+ # check if the shards_metadata is compatible with overall size of the sharded tensor.
1062
+ check_tensor(shards_metadata, list(sharded_tensor_metadata.size))
1063
+
1064
+ # done validation, add local_shards
1065
+ sharded_tensor._local_shards = local_shards
1066
+ sharded_tensor._prepare_init(process_group=process_group, init_rrefs=init_rrefs)
1067
+
1068
+ # run post initialization, i.e. map registration, rpc initialization
1069
+ sharded_tensor._post_init()
1070
+ return sharded_tensor
1071
+
1072
+ def sharding_spec(self) -> shard_spec.ShardingSpec:
1073
+ """
1074
+ Returns the ShardingSpec for the tensor.
1075
+ """
1076
+ return self._sharding_spec
1077
+
1078
+ @deprecated(DEPRECATE_MSG, category=FutureWarning)
1079
+ def reshard(self, resharding_spec: shard_spec.ShardingSpec) -> ShardedTensor:
1080
+ """
1081
+ Reshard a sharded tensor given the ``resharding_spec``. For now, we only support
1082
+ single local shard.
1083
+
1084
+ If ``resharding_spec`` is same as the original one, this becomes a no-op.
1085
+ If only ``resharding_spec`` shares the same sharding dim with the original one,
1086
+ we swap local shards directly.
1087
+ For more generic cases, we merge different shards across different ranks and split
1088
+ the local shards based on the ``resharding_spec`` via `all_to_all` collective API.
1089
+
1090
+ Args:
1091
+ resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
1092
+ specification describing how the tensor is sharded.
1093
+
1094
+ Returns:
1095
+ A :class:`ShardedTensor` object whose local shards are resharded.
1096
+
1097
+ Examples:
1098
+ >>> # xdoctest: +SKIP
1099
+ >>> # We have 2 process groups, 2 ranks.
1100
+ >>> tensor = torch.arange(4, dtype=torch.int64) + 1 + 2 * rank
1101
+ >>> tensor = torch.stack([tensor, tensor])
1102
+ >>> tensor
1103
+ tensor([[1, 2, 3, 4], [1, 2, 3, 4]]) # Rank 0
1104
+ tensor([[3, 4, 5, 6], [3, 4, 5, 6]]) # Rank 1
1105
+ tensor([[5, 6, 7, 8], [5, 6, 7, 8]]) # Rank 2
1106
+ tensor([[7, 8, 9, 10], [7, 8, 9, 10]]) # Rank 3
1107
+ >>> sharding_dim = 0
1108
+ >>> spec = ChunkShardingSpec(
1109
+ dim=sharding_dim,
1110
+ placements=[
1111
+ "rank:0/cuda:0",
1112
+ "rank:1/cuda:1",
1113
+ "rank:2/cuda:2",
1114
+ "rank:3/cuda:3",
1115
+ ],
1116
+ )
1117
+ >>> current_offsets = [0] * 2
1118
+ >>> current_offsets[0] = rank * 2
1119
+ >>> shard_metadata = ShardMetadata(
1120
+ shard_offsets=copy.deepcopy(current_offsets),
1121
+ shard_sizes=tensor.size(),
1122
+ placement=spec.placements[rank],
1123
+ )
1124
+ >>> local_shards = [
1125
+ Shard(
1126
+ tensor=tensor,
1127
+ metadata=shard_metadata,
1128
+ )
1129
+ ]
1130
+ >>> st = ShardedTensor._init_from_local_shards(local_shards, tensor.size())
1131
+ >>> sharding_dim = 1
1132
+ >>> resharding_spec = ChunkShardingSpec(
1133
+ dim=sharding_dim,
1134
+ placements=[
1135
+ "rank:0/cuda:0",
1136
+ "rank:1/cuda:1",
1137
+ "rank:2/cuda:2",
1138
+ "rank:3/cuda:3",
1139
+ ],
1140
+ )
1141
+ >>> st.reshard(resharding_spec)
1142
+ >>> tensor = st.local_shards()[0].tensor
1143
+ >>> tensor
1144
+ tensor([[1], [1], [3], [3], [5], [5], [7], [7]]) # Rank 0
1145
+ tensor([[2], [2], [4], [4], [6], [6], [8], [8]]) # Rank 1
1146
+ tensor([[3], [3], [5], [5], [7], [7], [9], [9]]) # Rank 2
1147
+ tensor([[4], [4], [6], [6], [8], [8], [10], [10]]) # Rank 3
1148
+ """
1149
+ if not isinstance(
1150
+ resharding_spec, shard_spec.ChunkShardingSpec
1151
+ ) or not isinstance(self._sharding_spec, shard_spec.ChunkShardingSpec):
1152
+ raise NotImplementedError("Only ChunkShardingSpec supported for reshard.")
1153
+
1154
+ num_local_shards = len(self.local_shards())
1155
+ if num_local_shards != 1:
1156
+ raise NotImplementedError(
1157
+ f"Only single local shard supported for reshard. Number of shards: {num_local_shards}"
1158
+ )
1159
+
1160
+ if self._sharding_spec.dim == resharding_spec.dim: # type: ignore[attr-defined]
1161
+ if self._sharding_spec.placements == resharding_spec.placements: # type: ignore[attr-defined]
1162
+ return self
1163
+ else:
1164
+ local_shards, shards_metadata = reshuffle_local_shard(
1165
+ self.local_tensor(),
1166
+ self.size(), # type: ignore[arg-type]
1167
+ self._sharding_spec,
1168
+ resharding_spec,
1169
+ self._process_group,
1170
+ )
1171
+ else:
1172
+ local_shards, shards_metadata = reshard_local_shard(
1173
+ self.local_tensor(),
1174
+ self.size(), # type: ignore[arg-type]
1175
+ self._sharding_spec,
1176
+ resharding_spec,
1177
+ self._process_group,
1178
+ )
1179
+ self._local_shards = local_shards
1180
+ self._metadata.shards_metadata = shards_metadata
1181
+ self._sharding_spec = resharding_spec
1182
+ return self
1183
+
1184
+ def local_tensor(self) -> torch.Tensor:
1185
+ """
1186
+ Return local tensor for a sharded_tensor. For now we only support single local shard.
1187
+
1188
+ Returns:
1189
+ A :class:`torch.Tensor` of the local shard.
1190
+ """
1191
+ num_local_shards = len(self.local_shards())
1192
+ if num_local_shards != 1:
1193
+ raise NotImplementedError(
1194
+ f"Only single local shard is supported. Number of shards: {num_local_shards}"
1195
+ )
1196
+ return self.local_shards()[0].tensor
1197
+
1198
+ @classmethod
1199
+ @deprecated(DEPRECATE_MSG, category=FutureWarning)
1200
+ def __torch_function__(cls, func, types, args=(), kwargs=None):
1201
+ def dispatch(st: ShardedTensor, func: Callable):
1202
+ # Dispatch to custom user provided op first if it exists.
1203
+ if func in _CUSTOM_SHARDED_OPS:
1204
+ return _CUSTOM_SHARDED_OPS[func](types, args, kwargs, st._process_group)
1205
+
1206
+ # Dispatch to custom sharding spec op if it has one.
1207
+ if _has_custom_op(st._sharding_spec, func):
1208
+ return _dispatch_custom_op(
1209
+ st._sharding_spec, func, types, args, kwargs, st._process_group
1210
+ )
1211
+
1212
+ if func in _SHARDED_OPS:
1213
+ return _SHARDED_OPS[func](types, args, kwargs, st._process_group)
1214
+
1215
+ raise RuntimeError(
1216
+ f"torch function '{func.__name__}', with args: {args} and "
1217
+ f"kwargs: {kwargs} not supported for ShardedTensor!"
1218
+ )
1219
+
1220
+ # Find ShardedTensor instance to get process_group and sharding_spec.
1221
+ st_instance = None
1222
+
1223
+ def find_sharded_tensor(e):
1224
+ nonlocal st_instance
1225
+ if st_instance is None and isinstance(e, ShardedTensor):
1226
+ st_instance = e
1227
+
1228
+ pytree.tree_map_(find_sharded_tensor, args)
1229
+ pytree.tree_map_(find_sharded_tensor, kwargs)
1230
+
1231
+ if st_instance is not None:
1232
+ return dispatch(st_instance, func)
1233
+
1234
+ raise RuntimeError(
1235
+ f"torch function '{func.__name__}', with args: {args} and "
1236
+ f"kwargs: {kwargs} not supported for ShardedTensor!"
1237
+ )
1238
+
1239
+ def is_pinned(self) -> bool: # type: ignore[override]
1240
+ """
1241
+ Returns True if the sharded tensor (each local shard) resides in pinned memory.
1242
+ """
1243
+ return self._metadata.tensor_properties.pin_memory
1244
+
1245
+ def _register_remote_shards(
1246
+ self, remote_shards: list[rpc.RRef[Shard]], rpc_rank: int
1247
+ ):
1248
+ self._remote_shards[rpc_rank] = remote_shards
1249
+
1250
+ def remote_shards(self) -> dict[int, list[rpc.RRef[Shard]]]:
1251
+ """
1252
+ Returns a Dict[int, RRef] with keys being the RPC rank and values
1253
+ being RRefs to shards on that rank. Need to initialize the
1254
+ RPC framework for this functionality.
1255
+
1256
+ Raises an exception if ShardedTensor was created with ``init_rrefs=False``
1257
+ """
1258
+ if not self._init_rrefs:
1259
+ raise RuntimeError(
1260
+ "ShardedTensor created with init_rrefs=False, no RRefs to remote shards available"
1261
+ )
1262
+ return self._remote_shards
1263
+
1264
+ def __hash__(self):
1265
+ return id(self)
1266
+
1267
+ def __repr__(self) -> str: # type: ignore[override]
1268
+ return f"ShardedTensor({self._metadata})"
1269
+
1270
+ @dataclass
1271
+ class ProcessGroupState:
1272
+ """
1273
+ State for ser-de of process group
1274
+ """
1275
+
1276
+ local_rank: int
1277
+ global_rank: int
1278
+ local_world_size: int
1279
+ global_world_size: int
1280
+
1281
+ def __getstate__(self):
1282
+ pg_state = ShardedTensor.ProcessGroupState(
1283
+ distributed_c10d.get_rank(self._process_group),
1284
+ distributed_c10d.get_rank(),
1285
+ distributed_c10d.get_world_size(self._process_group),
1286
+ distributed_c10d.get_world_size(),
1287
+ )
1288
+
1289
+ return (
1290
+ self._local_shards,
1291
+ self._metadata,
1292
+ pg_state,
1293
+ self._sharding_spec,
1294
+ self._init_rrefs,
1295
+ )
1296
+
1297
+ def __setstate__(self, state):
1298
+ self._sharded_tensor_id = None
1299
+ if not distributed_c10d.is_initialized():
1300
+ raise RuntimeError(
1301
+ "Need to initialize default process group using "
1302
+ '"init_process_group" before loading ShardedTensor'
1303
+ )
1304
+
1305
+ (
1306
+ self._local_shards,
1307
+ self._metadata,
1308
+ pg_state,
1309
+ self._sharding_spec,
1310
+ self._init_rrefs,
1311
+ ) = state
1312
+
1313
+ # Setup process group
1314
+ from torch.distributed._shard.api import _get_current_process_group
1315
+
1316
+ self._process_group = _get_current_process_group()
1317
+
1318
+ # Validate process group.
1319
+ local_rank = distributed_c10d.get_rank(self._process_group)
1320
+ if pg_state.local_rank != local_rank:
1321
+ raise RuntimeError(
1322
+ f"Local rank at save time was {pg_state.local_rank}, but at "
1323
+ f"load time was {local_rank}"
1324
+ )
1325
+
1326
+ global_rank = distributed_c10d.get_rank()
1327
+ if pg_state.global_rank != global_rank:
1328
+ raise RuntimeError(
1329
+ f"Global rank at save time was {pg_state.global_rank}, but at "
1330
+ f"load time was {global_rank}"
1331
+ )
1332
+
1333
+ local_world_size = distributed_c10d.get_world_size(self._process_group)
1334
+ if pg_state.local_world_size != local_world_size:
1335
+ raise RuntimeError(
1336
+ f"Local world size at save time was {pg_state.local_world_size}, "
1337
+ f"but at load time was {local_world_size}"
1338
+ )
1339
+
1340
+ global_world_size = distributed_c10d.get_world_size()
1341
+ if pg_state.global_world_size != global_world_size:
1342
+ raise RuntimeError(
1343
+ f"Global world size at save time was {pg_state.global_world_size}, "
1344
+ f"but at load time was {global_world_size}"
1345
+ )
1346
+
1347
+ self._post_init()
1348
+
1349
+
1350
+ def _create_tensor_from_params(
1351
+ *size, local_device, tensor_properties: TensorProperties
1352
+ ):
1353
+ """Helper to construct tensor from size, device and common params."""
1354
+ dtype = tensor_properties.dtype
1355
+ layout = tensor_properties.layout
1356
+ requires_grad = tensor_properties.requires_grad
1357
+ memory_format = tensor_properties.memory_format
1358
+ pin_memory = tensor_properties.pin_memory
1359
+
1360
+ return torch.empty(
1361
+ *size,
1362
+ dtype=dtype,
1363
+ layout=layout,
1364
+ device=local_device,
1365
+ requires_grad=requires_grad,
1366
+ memory_format=memory_format,
1367
+ pin_memory=pin_memory,
1368
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/logger.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) Facebook, Inc. and its affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ import logging
10
+
11
+ from torch.distributed._shard.sharded_tensor.logging_handlers import _log_handlers
12
+
13
+
14
+ __all__: list[str] = []
15
+
16
+
17
+ def _get_or_create_logger() -> logging.Logger:
18
+ logging_handler, log_handler_name = _get_logging_handler()
19
+ logger = logging.getLogger(f"sharding-spec-{log_handler_name}")
20
+ logger.setLevel(logging.DEBUG)
21
+ formatter = logging.Formatter(
22
+ "%(asctime)s %(filename)s:%(lineno)s %(levelname)s p:%(processName)s t:%(threadName)s: %(message)s"
23
+ )
24
+ logging_handler.setFormatter(formatter)
25
+ logger.propagate = False
26
+ logger.addHandler(logging_handler)
27
+ return logger
28
+
29
+
30
+ def _get_logging_handler(
31
+ destination: str = "default",
32
+ ) -> tuple[logging.Handler, str]:
33
+ log_handler = _log_handlers[destination]
34
+ log_handler_name = type(log_handler).__name__
35
+ return (log_handler, log_handler_name)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/logging_handlers.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) Facebook, Inc. and its affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ import logging
10
+
11
+
12
+ __all__: list[str] = []
13
+
14
+ _log_handlers: dict[str, logging.Handler] = {
15
+ "default": logging.NullHandler(),
16
+ }
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/metadata.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from dataclasses import dataclass, field
3
+ from enum import Enum
4
+
5
+ import torch
6
+ from torch.distributed._shard.metadata import ShardMetadata
7
+
8
+
9
+ class MEM_FORMAT_ENCODING(Enum):
10
+ TORCH_CONTIGUOUS_FORMAT = 0
11
+ TORCH_CHANNELS_LAST = 1
12
+ TORCH_PRESERVE_FORMAT = 2
13
+
14
+
15
+ @dataclass
16
+ class TensorProperties:
17
+ """Properties used to create :class:`Tensor`"""
18
+
19
+ # Regular tensor fields
20
+ dtype: torch.dtype = field(default=torch.get_default_dtype())
21
+ layout: torch.layout = field(default=torch.strided)
22
+ requires_grad: bool = False
23
+ memory_format: torch.memory_format = field(default=torch.contiguous_format)
24
+ pin_memory: bool = False
25
+
26
+ def __getstate__(self):
27
+ # Since torch.memory_format cannot be pickled!
28
+ memory_format = self.memory_format
29
+ if memory_format == torch.contiguous_format:
30
+ mem_format_encoding = MEM_FORMAT_ENCODING.TORCH_CONTIGUOUS_FORMAT
31
+ elif memory_format == torch.channels_last:
32
+ mem_format_encoding = MEM_FORMAT_ENCODING.TORCH_CHANNELS_LAST
33
+ elif memory_format == torch.preserve_format:
34
+ mem_format_encoding = MEM_FORMAT_ENCODING.TORCH_PRESERVE_FORMAT
35
+ else:
36
+ raise RuntimeError(f"Invalid torch.memory_format: {memory_format}")
37
+
38
+ return (
39
+ self.dtype,
40
+ self.layout,
41
+ self.requires_grad,
42
+ mem_format_encoding,
43
+ self.pin_memory,
44
+ )
45
+
46
+ def __setstate__(
47
+ self,
48
+ state,
49
+ ):
50
+ (
51
+ self.dtype,
52
+ self.layout,
53
+ self.requires_grad,
54
+ mem_format_encoding,
55
+ self.pin_memory,
56
+ ) = state
57
+
58
+ if mem_format_encoding == MEM_FORMAT_ENCODING.TORCH_CONTIGUOUS_FORMAT:
59
+ memory_format = torch.contiguous_format
60
+ elif mem_format_encoding == MEM_FORMAT_ENCODING.TORCH_CHANNELS_LAST:
61
+ memory_format = torch.channels_last
62
+ elif mem_format_encoding == MEM_FORMAT_ENCODING.TORCH_PRESERVE_FORMAT:
63
+ memory_format = torch.preserve_format
64
+ else:
65
+ raise RuntimeError(
66
+ f"Invalid torch.memory_format encoding: {mem_format_encoding}"
67
+ )
68
+
69
+ self.memory_format = memory_format
70
+
71
+ @staticmethod
72
+ def create_from_tensor(tensor: torch.Tensor) -> "TensorProperties":
73
+ return TensorProperties(
74
+ dtype=tensor.dtype,
75
+ layout=tensor.layout,
76
+ requires_grad=tensor.requires_grad,
77
+ memory_format=torch.contiguous_format,
78
+ pin_memory=tensor.is_pinned(),
79
+ )
80
+
81
+
82
+ @dataclass
83
+ class ShardedTensorMetadata:
84
+ """
85
+ Represents metadata for :class:`ShardedTensor`
86
+ """
87
+
88
+ # Metadata about each shard of the Tensor
89
+ shards_metadata: list[ShardMetadata] = field(default_factory=list)
90
+
91
+ # Size of each dim of the overall Tensor.
92
+ size: torch.Size = field(default=torch.Size([]))
93
+
94
+ tensor_properties: TensorProperties = field(default_factory=TensorProperties)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/reshard.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+
4
+ import torch
5
+ import torch.distributed as dist
6
+ import torch.distributed._shard.sharding_spec as shard_spec
7
+ from torch._C._distributed_c10d import ProcessGroup
8
+ from torch.distributed._shard.metadata import ShardMetadata
9
+ from torch.distributed._shard.sharding_spec._internals import (
10
+ get_chunked_dim_size,
11
+ get_split_size,
12
+ )
13
+ from torch.distributed.nn.functional import all_to_all, all_to_all_single
14
+
15
+ from .shard import Shard
16
+
17
+
18
+ def get_idx_from_placements(placements, current_rank) -> int:
19
+ """
20
+ Return the position of the current rank in the given placements.
21
+
22
+ Args:
23
+ placements(List[Union[_remote_device, str]]):
24
+ Specifies the placement of each shard of the Tensor. The size of
25
+ the list represents the number of shards to be created. This could
26
+ be a list of
27
+ :class:`torch.distributed._remote_device`'s. This list
28
+ could also contain a string which represents remote
29
+ device as accepted by
30
+ :class:`torch.distributed._remote_device`
31
+ current_rank (int): number of current device.
32
+
33
+ Returns:
34
+ A int which contains the position of current device in the placement list.
35
+ """
36
+ for idx, placement in enumerate(placements): # type: ignore[attr-defined]
37
+ if current_rank == placement.rank(): # type: ignore[union-attr]
38
+ return idx
39
+ raise RuntimeError("current_rank not in the placement.")
40
+
41
+
42
+ def build_reshard_metadata(
43
+ st_size: torch.Size,
44
+ sharding_spec: shard_spec.ShardingSpec,
45
+ world_size: int,
46
+ ) -> tuple[list[ShardMetadata], list[int]]:
47
+ """
48
+ Based the given sharding spec, we calculate the offset and local shard size.
49
+ We then build a ShardMetadata on top of the calculation result.
50
+
51
+ Args:
52
+ st_size (torch.Size): The size of the sharded tensor.
53
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
54
+ specification describing how the tensor is sharded.
55
+ world_size (int): number of ranks.
56
+
57
+ Returns:
58
+ A Tuple of the followings:
59
+ A List[`ShardMetadata`] which contains the metadata for the shard, including
60
+ offsets, lengths and device placement.
61
+ A List[int] which contains the ranks in the order of placement.
62
+ """
63
+ shard_dim = int(sharding_spec.dim) # type: ignore[attr-defined]
64
+ shards_metadata = [None] * world_size
65
+ ranks = []
66
+ offsets = [0] * len(st_size)
67
+ split_size = get_split_size(st_size[shard_dim], world_size)
68
+ for idx, placement in enumerate(sharding_spec.placements): # type: ignore[attr-defined]
69
+ ranks.append(placement.rank())
70
+ sharded_dim_size = get_chunked_dim_size(st_size[shard_dim], split_size, idx)
71
+ local_tensor_size = list(st_size)
72
+ local_tensor_size[shard_dim] = sharded_dim_size
73
+ shards_metadata[placement.rank()] = ShardMetadata( # type: ignore[call-overload]
74
+ shard_offsets=copy.deepcopy(offsets),
75
+ shard_sizes=local_tensor_size,
76
+ placement=placement,
77
+ )
78
+ offsets[shard_dim] += sharded_dim_size
79
+ return shards_metadata, ranks # type: ignore[return-value]
80
+
81
+
82
+ def reshuffle_local_shard(
83
+ local_shard: torch.Tensor,
84
+ st_size: torch.Size,
85
+ sharding_spec: shard_spec.ShardingSpec,
86
+ resharding_spec: shard_spec.ShardingSpec,
87
+ pg: ProcessGroup,
88
+ ) -> tuple[list[Shard], list[ShardMetadata]]:
89
+ """
90
+ Reshuffle the local shard directly when the reshard dim is same as the original
91
+ sharding dim. Logically we do this in two step:
92
+ 1. To collect all shards based on original sharding spec.
93
+ 2. Reshard the tensor based on the given resharding spec.
94
+
95
+ In reality, we consolidate the two steps into one by sending the local tensor to
96
+ the new shard directly based on the resharding spec.
97
+
98
+ Args:
99
+ local_shard (Tensor): Local tensor stored in the current rank.
100
+ st_size (torch.Size): The size of the sharded tensor.
101
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
102
+ specification describing how the tensor is sharded originally.
103
+ resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
104
+ specification describing how the tensor will be resharded.
105
+ pg (ProcessGroup): The process group to aggregate on.
106
+
107
+ Returns:
108
+ A Tuple of the followings:
109
+ A List[`Shard`] which contains the local tensor and its metadata.
110
+ A List[`ShardMetadata`] which contains the metadata for the shard, including
111
+ offsets, lengths and device placement.
112
+ """
113
+ current_rank = dist.get_rank(pg)
114
+ world_size = dist.get_world_size(pg)
115
+ # Build shards_metadata first.
116
+ shards_metadata, ranks = build_reshard_metadata(
117
+ st_size, resharding_spec, world_size
118
+ )
119
+ # Get input split size for all2all.
120
+ reshard_dim = int(resharding_spec.dim) # type: ignore[attr-defined]
121
+ split_size = get_split_size(st_size[reshard_dim], world_size)
122
+ input_split_sizes = [0] * world_size
123
+ idx = get_idx_from_placements(sharding_spec.placements, current_rank) # type: ignore[attr-defined]
124
+ new_rank = resharding_spec.placements[idx].rank() # type: ignore[union-attr, attr-defined]
125
+ input_split_sizes[new_rank] = local_shard.size(reshard_dim)
126
+ # Get output split size for all2all.
127
+ output_split_sizes = [0] * world_size
128
+ new_idx = ranks.index(current_rank)
129
+ sharded_dim_size = get_chunked_dim_size(st_size[reshard_dim], split_size, new_idx)
130
+ output_split_sizes[new_rank] = sharded_dim_size
131
+ # Get gathered_input for all2all.
132
+ local_shard = local_shard.transpose(0, reshard_dim).contiguous()
133
+ gathered_input_size = list(local_shard.size())
134
+ gathered_input_size[0] = sharded_dim_size
135
+ gathered_input = torch.empty(
136
+ gathered_input_size, device=local_shard.device, dtype=local_shard.dtype
137
+ )
138
+ # all2all.
139
+ local_shard = all_to_all_single(
140
+ gathered_input,
141
+ local_shard,
142
+ input_split_sizes=input_split_sizes,
143
+ output_split_sizes=output_split_sizes,
144
+ group=pg,
145
+ )
146
+ local_tensor = local_shard.transpose(0, reshard_dim).contiguous()
147
+ local_shards = [Shard(local_tensor, shards_metadata[current_rank])]
148
+ return local_shards, shards_metadata
149
+
150
+
151
+ def reshard_local_shard(
152
+ local_tensor: torch.Tensor,
153
+ st_size: torch.Size,
154
+ sharding_spec: shard_spec.ShardingSpec,
155
+ resharding_spec: shard_spec.ShardingSpec,
156
+ pg: ProcessGroup,
157
+ ) -> tuple[list[Shard], list[ShardMetadata]]:
158
+ """
159
+ Reshard a sharded tensor given the ``resharding_spec``. When the reshard dim is
160
+ different from the original sharding dim, we need to do two steps logically:
161
+ 1. To collect all shards based on original sharding spec.
162
+ 2. Reshard the tensor based on the given resharding spec.
163
+
164
+ In reality, we consolidate the two steps into one by sending each rank the new
165
+ shard based on the resharding spec.
166
+
167
+ Args:
168
+ local_tensor (Tensor): Local tensor stored in the current rank.
169
+ st_size (torch.Size): The size of the sharded tensor.
170
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
171
+ specification describing how the tensor is sharded originally.
172
+ resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The
173
+ specification describing how the tensor will be resharded.
174
+ pg (ProcessGroup): The process group to aggregate on.
175
+
176
+ Returns:
177
+ A Tuple of the followings:
178
+ A List[`Shard`] which contains the local tensor and its metadata.
179
+ A List[`ShardMetadata`] which contains the metadata for the shard, including
180
+ offsets, lengths and device placement.
181
+ """
182
+ current_rank = dist.get_rank(pg)
183
+ world_size = dist.get_world_size(pg)
184
+ current_sharding_dim = int(sharding_spec.dim) # type: ignore[attr-defined]
185
+ reshard_dim = int(resharding_spec.dim) # type: ignore[attr-defined]
186
+
187
+ # Build shards_metadata first.
188
+ shards_metadata, ranks = build_reshard_metadata(
189
+ st_size, resharding_spec, world_size
190
+ )
191
+
192
+ # Compute expected size
193
+ input_split_sizes = [
194
+ metadata.shard_sizes[reshard_dim] for metadata in shards_metadata
195
+ ]
196
+ rearrange_input = any(ranks[i] > ranks[i + 1] for i in range(len(ranks) - 1))
197
+
198
+ if rearrange_input:
199
+ # Need to re-arrange reshard_dim of local_tensor before all2all.
200
+ indices: list[int] = []
201
+ for metadata in shards_metadata:
202
+ offset_start_idx = metadata.shard_offsets[reshard_dim]
203
+ split_size = metadata.shard_sizes[reshard_dim]
204
+ indices += range(offset_start_idx, offset_start_idx + split_size)
205
+ local_tensor = local_tensor.index_select(
206
+ reshard_dim, torch.tensor(indices, device=local_tensor.device)
207
+ )
208
+
209
+ # Because reshard_dim != original shard_dim. We need to compute the
210
+ # size of tensor from each rank.
211
+ output_tensor_list = [torch.tensor(1)] * world_size
212
+ split_size = get_split_size(st_size[current_sharding_dim], world_size)
213
+ rearrange_output_list = False
214
+ indices = []
215
+ for idx, placement in enumerate(sharding_spec.placements): # type: ignore[attr-defined]
216
+ sharded_dim_size = get_chunked_dim_size(
217
+ st_size[current_sharding_dim], split_size, idx
218
+ )
219
+ output_tensor_size = list(st_size)
220
+ output_tensor_size[current_sharding_dim] = sharded_dim_size
221
+ output_tensor_size[reshard_dim] = input_split_sizes[current_rank]
222
+ output_tensor_list[placement.rank()] = torch.empty( # type: ignore[union-attr, index]
223
+ output_tensor_size, device=local_tensor.device, dtype=local_tensor.dtype
224
+ )
225
+ indices.append(placement.rank()) # type: ignore[union-attr, index, arg-type]
226
+ if idx != placement.rank(): # type: ignore[union-attr]
227
+ rearrange_output_list = True
228
+
229
+ # Perform autograd enabled all2all.
230
+ input_tensor_tuple = torch.split(local_tensor, input_split_sizes, dim=reshard_dim)
231
+ input_tensor_list = [tensor.contiguous() for tensor in input_tensor_tuple]
232
+ output_tensor_list = all_to_all(
233
+ output_tensor_list,
234
+ input_tensor_list,
235
+ group=pg,
236
+ )
237
+
238
+ if rearrange_output_list:
239
+ # Need to re-arrange original shard_dim of output_tensor_list.
240
+ output_tensor_list = [output_tensor_list[idx] for idx in indices] # type: ignore[call-overload]
241
+ local_tensor = torch.cat(output_tensor_list, dim=current_sharding_dim)
242
+ local_shards = [Shard(local_tensor, shards_metadata[current_rank])]
243
+ return local_shards, shards_metadata
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/shard.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ import torch
4
+ from torch.distributed._shard.metadata import ShardMetadata
5
+ from torch.distributed.remote_device import _remote_device
6
+
7
+
8
+ @dataclass
9
+ class Shard:
10
+ """
11
+ Container which holds the data for a shard as a Tensor and also
12
+ the associated metadata for that shard.
13
+
14
+ Args:
15
+ tensor(torch.Tensor): Local tensor for the shard.
16
+ metadata(:class `torch.distributed._shard.sharded_tensor.ShardMetadata`):
17
+ The metadata for the shard, including offsets, lengths and device placement.
18
+ """
19
+
20
+ __slots__ = ["tensor", "metadata"]
21
+ tensor: torch.Tensor
22
+ metadata: ShardMetadata
23
+
24
+ def __post_init__(self) -> None:
25
+ # verification between local tensor and metadata
26
+ if list(self.tensor.size()) != self.metadata.shard_sizes:
27
+ raise ValueError(
28
+ "Shard tensor size does not match with metadata.shard_lengths! "
29
+ f"Found shard tensor size: {list(self.tensor.size())}, "
30
+ f"metadata.shard_lengths: {self.metadata.shard_sizes}, "
31
+ )
32
+ placement_device = self.metadata.placement
33
+ if (
34
+ placement_device is not None
35
+ and placement_device.device() != self.tensor.device
36
+ ):
37
+ raise ValueError(
38
+ f"Local shard tensor device does not match with local Shard's placement! "
39
+ f"Found local shard tensor device: {self.tensor.device}, "
40
+ f"local shard metadata placement device: {placement_device.device()}"
41
+ )
42
+
43
+ @classmethod
44
+ def from_tensor_and_offsets(
45
+ cls, tensor: torch.Tensor, shard_offsets: list[int], rank: int
46
+ ) -> "Shard":
47
+ """
48
+ Creates a Shard of a ShardedTensor from a local torch.Tensor, shard_offsets and rank.
49
+
50
+ Args:
51
+ tensor(torch.Tensor): Local tensor for the shard.
52
+ shard_offsets(List[int]): List of integers specify the offset
53
+ of the shard on each dimension.
54
+ rank(int): Specify the rank for the shard.
55
+ """
56
+ shard_sizes = list(tensor.size())
57
+ placement = _remote_device(f"rank:{rank}/{str(tensor.device)}")
58
+ shard_meta = ShardMetadata(
59
+ shard_offsets=shard_offsets, shard_sizes=shard_sizes, placement=placement
60
+ )
61
+ return Shard(tensor, shard_meta)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharded_tensor/utils.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import collections.abc
3
+ import copy
4
+ import itertools
5
+ from collections.abc import Sequence
6
+ from typing import TYPE_CHECKING
7
+
8
+ import torch
9
+ from torch.distributed import distributed_c10d as c10d, rpc
10
+ from torch.distributed._shard.sharding_spec._internals import (
11
+ check_tensor,
12
+ validate_non_overlapping_shards_metadata,
13
+ )
14
+
15
+ from .metadata import ShardedTensorMetadata, TensorProperties
16
+ from .shard import Shard
17
+
18
+
19
+ if TYPE_CHECKING:
20
+ from torch.distributed._shard.metadata import ShardMetadata
21
+
22
+
23
+ def _parse_and_validate_remote_device(pg, remote_device):
24
+ if remote_device is None:
25
+ raise ValueError("remote device is None")
26
+
27
+ worker_name = remote_device.worker_name()
28
+ rank = remote_device.rank()
29
+ device = remote_device.device()
30
+
31
+ # Validate rank, skip validation if rank is not part of process group.
32
+ if rank is not None and not c10d._rank_not_in_group(pg):
33
+ pg_global_ranks = c10d.get_process_group_ranks(pg)
34
+ if rank not in pg_global_ranks:
35
+ raise ValueError(
36
+ f"Global rank {rank} does not exist in input process group: {pg_global_ranks}"
37
+ )
38
+
39
+ if worker_name is not None:
40
+ if not rpc._is_current_rpc_agent_set():
41
+ raise RuntimeError(
42
+ f"RPC framework needs to be initialized for using worker names: {worker_name}"
43
+ )
44
+
45
+ workers = rpc._get_current_rpc_agent().get_worker_infos()
46
+ for worker in workers:
47
+ if worker.name == worker_name:
48
+ return worker.id, device
49
+
50
+ raise ValueError(f"Invalid worker name: {worker_name}")
51
+
52
+ return rank, device
53
+
54
+
55
+ def _validate_output_tensor_for_gather(
56
+ my_rank: int,
57
+ dst_rank: int,
58
+ size: torch.Size,
59
+ dst_tensor: torch.Tensor | None,
60
+ ) -> None:
61
+ if dst_rank == my_rank:
62
+ if dst_tensor is None:
63
+ raise ValueError(
64
+ f"Argument ``dst_tensor`` must be specified on destination rank {dst_rank}"
65
+ )
66
+ if tuple(size) != (dst_tensor.size()):
67
+ raise ValueError(
68
+ f"Argument ``dst_tensor`` have size {tuple(dst_tensor.size())},"
69
+ f"but should be {tuple(size)}"
70
+ )
71
+ elif dst_tensor:
72
+ raise ValueError(
73
+ "Argument ``dst_tensor`` must NOT be specified on non-destination ranks."
74
+ )
75
+
76
+
77
+ def _flatten_tensor_size(size) -> torch.Size:
78
+ """
79
+ Checks if tensor size is valid, then flatten/return a torch.Size object.
80
+ """
81
+ if len(size) == 1 and isinstance(size[0], collections.abc.Sequence):
82
+ # pyrefly: ignore [not-iterable]
83
+ dims = list(*size)
84
+ else:
85
+ dims = list(size)
86
+
87
+ for dim in dims:
88
+ if not isinstance(dim, int):
89
+ raise TypeError(f"size has to be a sequence of ints, found: {dims}")
90
+
91
+ return torch.Size(dims)
92
+
93
+
94
+ def _raise_if_mismatch(expected, actual, prop_name, ranks, is_local=True):
95
+ if is_local:
96
+ assert isinstance(ranks, int)
97
+ if expected != actual:
98
+ raise ValueError(
99
+ f"Local shards' tensor {prop_name} property need to be the same on rank:{ranks}! "
100
+ f"Found one local shard tensor {prop_name}={expected}, "
101
+ f"the other local shard tensor {prop_name}={actual}."
102
+ )
103
+ else:
104
+ # compare failure check across ranks, ranks list should have two rank
105
+ assert len(ranks) == 2
106
+ if expected != actual:
107
+ raise ValueError(
108
+ f"ShardedTensor {prop_name} property does not match from different ranks! "
109
+ f"Found {prop_name}={expected} on rank:{ranks[0]}, "
110
+ f"and {prop_name}={actual} on rank:{ranks[1]}."
111
+ )
112
+
113
+
114
+ def build_metadata_from_local_shards(
115
+ local_shards: list[Shard],
116
+ global_size: torch.Size,
117
+ current_rank: int,
118
+ pg: c10d.ProcessGroup,
119
+ ) -> ShardedTensorMetadata:
120
+ assert len(local_shards) > 0, "must have local shards!"
121
+ local_shard_metadatas: list[ShardMetadata] = []
122
+
123
+ first_shard_dtype = local_shards[0].tensor.dtype
124
+ first_shard_layout = local_shards[0].tensor.layout
125
+ first_shard_requires_grad = local_shards[0].tensor.requires_grad
126
+ first_shard_is_pinned = local_shards[0].tensor.is_pinned()
127
+
128
+ # 1). Validate local tensors and associated metadatas
129
+ for local_shard in local_shards:
130
+ local_shard_tensor = local_shard.tensor
131
+ local_shard_meta = local_shard.metadata
132
+ local_shard_metadatas.append(local_shard_meta)
133
+ rank, local_device = _parse_and_validate_remote_device(
134
+ pg, local_shard_meta.placement
135
+ )
136
+
137
+ if (
138
+ local_shard_tensor.layout != torch.strided
139
+ or local_shard_tensor.layout != first_shard_layout
140
+ ):
141
+ raise ValueError(
142
+ f"Only torch.strided layout is currently supported, but found "
143
+ f"{local_shard_tensor.layout} on rank:{current_rank}!"
144
+ )
145
+
146
+ if not local_shard_tensor.is_contiguous():
147
+ raise ValueError(
148
+ "Only torch.contiguous_format memory_format is currently supported!"
149
+ )
150
+
151
+ if rank != current_rank:
152
+ raise ValueError(
153
+ f"Local shard metadata's rank does not match with the rank in its process group! "
154
+ f"Found current rank in the process group: {current_rank}, "
155
+ f"local ShardMetadata placement's rank: {rank}"
156
+ )
157
+ if local_shard_tensor.device != local_device:
158
+ raise ValueError(
159
+ f"Local shard tensor device does not match with local Shard's placement! "
160
+ f"Found local shard tensor device: {local_shard_tensor.device}, "
161
+ f"local shard metadata placement device: {local_device}"
162
+ )
163
+
164
+ _raise_if_mismatch(
165
+ local_shard_meta.shard_sizes,
166
+ list(local_shard_tensor.size()),
167
+ "size",
168
+ current_rank,
169
+ )
170
+ _raise_if_mismatch(
171
+ local_shard_tensor.is_pinned(),
172
+ first_shard_is_pinned,
173
+ "pin_memory",
174
+ current_rank,
175
+ )
176
+ _raise_if_mismatch(
177
+ local_shard_tensor.dtype, first_shard_dtype, "dtype", current_rank
178
+ )
179
+ _raise_if_mismatch(
180
+ local_shard_tensor.requires_grad,
181
+ first_shard_requires_grad,
182
+ "requires_grad",
183
+ current_rank,
184
+ )
185
+
186
+ # 2). Build a "local" ShardedTensorMetadata with all local shards on this rank, then
187
+ # do all_gather to collect local_sharded_tensor_metadata from all ranks
188
+ local_tensor_properties = TensorProperties(
189
+ dtype=first_shard_dtype,
190
+ layout=first_shard_layout,
191
+ requires_grad=first_shard_requires_grad,
192
+ memory_format=torch.contiguous_format,
193
+ pin_memory=first_shard_is_pinned,
194
+ )
195
+
196
+ local_sharded_tensor_metadata = ShardedTensorMetadata(
197
+ shards_metadata=local_shard_metadatas,
198
+ size=global_size,
199
+ tensor_properties=local_tensor_properties,
200
+ )
201
+
202
+ return local_sharded_tensor_metadata
203
+
204
+
205
+ def build_global_metadata(
206
+ gathered_metadatas: Sequence[ShardedTensorMetadata | None],
207
+ recalc_metadata: bool = False,
208
+ ):
209
+ global_sharded_tensor_metadata = None
210
+ global_metadata_rank = 0
211
+
212
+ # pyrefly: ignore [bad-assignment]
213
+ for rank, rank_metadata in enumerate(gathered_metadatas):
214
+ if rank_metadata is None:
215
+ continue
216
+
217
+ if global_sharded_tensor_metadata is None:
218
+ global_sharded_tensor_metadata = copy.deepcopy(rank_metadata)
219
+ global_metadata_rank = rank
220
+ else:
221
+ _raise_if_mismatch(
222
+ global_sharded_tensor_metadata.size,
223
+ rank_metadata.size,
224
+ "global_size",
225
+ [global_metadata_rank, rank],
226
+ is_local=False,
227
+ )
228
+
229
+ # don't need to check layout and memory format as we already checked in local shards validation stage
230
+ _raise_if_mismatch(
231
+ global_sharded_tensor_metadata.tensor_properties.dtype,
232
+ rank_metadata.tensor_properties.dtype,
233
+ "dtype",
234
+ [global_metadata_rank, rank],
235
+ is_local=False,
236
+ )
237
+
238
+ _raise_if_mismatch(
239
+ global_sharded_tensor_metadata.tensor_properties.requires_grad,
240
+ rank_metadata.tensor_properties.requires_grad,
241
+ "requires_grad",
242
+ [global_metadata_rank, rank],
243
+ is_local=False,
244
+ )
245
+
246
+ _raise_if_mismatch(
247
+ global_sharded_tensor_metadata.tensor_properties.pin_memory,
248
+ rank_metadata.tensor_properties.pin_memory,
249
+ "pin_memory",
250
+ [global_metadata_rank, rank],
251
+ is_local=False,
252
+ )
253
+ # pass all validations, extend shards metadata
254
+ global_sharded_tensor_metadata.shards_metadata.extend(
255
+ rank_metadata.shards_metadata
256
+ )
257
+
258
+ if global_sharded_tensor_metadata is not None:
259
+ if recalc_metadata:
260
+ recalc_global_sharded_tensor_metadata(
261
+ global_sharded_tensor_metadata,
262
+ 0, # sharded on 0th dim
263
+ )
264
+
265
+ # check if shards_metadata have overlap shards
266
+ validate_non_overlapping_shards_metadata(
267
+ global_sharded_tensor_metadata.shards_metadata
268
+ )
269
+
270
+ # check if the shards_metadata is compatible with global size of the sharded tensor.
271
+ check_tensor(
272
+ global_sharded_tensor_metadata.shards_metadata,
273
+ global_sharded_tensor_metadata.size,
274
+ )
275
+ else:
276
+ raise ValueError("ShardedTensor have no local shards on all ranks!")
277
+
278
+ return global_sharded_tensor_metadata
279
+
280
+
281
+ def recalc_global_sharded_tensor_metadata(
282
+ global_sharded_tensor_metadata: ShardedTensorMetadata, sharded_dim: int
283
+ ) -> None:
284
+ # recalculate global ShardedTensorMetadata
285
+
286
+ # reorder here in case shard metadata is not sorted on sharded_dim
287
+ placement_idx_pairs = []
288
+ for i, shard_metadata in enumerate(global_sharded_tensor_metadata.shards_metadata):
289
+ if shard_metadata.placement:
290
+ placement_idx_pairs.append((shard_metadata.placement.rank(), i))
291
+ else:
292
+ raise AssertionError(
293
+ "currently only support rw, it should always have valid rank info"
294
+ )
295
+ sorted_idx = sorted(placement_idx_pairs)
296
+ shard_sizes = [
297
+ global_sharded_tensor_metadata.shards_metadata[idx].shard_sizes[sharded_dim]
298
+ for _, idx in sorted_idx
299
+ ]
300
+ cum_sum = [0] + list(itertools.accumulate(shard_sizes))
301
+
302
+ for shard_id, shard_metadata in enumerate(
303
+ global_sharded_tensor_metadata.shards_metadata
304
+ ):
305
+ # update shard offset for each shard on the sharded dimension
306
+ shard_metadata.shard_offsets[sharded_dim] = cum_sum[shard_id]
307
+ for other_dim in range(
308
+ len(global_sharded_tensor_metadata.shards_metadata[0].shard_sizes)
309
+ ):
310
+ if other_dim != sharded_dim:
311
+ # shard offset for each shard on the unsharded dimension
312
+ shard_metadata.shard_offsets[other_dim] = 0
313
+
314
+ # update global size for ShardedTensorMetadata
315
+ global_size_list = []
316
+ for other_dim in range(
317
+ len(global_sharded_tensor_metadata.shards_metadata[0].shard_sizes)
318
+ ):
319
+ if other_dim != sharded_dim:
320
+ global_size_list.append(
321
+ global_sharded_tensor_metadata.shards_metadata[0].shard_sizes[other_dim]
322
+ )
323
+ else:
324
+ global_size_list.append(cum_sum[-1])
325
+ global_sharded_tensor_metadata.size = torch.Size(global_size_list)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/distributed/_shard/sharder.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+
3
+ import torch.nn as nn
4
+
5
+
6
+ class Sharder(abc.ABC):
7
+ """
8
+ This is an interface which allows user to create more advanced
9
+ sharding strategies that are not easily be composed by the
10
+ `ShardingSpec`.
11
+
12
+ :class:`torch.distributed._shard.sharding_plan.ShardingPlan` could
13
+ take an object of the `Sharder` and call `shard` to shard the module,
14
+ then replace the original module with sharded module returned.
15
+ """
16
+
17
+ @abc.abstractmethod
18
+ def shard(self, module: nn.Module) -> nn.Module:
19
+ """
20
+ Shard a module base on the implementation of this method, and
21
+ return the sharded version of the module.
22
+
23
+ Args:
24
+ module (:class:`torch.nn.Module`):
25
+ The module to apply sharding to.
26
+ Returns:
27
+ A :class:`torch.nn.Module` object that represents a module
28
+ that's already been sharded.
29
+ """