jasonfan commited on
Commit
8ccd33f
·
verified ·
1 Parent(s): e1e2f25

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/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__init__.py +9 -0
  2. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_common_rules.py +285 -0
  3. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_conv_ops.py +127 -0
  4. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_einsum_strategy.py +186 -0
  5. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_embedding_ops.py +111 -0
  6. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_mask_buffer.py +43 -0
  7. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_math_ops.py +1406 -0
  8. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_matrix_ops.py +1087 -0
  9. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_pointwise_ops.py +809 -0
  10. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_random_ops.py +43 -0
  11. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_tensor_ops.py +1258 -0
  12. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_view_ops.py +798 -0
  13. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/registration.py +83 -0
  14. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/utils.py +388 -0
  15. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_utils.py +461 -0
  16. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/debug/__init__.py +52 -0
  17. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/debug/_comm_mode.py +740 -0
  18. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/debug/_op_coverage.py +106 -0
  19. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/debug/_visualize_sharding.py +227 -0
  20. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/device_mesh.py +9 -0
  21. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/__init__.py +34 -0
  22. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_attention.py +44 -0
  23. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_context_parallel/__init__.py +46 -0
  24. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_context_parallel/_attention.py +1675 -0
  25. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_context_parallel/_cp_custom_ops.py +88 -0
  26. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_context_parallel/_load_balancer.py +486 -0
  27. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_context_parallel/_sharding_rules.py +406 -0
  28. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_func_map.py +278 -0
  29. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_register_sharding.py +136 -0
  30. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_tp_transform.py +557 -0
  31. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/__init__.py +25 -0
  32. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/_data_parallel_utils.py +51 -0
  33. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/api.py +142 -0
  34. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/ddp.py +104 -0
  35. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/fsdp.py +391 -0
  36. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/input_reshard.py +106 -0
  37. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/loss.py +505 -0
  38. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/style.py +810 -0
  39. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/placement_types.py +1114 -0
  40. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/__init__.py +174 -0
  41. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/bernoulli.py +145 -0
  42. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/beta.py +119 -0
  43. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/binomial.py +182 -0
  44. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/categorical.py +170 -0
  45. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/cauchy.py +100 -0
  46. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/chi2.py +43 -0
  47. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/constraint_registry.py +291 -0
  48. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/constraints.py +738 -0
  49. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/continuous_bernoulli.py +250 -0
  50. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/dirichlet.py +138 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ from ._conv_ops import * # noqa: F403
3
+ from ._embedding_ops import * # noqa: F403
4
+ from ._math_ops import * # noqa: F403
5
+ from ._matrix_ops import * # noqa: F403
6
+ from ._pointwise_ops import * # noqa: F403
7
+ from ._random_ops import * # noqa: F403
8
+ from ._tensor_ops import * # noqa: F403
9
+ from ._view_ops import * # noqa: F403
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_common_rules.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ import string
3
+ from typing import cast
4
+
5
+ import torch
6
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
7
+ from torch.distributed.tensor._op_schema import OpSchema, OutputSharding
8
+ from torch.distributed.tensor._ops.utils import prod
9
+ from torch.distributed.tensor._utils import compute_local_shape_and_global_offset
10
+
11
+
12
+ def _replace_char_in_str(string: str, new_char: str, idx: int) -> str:
13
+ return string[:idx] + new_char + string[idx + 1 :]
14
+
15
+
16
+ def _gen_reshard_suggestions(
17
+ op_schema: OpSchema,
18
+ input_dims: list[str],
19
+ input_specs: tuple[DTensorSpec, ...],
20
+ dim_to_sharding: dict[str, int],
21
+ pending_sum: list[int],
22
+ ) -> OutputSharding:
23
+ suggested_arg_specs: list[DTensorSpec] = []
24
+ for input_dim, input_spec in zip(input_dims, input_specs):
25
+ dim_map = [dim_to_sharding[dim] for dim in input_dim]
26
+ suggested_arg_specs.append(
27
+ DTensorSpec.from_dim_map(
28
+ mesh=input_spec.mesh,
29
+ dim_map=dim_map,
30
+ sums=pending_sum,
31
+ tensor_meta=input_spec.tensor_meta,
32
+ )
33
+ )
34
+ suggested_schema = OpSchema(op_schema.op, tuple(suggested_arg_specs), {})
35
+ suggested_schema._inplace_rewrap_schema_suggestion(op_schema)
36
+ return OutputSharding(
37
+ None,
38
+ redistribute_schema=suggested_schema,
39
+ )
40
+
41
+
42
+ def einop_rule(
43
+ equation: str,
44
+ op_schema: OpSchema,
45
+ *,
46
+ linearity: bool = False,
47
+ enforce_sharding: dict[str, int] | None = None,
48
+ ) -> OutputSharding:
49
+ """
50
+ Propagate the sharding of inputs to output for ops whose data moves according to einsum notation.
51
+
52
+ This is mostly borrowed from @zdevito's sharding simulator. Examples:
53
+ mk,kn->mn - einsum
54
+ ij,ij->ij - addition
55
+ ij,j->ij - broadcasted addition
56
+ ij->i - reduction
57
+ Other ops could use this propagation algorithm when applied, note
58
+ that einsum propagation only deal with list of specs (DTensor specs)
59
+ as it only works on list of tensors!
60
+
61
+ linearity in einop_rule means that the calling op `f` follows this rule:
62
+ f(a + b) = f(a) + f(b)
63
+
64
+ In this case we can propagate the partial sum, note that linearity in einop
65
+ only applies to partial sum, not other operations like min/max (which are
66
+ associative but not linear).
67
+ """
68
+ # parse einop equation and extract arg specs
69
+ inputs, outputs = equation.split("->")
70
+ input_dims, output_dims = inputs.split(","), outputs.split(",")
71
+ input_specs = op_schema.args_spec
72
+ # NOTE: only support single output unless needed in future
73
+ output_dim = output_dims[0]
74
+
75
+ dim_to_sharding: dict[str, int] = {}
76
+ dim_to_size: dict[str, int] = {}
77
+ # record pending sum, key is mesh dimension, value is pending sum
78
+ # counter across input specs
79
+ pending_sums_counter: dict[int, int] = {}
80
+ seen_shardings: dict[int, str] = {}
81
+ needs_reshard = False
82
+
83
+ def merge_sharding(dim: str, a: int, b: int) -> int:
84
+ # merge the sharding of inputs if it's able to merge, i.e. we can merge
85
+ # replicate and shard to shard, but this will trigger an reshard operation
86
+ if a != b:
87
+ if a == -1 or b == -1:
88
+ # reshard the replicate to match the sharded one
89
+ nonlocal needs_reshard
90
+ needs_reshard = True
91
+ return a if a != -1 else b
92
+ else:
93
+ # TODO: further merge the sharding properly (i.e. reshard one input to replicate)
94
+ raise RuntimeError(
95
+ f"{equation}: dim {dim} sharded two different ways: {a} and {b}"
96
+ )
97
+ else:
98
+ return a
99
+
100
+ for input_dim, input_spec in zip(input_dims, input_specs):
101
+ # deal with partial sums
102
+ input_sums = input_spec.sums
103
+ for sum_dim in input_sums:
104
+ if sum_dim not in pending_sums_counter:
105
+ seen_shardings[sum_dim] = "+"
106
+ # update pending sum counter for pending sum mesh
107
+ # dimension with the occurrence from each input
108
+ pending_sums_counter[sum_dim] = pending_sums_counter.get(sum_dim, 0) + 1
109
+
110
+ for idx, (dim, mesh_dim) in enumerate(zip(input_dim, input_spec.dim_map)):
111
+ if enforce_sharding and dim in enforce_sharding:
112
+ if enforce_sharding[dim] != mesh_dim:
113
+ needs_reshard = True
114
+ dim_to_sharding[dim] = enforce_sharding[dim]
115
+ dim_to_size[dim] = input_spec.shape[idx]
116
+ elif dim not in dim_to_sharding:
117
+ dim_to_sharding[dim] = mesh_dim
118
+ dim_to_size[dim] = input_spec.shape[idx]
119
+ else:
120
+ dim_to_sharding[dim] = merge_sharding(
121
+ dim, dim_to_sharding[dim], mesh_dim
122
+ )
123
+ assert dim_to_size[dim] == input_spec.shape[idx]
124
+
125
+ # after merging sharding, we check if there're multiple
126
+ # sharding on the same mesh dim.
127
+ merged_sharding_for_dim = dim_to_sharding[dim]
128
+ if merged_sharding_for_dim != -1:
129
+ if (
130
+ merged_sharding_for_dim in seen_shardings
131
+ and dim != seen_shardings[merged_sharding_for_dim]
132
+ ):
133
+ needs_reshard = True
134
+ seen_shardings[merged_sharding_for_dim] += dim
135
+ else:
136
+ seen_shardings[merged_sharding_for_dim] = dim
137
+
138
+ if pending_sums_counter and not linearity:
139
+ # return reshard suggestion with no pending sum, because we already properly
140
+ # merge the sharding, this reshard suggestion is legit to use
141
+ return _gen_reshard_suggestions(
142
+ op_schema, input_dims, input_specs, dim_to_sharding, []
143
+ )
144
+ else:
145
+ # It's a op that support linearity, but not all input arguments are partial
146
+ # we fail the sharding propagation with suggestion to make all inputs be
147
+ # partial on the corresponding mesh dim (all inputs should be partial for
148
+ # the mesh dims in order to execute locally and delay the sum reduction)
149
+ for value in pending_sums_counter.values():
150
+ if value != len(input_specs):
151
+ needs_reshard = True
152
+
153
+ for mesh_dim, dims in seen_shardings.items():
154
+ if len(dims) > 1:
155
+ # we found different input dims are being sharded on the same mesh dim
156
+ # in order to perform local op computation, we need to reshard inputs
157
+ # base on some simple heuristics, now we simply pick the one with least comm
158
+ # volume. (i.e. the input with least size)
159
+ # TODO: consider a more advanced heuristic to pick the best sharding
160
+ costs = []
161
+ for d in dims:
162
+ cost = 0
163
+ for input_dim, input_spec in zip(input_dims, input_specs):
164
+ if (
165
+ d in input_dim
166
+ and input_spec.dim_map[input_dim.index(d)] == mesh_dim
167
+ ):
168
+ assert input_spec.tensor_meta is not None
169
+ global_shape = input_spec.tensor_meta.shape
170
+ local_shape, _ = compute_local_shape_and_global_offset(
171
+ global_shape,
172
+ input_spec.mesh,
173
+ input_spec.placements,
174
+ skip_offset=True,
175
+ )
176
+ cost += prod(local_shape) * input_spec.mesh.size(mesh_dim)
177
+ # pyrefly: ignore [bad-argument-type]
178
+ costs.append(cost)
179
+ d_to_keep_sharding = dims[costs.index(max(costs))]
180
+ for d in dims:
181
+ # update dim_to_sharding to keep the sharding of the dim with
182
+ # highest comm and make the rest of the dims to replicate
183
+ if d != d_to_keep_sharding:
184
+ dim_to_sharding[d] = -1
185
+
186
+ pending_sums = list(pending_sums_counter.keys())
187
+ if needs_reshard:
188
+ return _gen_reshard_suggestions(
189
+ op_schema, input_dims, input_specs, dim_to_sharding, pending_sums
190
+ )
191
+
192
+ # generate output pending sum if a dim is sharded, and it appears in input
193
+ # but not output
194
+ for dim, shard_on_mesh in dim_to_sharding.items():
195
+ if dim not in output_dims[0] and shard_on_mesh != -1:
196
+ pending_sums.append(shard_on_mesh)
197
+
198
+ # if no need to reshard, we directly generate the output sharding
199
+ output_dim_map = []
200
+ output_shape = []
201
+ for dim in output_dim:
202
+ if dim == "1":
203
+ # find output dim that is a singleton dimension, mark sharding and shape
204
+ output_dim_map.append(-1)
205
+ output_shape.append(1)
206
+ else:
207
+ output_dim_map.append(dim_to_sharding[dim])
208
+ output_shape.append(dim_to_size[dim])
209
+
210
+ # XXX: since we still need to have intermediate shape calculation, we need
211
+ # to pass in the shape here. We should remove this once sharding decomp works
212
+ # for ops like addmm
213
+ assert input_specs[0].tensor_meta is not None
214
+ tensor_meta = TensorMeta(
215
+ torch.Size(output_shape),
216
+ input_specs[0].tensor_meta.stride,
217
+ input_specs[0].tensor_meta.dtype,
218
+ )
219
+ return OutputSharding(
220
+ DTensorSpec.from_dim_map(
221
+ input_specs[0].mesh,
222
+ output_dim_map,
223
+ pending_sums,
224
+ tensor_meta=tensor_meta,
225
+ )
226
+ )
227
+
228
+
229
+ def pointwise_rule(op_schema: OpSchema, linearity: bool = False) -> OutputSharding:
230
+ """
231
+ Propagate the sharding for pointwise operations.
232
+
233
+ Examples:
234
+ ij,ij->ij - addition/mul
235
+ ij,j->ij - broadcasted addition
236
+ """
237
+ alphabet = string.ascii_lowercase
238
+ # find the max_dim first in case we need to broadcasting
239
+ input_specs = op_schema.args_spec
240
+ max_dim = max(input.ndim for input in input_specs)
241
+ dimchars = []
242
+ singleton_counter: list[int] = [0] * max_dim
243
+ for input in input_specs:
244
+ start_dim = max_dim - input.ndim
245
+ p = alphabet[start_dim:max_dim]
246
+ # handle the "broadcasting to a common shape case"
247
+ # see https://pytorch.org/docs/stable/notes/broadcasting.html
248
+ # If any of the dimensions is singleton dimension (i.e. 1).
249
+ # we mark the dim char as a special "1" to distinguish with
250
+ # the non-singleton dimension, so that sharding propagation
251
+ # should just ignore the singleton dimension.
252
+ if len(input_specs) > 1:
253
+ for i in range(max_dim):
254
+ if i < start_dim:
255
+ # treat the leading miss dim chars as singleton
256
+ singleton_counter[i] += 1
257
+ elif input.shape[i - start_dim] == 1:
258
+ # mark singleton dim char as a special "1" in einop rule
259
+ singleton_counter[i] += 1
260
+ p = _replace_char_in_str(p, "1", (i - start_dim))
261
+
262
+ dimchars.append(p)
263
+ out_dimchars = alphabet[:max_dim]
264
+ # check if we replace the all inputs dim char with singleton dimension,
265
+ # if we replace all inputs, we also need to replace the output dimension.
266
+ for output_dim_idx in range(len(out_dimchars)):
267
+ if singleton_counter[output_dim_idx] == len(input_specs):
268
+ out_dimchars = _replace_char_in_str(out_dimchars, "1", output_dim_idx)
269
+
270
+ fmt = f"{','.join(p for p in dimchars)}->{out_dimchars}"
271
+
272
+ enforce_sharding: dict[str, int] = {}
273
+ if op_schema.is_inplace_op():
274
+ follow_spec = op_schema.args_spec[0]
275
+ enforce_sharding.update(zip(out_dimchars, follow_spec.dim_map))
276
+ elif op_schema.is_out_variant_op():
277
+ follow_spec = cast(DTensorSpec, op_schema.kwargs_schema["out"])
278
+ enforce_sharding.update(zip(out_dimchars, follow_spec.dim_map))
279
+
280
+ return einop_rule(
281
+ fmt,
282
+ op_schema,
283
+ linearity=linearity,
284
+ enforce_sharding=enforce_sharding,
285
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_conv_ops.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ # implement matrix related ops for distributed tensor
3
+
4
+ import torch
5
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
6
+ from torch.distributed.tensor._op_schema import OpSchema, OutputSharding
7
+ from torch.distributed.tensor._ops.registration import register_prop_rule
8
+
9
+
10
+ aten = torch.ops.aten
11
+
12
+
13
+ @register_prop_rule(aten.convolution.default)
14
+ def convolution_rules(op_schema: OpSchema) -> OutputSharding:
15
+ (
16
+ input_spec,
17
+ weight_spec,
18
+ bias_spec,
19
+ stride,
20
+ padding,
21
+ dilation,
22
+ _transposed,
23
+ _output_padding,
24
+ _groups,
25
+ ) = op_schema.args_schema
26
+
27
+ assert isinstance(input_spec, DTensorSpec)
28
+ assert isinstance(weight_spec, DTensorSpec)
29
+ # bias_spec can be None (optional parameter in aten.convolution schema)
30
+ if bias_spec is not None:
31
+ assert isinstance(bias_spec, DTensorSpec)
32
+ assert input_spec.tensor_meta is not None
33
+ assert weight_spec.tensor_meta is not None
34
+ in_shape = input_spec.tensor_meta.shape
35
+ weight_shape = weight_spec.tensor_meta.shape
36
+ assert isinstance(stride, list), f"stride must be list, got {type(stride)}"
37
+ assert isinstance(padding, list), f"padding must be list, got {type(padding)}"
38
+ assert isinstance(dilation, list), f"dilation must be list, got {type(dilation)}"
39
+ # weight_shape might not be torch.Size in all cases (e.g., SymIntArrayRef during tracing)
40
+ # so we don't assert its type, just use it
41
+ out_conv_shape = [
42
+ (d + 2 * padding[i] - dilation[i] * (weight_shape[i + 1] - 1) - 1) // stride[i]
43
+ + 1
44
+ for (i, d) in enumerate(in_shape[2:])
45
+ ]
46
+ output_shape = [in_shape[0], weight_shape[0]] + out_conv_shape
47
+ output_stride = [1]
48
+ for i in range(1, len(output_shape)):
49
+ output_stride.insert(0, output_stride[0] * output_shape[-i])
50
+ output_dim_map = input_spec.dim_map
51
+ pending_sums = input_spec.sums
52
+
53
+ tensor_meta = TensorMeta(
54
+ torch.Size(output_shape),
55
+ tuple(output_stride),
56
+ input_spec.tensor_meta.dtype,
57
+ )
58
+ return OutputSharding(
59
+ DTensorSpec.from_dim_map(
60
+ input_spec.mesh,
61
+ output_dim_map,
62
+ pending_sums,
63
+ tensor_meta=tensor_meta,
64
+ )
65
+ )
66
+
67
+
68
+ @register_prop_rule(aten.convolution_backward.default)
69
+ def convolution_backward_rules(op_schema: OpSchema) -> OutputSharding:
70
+ input_spec = op_schema.args_schema[0]
71
+ (
72
+ grad_output_spec,
73
+ input_spec,
74
+ weight_spec,
75
+ bias_shape_opt,
76
+ _stride,
77
+ _padding,
78
+ _dilation,
79
+ _transposed,
80
+ _output_padding,
81
+ _groups,
82
+ _output_mask,
83
+ ) = op_schema.args_schema
84
+
85
+ assert isinstance(grad_output_spec, DTensorSpec)
86
+ assert isinstance(input_spec, DTensorSpec)
87
+ assert isinstance(weight_spec, DTensorSpec)
88
+ # bias_shape_opt can be None (optional parameter in aten.convolution_backward schema)
89
+ if bias_shape_opt is not None:
90
+ assert isinstance(bias_shape_opt, list)
91
+ assert input_spec.tensor_meta is not None
92
+ weight_tensor_meta = weight_spec.tensor_meta
93
+
94
+ # Only create bias_tensor_meta if bias_shape_opt is not None
95
+ if bias_shape_opt is not None:
96
+ bias_tensor_meta = TensorMeta(
97
+ torch.Size(bias_shape_opt),
98
+ (1,),
99
+ input_spec.tensor_meta.dtype,
100
+ )
101
+ else:
102
+ bias_tensor_meta = None
103
+
104
+ grad_input_spec = input_spec
105
+ grad_weight_spec = DTensorSpec.from_dim_map(
106
+ input_spec.mesh,
107
+ [-1, -1, -1, -1],
108
+ [0],
109
+ tensor_meta=weight_tensor_meta,
110
+ )
111
+
112
+ # Only create grad_bias_spec if we have bias_tensor_meta
113
+ if bias_tensor_meta is not None:
114
+ grad_bias_spec = DTensorSpec.from_dim_map(
115
+ input_spec.mesh,
116
+ [-1],
117
+ [0],
118
+ tensor_meta=bias_tensor_meta,
119
+ )
120
+ else:
121
+ grad_bias_spec = None
122
+
123
+ # TODO: actually the output_mask is not respected here, we should
124
+ # set the corresponding spec to `None` if the output_mask is not `False`
125
+ # for a certain output Tensor. This also applies to the conv handler
126
+ # in torch/distributed/tensor/_tp_conv.py
127
+ return OutputSharding([grad_input_spec, grad_weight_spec, grad_bias_spec])
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_einsum_strategy.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from dataclasses import dataclass
3
+
4
+ from torch.distributed.device_mesh import DeviceMesh
5
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec
6
+ from torch.distributed.tensor._op_schema import OpSpec, OpStrategy
7
+ from torch.distributed.tensor.placement_types import (
8
+ Partial,
9
+ Placement,
10
+ Replicate,
11
+ Shard,
12
+ )
13
+
14
+
15
+ @dataclass
16
+ class EinsumDims:
17
+ contracting_dims: list[str]
18
+ batch_dims: list[str]
19
+ lhs_out_only_dims: list[str]
20
+ rhs_out_only_dims: list[str]
21
+
22
+ @classmethod
23
+ def parse_equation(cls, equation: str) -> tuple[list[str], str]:
24
+ # parse einop equation and extract arg specs
25
+ """
26
+ Parse the einsum equation str to input dim chars and output dim char
27
+ """
28
+ inputs, outputs = equation.split("->")
29
+ input_dims, output_dims = inputs.split(","), outputs.split(",")
30
+
31
+ # NOTE: only support at most two inputs, and single output
32
+ # extend to support more inputs if needed in future
33
+ assert len(input_dims) <= 2, "Only support at most two inputs"
34
+ assert len(output_dims) == 1, "Only support single output"
35
+ output_dim = output_dims[0]
36
+ return input_dims, output_dim
37
+
38
+ @classmethod
39
+ def parse_dims(cls, input_dims: list[str], output_dim: str) -> "EinsumDims":
40
+ """
41
+ Parse the dims and extract the contracting, batch, and free dimensions
42
+ for the left and right hand sides.
43
+ """
44
+ dim_char_set: set[str] = set()
45
+ for input_dim in input_dims:
46
+ dim_char_set.update(input_dim)
47
+
48
+ # get a deterministic order of all dim chars
49
+ all_dim_chars = sorted(dim_char_set)
50
+
51
+ # parse input and output dimensions
52
+ lhs_out_only_dims, rhs_out_only_dims = [], []
53
+ batch_dims, contracting_dims = [], []
54
+
55
+ for dim_char in all_dim_chars:
56
+ if dim_char not in output_dim:
57
+ contracting_dims.append(dim_char)
58
+ else:
59
+ is_batch_dim = True
60
+ for input_dim in input_dims:
61
+ is_batch_dim = is_batch_dim and dim_char in input_dim
62
+
63
+ if is_batch_dim:
64
+ batch_dims.append(dim_char)
65
+ else:
66
+ assert len(input_dims) == 2, (
67
+ "free dimension only supported for two inputs!"
68
+ )
69
+ lhs, rhs = input_dims
70
+ if dim_char in lhs:
71
+ lhs_out_only_dims.append(dim_char)
72
+ elif dim_char in rhs:
73
+ rhs_out_only_dims.append(dim_char)
74
+ else:
75
+ raise RuntimeError("Invalid dimension character")
76
+
77
+ return cls(
78
+ contracting_dims=contracting_dims,
79
+ batch_dims=batch_dims,
80
+ lhs_out_only_dims=lhs_out_only_dims,
81
+ rhs_out_only_dims=rhs_out_only_dims,
82
+ )
83
+
84
+
85
+ def gen_einsum_strategies(
86
+ equation: str,
87
+ mesh: DeviceMesh,
88
+ *,
89
+ linearity: bool = False,
90
+ ) -> OpStrategy:
91
+ """
92
+ Generate a strategy list for the ops that follow einsum style notation.
93
+
94
+ In principle, each mesh dim is independent of other device mesh dim when we
95
+ generate strategies. So we generate strategy over each device mesh dim and
96
+ do product combination on all mesh dims. We basically follow the below rule
97
+ for each device mesh dim:
98
+
99
+ 1. Shard on contracting dim: When both inputs shard on contracting dim over
100
+ the same device dim. The result will be Partial over that device dim.
101
+
102
+ 2. Shard on noncontracting dim:
103
+ 2.1: Shard on batch dim: output, both inputs all should shard on batch
104
+ dim.
105
+ 2.2: Shard on lhs only dim or rhs only dim: both output and lhs or rhs
106
+ input should shard on this free dim.
107
+
108
+ 3. Linearity (Partial): If enabled, set Partial on output and inputs over
109
+ the same device mesh dim.
110
+ """
111
+ # parse einop equation and extract dims
112
+ input_dims, output_dim = EinsumDims.parse_equation(equation)
113
+ edims = EinsumDims.parse_dims(input_dims, output_dim)
114
+ all_mesh_dim_strategies = []
115
+
116
+ # generate strategies for each mesh dim and do cartesian product for final strategy. E.g., for a 2D mesh, we can have [P(),R,R]
117
+ strategies_over_one_mesh_dim = []
118
+
119
+ # placement list stores placements of [output, input1, input2, ...]
120
+ # first we always have replicate all for inputs and output
121
+ placement_list: list[Placement] = [Replicate()] * (len(input_dims) + 1)
122
+ strategies_over_one_mesh_dim.append(placement_list)
123
+
124
+ # split batch dim
125
+ for batch_dim in edims.batch_dims:
126
+ output_batch_dim = output_dim.index(batch_dim)
127
+ placement_list = [Shard(output_batch_dim)]
128
+ for input_dim in input_dims:
129
+ input_batch_dim = input_dim.index(batch_dim)
130
+ placement_list.append(Shard(input_batch_dim))
131
+
132
+ strategies_over_one_mesh_dim.append(placement_list)
133
+
134
+ # split contracting dim
135
+ for contracting_dim in edims.contracting_dims:
136
+ # Contracting dim can shard on same device axis for both inputs. This
137
+ # results in the output being Partial on that device axis. For example:
138
+ # bmk_{x},k_{x}n -> bmn{Ux} (becomes partial over device axis x)
139
+ placement_list = [Partial()]
140
+ for input_dim in input_dims:
141
+ input_contracting_dim = input_dim.index(contracting_dim)
142
+ placement_list.append(Shard(input_contracting_dim))
143
+
144
+ strategies_over_one_mesh_dim.append(placement_list)
145
+
146
+ # split lhs free dim
147
+ for lhs_dim in edims.lhs_out_only_dims:
148
+ lhs_free_dim_output = output_dim.index(lhs_dim)
149
+ lhs_free_dim_input = input_dims[0].index(lhs_dim)
150
+ # this means split the lhs input and output
151
+ # i.e. S(0), R -> S(0)
152
+ lhs_placement_list: list[Placement] = [
153
+ Shard(lhs_free_dim_output),
154
+ Shard(lhs_free_dim_input),
155
+ Replicate(),
156
+ ]
157
+ strategies_over_one_mesh_dim.append(lhs_placement_list)
158
+
159
+ # split rhs free dim
160
+ for rhs_dim in edims.rhs_out_only_dims:
161
+ rhs_free_dim_output = output_dim.index(rhs_dim)
162
+ rhs_free_dim_input = input_dims[1].index(rhs_dim)
163
+ rhs_placement_list: list[Placement] = [
164
+ Shard(rhs_free_dim_output),
165
+ Replicate(),
166
+ Shard(rhs_free_dim_input),
167
+ ]
168
+ strategies_over_one_mesh_dim.append(rhs_placement_list)
169
+
170
+ # linearity strategy
171
+ if linearity:
172
+ linearity_placement_list: list[Placement] = [Partial()]
173
+ for _ in input_dims:
174
+ linearity_placement_list.append(Partial())
175
+ strategies_over_one_mesh_dim.append(linearity_placement_list)
176
+
177
+ # generate strategies for entire mesh
178
+ all_mesh_dim_strategies = [strategies_over_one_mesh_dim] * mesh.ndim
179
+ strategy_combs = itertools.product(*all_mesh_dim_strategies)
180
+ all_strategies = []
181
+ for strategy_comb in strategy_combs:
182
+ spec_list = [DTensorSpec(mesh, tuple(specs)) for specs in zip(*strategy_comb)]
183
+ strat = OpSpec(output_specs=spec_list[0], input_specs=spec_list[1:])
184
+ all_strategies.append(strat)
185
+
186
+ return OpStrategy(all_strategies)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_embedding_ops.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+ # implement matrix related ops for distributed tensor
4
+ from typing import cast
5
+
6
+ import torch
7
+ from torch.distributed.tensor._op_schema import (
8
+ OpSchema,
9
+ OpStrategy,
10
+ PlacementList,
11
+ StrategyType,
12
+ )
13
+ from torch.distributed.tensor._ops.registration import register_op_strategy
14
+ from torch.distributed.tensor._ops.utils import expand_to_full_mesh_op_strategy
15
+ from torch.distributed.tensor.placement_types import (
16
+ MaskPartial,
17
+ Partial,
18
+ Replicate,
19
+ Shard,
20
+ )
21
+
22
+
23
+ aten = torch.ops.aten
24
+
25
+
26
+ @register_op_strategy(aten.embedding.default)
27
+ def embedding_strategy(op_schema: OpSchema) -> StrategyType:
28
+ """
29
+ This strategy handles embedding op. We have two possible embedding shardings:
30
+ rowwise and colwise
31
+ """
32
+ weight_strategy = cast(OpStrategy, op_schema.args_schema[0])
33
+ indices_strategy = cast(OpStrategy, op_schema.args_schema[1])
34
+ mesh = op_schema.get_mesh_from_args()
35
+
36
+ weight_shape = weight_strategy.shape
37
+ indices_shape = indices_strategy.shape
38
+ output_emd_dim = len(indices_shape)
39
+
40
+ single_mesh_dim_strategies = []
41
+
42
+ # placement list stores placements of [output, weight, input_indices]
43
+ # first we always have replicate all for inputs and output
44
+ all_replicate: PlacementList = [Replicate()] * 3
45
+ single_mesh_dim_strategies.append(all_replicate)
46
+
47
+ # colwise sharding, output shard on last dim, weight shard on dim 1, input replicate
48
+ colwise_sharding: PlacementList = [Shard(output_emd_dim), Shard(1), Replicate()]
49
+ single_mesh_dim_strategies.append(colwise_sharding)
50
+
51
+ # rowwise sharding, output is embedding partial, weight shard on dim 0, input accepts embedding partial
52
+ embedding_partial_placement = MaskPartial(offset_shape=weight_shape, offset_dim=0)
53
+
54
+ # NOTE we want to reuse the same mask partial placement so that we can reuse the same mask that generates
55
+ # from the input indices and use it for output reduction
56
+ rowwise_sharding: PlacementList = [
57
+ embedding_partial_placement,
58
+ Shard(0),
59
+ embedding_partial_placement,
60
+ ]
61
+ single_mesh_dim_strategies.append(rowwise_sharding)
62
+
63
+ # batch dim sharding, weight replicated, input can shard on any dim, output follows input
64
+ for input_dim in range(len(indices_shape)):
65
+ batch_sharding: PlacementList = [
66
+ Shard(input_dim),
67
+ Replicate(),
68
+ Shard(input_dim),
69
+ ]
70
+ single_mesh_dim_strategies.append(batch_sharding)
71
+
72
+ return expand_to_full_mesh_op_strategy(mesh, op_schema, single_mesh_dim_strategies)
73
+
74
+
75
+ @register_op_strategy(aten.embedding_dense_backward.default)
76
+ def embedding_dense_backward_strategy(op_schema: OpSchema) -> StrategyType:
77
+ """
78
+ This strategy handles embedding op. We have two possible embedding shardings:
79
+ rowwise and colwise
80
+ """
81
+ grad_out_strategy = cast(OpStrategy, op_schema.args_schema[0])
82
+ indices_strategy = cast(OpStrategy, op_schema.args_schema[1])
83
+ mesh = op_schema.get_mesh_from_args()
84
+
85
+ grad_out_shape = grad_out_strategy.shape
86
+ indices_shape = indices_strategy.shape
87
+ grad_out_ndim = len(grad_out_shape)
88
+
89
+ single_mesh_dim_strategies = []
90
+
91
+ # placement list stores placements of [output, weight, input_indices]
92
+ # first we always have replicate all for inputs and output
93
+ all_replicate: PlacementList = [Replicate()] * 3
94
+ single_mesh_dim_strategies.append(all_replicate)
95
+
96
+ # colwise sharding backward, grad_out shard on last dim, input replicate,
97
+ # weight grad shard colwise
98
+ colwise_sharding: PlacementList = [Shard(1), Shard(grad_out_ndim - 1), Replicate()]
99
+ single_mesh_dim_strategies.append(colwise_sharding)
100
+
101
+ # batch dim sharding, weight replicated, grad_out/input have same sharding
102
+ # that can shard on any dim, weight grad partial
103
+ for input_dim in range(len(indices_shape)):
104
+ batch_sharding: PlacementList = [Partial(), Shard(input_dim), Shard(input_dim)]
105
+ single_mesh_dim_strategies.append(batch_sharding)
106
+
107
+ # grad_out partial, input replicate, weight grad keep partial
108
+ partial_sharding: PlacementList = [Partial(), Partial(), Replicate()]
109
+ single_mesh_dim_strategies.append(partial_sharding)
110
+
111
+ return expand_to_full_mesh_op_strategy(mesh, op_schema, single_mesh_dim_strategies)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_mask_buffer.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+ from dataclasses import dataclass
4
+
5
+ import torch
6
+
7
+
8
+ @dataclass
9
+ class MaskBuffer:
10
+ data: torch.Tensor | None = None
11
+ # refcount allows shared usage of the MaskBuffer, as long as all users have the same data
12
+ refcount: int = 0
13
+
14
+ def materialize_mask(self, mask):
15
+ if self.refcount == 0:
16
+ self.data = mask
17
+ else:
18
+ assert self.data is not None
19
+ if not torch.equal(self.data, mask):
20
+ raise RuntimeError(
21
+ "MaskBuffer has been materialized with conflicting data"
22
+ )
23
+ self.refcount += 1
24
+
25
+ def release_mask(self):
26
+ if self.refcount == 0 or self.data is None:
27
+ raise RuntimeError("MaskBuffer has not been materialized")
28
+ self.refcount -= 1
29
+ if self.refcount == 0:
30
+ self.data = None
31
+
32
+ def apply_mask(self, tensor):
33
+ if self.refcount == 0 or self.data is None:
34
+ raise RuntimeError("MaskBuffer has not been materialized")
35
+
36
+ # NOTE: MaskPartial is being used by the embedding op and the gather op.
37
+ # For gather, the mask has the same dimension as the output tensor, whereas
38
+ # the output of the embedding op has an additional dimension compare to the input,
39
+ # hence the output masking logic below having two different cases.
40
+ if tensor.ndim == self.data.ndim:
41
+ tensor[self.data] = 0.0
42
+ else:
43
+ tensor[self.data, :] = 0.0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_math_ops.py ADDED
@@ -0,0 +1,1406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+ import math
4
+ from collections.abc import Sequence
5
+ from dataclasses import dataclass
6
+ from enum import Enum
7
+ from typing import cast, Union
8
+
9
+ import torch
10
+ from torch.distributed.device_mesh import DeviceMesh
11
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec
12
+ from torch.distributed.tensor._op_schema import (
13
+ OpSchema,
14
+ OpSpec,
15
+ OpStrategy,
16
+ PlacementList,
17
+ RuntimeSchemaInfo,
18
+ TupleStrategy,
19
+ )
20
+ from torch.distributed.tensor._ops.registration import register_op_strategy
21
+ from torch.distributed.tensor._ops.utils import (
22
+ as_list,
23
+ expand_to_full_mesh_op_strategy,
24
+ generate_redistribute_costs,
25
+ is_tensor_evenly_shardable,
26
+ is_tensor_evenly_shardable_on_dim,
27
+ normalize_dim,
28
+ normalize_dims,
29
+ )
30
+ from torch.distributed.tensor._utils import normalize_to_torch_size
31
+ from torch.distributed.tensor.placement_types import (
32
+ _StridedShard,
33
+ Partial,
34
+ Placement,
35
+ Replicate,
36
+ Shard,
37
+ )
38
+
39
+
40
+ aten = torch.ops.aten
41
+
42
+
43
+ class Reduction(Enum):
44
+ NONE = 0
45
+ MEAN = 1
46
+ SUM = 2
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class NormReduction:
51
+ norm_type: int | float | str
52
+
53
+
54
+ ReductionOpType = Union[NormReduction, str]
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class _NormPartial(Partial):
59
+ """
60
+ This placement is used for partial vector norm.
61
+
62
+ For p-norms (where p not inf or -inf), the p-norm over n elements computes
63
+ (sum_i x_i^p)^(1/p)
64
+ where the sum is from i=1 to n. The reduction op is the p-norm itself.
65
+ For example, consider 2 ranks, a (4,) tensor sharded on dim-0, and 2-norm:
66
+ Rank 0: [t1, t2] | Rank 1: [t3, t4]
67
+ After computing 2-norm per gradient (partial placement):
68
+ Rank 0: [sqrt(t1^2 + t2^2)] | Rank 1: [sqrt(t3^2 + t4^2)]
69
+ Converting from partial to replicate wants to ultimately get:
70
+ Rank 0/1: [sqrt(t1^2 + t2^2 + t3^2 + t4^2)]
71
+ This can be achieved by computing 2-norm on each rank's result. This holds
72
+ similarly for inf and -inf norm. For 0-norm, the reduction op is sum.
73
+ """
74
+
75
+ norm_type: int | float | str = 2
76
+
77
+ def __init__(self, norm_type: int | float | str = 2):
78
+ reduce_op = None
79
+ if norm_type in (float("inf"), "inf"):
80
+ reduce_op = "max"
81
+ elif norm_type in (float("-inf"), "-inf"):
82
+ reduce_op = "min"
83
+ elif isinstance(norm_type, (int, float)):
84
+ reduce_op = "sum"
85
+ else:
86
+ raise NotImplementedError(f"Unsupported norm type: {norm_type}")
87
+
88
+ super().__init__(reduce_op)
89
+ object.__setattr__(self, "norm_type", norm_type)
90
+
91
+ def _partition_value(
92
+ self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
93
+ ) -> torch.Tensor:
94
+ """
95
+ For example, consider 4 ranks, a (3,) replicated tensor, and 2-norm:
96
+ Ranks 0 and 1: sqrt(t1^2 + t2^2 + t3^3)
97
+ To convert from replicated to partial, we want f(x) such that
98
+ sqrt(t1^2 + t2^2 + t3^3) = sqrt(4f(t1)^2 + 4f(t2)^2 + 4f(t3)^2)
99
+ = sqrt(4) sqrt(f(t1)^2 + f(t2)^2 + f(t3)^2).
100
+ One such f(x) is f(x) = x / sqrt(4). This generalizes to d ranks and
101
+ p-norm as f(x) = x / d^(1/p).
102
+ """
103
+ if self.reduce_op in ("max", "min"):
104
+ return tensor
105
+ elif self.reduce_op == "sum":
106
+ if self.norm_type == 0:
107
+ raise NotImplementedError(f"Unsupported norm type:: {self.norm_type}")
108
+ elif self.norm_type == 1:
109
+ return tensor / mesh.size(mesh_dim)
110
+ if not isinstance(self.norm_type, (int, float)):
111
+ raise AssertionError(
112
+ f"Expected int or float, got {type(self.norm_type)}"
113
+ )
114
+ return tensor / math.pow(mesh.size(mesh_dim), 1 / self.norm_type)
115
+ raise NotImplementedError(self.reduce_op)
116
+
117
+ def _reduce_shard_value(
118
+ self,
119
+ tensor: torch.Tensor,
120
+ mesh: DeviceMesh,
121
+ mesh_dim: int,
122
+ shard_spec: Placement,
123
+ ) -> torch.Tensor:
124
+ if not isinstance(shard_spec, Shard):
125
+ raise AssertionError(f"Expected Shard, got {type(shard_spec)}")
126
+ tensor = self._pre_reduce_transform(tensor)
127
+ reduced_tensor = super()._reduce_shard_value(tensor, mesh, mesh_dim, shard_spec)
128
+ return self._post_reduce_transform(reduced_tensor)
129
+
130
+ def _reduce_value(
131
+ self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
132
+ ) -> torch.Tensor:
133
+ tensor = self._pre_reduce_transform(tensor)
134
+ reduced_tensor = super()._reduce_value(tensor, mesh, mesh_dim)
135
+ return self._post_reduce_transform(reduced_tensor)
136
+
137
+ def _pre_reduce_transform(self, tensor: torch.Tensor) -> torch.Tensor:
138
+ if self.reduce_op == "sum":
139
+ if not isinstance(self.norm_type, (int, float)):
140
+ raise AssertionError(
141
+ f"Expected int or float, got {type(self.norm_type)}"
142
+ )
143
+ if self.norm_type != 0 and self.norm_type != 1:
144
+ # pyrefly: ignore [unsupported-operation]
145
+ return tensor**self.norm_type
146
+ return tensor
147
+
148
+ def _post_reduce_transform(self, tensor: torch.Tensor) -> torch.Tensor:
149
+ if self.reduce_op == "sum":
150
+ if not isinstance(self.norm_type, (int, float)):
151
+ raise AssertionError(
152
+ f"Expected int or float, got {type(self.norm_type)}"
153
+ )
154
+ if self.norm_type != 0 and self.norm_type != 1:
155
+ # pyrefly: ignore [unsupported-operation]
156
+ return tensor ** (1.0 / self.norm_type)
157
+ return tensor
158
+
159
+ def __eq__(self, other: object) -> bool:
160
+ if not isinstance(other, _NormPartial):
161
+ return False
162
+ return self.norm_type == other.norm_type
163
+
164
+ def __hash__(self) -> int:
165
+ return 1 + hash(self.norm_type)
166
+
167
+ def __repr__(self) -> str:
168
+ """
169
+ machine readable representation of the _NormPartial placement
170
+ """
171
+ return f"_NormPartial(reduce_op={self.reduce_op}, norm_type={self.norm_type})"
172
+
173
+ def __str__(self) -> str:
174
+ """human readable representation of the _NormPartial placement"""
175
+ return f"_NormP({self.reduce_op}, {self.norm_type})"
176
+
177
+
178
+ def _infer_reduction_dims(dims_arg: object, ndim: int) -> list[int] | None:
179
+ if dims_arg is None:
180
+ return None
181
+ dims = cast(list[int], as_list(dims_arg))
182
+ dims = cast(list[int], normalize_dims(dims, ndim))
183
+ empty_dims = [[0], [-1], []]
184
+ if ndim == 0 and dims_arg in empty_dims:
185
+ return None
186
+ return dims
187
+
188
+
189
+ def _infer_reduce_dims_map(
190
+ reduction_dims: list[int], input_ndim: int, keep_dim=False
191
+ ) -> list[int]:
192
+ reduction_dims_map = []
193
+ new_dim_count = 0
194
+ for input_dim in range(input_ndim):
195
+ if input_dim in reduction_dims and not keep_dim:
196
+ # if input dim in reduction dims, mark it as -1
197
+ reduction_dims_map.append(-1)
198
+ else:
199
+ # otherwise mark it as the new dim
200
+ reduction_dims_map.append(new_dim_count)
201
+ new_dim_count += 1
202
+
203
+ return reduction_dims_map
204
+
205
+
206
+ def _replicate_dims_start_at(
207
+ placements: Sequence[Placement], start_dim: int = 0
208
+ ) -> tuple[Placement, ...]:
209
+ new_placements: list[Placement] = []
210
+ for p in placements:
211
+ if p.is_partial() or (isinstance(p, Shard) and p.dim >= start_dim):
212
+ new_placements.append(Replicate()) # make it replicate
213
+ else:
214
+ new_placements.append(p) # keep the placement
215
+ return tuple(new_placements)
216
+
217
+
218
+ # return new_placements which align with placements but skip the skipped_dim
219
+ def _skip_dim(
220
+ placements: tuple[Placement, ...], skipped_dim: int
221
+ ) -> tuple[Placement, ...]:
222
+ new_placements: list[Placement] = []
223
+ for p in placements:
224
+ if isinstance(p, Shard) and p.dim >= skipped_dim:
225
+ new_placements.append(Shard(p.dim - 1))
226
+ else:
227
+ new_placements.append(p)
228
+ return tuple(new_placements)
229
+
230
+
231
+ def replicate_reduction_dims(
232
+ placements: tuple[Placement, ...], reduction_dims: list[int]
233
+ ) -> tuple[Placement, ...]:
234
+ # replicate the reduction dims if not reduction_linear
235
+ new_placements: list[Placement] = []
236
+
237
+ for p in placements:
238
+ if p.is_partial():
239
+ new_placements.append(Replicate())
240
+ elif isinstance(p, Shard) and p.dim in reduction_dims:
241
+ new_placements.append(Replicate())
242
+ else:
243
+ new_placements.append(p)
244
+
245
+ return tuple(new_placements)
246
+
247
+
248
+ def map_placements_after_reduction(
249
+ placements: tuple[Placement, ...],
250
+ reduction_dims: list[int],
251
+ reduction_dims_map: list[int],
252
+ reduction_op: ReductionOpType,
253
+ ) -> tuple[Placement, ...]:
254
+ """
255
+ Map each placement based on the output shape after reduction.
256
+ """
257
+ new_placements: list[Placement] = []
258
+ for placement in placements:
259
+ if isinstance(placement, (Replicate, Partial)):
260
+ new_placements.append(placement)
261
+ else:
262
+ if not isinstance(placement, Shard | _StridedShard):
263
+ raise AssertionError(
264
+ f"Expected Shard/_StridedShard, got {type(placement)}"
265
+ )
266
+ shard_dim = placement.dim
267
+ new_shard_dim = reduction_dims_map[shard_dim]
268
+ if new_shard_dim == -1 or shard_dim in reduction_dims:
269
+ # if new_shard_dim collapsed or its in the reduction dims
270
+ # (i.e. for the case where keepdims=True), we generate partial
271
+ new_placements.append(get_placement_from_reduction_op(reduction_op))
272
+ else:
273
+ if isinstance(placement, Shard):
274
+ new_placements.append(Shard(new_shard_dim))
275
+ else:
276
+ new_placements.append(
277
+ _StridedShard(
278
+ new_shard_dim, split_factor=placement.split_factor
279
+ )
280
+ )
281
+ return tuple(new_placements)
282
+
283
+
284
+ def get_placement_from_reduction_op(reduction_op: ReductionOpType) -> Placement:
285
+ if isinstance(reduction_op, NormReduction):
286
+ return _NormPartial(norm_type=reduction_op.norm_type)
287
+ return Partial(reduction_op)
288
+
289
+
290
+ def common_reduction_strategy(
291
+ input_strategy: OpStrategy,
292
+ reduce_dims: list[int],
293
+ keep_dim: bool = False,
294
+ reduction_linear: bool = True,
295
+ reduction_op: ReductionOpType = "sum",
296
+ ) -> OpStrategy:
297
+ """
298
+ reduction_linear means that the reduction `f` follows this rule:
299
+ f([f(a), f(b)]) = f([a, b])
300
+
301
+ reduction linear should be super set of linearity.
302
+ """
303
+ # by default follow reduction input strategy
304
+ reduction_strategy = OpStrategy([])
305
+
306
+ for op_spec in input_strategy.strategies:
307
+ if reduction_op == "avg":
308
+ output_spec = op_spec.output_spec
309
+ local_shape = list(output_spec.tensor_meta.shape) # type:ignore[union-attr]
310
+ for dim in reduce_dims:
311
+ if not is_tensor_evenly_shardable_on_dim(local_shape, output_spec, dim):
312
+ # reduce(avg) is not linear for unevenly sharded tensors
313
+ reduction_linear = False
314
+ break
315
+
316
+ for p in op_spec.output_spec.placements:
317
+ # when the partial reduction op matches the global reduction op,
318
+ # we can delay redistribution (i.e max, max)
319
+ if isinstance(p, Partial) and p.reduce_op != reduction_op:
320
+ reduction_linear = False
321
+ break
322
+
323
+ if not reduction_linear:
324
+ # input placements for this strategy should clear out pending sum and sharding
325
+ # on the reduction dimension
326
+ input_placements = replicate_reduction_dims(
327
+ op_spec.output_spec.placements, reduce_dims
328
+ )
329
+ else:
330
+ input_placements = op_spec.output_spec.placements
331
+
332
+ input_spec = DTensorSpec(
333
+ mesh=input_strategy.mesh,
334
+ placements=input_placements,
335
+ tensor_meta=op_spec.output_spec.tensor_meta,
336
+ )
337
+
338
+ reduce_dims_map = _infer_reduce_dims_map(reduce_dims, input_spec.ndim, keep_dim)
339
+ out_placements = map_placements_after_reduction(
340
+ input_spec.placements, reduce_dims, reduce_dims_map, reduction_op
341
+ )
342
+ redistribute_cost = [generate_redistribute_costs(input_strategy, input_spec)]
343
+ reduction_strategy.strategies.append(
344
+ OpSpec(
345
+ output_specs=DTensorSpec(
346
+ mesh=input_strategy.mesh,
347
+ placements=out_placements,
348
+ ),
349
+ input_specs=(input_spec,),
350
+ redistribute_cost=redistribute_cost,
351
+ )
352
+ )
353
+
354
+ return reduction_strategy
355
+
356
+
357
+ LINEAR_REDUCTION_OP_MAP = {
358
+ aten.all.default: "product",
359
+ aten.all.dim: "product",
360
+ aten.sum.default: "sum",
361
+ aten.sum.dim_IntList: "sum",
362
+ aten.any.default: "sum",
363
+ aten.any.dim: "sum",
364
+ aten.any.out: "sum",
365
+ # These are only valid when there is no padding
366
+ aten.prod.default: "product",
367
+ aten.prod.dim_int: "product",
368
+ aten.prod.int_out: "product",
369
+ # avg is only linear when there is no padding
370
+ aten.mean.default: "avg",
371
+ aten.mean.dim: "avg",
372
+ aten.mean.out: "avg",
373
+ aten.max.default: "max",
374
+ aten.max.dim: "max",
375
+ aten.max.out: "max",
376
+ aten.min.default: "min",
377
+ aten.min.dim: "min",
378
+ aten.min.out: "min",
379
+ aten.amax.default: "max",
380
+ aten.amax.out: "max",
381
+ aten.amin.default: "min",
382
+ aten.amin.out: "min",
383
+ # argmax and argmin is using custom hanndler leveraging linear reduction of max and min
384
+ aten.argmax.default: "max",
385
+ aten.argmin.default: "min",
386
+ }
387
+
388
+
389
+ @register_op_strategy(
390
+ list(LINEAR_REDUCTION_OP_MAP.keys()), schema_info=RuntimeSchemaInfo(1)
391
+ )
392
+ def linear_reduction_strategy(op_schema: OpSchema) -> OpStrategy:
393
+ args_schema = op_schema.args_schema
394
+ input_strategy = args_schema[0]
395
+ if not isinstance(input_strategy, OpStrategy):
396
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
397
+
398
+ dims = None
399
+ if len(op_schema.args_schema) > 1:
400
+ dims = _infer_reduction_dims(args_schema[1], input_strategy.ndim)
401
+
402
+ reduce_dims = list(range(input_strategy.ndim)) if dims is None else dims
403
+
404
+ keep_dim = len(op_schema.args_schema) > 2 and bool(op_schema.args_schema[2])
405
+ reduction_op = LINEAR_REDUCTION_OP_MAP[op_schema.op]
406
+ return common_reduction_strategy(
407
+ input_strategy,
408
+ reduce_dims,
409
+ keep_dim=keep_dim,
410
+ reduction_linear=True,
411
+ reduction_op=reduction_op,
412
+ )
413
+
414
+
415
+ @register_op_strategy(aten.cumsum.default, schema_info=RuntimeSchemaInfo(1))
416
+ def cumsum_strategy(op_schema: OpSchema) -> OpStrategy:
417
+ args_schema = op_schema.args_schema
418
+ input_strategy = args_schema[0]
419
+ if not isinstance(input_strategy, OpStrategy):
420
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
421
+ dim = args_schema[1]
422
+ if not isinstance(dim, int):
423
+ raise AssertionError(f"Expected int, got {type(dim)}")
424
+
425
+ return common_reduction_strategy(
426
+ input_strategy, [dim], keep_dim=True, reduction_linear=False
427
+ )
428
+
429
+
430
+ @register_op_strategy(
431
+ [
432
+ aten.std.correction,
433
+ aten.std.correction_out,
434
+ aten.var.correction,
435
+ aten.var.correction_out,
436
+ ],
437
+ schema_info=RuntimeSchemaInfo(1, ["keepdim"]),
438
+ )
439
+ def std_var_reduction_strategy(op_schema: OpSchema) -> OpStrategy:
440
+ args_schema = op_schema.args_schema
441
+ input_strategy = args_schema[0]
442
+ if not isinstance(input_strategy, OpStrategy):
443
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
444
+ dims = None
445
+ if len(op_schema.args_schema) > 1:
446
+ dims = _infer_reduction_dims(args_schema[1], input_strategy.ndim)
447
+
448
+ reduce_dims = list(range(input_strategy.ndim)) if dims is None else dims
449
+
450
+ keep_dim = cast(bool, op_schema.kwargs_schema.get("keepdim", False))
451
+ return common_reduction_strategy(
452
+ input_strategy, reduce_dims, keep_dim=keep_dim, reduction_linear=False
453
+ )
454
+
455
+
456
+ @register_op_strategy(
457
+ [aten.linalg_vector_norm.default], schema_info=RuntimeSchemaInfo(1)
458
+ )
459
+ def vector_norm_strategy(op_schema: OpSchema) -> OpStrategy:
460
+ args_schema = op_schema.args_schema
461
+ input_strategy = args_schema[0]
462
+ if not isinstance(input_strategy, OpStrategy):
463
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
464
+
465
+ norm_type = args_schema[1] if len(args_schema) > 1 else 2
466
+ if not isinstance(norm_type, (int, float, str)):
467
+ raise AssertionError(f"Expected int, float, or str, got {type(norm_type)}")
468
+ dim = args_schema[2] if len(args_schema) > 2 else None
469
+ keepdim = args_schema[3] if len(args_schema) > 3 else False
470
+ dims = _infer_reduction_dims(dim, input_strategy.ndim)
471
+ reduce_dims = list(range(input_strategy.ndim)) if dims is None else dims
472
+ return common_reduction_strategy(
473
+ input_strategy,
474
+ reduce_dims,
475
+ keep_dim=cast(bool, keepdim),
476
+ reduction_linear=True,
477
+ reduction_op=NormReduction(norm_type),
478
+ )
479
+
480
+
481
+ @register_op_strategy(
482
+ [aten._foreach_norm.Scalar], schema_info=RuntimeSchemaInfo(1, needs_pytree=True)
483
+ )
484
+ def foreach_norm_strategy(op_schema: OpSchema) -> TupleStrategy:
485
+ args_schema = op_schema.args_schema
486
+ input_tuple_strategy = args_schema[0]
487
+ if not isinstance(input_tuple_strategy, TupleStrategy):
488
+ raise AssertionError(
489
+ f"Expected TupleStrategy, got {type(input_tuple_strategy)}"
490
+ )
491
+ norm_type = args_schema[1] if len(args_schema) > 1 else 2
492
+ if not isinstance(norm_type, (int, float, str)):
493
+ raise AssertionError(f"Expected int, float, or str, got {type(norm_type)}")
494
+ output_tuple_strategy_children: list[OpStrategy] = []
495
+ for op_strategy in input_tuple_strategy.children:
496
+ if not isinstance(op_strategy, OpStrategy):
497
+ raise AssertionError(f"Expected OpStrategy, got {type(op_strategy)}")
498
+ reduce_dims = list(range(op_strategy.ndim))
499
+ output_strategy = common_reduction_strategy(
500
+ op_strategy,
501
+ reduce_dims,
502
+ reduction_linear=True,
503
+ reduction_op=NormReduction(norm_type),
504
+ )
505
+ output_tuple_strategy_children.append(output_strategy)
506
+ return TupleStrategy(output_tuple_strategy_children)
507
+
508
+
509
+ @register_op_strategy(
510
+ [aten._foreach_max.default], schema_info=RuntimeSchemaInfo(1, needs_pytree=True)
511
+ )
512
+ def foreach_max_strategy(op_schema: OpSchema) -> TupleStrategy:
513
+ """
514
+ Strategy for _foreach_max, which reduces each tensor in a list to its maximum value.
515
+ """
516
+ args_schema = op_schema.args_schema
517
+ input_tuple_strategy = args_schema[0]
518
+ if not isinstance(input_tuple_strategy, TupleStrategy):
519
+ raise AssertionError(
520
+ f"Expected TupleStrategy, got {type(input_tuple_strategy)}"
521
+ )
522
+ output_tuple_strategy_children: list[OpStrategy] = []
523
+ for op_strategy in input_tuple_strategy.children:
524
+ if not isinstance(op_strategy, OpStrategy):
525
+ raise AssertionError(f"Expected OpStrategy, got {type(op_strategy)}")
526
+ # Reduce all dimensions to get a scalar
527
+ reduce_dims = list(range(op_strategy.ndim))
528
+ output_strategy = common_reduction_strategy(
529
+ op_strategy,
530
+ reduce_dims,
531
+ reduction_linear=True,
532
+ reduction_op="max",
533
+ )
534
+ output_tuple_strategy_children.append(output_strategy)
535
+ return TupleStrategy(output_tuple_strategy_children)
536
+
537
+
538
+ @register_op_strategy(
539
+ [
540
+ aten._linalg_svd.default,
541
+ aten.linalg_qr.default,
542
+ # TODO: The diagonal ops can have an improved sharding strategy for
543
+ # shard placements that does not require redistributing to replicate.
544
+ aten.diagonal_copy.default,
545
+ aten.diag_embed.default,
546
+ aten.diag.default,
547
+ aten.diagonal.default,
548
+ aten.tril.default,
549
+ aten.triu.default,
550
+ aten._linalg_eigh.default,
551
+ aten.upsample_bicubic2d.default,
552
+ aten.upsample_bilinear2d.default,
553
+ aten.upsample_linear1d.default,
554
+ aten.upsample_nearest2d.default,
555
+ aten.upsample_trilinear3d.default,
556
+ # TODO: support the full F.interpolate set of options.
557
+ ],
558
+ schema_info=RuntimeSchemaInfo(1),
559
+ )
560
+ def linalg_replicate_strategy(op_schema: OpSchema) -> OpStrategy:
561
+ """
562
+ Since we do not have a simple way to compute some linear algebra operations
563
+ like SVD or QR decomposition, always fall back to replicate.
564
+ """
565
+ args_schema = op_schema.args_schema
566
+ input_strategy = args_schema[0]
567
+ if not isinstance(input_strategy, OpStrategy):
568
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
569
+ mesh = input_strategy.mesh
570
+
571
+ output_strategies: list[OpSpec] = []
572
+ for placement_strategy in input_strategy.strategies:
573
+ replicate_placements = tuple(Replicate() for _ in range(mesh.ndim))
574
+ replicate_spec = DTensorSpec(
575
+ mesh=mesh,
576
+ placements=replicate_placements,
577
+ tensor_meta=placement_strategy.output_spec.tensor_meta,
578
+ )
579
+ redistribute_cost = [
580
+ generate_redistribute_costs(input_strategy, replicate_spec)
581
+ ]
582
+ replicate_strategy = OpSpec(
583
+ output_specs=replicate_spec,
584
+ input_specs=(replicate_spec,),
585
+ redistribute_cost=redistribute_cost,
586
+ )
587
+ output_strategies.append(replicate_strategy)
588
+ return OpStrategy(output_strategies)
589
+
590
+
591
+ @register_op_strategy(
592
+ [aten._log_softmax.default, aten._softmax.default, aten._safe_softmax.default],
593
+ schema_info=RuntimeSchemaInfo(1),
594
+ )
595
+ def softmax_strategy(op_schema: OpSchema) -> OpStrategy:
596
+ input_strategy, softmax_dim, *_ = op_schema.args_schema
597
+ input_strategy = cast(OpStrategy, input_strategy)
598
+
599
+ softmax_dim = cast(int, softmax_dim)
600
+ softmax_dim = normalize_dim(softmax_dim, input_strategy.ndim)
601
+
602
+ output_strategy = OpStrategy([])
603
+ for input_placement_strategy in input_strategy.strategies:
604
+ redistribute_costs = []
605
+ input_src_spec = input_placement_strategy.output_spec
606
+
607
+ # make sure input is replicated along the softmax dim
608
+ input_target_spec = DTensorSpec(
609
+ mesh=input_strategy.mesh,
610
+ placements=replicate_reduction_dims(
611
+ input_src_spec.placements, [softmax_dim]
612
+ ),
613
+ tensor_meta=input_src_spec.tensor_meta,
614
+ )
615
+ redistribute_costs.append(
616
+ generate_redistribute_costs(input_strategy, input_target_spec)
617
+ )
618
+ output_target_spec = input_target_spec
619
+ output_strategy.strategies.append(
620
+ OpSpec(
621
+ output_specs=output_target_spec,
622
+ input_specs=[input_target_spec],
623
+ redistribute_cost=redistribute_costs,
624
+ )
625
+ )
626
+
627
+ return output_strategy
628
+
629
+
630
+ @register_op_strategy(
631
+ [
632
+ aten._log_softmax_backward_data.default,
633
+ aten._softmax_backward_data.default,
634
+ ],
635
+ schema_info=RuntimeSchemaInfo(2),
636
+ )
637
+ def softmax_backward_strategy(op_schema: OpSchema) -> OpStrategy:
638
+ grad_out_strategy, out_strategy, softmax_dim, _ = op_schema.args_schema
639
+ grad_out_strategy = cast(OpStrategy, grad_out_strategy)
640
+ out_strategy = cast(OpStrategy, out_strategy)
641
+ softmax_dim = cast(int, softmax_dim)
642
+ softmax_dim = normalize_dim(softmax_dim, grad_out_strategy.ndim)
643
+
644
+ grad_in_strategy = OpStrategy([])
645
+ for grad_out_placement_strat, out_placement_strat in zip(
646
+ grad_out_strategy.strategies, out_strategy.strategies
647
+ ):
648
+ # follow the sharding of the grad_out or out depending on which has more shards
649
+ grad_out_src_spec = grad_out_placement_strat.output_spec
650
+ out_src_spec = out_placement_strat.output_spec
651
+ src_spec = (
652
+ grad_out_src_spec
653
+ if grad_out_src_spec.num_shards >= out_src_spec.num_shards
654
+ else out_src_spec
655
+ )
656
+
657
+ # make sure inputs are replicated along the softmax dim
658
+ tgt_spec = DTensorSpec(
659
+ mesh=grad_out_strategy.mesh,
660
+ placements=replicate_reduction_dims(src_spec.placements, [softmax_dim]),
661
+ )
662
+ new_grad_out_spec = DTensorSpec(
663
+ mesh=tgt_spec.mesh,
664
+ placements=tgt_spec.placements,
665
+ tensor_meta=grad_out_src_spec.tensor_meta,
666
+ )
667
+ new_out_spec = DTensorSpec(
668
+ mesh=tgt_spec.mesh,
669
+ placements=tgt_spec.placements,
670
+ tensor_meta=out_src_spec.tensor_meta,
671
+ )
672
+ redist_grad_out_cost = generate_redistribute_costs(grad_out_strategy, tgt_spec)
673
+ redist_out_cost = generate_redistribute_costs(out_strategy, tgt_spec)
674
+ grad_in_strategy.strategies.append(
675
+ OpSpec(
676
+ output_specs=tgt_spec,
677
+ input_specs=(new_grad_out_spec, new_out_spec),
678
+ redistribute_cost=[redist_grad_out_cost, redist_out_cost],
679
+ )
680
+ )
681
+
682
+ return grad_in_strategy
683
+
684
+
685
+ @register_op_strategy(
686
+ [aten.nll_loss_forward.default, aten.nll_loss2d_forward.default],
687
+ schema_info=RuntimeSchemaInfo(3),
688
+ )
689
+ def nll_loss_forward_strategy(op_schema: OpSchema) -> OpStrategy:
690
+ mesh = op_schema.get_mesh_from_args()
691
+
692
+ if not len(op_schema.args_schema) == 5:
693
+ raise AssertionError(f"Expected 5 args, got {len(op_schema.args_schema)}")
694
+
695
+ (
696
+ input_strategy,
697
+ target_strategy,
698
+ weight_strategy,
699
+ reduction,
700
+ _,
701
+ ) = op_schema.args_schema
702
+ input_strategy = cast(OpStrategy, input_strategy)
703
+ target_strategy = cast(OpStrategy, target_strategy)
704
+ reduction = cast(int, reduction)
705
+
706
+ input_shape = input_strategy.shape
707
+ channel_dim = 1 if len(input_shape) >= 2 else 0
708
+
709
+ output_strategy = OpStrategy([])
710
+ for idx, input_placement_strategy in enumerate(input_strategy.strategies):
711
+ op_args_target_specs = []
712
+ redistribute_costs = []
713
+
714
+ # make sure input is replicated along the channel dim
715
+ input_src_spec = input_placement_strategy.output_spec
716
+ input_expected_spec = DTensorSpec(
717
+ mesh=mesh,
718
+ placements=replicate_reduction_dims(
719
+ input_src_spec.placements, [channel_dim]
720
+ ),
721
+ tensor_meta=input_src_spec.tensor_meta,
722
+ )
723
+ op_args_target_specs.append(input_expected_spec)
724
+ redistribute_costs.append(
725
+ generate_redistribute_costs(input_strategy, input_expected_spec)
726
+ )
727
+
728
+ # target doesn't have channel dim, and it follows input on other dims
729
+ target_src_spec = target_strategy.strategies[idx].output_spec
730
+ target_expected_spec = DTensorSpec(
731
+ mesh=mesh,
732
+ placements=_skip_dim(input_expected_spec.placements, channel_dim),
733
+ tensor_meta=target_src_spec.tensor_meta,
734
+ )
735
+ op_args_target_specs.append(target_expected_spec)
736
+ redistribute_costs.append(
737
+ generate_redistribute_costs(target_strategy, target_expected_spec)
738
+ )
739
+
740
+ # weight tensor, if given, has to be a Tensor of size input_shape[channel_dim]
741
+ # make sure it is replicated
742
+ if weight_strategy is not None:
743
+ if not isinstance(weight_strategy, OpStrategy):
744
+ raise AssertionError(
745
+ f"Expected OpStrategy, got {type(weight_strategy)}"
746
+ )
747
+ weight_src_spec = weight_strategy.strategies[idx].output_spec
748
+ weight_expected_spec = DTensorSpec(
749
+ mesh=mesh,
750
+ placements=_replicate_dims_start_at(weight_src_spec.placements),
751
+ tensor_meta=weight_src_spec.tensor_meta,
752
+ )
753
+ op_args_target_specs.append(weight_expected_spec)
754
+ redistribute_costs.append(
755
+ generate_redistribute_costs(weight_strategy, weight_expected_spec)
756
+ )
757
+
758
+ if reduction == Reduction.NONE.value:
759
+ output_expected_spec = target_expected_spec
760
+ total_weight_expected_spec = DTensorSpec(
761
+ mesh=mesh, placements=tuple([Replicate()] * mesh.ndim)
762
+ )
763
+ else:
764
+ if reduction == Reduction.MEAN.value:
765
+ reduction_op = "avg"
766
+ if not is_tensor_evenly_shardable(
767
+ target_expected_spec.shape, target_expected_spec
768
+ ):
769
+ raise ValueError(
770
+ "The intermediate results of nll_loss cannot be evenly sharded, \
771
+ resulting in biased mean result."
772
+ )
773
+ else: # reduction == Reduction.SUM.value:
774
+ reduction_op = "sum"
775
+ reduce_dims = list(range(target_expected_spec.ndim))
776
+ reduce_dims_map = _infer_reduce_dims_map(
777
+ reduce_dims, target_expected_spec.ndim, keep_dim=False
778
+ )
779
+ out_placements = map_placements_after_reduction(
780
+ target_expected_spec.placements,
781
+ reduce_dims,
782
+ reduce_dims_map,
783
+ reduction_op,
784
+ )
785
+ output_expected_spec = DTensorSpec(
786
+ mesh=mesh,
787
+ placements=out_placements,
788
+ )
789
+
790
+ # whether reduction is sum or mean, the total weight has to be summed up if not replicated
791
+ total_weight_placements = map_placements_after_reduction(
792
+ target_expected_spec.placements,
793
+ reduce_dims,
794
+ reduce_dims_map,
795
+ "sum",
796
+ )
797
+ total_weight_expected_spec = DTensorSpec(
798
+ mesh=mesh,
799
+ placements=total_weight_placements,
800
+ )
801
+
802
+ output_strategy.strategies.append(
803
+ OpSpec(
804
+ output_specs=(output_expected_spec, total_weight_expected_spec),
805
+ input_specs=op_args_target_specs,
806
+ redistribute_cost=redistribute_costs,
807
+ )
808
+ )
809
+
810
+ return output_strategy
811
+
812
+
813
+ @register_op_strategy(
814
+ [aten.nll_loss_backward.default, aten.nll_loss2d_backward.default],
815
+ schema_info=RuntimeSchemaInfo(4),
816
+ )
817
+ def nll_loss_backward_strategy(op_schema: OpSchema) -> OpStrategy:
818
+ # backward op does not need to validate the mesh since forward op has already done it
819
+ mesh = op_schema.get_mesh_from_args(validate=False)
820
+
821
+ if not len(op_schema.args_schema) == 7:
822
+ raise AssertionError(f"Expected 7 args, got {len(op_schema.args_schema)}")
823
+ (
824
+ grad_out_strategy,
825
+ input_strategy,
826
+ target_strategy,
827
+ weight_strategy,
828
+ reduction,
829
+ _,
830
+ total_weight_strategy,
831
+ ) = op_schema.args_schema
832
+ grad_out_strategy = cast(OpStrategy, grad_out_strategy)
833
+ input_strategy = cast(OpStrategy, input_strategy)
834
+ target_strategy = cast(OpStrategy, target_strategy)
835
+ reduction = cast(int, reduction)
836
+ total_weight_strategy = cast(OpStrategy, total_weight_strategy)
837
+
838
+ input_shape = input_strategy.shape
839
+ channel_dim = 1 if len(input_shape) >= 2 else 0
840
+
841
+ grad_in_strategy = OpStrategy([])
842
+ for idx, input_placement_strategy in enumerate(input_strategy.strategies):
843
+ op_args_target_specs = []
844
+ redistribute_costs = []
845
+
846
+ # make sure input is replicated along the channel dim
847
+ input_src_spec = input_placement_strategy.output_spec
848
+ input_expected_spec = DTensorSpec(
849
+ mesh=mesh,
850
+ placements=replicate_reduction_dims(
851
+ input_src_spec.placements, [channel_dim]
852
+ ),
853
+ tensor_meta=input_src_spec.tensor_meta,
854
+ )
855
+ op_args_target_specs.append(input_expected_spec)
856
+ redistribute_costs.append(
857
+ generate_redistribute_costs(input_strategy, input_expected_spec)
858
+ )
859
+
860
+ # target doesn't have channel dim, and it follows input on other dims
861
+ target_src_spec = target_strategy.strategies[idx].output_spec
862
+ target_expected_spec = DTensorSpec(
863
+ mesh=mesh,
864
+ placements=_skip_dim(input_expected_spec.placements, channel_dim),
865
+ tensor_meta=target_src_spec.tensor_meta,
866
+ )
867
+ op_args_target_specs.append(target_expected_spec)
868
+ redistribute_costs.append(
869
+ generate_redistribute_costs(target_strategy, target_expected_spec)
870
+ )
871
+
872
+ # grad_out follows target if there is no reduction;
873
+ # otherwise, it should be a replicated scalar.
874
+ grad_out_src_spec = grad_out_strategy.strategies[idx].output_spec
875
+ if reduction == Reduction.NONE.value:
876
+ grad_out_expected_spec = target_expected_spec
877
+ else:
878
+ grad_out_expected_spec = DTensorSpec(
879
+ mesh=mesh,
880
+ placements=_replicate_dims_start_at(grad_out_src_spec.placements),
881
+ tensor_meta=grad_out_src_spec.tensor_meta,
882
+ )
883
+ op_args_target_specs.insert(0, grad_out_expected_spec)
884
+ redistribute_costs.insert(
885
+ 0, generate_redistribute_costs(grad_out_strategy, grad_out_expected_spec)
886
+ )
887
+
888
+ # weight tensor, if given, has to be a Tensor of size input_shape[channel_dim]
889
+ # make sure it is replicated
890
+ if weight_strategy is not None:
891
+ if not isinstance(weight_strategy, OpStrategy):
892
+ raise AssertionError(
893
+ f"Expected OpStrategy, got {type(weight_strategy)}"
894
+ )
895
+ weight_src_spec = weight_strategy.strategies[idx].output_spec
896
+ weight_expected_spec = DTensorSpec(
897
+ mesh=mesh,
898
+ placements=_replicate_dims_start_at(weight_src_spec.placements),
899
+ tensor_meta=weight_src_spec.tensor_meta,
900
+ )
901
+ op_args_target_specs.append(weight_expected_spec)
902
+ redistribute_costs.append(
903
+ generate_redistribute_costs(weight_strategy, weight_expected_spec)
904
+ )
905
+
906
+ # total_weight should always be replicated
907
+ total_weight_src_spec = total_weight_strategy.strategies[idx].output_spec
908
+ total_weight_expected_spec = DTensorSpec(
909
+ mesh=mesh,
910
+ placements=_replicate_dims_start_at(total_weight_src_spec.placements),
911
+ tensor_meta=total_weight_src_spec.tensor_meta,
912
+ )
913
+ op_args_target_specs.append(total_weight_expected_spec)
914
+ redistribute_costs.append(
915
+ generate_redistribute_costs(
916
+ total_weight_strategy, total_weight_expected_spec
917
+ )
918
+ )
919
+
920
+ grad_in_expected_spec = input_expected_spec
921
+ grad_in_strategy.strategies.append(
922
+ OpSpec(
923
+ output_specs=grad_in_expected_spec,
924
+ input_specs=op_args_target_specs,
925
+ redistribute_cost=redistribute_costs,
926
+ )
927
+ )
928
+
929
+ return grad_in_strategy
930
+
931
+
932
+ def _common_norm_forward_strategy(
933
+ op_schema: OpSchema,
934
+ rms_norm: bool = False,
935
+ ) -> OpStrategy:
936
+ """Common forward strategy logic for layer_norm and rms_norm."""
937
+ mesh = op_schema.get_mesh_from_args()
938
+
939
+ if not rms_norm:
940
+ # layer_norm args: input, normalized_shape, weight, bias, eps
941
+ # for None weight and bias, their corresponding objects will
942
+ # be None as well. layer_norm_strategy returns one OpStrategy
943
+ # for the triple return values (out, mean, rstd).
944
+ if not len(op_schema.args_schema) == 5:
945
+ raise AssertionError(f"Expected 5 args, got {len(op_schema.args_schema)}")
946
+ (
947
+ input_strategy,
948
+ normalized_shape,
949
+ weight_strategy,
950
+ bias_strategy,
951
+ _,
952
+ ) = op_schema.args_schema
953
+ else:
954
+ # rms_norm args: input, normalized_shape, weight, eps
955
+ if not len(op_schema.args_schema) == 4:
956
+ raise AssertionError(f"Expected 4 args, got {len(op_schema.args_schema)}")
957
+ (
958
+ input_strategy,
959
+ normalized_shape,
960
+ weight_strategy,
961
+ _,
962
+ ) = op_schema.args_schema
963
+ bias_strategy = None
964
+
965
+ # the current norm implementation requires that all
966
+ # input DTensor's sharding must be in form of OpStrategy
967
+ if not isinstance(input_strategy, OpStrategy):
968
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
969
+ if not isinstance(normalized_shape, (int, Sequence, torch.Size)):
970
+ raise AssertionError(
971
+ f"Expected int, Sequence, or torch.Size, got {type(normalized_shape)}"
972
+ )
973
+ normalized_size = normalize_to_torch_size(normalized_shape)
974
+
975
+ input_ndim = input_strategy.ndim
976
+ axis = input_ndim - len(normalized_size)
977
+
978
+ # we use OpStrategy because the output values (out, mean, rstd)
979
+ # should have the same placements
980
+ output_strategy = OpStrategy([])
981
+ for idx, input_placement_strategy in enumerate(input_strategy.strategies):
982
+ op_args_target_specs = []
983
+ redistribute_costs = []
984
+ input_src_spec = input_placement_strategy.output_spec
985
+
986
+ # for the input tensor, we replicate it on the inner dims if necessary
987
+ # TODO: we can avoid forcing the redistribution once we figure out
988
+ # how to decompose layer norm
989
+ input_target_spec = DTensorSpec(
990
+ mesh=mesh,
991
+ placements=_replicate_dims_start_at(input_src_spec.placements, axis),
992
+ tensor_meta=input_src_spec.tensor_meta,
993
+ )
994
+ op_args_target_specs.append(input_target_spec)
995
+ redistribute_costs.append(
996
+ generate_redistribute_costs(input_strategy, input_target_spec)
997
+ )
998
+
999
+ if weight_strategy is not None:
1000
+ if not isinstance(weight_strategy, OpStrategy):
1001
+ raise AssertionError(
1002
+ f"Expected OpStrategy, got {type(weight_strategy)}"
1003
+ )
1004
+ weight_src_spec = weight_strategy.strategies[idx].output_spec
1005
+
1006
+ # for the weight tensor, we replicate it on all dims if necessary
1007
+ # TODO: we can avoid forcing the redistribution once we figure out
1008
+ # how to decompose layer norm
1009
+ weight_target_spec = DTensorSpec(
1010
+ mesh=mesh,
1011
+ placements=_replicate_dims_start_at(weight_src_spec.placements),
1012
+ tensor_meta=weight_src_spec.tensor_meta,
1013
+ )
1014
+ op_args_target_specs.append(weight_target_spec)
1015
+ redistribute_costs.append(
1016
+ generate_redistribute_costs(weight_strategy, weight_target_spec)
1017
+ )
1018
+
1019
+ if bias_strategy is not None:
1020
+ if not isinstance(bias_strategy, OpStrategy):
1021
+ raise AssertionError(f"Expected OpStrategy, got {type(bias_strategy)}")
1022
+ bias_src_spec = bias_strategy.strategies[idx].output_spec
1023
+
1024
+ # for the bias tensor, we replicate it on all dims if necessary
1025
+ # TODO: we can avoid forcing the redistribution once we figure out
1026
+ # how to decompose layer norm
1027
+ bias_target_spec = DTensorSpec(
1028
+ mesh=mesh,
1029
+ placements=_replicate_dims_start_at(bias_src_spec.placements),
1030
+ tensor_meta=bias_src_spec.tensor_meta,
1031
+ )
1032
+ op_args_target_specs.append(bias_target_spec)
1033
+ redistribute_costs.append(
1034
+ generate_redistribute_costs(bias_strategy, bias_target_spec)
1035
+ )
1036
+
1037
+ # the output spec is the same as input spec
1038
+ output_target_spec = input_target_spec
1039
+ output_strategy.strategies.append(
1040
+ OpSpec(
1041
+ output_specs=output_target_spec,
1042
+ input_specs=op_args_target_specs,
1043
+ redistribute_cost=redistribute_costs,
1044
+ )
1045
+ )
1046
+
1047
+ return output_strategy
1048
+
1049
+
1050
+ @register_op_strategy(
1051
+ [aten.native_layer_norm.default],
1052
+ schema_info=RuntimeSchemaInfo(1),
1053
+ )
1054
+ def layer_norm_strategy(op_schema: OpSchema) -> OpStrategy:
1055
+ return _common_norm_forward_strategy(op_schema)
1056
+
1057
+
1058
+ @register_op_strategy(
1059
+ [aten._fused_rms_norm.default],
1060
+ schema_info=RuntimeSchemaInfo(1),
1061
+ )
1062
+ def fused_rms_norm_strategy(op_schema: OpSchema) -> OpStrategy:
1063
+ return _common_norm_forward_strategy(op_schema, rms_norm=True)
1064
+
1065
+
1066
+ def _common_norm_backward_strategy(
1067
+ op_schema: OpSchema,
1068
+ rms_norm: bool = False,
1069
+ ) -> OpStrategy:
1070
+ """Common backward strategy logic for layer_norm and rms_norm."""
1071
+ # backward op does not need to validate the mesh since forward op has already done it
1072
+ mesh = op_schema.get_mesh_from_args(validate=False)
1073
+
1074
+ if not rms_norm:
1075
+ # layer_norm args: grad_out, input, normalized_shape, mean, rstd,
1076
+ # weight, bias, output_mask. For None weight and bias, their
1077
+ # corresponding objects will be None as well.
1078
+ if not len(op_schema.args_schema) == 8:
1079
+ raise AssertionError(f"Expected 8 args, got {len(op_schema.args_schema)}")
1080
+ (
1081
+ grad_out_strategy,
1082
+ input_strategy,
1083
+ normalized_shape,
1084
+ mean_strategy,
1085
+ rstd_strategy,
1086
+ weight_strategy,
1087
+ bias_strategy,
1088
+ output_mask,
1089
+ ) = op_schema.args_schema
1090
+ else:
1091
+ # rms_norm args: grad_out, input, normalized_shape, rstd,
1092
+ if not len(op_schema.args_schema) == 6:
1093
+ raise AssertionError(f"Expected 6 args, got {len(op_schema.args_schema)}")
1094
+ (
1095
+ grad_out_strategy,
1096
+ input_strategy,
1097
+ normalized_shape,
1098
+ rstd_strategy,
1099
+ weight_strategy,
1100
+ output_mask,
1101
+ ) = op_schema.args_schema
1102
+ mean_strategy = None
1103
+ bias_strategy = None
1104
+
1105
+ if not isinstance(grad_out_strategy, OpStrategy):
1106
+ raise AssertionError(f"Expected OpStrategy, got {type(grad_out_strategy)}")
1107
+ if not isinstance(input_strategy, OpStrategy):
1108
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
1109
+ if not isinstance(rstd_strategy, OpStrategy):
1110
+ raise AssertionError(f"Expected OpStrategy, got {type(rstd_strategy)}")
1111
+ if mean_strategy is not None:
1112
+ if not isinstance(mean_strategy, OpStrategy):
1113
+ raise AssertionError(f"Expected OpStrategy, got {type(mean_strategy)}")
1114
+
1115
+ if not isinstance(normalized_shape, (int, Sequence, torch.Size)):
1116
+ raise AssertionError(
1117
+ f"Expected int, Sequence, or torch.Size, got {type(normalized_shape)}"
1118
+ )
1119
+ normalized_size = normalize_to_torch_size(normalized_shape)
1120
+ input_ndim = input_strategy.ndim
1121
+ axis = input_ndim - len(normalized_size)
1122
+ outer_dims = list(range(axis))
1123
+
1124
+ if not rms_norm:
1125
+ if not (isinstance(output_mask, list) and len(output_mask) == 3):
1126
+ raise AssertionError(
1127
+ f"Expected output_mask to be list of length 3, got {type(output_mask)} "
1128
+ f"of length {len(output_mask) if isinstance(output_mask, list) else 'N/A'}"
1129
+ )
1130
+ else:
1131
+ if not (isinstance(output_mask, list) and len(output_mask) == 2):
1132
+ raise AssertionError(
1133
+ f"Expected output_mask to be list of length 2, got {type(output_mask)} "
1134
+ f"of length {len(output_mask) if isinstance(output_mask, list) else 'N/A'}"
1135
+ )
1136
+
1137
+ # output tuple: (d_input, d_weight[, d_bias])
1138
+ out_tuple_strategy = OpStrategy([])
1139
+ for idx, input_placement_strategy in enumerate(input_strategy.strategies):
1140
+ # args for OpSpec
1141
+ output_specs_list: list[DTensorSpec | None] = []
1142
+ input_specs_list: list[DTensorSpec] = []
1143
+ redistribute_costs = []
1144
+
1145
+ input_src_spec = input_placement_strategy.output_spec
1146
+ # arg: grad_out
1147
+ # TODO: change the strategy to the following rule.
1148
+ # d_input is basically a product of element-wise mul of
1149
+ # grad_out, rstd, and normalized input, among which rstd
1150
+ # and normalized input (x_hat) should have the same sharding
1151
+ # placements, and grad_out's sharding is determined by the
1152
+ # pointwise result of x_hat and weight/bias.
1153
+ # TODO: now grad_out spec follows input spec. we may need
1154
+ # to change it to apply a pointwise rule over grad_out,
1155
+ # input, and weight.
1156
+ grad_out_target_spec = DTensorSpec(
1157
+ mesh=mesh,
1158
+ placements=_replicate_dims_start_at(input_src_spec.placements, axis),
1159
+ tensor_meta=input_src_spec.tensor_meta,
1160
+ )
1161
+ input_specs_list.append(grad_out_target_spec)
1162
+ redistribute_costs.append(
1163
+ generate_redistribute_costs(grad_out_strategy, grad_out_target_spec)
1164
+ )
1165
+ output_specs_list.append(grad_out_target_spec if output_mask[0] else None)
1166
+
1167
+ # arg: input
1168
+ input_target_spec = DTensorSpec(
1169
+ mesh=mesh,
1170
+ placements=_replicate_dims_start_at(input_src_spec.placements, axis),
1171
+ tensor_meta=input_src_spec.tensor_meta,
1172
+ )
1173
+ input_specs_list.append(input_target_spec)
1174
+ redistribute_costs.append(
1175
+ generate_redistribute_costs(input_strategy, input_target_spec)
1176
+ )
1177
+
1178
+ # arg: mean
1179
+ if not rms_norm:
1180
+ if mean_strategy is None:
1181
+ raise AssertionError("Expected mean_strategy to not be None")
1182
+ mean_src_spec = mean_strategy.strategies[idx].output_spec
1183
+ input_specs_list.append(mean_src_spec)
1184
+ redistribute_costs.append([0.0 for _ in mean_strategy.strategies])
1185
+
1186
+ # arg: rstd
1187
+ rstd_src_spec = rstd_strategy.strategies[idx].output_spec
1188
+ input_specs_list.append(rstd_src_spec)
1189
+ redistribute_costs.append([0.0 for _ in rstd_strategy.strategies])
1190
+
1191
+ def _add_target_input_spec(strategy) -> DTensorSpec:
1192
+ # shared logic for setting the weight and bias target input specs
1193
+ if not isinstance(strategy, OpStrategy):
1194
+ raise AssertionError(f"Expected OpStrategy, got {type(strategy)}")
1195
+ src_spec = strategy.strategies[idx].output_spec
1196
+ # no need to redistribute since they should be replicated in forward pass
1197
+ input_specs_list.append(src_spec)
1198
+ redistribute_costs.append([0.0 for _ in strategy.strategies])
1199
+ return src_spec
1200
+
1201
+ # arg: weight
1202
+ # d_weight = sum(grad_out * (input - mean) / rstd, outer_dim, keepdim=False)
1203
+ # For RMS norm, mean is 0, so it's just: sum(grad_out * input / rstd, outer_dim, keepdim=False)
1204
+ if weight_strategy is not None:
1205
+ weight_src_spec = _add_target_input_spec(weight_strategy)
1206
+ # TODO: now d_weight spec follows input spec w/ a reduction.
1207
+ # we may need to change to a pointwise rule over grad_out and
1208
+ # input, then apply a reduction.
1209
+ inp_placements = _replicate_dims_start_at(input_src_spec.placements, axis)
1210
+ reduce_dims_map = _infer_reduce_dims_map(
1211
+ outer_dims, input_src_spec.ndim, False
1212
+ )
1213
+ out_placements = map_placements_after_reduction(
1214
+ inp_placements, outer_dims, reduce_dims_map, "sum"
1215
+ )
1216
+ weight_out_spec = DTensorSpec(
1217
+ mesh=mesh,
1218
+ placements=out_placements,
1219
+ tensor_meta=weight_src_spec.tensor_meta,
1220
+ )
1221
+ output_specs_list.append(weight_out_spec if output_mask[1] else None)
1222
+ else:
1223
+ if not rms_norm:
1224
+ error_msg = "output_mask[1] should not be `True` while weight argument is `None` in native_layer_norm_backward."
1225
+ else:
1226
+ error_msg = "output_mask[1] should not be `True` while weight argument is `None` in _fused_rms_norm_backward."
1227
+ if output_mask[1] is not False:
1228
+ raise AssertionError(error_msg)
1229
+ output_specs_list.append(None)
1230
+
1231
+ # arg: bias
1232
+ # d_bias = sum(grad_out, outer_dim, keepdim=False)
1233
+ if not rms_norm:
1234
+ if bias_strategy is not None:
1235
+ bias_src_spec = _add_target_input_spec(bias_strategy)
1236
+ # d_bias spec follows a reduction over grad_out
1237
+ inp_placements = _replicate_dims_start_at(
1238
+ grad_out_target_spec.placements, axis
1239
+ )
1240
+ reduce_dims_map = _infer_reduce_dims_map(
1241
+ outer_dims, grad_out_target_spec.ndim, False
1242
+ )
1243
+ out_placements = map_placements_after_reduction(
1244
+ inp_placements, outer_dims, reduce_dims_map, "sum"
1245
+ )
1246
+ bias_out_spec = DTensorSpec(
1247
+ mesh=mesh,
1248
+ placements=out_placements,
1249
+ tensor_meta=bias_src_spec.tensor_meta,
1250
+ )
1251
+ output_specs_list.append(bias_out_spec if output_mask[2] else None)
1252
+ else:
1253
+ if output_mask[2] is not False:
1254
+ raise AssertionError(
1255
+ "output_mask[2] should not be `True` while bias argument is `None` in native_layer_norm_backward."
1256
+ )
1257
+ output_specs_list.append(None)
1258
+
1259
+ out_tuple_strategy.strategies.append(
1260
+ OpSpec(
1261
+ output_specs=tuple(output_specs_list),
1262
+ input_specs=input_specs_list,
1263
+ redistribute_cost=redistribute_costs,
1264
+ )
1265
+ )
1266
+
1267
+ return out_tuple_strategy
1268
+
1269
+
1270
+ @register_op_strategy(
1271
+ [aten.native_layer_norm_backward.default],
1272
+ schema_info=RuntimeSchemaInfo(2),
1273
+ )
1274
+ def layer_norm_bwd_strategy(op_schema: OpSchema) -> OpStrategy:
1275
+ return _common_norm_backward_strategy(op_schema)
1276
+
1277
+
1278
+ @register_op_strategy(
1279
+ [aten._fused_rms_norm_backward.default],
1280
+ schema_info=RuntimeSchemaInfo(2),
1281
+ )
1282
+ def fused_rms_norm_bwd_strategy(op_schema: OpSchema) -> OpStrategy:
1283
+ return _common_norm_backward_strategy(op_schema, rms_norm=True)
1284
+
1285
+
1286
+ def sort_strategy(op_schema: OpSchema, sort_dim: int) -> OpStrategy:
1287
+ input_strategy = cast(OpStrategy, op_schema.args_schema[0])
1288
+ sort_dim = normalize_dim(sort_dim, input_strategy.ndim)
1289
+ single_mesh_dim_strategies = []
1290
+ all_replicate: PlacementList = [Replicate()] * 3
1291
+ single_mesh_dim_strategies.append(all_replicate)
1292
+ for dim in range(input_strategy.ndim):
1293
+ if dim != sort_dim:
1294
+ dim_shardings: PlacementList = [Shard(dim)] * 3
1295
+ single_mesh_dim_strategies.append(dim_shardings)
1296
+ return expand_to_full_mesh_op_strategy(
1297
+ input_strategy.mesh, op_schema, single_mesh_dim_strategies, input_index=2
1298
+ )
1299
+
1300
+
1301
+ @register_op_strategy(
1302
+ [aten.topk.default],
1303
+ schema_info=RuntimeSchemaInfo(2),
1304
+ )
1305
+ def topk_strategy(op_schema: OpSchema) -> OpStrategy:
1306
+ topk_dim = (
1307
+ cast(int, op_schema.args_schema[2]) if len(op_schema.args_schema) > 2 else -1
1308
+ )
1309
+ return sort_strategy(op_schema, topk_dim)
1310
+
1311
+
1312
+ @register_op_strategy(
1313
+ aten.sort.default,
1314
+ schema_info=RuntimeSchemaInfo(
1315
+ 1,
1316
+ ),
1317
+ )
1318
+ def sort_default_strategy(op_schema: OpSchema) -> OpStrategy:
1319
+ # mostly copy paste from topk_strategy
1320
+ input_strategy = op_schema.args_schema[0]
1321
+ if not isinstance(input_strategy, OpStrategy):
1322
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
1323
+ sort_dim = -1
1324
+ if len(op_schema.args_schema) > 1:
1325
+ sort_dim = cast(int, op_schema.args_schema[1])
1326
+ return sort_strategy(op_schema, sort_dim)
1327
+
1328
+
1329
+ @register_op_strategy(
1330
+ aten.sort.stable,
1331
+ schema_info=RuntimeSchemaInfo(
1332
+ 1,
1333
+ static_kwargkey=["dim", "descending", "stable"],
1334
+ ),
1335
+ )
1336
+ def sort_stable_strategy(op_schema: OpSchema) -> OpStrategy:
1337
+ # mostly copy paste from topk_strategy
1338
+ input_strategy = op_schema.args_schema[0]
1339
+ if not isinstance(input_strategy, OpStrategy):
1340
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
1341
+ sort_dim = -1
1342
+ if "dim" in op_schema.kwargs_schema:
1343
+ sort_dim = cast(int, op_schema.kwargs_schema["dim"])
1344
+ return sort_strategy(op_schema, sort_dim)
1345
+
1346
+
1347
+ @register_op_strategy(
1348
+ [aten.histc.default],
1349
+ # strategy choice depends on the value of 'min' and 'max' kwargs, which are position 2 and 3
1350
+ schema_info=RuntimeSchemaInfo(2),
1351
+ )
1352
+ def histc_strategy(op_schema: OpSchema) -> OpStrategy:
1353
+ input_strategy = cast(OpStrategy, op_schema.args_schema[0])
1354
+ single_mesh_dim_strategies: list[PlacementList] = []
1355
+ single_mesh_dim_strategies.append([Replicate(), Replicate()])
1356
+
1357
+ # histc can support sharded input and partial output on any input dim, provided the min and max
1358
+ # values are user-specified. If not user-specified, the true min and max of the data in each local
1359
+ # tensor will be used to compute bin boundaries, which will not be the same across ranks, leading to
1360
+ # an incorrect final result
1361
+ if len(op_schema.args_schema) == 4:
1362
+ for dim in range(input_strategy.ndim):
1363
+ dim_shardings: PlacementList = [Partial(), Shard(dim)]
1364
+ single_mesh_dim_strategies.append(dim_shardings)
1365
+
1366
+ return expand_to_full_mesh_op_strategy(
1367
+ input_strategy.mesh, op_schema, single_mesh_dim_strategies
1368
+ )
1369
+
1370
+
1371
+ @register_op_strategy(
1372
+ [aten.logsumexp.default],
1373
+ schema_info=RuntimeSchemaInfo(
1374
+ # static_argnum is the position where non-Tensor args beings.
1375
+ static_argnum=1,
1376
+ # static_kwargkey is the name of kwargs to hash (which determines
1377
+ # whether sharding prop can be cached).
1378
+ static_kwargkey=["keepdim"],
1379
+ ),
1380
+ )
1381
+ def logsumexp_strategy(op_schema: OpSchema) -> OpStrategy:
1382
+ """Implements the sharding propagation strategy for logsumexp."""
1383
+
1384
+ # args_schema contains all but the DTensor args (e.g., dim, keepdim).
1385
+ args_schema = op_schema.args_schema
1386
+ if not len(args_schema) > 1:
1387
+ raise AssertionError(
1388
+ f"Expected more than 1 arg (input and dim are required), got {len(args_schema)}"
1389
+ )
1390
+
1391
+ input_strategy = args_schema[0]
1392
+ if not isinstance(input_strategy, OpStrategy):
1393
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
1394
+
1395
+ dims_arg = args_schema[1]
1396
+ reduce_dims = _infer_reduction_dims(dims_arg, input_strategy.ndim)
1397
+ if reduce_dims is None:
1398
+ raise AssertionError("Expected reduce_dims to not be None")
1399
+
1400
+ keep_dim = cast(bool, op_schema.kwargs_schema.get("keepdim", False))
1401
+ return common_reduction_strategy(
1402
+ input_strategy,
1403
+ reduce_dims,
1404
+ keep_dim=keep_dim,
1405
+ reduction_linear=False,
1406
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_matrix_ops.py ADDED
@@ -0,0 +1,1087 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ # implement matrix related ops for distributed tensor
3
+
4
+
5
+ import torch
6
+ from torch.distributed.device_mesh import DeviceMesh
7
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
8
+ from torch.distributed.tensor._op_schema import (
9
+ OpSchema,
10
+ OpSpec,
11
+ OpStrategy,
12
+ PlacementList,
13
+ RuntimeSchemaInfo,
14
+ )
15
+ from torch.distributed.tensor._ops._einsum_strategy import gen_einsum_strategies
16
+ from torch.distributed.tensor._ops.registration import register_op_strategy
17
+ from torch.distributed.tensor._ops.utils import (
18
+ expand_to_full_mesh_op_strategy,
19
+ generate_redistribute_costs,
20
+ infer_broadcast_dims_map,
21
+ is_tensor_shardable,
22
+ map_placements_after_broadcast,
23
+ prod,
24
+ )
25
+ from torch.distributed.tensor._utils import (
26
+ compute_local_shape_and_global_offset,
27
+ compute_local_stride,
28
+ )
29
+ from torch.distributed.tensor.placement_types import (
30
+ Partial,
31
+ Placement,
32
+ Replicate,
33
+ Shard,
34
+ )
35
+
36
+
37
+ aten = torch.ops.aten
38
+
39
+
40
+ @register_op_strategy(aten.t.default)
41
+ def transpose_strategy(op_schema: OpSchema) -> OpStrategy:
42
+ self_strategy = op_schema.args_schema[0]
43
+ if not isinstance(self_strategy, OpStrategy):
44
+ raise AssertionError(f"Expected OpStrategy, got {type(self_strategy)}")
45
+
46
+ transpose_strategies = []
47
+ for input_strategy in self_strategy.strategies:
48
+ input_spec = input_strategy.output_spec
49
+ # follow the input spec but transpose the Shard placements
50
+ output_placements = [
51
+ Shard(1 - p.dim) if isinstance(p, Shard) else p
52
+ for p in input_spec.placements
53
+ ]
54
+ transpose_strategy = OpSpec(
55
+ output_specs=DTensorSpec(
56
+ mesh=input_strategy.mesh,
57
+ placements=tuple(output_placements),
58
+ ),
59
+ input_specs=(input_strategy.output_spec,),
60
+ )
61
+ transpose_strategies.append(transpose_strategy)
62
+
63
+ return OpStrategy(strategies=transpose_strategies)
64
+
65
+
66
+ def _mm_like_strategy(
67
+ mm_equation: str, mesh: DeviceMesh, op_schema: OpSchema
68
+ ) -> OpStrategy:
69
+ self_strategy, mat2_strategy = op_schema.args_schema
70
+ if not isinstance(self_strategy, OpStrategy):
71
+ raise AssertionError(f"Expected OpStrategy, got {type(self_strategy)}")
72
+ if not isinstance(mat2_strategy, OpStrategy):
73
+ raise AssertionError(f"Expected OpStrategy, got {type(mat2_strategy)}")
74
+ # generate all possible strategies for mm
75
+ mm_strategy = gen_einsum_strategies(mm_equation, mesh)
76
+ # filter out invalid strategies and associate costs
77
+ strategies = mm_strategy.strategies
78
+ filtered_strategies = []
79
+ for strtg in strategies:
80
+ if strtg.input_specs is None:
81
+ raise AssertionError(
82
+ f"Expected input_specs to be not None, got {strtg.input_specs}"
83
+ )
84
+ self_spec = strtg.input_specs[0]
85
+ mat2_spec = strtg.input_specs[1]
86
+ if is_tensor_shardable(
87
+ self_strategy.shape, self_spec, allow_unbacked_sharding=True
88
+ ) and is_tensor_shardable(
89
+ mat2_strategy.shape, mat2_spec, allow_unbacked_sharding=True
90
+ ):
91
+ redistribute_cost = [
92
+ generate_redistribute_costs(self_strategy, self_spec),
93
+ generate_redistribute_costs(mat2_strategy, mat2_spec),
94
+ ]
95
+ strtg.redistribute_cost = redistribute_cost
96
+ filtered_strategies.append(strtg)
97
+
98
+ mm_strategy.strategies = filtered_strategies
99
+
100
+ return mm_strategy
101
+
102
+
103
+ def _addmm_like_strategy(
104
+ mm_equation: str, mesh: DeviceMesh, op_schema: OpSchema
105
+ ) -> OpStrategy:
106
+ self_strategy, mat1_strategy, mat2_strategy = op_schema.args_schema
107
+ if not isinstance(self_strategy, OpStrategy):
108
+ raise AssertionError(f"Expected OpStrategy, got {type(self_strategy)}")
109
+ if not isinstance(mat1_strategy, OpStrategy):
110
+ raise AssertionError(f"Expected OpStrategy, got {type(mat1_strategy)}")
111
+ if not isinstance(mat2_strategy, OpStrategy):
112
+ raise AssertionError(f"Expected OpStrategy, got {type(mat2_strategy)}")
113
+ self_shape = self_strategy.shape
114
+ mm_out_shape = torch.Size(
115
+ [
116
+ mat2_strategy.shape[-1] if i == len(mat1_strategy.shape) - 1 else dim_size
117
+ for i, dim_size in enumerate(mat1_strategy.shape)
118
+ ]
119
+ )
120
+ # generate all possible strategies for mm
121
+ mm_strategy = gen_einsum_strategies(mm_equation, mesh)
122
+ # filter out invalid strategies and associate costs
123
+ strategies = mm_strategy.strategies
124
+ filtered_strategies = []
125
+ for strtg in strategies:
126
+ # construct new strategy by consider the self arg
127
+ if strtg.input_specs is None:
128
+ raise AssertionError(
129
+ f"Expected input_specs to be not None, got {strtg.input_specs}"
130
+ )
131
+ mat1_spec = strtg.input_specs[0]
132
+ mat2_spec = strtg.input_specs[1]
133
+ out_spec = strtg.output_spec
134
+
135
+ # self arg's spec should follow the output of mm, but need
136
+ # to consider broadcast for the self arg
137
+ broadcast_dims_map = infer_broadcast_dims_map(mm_out_shape, self_shape)
138
+ self_placements = map_placements_after_broadcast(
139
+ out_spec.placements, mm_out_shape, broadcast_dims_map
140
+ )
141
+ self_spec = DTensorSpec(mesh=mesh, placements=self_placements)
142
+
143
+ if is_tensor_shardable(
144
+ mat1_strategy.shape, mat1_spec, allow_unbacked_sharding=True
145
+ ) and is_tensor_shardable(
146
+ mat2_strategy.shape, mat2_spec, allow_unbacked_sharding=True
147
+ ):
148
+ # update input specs with new self spec
149
+ strtg.input_specs = (self_spec, mat1_spec, mat2_spec)
150
+
151
+ # associate costs
152
+ redistribute_cost = [
153
+ generate_redistribute_costs(self_strategy, self_spec),
154
+ generate_redistribute_costs(mat1_strategy, mat1_spec),
155
+ generate_redistribute_costs(mat2_strategy, mat2_spec),
156
+ ]
157
+ strtg.redistribute_cost = redistribute_cost
158
+ filtered_strategies.append(strtg)
159
+
160
+ mm_strategy.strategies = filtered_strategies
161
+
162
+ return mm_strategy
163
+
164
+
165
+ def _scaled_mm_like_strategy(
166
+ mm_equation: str, mesh: DeviceMesh, op_schema: OpSchema
167
+ ) -> OpStrategy:
168
+ (
169
+ self_strategy,
170
+ mat2_strategy,
171
+ scale_self_strategy,
172
+ scale_mat2_strategy,
173
+ bias_strategy,
174
+ scale_result_strategy,
175
+ *_,
176
+ ) = op_schema.args_schema
177
+ if not isinstance(self_strategy, OpStrategy):
178
+ raise AssertionError(f"Expected OpStrategy, got {type(self_strategy)}")
179
+ if not isinstance(mat2_strategy, OpStrategy):
180
+ raise AssertionError(f"Expected OpStrategy, got {type(mat2_strategy)}")
181
+ if not isinstance(scale_self_strategy, OpStrategy):
182
+ raise AssertionError(f"Expected OpStrategy, got {type(scale_self_strategy)}")
183
+ if not isinstance(scale_mat2_strategy, OpStrategy):
184
+ raise AssertionError(f"Expected OpStrategy, got {type(scale_mat2_strategy)}")
185
+ # TODO: add support for these later
186
+ if bias_strategy is not None:
187
+ raise AssertionError("_scaled_mm on DTensors doesn't support bias")
188
+ if scale_result_strategy is not None:
189
+ raise AssertionError("_scaled_mm on DTensors doesn't support scale_result")
190
+ # generate all possible strategies for mm
191
+ mm_strategy = gen_einsum_strategies(mm_equation, mesh)
192
+ # filter out invalid strategies and associate costs
193
+ strategies = mm_strategy.strategies
194
+ filtered_strategies = []
195
+ for strtg in strategies:
196
+ if strtg.input_specs is None:
197
+ raise AssertionError(
198
+ f"Expected input_specs to be not None, got {strtg.input_specs}"
199
+ )
200
+ self_spec = strtg.input_specs[0]
201
+ mat2_spec = strtg.input_specs[1]
202
+ # propagate the operands' specs to their scales, except for tensor-wise
203
+ # scaling which can have any numbers of dims (legacy...), hence sharding
204
+ # dims won't map. for tensor-wise, anyways, we can only do replication.
205
+ scale_self_spec = (
206
+ DTensorSpec(self_spec.mesh, (Replicate(),))
207
+ if prod(scale_self_strategy.shape) == 1
208
+ else self_spec
209
+ )
210
+ scale_mat2_spec = (
211
+ DTensorSpec(mat2_spec.mesh, (Replicate(),))
212
+ if prod(scale_mat2_strategy.shape) == 1
213
+ else mat2_spec
214
+ )
215
+ strtg.input_specs = list(strtg.input_specs) + [scale_self_spec, scale_mat2_spec]
216
+ if (
217
+ is_tensor_shardable(
218
+ self_strategy.shape, self_spec, allow_unbacked_sharding=True
219
+ )
220
+ and is_tensor_shardable(
221
+ mat2_strategy.shape, mat2_spec, allow_unbacked_sharding=True
222
+ )
223
+ and is_tensor_shardable(
224
+ scale_self_strategy.shape, scale_self_spec, allow_unbacked_sharding=True
225
+ )
226
+ and is_tensor_shardable(
227
+ scale_mat2_strategy.shape, scale_mat2_spec, allow_unbacked_sharding=True
228
+ )
229
+ ):
230
+ redistribute_cost = [
231
+ generate_redistribute_costs(self_strategy, self_spec),
232
+ generate_redistribute_costs(mat2_strategy, mat2_spec),
233
+ generate_redistribute_costs(scale_self_strategy, scale_self_spec),
234
+ generate_redistribute_costs(scale_mat2_strategy, scale_mat2_spec),
235
+ ]
236
+ strtg.redistribute_cost = redistribute_cost
237
+ filtered_strategies.append(strtg)
238
+
239
+ mm_strategy.strategies = filtered_strategies
240
+
241
+ return mm_strategy
242
+
243
+
244
+ @register_op_strategy(aten.dot.default)
245
+ def dot_strategy(op_schema: OpSchema) -> OpStrategy:
246
+ mesh = op_schema.get_mesh_from_args()
247
+ return _mm_like_strategy("i,i->", mesh, op_schema)
248
+
249
+
250
+ @register_op_strategy(aten.mm.default)
251
+ def mm_strategy(op_schema: OpSchema) -> OpStrategy:
252
+ mesh = op_schema.get_mesh_from_args()
253
+ return _mm_like_strategy("mk,kn->mn", mesh, op_schema)
254
+
255
+
256
+ @register_op_strategy(aten.addmm.default)
257
+ def addmm_strategy(op_schema: OpSchema) -> OpStrategy:
258
+ mesh = op_schema.get_mesh_from_args()
259
+ return _addmm_like_strategy("mk,kn->mn", mesh, op_schema)
260
+
261
+
262
+ @register_op_strategy(aten.bmm.default)
263
+ def bmm_strategy(op_schema: OpSchema) -> OpStrategy:
264
+ mesh = op_schema.get_mesh_from_args()
265
+ return _mm_like_strategy("bmk,bkn->bmn", mesh, op_schema)
266
+
267
+
268
+ @register_op_strategy(aten.baddbmm.default)
269
+ def baddbmm_strategy(op_schema: OpSchema) -> OpStrategy:
270
+ mesh = op_schema.get_mesh_from_args()
271
+ return _addmm_like_strategy("bmk,bkn->bmn", mesh, op_schema)
272
+
273
+
274
+ @register_op_strategy(aten._scaled_mm.default)
275
+ def scaled_mm_strategy(op_schema: OpSchema) -> OpStrategy:
276
+ mesh = op_schema.get_mesh_from_args()
277
+ return _scaled_mm_like_strategy("mk,kn->mn", mesh, op_schema)
278
+
279
+
280
+ def _scaled_dot_product_flash_attention_base_strategies(
281
+ op_schema: OpSchema,
282
+ ) -> list[PlacementList]:
283
+ """Helper that returns list of base placement strategies (without CP)."""
284
+ return_debug_mask = len(op_schema.args_schema) >= 6 and op_schema.args_schema[5]
285
+ q_input_strategy = op_schema.args_schema[0]
286
+ if not isinstance(q_input_strategy, OpStrategy):
287
+ raise AssertionError(f"Expected OpStrategy, got {type(q_input_strategy)}")
288
+ # assuming q/k/v have the same shape
289
+
290
+ single_mesh_dim_strategies = []
291
+
292
+ # placement list stores placements of [outputs, inputs]
293
+ # in the spda case, we have 3 valid tensor outputs and 3 tensor inputs
294
+ # first we can always accept full replication for both inputs and outputs
295
+ all_replicate: PlacementList = [
296
+ Replicate(),
297
+ Replicate(),
298
+ None, # cum_seq_q
299
+ None, # cum_seq_k
300
+ None, # max_q
301
+ None, # max_k
302
+ Replicate(), # rng_state
303
+ None, # unused
304
+ Replicate(),
305
+ Replicate(),
306
+ Replicate(),
307
+ Replicate(),
308
+ ]
309
+ single_mesh_dim_strategies.append(all_replicate)
310
+
311
+ # second we can accept the sharding pattern of tensor parallelism, which
312
+ # shard on the num of head dim
313
+ qkv_sharding = Shard(1) # num head dim
314
+ output_sharding = Shard(1) # num head dim
315
+ logsumexp_sharding = Shard(1) # num head dim
316
+ if return_debug_mask:
317
+ debug_attn_mask_sharding: Placement = Shard(1) # num head dim
318
+ else:
319
+ # empty debug mask, replicated
320
+ debug_attn_mask_sharding = Replicate()
321
+
322
+ num_heads_dim_sharding: PlacementList = [
323
+ output_sharding,
324
+ logsumexp_sharding,
325
+ None, # cum_seq_q
326
+ None, # cum_seq_k
327
+ None, # max_q
328
+ None, # max_k
329
+ Replicate(), # rng_state
330
+ None, # unused
331
+ debug_attn_mask_sharding,
332
+ qkv_sharding,
333
+ qkv_sharding,
334
+ qkv_sharding,
335
+ ]
336
+ single_mesh_dim_strategies.append(num_heads_dim_sharding)
337
+
338
+ # Shard on the batch dimension
339
+ debug_attn_mask_sharding = Shard(0) if return_debug_mask else Replicate()
340
+ single_mesh_dim_strategies.append(
341
+ [
342
+ Shard(0), # output
343
+ Shard(0), # logsumexp
344
+ None, # cum_seq_q
345
+ None, # cum_seq_k
346
+ None, # max_q
347
+ None, # max_k
348
+ Replicate(), # rng_state
349
+ None, # unused
350
+ debug_attn_mask_sharding, # debugattn
351
+ Shard(0), # q
352
+ Shard(0), # k
353
+ Shard(0), # v
354
+ ]
355
+ )
356
+ return single_mesh_dim_strategies
357
+
358
+
359
+ @register_op_strategy(
360
+ aten._scaled_dot_product_flash_attention.default, schema_info=RuntimeSchemaInfo(5)
361
+ )
362
+ def scaled_dot_product_flash_attention_strategy(op_schema: OpSchema) -> OpStrategy:
363
+ # NOTE: currently we only support some simple strategies to support tensor parallelism
364
+ # TODO: sdpa might be a good candidate for us to explore decomposed sharding propagation
365
+ # as it involves: matmul, pointwise, reduction ops together.
366
+
367
+ mesh = op_schema.get_mesh_from_args()
368
+ single_mesh_dim_strategies = _scaled_dot_product_flash_attention_base_strategies(
369
+ op_schema
370
+ )
371
+ return expand_to_full_mesh_op_strategy(
372
+ mesh, op_schema, single_mesh_dim_strategies, input_index=9
373
+ )
374
+
375
+
376
+ def _scaled_dot_product_flash_attention_backward_base_strategies(
377
+ op_schema: OpSchema,
378
+ ) -> list[PlacementList]:
379
+ """Helper that returns list of base placement strategies (without CP)."""
380
+ q_input_strategy = op_schema.args_schema[1]
381
+ if not isinstance(q_input_strategy, OpStrategy):
382
+ raise AssertionError(f"Expected OpStrategy, got {type(q_input_strategy)}")
383
+ # assuming q/k/v have the same shape
384
+
385
+ tensor_input_indices = [
386
+ i
387
+ for i, arg_spec in enumerate(op_schema.args_schema)
388
+ if isinstance(arg_spec, OpStrategy)
389
+ ]
390
+ num_tensor_inputs = len(tensor_input_indices)
391
+
392
+ single_mesh_dim_strategies = []
393
+
394
+ # placement list stores placements of [outputs, inputs]
395
+ # in the spda backward case, we have 3 tensor outputs and 6 to 10 tensor inputs
396
+ # first we can always accept full replication for both inputs and outputs
397
+ all_replicate: PlacementList = [Replicate()] * (3 + num_tensor_inputs)
398
+
399
+ single_mesh_dim_strategies.append(all_replicate)
400
+
401
+ # second we can accept the sharding pattern of tensor parallelism, which
402
+ # shard on the num of head dim
403
+ grad_output_sharding = Shard(1) # num head dim
404
+ qkv_sharding = Shard(1) # num head dim
405
+ output_sharding = Shard(1) # num head dim
406
+ logsumexp_sharding = Shard(1) # num head dim
407
+ grad_qkv_sharding = Shard(1) # num head dim
408
+
409
+ num_heads_dim_sharding: PlacementList = [
410
+ grad_qkv_sharding,
411
+ grad_qkv_sharding,
412
+ grad_qkv_sharding,
413
+ grad_output_sharding,
414
+ qkv_sharding,
415
+ qkv_sharding,
416
+ qkv_sharding,
417
+ output_sharding,
418
+ logsumexp_sharding,
419
+ ]
420
+ # accept replicate on the rest tensor inputs, potentially
421
+ # cum_seq_q, cum_seq_k, philox_seed, philox_offset
422
+ # at indices 6, 7, 12, 13, respectively
423
+ num_heads_dim_sharding.extend([Replicate()] * (num_tensor_inputs - 6))
424
+ single_mesh_dim_strategies.append(num_heads_dim_sharding)
425
+
426
+ # Batch sharding
427
+ batch_dim_sharding: PlacementList = [
428
+ Shard(0), # grad_q
429
+ Shard(0), # grad_k
430
+ Shard(0), # grad_v
431
+ Shard(0), # grad_output
432
+ Shard(0), # q
433
+ Shard(0), # k
434
+ Shard(0), # v
435
+ Shard(0), # output
436
+ Shard(0), # logsumexp
437
+ ]
438
+ # accept replicate on the rest tensor inputs, potentially
439
+ # cum_seq_q, cum_seq_k, philox_seed, philox_offset
440
+ # at indices 6, 7, 12, 13, respectively
441
+ batch_dim_sharding.extend([Replicate()] * (num_tensor_inputs - 6))
442
+ single_mesh_dim_strategies.append(batch_dim_sharding)
443
+
444
+ return single_mesh_dim_strategies
445
+
446
+
447
+ @register_op_strategy(aten._scaled_dot_product_flash_attention_backward.default)
448
+ def scaled_dot_product_flash_attention_backward_strategy(
449
+ op_schema: OpSchema,
450
+ ) -> OpStrategy:
451
+ # backward op does not need to validate the mesh since forward op has already done it
452
+ mesh = op_schema.get_mesh_from_args(validate=False)
453
+ single_mesh_dim_strategies = (
454
+ _scaled_dot_product_flash_attention_backward_base_strategies(op_schema)
455
+ )
456
+ return expand_to_full_mesh_op_strategy(
457
+ mesh, op_schema, single_mesh_dim_strategies, input_index=3
458
+ )
459
+
460
+
461
+ @register_op_strategy(aten.constant_pad_nd.default)
462
+ def constant_pad_nd_strategy(op_schema: OpSchema) -> OpStrategy:
463
+ mesh = op_schema.get_mesh_from_args(validate=False)
464
+
465
+ # TODO(d4l3k); implement a more correct strategy for constant_pad_nd
466
+ return OpStrategy(
467
+ [
468
+ OpSpec(
469
+ output_specs=DTensorSpec(mesh, (Replicate(),)),
470
+ input_specs=(
471
+ DTensorSpec(mesh, (Replicate(),)),
472
+ DTensorSpec(mesh, (Replicate(),)),
473
+ ),
474
+ redistribute_cost=[[1]],
475
+ )
476
+ ]
477
+ )
478
+
479
+
480
+ def _scaled_dot_product_efficient_attention_base_strategies(
481
+ op_schema: OpSchema,
482
+ ) -> list[PlacementList]:
483
+ """Helper that returns list of base placement strategies (without CP)."""
484
+ q_input_strategy = op_schema.args_schema[0]
485
+ if not isinstance(q_input_strategy, OpStrategy):
486
+ raise AssertionError(f"Expected OpStrategy, got {type(q_input_strategy)}")
487
+ # assuming q/k/v have the same shape
488
+
489
+ has_attn_bias = op_schema.args_schema[3] is not None
490
+ compute_log_sumexp = op_schema.args_schema[4]
491
+
492
+ single_mesh_dim_strategies: list[PlacementList] = []
493
+
494
+ # placement list stores placements of [outputs, inputs]
495
+ # in the spda case, we have 2 valid tensor outputs and 3 or 4 tensor inputs
496
+ # first we can always accept full replication for both inputs and outputs
497
+ all_replicate: PlacementList = [
498
+ Replicate(),
499
+ Replicate(),
500
+ None,
501
+ None,
502
+ Replicate(),
503
+ Replicate(),
504
+ Replicate(),
505
+ ]
506
+ if has_attn_bias:
507
+ all_replicate.append(Replicate()) # attn bias
508
+
509
+ single_mesh_dim_strategies.append(all_replicate)
510
+
511
+ # second we can accept the sharding pattern of tensor parallelism, which
512
+ # shard on the heads dimension
513
+ qkv_sharding = Shard(1)
514
+ output_sharding = Shard(1)
515
+ if compute_log_sumexp:
516
+ logsumexp_sharding: Placement = Shard(1)
517
+ else:
518
+ # empty logsumexp, replicated
519
+ logsumexp_sharding = Replicate()
520
+
521
+ num_heads_dim_sharding = [
522
+ output_sharding,
523
+ logsumexp_sharding,
524
+ None,
525
+ None,
526
+ qkv_sharding,
527
+ qkv_sharding,
528
+ qkv_sharding,
529
+ ]
530
+ if has_attn_bias:
531
+ num_heads_dim_sharding.append(Shard(1))
532
+ single_mesh_dim_strategies.append(num_heads_dim_sharding)
533
+
534
+ # batch sharding
535
+ if compute_log_sumexp:
536
+ logsumexp_sharding_dp: Placement = Shard(0)
537
+ else:
538
+ # empty logsumexp, replicated
539
+ logsumexp_sharding_dp = Replicate()
540
+ batch_sharding = [
541
+ Shard(0), # output
542
+ logsumexp_sharding_dp, # logsumexp
543
+ None, # philox_seed
544
+ None, # philox_offset
545
+ Shard(0), # q
546
+ Shard(0), # k
547
+ Shard(0), # v
548
+ ]
549
+ if has_attn_bias:
550
+ batch_sharding.append(Shard(0))
551
+
552
+ single_mesh_dim_strategies.append(batch_sharding)
553
+
554
+ return single_mesh_dim_strategies
555
+
556
+
557
+ @register_op_strategy(
558
+ aten._scaled_dot_product_efficient_attention.default,
559
+ schema_info=RuntimeSchemaInfo(4),
560
+ )
561
+ def scaled_dot_product_efficient_attention_strategy(op_schema: OpSchema) -> OpStrategy:
562
+ # NOTE: currently we only support some simple strategies to support tensor parallelism
563
+ mesh = op_schema.get_mesh_from_args()
564
+ single_mesh_dim_strategies = (
565
+ _scaled_dot_product_efficient_attention_base_strategies(op_schema)
566
+ )
567
+ return expand_to_full_mesh_op_strategy(
568
+ mesh,
569
+ op_schema,
570
+ single_mesh_dim_strategies,
571
+ input_index=4,
572
+ )
573
+
574
+
575
+ def _scaled_dot_product_efficient_attention_backward_base_strategies(
576
+ op_schema: OpSchema,
577
+ ) -> list[PlacementList]:
578
+ """Helper that returns list of base placement strategies (without CP)."""
579
+ q_input_strategy = op_schema.args_schema[1]
580
+ if not isinstance(q_input_strategy, OpStrategy):
581
+ raise AssertionError(f"Expected OpStrategy, got {type(q_input_strategy)}")
582
+ # assuming q/k/v have the same shape
583
+ has_attn_bias = op_schema.args_schema[4] is not None
584
+
585
+ single_mesh_dim_strategies = []
586
+
587
+ # placement list stores placements of [outputs, inputs]
588
+ # in the spda backward case, we have 4 tensor outputs and 8 or 9 tensor inputs
589
+ # NOTE: Output sharding of grad_bias on heads dim if attn_bias is present;
590
+ # otherwise grad_bias will be empty and its DTensorSpec will be removed.
591
+ # first we can always accept full replication for both inputs and outputs
592
+ all_replicate: PlacementList = [Replicate()] * (12 + has_attn_bias)
593
+
594
+ if not has_attn_bias:
595
+ all_replicate[3] = None # grad bias is None if attn_bias is not present
596
+
597
+ single_mesh_dim_strategies.append(all_replicate)
598
+
599
+ # second we can accept the sharding pattern of tensor parallelism, which
600
+ # shard on the heads dimension
601
+ grad_output_sharding = Shard(1)
602
+ qkv_sharding = Shard(1)
603
+ output_sharding = Shard(1)
604
+ logsumexp_sharding = Shard(1)
605
+ grad_qkv_sharding = Shard(1)
606
+ grad_bias_sharding = Shard(1) if has_attn_bias else None
607
+
608
+ num_heads_dim_sharding: PlacementList = [
609
+ grad_qkv_sharding,
610
+ grad_qkv_sharding,
611
+ grad_qkv_sharding,
612
+ grad_bias_sharding,
613
+ grad_output_sharding,
614
+ qkv_sharding,
615
+ qkv_sharding,
616
+ qkv_sharding,
617
+ # the place for optional input attn_bias,
618
+ output_sharding,
619
+ logsumexp_sharding,
620
+ ]
621
+ # input sharding of attn_bias on heads dim if present
622
+ if has_attn_bias:
623
+ num_heads_dim_sharding.insert(8, Shard(1))
624
+ # accept replicate on the rest scalar tensor inputs
625
+ # namely philox_seed and philox_offset
626
+ num_heads_dim_sharding.extend([Replicate(), Replicate()])
627
+ single_mesh_dim_strategies.append(num_heads_dim_sharding)
628
+
629
+ # Shards on batch dim
630
+ batch_dim_sharding: PlacementList = [
631
+ Shard(0), # grad_q
632
+ Shard(0), # grad_k
633
+ Shard(0), # grad_v
634
+ Shard(0) if has_attn_bias else None, # grad_bias
635
+ Shard(0), # grad_output
636
+ Shard(0), # q
637
+ Shard(0), # k
638
+ Shard(0), # v
639
+ Shard(0), # output
640
+ Shard(0), # logsumexp
641
+ ]
642
+ # accept replicate on the rest tensor inputs, potentially
643
+ # cum_seq_q, cum_seq_k, philox_seed, philox_offset
644
+ # at indices 6, 7, 12, 13, respectively
645
+ if has_attn_bias:
646
+ batch_dim_sharding.insert(8, Shard(0))
647
+ batch_dim_sharding.extend([Replicate(), Replicate()])
648
+ single_mesh_dim_strategies.append(batch_dim_sharding)
649
+
650
+ return single_mesh_dim_strategies
651
+
652
+
653
+ @register_op_strategy(aten._scaled_dot_product_efficient_attention_backward.default)
654
+ def scaled_dot_product_efficient_attention_backward_strategy(
655
+ op_schema: OpSchema,
656
+ ) -> OpStrategy:
657
+ # backward op does not need to validate the mesh since forward op has already done it
658
+ mesh = op_schema.get_mesh_from_args(validate=False)
659
+ single_mesh_dim_strategies = (
660
+ _scaled_dot_product_efficient_attention_backward_base_strategies(op_schema)
661
+ )
662
+ return expand_to_full_mesh_op_strategy(
663
+ mesh,
664
+ op_schema,
665
+ single_mesh_dim_strategies,
666
+ input_index=4,
667
+ )
668
+
669
+
670
+ def _scaled_dot_product_cudnn_attention_base_strategies(
671
+ op_schema: OpSchema,
672
+ ) -> list[PlacementList]:
673
+ """Helper that returns list of base placement strategies (without CP)."""
674
+ (
675
+ query_strategy, # query
676
+ _, # key
677
+ _, # value
678
+ attn_bias_strategy,
679
+ compute_log_sumexp, # compute_log_sumexp
680
+ *rest_args, # optional args: dropout_p, is_causal, return_debug_mask, scale
681
+ ) = op_schema.args_schema
682
+ return_debug_mask = len(op_schema.args_schema) >= 8 and rest_args[2]
683
+ has_attn_bias = attn_bias_strategy is not None
684
+ debug_attn_mask_sharding: Placement | None = (
685
+ Replicate() if return_debug_mask else None
686
+ )
687
+
688
+ if not isinstance(query_strategy, OpStrategy):
689
+ raise AssertionError(f"Expected OpStrategy, got {type(query_strategy)}")
690
+ # assuming q/k/v have the same shape
691
+
692
+ single_mesh_dim_strategies = []
693
+
694
+ # placement list stores placements of [outputs, inputs]
695
+ # in the spda case, we have 2 valid tensor outputs and 3 tensor inputs
696
+ # first we can always accept full replication for both inputs and outputs
697
+ all_replicate: PlacementList = [
698
+ Replicate(), # output
699
+ Replicate(), # logsumexp
700
+ None, # cum_seq_q
701
+ None, # cum_seq_k
702
+ None, # max_q
703
+ None, # max_k
704
+ None, # philox_seed
705
+ None, # philox_offset
706
+ # NOTE: debug_attn_mask is not supported by pytorch and is always an empty tensor
707
+ # https://github.com/pytorch/pytorch/blob/60205b0eb2602317856312a66d955c88334ade0b/aten/src/ATen/native/transformers/cuda/attention.cu#L839-L840
708
+ debug_attn_mask_sharding, # debug_attn_mask
709
+ Replicate(), # q
710
+ Replicate(), # k
711
+ Replicate(), # v
712
+ ]
713
+ if has_attn_bias:
714
+ all_replicate.append(Replicate()) # attn bias
715
+
716
+ single_mesh_dim_strategies.append(all_replicate)
717
+
718
+ # second we can accept the sharding pattern of tensor parallelism, which
719
+ # shard on the num of head dim
720
+ tp_sharding = Shard(1) # num head dim
721
+ qkv_sharding = tp_sharding
722
+ output_sharding = tp_sharding
723
+ logsumexp_sharding = tp_sharding if compute_log_sumexp else Replicate()
724
+ debug_attn_mask_sharding = tp_sharding if return_debug_mask else None
725
+
726
+ num_heads_dim_sharding: PlacementList = [
727
+ output_sharding,
728
+ logsumexp_sharding,
729
+ None, # cum_seq_q
730
+ None, # cum_seq_k
731
+ None, # max_q
732
+ None, # max_k
733
+ None, # philox_seed
734
+ None, # philox_offset
735
+ debug_attn_mask_sharding,
736
+ qkv_sharding,
737
+ qkv_sharding,
738
+ qkv_sharding,
739
+ ]
740
+ single_mesh_dim_strategies.append(num_heads_dim_sharding)
741
+
742
+ # batch parallelism
743
+ logsumexp_sharding = Shard(0) if compute_log_sumexp else Replicate()
744
+ debug_attn_mask_sharding = Shard(0) if return_debug_mask else None
745
+ batch_dim_sharding: PlacementList = [
746
+ Shard(0), # output
747
+ logsumexp_sharding,
748
+ None, # cum_seq_q
749
+ None, # cum_seq_k
750
+ None, # max_q
751
+ None, # max_k
752
+ None, # philox_seed
753
+ None, # philox_offset
754
+ debug_attn_mask_sharding,
755
+ Shard(0), # q
756
+ Shard(0), # k
757
+ Shard(0), # v
758
+ ]
759
+ single_mesh_dim_strategies.append(batch_dim_sharding)
760
+
761
+ return single_mesh_dim_strategies
762
+
763
+
764
+ @register_op_strategy(
765
+ aten._scaled_dot_product_cudnn_attention.default,
766
+ schema_info=RuntimeSchemaInfo(4),
767
+ )
768
+ def scaled_dot_product_cudnn_attention_strategy(op_schema: OpSchema) -> OpStrategy:
769
+ mesh = op_schema.get_mesh_from_args()
770
+ single_mesh_dim_strategies = _scaled_dot_product_cudnn_attention_base_strategies(
771
+ op_schema
772
+ )
773
+ return expand_to_full_mesh_op_strategy(
774
+ mesh, op_schema, single_mesh_dim_strategies, input_index=9
775
+ )
776
+
777
+
778
+ def _scaled_dot_product_cudnn_attention_backward_base_strategies(
779
+ op_schema: OpSchema,
780
+ ) -> list[PlacementList]:
781
+ """Helper that returns list of base placement strategies (without CP)."""
782
+ if len(op_schema.args_schema) < 15:
783
+ raise AssertionError(
784
+ f"Expected at least 15 args_schema, got {len(op_schema.args_schema)}"
785
+ )
786
+ has_attn_bias = op_schema.args_schema[8] is not None
787
+ has_scale = len(op_schema.args_schema) >= 16 and False
788
+
789
+ query_strategy = op_schema.args_schema[1]
790
+ if not isinstance(query_strategy, OpStrategy):
791
+ raise AssertionError(f"Expected OpStrategy, got {type(query_strategy)}")
792
+ # assuming q/k/v have the same shape
793
+
794
+ single_mesh_dim_strategies = []
795
+
796
+ # placement list stores placements of [outputs, inputs]
797
+ # cudnn outputs: (Tensor dq, Tensor dk, Tensor dv)
798
+ # cudnn inputs: (
799
+ # Tensor grad_out,
800
+ # Tensor query,
801
+ # Tensor key,
802
+ # Tensor value,
803
+ # Tensor out,
804
+ # Tensor logsumexp,
805
+ # Tensor philox_seed,
806
+ # Tensor philox_offset,
807
+ # Tensor attn_bias,
808
+ # Tensor cum_seq_q,
809
+ # Tensor cum_seq_k,
810
+ # SymInt max_q,
811
+ # SymInt max_k,
812
+ # float dropout_p,
813
+ # bool is_causal,
814
+ # int? scale,
815
+ # )
816
+
817
+ # case 1: we can always accept full replication for both inputs and outputs
818
+ all_replicate_out: PlacementList = [
819
+ Replicate(), # dq
820
+ Replicate(), # dk
821
+ Replicate(), # dv
822
+ ]
823
+ all_replicate_inp: PlacementList = [Replicate()] * 6
824
+ all_replicate_inp += [
825
+ Replicate()
826
+ ] * 2 # philox_seed, philox_offset is casted to Replicate() in DTensor
827
+ all_replicate_inp += [Replicate() if has_attn_bias else None]
828
+ all_replicate_inp += [None] * 6
829
+ if has_scale:
830
+ all_replicate_inp.append(None)
831
+
832
+ all_replicate: PlacementList = all_replicate_out + all_replicate_inp
833
+ single_mesh_dim_strategies.append(all_replicate)
834
+
835
+ # case 2: we can accept the sharding pattern of tensor parallelism, which
836
+ # shards on the num of head dim
837
+ qkv_sharding = Shard(1) # num head dim
838
+ output_sharding = Shard(1) # num head dim
839
+ logsumexp_sharding = Shard(1) # num head dim
840
+
841
+ num_heads_dim_sharding_out: PlacementList = [qkv_sharding] * 3
842
+ num_heads_dim_sharding_inp: PlacementList = [qkv_sharding] * 4
843
+ num_heads_dim_sharding_inp += [output_sharding]
844
+ num_heads_dim_sharding_inp += [logsumexp_sharding]
845
+ num_heads_dim_sharding_inp += [
846
+ Replicate()
847
+ ] * 2 # philox_seed, philox_offset is casted to Replicate() in DTensor
848
+ num_heads_dim_sharding_inp += [Shard(1) if has_attn_bias else None]
849
+ num_heads_dim_sharding_inp += [None] * 6
850
+ if has_scale:
851
+ num_heads_dim_sharding_inp.append(None)
852
+
853
+ num_heads_dim_sharding = num_heads_dim_sharding_out + num_heads_dim_sharding_inp
854
+ single_mesh_dim_strategies.append(num_heads_dim_sharding)
855
+
856
+ # case 3: we can accept the sharding pattern of batch parallelism, which
857
+ # shards on the batch dimension
858
+ qkv_sharding = Shard(0)
859
+ output_sharding = Shard(0)
860
+ logsumexp_sharding = Shard(0)
861
+
862
+ batch_dim_sharding_out: PlacementList = [qkv_sharding] * 3
863
+ batch_dim_sharding_inp: PlacementList = [qkv_sharding] * 4
864
+ batch_dim_sharding_inp += [output_sharding]
865
+ batch_dim_sharding_inp += [logsumexp_sharding]
866
+ batch_dim_sharding_inp += [
867
+ Replicate()
868
+ ] * 2 # philox_seed, philox_offset is casted to Replicate() in DTensor
869
+ batch_dim_sharding_inp += [Shard(0) if has_attn_bias else None]
870
+ batch_dim_sharding_inp += [None] * 6
871
+ if has_scale:
872
+ batch_dim_sharding_inp.append(None)
873
+
874
+ batch_dim_sharding = batch_dim_sharding_out + batch_dim_sharding_inp
875
+ single_mesh_dim_strategies.append(batch_dim_sharding)
876
+
877
+ return single_mesh_dim_strategies
878
+
879
+
880
+ @register_op_strategy(aten._scaled_dot_product_cudnn_attention_backward.default)
881
+ def scaled_scaled_dot_product_cudnn_attention_backward_strategy(
882
+ op_schema: OpSchema,
883
+ ) -> OpStrategy:
884
+ # backward op does not need to validate the mesh since forward op has already done it
885
+ mesh = op_schema.get_mesh_from_args(validate=False)
886
+ single_mesh_dim_strategies = (
887
+ _scaled_dot_product_cudnn_attention_backward_base_strategies(op_schema)
888
+ )
889
+ return expand_to_full_mesh_op_strategy(
890
+ mesh, op_schema, single_mesh_dim_strategies, input_index=3
891
+ )
892
+
893
+
894
+ @register_op_strategy(aten._grouped_mm.default)
895
+ def grouped_mm_strategy(op_schema: OpSchema) -> OpStrategy:
896
+ mesh = op_schema.get_mesh_from_args()
897
+
898
+ mat1_strategy = op_schema.args_schema[0]
899
+ if not isinstance(mat1_strategy, OpStrategy):
900
+ raise AssertionError(f"Expected OpStrategy, got {type(mat1_strategy)}")
901
+ mat2_strategy = op_schema.args_schema[1]
902
+ if not isinstance(mat2_strategy, OpStrategy):
903
+ raise AssertionError(f"Expected OpStrategy, got {type(mat2_strategy)}")
904
+ if len(op_schema.args_schema) > 3:
905
+ bias_strategy = op_schema.args_schema[3]
906
+ if bias_strategy is not None:
907
+ raise AssertionError("grouped_mm doesn't support bias yet")
908
+
909
+ single_mesh_dim_strategies = []
910
+
911
+ offs_placement = None
912
+ if len(op_schema.args_schema) > 2 and op_schema.args_schema[2] is not None:
913
+ offs_placement = Replicate() # offs should always be replicated
914
+
915
+ all_replicate: PlacementList = [
916
+ Replicate(),
917
+ Replicate(), # mat1
918
+ Replicate(), # mat2
919
+ offs_placement, # offs
920
+ None, # bias
921
+ ]
922
+ partial_replicate: PlacementList = [
923
+ Partial(),
924
+ Partial(), # mat1
925
+ Replicate(), # mat2
926
+ offs_placement, # offs
927
+ None, # bias
928
+ ]
929
+ replicate_partial: PlacementList = [
930
+ Partial(),
931
+ Replicate(), # mat1
932
+ Partial(), # mat2
933
+ offs_placement, # offs
934
+ None, # bias
935
+ ]
936
+ single_mesh_dim_strategies = [all_replicate, partial_replicate, replicate_partial]
937
+
938
+ if mat1_strategy.ndim == 2 and mat2_strategy.ndim == 3:
939
+ # rowwise_replicate for 2dx3d not supported
940
+ replicate_colwise_2x3: PlacementList = [
941
+ Shard(1),
942
+ Replicate(), # mat1
943
+ Shard(2), # mat2
944
+ offs_placement, # offs
945
+ None, # bias
946
+ ]
947
+ colwise_rowwise_2x3: PlacementList = [
948
+ Partial(),
949
+ Shard(1), # mat1
950
+ Shard(1), # mat2
951
+ offs_placement, # offs
952
+ None, # bias
953
+ ]
954
+ single_mesh_dim_strategies.extend([replicate_colwise_2x3, colwise_rowwise_2x3])
955
+
956
+ if mat1_strategy.ndim == 3 and mat2_strategy.ndim == 2:
957
+ # replicate_colwise for 3dx2d not supported
958
+ colwise_rowwise_3x2: PlacementList = [
959
+ Partial(),
960
+ Shard(2), # mat1
961
+ Shard(0), # mat2
962
+ offs_placement, # offs
963
+ None, # bias
964
+ ]
965
+ rowwise_replicate_3x2: PlacementList = [
966
+ Shard(0),
967
+ Shard(1), # mat1
968
+ Replicate(), # mat2
969
+ offs_placement, # offs
970
+ None, # bias
971
+ ]
972
+ single_mesh_dim_strategies.extend([colwise_rowwise_3x2, rowwise_replicate_3x2])
973
+
974
+ if mat1_strategy.ndim == 2 and mat2_strategy.ndim == 2:
975
+ # colwise_rowwise for 2dx2d not supported
976
+ replicate_colwise_2x2: PlacementList = [
977
+ Shard(2),
978
+ Replicate(), # mat1
979
+ Shard(1), # mat2
980
+ offs_placement, # offs
981
+ None, # bias
982
+ ]
983
+ rowwise_replicate_2x2: PlacementList = [
984
+ Shard(1),
985
+ Shard(0), # mat1
986
+ Replicate(), # mat2
987
+ offs_placement, # offs
988
+ None, # bias
989
+ ]
990
+ single_mesh_dim_strategies.extend(
991
+ [replicate_colwise_2x2, rowwise_replicate_2x2]
992
+ )
993
+
994
+ if mat1_strategy.ndim == 3 and mat2_strategy.ndim == 3:
995
+ replicate_colwise_3x3: PlacementList = [
996
+ Shard(2),
997
+ Replicate(), # mat1
998
+ Shard(2), # mat2
999
+ offs_placement, # offs
1000
+ None, # bias
1001
+ ]
1002
+ rowwise_replicate_3x3: PlacementList = [
1003
+ Shard(1),
1004
+ Shard(1), # mat1
1005
+ Replicate(), # mat2
1006
+ offs_placement, # offs
1007
+ None, # bias
1008
+ ]
1009
+ colwise_rowwise_3x3: PlacementList = [
1010
+ Partial(),
1011
+ Shard(2), # mat1
1012
+ Shard(1), # mat2
1013
+ offs_placement, # offs
1014
+ None, # bias
1015
+ ]
1016
+ batch_dim_sharding: PlacementList = [
1017
+ Shard(0),
1018
+ Shard(0), # mat1
1019
+ Shard(0), # mat2
1020
+ offs_placement, # offs
1021
+ None, # bias
1022
+ ]
1023
+ single_mesh_dim_strategies.extend(
1024
+ [
1025
+ replicate_colwise_3x3,
1026
+ rowwise_replicate_3x3,
1027
+ colwise_rowwise_3x3,
1028
+ batch_dim_sharding,
1029
+ ]
1030
+ )
1031
+
1032
+ def valid_grouped_mm_strides(
1033
+ input_specs: list[DTensorSpec], output_specs: tuple[DTensorSpec | None, ...]
1034
+ ) -> bool:
1035
+ # 1. compute the local-tensor shape/strides given this sharding proposal
1036
+ # 2. apply the logic from the groped_mm meta function
1037
+ # UGH the input DTensorSpecs are missing their tensormetas... so i can get them another way
1038
+ def local_meta(spec: OpSpec, placements: tuple[Placement, ...]) -> TensorMeta:
1039
+ if not isinstance(spec.output_specs, DTensorSpec):
1040
+ raise AssertionError(
1041
+ f"Expected DTensorSpec, got {type(spec.output_specs)}"
1042
+ )
1043
+ if not isinstance(spec.output_specs.tensor_meta, TensorMeta):
1044
+ raise AssertionError(
1045
+ f"Expected TensorMeta, got {type(spec.output_specs.tensor_meta)}"
1046
+ )
1047
+ meta: TensorMeta = spec.output_specs.tensor_meta
1048
+ local_stride = compute_local_stride(meta.stride, mesh, placements)
1049
+ local_shape, _ = compute_local_shape_and_global_offset(
1050
+ meta.shape, mesh, placements, skip_offset=True
1051
+ )
1052
+ return TensorMeta(torch.Size(local_shape), local_stride, meta.dtype)
1053
+
1054
+ # pyrefly: ignore [missing-attribute]
1055
+ mat1_meta = local_meta(mat1_strategy.strategies[0], input_specs[0].placements)
1056
+ # pyrefly: ignore [missing-attribute]
1057
+ mat2_meta = local_meta(mat2_strategy.strategies[0], input_specs[1].placements)
1058
+
1059
+ def check_valid_strides(meta: TensorMeta) -> bool:
1060
+ # copied from `_meta_grouped_mm_common` in meta_registrations.py
1061
+ end_dim = len(meta.shape) - 1
1062
+ alignment = 16 // meta.dtype.itemsize
1063
+ if meta.stride[end_dim - 1] == 1 and meta.stride[end_dim] >= max(
1064
+ 1, meta.shape[end_dim - 1]
1065
+ ):
1066
+ if meta.stride[end_dim] % alignment != 0:
1067
+ return False
1068
+ elif meta.stride[end_dim] == 1 and meta.stride[end_dim - 1] >= max(
1069
+ 1, meta.shape[end_dim]
1070
+ ):
1071
+ if meta.stride[end_dim - 1] % alignment != 0:
1072
+ return False
1073
+ else:
1074
+ return False
1075
+ return True
1076
+
1077
+ mat1_valid = check_valid_strides(mat1_meta)
1078
+ mat2_valid = check_valid_strides(mat2_meta)
1079
+ return mat1_valid and mat2_valid
1080
+
1081
+ return expand_to_full_mesh_op_strategy(
1082
+ mesh,
1083
+ op_schema,
1084
+ single_mesh_dim_strategies,
1085
+ input_index=1,
1086
+ is_valid_strategy_cb=valid_grouped_mm_strides,
1087
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_pointwise_ops.py ADDED
@@ -0,0 +1,809 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ from collections.abc import Sequence
3
+ from typing import cast
4
+
5
+ import torch
6
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec
7
+ from torch.distributed.tensor._op_schema import (
8
+ OpSchema,
9
+ OpSpec,
10
+ OpStrategy,
11
+ RuntimeSchemaInfo,
12
+ StrategyType,
13
+ TupleStrategy,
14
+ )
15
+ from torch.distributed.tensor._ops.registration import register_op_strategy
16
+ from torch.distributed.tensor._ops.utils import (
17
+ generate_redistribute_costs,
18
+ infer_broadcast_dims_map,
19
+ map_placements_after_broadcast,
20
+ normalize_dim,
21
+ )
22
+ from torch.distributed.tensor.placement_types import (
23
+ _StridedShard,
24
+ Partial,
25
+ Placement,
26
+ Replicate,
27
+ Shard,
28
+ )
29
+ from torch.utils._typing_utils import not_none
30
+
31
+
32
+ aten = torch.ops.aten
33
+ # leave the remaining pointwise_ops list here for convenience,
34
+ # Below ops are some pointwise ops that are yet to be supported,
35
+ # they might not be a complete list.
36
+ # pointwise_ops = [
37
+ # "fake_quantize_per_channel_affine",
38
+ # "fake_quantize_per_tensor_affine",
39
+ # "floor_divide", # floor_divide is deprecated
40
+ # "frexp", # multiple output pointwise op, need to add support
41
+ # "gradient", # need investigation on this op
42
+ # "imag", # complex data type only
43
+ # "quantized_batch_norm",
44
+ # "quantized_max_pool1d",
45
+ # "quantized_max_pool2d",
46
+ # "real", # complex data type only
47
+ # ]
48
+
49
+
50
+ pointwise_ops = [
51
+ # please keep the entries below alphabetically sorted
52
+ aten.__ilshift__.Scalar,
53
+ aten.__ilshift__.Tensor,
54
+ aten.__irshift__.Scalar,
55
+ aten.__irshift__.Tensor,
56
+ aten.__lshift__.Scalar,
57
+ aten.__lshift__.Tensor,
58
+ aten.__rshift__.Scalar,
59
+ aten.__rshift__.Tensor,
60
+ aten._conj.default,
61
+ aten.abs.default,
62
+ aten.abs.out,
63
+ aten.abs_.default,
64
+ aten.acos.default,
65
+ aten.acos.out,
66
+ aten.acos_.default,
67
+ aten.acosh.default,
68
+ aten.acosh.out,
69
+ aten.acosh_.default,
70
+ aten.add.Scalar,
71
+ aten.add.out,
72
+ aten.add_.Scalar,
73
+ aten.addcdiv.default,
74
+ aten.addcdiv.out,
75
+ aten.addcdiv_.default,
76
+ aten.addcmul.default,
77
+ aten.addcmul.out,
78
+ aten.addcmul_.default,
79
+ aten.angle.default,
80
+ aten.angle.out,
81
+ aten.asin.default,
82
+ aten.asin.out,
83
+ aten.asin_.default,
84
+ aten.asinh.default,
85
+ aten.asinh.out,
86
+ aten.asinh_.default,
87
+ aten.atan.default,
88
+ aten.atan.out,
89
+ aten.atan2.default,
90
+ aten.atan2.out,
91
+ aten.atan2_.default,
92
+ aten.atan_.default,
93
+ aten.atanh.default,
94
+ aten.atanh.out,
95
+ aten.atanh_.default,
96
+ aten.bitwise_and.Scalar,
97
+ aten.bitwise_and.Scalar_Tensor,
98
+ aten.bitwise_and.Scalar_out,
99
+ aten.bitwise_and.Tensor,
100
+ aten.bitwise_and.Tensor_out,
101
+ aten.bitwise_and_.Scalar,
102
+ aten.bitwise_and_.Tensor,
103
+ aten.bitwise_left_shift.Scalar_Tensor,
104
+ aten.bitwise_left_shift.Tensor,
105
+ aten.bitwise_left_shift.Tensor_Scalar,
106
+ aten.bitwise_left_shift.Tensor_Scalar_out,
107
+ aten.bitwise_left_shift.Tensor_out,
108
+ aten.bitwise_left_shift_.Tensor,
109
+ aten.bitwise_left_shift_.Tensor_Scalar,
110
+ aten.bitwise_not.default,
111
+ aten.bitwise_not.out,
112
+ aten.bitwise_not_.default,
113
+ aten.bitwise_or.Scalar,
114
+ aten.bitwise_or.Scalar_Tensor,
115
+ aten.bitwise_or.Scalar_out,
116
+ aten.bitwise_or.Tensor,
117
+ aten.bitwise_or.Tensor_out,
118
+ aten.bitwise_or_.Scalar,
119
+ aten.bitwise_or_.Tensor,
120
+ aten.bitwise_right_shift.Scalar_Tensor,
121
+ aten.bitwise_right_shift.Tensor,
122
+ aten.bitwise_right_shift.Tensor_Scalar,
123
+ aten.bitwise_right_shift.Tensor_Scalar_out,
124
+ aten.bitwise_right_shift.Tensor_out,
125
+ aten.bitwise_right_shift_.Tensor,
126
+ aten.bitwise_right_shift_.Tensor_Scalar,
127
+ aten.bitwise_xor.Scalar,
128
+ aten.bitwise_xor.Scalar_Tensor,
129
+ aten.bitwise_xor.Scalar_out,
130
+ aten.bitwise_xor.Tensor,
131
+ aten.bitwise_xor.Tensor_out,
132
+ aten.bitwise_xor_.Scalar,
133
+ aten.bitwise_xor_.Tensor,
134
+ aten.ceil.default,
135
+ aten.ceil.out,
136
+ aten.ceil_.default,
137
+ aten.clamp.default,
138
+ aten.clamp.Tensor,
139
+ aten.clamp.out,
140
+ aten.clamp_.default,
141
+ aten.clamp_.Tensor,
142
+ aten.clamp_min.default,
143
+ aten.clamp_min.Tensor,
144
+ aten.clamp_max.default,
145
+ aten.clamp_max.Tensor,
146
+ aten.clip.default,
147
+ aten.clip.out,
148
+ aten.clip_.default,
149
+ aten.conj_physical.default,
150
+ aten.conj_physical.out,
151
+ aten.conj_physical_.default,
152
+ aten.copysign.Scalar,
153
+ aten.copysign.Scalar_out,
154
+ aten.copysign.Tensor,
155
+ aten.copysign.out,
156
+ aten.copysign_.Scalar,
157
+ aten.copysign_.Tensor,
158
+ aten.cos.default,
159
+ aten.cos.out,
160
+ aten.cos_.default,
161
+ aten.cosh.default,
162
+ aten.cosh.out,
163
+ aten.cosh_.default,
164
+ aten.deg2rad.default,
165
+ aten.deg2rad.out,
166
+ aten.deg2rad_.default,
167
+ aten.digamma.default,
168
+ aten.digamma.out,
169
+ aten.digamma_.default,
170
+ aten.div.Tensor,
171
+ aten.div.Tensor_mode,
172
+ aten.div.out,
173
+ aten.div.out_mode,
174
+ aten.div_.Tensor,
175
+ aten.div_.Tensor_mode,
176
+ aten.eq.Tensor,
177
+ aten.eq.Tensor_out,
178
+ aten.eq.Scalar,
179
+ aten.eq.Scalar_out,
180
+ aten.erf.default,
181
+ aten.erf.out,
182
+ aten.erf_.default,
183
+ aten.erfc.default,
184
+ aten.erfc.out,
185
+ aten.erfc_.default,
186
+ aten.erfinv.default,
187
+ aten.erfinv.out,
188
+ aten.erfinv_.default,
189
+ aten.exp.default,
190
+ aten.exp.out,
191
+ aten.exp2.default,
192
+ aten.exp2.out,
193
+ aten.exp2_.default,
194
+ aten.exp_.default,
195
+ aten.expm1.default,
196
+ aten.expm1.out,
197
+ aten.expm1_.default,
198
+ aten.float_power.Scalar,
199
+ aten.float_power.Scalar_out,
200
+ aten.float_power.Tensor_Scalar,
201
+ aten.float_power.Tensor_Scalar_out,
202
+ aten.float_power.Tensor_Tensor,
203
+ aten.float_power.Tensor_Tensor_out,
204
+ aten.float_power_.Scalar,
205
+ aten.float_power_.Tensor,
206
+ aten.floor.default,
207
+ aten.floor.out,
208
+ aten.floor_.default,
209
+ aten.fmod.Scalar,
210
+ aten.fmod.Scalar_out,
211
+ aten.fmod.Tensor,
212
+ aten.fmod.Tensor_out,
213
+ aten.fmod_.Scalar,
214
+ aten.fmod_.Tensor,
215
+ aten.frac.default,
216
+ aten.frac.out,
217
+ aten.frac_.default,
218
+ aten.ge.Scalar,
219
+ aten.ge.Tensor,
220
+ aten.gelu.default,
221
+ aten.gt.Tensor,
222
+ aten.gt.Tensor_out,
223
+ aten.gt.Scalar,
224
+ aten.gt.Scalar_out,
225
+ aten.gt.Scalar,
226
+ aten.gt.Tensor,
227
+ aten.hypot.default,
228
+ aten.hypot.out,
229
+ aten.hypot_.default,
230
+ aten.i0.default,
231
+ aten.i0.out,
232
+ aten.i0_.default,
233
+ aten.igamma.default,
234
+ aten.igamma.out,
235
+ aten.igamma_.default,
236
+ aten.igammac.default,
237
+ aten.igammac.out,
238
+ aten.igammac_.default,
239
+ aten.isinf.default,
240
+ aten.isnan.default,
241
+ aten.isneginf.default,
242
+ aten.isneginf.out,
243
+ aten.isposinf.default,
244
+ aten.isposinf.out,
245
+ aten.ldexp.default,
246
+ aten.ldexp.out,
247
+ aten.ldexp_.default,
248
+ aten.lt.Tensor,
249
+ aten.lt.Tensor_out,
250
+ aten.lt.Scalar,
251
+ aten.lt.Scalar_out,
252
+ aten.le.Scalar,
253
+ aten.le.Tensor,
254
+ aten.lerp.Scalar,
255
+ aten.lerp.Scalar_out,
256
+ aten.lerp.Tensor,
257
+ aten.lerp.Tensor_out,
258
+ aten.lerp_.Scalar,
259
+ aten.lerp_.Tensor,
260
+ aten.lgamma.default,
261
+ aten.lgamma.out,
262
+ aten.lgamma_.default,
263
+ aten.log.default,
264
+ aten.log.out,
265
+ aten.log10.default,
266
+ aten.log10.out,
267
+ aten.log10_.default,
268
+ aten.log1p.default,
269
+ aten.log1p.out,
270
+ aten.log1p_.default,
271
+ aten.log2.default,
272
+ aten.log2.out,
273
+ aten.log2_.default,
274
+ aten.log_.default,
275
+ aten.logaddexp.default,
276
+ aten.logaddexp.out,
277
+ aten.logaddexp2.default,
278
+ aten.logaddexp2.out,
279
+ aten.logical_and.default,
280
+ aten.logical_and.out,
281
+ aten.logical_and_.default,
282
+ aten.logical_not.default,
283
+ aten.logical_not.out,
284
+ aten.logical_not_.default,
285
+ aten.logical_or.default,
286
+ aten.logical_or.out,
287
+ aten.logical_or_.default,
288
+ aten.logical_xor.default,
289
+ aten.logical_xor.out,
290
+ aten.logical_xor_.default,
291
+ aten.logit.default,
292
+ aten.logit.out,
293
+ aten.logit_.default,
294
+ aten.masked_fill.Scalar,
295
+ aten.masked_fill_.Scalar,
296
+ aten.maximum.default,
297
+ aten.maximum.out,
298
+ aten.minimum.default,
299
+ aten.minimum.out,
300
+ aten.mul.out,
301
+ aten.mvlgamma.default,
302
+ aten.mvlgamma.out,
303
+ aten.mvlgamma_.default,
304
+ aten.native_dropout_backward.default,
305
+ aten.native_dropout_backward.out,
306
+ aten.nan_to_num.default,
307
+ aten.nan_to_num.out,
308
+ aten.nan_to_num_.default,
309
+ aten.ne.Scalar,
310
+ aten.neg.default,
311
+ aten.neg.out,
312
+ aten.neg_.default,
313
+ aten.nextafter.default,
314
+ aten.nextafter.out,
315
+ aten.nextafter_.default,
316
+ aten.polygamma.default,
317
+ aten.polygamma.out,
318
+ aten.polygamma_.default,
319
+ aten.positive.default,
320
+ aten.pow.Scalar,
321
+ aten.pow.Scalar_out,
322
+ aten.pow.Tensor_Scalar,
323
+ aten.pow.Tensor_Scalar_out,
324
+ aten.pow.Tensor_Tensor,
325
+ aten.pow.Tensor_Tensor_out,
326
+ aten.pow_.Scalar,
327
+ aten.pow_.Tensor,
328
+ aten.reciprocal.default,
329
+ aten.reciprocal.out,
330
+ aten.reciprocal_.default,
331
+ aten.rad2deg.default,
332
+ aten.rad2deg.out,
333
+ aten.rad2deg_.default,
334
+ aten.relu.default,
335
+ aten.relu_.default,
336
+ aten.remainder.Scalar,
337
+ aten.remainder.Scalar_Tensor,
338
+ aten.remainder.Scalar_out,
339
+ aten.remainder.Tensor,
340
+ aten.remainder.Tensor_out,
341
+ aten.remainder_.Scalar,
342
+ aten.remainder_.Tensor,
343
+ aten.round.decimals,
344
+ aten.round.decimals_out,
345
+ aten.round.default,
346
+ aten.round.out,
347
+ aten.round_.decimals,
348
+ aten.round_.default,
349
+ aten.rsqrt.default,
350
+ aten.rsqrt.out,
351
+ aten.rsqrt_.default,
352
+ aten.rsub.Scalar,
353
+ aten.sgn.default,
354
+ aten.sgn.out,
355
+ aten.sgn_.default,
356
+ aten.sigmoid.default,
357
+ aten.sigmoid.out,
358
+ aten.sigmoid_.default,
359
+ aten.sign.default,
360
+ aten.sign.out,
361
+ aten.sign_.default,
362
+ aten.signbit.default,
363
+ aten.signbit.out,
364
+ aten.silu.default,
365
+ aten.silu.out,
366
+ aten.sin.default,
367
+ aten.sin.out,
368
+ aten.sin_.default,
369
+ aten.sinc.default,
370
+ aten.sinc.out,
371
+ aten.sinc_.default,
372
+ aten.sinh.default,
373
+ aten.sinh.out,
374
+ aten.sinh_.default,
375
+ aten.sqrt.default,
376
+ aten.sqrt.out,
377
+ aten.sqrt_.default,
378
+ aten.square.default,
379
+ aten.square.out,
380
+ aten.square_.default,
381
+ aten.sub.Scalar,
382
+ aten.sub.Tensor,
383
+ aten.sub.out,
384
+ aten.sub_.Scalar,
385
+ aten.sub_.Tensor,
386
+ aten.tan.default,
387
+ aten.tan.out,
388
+ aten.tan_.default,
389
+ aten.tanh.default,
390
+ aten.tanh.out,
391
+ aten.tanh_.default,
392
+ aten.true_divide.Tensor,
393
+ aten.trunc.default,
394
+ aten.trunc.out,
395
+ aten.trunc_.default,
396
+ aten.where.self,
397
+ aten.where.self_out,
398
+ aten.xlogy.OutScalar_Self,
399
+ aten.xlogy.OutScalar_Other,
400
+ aten.xlogy.OutTensor,
401
+ aten.xlogy.Scalar_Other,
402
+ aten.xlogy.Scalar_Self,
403
+ aten.xlogy.Tensor,
404
+ aten.xlogy_.Scalar_Other,
405
+ aten.xlogy_.Tensor,
406
+ # backward point-wise ops
407
+ # please keep the entries below alphabetically sorted
408
+ aten.gelu_backward.default,
409
+ aten.sigmoid_backward.default,
410
+ aten.silu_backward.default,
411
+ aten.tanh_backward.default,
412
+ aten.threshold_backward.default,
413
+ ]
414
+
415
+ # the linear pointwise ops map, key is op, value is the type of linearity
416
+ linear_pointwise_ops = {
417
+ aten.to.dtype: 0,
418
+ aten.add.Tensor: 1,
419
+ aten.add_.Tensor: 1,
420
+ aten.div.Scalar: 0,
421
+ aten.div_.Scalar: 0,
422
+ aten.mul.Scalar: 0,
423
+ aten.mul_.Scalar: 0,
424
+ aten.mul.Tensor: 2,
425
+ aten.mul_.Tensor: 2,
426
+ aten.copy_.default: 1,
427
+ }
428
+
429
+
430
+ def pointwise_strategy(op_schema: OpSchema, linearity: int = -1) -> OpStrategy:
431
+ followed_strategy_index = -1
432
+ max_shards = -1
433
+ max_ndim = -1
434
+
435
+ if op_schema.is_inplace_op():
436
+ # inplace op should follow the first arg strategy
437
+ followed_strategy = op_schema.args_schema[0]
438
+ followed_strategy_index = 0
439
+ elif op_schema.is_out_variant_op():
440
+ # out variant op should follow the out kwarg strategy
441
+ followed_strategy = op_schema.kwargs_schema["out"]
442
+ # out variant is technically a kwarg for the strategy to follow so it does not
443
+ # have an "index", we set it to a reasonably large number just to indicate it's
444
+ # not a valid index
445
+ followed_strategy_index = 100
446
+ else:
447
+ # normal pointwise op, we choose to follow the arg with
448
+ # the max shards in case operands needs reshard
449
+ # in case of multiple operands with max shard, we take
450
+ # the one with the max number of dimensions
451
+ for idx, arg_strategy in enumerate(op_schema.args_schema):
452
+ if not isinstance(arg_strategy, OpStrategy):
453
+ continue
454
+
455
+ arg_max_shards = arg_strategy.max_num_shards()
456
+ arg_max_ndim = arg_strategy.ndim
457
+ if (arg_max_shards > max_shards) or (
458
+ arg_max_shards == max_shards and arg_max_ndim > max_ndim
459
+ ):
460
+ followed_strategy_index = idx
461
+ max_shards = arg_max_shards
462
+ max_ndim = arg_max_ndim
463
+
464
+ followed_strategy = op_schema.args_schema[followed_strategy_index]
465
+
466
+ assert isinstance(followed_strategy, OpStrategy), (
467
+ f"no strategy to follow for {op_schema}!"
468
+ )
469
+ return common_pointwise_strategy(
470
+ op_schema.args_schema,
471
+ followed_strategy,
472
+ followed_strategy_index,
473
+ linearity,
474
+ )
475
+
476
+
477
+ def linear_pointwise_strategy(op_schema: OpSchema) -> StrategyType:
478
+ """
479
+ Linear pointwise operators can propagate pending reductions.
480
+ For example, c = add(a, b); if a is pending sum, then c will be
481
+ pending sum as well without any communication overhead.
482
+
483
+ Note that:
484
+ 1. Only unary and binary operations are supported, out variant
485
+ ops are not supported.
486
+ 2. There're multiple types of linearity, refer to the doc of
487
+ common_pointwise_strategy for more details.
488
+ """
489
+ linearity_type = linear_pointwise_ops.get(op_schema.op, -1)
490
+ return pointwise_strategy(op_schema, linearity=linearity_type)
491
+
492
+
493
+ def common_pointwise_strategy(
494
+ args_schema: Sequence[object],
495
+ followed_strategy: OpStrategy,
496
+ followed_strategy_index: int,
497
+ linearity: int = -1,
498
+ scalar_tensor_idx: int | None = None,
499
+ ) -> OpStrategy:
500
+ """
501
+ Common strategy for pointwise operations.
502
+
503
+ Args:
504
+ args_schema: Input arguments schema
505
+ followed_strategy: Strategy to follow for output placement
506
+ followed_strategy_index: Index of the strategy being followed
507
+ linearity: depending on the operator, we support different types of linearity
508
+ -1: the operation does not support linearity
509
+ 0: the unary operation that supports linearity, output propagates partial.
510
+ 1: the binary operation supports add linearity, where it requires every operand
511
+ to be partial, output propagates partial.
512
+ 2: the binary operation supports multiplicative linearity, where it requires
513
+ the primary operand to be partial, and the other operands to be replicate,
514
+ output propagates partial.
515
+ scalar_tensor_idx: Index of the Replicate scalar tensor for which we allow the mesh
516
+ to be different from the mesh of followed_strategy
517
+ """
518
+ # handle broadcasting
519
+ common_shape = torch.broadcast_shapes(
520
+ *[arg.shape for arg in args_schema if isinstance(arg, OpStrategy)]
521
+ )
522
+ pointwise_strategy = OpStrategy([])
523
+
524
+ for op_spec in followed_strategy.strategies:
525
+ spec_to_follow = op_spec.output_spec
526
+
527
+ out_placements: list[Placement] = []
528
+ for placement in spec_to_follow.placements:
529
+ if isinstance(placement, Shard | _StridedShard):
530
+ shard_dim = normalize_dim(placement.dim, len(spec_to_follow.shape))
531
+ common_ndim = len(common_shape)
532
+ new_shard_dim = common_ndim - len(spec_to_follow.shape) + shard_dim
533
+ if isinstance(placement, _StridedShard):
534
+ out_placements.append(
535
+ _StridedShard(
536
+ new_shard_dim, split_factor=placement.split_factor
537
+ )
538
+ )
539
+ else:
540
+ out_placements.append(Shard(new_shard_dim))
541
+ elif isinstance(placement, Partial):
542
+ # note that only partial-sum and partial-avg are supported for linearity
543
+ partial_supports_linearity = placement.is_partial(
544
+ "sum"
545
+ ) or placement.is_partial("avg")
546
+ if linearity > 0 and partial_supports_linearity:
547
+ # propagate the partial placement
548
+ out_placements.append(placement)
549
+ else:
550
+ # clear the partial placement if op does not support linearity
551
+ # by default we just replicate the partial, need to see if this
552
+ # is optimal for all cases
553
+ out_placements.append(Replicate())
554
+ else:
555
+ out_placements.append(placement)
556
+
557
+ input_specs: list[DTensorSpec] = []
558
+ redistribute_costs: list[list[float]] = []
559
+ for input_idx, input_arg in enumerate(args_schema):
560
+ if isinstance(input_arg, OpStrategy):
561
+ input_arg_spec = input_arg.strategies[0].output_spec
562
+
563
+ # sanity check that all args that follow the same strategy
564
+ # are on the same DeviceMesh
565
+ if input_arg.mesh != followed_strategy.mesh:
566
+ # For the scalar tensor arg in fused ops, do not follow followed_strategy;
567
+ # instead, let the input mesh and the Replicate placements propagate through.
568
+ if input_idx == scalar_tensor_idx:
569
+ assert all(p == Replicate() for p in input_arg_spec.placements)
570
+ input_arg_target_spec = DTensorSpec(
571
+ mesh=input_arg.mesh,
572
+ placements=input_arg_spec.placements,
573
+ tensor_meta=input_arg_spec.tensor_meta,
574
+ )
575
+ input_specs.append(input_arg_target_spec)
576
+ redistribute_costs.append(
577
+ generate_redistribute_costs(
578
+ input_arg, input_arg_target_spec
579
+ )
580
+ )
581
+ continue
582
+ else:
583
+ raise ValueError(
584
+ f"Could not run pointwise computation across different mesh: "
585
+ f"Found {input_arg.mesh} and {followed_strategy.mesh}!"
586
+ )
587
+
588
+ # every arg follow the out_placements, but need to handle broadcasting
589
+ input_arg_dims_map = infer_broadcast_dims_map(
590
+ common_shape, input_arg_spec.shape
591
+ )
592
+
593
+ # Determine if this input should convert Partial to Replicate base on linearity
594
+ should_convert_partial = (
595
+ linearity == 2
596
+ and input_idx
597
+ != followed_strategy_index # Don't convert the "followed" strategy
598
+ )
599
+
600
+ input_target_placements = map_placements_after_broadcast(
601
+ tuple(out_placements),
602
+ common_shape,
603
+ input_arg_dims_map,
604
+ partial_to_replicate=should_convert_partial,
605
+ )
606
+
607
+ input_arg_target_spec = DTensorSpec(
608
+ mesh=followed_strategy.mesh,
609
+ placements=input_target_placements,
610
+ tensor_meta=input_arg_spec.tensor_meta,
611
+ )
612
+ input_specs.append(input_arg_target_spec)
613
+ redistribute_costs.append(
614
+ generate_redistribute_costs(input_arg, input_arg_target_spec)
615
+ )
616
+
617
+ pointwise_strategy.strategies.append(
618
+ OpSpec(
619
+ output_specs=DTensorSpec(
620
+ mesh=followed_strategy.mesh,
621
+ placements=tuple(out_placements),
622
+ ),
623
+ input_specs=input_specs,
624
+ redistribute_cost=redistribute_costs,
625
+ )
626
+ )
627
+ return pointwise_strategy
628
+
629
+
630
+ for op in linear_pointwise_ops:
631
+ register_op_strategy(op, schema_info=RuntimeSchemaInfo(static_kwargkey=["out"]))(
632
+ linear_pointwise_strategy
633
+ )
634
+
635
+ for op in pointwise_ops:
636
+ register_op_strategy(op, schema_info=RuntimeSchemaInfo(static_kwargkey=["out"]))(
637
+ pointwise_strategy
638
+ )
639
+
640
+
641
+ # TODO: add all for_each ops
642
+ for_each_ops = [
643
+ aten._foreach_abs.default,
644
+ aten._foreach_abs_.default,
645
+ aten._foreach_addcdiv_.Scalar,
646
+ aten._foreach_addcdiv_.ScalarList,
647
+ aten._foreach_addcdiv_.Tensor,
648
+ aten._foreach_addcmul.Scalar,
649
+ aten._foreach_addcmul_.Scalar,
650
+ aten._foreach_addcmul_.ScalarList,
651
+ aten._foreach_addcmul_.Tensor,
652
+ aten._foreach_clamp_max_.Scalar,
653
+ aten._foreach_clamp_min_.Scalar,
654
+ aten._foreach_div_.List,
655
+ aten._foreach_div_.Scalar,
656
+ aten._foreach_div_.ScalarList,
657
+ aten._foreach_div_.Tensor,
658
+ aten._foreach_div.List,
659
+ aten._foreach_div.Scalar,
660
+ aten._foreach_div.ScalarList,
661
+ aten._foreach_div.Tensor,
662
+ aten._foreach_lerp_.Scalar,
663
+ aten._foreach_maximum_.List,
664
+ aten._foreach_mul.Scalar,
665
+ aten._foreach_mul.ScalarList,
666
+ aten._foreach_mul.Tensor,
667
+ aten._foreach_mul.List,
668
+ aten._foreach_mul_.Scalar,
669
+ aten._foreach_mul_.ScalarList,
670
+ aten._foreach_mul_.Tensor,
671
+ aten._foreach_mul_.List,
672
+ aten._foreach_pow.List,
673
+ aten._foreach_pow.ScalarList,
674
+ aten._foreach_neg.default,
675
+ aten._foreach_neg_.default,
676
+ aten._foreach_reciprocal_.default,
677
+ aten._foreach_sub.Scalar,
678
+ aten._foreach_sub_.Scalar,
679
+ aten._foreach_sub.List,
680
+ aten._foreach_sub_.List,
681
+ aten._foreach_sub.ScalarList,
682
+ aten._foreach_sub_.ScalarList,
683
+ aten._foreach_sqrt.default,
684
+ aten._foreach_sqrt_.default,
685
+ aten._foreach_zero_.default,
686
+ aten._foreach_exp.default,
687
+ aten._foreach_exp_.default,
688
+ aten._foreach_cos.default,
689
+ aten._foreach_cos_.default,
690
+ aten._foreach_log.default,
691
+ aten._foreach_log_.default,
692
+ aten._amp_foreach_non_finite_check_and_unscale_.default,
693
+ ]
694
+
695
+ for_each_linearity_ops = [
696
+ aten._foreach_add.Scalar,
697
+ aten._foreach_add_.Scalar,
698
+ aten._foreach_add_.ScalarList,
699
+ aten._foreach_add.List,
700
+ aten._foreach_add_.List,
701
+ ]
702
+
703
+
704
+ def list_pointwise_strategy(
705
+ op_schema: OpSchema, linearity: bool = False
706
+ ) -> StrategyType:
707
+ """
708
+ Apply the pointwise strategy to the zipped arguments. For example, if we
709
+ run a foreach add of two lists l1 and l2, then we apply the pointwise
710
+ strategy on each pair (l1[i], l2[i]). If the first argument is a list but
711
+ the second (or later) one is a tensor, then we broadcast the tensor by
712
+ replicating it into a list with the length of the first argument.
713
+
714
+ Args:
715
+ mesh (DeviceMesh): device mesh for pointwise ops
716
+ op_schema (OpSchema): schema of the operator to generate strategy for
717
+ linearity (bool): specify whether op(a) + op(b) = op(a + b)
718
+
719
+ Returns:
720
+ OpStrategy: generated strategy
721
+ """
722
+
723
+ def args_tuple_strategies(
724
+ args_schema: tuple[object, ...],
725
+ ) -> list[TupleStrategy | None]:
726
+ first_arg = args_schema[0]
727
+ assert isinstance(first_arg, TupleStrategy)
728
+ strategy_len = len(first_arg.children)
729
+ tuple_strategies: list[TupleStrategy | None] = []
730
+ for arg_idx, arg in enumerate(args_schema):
731
+ if isinstance(arg, TupleStrategy):
732
+ # every tuple strategy should have the same length
733
+ assert len(arg.children) == strategy_len
734
+ tuple_strategies.append(arg)
735
+ elif isinstance(arg, OpStrategy):
736
+ if arg_idx > 0: # implicitly broadcast
737
+ tuple_strategies.append(
738
+ TupleStrategy([arg for _ in range(strategy_len)])
739
+ )
740
+ else:
741
+ raise RuntimeError(
742
+ f"list op only supports tuple strategy! {op_schema}"
743
+ )
744
+ else:
745
+ # insert None as placeholder so that the idx of arg is kept
746
+ tuple_strategies.append(None)
747
+ return tuple_strategies
748
+
749
+ args_strategies = args_tuple_strategies(op_schema.args_schema)
750
+ follow_strategy: TupleStrategy = not_none(args_strategies[0])
751
+ list_strategy: list[OpStrategy] = []
752
+
753
+ for child_idx, child_strtgy in enumerate(follow_strategy.children):
754
+ assert isinstance(child_strtgy, OpStrategy)
755
+ args_schema: list[OpStrategy | None] = [
756
+ cast(OpStrategy, arg_strategy.children[child_idx]) if arg_strategy else None
757
+ for arg_strategy in args_strategies
758
+ ]
759
+ pointwise_strategy: OpStrategy = common_pointwise_strategy(
760
+ args_schema,
761
+ child_strtgy,
762
+ linearity,
763
+ scalar_tensor_idx=(
764
+ _FUSED_OP_SCALAR_IDX if op_schema.op in fused_ops else None
765
+ ),
766
+ )
767
+ list_strategy.append(pointwise_strategy)
768
+ return TupleStrategy(list_strategy)
769
+
770
+
771
+ def list_linear_pointwise_strategy(op_schema: OpSchema) -> StrategyType:
772
+ """
773
+ for each list op stratgy that supports linearity
774
+ """
775
+ return list_pointwise_strategy(op_schema, linearity=True)
776
+
777
+
778
+ for op in for_each_ops:
779
+ register_op_strategy(op, schema_info=RuntimeSchemaInfo(needs_pytree=True))(
780
+ list_pointwise_strategy
781
+ )
782
+
783
+ for op in for_each_linearity_ops:
784
+ register_op_strategy(op, schema_info=RuntimeSchemaInfo(needs_pytree=True))(
785
+ list_linear_pointwise_strategy
786
+ )
787
+
788
+ fused_ops = [
789
+ aten._fused_adam_.default,
790
+ aten._fused_adam.default,
791
+ aten._fused_adam.tensor_lr,
792
+ aten._fused_adam_.tensor_lr,
793
+ aten._fused_adamw_.default,
794
+ aten._fused_adamw.default,
795
+ aten._fused_adamw.tensor_lr,
796
+ aten._fused_adamw_.tensor_lr,
797
+ ]
798
+
799
+
800
+ # The state_steps arg of fused adam / adamw is a Replicate scalar tensor, which will be put on
801
+ # the compute_mesh of an op across all parameter groups, even when not all parameter groups
802
+ # are on the same device mesh. This idx will help avoid hitting exceptions or unnecessary
803
+ # redistribute during sharding propagation.
804
+ _FUSED_OP_SCALAR_IDX = 5
805
+
806
+ for op in fused_ops:
807
+ register_op_strategy(op, schema_info=RuntimeSchemaInfo(needs_pytree=True))(
808
+ list_pointwise_strategy
809
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_random_ops.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ import torch
3
+ from torch.distributed.tensor._op_schema import (
4
+ OpSchema,
5
+ OpSpec,
6
+ OpStrategy,
7
+ StrategyType,
8
+ )
9
+ from torch.distributed.tensor._ops.registration import register_op_strategy
10
+ from torch.distributed.tensor._ops.utils import is_tensor_partial
11
+
12
+
13
+ aten = torch.ops.aten
14
+
15
+
16
+ @register_op_strategy(
17
+ [
18
+ aten.normal_.default,
19
+ aten.uniform_.default,
20
+ aten.native_dropout.default,
21
+ aten.bernoulli_.float,
22
+ aten.bernoulli.default,
23
+ ]
24
+ )
25
+ def random_op_strategy(op_schema: OpSchema) -> StrategyType:
26
+ self_strategy = op_schema.args_schema[0]
27
+ assert isinstance(self_strategy, OpStrategy)
28
+
29
+ random_strategy = OpStrategy([])
30
+ for arg_strategy in self_strategy.strategies:
31
+ arg_spec = arg_strategy.output_spec
32
+ if is_tensor_partial(arg_spec):
33
+ # TODO: figure out how inplace random op should behave when it's partial
34
+ raise RuntimeError(f"{op_schema.op} with Partial is not supported yet!")
35
+ random_strategy.strategies.append(
36
+ OpSpec(
37
+ output_specs=arg_spec,
38
+ input_specs=(arg_spec,),
39
+ redistribute_cost=[[0.0] * len(self_strategy.strategies)],
40
+ )
41
+ )
42
+
43
+ return random_strategy
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_tensor_ops.py ADDED
@@ -0,0 +1,1258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+ from collections.abc import Sequence, Sized
4
+ from typing import cast
5
+
6
+ import torch
7
+ from torch._prims_common import IntLike
8
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec
9
+ from torch.distributed.tensor._op_schema import (
10
+ OpSchema,
11
+ OpSpec,
12
+ OpStrategy,
13
+ OutputSharding,
14
+ PlacementList,
15
+ RuntimeSchemaInfo,
16
+ StrategyType,
17
+ TupleStrategy,
18
+ )
19
+ from torch.distributed.tensor._ops._common_rules import pointwise_rule
20
+ from torch.distributed.tensor._ops._embedding_ops import MaskPartial
21
+ from torch.distributed.tensor._ops.registration import (
22
+ register_op_strategy,
23
+ register_prop_rule,
24
+ )
25
+ from torch.distributed.tensor._ops.utils import (
26
+ expand_to_full_mesh_op_strategy,
27
+ generate_redistribute_costs,
28
+ is_tensor_dim_sharded,
29
+ is_tensor_evenly_shardable,
30
+ is_tensor_partial,
31
+ normalize_dim,
32
+ shift_shard_dims_after_insert,
33
+ shift_shard_dims_after_remove,
34
+ )
35
+ from torch.distributed.tensor.placement_types import (
36
+ Partial,
37
+ Placement,
38
+ Replicate,
39
+ Shard,
40
+ )
41
+ from torch.fx.experimental.symbolic_shapes import statically_known_true
42
+
43
+
44
+ aten = torch.ops.aten
45
+
46
+
47
+ def propagate_single_input_strategy(op_schema: OpSchema) -> StrategyType:
48
+ # For ops with a single tensor input, we perform a 1:1 mapping such that
49
+ # for each strategy that the input supports, we create a corresponding strategy.
50
+ # Note: this may be a complete waste of work, because it should be equivalent to
51
+ # `return first_input_strategy` (unless creating a deep copy is important for some reason)
52
+ if len([s for s in op_schema.args_schema if isinstance(s, OpStrategy)]) != 1:
53
+ raise AssertionError(
54
+ "propagate_single_input_strategy only works for single-tensor-input ops"
55
+ )
56
+ first_input_strategy = op_schema.args_schema[0]
57
+ if not isinstance(first_input_strategy, OpStrategy):
58
+ raise AssertionError(f"Expected OpStrategy, got {type(first_input_strategy)}")
59
+ return OpStrategy(
60
+ [
61
+ OpSpec(
62
+ output_specs=DTensorSpec(
63
+ mesh=first_input_strategy.mesh,
64
+ placements=strategy.output_spec.placements,
65
+ tensor_meta=strategy.output_spec.tensor_meta,
66
+ ),
67
+ input_specs=[
68
+ DTensorSpec(
69
+ mesh=first_input_strategy.mesh,
70
+ placements=strategy.output_spec.placements,
71
+ tensor_meta=strategy.output_spec.tensor_meta,
72
+ )
73
+ ],
74
+ redistribute_cost=[
75
+ generate_redistribute_costs(
76
+ first_input_strategy, strategy.output_spec
77
+ )
78
+ ],
79
+ )
80
+ for strategy in first_input_strategy.strategies
81
+ ]
82
+ )
83
+
84
+
85
+ register_op_strategy(
86
+ [
87
+ aten.clone.default,
88
+ aten.contiguous.default,
89
+ aten.detach.default,
90
+ aten.alias.default,
91
+ aten.fill_.Scalar,
92
+ aten.view.dtype,
93
+ aten.zero_.default,
94
+ ]
95
+ )(propagate_single_input_strategy)
96
+
97
+
98
+ register_op_strategy(
99
+ aten._to_copy.default, schema_info=RuntimeSchemaInfo(static_kwargkey=["dtype"])
100
+ )(propagate_single_input_strategy)
101
+
102
+
103
+ @register_op_strategy(
104
+ [
105
+ aten.equal.default,
106
+ aten.is_same_size.default,
107
+ ]
108
+ )
109
+ def equal_strategy(op_schema: OpSchema) -> StrategyType:
110
+ # equal_strategy deals with ops that comparing two tensor, we need to make sure
111
+ # sharding layout the same with two operands, we choose to follow the arg with max
112
+ # num of shards, still keep is_same_size here for completeness as they share the
113
+ # same strategy in theory.
114
+ mesh = op_schema.get_mesh_from_args()
115
+ self_strategy, other_strategy = op_schema.args_schema
116
+ if not isinstance(self_strategy, OpStrategy):
117
+ raise AssertionError(f"Expected OpStrategy, got {type(self_strategy)}")
118
+ if not isinstance(other_strategy, OpStrategy):
119
+ raise AssertionError(f"Expected OpStrategy, got {type(other_strategy)}")
120
+
121
+ select_strategy = (
122
+ self_strategy
123
+ if self_strategy.max_num_shards() >= other_strategy.max_num_shards()
124
+ else other_strategy
125
+ )
126
+ equal_strategy = OpStrategy([])
127
+
128
+ for arg_strategy in select_strategy.strategies:
129
+ arg_spec = arg_strategy.output_spec
130
+ if is_tensor_partial(arg_spec):
131
+ # if the arg_spec have partial, reshard to replicate
132
+ # otherwise local shard tensor comparison would be invalid
133
+ output_spec = DTensorSpec(
134
+ mesh=mesh,
135
+ placements=tuple(
136
+ Replicate() if isinstance(p, Partial) else p
137
+ for p in arg_spec.placements
138
+ ),
139
+ )
140
+ equal_strategy.strategies.append(OpSpec(output_specs=output_spec))
141
+ else:
142
+ equal_strategy.strategies.append(OpSpec(arg_spec))
143
+ return equal_strategy
144
+
145
+
146
+ register_op_strategy(
147
+ aten.empty_like.default, schema_info=RuntimeSchemaInfo(1, ["dtype"])
148
+ )(propagate_single_input_strategy)
149
+
150
+
151
+ @register_op_strategy(
152
+ [
153
+ aten.ones_like.default,
154
+ aten.rand_like.default,
155
+ aten.randn_like.default,
156
+ aten.zeros_like.default,
157
+ ],
158
+ schema_info=RuntimeSchemaInfo(1, ["dtype"]),
159
+ )
160
+ @register_op_strategy(
161
+ [aten.full_like.default],
162
+ schema_info=RuntimeSchemaInfo(2, ["dtype"]),
163
+ )
164
+ @register_op_strategy(
165
+ [
166
+ aten.randint_like.default,
167
+ aten.randint_like.low_dtype,
168
+ aten.randint_like.low_dtype_out,
169
+ ],
170
+ schema_info=RuntimeSchemaInfo(3, ["dtype"]),
171
+ )
172
+ def create_like_strategy(op_schema: OpSchema) -> StrategyType:
173
+ # create_like_strategy deals with ops that creating tensors with same
174
+ # shape as input, but with specific content that does not depend on
175
+ # the input, we can propagate sharding, but we have to make sure we
176
+ # move from partial to replicated.
177
+ select_strategy = op_schema.args_schema[0]
178
+ create_like_strategy = OpStrategy([])
179
+ if not isinstance(select_strategy, OpStrategy):
180
+ raise AssertionError(f"Expected OpStrategy, got {type(select_strategy)}")
181
+ for arg_strategy in select_strategy.strategies:
182
+ arg_spec = arg_strategy.output_spec
183
+ output_spec = DTensorSpec(
184
+ mesh=select_strategy.mesh,
185
+ placements=tuple(
186
+ Replicate() if isinstance(p, Partial) else p
187
+ for p in arg_spec.placements
188
+ ),
189
+ )
190
+ create_like_strategy.strategies.append(
191
+ OpSpec(output_specs=output_spec, input_specs=(arg_spec,))
192
+ )
193
+
194
+ return create_like_strategy
195
+
196
+
197
+ @register_op_strategy(
198
+ [
199
+ aten.new_empty.default,
200
+ aten.new_full.default,
201
+ aten.new_ones.default,
202
+ aten.new_zeros.default,
203
+ aten.new_empty_strided.default,
204
+ ],
205
+ schema_info=RuntimeSchemaInfo(1, ["dtype"]),
206
+ )
207
+ def new_factory_strategy(op_schema: OpSchema) -> StrategyType:
208
+ # Currently there are two strategies:
209
+ # 1. let the output be replicated
210
+ # 2. let the output follow the input if input and output have the same shape
211
+ input_strategy = op_schema.args_schema[0]
212
+ if not isinstance(input_strategy, OpStrategy):
213
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
214
+
215
+ mesh = input_strategy.mesh
216
+ input_shape = input_strategy.shape
217
+ output_shape = op_schema.args_schema[1]
218
+ if not isinstance(output_shape, list):
219
+ raise AssertionError(f"Expected list, got {type(output_shape)}")
220
+
221
+ new_factory_strategy = OpStrategy([])
222
+ for arg_strategy in input_strategy.strategies:
223
+ input_spec = arg_strategy.output_spec
224
+ replica_spec = DTensorSpec(mesh, tuple([Replicate()] * mesh.ndim))
225
+ new_factory_strategy.strategies.append(
226
+ OpSpec(
227
+ output_specs=replica_spec,
228
+ input_specs=(input_spec,),
229
+ redistribute_cost=[[0.0] * len(input_strategy.strategies)],
230
+ )
231
+ )
232
+
233
+ if tuple(input_shape) == tuple(output_shape) and input_spec.is_sharded():
234
+ # NOTE: for new_empty_strided, currently the non-replicate sharding
235
+ # is supported only when the shape is evenly shardable
236
+ if (
237
+ op_schema.op == aten.new_empty_strided.default
238
+ and not is_tensor_evenly_shardable(input_shape, input_spec)
239
+ ):
240
+ continue
241
+
242
+ new_factory_strategy.strategies.append(
243
+ OpSpec(
244
+ output_specs=input_spec,
245
+ input_specs=(input_spec,),
246
+ # encouraging new tensor placement to be the same as input
247
+ redistribute_cost=[[-0.1] * len(input_strategy.strategies)],
248
+ )
249
+ )
250
+
251
+ return new_factory_strategy
252
+
253
+
254
+ @register_op_strategy(aten.bucketize.Tensor)
255
+ def gen_bucketize_strategy(op_schema: OpSchema) -> StrategyType:
256
+ """Just propagate input sharding, but expect replicated for boundaries input."""
257
+ mesh = op_schema.get_mesh_from_args()
258
+ input_strategy, boundaries_strategy = op_schema.args_schema
259
+ bucketize_strategy = OpStrategy([])
260
+ if not isinstance(input_strategy, OpStrategy):
261
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
262
+ if not isinstance(boundaries_strategy, OpStrategy):
263
+ raise AssertionError(f"Expected OpStrategy, got {type(boundaries_strategy)}")
264
+ for arg_strategy in input_strategy.strategies:
265
+ arg_spec = DTensorSpec(
266
+ mesh,
267
+ arg_strategy.output_spec.placements,
268
+ arg_strategy.output_spec.tensor_meta,
269
+ )
270
+ replica_spec = DTensorSpec(
271
+ mesh,
272
+ tuple([Replicate()] * mesh.ndim),
273
+ boundaries_strategy.strategies[0].output_spec.tensor_meta,
274
+ )
275
+ bucketize_strategy.strategies.append(
276
+ OpSpec(
277
+ output_specs=arg_spec,
278
+ input_specs=(arg_spec, replica_spec),
279
+ redistribute_cost=[
280
+ generate_redistribute_costs(input_strategy, arg_spec),
281
+ generate_redistribute_costs(boundaries_strategy, replica_spec),
282
+ ],
283
+ )
284
+ )
285
+
286
+ return bucketize_strategy
287
+
288
+
289
+ @register_op_strategy(aten.select.int, schema_info=RuntimeSchemaInfo(1))
290
+ def select_int_strategy(op_schema: OpSchema) -> StrategyType:
291
+ """
292
+ In this select op, first determine the input specs, then determine the output specs.
293
+ - Input specs:
294
+ - If the input is sharded on the selected dim, unshard it and change to replicate.
295
+ - Otherwise, keep the original input specs.
296
+ - Output specs:
297
+ - It checks the input specs with the following cases:
298
+ - Case 1 shard_dim == selected_dim: not possible as the input is already unsharded.
299
+ - Case 2 shard_dim < selected_dim: keep the input specs.
300
+ - Case 3 shard_dim > selected_dim: shard_dim -= 1.
301
+ """
302
+ input_strategy = op_schema.args_schema[0]
303
+ if not isinstance(input_strategy, OpStrategy):
304
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
305
+ if len(op_schema.args_schema) != 3:
306
+ raise AssertionError(f"Expected 3 args, got {len(op_schema.args_schema)}")
307
+ selected_dim, index = (
308
+ cast(int, op_schema.args_schema[1]),
309
+ cast(int, op_schema.args_schema[2]),
310
+ )
311
+ input_shape = input_strategy.shape
312
+ input_ndim = input_strategy.ndim
313
+ selected_dim = normalize_dim(selected_dim, input_ndim)
314
+ index = normalize_dim(index, input_shape[selected_dim])
315
+
316
+ select_strategy = OpStrategy([])
317
+ for arg_strategy in input_strategy.strategies:
318
+ arg_spec = arg_strategy.output_spec
319
+
320
+ # determine input spec
321
+ input_specs = arg_spec
322
+ if is_tensor_dim_sharded(arg_spec, dim=selected_dim):
323
+ # if input is sharded on the selected dim, need to unshard it, change to replicate
324
+ arg_target_placements = unshard_tensor_dim(
325
+ arg_spec.placements, dim=selected_dim
326
+ )
327
+ input_specs = DTensorSpec(arg_spec.mesh, arg_target_placements) # R
328
+
329
+ # determine output spec
330
+ output_specs = input_specs
331
+ if input_specs.is_sharded():
332
+ # handle cases with sharded_dim != selected_dim
333
+ output_placements = shift_shard_dims_after_remove(
334
+ input_specs.placements, selected_dim
335
+ )
336
+ output_specs = DTensorSpec(
337
+ arg_spec.mesh, placements=tuple(output_placements)
338
+ )
339
+
340
+ select_strategy.strategies.append(
341
+ OpSpec(
342
+ output_specs=output_specs,
343
+ input_specs=(input_specs,),
344
+ )
345
+ )
346
+ return select_strategy
347
+
348
+
349
+ @register_op_strategy(
350
+ aten.select_backward.default,
351
+ schema_info=RuntimeSchemaInfo(1),
352
+ )
353
+ def select_backward_strategy(op_schema: OpSchema) -> OpStrategy:
354
+ # func: select_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt index) -> Tensor
355
+ args_schema = op_schema.args_schema
356
+ input_strategy, dim = args_schema[0], args_schema[2]
357
+ if not isinstance(input_strategy, OpStrategy):
358
+ raise AssertionError(f"Expected OpStrategy, got {input_strategy}")
359
+ if not isinstance(dim, int):
360
+ raise AssertionError(f"Expected int, got {type(dim)}")
361
+ output_strategies: list[OpSpec] = []
362
+ for placement_strategy in input_strategy.strategies:
363
+ input_spec = placement_strategy.output_spec
364
+ # NOTE: shard_dim is guaranteed to exist because
365
+ # grad_input has one more dim than grad_output
366
+ output_placements = shift_shard_dims_after_insert(input_spec.placements, dim)
367
+ output_specs = DTensorSpec(input_spec.mesh, tuple(output_placements))
368
+ output_strategies.append(
369
+ OpSpec(output_specs=output_specs, input_specs=(input_spec,))
370
+ )
371
+ return OpStrategy(output_strategies)
372
+
373
+
374
+ @register_op_strategy(aten.slice.Tensor, schema_info=RuntimeSchemaInfo(1))
375
+ def gen_slice_strategy(op_schema: OpSchema) -> StrategyType:
376
+ """Forward all shardings except the slice dimension."""
377
+ defaults = (None, 0, None, None, 1)
378
+ input_strategy, dim, start, end, step = (
379
+ op_schema.args_schema + defaults[len(op_schema.args_schema) :]
380
+ )
381
+ if not isinstance(input_strategy, OpStrategy):
382
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
383
+
384
+ mesh = input_strategy.mesh
385
+ input_shape = input_strategy.shape
386
+ input_ndim = input_strategy.ndim
387
+ if not isinstance(dim, int):
388
+ raise AssertionError(f"Expected int, got {type(dim)}")
389
+ if start is None:
390
+ start = 0
391
+ if end is None or statically_known_true(end > input_shape[dim]):
392
+ end = input_shape[dim]
393
+ if not isinstance(start, IntLike):
394
+ raise AssertionError(f"Expected IntLike, got {type(start)}")
395
+ if not isinstance(end, IntLike):
396
+ raise AssertionError(f"Expected IntLike, got {type(end)}")
397
+ if not isinstance(step, IntLike):
398
+ raise AssertionError(f"Expected IntLike, got {type(step)}")
399
+
400
+ # normalize args
401
+ slice_dim = normalize_dim(dim, input_ndim) # type: ignore[arg-type]
402
+ start = normalize_dim(start, input_shape[dim]) # type: ignore[arg-type]
403
+ end = normalize_dim(end, input_shape[dim]) # type: ignore[arg-type]
404
+
405
+ statically_redundant_slice = (
406
+ statically_known_true(start == 0)
407
+ and statically_known_true(end == input_shape[dim])
408
+ and statically_known_true(step == 1)
409
+ )
410
+
411
+ slice_strategy = OpStrategy([])
412
+
413
+ for arg_strategy in input_strategy.strategies:
414
+ arg_spec = arg_strategy.output_spec
415
+ if (
416
+ not is_tensor_dim_sharded(arg_spec, dim=slice_dim)
417
+ or statically_redundant_slice
418
+ ):
419
+ # only add the strategy if the slice dim is not sharded
420
+ out_spec = DTensorSpec(mesh, arg_spec.placements)
421
+ slice_strategy.strategies.append(
422
+ OpSpec(
423
+ output_specs=out_spec,
424
+ input_specs=(arg_spec,),
425
+ redistribute_cost=[[0.0] * len(input_strategy.strategies)],
426
+ )
427
+ )
428
+ if not slice_strategy.strategies:
429
+ # if all strategies are filtered out, unsharding all specs on slice dim
430
+ # of the input strategy, and use that as the op strategy
431
+ for arg_strategy in input_strategy.strategies:
432
+ arg_spec = arg_strategy.output_spec
433
+ unshard_spec = DTensorSpec(
434
+ mesh, unshard_tensor_dim(arg_spec.placements, dim=slice_dim)
435
+ )
436
+ slice_strategy.strategies.append(
437
+ OpSpec(
438
+ output_specs=unshard_spec,
439
+ redistribute_cost=[
440
+ generate_redistribute_costs(input_strategy, unshard_spec)
441
+ ],
442
+ )
443
+ )
444
+ return slice_strategy
445
+
446
+
447
+ @register_op_strategy(
448
+ aten.slice_backward.default,
449
+ schema_info=RuntimeSchemaInfo(1),
450
+ )
451
+ def slice_backward_rules(op_schema: OpSchema) -> OpStrategy:
452
+ # func: slice_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt start, SymInt end, SymInt step) -> Tensor
453
+ args_schema = op_schema.args_schema
454
+ input_strategy, dim = args_schema[0], args_schema[2]
455
+ if not isinstance(input_strategy, OpStrategy):
456
+ raise AssertionError(f"Expected OpStrategy, got {input_strategy}")
457
+ output_strategies: list[OpSpec] = []
458
+ for placement_strategy in input_strategy.strategies:
459
+ output_spec = placement_strategy.output_spec
460
+ new_placements: list[Placement] = []
461
+ for placement in output_spec.placements:
462
+ # Redistribute to replicate only if the dim is sharded and matches the slice dim
463
+ if isinstance(placement, Shard) and placement.dim == dim:
464
+ new_placements.append(Replicate())
465
+ else:
466
+ new_placements.append(placement)
467
+ new_spec = DTensorSpec(output_spec.mesh, tuple(new_placements))
468
+ redistribute_cost = [generate_redistribute_costs(input_strategy, new_spec)]
469
+ new_strategy = OpSpec(
470
+ output_specs=new_spec, redistribute_cost=redistribute_cost
471
+ )
472
+ output_strategies.append(new_strategy)
473
+ return OpStrategy(output_strategies)
474
+
475
+
476
+ def unshard_tensor_dim(
477
+ placements: Sequence[Placement], dim: int
478
+ ) -> tuple[Placement, ...]:
479
+ """Disallow the given tensor dimension to be sharded."""
480
+ return tuple(
481
+ p if (not isinstance(p, Shard) or p.dim != dim) else Replicate()
482
+ for p in placements
483
+ )
484
+
485
+
486
+ def replicate_tensor_dim(
487
+ placements: Sequence[Placement], dim: int
488
+ ) -> tuple[Placement, ...]:
489
+ """Force the given tensor dimension to be replicated."""
490
+ # Not using p.is_shard() to avoid mypy complain about Placement not having
491
+ # attribute dim.
492
+ return tuple(
493
+ Replicate() if p.is_partial() or isinstance(p, Shard) and p.dim == dim else p
494
+ for p in placements
495
+ )
496
+
497
+
498
+ @register_op_strategy(aten.slice_scatter.default, schema_info=RuntimeSchemaInfo(2))
499
+ def gen_slice_scatter_strategy(op_schema: OpSchema) -> StrategyType:
500
+ # 1. number of dimensions in input and src need to match.
501
+ # 2. number of elements on all non-dim need to match between input and src.
502
+ # 3. number of elements in src in dim need to match the slice size.
503
+ # Given the above:
504
+ # - We suggest for src to follow the sharding of input, except on the scatter dimension,
505
+ # where our best bet for now is to make them replicated as a fall-back.
506
+ # TODO: Ideally we'd like to make sure the output is re-sharded afterwards to keep input sharding.
507
+ mesh = op_schema.get_mesh_from_args()
508
+ input_strategy = op_schema.args_schema[0]
509
+ src_strategy = op_schema.args_schema[1]
510
+ if not isinstance(input_strategy, OpStrategy):
511
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
512
+ if not isinstance(src_strategy, OpStrategy):
513
+ raise AssertionError(f"Expected OpStrategy, got {type(src_strategy)}")
514
+ input_ndim = input_strategy.ndim
515
+ slice_dim = (
516
+ cast(int, op_schema.args_schema[2]) if len(op_schema.args_schema) > 2 else 0
517
+ )
518
+ slice_dim = normalize_dim(slice_dim, input_ndim)
519
+
520
+ slice_scatter_strategy = OpStrategy([])
521
+ # by default follow the input strategy for both input and src
522
+ for arg_strategy in input_strategy.strategies:
523
+ arg_spec = arg_strategy.output_spec
524
+ if not (
525
+ is_tensor_dim_sharded(arg_spec, dim=slice_dim)
526
+ or is_tensor_partial(arg_spec)
527
+ ):
528
+ input_spec = DTensorSpec(mesh, arg_spec.placements, arg_spec.tensor_meta)
529
+ # TODO: need to relax the constraint to src
530
+ src_spec = DTensorSpec(mesh, arg_spec.placements)
531
+ # only add the strategy if the slice_scatter dim is not sharded or partial
532
+ slice_scatter_strategy.strategies.append(
533
+ OpSpec(
534
+ output_specs=arg_spec,
535
+ input_specs=(input_spec, src_spec),
536
+ redistribute_cost=[
537
+ generate_redistribute_costs(input_strategy, input_spec),
538
+ generate_redistribute_costs(src_strategy, src_spec),
539
+ ],
540
+ )
541
+ )
542
+
543
+ if not slice_scatter_strategy.strategies:
544
+ # if all strategies are filtered out, replicating all specs on slice_scatter dim
545
+ # of the input strategy, and use that as the op strategy
546
+ for arg_strategy in input_strategy.strategies:
547
+ arg_spec = arg_strategy.output_spec
548
+ new_placement = replicate_tensor_dim(arg_spec.placements, dim=slice_dim)
549
+ input_spec = DTensorSpec(mesh, new_placement)
550
+ src_spec = DTensorSpec(mesh, new_placement)
551
+ slice_scatter_strategy.strategies.append(
552
+ OpSpec(
553
+ output_specs=input_spec,
554
+ input_specs=(input_spec, src_spec),
555
+ redistribute_cost=[
556
+ generate_redistribute_costs(input_strategy, input_spec),
557
+ generate_redistribute_costs(src_strategy, src_spec),
558
+ ],
559
+ )
560
+ )
561
+ return slice_scatter_strategy
562
+
563
+
564
+ @register_op_strategy(aten._local_scalar_dense.default)
565
+ def replica_only_strategy(op_schema: OpSchema) -> StrategyType:
566
+ """Only allow replication on the input/output."""
567
+ input_strategy = op_schema.args_schema[0]
568
+ if not isinstance(input_strategy, OpStrategy):
569
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
570
+ mesh = input_strategy.mesh
571
+ replicate_spec = DTensorSpec(mesh, tuple([Replicate()] * mesh.ndim))
572
+ return OpStrategy([OpSpec(replicate_spec)])
573
+
574
+
575
+ @register_op_strategy(
576
+ [
577
+ aten.scatter_.value,
578
+ aten.scatter.value,
579
+ aten.scatter_.src,
580
+ aten.scatter.src,
581
+ ],
582
+ schema_info=RuntimeSchemaInfo(1),
583
+ )
584
+ def scatter_strategy(op_schema: OpSchema) -> StrategyType:
585
+ mesh = op_schema.get_mesh_from_args()
586
+ single_mesh_dim_strategies = []
587
+
588
+ # placement list stores placements of [output, input, index, src]
589
+ # first we always have replicate all for inputs and output
590
+ if len(op_schema.args_strategy) < 3:
591
+ # scatter_.src/scatter.src with src be float number instead of tensor
592
+ all_replicate: PlacementList = [Replicate()] * 3
593
+ else:
594
+ all_replicate = [Replicate()] * 4
595
+ single_mesh_dim_strategies.append(all_replicate)
596
+
597
+ # TODO: see if we can support input sharding pattern
598
+ op_strategy = expand_to_full_mesh_op_strategy(
599
+ mesh,
600
+ op_schema,
601
+ single_mesh_dim_strategies,
602
+ inplace_op=op_schema.is_inplace_op(),
603
+ )
604
+ return op_strategy
605
+
606
+
607
+ @register_op_strategy(aten.scatter_add.default, schema_info=RuntimeSchemaInfo(1))
608
+ def scatter_add_strategy(op_schema: OpSchema) -> StrategyType:
609
+ input_strategy = op_schema.args_schema[0]
610
+ dim = op_schema.args_schema[1]
611
+ index_strategy = op_schema.args_schema[2]
612
+
613
+ if not isinstance(input_strategy, OpStrategy):
614
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
615
+ if not isinstance(index_strategy, OpStrategy):
616
+ raise AssertionError(f"Expected OpStrategy, got {type(index_strategy)}")
617
+ if not isinstance(dim, int):
618
+ raise AssertionError(f"Expected int, got {type(dim)}")
619
+ dim = normalize_dim(dim, input_strategy.ndim)
620
+ mesh = input_strategy.mesh
621
+ input_shape = input_strategy.shape
622
+ index_shape = index_strategy.shape
623
+
624
+ single_mesh_dim_strategies = []
625
+
626
+ # placement list stores placements of [output, input, index, src]
627
+ # first we always have replicate all for inputs and output
628
+ all_replicate: PlacementList = [Replicate()] * 4
629
+ single_mesh_dim_strategies.append(all_replicate)
630
+
631
+ if len(input_shape) == len(index_shape):
632
+ for d in range(len(input_shape)):
633
+ if d != dim and input_shape[d] == index_shape[d]:
634
+ sharding: PlacementList = [Shard(d), Shard(d), Shard(d), Shard(d)]
635
+ single_mesh_dim_strategies.append(sharding)
636
+
637
+ return expand_to_full_mesh_op_strategy(
638
+ mesh, op_schema, single_mesh_dim_strategies, input_index=1
639
+ )
640
+
641
+
642
+ @register_op_strategy(aten.gather.default, schema_info=RuntimeSchemaInfo(1))
643
+ def gather_strategy(op_schema: OpSchema) -> StrategyType:
644
+ mesh = op_schema.get_mesh_from_args()
645
+ input_strategy = cast(OpStrategy, op_schema.args_schema[0])
646
+ dim = cast(int, op_schema.args_schema[1])
647
+ dim = normalize_dim(dim, input_strategy.ndim)
648
+ index_strategy = cast(OpStrategy, op_schema.args_schema[2])
649
+
650
+ input_shape = input_strategy.shape
651
+ index_shape = index_strategy.shape
652
+
653
+ single_mesh_dim_strategies = []
654
+
655
+ # placement list stores placements of [output, input, index]
656
+ # first we always have replicate all for inputs and output
657
+ all_replicate: PlacementList = [Replicate()] * 3
658
+ single_mesh_dim_strategies.append(all_replicate)
659
+
660
+ # input sharding, input sharded, index accepts mask partial, output follows index
661
+ # this only works when the input is sharded on the gather dimension, and
662
+ # index has size 1 on the gather dimension
663
+ if dim < len(index_shape) and index_shape[dim] == 1:
664
+ index_partial_placement = MaskPartial(offset_shape=input_shape, offset_dim=dim)
665
+ input_sharding: PlacementList = [
666
+ index_partial_placement,
667
+ Shard(dim),
668
+ index_partial_placement,
669
+ ]
670
+ single_mesh_dim_strategies.append(input_sharding)
671
+
672
+ # index sharding, input replicated, index sharded, output follows index
673
+ # this only works when the sharding dimension is the gather dimension
674
+ index_sharding: PlacementList = [Shard(dim), Replicate(), Shard(dim)]
675
+ single_mesh_dim_strategies.append(index_sharding)
676
+
677
+ if len(input_shape) == len(index_shape):
678
+ for d in range(len(input_shape)):
679
+ if d != dim:
680
+ sharding: PlacementList = [Shard(d), Shard(d), Shard(d)]
681
+ single_mesh_dim_strategies.append(sharding)
682
+
683
+ return expand_to_full_mesh_op_strategy(
684
+ mesh, op_schema, single_mesh_dim_strategies, input_index=1
685
+ )
686
+
687
+
688
+ def _derive_follow_placements_from_tuple_strategy(
689
+ op: torch._ops.OpOverload,
690
+ tuple_strategy: TupleStrategy,
691
+ ) -> Sequence[Placement]:
692
+ """
693
+ derive the placements to follow from the tuple strategy, mainly used by
694
+ aten.stack, aten.cat, where each operand have the same shape, and correspondingly
695
+ expecting the same sharding
696
+ """
697
+
698
+ def merge_placement(
699
+ cur_placement: Placement, new_placement: Placement
700
+ ) -> Placement:
701
+ # semantic if we already have a follow placement, we
702
+ # check each placement for the current arg placement
703
+ # to see if we want to merge/adjust the placement to follow
704
+ # the priority: Partial -> Shard -> Replicate
705
+ if cur_placement == new_placement:
706
+ return cur_placement
707
+
708
+ if cur_placement.is_partial():
709
+ if new_placement.is_shard():
710
+ # follow new placement
711
+ return new_placement
712
+ elif new_placement.is_partial():
713
+ # different partial types, we can't merge and have to replicate all here
714
+ return Replicate()
715
+ else:
716
+ # follow partial
717
+ return cur_placement
718
+ elif cur_placement.is_shard():
719
+ if new_placement.is_shard():
720
+ # cur/new placement are different sharding (i.e. different shard dim)
721
+ # currently fallback to replicate all args
722
+ return Replicate()
723
+ else:
724
+ # for partial/replicate, follow the current shard placement
725
+ return cur_placement
726
+ else:
727
+ # current replicate, just follow new placement
728
+ return new_placement
729
+
730
+ follow_placements: list[Placement] | None = None
731
+ mesh = tuple_strategy.child_mesh(0)
732
+ for arg_strategy in tuple_strategy.children:
733
+ if not isinstance(arg_strategy, OpStrategy):
734
+ raise AssertionError(f"Expected OpStrategy, got {type(arg_strategy)}")
735
+ if arg_strategy.mesh != mesh:
736
+ raise ValueError(
737
+ f"All operands in {op} must have the same mesh, "
738
+ f"but got {arg_strategy.mesh} and {mesh}."
739
+ )
740
+
741
+ for placement_strategy in arg_strategy.strategies:
742
+ arg_placements = placement_strategy.output_spec.placements
743
+ if follow_placements is None:
744
+ follow_placements = list(arg_placements)
745
+ continue
746
+ if follow_placements is None:
747
+ raise AssertionError(
748
+ "follow_placements should not be None at this point"
749
+ )
750
+ for mesh_idx in range(mesh.ndim):
751
+ # merge placements with the priority
752
+ follow_placements[mesh_idx] = merge_placement(
753
+ follow_placements[mesh_idx], arg_placements[mesh_idx]
754
+ )
755
+ if follow_placements is None:
756
+ raise AssertionError("follow placements should not be None!")
757
+ return follow_placements
758
+
759
+
760
+ @register_op_strategy(aten.stack.default, RuntimeSchemaInfo(1, needs_pytree=True))
761
+ def stack_strategy(op_schema: OpSchema) -> StrategyType:
762
+ args_schema = op_schema.args_schema
763
+ input_tuple_strategy = args_schema[0]
764
+ if not isinstance(input_tuple_strategy, TupleStrategy):
765
+ raise AssertionError(f"Expected TupleStrategy, got {input_tuple_strategy}")
766
+ input_strategies: list[OpStrategy] = []
767
+ for child in input_tuple_strategy.children:
768
+ assert isinstance(child, OpStrategy), f"Expected OpStrategy, got {child}"
769
+ input_strategies.append(child)
770
+ first_input_strategy = input_strategies[0]
771
+ common_input_ndim = first_input_strategy.ndim
772
+ dim = cast(int, args_schema[1]) if len(args_schema) > 1 else 0
773
+ # normalize the dim to be within the common input ndim
774
+ dim = normalize_dim(dim, common_input_ndim)
775
+
776
+ mesh = first_input_strategy.mesh
777
+
778
+ follow_placements = _derive_follow_placements_from_tuple_strategy(
779
+ op_schema.op, input_tuple_strategy
780
+ )
781
+
782
+ # create op strategy base on the follow placements
783
+ op_strategy = OpStrategy([])
784
+
785
+ input_specs = tuple(
786
+ DTensorSpec(mesh, tuple(follow_placements))
787
+ for _ in range(len(input_tuple_strategy.children))
788
+ )
789
+
790
+ # stack op would "insert" new dim, so all sharded dim >= the inserted dim need to
791
+ # be normalized with the new Shard placement
792
+ follow_placements = shift_shard_dims_after_insert(follow_placements, dim)
793
+ output_spec = DTensorSpec(mesh, tuple(follow_placements))
794
+ redistribute_cost = [
795
+ generate_redistribute_costs(input_strategies[i], input_specs[i])
796
+ for i in range(len(input_specs))
797
+ ]
798
+ op_strategy.strategies.append(
799
+ OpSpec(
800
+ output_specs=output_spec,
801
+ input_specs=input_specs,
802
+ redistribute_cost=redistribute_cost,
803
+ )
804
+ )
805
+ return op_strategy
806
+
807
+
808
+ @register_op_strategy(aten.cat.default, RuntimeSchemaInfo(1, needs_pytree=True))
809
+ def cat_strategy(op_schema: OpSchema) -> StrategyType:
810
+ args_schema = op_schema.args_schema
811
+ input_tuple_strategy = args_schema[0]
812
+ if not isinstance(input_tuple_strategy, TupleStrategy):
813
+ raise AssertionError(f"Expected TupleStrategy, got {input_tuple_strategy}")
814
+ num_input_tensor = len(input_tuple_strategy.children)
815
+ first_input_strategy = input_tuple_strategy.children[0]
816
+ if not isinstance(first_input_strategy, OpStrategy):
817
+ raise AssertionError(f"Expected OpStrategy, got {first_input_strategy}")
818
+ common_input_ndim = first_input_strategy.ndim
819
+ dim = cast(int, args_schema[1]) if len(args_schema) > 1 else 0
820
+ # normalize the dim to be within the common input ndim
821
+ dim = normalize_dim(dim, common_input_ndim)
822
+
823
+ mesh = first_input_strategy.mesh
824
+
825
+ op_strategy = OpStrategy([])
826
+ # use a set to deduplicate strategies with the same placement
827
+ strategies_placement_pool = set()
828
+ for this_strategy in input_tuple_strategy.children:
829
+ # check strategy of each tensor to be concatenated
830
+ if not isinstance(this_strategy, OpStrategy):
831
+ raise AssertionError(f"Expected OpStrategy, got {type(this_strategy)}")
832
+ if this_strategy.mesh != mesh:
833
+ raise AssertionError("cat op doesn't support cross mesh concatenation")
834
+ for op_spec in this_strategy.strategies:
835
+ # Check each OpSpec of the tensor, the placement in this OpSpec
836
+ # is used as the exemplar strategy that other tensors and output
837
+ # tensor should follow. We also need to deduplicate the output
838
+ # strategy with the same placement.
839
+ if not isinstance(op_spec, OpSpec):
840
+ raise AssertionError(f"Expected OpSpec, got {type(op_spec)}")
841
+ # exemplar OpSpec to follow
842
+ exemplar_spec = op_spec.output_spec
843
+ # check if the tensor is sharded on the concat dim
844
+ if is_tensor_dim_sharded(exemplar_spec, dim):
845
+ # if the tensor is sharded on the concat dim, we need to unshard it
846
+ # first
847
+ exemplar_placement = unshard_tensor_dim(exemplar_spec.placements, dim)
848
+ else:
849
+ exemplar_placement = exemplar_spec.placements
850
+ if exemplar_placement not in strategies_placement_pool:
851
+ strategies_placement_pool.add(exemplar_placement)
852
+ # assert isinstance(exemplar_placement, Tuple)
853
+ redistribute_costs = []
854
+ input_specs = []
855
+ for idx in range(num_input_tensor):
856
+ # extract the strategy for the idx tensors to build the tensor_metadata and redistribute_cost
857
+ that_tensor_strategy = input_tuple_strategy.children[idx]
858
+ if not isinstance(that_tensor_strategy, OpStrategy):
859
+ raise AssertionError(
860
+ f"Expected OpStrategy, got {type(that_tensor_strategy)}"
861
+ )
862
+ input_spec = DTensorSpec(
863
+ mesh,
864
+ exemplar_placement,
865
+ tensor_meta=that_tensor_strategy.strategies[
866
+ 0
867
+ ].output_spec.tensor_meta,
868
+ )
869
+ input_specs.append(input_spec)
870
+ redistribute_costs.append(
871
+ generate_redistribute_costs(that_tensor_strategy, input_spec)
872
+ )
873
+ op_strategy.strategies.append(
874
+ OpSpec(
875
+ output_specs=DTensorSpec(mesh, exemplar_placement),
876
+ input_specs=tuple(input_specs),
877
+ redistribute_cost=redistribute_costs,
878
+ )
879
+ )
880
+ return op_strategy
881
+
882
+
883
+ @register_prop_rule(aten.index_select.default, schema_info=RuntimeSchemaInfo(1))
884
+ def prop_index_select(op_schema: OpSchema) -> OutputSharding:
885
+ values_spec, dim, indices_spec = op_schema.args_schema
886
+
887
+ if not isinstance(values_spec, DTensorSpec):
888
+ raise AssertionError(f"Expected DTensorSpec, got {type(values_spec)}")
889
+ if not isinstance(dim, int):
890
+ raise AssertionError(f"Expected int, got {type(dim)}")
891
+ if not isinstance(indices_spec, DTensorSpec):
892
+ raise AssertionError(f"Expected DTensorSpec, got {type(indices_spec)}")
893
+
894
+ all_indices_spec: list[DTensorSpec | None] = [
895
+ indices_spec if dim == i else None for i in range(values_spec.ndim)
896
+ ]
897
+
898
+ result = prop_index(
899
+ OpSchema(
900
+ op=op_schema.op,
901
+ args_schema=(values_spec, all_indices_spec),
902
+ kwargs_schema=op_schema.kwargs_schema,
903
+ )
904
+ )
905
+ if result.redistribute_schema:
906
+ schema_suggestion = result.redistribute_schema
907
+ result.redistribute_schema = OpSchema(
908
+ op=op_schema.op,
909
+ args_schema=(
910
+ schema_suggestion.args_schema[0],
911
+ dim,
912
+ schema_suggestion.args_schema[1][dim], # type: ignore[index]
913
+ ),
914
+ kwargs_schema=op_schema.kwargs_schema,
915
+ )
916
+ return result
917
+
918
+
919
+ @register_op_strategy(
920
+ [
921
+ aten.index_put.default,
922
+ aten._index_put_impl_.default,
923
+ ],
924
+ schema_info=RuntimeSchemaInfo(needs_pytree=True),
925
+ )
926
+ def prop_index_put(op_schema: OpSchema) -> StrategyType:
927
+ # We have 3 DTensor spec from argument `in`, `indices` and `values`
928
+ # accordingly.
929
+ in_spec, indices_spec, values_spec, *_ = op_schema.args_schema
930
+ if not isinstance(in_spec, OpStrategy):
931
+ raise AssertionError(f"Expected OpStrategy, got {type(in_spec)}")
932
+ # `indices`` is a tuple of scalar LongTensor, so we use TupleStrategy.
933
+ if not isinstance(indices_spec, TupleStrategy):
934
+ raise AssertionError(f"Expected TupleStrategy, got {type(indices_spec)}")
935
+ if not isinstance(values_spec, OpStrategy):
936
+ raise AssertionError(f"Expected OpStrategy, got {type(values_spec)}")
937
+ mesh = values_spec.mesh
938
+ op_strategy = OpStrategy([])
939
+ # 1. `indices` should all be replicated first.
940
+ indices_redistribute_costs = []
941
+ new_indices_spec: list[DTensorSpec | None] = []
942
+ for indices_spec_child in indices_spec.children:
943
+ if not isinstance(indices_spec_child, OpStrategy):
944
+ raise AssertionError(f"Expected OpStrategy, got {type(indices_spec_child)}")
945
+
946
+ replicated_spec = DTensorSpec(
947
+ mesh=mesh,
948
+ placements=tuple([Replicate()] * mesh.ndim),
949
+ tensor_meta=indices_spec_child.strategies[0].output_spec.tensor_meta,
950
+ )
951
+ new_indices_spec.append(replicated_spec)
952
+ child_costs = generate_redistribute_costs(indices_spec_child, replicated_spec)
953
+ indices_redistribute_costs.append(child_costs)
954
+
955
+ # 2. For placement rule of `values` and `in`, assume `values` shape =
956
+ # [a,b,c,d,e,f], `in` shape = [d,e,f]. Then `values`'s a,b,c (selected dim)
957
+ # must be replicated and d,e,f (nonselected dim) in both `values` and `in`
958
+ # should follow the same sharding (replicate or shard, but not partial).
959
+ size_offset = (
960
+ in_spec.strategies[0].output_spec.ndim
961
+ - values_spec.strategies[0].output_spec.ndim
962
+ )
963
+ # We can either let `values` follow `in`'s placements or reverse.
964
+ for exemplar_spec in [in_spec, values_spec]:
965
+ # use exemplar_spec as the target spec
966
+ for strategy in exemplar_spec.strategies:
967
+ in_spec_new_placements: list[Placement] = []
968
+ values_spec_new_placements: list[Placement] = []
969
+ placements = strategy.output_spec.placements
970
+ for placement in placements:
971
+ if placement.is_shard():
972
+ if not isinstance(placement, Shard):
973
+ raise AssertionError(f"Expected Shard, got {type(placement)}")
974
+ if exemplar_spec is in_spec:
975
+ # let `values_spce` follow `in_spec`
976
+ if placement.dim < size_offset:
977
+ # sharded on selected dim, need to change to replicate
978
+ in_spec_new_placements.append(Replicate())
979
+ values_spec_new_placements.append(Replicate())
980
+ else:
981
+ in_spec_new_placements.append(placement)
982
+ values_spec_new_placements.append(
983
+ Shard(placement.dim - size_offset)
984
+ )
985
+ else:
986
+ # let `in_spec` follow `values_spec`
987
+ in_spec_new_placements.append(
988
+ Shard(placement.dim + size_offset)
989
+ )
990
+ values_spec_new_placements.append(placement)
991
+ else:
992
+ in_spec_new_placements.append(Replicate())
993
+ values_spec_new_placements.append(Replicate())
994
+ new_in_spec = DTensorSpec(
995
+ mesh=mesh,
996
+ placements=tuple(in_spec_new_placements),
997
+ tensor_meta=in_spec.strategies[0].output_spec.tensor_meta,
998
+ )
999
+ new_values_spec = DTensorSpec(
1000
+ mesh=mesh,
1001
+ placements=tuple(values_spec_new_placements),
1002
+ tensor_meta=values_spec.strategies[0].output_spec.tensor_meta,
1003
+ )
1004
+ output_spec = DTensorSpec(
1005
+ mesh=mesh,
1006
+ placements=tuple(in_spec_new_placements),
1007
+ tensor_meta=in_spec.strategies[0].output_spec.tensor_meta,
1008
+ )
1009
+ cost_in_spec = generate_redistribute_costs(in_spec, new_in_spec)
1010
+ cost_values_spec = generate_redistribute_costs(values_spec, new_values_spec)
1011
+ op_strategy.strategies.append(
1012
+ OpSpec(
1013
+ input_specs=(
1014
+ new_in_spec,
1015
+ *new_indices_spec, # type: ignore[arg-type]
1016
+ new_values_spec,
1017
+ ),
1018
+ output_specs=output_spec,
1019
+ redistribute_cost=[
1020
+ cost_in_spec,
1021
+ *indices_redistribute_costs,
1022
+ cost_values_spec,
1023
+ ],
1024
+ )
1025
+ )
1026
+ return op_strategy
1027
+
1028
+
1029
+ @register_prop_rule(aten.index.Tensor, schema_info=RuntimeSchemaInfo(needs_pytree=True))
1030
+ def prop_index(op_schema: OpSchema) -> OutputSharding:
1031
+ """
1032
+ Expect replicated on the first input; _mostly_ pointwise on the second input.
1033
+
1034
+ TODO: exception: when the dtype of second input is "bool", then a torch.nonzero needs to be triggered first.
1035
+ """
1036
+ # Current sharding constraints:
1037
+ # For values:
1038
+ # 1. We currently require that the dimension of values_spec be replicated or partial
1039
+ # if they are being indexed on.
1040
+ # 2. Other dimensions of values_spec can remain sharded if they are so.
1041
+ # For indices:
1042
+ # Indices can be either sharded or replicated. All index tensors need to be sharded
1043
+ # in a compatible way, following the pointwise rule (including resolving Partial
1044
+ # into either sharded or replicated)
1045
+
1046
+ values_spec, multi_indices_spec = op_schema.args_schema
1047
+ if not isinstance(values_spec, DTensorSpec):
1048
+ raise AssertionError(f"Expected DTensorSpec, got {type(values_spec)}")
1049
+ if not isinstance(multi_indices_spec, list):
1050
+ raise AssertionError(f"Expected list, got {type(multi_indices_spec)}")
1051
+ multi_indices_spec = cast(list[DTensorSpec | None], multi_indices_spec)
1052
+ valid_indices_spec: list[tuple[int, DTensorSpec]] = [
1053
+ (i, a) for i, a in enumerate(multi_indices_spec) if a is not None
1054
+ ]
1055
+
1056
+ # 1. All indices have to be sharded equally. Moreover, indices can be broadcast.
1057
+ # Here, we piggyback on the pointwise sharding rule for indices.
1058
+ indices_out = pointwise_rule(
1059
+ OpSchema(
1060
+ op=op_schema.op,
1061
+ args_schema=tuple(v[1] for v in valid_indices_spec),
1062
+ kwargs_schema={},
1063
+ )
1064
+ )
1065
+ need_reshard_on_indices = indices_out.output_spec is None
1066
+
1067
+ if not need_reshard_on_indices:
1068
+ # this means that our inputs are already sharded properly and we will use that as our indices_spec
1069
+ if not isinstance(indices_out.output_spec, DTensorSpec):
1070
+ raise AssertionError(
1071
+ f"Expected DTensorSpec, got {type(indices_out.output_spec)}"
1072
+ )
1073
+ indices_spec: DTensorSpec = indices_out.output_spec
1074
+ else:
1075
+ if indices_out.redistribute_schema is None:
1076
+ raise AssertionError("redistribute_schema should not be None")
1077
+ valid_indices_suggestion = indices_out.redistribute_schema
1078
+ for i, v in enumerate(valid_indices_suggestion.args_spec):
1079
+ multi_indices_spec[valid_indices_spec[i][0]] = v
1080
+ # we'll need to call pointwise_rule again to see what's our ideal indices_spec and then
1081
+ # use that to compute our ideal values_spec
1082
+ indices_output_spec = pointwise_rule(valid_indices_suggestion).output_spec
1083
+ if not isinstance(indices_output_spec, DTensorSpec):
1084
+ raise AssertionError(
1085
+ f"Expected DTensorSpec, got {type(indices_output_spec)}"
1086
+ )
1087
+ indices_spec = indices_output_spec
1088
+
1089
+ lookup_dims = {v[0] for v in valid_indices_spec}
1090
+
1091
+ need_reshard_on_values = tuple(
1092
+ (isinstance(vp, Shard) and (vp.dim in lookup_dims or isinstance(ip, Shard)))
1093
+ for vp, ip in zip(values_spec.placements, indices_spec.placements)
1094
+ )
1095
+
1096
+ if not need_reshard_on_indices and not any(need_reshard_on_values):
1097
+ value_placements = values_spec.placements
1098
+
1099
+ all_dims_consecutive = all(
1100
+ b[0] - a[0] == 1
1101
+ for b, a in zip(valid_indices_spec[1:], valid_indices_spec[:-1])
1102
+ )
1103
+ if all_dims_consecutive:
1104
+ # if all index vectors are consecutives, insert at the dimension of the first index
1105
+ insert_dim: int = valid_indices_spec[0][0]
1106
+ else:
1107
+ # else, insert on the first dimension
1108
+ insert_dim = 0
1109
+
1110
+ def place(vp: Placement, ip: Placement) -> Placement:
1111
+ if isinstance(vp, Shard):
1112
+ return Shard(
1113
+ vp.dim
1114
+ if vp.dim < insert_dim
1115
+ # accounts for the offset in output dimensions
1116
+ else vp.dim
1117
+ + indices_spec.ndim
1118
+ - sum(1 if vp.dim > v[0] else 0 for v in valid_indices_spec)
1119
+ )
1120
+ if isinstance(ip, Shard):
1121
+ return Shard(ip.dim + insert_dim)
1122
+ # Partial or Replicated
1123
+ return vp
1124
+
1125
+ value_placements = tuple(
1126
+ place(vp, ip)
1127
+ for vp, ip in zip(values_spec.placements, indices_spec.placements)
1128
+ )
1129
+ result = OutputSharding(
1130
+ output_spec=DTensorSpec(
1131
+ mesh=values_spec.mesh,
1132
+ placements=value_placements,
1133
+ )
1134
+ )
1135
+ return result
1136
+ else:
1137
+ result = OutputSharding(
1138
+ output_spec=None,
1139
+ redistribute_schema=OpSchema(
1140
+ op=op_schema.op,
1141
+ args_schema=(
1142
+ DTensorSpec(
1143
+ mesh=values_spec.mesh,
1144
+ placements=tuple(
1145
+ Replicate() if need_reshard_on_values[i] else v
1146
+ for i, v in enumerate(values_spec.placements)
1147
+ ),
1148
+ tensor_meta=values_spec.tensor_meta,
1149
+ ),
1150
+ multi_indices_spec,
1151
+ ),
1152
+ kwargs_schema=op_schema.kwargs_schema,
1153
+ ),
1154
+ )
1155
+ return result
1156
+
1157
+
1158
+ @register_op_strategy(
1159
+ [
1160
+ aten.split.Tensor,
1161
+ aten.split_with_sizes.default,
1162
+ aten.split_with_sizes_copy.default,
1163
+ ],
1164
+ RuntimeSchemaInfo(1),
1165
+ )
1166
+ def split_strategy(op_schema: OpSchema) -> OpStrategy:
1167
+ input_strategy = op_schema.args_schema[0]
1168
+ split_size_or_sections = op_schema.args_schema[1]
1169
+ if not isinstance(input_strategy, OpStrategy):
1170
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
1171
+ input_ndim = input_strategy.ndim
1172
+ split_dim = (
1173
+ cast(int, op_schema.args_schema[2]) if len(op_schema.args_schema) > 2 else 0
1174
+ )
1175
+ dim = normalize_dim(split_dim, input_ndim)
1176
+
1177
+ def size_split(N, i) -> list:
1178
+ # Last chunk will be smaller if the tensor size N
1179
+ # along the given dimension dim is not divisible by i.
1180
+ if not i > 0:
1181
+ raise AssertionError(f"Split size must be positive, got {i}")
1182
+ return [i] * (N // i) + ([N % i] if N % i != 0 else [])
1183
+
1184
+ output_size_list = (
1185
+ size_split(input_strategy.shape[dim], split_size_or_sections)
1186
+ if isinstance(split_size_or_sections, int)
1187
+ else split_size_or_sections
1188
+ )
1189
+ if not isinstance(output_size_list, Sized):
1190
+ raise AssertionError(f"Expected Sized, got {type(output_size_list)}")
1191
+
1192
+ all_strategies = []
1193
+ for strategy in input_strategy.strategies:
1194
+ spec = strategy.output_spec
1195
+ placements = spec.placements
1196
+ if is_tensor_dim_sharded(spec, dim=dim):
1197
+ # if the input is sharded on the split dim, we need to unshard it
1198
+ placements = unshard_tensor_dim(spec.placements, dim=dim)
1199
+
1200
+ input_spec = DTensorSpec(spec.device_mesh, placements, spec.tensor_meta)
1201
+ output_specs = tuple(
1202
+ DTensorSpec(spec.device_mesh, placements)
1203
+ for _ in range(len(output_size_list))
1204
+ )
1205
+ all_strategies.append(
1206
+ OpSpec(
1207
+ output_specs=output_specs,
1208
+ input_specs=(input_spec,),
1209
+ redistribute_cost=[
1210
+ generate_redistribute_costs(input_strategy, input_spec)
1211
+ ],
1212
+ )
1213
+ )
1214
+
1215
+ return OpStrategy(all_strategies)
1216
+
1217
+
1218
+ # TODO: fix remaining failures in xfail("unbind") in test_dtensor_ops.py
1219
+ # and remove this xfail item
1220
+ @register_op_strategy(aten.unbind.int, schema_info=RuntimeSchemaInfo(1))
1221
+ def gen_unbind_strategy(op_schema: OpSchema) -> StrategyType:
1222
+ """Forward all shardings except the unbind dimension."""
1223
+ input_strategy = op_schema.args_schema[0]
1224
+ if not isinstance(input_strategy, OpStrategy):
1225
+ raise AssertionError(f"Expected OpStrategy, got {type(input_strategy)}")
1226
+ input_ndim = input_strategy.ndim
1227
+ input_shape = input_strategy.shape
1228
+ unbind_dim = (
1229
+ cast(int, op_schema.args_schema[1]) if len(op_schema.args_schema) > 1 else 0
1230
+ )
1231
+ unbind_dim = normalize_dim(unbind_dim, input_ndim)
1232
+
1233
+ mesh = input_strategy.mesh
1234
+ unbind_strategy = OpStrategy([])
1235
+ for arg_strategy in input_strategy.strategies:
1236
+ arg_spec = arg_strategy.output_spec
1237
+ if is_tensor_dim_sharded(arg_spec, dim=unbind_dim):
1238
+ raise RuntimeError(
1239
+ f"Attempted to unbind along the sharded dimension {unbind_dim}. ",
1240
+ "It cannot be performed without redistribution, which is disallowed "
1241
+ "by the current operator.",
1242
+ )
1243
+ # only add the strategy if the unbind dim is not sharded
1244
+ output_placements = shift_shard_dims_after_remove(
1245
+ arg_spec.placements, unbind_dim
1246
+ )
1247
+ output_specs = tuple(
1248
+ DTensorSpec(mesh, tuple(output_placements))
1249
+ for _ in range(input_shape[unbind_dim])
1250
+ )
1251
+ unbind_strategy.strategies.append(
1252
+ OpSpec(
1253
+ output_specs=output_specs,
1254
+ input_specs=(arg_spec,),
1255
+ redistribute_cost=[[0.0] * len(input_strategy.strategies)],
1256
+ )
1257
+ )
1258
+ return unbind_strategy
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/_view_ops.py ADDED
@@ -0,0 +1,798 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+ from collections.abc import Callable, Iterable, Sequence
4
+ from dataclasses import dataclass
5
+ from typing import cast, Optional
6
+
7
+ import torch
8
+ from torch import Tensor
9
+ from torch._prims_common import DimsType
10
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec
11
+ from torch.distributed.tensor._op_schema import (
12
+ OpSchema,
13
+ OpSpec,
14
+ OpStrategy,
15
+ RuntimeSchemaInfo,
16
+ StrategyType,
17
+ )
18
+ from torch.distributed.tensor._ops.registration import register_op_strategy
19
+ from torch.distributed.tensor._ops.utils import (
20
+ generate_redistribute_costs,
21
+ normalize_dim,
22
+ normalize_dims,
23
+ prod,
24
+ )
25
+ from torch.distributed.tensor.placement_types import (
26
+ _StridedShard,
27
+ Placement,
28
+ Replicate,
29
+ Shard,
30
+ )
31
+
32
+
33
+ aten = torch.ops.aten
34
+
35
+ Shape = tuple[int, ...]
36
+
37
+
38
+ @dataclass
39
+ class DimSpec:
40
+ """Specifies how an output dimension maps to an input dimension."""
41
+
42
+ def inputs(self) -> Iterable["DimSpec"]:
43
+ return ()
44
+
45
+
46
+ # Rules that map each dimension of the output to dimensions of the input tensor
47
+ DimMap = tuple[DimSpec, ...]
48
+
49
+
50
+ @dataclass
51
+ class Singleton(DimSpec):
52
+ """Output dimension is a singleton."""
53
+
54
+
55
+ @dataclass
56
+ class InputDim(DimSpec):
57
+ """Output dimension maps directly to an input dimension."""
58
+
59
+ input_dim: int
60
+
61
+
62
+ @dataclass
63
+ class Broadcast(DimSpec):
64
+ """Output is the broadcast of a singleton input dimension."""
65
+
66
+ dim: DimSpec
67
+ dim_size: int
68
+
69
+ @classmethod
70
+ def new(cls, dim: DimSpec, dim_size: int) -> DimSpec:
71
+ return Broadcast(dim, dim_size)
72
+
73
+ def inputs(self) -> Iterable[DimSpec]:
74
+ return (self.dim,)
75
+
76
+
77
+ @dataclass
78
+ class NewDim(DimSpec):
79
+ """This is a new dimension created by the op."""
80
+
81
+ size: int
82
+
83
+ @classmethod
84
+ def new(cls, size: int) -> DimSpec:
85
+ return Singleton() if size == 1 else NewDim(size)
86
+
87
+
88
+ @dataclass
89
+ class Repeat(DimSpec):
90
+ """Output dimension is the input dimension repeated n-times."""
91
+
92
+ input_dim: DimSpec
93
+ times: int
94
+
95
+ @classmethod
96
+ def new(cls, dim: DimSpec, times: int) -> DimSpec:
97
+ if times == 1:
98
+ return dim
99
+ elif isinstance(dim, Singleton):
100
+ # repeating a singleton is the same as broadcasting it
101
+ return Broadcast(dim, times)
102
+ else:
103
+ return Repeat(dim, times)
104
+
105
+ def inputs(self) -> Iterable[DimSpec]:
106
+ return (self.input_dim,)
107
+
108
+
109
+ @dataclass
110
+ class Flatten(DimSpec):
111
+ """Flatten a set of input dimensions, ensuring right-most adjacent elements remain adjacent in the output."""
112
+
113
+ input_dims: Sequence[DimSpec]
114
+
115
+ @classmethod
116
+ def new(cls, dims: Sequence[DimSpec]) -> DimSpec:
117
+ if len(dims) == 0:
118
+ # flattening a scalar leads to a singleton
119
+ return Singleton()
120
+ elif len(dims) == 1:
121
+ # flattening a single dimension is no-op
122
+ return dims[0]
123
+ else:
124
+ return Flatten(dims)
125
+
126
+ def inputs(self) -> Iterable[DimSpec]:
127
+ return self.input_dims
128
+
129
+
130
+ @dataclass
131
+ class Split(DimSpec):
132
+ """
133
+ This dimension is a member of a decomposition of the input dim.
134
+
135
+ Note that input_dim itself could be a Flattened set of input dims.
136
+ """
137
+
138
+ input_dim: DimSpec
139
+ group_shape: Shape
140
+ split_id: int
141
+
142
+ @classmethod
143
+ def new(cls, dim: DimSpec, group_shape: tuple[int, ...], idx: int) -> DimSpec:
144
+ if not len(group_shape) > 0:
145
+ raise AssertionError(
146
+ f"Expected group_shape length > 0, got {len(group_shape)}"
147
+ )
148
+ if len(group_shape) == 1:
149
+ # not really a group, just return the input dim back
150
+ if not idx == 0:
151
+ raise AssertionError(f"Expected idx == 0, got {idx}")
152
+ return dim
153
+ elif group_shape[idx] == 1:
154
+ return Singleton()
155
+ else:
156
+ # remove singletons from group
157
+ # group_mapping = [(new_index, (shape, old_index)) ...]
158
+ group_mapping = list(
159
+ enumerate((s, i) for i, s in enumerate(group_shape) if s != 1)
160
+ )
161
+ new_group_shape = tuple(m[1][0] for m in group_mapping)
162
+ new_idx = next(filter(lambda x: x[1][1] == idx, group_mapping))[0]
163
+ return Split(dim, new_group_shape, new_idx)
164
+
165
+ def inputs(self) -> Iterable[DimSpec]:
166
+ return (self.input_dim,)
167
+
168
+
169
+ def dim_pad_left(ndim: int, min_dims: int) -> DimMap:
170
+ return (Singleton(),) * max(0, min_dims - ndim) + tuple(
171
+ InputDim(i) for i in range(ndim)
172
+ )
173
+
174
+
175
+ def dim_atleast_3d(ndim: int) -> DimMap:
176
+ if ndim == 0:
177
+ return (Singleton(), Singleton(), Singleton())
178
+ elif ndim == 1:
179
+ return (Singleton(), InputDim(0), Singleton())
180
+ elif ndim == 2:
181
+ return (InputDim(0), InputDim(1), Singleton())
182
+ else:
183
+ return tuple(InputDim(i) for i in range(ndim))
184
+
185
+
186
+ def expand(input_shape: Shape, shape: Shape) -> DimMap:
187
+ """Implement broadcast on multiple dimensions."""
188
+ if not len(shape) >= len(input_shape):
189
+ raise AssertionError(
190
+ f"Expected len(shape) >= len(input_shape), got {len(shape)} < {len(input_shape)}"
191
+ )
192
+
193
+ # 1. create padded input dimensions
194
+ padded_input = dim_pad_left(len(input_shape), len(shape))
195
+ # 2. check that input shapes are compatible
196
+ mapping = []
197
+ for p, desired_s in zip(padded_input, shape):
198
+ if isinstance(p, Singleton):
199
+ actual_s = 1
200
+ if not desired_s >= 0:
201
+ raise AssertionError(f"Expected desired_s >= 0, got {desired_s}")
202
+ else:
203
+ if not isinstance(p, InputDim):
204
+ raise AssertionError(f"DimSpec not supported in expand: {p}")
205
+ actual_s = input_shape[p.input_dim]
206
+ if not (actual_s == 1 or desired_s == -1 or desired_s == actual_s):
207
+ raise AssertionError(
208
+ f"Expected actual_s == 1 or desired_s == -1 or "
209
+ f"desired_s == actual_s, got actual_s={actual_s}, desired_s={desired_s}"
210
+ )
211
+ mapping.append(
212
+ p
213
+ if desired_s in (1, -1) or desired_s == actual_s
214
+ else Broadcast.new(p, desired_s)
215
+ )
216
+ return tuple(mapping)
217
+
218
+
219
+ def normalize_sizes(sizes: Shape | tuple[Shape]) -> Shape:
220
+ if isinstance(sizes[0], int):
221
+ return cast(Shape, sizes)
222
+ elif len(sizes) == 1:
223
+ return sizes[0]
224
+ else:
225
+ raise RuntimeError("Size must be int... or tuple")
226
+
227
+
228
+ def dim_flatten(ndim: int, start_dim=0, end_dim=-1) -> DimMap:
229
+ if ndim == 0:
230
+ return (Singleton(),)
231
+ elif ndim == 1:
232
+ return (InputDim(0),)
233
+ else:
234
+ # only flattening dims from start_dim to end_dim (inclusive)
235
+ # other dims are passed through
236
+ if end_dim < 0:
237
+ end_dim += ndim
238
+ results: list[DimSpec] = [InputDim(i) for i in range(start_dim)]
239
+ results.append(
240
+ Flatten.new(tuple(InputDim(i) for i in range(start_dim, end_dim + 1)))
241
+ )
242
+ results.extend([InputDim(i) for i in range(end_dim + 1, ndim)])
243
+ return tuple(results)
244
+
245
+
246
+ def dim_movedim(
247
+ ndim: int,
248
+ input: DimsType,
249
+ destination: DimsType,
250
+ ) -> DimMap:
251
+ input = normalize_dims(input, ndim)
252
+ destination = normalize_dims(destination, ndim)
253
+
254
+ if not len(input) == len(destination):
255
+ raise AssertionError(
256
+ f"Expected len(input) == len(destination), got {len(input)} != {len(destination)}"
257
+ )
258
+ input_set = set(input)
259
+ if not len(input_set) == len(input):
260
+ raise AssertionError("Found repeated input dims")
261
+ if not len(set(destination)) == len(destination):
262
+ raise AssertionError("Found repeated output dims")
263
+ if not max(input) < ndim:
264
+ raise AssertionError(f"Expected max(input) < ndim, got {max(input)} >= {ndim}")
265
+ if not max(destination) < ndim:
266
+ raise AssertionError(
267
+ f"Expected max(destination) < ndim, got {max(destination)} >= {ndim}"
268
+ )
269
+
270
+ dest = [-1] * ndim
271
+ for i, d in zip(input, destination):
272
+ dest[d] = i
273
+
274
+ unused_inputs_iter = iter(i for i in range(ndim) if i not in input_set)
275
+ for i in range(ndim):
276
+ if dest[i] == -1:
277
+ dest[i] = next(unused_inputs_iter)
278
+
279
+ return tuple(InputDim(i) for i in dest)
280
+
281
+
282
+ def dim_repeat(ndim: int, sizes: Shape) -> DimMap:
283
+ sizes = normalize_sizes(sizes)
284
+ if not len(sizes) >= ndim:
285
+ raise AssertionError(
286
+ f"Number of dimensions of repeat dims {sizes} can not be smaller than number of dimensions of tensor {ndim}."
287
+ )
288
+ pad = len(sizes) - ndim
289
+ return tuple(Repeat.new(Singleton(), s) for s in sizes[:pad]) + tuple(
290
+ Repeat.new(InputDim(i), s) for i, s in enumerate(sizes[pad:])
291
+ )
292
+
293
+
294
+ def infer_size(total_size: int, sizes: Shape) -> Shape:
295
+ """
296
+ One dimension input to view may be "-1".
297
+
298
+ Infer the size of this dimension given the total_size.
299
+ """
300
+ infers = [i for i, s in enumerate(sizes) if s == -1]
301
+ size = prod(sizes)
302
+ if not len(infers) <= 1:
303
+ raise AssertionError("can only infer one size")
304
+ if infers:
305
+ size = -size
306
+ missing_size = total_size // size
307
+ if not total_size % size == 0:
308
+ raise AssertionError(
309
+ f"size inferred for -1 is not integral {sizes} should have {total_size} elements."
310
+ )
311
+ return tuple(s if s != -1 else missing_size for s in sizes)
312
+ if not size == total_size:
313
+ raise AssertionError(f"sizes do not match {total_size} vs {size}")
314
+ return sizes
315
+
316
+
317
+ def view_groups(from_size: Shape, to_size: Shape) -> DimMap:
318
+ """
319
+ Decompose a reshape operation into forwarding, flattening, or splitting dimensions for each output dimension.
320
+
321
+ A view or reshape operation can be decomposed into a set of 3 types of smaller operations:
322
+ 1) Forward a dimension from input to output
323
+ 2) Flatten a set of dimensions into a single dimension
324
+ 3) Split one dimension into multiple dimensions
325
+
326
+ view_groups identifies these operations and returns, for each output dimension, what
327
+ is operation was performed in the input dimension. For example:
328
+
329
+ view_groups([2, 3, 4], [2, 12]) -> (
330
+ InputDim(0),
331
+ Flatten((InputDim(1), InputDim(2)))
332
+ )
333
+
334
+ - output dimension 0 maps to input dimension 0
335
+ - output dimension 1 maps to a flattened input dimensions 1 and 2
336
+
337
+
338
+ view_groups([2, 3], [3, 2]) -> (
339
+ Split(Flatten((InputDim(0), InputDim(1))), (3, 2), 0),
340
+ Split(Flatten((InputDim(0), InputDim(1))), (3, 2), 1),
341
+ )
342
+
343
+ - in the above, input is flattened into a single dimension and then split
344
+ into two separate dimensions with different sizes from the input.
345
+ """
346
+ from_nelem = prod(from_size)
347
+ to_size = infer_size(from_nelem, normalize_sizes(to_size))
348
+
349
+ if not from_nelem == prod(to_size):
350
+ raise AssertionError("Total view shape does not add up")
351
+
352
+ from_idx = 0
353
+ to_idx = 0
354
+ from_len = len(from_size)
355
+ to_len = len(to_size)
356
+
357
+ result_pp = []
358
+
359
+ while from_idx < from_len or to_idx < to_len:
360
+ from_group_dim, to_group_shape = [], []
361
+
362
+ if from_idx >= from_len:
363
+ f = 1
364
+ else:
365
+ f = from_size[from_idx]
366
+ from_group_dim.append(from_idx)
367
+ from_idx += 1
368
+
369
+ if to_idx >= to_len:
370
+ t = 1
371
+ else:
372
+ t = to_size[to_idx]
373
+ to_group_shape.append(t)
374
+ to_idx += 1
375
+
376
+ # if any of the groups is singleton, great, we need to backtrack though
377
+ if f == 1 and t != 1:
378
+ # produces ([1], [])
379
+ to_idx -= 1
380
+ to_group_shape = []
381
+ elif f != 1 and t == 1:
382
+ # produces ([], [1])
383
+ from_idx -= 1
384
+ from_group_dim = []
385
+ else:
386
+ # produces ([1], [1]), ([2], [2]), ([2,3], [6])
387
+ while f != t:
388
+ if f < t:
389
+ nf = from_size[from_idx]
390
+ from_group_dim.append(from_idx)
391
+ from_idx += 1
392
+ f *= nf
393
+ else:
394
+ nt = to_size[to_idx]
395
+ to_group_shape.append(nt)
396
+ to_idx += 1
397
+ t *= nt
398
+
399
+ if len(to_group_shape) > 0:
400
+ flattened = Flatten.new(
401
+ tuple(InputDim(fi) for fi in from_group_dim if from_size[fi] >= 1)
402
+ )
403
+ result_pp += [
404
+ Split.new(flattened, tuple(to_group_shape), i)
405
+ for i in range(len(to_group_shape))
406
+ ]
407
+
408
+ return tuple(result_pp)
409
+
410
+
411
+ def dim_tile(ndim: int, dims: tuple[int, ...]) -> DimMap:
412
+ if len(dims) < ndim:
413
+ dims = (1,) * (ndim - len(dims)) + dims
414
+ return dim_repeat(ndim, dims)
415
+
416
+
417
+ def dim_transpose(ndim: int, dim1: int, dim2: int) -> DimMap:
418
+ dim1 = normalize_dim(dim1, ndim)
419
+ dim2 = normalize_dim(dim2, ndim)
420
+ if not dim1 < ndim:
421
+ raise AssertionError(f"Expected dim1 < ndim, got {dim1} >= {ndim}")
422
+ if not dim2 < ndim:
423
+ raise AssertionError(f"Expected dim2 < ndim, got {dim2} >= {ndim}")
424
+ dimmap = [InputDim(i) for i in range(ndim)]
425
+ swapdim = dimmap[dim1]
426
+ dimmap[dim1] = dimmap[dim2]
427
+ dimmap[dim2] = swapdim
428
+ return tuple(dimmap)
429
+
430
+
431
+ def dim_squeeze(shape: Shape, dim: int | None = None) -> DimMap:
432
+ # FIXME: this is wrong when dim=None and one of the dimensions
433
+ # equals size of the mesh. For example squeeze(DTensor(tensor(4), Shard[0])) could
434
+ # end up as squeeze(tensor(1)) if we have 4 devices; this would lead to
435
+ # removal of a dimension that is not actually a singleton.
436
+ return tuple(
437
+ InputDim(i)
438
+ for i, s in enumerate(shape)
439
+ if s > 1 or (dim is not None and i != normalize_dim(dim, len(shape)))
440
+ )
441
+
442
+
443
+ def dim_unsqueeze(ndim: int, dim: int) -> DimMap:
444
+ dims = tuple(InputDim(i) for i in range(ndim))
445
+ if dim < 0:
446
+ dim += ndim + 1
447
+ return dims[:dim] + (Singleton(),) + dims[dim:]
448
+
449
+
450
+ def dim_view_as_real(shape: Shape) -> DimMap:
451
+ ndim = len(shape)
452
+ results: list[DimSpec] = [InputDim(i) for i in range(ndim - 1)]
453
+ # each complex number is split into two real numbers,
454
+ # resulting in one more dimension of size 2
455
+ results.append(Split(InputDim(ndim - 1), (shape[-1], 2), 0))
456
+ results.append(Split(InputDim(ndim - 1), (shape[-1], 2), 1))
457
+ return tuple(results)
458
+
459
+
460
+ def dim_reduction(ndim: int, dim_or_dims: DimsType | None, keepdim: bool) -> DimMap:
461
+ """
462
+ General fallback for reduction ops where Partial() does not apply.
463
+
464
+ This will cause incoming tensor to be replicated on the reducing dimensions.
465
+ """
466
+ if dim_or_dims is None:
467
+ dim_or_dims = tuple(range(ndim))
468
+ if isinstance(dim_or_dims, int):
469
+ dim_or_dims = (dim_or_dims,)
470
+ dim_or_dims = tuple(d if d >= 0 else d + ndim for d in dim_or_dims)
471
+ return tuple(
472
+ InputDim(i) if i not in dim_or_dims else Singleton()
473
+ for i in range(ndim)
474
+ if i not in dim_or_dims or keepdim
475
+ )
476
+
477
+
478
+ dim_maps: dict[Callable[..., torch.Tensor], Callable[..., DimMap]] = {
479
+ torch.atleast_1d: lambda x: dim_pad_left(x.ndim, 1),
480
+ torch.atleast_2d: lambda x: dim_pad_left(x.ndim, 2),
481
+ torch.atleast_3d: lambda x: dim_atleast_3d(x.ndim),
482
+ torch.broadcast_to: lambda input, shape: expand(input.shape, shape),
483
+ Tensor.expand: lambda self, *sizes: expand(self.shape, normalize_sizes(sizes)),
484
+ torch.flatten: lambda tensor: dim_flatten(tensor.ndim),
485
+ torch.movedim: lambda input, source, destination: dim_movedim(
486
+ input.ndim, source, destination
487
+ ),
488
+ torch.permute: lambda input, dims: tuple(
489
+ InputDim(i) for i in normalize_dims(dims, input.ndim)
490
+ ),
491
+ torch.ravel: lambda tensor: dim_flatten(tensor.ndim),
492
+ Tensor.repeat: lambda self, *sizes: dim_repeat(self.ndim, sizes),
493
+ torch.reshape: lambda input, shape: view_groups(input.shape, shape),
494
+ torch.squeeze: lambda input, dim=None: dim_squeeze(input.shape, dim),
495
+ torch.tile: lambda input, dims: dim_tile(input.ndim, dims),
496
+ torch.transpose: lambda input, dim0, dim1: dim_transpose(input.ndim, dim0, dim1),
497
+ torch.unsqueeze: lambda input, dim: dim_unsqueeze(input.ndim, dim),
498
+ Tensor.view: lambda input, *shape: view_groups(input.shape, shape),
499
+ torch.view_as_complex: lambda input: dim_flatten(input.ndim, input.ndim - 2),
500
+ torch.view_as_real: lambda input: dim_view_as_real(input.shape),
501
+ }
502
+
503
+
504
+ def propagate_shape_and_sharding(
505
+ input_src_placements: Sequence[Placement],
506
+ global_input_shape: Shape,
507
+ rule: DimMap,
508
+ mesh_sizes: Shape,
509
+ strict_view: bool = False,
510
+ ) -> tuple[Sequence[Placement], Sequence[Placement]]:
511
+ """
512
+ Determine input target sharding and output sharding based on
513
+ given global tensor shape and input source sharding.
514
+
515
+ Sharding propagation follows mapped dimensions:
516
+ - An output dimension that maps directly to an input dimension is sharded equally
517
+ - An output dimension that is a flattened set of input dimensions can only be
518
+ sharded if only the leftmost flattened dimension is sharded.
519
+ - An output dimension that is a split of the input dimension can only be sharded
520
+ if the leftmost split size is divisible by the mesh dimension
521
+ """
522
+ if not len(input_src_placements) == len(mesh_sizes):
523
+ raise AssertionError(f"{input_src_placements} != {mesh_sizes}")
524
+ # for each input dim, for each mesh dim, provides a list of possible shardable dimensions
525
+ mesh_ndim = len(mesh_sizes)
526
+ shardable_dims: dict[int, list[bool]] = {}
527
+
528
+ # in case an input dimension disappears (e.g. collapsing, reduction)
529
+ # we cannot shard in that dimension (we need a replication fall-back rule)
530
+ seen_input_dims: set[int] = set()
531
+
532
+ def collect_used_inputs(cmd: DimSpec) -> None:
533
+ if isinstance(cmd, InputDim):
534
+ seen_input_dims.add(cmd.input_dim)
535
+ for inp in cmd.inputs():
536
+ collect_used_inputs(inp)
537
+
538
+ for cmd in rule:
539
+ collect_used_inputs(cmd)
540
+ for dim in range(len(global_input_shape)):
541
+ shardable_dims[dim] = [dim in seen_input_dims] * mesh_ndim
542
+
543
+ def maybe_get_shard_mesh_dim_and_placement(
544
+ input_dim: InputDim,
545
+ ) -> tuple[Optional[int], Optional[Shard | _StridedShard]]:
546
+ # if input_dim is sharded, return the mesh_dim and shard placement
547
+ for i, placement in enumerate(input_src_placements):
548
+ if (
549
+ isinstance(placement, Shard | _StridedShard)
550
+ and placement.dim == input_dim.input_dim
551
+ ):
552
+ return i, placement
553
+ return None, None
554
+
555
+ # NOTE: This function has three responsibilities:
556
+ # 1. determine "theoretically" if an output dimension can be sharded, i.e. fill the shardable_dims map
557
+ # 2. determine "theoretically" the corresponding input dimension to shard on, via return value
558
+ # 3. throw an error when strict_view is enabled and we cannot shard an output dimension
559
+ # 1 and 2 doesn't require the info of whether current input is sharded.
560
+ # 3 requires that info, to decide whether we can error out. Maybe we can refactor
561
+ # to make this function purely "theoretical".
562
+ def get_in_dim_to_shard(cmd: DimSpec) -> InputDim | None:
563
+ if isinstance(cmd, InputDim):
564
+ return cmd
565
+ elif isinstance(cmd, Flatten):
566
+ for i, dim in enumerate(cmd.input_dims):
567
+ # so far all Flatten is always composed of InputDims; revisit this if needed
568
+ if not isinstance(dim, InputDim):
569
+ raise AssertionError(f"Expected InputDim, got {type(dim)}")
570
+ can_shard_dim = True
571
+ shard_mesh_dim, shard_placement = (
572
+ maybe_get_shard_mesh_dim_and_placement(dim)
573
+ )
574
+ input_sharded = shard_mesh_dim is not None
575
+ if i > 0:
576
+ can_shard_dim = False
577
+ if strict_view and input_sharded:
578
+ raise RuntimeError(
579
+ f"Attempted to flatten multiple dimensions, with dimension {dim.input_dim} being sharded. ",
580
+ "It cannot be performed without redistribution, which is disallowed by the current operator.",
581
+ )
582
+ elif input_sharded:
583
+ if not (shard_placement is not None and shard_mesh_dim is not None):
584
+ raise AssertionError(
585
+ "Expected shard_placement and shard_mesh_dim to be not None"
586
+ )
587
+ tensor_dim_size = global_input_shape[shard_placement.dim]
588
+ mesh_dim_size = mesh_sizes[shard_mesh_dim]
589
+ if tensor_dim_size % mesh_dim_size != 0:
590
+ can_shard_dim = False
591
+ if strict_view:
592
+ raise RuntimeError(
593
+ f"Attempted to flatten unevenly sharded dimension {i}, "
594
+ "which would require resharding the input. "
595
+ "Please explicitly redistribute the tensor instead."
596
+ )
597
+ shardable_dims[dim.input_dim] = [can_shard_dim] * mesh_ndim
598
+
599
+ if not isinstance(cmd.input_dims[0], InputDim):
600
+ raise AssertionError(
601
+ f"Expected InputDim, got {type(cmd.input_dims[0])}"
602
+ )
603
+ return cmd.input_dims[0]
604
+ elif isinstance(cmd, Split):
605
+ in_dim = get_in_dim_to_shard(cmd.input_dim)
606
+ out_size = cmd.group_shape[cmd.split_id]
607
+ if cmd.split_id == 0 and in_dim is not None:
608
+ # we need to check that the input dimension is divisible
609
+ # by the size of the submesh we're sharding it on
610
+ # NOTE: it would be possible to shard the same input dimension
611
+ # on more than one mesh dimension. In that case, the dimension
612
+ # needs to be divisible by the product of mesh sizes.
613
+ # In order to keep the problem more tractable, we will not consider
614
+ # double resharding as a suggestion (e.g. [Shard(0), Shard(0) ])
615
+ # but we will allow it if that's the input and it's compatible
616
+
617
+ # 1. is this dimension shardable on each individual mesh dim?
618
+ shardable_dims[in_dim.input_dim] = [
619
+ out_size % mesh_dim_size == 0 for mesh_dim_size in mesh_sizes
620
+ ]
621
+
622
+ shard_mesh_dim, _ = maybe_get_shard_mesh_dim_and_placement(in_dim)
623
+ if strict_view and shard_mesh_dim is not None:
624
+ if not shardable_dims[in_dim.input_dim][shard_mesh_dim]:
625
+ raise RuntimeError(
626
+ f"Attempted to split the sharded dimension {in_dim.input_dim} into multiple subdimensions. ",
627
+ "It cannot be performed without redistribution, which is disallowed by the current operator.",
628
+ )
629
+
630
+ # 2. here we special case things like [Shard(0), Shard(0)]
631
+ submesh_size = 1
632
+ for size, shard in zip(mesh_sizes, input_src_placements):
633
+ if isinstance(shard, Shard | _StridedShard) and shard.dim == in_dim:
634
+ submesh_size *= size
635
+ if not out_size % submesh_size == 0:
636
+ raise AssertionError(
637
+ f"Resulting dimension size {out_size} is not divisible by its mesh dimension {submesh_size}."
638
+ )
639
+
640
+ # we will only shard our first component of the split
641
+ return in_dim if cmd.split_id == 0 else None
642
+ elif isinstance(cmd, Repeat):
643
+ in_dim = get_in_dim_to_shard(cmd.input_dim)
644
+ if in_dim is not None:
645
+ shardable_dims[in_dim.input_dim] = [False] * mesh_ndim
646
+ return None
647
+ else:
648
+ return None
649
+
650
+ # for each output dim, find the corresponding input dim in terms of sharding prop
651
+ shard_dim_map = {}
652
+ for dim, cmd in enumerate(rule):
653
+ in_dim = get_in_dim_to_shard(cmd)
654
+ if in_dim is not None:
655
+ shard_dim_map[in_dim.input_dim] = dim
656
+
657
+ input_tgt_placements = [
658
+ (
659
+ Replicate()
660
+ if isinstance(p, Shard | _StridedShard)
661
+ and not shardable_dims[p.dim][mesh_dim]
662
+ else p
663
+ )
664
+ for mesh_dim, p in enumerate(input_src_placements)
665
+ ]
666
+
667
+ def _rewrite_shard_dim(p: Shard | _StridedShard):
668
+ """
669
+ Rewrite the shard dim to the corresponding tensor dim in output.
670
+ For ``_StridedShard``, we can safely keep the placement type and
671
+ ``split_factor`` unchanged and only rewrite the ``dim`` because:
672
+ 1. ``_StridedShard`` has no impact on sharding (i.e. how
673
+ tensor is partitioned) compared to ``Shard``. It only changes
674
+ how shards permute across the devices.
675
+ 2. ``view()`` op on DTensor strictly forbids shard redistribution
676
+ which means if ``view()`` may cause shard permutation across
677
+ devices, it should be rejected. This is enforced in today's
678
+ sharding prop for ``view()``.
679
+ 3. Since DTensor ``view()`` won't introduce any redistribution,
680
+ it's certain that ``placements`` won't change except the
681
+ inner ``dim`` attribute of ``Shard`` or ``_StridedShard``.
682
+ """
683
+ if isinstance(p, _StridedShard):
684
+ return _StridedShard(shard_dim_map[p.dim], split_factor=p.split_factor)
685
+ else:
686
+ return Shard(shard_dim_map[p.dim])
687
+
688
+ output_placements = [
689
+ _rewrite_shard_dim(p) if isinstance(p, Shard | _StridedShard) else p
690
+ for p in input_tgt_placements
691
+ ]
692
+
693
+ return input_tgt_placements, output_placements
694
+
695
+
696
+ def register_op_strategy_map(
697
+ aten_op_overload: torch._ops.OpOverload,
698
+ local_op_name: Callable[..., torch.Tensor],
699
+ schema_info: RuntimeSchemaInfo | None = None,
700
+ strict_view: bool = False,
701
+ ) -> None:
702
+ """
703
+ Helper that registers strategies for view-like operators that follow a pattern:
704
+ (1) define the way input dims are split/combined to form output dims (dim_maps)
705
+ (2) register a strategy for the op schema that uses the dim_map as a sharding prop rule
706
+
707
+ strict_view: if True, we will error out if the view-operation would require resharding the input.
708
+ Currently, this should be set to 'true' for any "view" ops.
709
+ We could diverge behavior for "reshape" ops which could perform a redistribute implicitly.
710
+ """
711
+ dim_map: Callable[..., DimMap] = dim_maps[local_op_name]
712
+
713
+ @register_op_strategy(aten_op_overload, schema_info=schema_info)
714
+ def reshape_strategy(op_schema: OpSchema) -> StrategyType:
715
+ rules = dim_map(*op_schema.args_schema, **op_schema.kwargs_schema)
716
+ input_strategy = cast(OpStrategy, op_schema.args_schema[0])
717
+ mesh = op_schema.get_mesh_from_args(validate=False)
718
+
719
+ global_in_shape = input_strategy.shape
720
+ if global_in_shape is None:
721
+ raise AssertionError("Shape required.")
722
+
723
+ output_strategy = OpStrategy([])
724
+ for input_placement_strategy in input_strategy.strategies:
725
+ input_src_spec = input_placement_strategy.output_spec
726
+
727
+ input_tgt_placements, output_placements = propagate_shape_and_sharding(
728
+ input_src_spec.placements,
729
+ tuple(global_in_shape),
730
+ rules,
731
+ mesh.shape,
732
+ strict_view,
733
+ )
734
+
735
+ # TODO: optimize this. we shouldn't simply blindly replicate
736
+ # unshardable dims ...
737
+ # FIXME: this can be wrong for situations where we have
738
+ # [Shard(0), Shard(0)]
739
+ input_tgt_spec = DTensorSpec(
740
+ placements=tuple(input_tgt_placements),
741
+ mesh=mesh,
742
+ tensor_meta=input_src_spec.tensor_meta,
743
+ )
744
+ redistribute_costs: list[list[float]] = [
745
+ generate_redistribute_costs(input_strategy, input_tgt_spec)
746
+ ]
747
+
748
+ output_spec = DTensorSpec(mesh=mesh, placements=tuple(output_placements))
749
+ output_strategy.strategies.append(
750
+ OpSpec(
751
+ output_specs=output_spec,
752
+ input_specs=(input_tgt_spec,),
753
+ redistribute_cost=redistribute_costs,
754
+ )
755
+ )
756
+
757
+ return output_strategy
758
+
759
+
760
+ register_op_strategy_map(aten.squeeze.default, torch.squeeze)
761
+ register_op_strategy_map(
762
+ aten.squeeze_.dim, torch.squeeze, schema_info=RuntimeSchemaInfo(1)
763
+ )
764
+ register_op_strategy_map(
765
+ aten.squeeze.dim, torch.squeeze, schema_info=RuntimeSchemaInfo(1)
766
+ )
767
+ register_op_strategy_map(
768
+ aten.view.default,
769
+ Tensor.view,
770
+ schema_info=RuntimeSchemaInfo(1),
771
+ strict_view=True,
772
+ )
773
+ register_op_strategy_map(
774
+ aten.reshape.default, torch.reshape, schema_info=RuntimeSchemaInfo(1)
775
+ )
776
+ register_op_strategy_map(
777
+ aten._unsafe_view.default,
778
+ Tensor.view,
779
+ schema_info=RuntimeSchemaInfo(1),
780
+ strict_view=True,
781
+ )
782
+ register_op_strategy_map(
783
+ aten.unsqueeze.default, torch.unsqueeze, schema_info=RuntimeSchemaInfo(1)
784
+ )
785
+ register_op_strategy_map(
786
+ aten.expand.default, Tensor.expand, schema_info=RuntimeSchemaInfo(1)
787
+ )
788
+ register_op_strategy_map(
789
+ aten.permute.default, torch.permute, schema_info=RuntimeSchemaInfo(1)
790
+ )
791
+ register_op_strategy_map(
792
+ aten.repeat.default, Tensor.repeat, schema_info=RuntimeSchemaInfo(1)
793
+ )
794
+ register_op_strategy_map(
795
+ aten.transpose.int, torch.transpose, schema_info=RuntimeSchemaInfo(1)
796
+ )
797
+ register_op_strategy_map(aten.view_as_complex.default, torch.view_as_complex)
798
+ register_op_strategy_map(aten.view_as_real.default, torch.view_as_real)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/registration.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ from collections.abc import Callable
3
+ from typing import TypeAlias, TypeVar
4
+
5
+ import torch
6
+ from torch.distributed.tensor._api import DTensor
7
+ from torch.distributed.tensor._op_schema import (
8
+ OpSchema,
9
+ OutputSharding,
10
+ RuntimeSchemaInfo,
11
+ StrategyType,
12
+ )
13
+
14
+
15
+ # convenient wrapper to register sharding propagation rules
16
+ def register_prop_rule(
17
+ op: torch._ops.OpOverload | list[torch._ops.OpOverload],
18
+ schema_info: RuntimeSchemaInfo | None = None,
19
+ ) -> Callable[
20
+ [Callable[[OpSchema], OutputSharding]], Callable[[OpSchema], OutputSharding]
21
+ ]:
22
+ def wrapper(
23
+ impl: Callable[[OpSchema], OutputSharding],
24
+ ) -> Callable[[OpSchema], OutputSharding]:
25
+ overloads = op if isinstance(op, list) else [op]
26
+ for overload in overloads:
27
+ DTensor._op_dispatcher.sharding_propagator.register_sharding_prop_rule(
28
+ overload, impl, schema_info
29
+ )
30
+ return impl
31
+
32
+ return wrapper
33
+
34
+
35
+ # Note:
36
+ # using TypeVar here allows the registration decorator to preserve the specific type info of the wrapped strategy,
37
+ # while hardcoding the typing on the wrapper (e.g. Callable[[OpSchema], StrategyType]) would mean mypy would treat
38
+ # the return value of the wrapped strategy as always being a `StrategyType` even if it were a derived class like
39
+ # MyStrategyType(StrategyType).
40
+ _OpSchemaT = TypeVar("_OpSchemaT", bound=OpSchema)
41
+ _StrategyTypeT = TypeVar("_StrategyTypeT", bound=StrategyType)
42
+ _ShardingStrategyFunc: TypeAlias = Callable[[_OpSchemaT], _StrategyTypeT]
43
+
44
+
45
+ def register_op_strategy(
46
+ op: torch._ops.OpOverload | list[torch._ops.OpOverload],
47
+ schema_info: RuntimeSchemaInfo | None = None,
48
+ ) -> Callable[[_ShardingStrategyFunc], _ShardingStrategyFunc]:
49
+ # For every ATen op that accepts any args in this list,
50
+ # the arg itself can impact the strides (and potentially the sharding strategy)
51
+ # of the output tensor.
52
+ # thus, we will detect ATen schemas with any of these args and ensure
53
+ # that they get specialized here.
54
+ arg_names_that_require_specializing_cache_strategy = [
55
+ "memory_format",
56
+ ]
57
+
58
+ def wrapper(impl: _ShardingStrategyFunc) -> _ShardingStrategyFunc:
59
+ if isinstance(op, list):
60
+ overloads = op
61
+ else:
62
+ overloads = [op]
63
+
64
+ for overload in overloads:
65
+ curr_schema_info = None
66
+ if schema_info is None:
67
+ specialized_args = [
68
+ a.name
69
+ for a in overload._schema.arguments
70
+ if a.name in arg_names_that_require_specializing_cache_strategy
71
+ ]
72
+ if any(specialized_args):
73
+ curr_schema_info = RuntimeSchemaInfo(
74
+ static_kwargkey=specialized_args
75
+ )
76
+ else:
77
+ curr_schema_info = schema_info
78
+ DTensor._op_dispatcher.sharding_propagator.register_op_strategy(
79
+ overload, impl, curr_schema_info
80
+ )
81
+ return impl
82
+
83
+ return wrapper
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_ops/utils.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+ import functools
4
+ import itertools
5
+ import operator
6
+ from collections.abc import Callable, Iterable, Sequence
7
+ from typing import cast
8
+
9
+ import torch
10
+ from torch._prims_common import DimsSequenceType, DimsType
11
+ from torch.distributed.tensor._collective_utils import redistribute_cost
12
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec
13
+ from torch.distributed.tensor._op_schema import (
14
+ OpSchema,
15
+ OpSpec,
16
+ OpStrategy,
17
+ PlacementList,
18
+ StrategyType,
19
+ )
20
+ from torch.distributed.tensor.device_mesh import DeviceMesh
21
+ from torch.distributed.tensor.placement_types import (
22
+ _StridedShard,
23
+ Partial,
24
+ Placement,
25
+ Replicate,
26
+ Shard,
27
+ )
28
+
29
+
30
+ def replicate_op_strategy(op_schema: OpSchema) -> StrategyType:
31
+ """
32
+ Fallback strategy all use Replication()
33
+ """
34
+ args_strategy = op_schema.args_strategy
35
+ kwargs_strategy = op_schema.kwargs_strategy
36
+ inputs_strategy = args_strategy + kwargs_strategy
37
+
38
+ output_type = [str(ret.type) for ret in op_schema.op._schema.returns]
39
+ output_len = output_type.count("Tensor")
40
+ # TODO(zpcore): Confirm if view op can be handle properly or not. Prevent
41
+ # handling view ops until confirmed.
42
+ if op_schema.op.is_view:
43
+ raise RuntimeError(
44
+ "fallback strategy is unable to handle view ops until confirmed"
45
+ )
46
+ if "List[Tensor]" in output_type:
47
+ raise RuntimeError(
48
+ "fallback strategy is unable to handle ops with List[Tensor] output "
49
+ "because size of the list may depend on the op's input value"
50
+ )
51
+
52
+ mesh = inputs_strategy[0].mesh
53
+
54
+ dim_sharding: PlacementList = [Replicate()] * (output_len + len(inputs_strategy))
55
+ single_dim_placement = [dim_sharding]
56
+ return expand_to_full_mesh_op_strategy(
57
+ mesh, op_schema, single_dim_placement, input_index=output_len
58
+ )
59
+
60
+
61
+ def as_list(
62
+ x: list[object] | object,
63
+ # pyre-fixme[11]: Annotation `immutable_list` is not defined as a type.
64
+ ) -> list[object] | torch.fx.immutable_collections.immutable_list: # type: ignore[valid-type]
65
+ # During tracing, `aten.sum.dim_IntList` uses `immutable_list` for its args,
66
+ # which is an object but treated as a list by the tracer. Therefore, keep
67
+ # `immutable_list` intact here as well.
68
+ if type(x) is list or isinstance(x, torch.fx.immutable_collections.immutable_list):
69
+ return x
70
+ else:
71
+ return [x]
72
+
73
+
74
+ def normalize_dim(dim: int, ndim: int) -> int:
75
+ return dim if dim >= 0 else dim + ndim
76
+
77
+
78
+ def normalize_dims(dims: DimsType, ndim: int) -> DimsSequenceType:
79
+ """Normalize a dim or a sequence of dims, so that they are all positive."""
80
+ if isinstance(dims, int):
81
+ dims = (normalize_dim(dims, ndim),)
82
+ elif isinstance(dims, list):
83
+ dims = [normalize_dim(dim, ndim) for dim in dims]
84
+ elif isinstance(dims, tuple):
85
+ dims = tuple(normalize_dim(dim, ndim) for dim in dims)
86
+ return dims
87
+
88
+
89
+ def prod(xs: Iterable[int]) -> int:
90
+ return functools.reduce(operator.mul, xs, 1)
91
+
92
+
93
+ def is_tensor_shardable(
94
+ shape: Sequence[int],
95
+ spec: DTensorSpec,
96
+ allow_unbacked_sharding: bool | None = None,
97
+ ) -> bool:
98
+ """
99
+ Check if the shape is shardable according to the spec.
100
+
101
+ allow_unbacked_sharding: determines the fallback value if unbacked shapes are involved,
102
+ and the queried shape properties are not statically known.
103
+
104
+ e.g. when asking if u0 is shardable on num_shards, and u0 has generic bounds [0, inf],
105
+ the behavior of allow_unbacked_sharding is:
106
+
107
+ None: will data-dependent error
108
+ True: assumes shardability; we return True, allowing zero-size shards at runtime when u0 < num_shards.
109
+ False: returns False, and lower-bounding u0, e.g. torch._check(u0 >= num_shards), is needed to enable sharding.
110
+ """
111
+ from torch.fx.experimental.symbolic_shapes import guard_or_false, guard_or_true
112
+
113
+ assert allow_unbacked_sharding in [None, True, False]
114
+ guard_fn = {
115
+ None: bool,
116
+ True: guard_or_false,
117
+ False: guard_or_true,
118
+ }[allow_unbacked_sharding]
119
+
120
+ # number of shards in each tensor dimension
121
+ shards_map = [1] * len(shape)
122
+ for i, placement in enumerate(spec.placements):
123
+ if placement.is_shard():
124
+ shard_dim = cast(Shard, placement).dim
125
+ if shard_dim >= len(shape):
126
+ return False
127
+ shards_map[shard_dim] *= spec.mesh.size(i)
128
+
129
+ for i, dim_size in enumerate(shape):
130
+ # TODO: maybe we should determine is_shardable based on
131
+ # whether it's evenly sharded or not
132
+ if shards_map[i] > 1 and guard_fn(dim_size < shards_map[i]):
133
+ return False
134
+
135
+ return True
136
+
137
+
138
+ def is_tensor_evenly_shardable(shape: Sequence[int], spec: DTensorSpec) -> bool:
139
+ """Check if the shape is evenly shardable according to the spec."""
140
+ # number of shards in each tensor dimension
141
+ shards_map = [1] * len(shape)
142
+ for i, placement in enumerate(spec.placements):
143
+ if placement.is_shard():
144
+ shard_dim = cast(Shard, placement).dim
145
+ shards_map[shard_dim] *= spec.mesh.size(i)
146
+
147
+ for i, dim_size in enumerate(shape):
148
+ if shards_map[i] > 1 and (dim_size % shards_map[i] != 0):
149
+ return False
150
+
151
+ return True
152
+
153
+
154
+ def is_tensor_evenly_shardable_on_dim(
155
+ shape: Sequence[int], spec: DTensorSpec, dim: int
156
+ ) -> bool:
157
+ """Check if the shape is evenly shardable according to the spec on dim."""
158
+ dim = normalize_dim(dim, len(shape))
159
+
160
+ num_shards = 1
161
+ for i, placement in enumerate(spec.placements):
162
+ if placement.is_shard():
163
+ shard_dim = cast(Shard, placement).dim
164
+ if shard_dim == dim:
165
+ num_shards *= spec.mesh.size(i)
166
+
167
+ return shape[dim] % num_shards == 0
168
+
169
+
170
+ def is_tensor_dim_sharded(spec: DTensorSpec, dim: int) -> bool:
171
+ """Return True if tensor dim is sharded."""
172
+ return any(p.is_shard(dim) for p in spec.placements)
173
+
174
+
175
+ def is_tensor_partial(spec: DTensorSpec) -> bool:
176
+ """Return True if tensor is partial on the mesh."""
177
+ return any(p.is_partial() for p in spec.placements)
178
+
179
+
180
+ def infer_broadcast_dims_map(
181
+ common_shape: torch.Size, input_shape: torch.Size
182
+ ) -> list[int]:
183
+ # infer the broadcast dims map, where it maps from the common shape dim to the input shape dim
184
+ # this is aligned with the broadcast semantics
185
+ # e.g. if common_shape = [1, 2, 3, 4] and input_shape = [2, 3, 4],
186
+ # broadcast_dims_map will be [-1, 0, 1, 2]
187
+ # meaning that dim 0 in the output has no mapping to the input, and dim 1 in the output maps to dim 0 in the input
188
+ common_ndim = len(common_shape)
189
+ input_ndim = len(input_shape)
190
+ broadcast_dims_map = [-1] * common_ndim
191
+ for idx in range(-1, -1 - input_ndim, -1):
192
+ if input_shape[idx] == common_shape[idx]:
193
+ broadcast_dims_map[common_ndim + idx] = input_ndim + idx
194
+ return broadcast_dims_map
195
+
196
+
197
+ def map_placements_after_broadcast(
198
+ placements: tuple[Placement, ...],
199
+ shape: torch.Size,
200
+ broadcast_dims_map: list[int],
201
+ partial_to_replicate: bool = False,
202
+ ) -> tuple[Placement, ...]:
203
+ """Map each placement based on the output shape after broadcast."""
204
+ new_placements: list[Placement] = []
205
+ for placement in placements:
206
+ if isinstance(placement, Partial):
207
+ if partial_to_replicate:
208
+ # map the partial placement to replicate
209
+ new_placements.append(Replicate())
210
+ else:
211
+ new_placements.append(placement)
212
+ elif isinstance(placement, Replicate):
213
+ new_placements.append(placement)
214
+ else:
215
+ assert isinstance(placement, Shard | _StridedShard)
216
+ shard_dim = normalize_dim(placement.dim, len(shape))
217
+ new_shard_dim = broadcast_dims_map[shard_dim]
218
+ if new_shard_dim != -1:
219
+ # there's a map from the common shape shard dim to
220
+ # the input shape shard dim before broadcasting,
221
+ # use that instead
222
+ if isinstance(placement, _StridedShard):
223
+ new_placements.append(
224
+ _StridedShard(
225
+ new_shard_dim, split_factor=placement.split_factor
226
+ )
227
+ )
228
+ else:
229
+ new_placements.append(Shard(new_shard_dim))
230
+ else:
231
+ # there's no map between common shape shard dim and
232
+ # the input shape shard dim before broadcasting,
233
+ # in this case it means implicit broadcasting happen
234
+ # in this dim, so we can just mark it as replicate
235
+ # and implicit broadcast will broadcast automatically
236
+ # to the sharded shape
237
+ new_placements.append(Replicate())
238
+
239
+ return tuple(new_placements)
240
+
241
+
242
+ def generate_redistribute_costs(
243
+ src_strategy: OpStrategy, dst_spec: DTensorSpec
244
+ ) -> list[float]:
245
+ """Generates one row in the 'redistribute_costs' matrix in an OpSpec
246
+ The length of the returned list will match the number of strategies in 'src_strategy'.
247
+
248
+ Each value in the row is the cost of redistributing from a particular src_strategy to dst_spec.
249
+ """
250
+ redistribute_costs: list[float] = [
251
+ redistribute_cost(strat.output_spec, dst_spec)
252
+ for strat in src_strategy.strategies
253
+ ]
254
+
255
+ return redistribute_costs
256
+
257
+
258
+ def expand_to_full_mesh_op_strategy(
259
+ mesh: DeviceMesh,
260
+ op_schema: OpSchema,
261
+ single_mesh_dim_strategies: list[PlacementList],
262
+ *,
263
+ input_index: int = 1,
264
+ inplace_op: bool = False,
265
+ is_valid_strategy_cb: Callable[
266
+ [list[DTensorSpec], tuple[DTensorSpec | None, ...]], bool
267
+ ]
268
+ | None = None,
269
+ ) -> OpStrategy:
270
+ """
271
+ Convenience function to allow writing a sharding strategy considering only a single mesh dimension,
272
+ and have it expanded combinatorically to all mesh dimensions.
273
+
274
+ Args:
275
+ mesh (DeviceMesh): the device mesh to expand the strategy to
276
+ op_schema (OpSchema): the op schema
277
+ single_mesh_dim_strategies (list[PlacementList]): the sharding strategies to expand. The outer list is over
278
+ different strategies. The inner PlacementList is over the outputs and inputs of the op. If input_index is 1,
279
+ a PlacementList looks like [output_placement, input_placement1, input_placement2, ...].
280
+ input_index: the number of outputs of the op, defaults to 1
281
+ inplace_op: whether the op is inplace or not, defaults to False
282
+ is_valid_strategy_cb: a callback function to filter out invalid sharding rules, defaults to None.
283
+
284
+ Example: Let's say `my_op(tensor_x, tensor_y) - > output_tensor` can support sharding or replicating tensor_x,
285
+ but always requires tensor_y to be replicated. We can specify these valid combinations ignoring mesh dims.
286
+ Then, we can rely on `expand_to_full_mesh_op_strategy` to create every possible combination of these shardings
287
+ over multiple mesh dimensions, filtering out any combinations that are invalid based on the actual mesh dim size.
288
+
289
+ single_mesh_dim_strategies = [
290
+ # first strategy: return output sharded on first dim, shard tensor_x on its first dim, replicate tensor_y
291
+ [Shard(0), Shard(0), Replicate()]
292
+ # second strategy: replicate output, and both inputs
293
+ [Replicate(), Replicate(), Replicate()]
294
+ ]
295
+ """
296
+ # Expand the single_mesh_dim_strategies to full mesh dim strategies.
297
+ all_mesh_dim_strategies = [single_mesh_dim_strategies] * mesh.ndim
298
+
299
+ strategy_combs = itertools.product(*all_mesh_dim_strategies)
300
+
301
+ all_strategies = []
302
+ for strategy_comb in strategy_combs:
303
+ spec_list: list[DTensorSpec | None] = []
304
+ for specs in zip(*strategy_comb):
305
+ if specs[0] is not None:
306
+ # TODO: we should fill in tensor_meta here. If nothing else, it helps the filter strategy callback
307
+ # pyrefly: ignore [bad-argument-type]
308
+ spec_list.append(DTensorSpec(mesh, specs))
309
+ else:
310
+ spec_list.append(None)
311
+
312
+ input_specs: list[DTensorSpec] = [
313
+ s for s in spec_list[input_index:] if isinstance(s, DTensorSpec)
314
+ ]
315
+
316
+ args_strategy = op_schema.args_strategy
317
+ kwargs_strategy = op_schema.kwargs_strategy
318
+ input_args_strategy = args_strategy + kwargs_strategy
319
+
320
+ if len(input_specs) != len(input_args_strategy):
321
+ raise AssertionError(
322
+ f"input_specs({len(input_specs)}) != strategies({len(input_args_strategy)}: "
323
+ f"{len(args_strategy)} args + {len(kwargs_strategy)} kwargs)"
324
+ )
325
+ self_spec = input_args_strategy[0].strategies[0].output_spec
326
+
327
+ if inplace_op and self_spec.placements != input_specs[0].placements:
328
+ # if it's inplace op, we would only allow the OpSpec to be added when the
329
+ # input_spec matches the first argument's runtime sharding, otherwise we skip
330
+ continue
331
+
332
+ output_specs: tuple[DTensorSpec | None, ...]
333
+ if input_index > 1:
334
+ output_specs = tuple(spec_list[:input_index])
335
+ else:
336
+ if spec_list[0] is not None:
337
+ output_specs = spec_list[0] # type: ignore[assignment]
338
+ else:
339
+ raise RuntimeError("output spec is None")
340
+
341
+ # check all inputs are shardable
342
+ if not all(
343
+ is_tensor_shardable(inp.shape, s)
344
+ for inp, s in zip(input_args_strategy, input_specs)
345
+ ):
346
+ continue
347
+
348
+ # perform additional op-specific filtering
349
+ if is_valid_strategy_cb is not None:
350
+ if not is_valid_strategy_cb(input_specs, output_specs):
351
+ continue
352
+
353
+ redistribute_cost = [
354
+ generate_redistribute_costs(input_strategy, input_spec)
355
+ for input_strategy, input_spec in zip(input_args_strategy, input_specs)
356
+ ]
357
+
358
+ strategy = OpSpec(
359
+ output_specs=output_specs,
360
+ input_specs=input_specs,
361
+ redistribute_cost=redistribute_cost,
362
+ )
363
+ all_strategies.append(strategy)
364
+ return OpStrategy(all_strategies)
365
+
366
+
367
+ def shift_shard_dims_after_insert(
368
+ placements: Sequence[Placement], insert_dim: int = 0
369
+ ) -> Sequence[Placement]:
370
+ normalized_placements: list[Placement] = []
371
+ for placement in placements:
372
+ if isinstance(placement, Shard) and placement.dim >= insert_dim:
373
+ normalized_placements.append(Shard(placement.dim + 1))
374
+ else:
375
+ normalized_placements.append(placement)
376
+ return normalized_placements
377
+
378
+
379
+ def shift_shard_dims_after_remove(
380
+ placements: Sequence[Placement], remove_dim: int = 0
381
+ ) -> Sequence[Placement]:
382
+ normalized_placements: list[Placement] = []
383
+ for placement in placements:
384
+ if isinstance(placement, Shard) and placement.dim > remove_dim:
385
+ normalized_placements.append(Shard(placement.dim - 1))
386
+ else:
387
+ normalized_placements.append(placement)
388
+ return normalized_placements
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/_utils.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import threading
3
+ from collections.abc import Sequence
4
+ from typing import Any, cast, Optional
5
+
6
+ import torch
7
+ import torch.distributed._functional_collectives as funcol
8
+ import torch.distributed.tensor._api as dtensor
9
+ from torch._prims_common import ShapeType
10
+ from torch.distributed._local_tensor import maybe_run_for_local_tensor
11
+ from torch.distributed.device_mesh import DeviceMesh
12
+ from torch.distributed.tensor._collective_utils import redistribute_cost
13
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec
14
+ from torch.distributed.tensor.placement_types import (
15
+ _StridedShard,
16
+ Partial,
17
+ Placement,
18
+ Replicate,
19
+ Shard,
20
+ )
21
+
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class ExplicitRedistributionContext:
27
+ """
28
+ Within this context manager, DTensor will refuse to perform implicit redistribution,
29
+ instead raising an error. Manual calls to ``redistribute()`` are required wherever a redistribution
30
+ must occur to avoid erroring. This can be used to ensure that the user is aware of all redistribution.
31
+
32
+ Note: it is easier to use this mode on just the forward pass of a typical DTensor program, as the backwards pass
33
+ may contain implicit redistribution calls that are not visible to the user and difficult to replace with manual
34
+ calls. Redistribution during backward can be made explicit by writing `autograd.Function`s that are no-op
35
+ during forward and perform a manual redistribution during backwards.
36
+
37
+ enable (bool) if False, disables the context manager. Can be used nested inside an enabled region.
38
+
39
+ strict (bool) if True, triggers on any redistribution. If False, only triggers on redistributions that perform
40
+ communication.
41
+
42
+ mode (str) Determines what happens when ExplicitRedistributionContext triggers:
43
+ "raise": raises an exceptoin, "warn" issues a warning
44
+ """
45
+
46
+ _local = threading.local()
47
+
48
+ def __init__(self, enable: bool = True, strict: bool = False, mode="raise"):
49
+ self._enable = enable
50
+ self._strict = strict
51
+ if mode not in ("raise", "warn"):
52
+ raise RuntimeError(f"Invalid mode {mode}")
53
+ self._raise_on_redistribution = mode == "raise"
54
+
55
+ @classmethod
56
+ def observe_redistribution(
57
+ cls, src_spec: DTensorSpec, dst_spec: DTensorSpec, message: str
58
+ ):
59
+ if instance := getattr(cls._local, "_active", None):
60
+ allowed = True
61
+ if instance._enable:
62
+ if instance._strict:
63
+ allowed = False
64
+ else:
65
+ allowed = redistribute_cost(src_spec, dst_spec) <= 0
66
+ if not allowed:
67
+ if instance._raise_on_redistribution:
68
+ raise RuntimeError(message)
69
+ else:
70
+ logger.warning(message)
71
+
72
+ def __enter__(self):
73
+ self._prev = getattr(ExplicitRedistributionContext._local, "_active", None)
74
+ ExplicitRedistributionContext._local._active = self
75
+ return self
76
+
77
+ def __exit__(self, exc_type, exc_val, exc_tb):
78
+ ExplicitRedistributionContext._local._active = self._prev
79
+
80
+
81
+ def compute_local_shape_and_global_offset(
82
+ global_shape: ShapeType,
83
+ mesh: DeviceMesh,
84
+ placements: Sequence[Placement],
85
+ skip_offset: bool = False,
86
+ ) -> tuple[tuple[int, ...], tuple[int, ...]]:
87
+ """
88
+ Compute the local tensor shape and the global offsets into the original tensor
89
+ of a DTensor on its current global rank. This is useful for checkpointing purpose.
90
+
91
+ Example:
92
+ global_tensor = [[0, 1, 2, 3, 4], sharded on mesh (DP=2, TP=2) with (Shard(1), Shard(1))
93
+ [10, 11, 12, 13, 14]]
94
+
95
+ This table shows the return value of local_shape and global_offset for each rank.
96
+ (`local_tensor` is for illustration only).
97
+
98
+ Note how the first coordinate of global_offset is always 0, corresponding to tensor dim 0 being replicated.
99
+
100
+ Rank local_tensor local_shape global_offset
101
+ -------------------------------------------------------------
102
+ 0 [[0, 1], (2, 2) (0, 0)
103
+ [10, 11]]
104
+
105
+ 1 [[2], (2, 1) (0, 2)
106
+ [12]]
107
+
108
+ 2 [[3], (2, 1) (0, 3)
109
+ [13]]
110
+
111
+ 3 [[4], (2, 1) (0, 4)
112
+ [14]]
113
+
114
+ Args:
115
+ global_shape (ShapeType): The global shape of the DTensor.
116
+ mesh (:class:`DeviceMesh`): The device mesh this DTensor is distributed on.
117
+ placements (Sequence[:class:`Placement`]]): The placements of the DTensor.
118
+ skip_offset (bool): If True, skip computing the global offsets and return an empty
119
+ tuple for global_offset. This can improve performance when only the local shape
120
+ is needed. Defaults to False.
121
+
122
+ Return:
123
+ local_shape: the shape of the DTensor's _local_tensor on the current rank.
124
+ global_offset: a tuple of offsets for each dimension of the global tensor shape,
125
+ identifying how this shard fits into the global tensor in each dimension. If
126
+ skip_offset is True, this will be an empty tuple.
127
+
128
+ """
129
+ return _compute_local_shape_and_global_offset(
130
+ global_shape, mesh.shape, mesh.get_coordinate(), placements, skip_offset
131
+ )
132
+
133
+
134
+ @maybe_run_for_local_tensor
135
+ def _get_shard_size_and_offsets(
136
+ curr_local_size: int,
137
+ mesh_dim_size: int,
138
+ rank: int,
139
+ placement: Shard | _StridedShard,
140
+ previous_offsets,
141
+ zero_global_offset: int,
142
+ skip_offset: bool,
143
+ ) -> tuple[int, Optional[torch.Tensor]]:
144
+ kwargs: dict[str, Any] = {
145
+ "curr_local_size": curr_local_size,
146
+ "num_chunks": mesh_dim_size,
147
+ "rank": rank,
148
+ }
149
+ if isinstance(placement, _StridedShard):
150
+ kwargs["return_first_offset"] = False
151
+ shard_size, shard_offsets = placement._local_shard_size_and_offset(**kwargs)
152
+ if skip_offset:
153
+ return shard_size, None
154
+ if shard_size == 0:
155
+ return shard_size, torch.arange(zero_global_offset, zero_global_offset + 1)
156
+ if isinstance(placement, Shard) and not isinstance(placement, _StridedShard):
157
+ assert isinstance(shard_offsets, int)
158
+ index = torch.arange(shard_offsets, shard_offsets + shard_size)
159
+ else:
160
+ assert isinstance(shard_offsets, list)
161
+ index = torch.tensor(shard_offsets)
162
+ if previous_offsets is None:
163
+ return shard_size, index
164
+ else:
165
+ return shard_size, previous_offsets[index]
166
+
167
+
168
+ @maybe_run_for_local_tensor
169
+ def _get_first_offset(offsets: torch.Tensor) -> int:
170
+ return int(offsets[0])
171
+
172
+
173
+ # accept 'plain data types' to enable simpler unit testing without creating device mesh
174
+ def _compute_local_shape_and_global_offset(
175
+ global_shape: ShapeType,
176
+ mesh_shape: ShapeType,
177
+ my_coordinate: list[int] | None,
178
+ placements: Sequence[Placement],
179
+ skip_offset: bool = False,
180
+ ) -> tuple[tuple[int, ...], tuple[int, ...]]:
181
+ """
182
+ Suppose you have a full tensor with size global_shape, and you have sharded
183
+ it according to placements for mesh_shape. This function returns, for a
184
+ specific coordinate my_coordinate in the device mesh:
185
+
186
+ - The size of your local shard WITHOUT padding (i.e., if you have
187
+ an uneven split, your size might be smaller than the other entries
188
+ in your dim), and
189
+
190
+ - Where the data for your shard begins, in the full tensor.
191
+
192
+ This function is fairly simple if your tensor is evenly sharded; the complication
193
+ is around uneven splits. There is also some complication for handling StridedShard,
194
+ which changes the order you should apply sharding.
195
+
196
+ Args:
197
+ global_shape (ShapeType): The global shape of the tensor.
198
+ mesh_shape (ShapeType): The shape of the device mesh.
199
+ my_coordinate (Optional[list[int]]): The coordinate of the current rank in the device mesh.
200
+ placements (Sequence[Placement]): The placements of the DTensor.
201
+ skip_offset (bool): If True, skip computing the global offsets and return an empty
202
+ tuple for global_offset. This can improve performance when only the local shape
203
+ is needed. Defaults to False.
204
+
205
+ Returns:
206
+ tuple: A tuple containing:
207
+ - local_shape (tuple[int, ...]): The shape of the local shard on the current rank.
208
+ - global_offset (tuple[int, ...]): The offsets for each dimension identifying where
209
+ this shard begins in the global tensor. If skip_offset is True, this will be an
210
+ empty tuple.
211
+ """
212
+
213
+ empty_offset = ()
214
+ if my_coordinate is None:
215
+ # if rank not in the mesh, return empty offset
216
+ return ((0,), empty_offset)
217
+
218
+ local_shape = list(global_shape)
219
+ # Perform shard from left to right. For example,
220
+ # global tensor: [0, 1, 2, 3, 4, 5, 6, 7]
221
+ # placements: S(0), SS(0, split_factor=2)
222
+ # mesh_shape: (2, 2)
223
+ # After S(0), shard_dim_to_global_offsets are
224
+ # {0: [0, 1, 2, 3]} on my_coordinate [0, 0] [0, 1]
225
+ # {0: [4, 5, 6, 7]} on my_coordinate [1, 0] [1, 1]
226
+ # After SS(0, split_factor=2), shard_dim_to_global_offsets are
227
+ # {0: [0, 2]} on my_coordinate [0, 0]
228
+ # {0: [1, 3]} on my_coordinate [0, 1]
229
+ # {0: [4, 6]} on my_coordinate [1, 0]
230
+ # {0: [5, 7]} on my_coordinate [1, 1]
231
+ shard_dim_to_global_offsets = {}
232
+ for mesh_dim, placement in enumerate(placements):
233
+ if not isinstance(placement, (Shard, _StridedShard)):
234
+ continue
235
+ shard_dim = placement.dim
236
+ zero_global_offset = global_shape[shard_dim]
237
+ assert shard_dim < len(local_shape), (
238
+ f"Sharding dim {shard_dim} greater than tensor ndim {len(local_shape)}"
239
+ )
240
+ previous_offsets = shard_dim_to_global_offsets.get(shard_dim)
241
+ shard_size, shard_offsets = _get_shard_size_and_offsets(
242
+ local_shape[shard_dim],
243
+ mesh_shape[mesh_dim],
244
+ my_coordinate[mesh_dim],
245
+ placement,
246
+ previous_offsets,
247
+ zero_global_offset,
248
+ skip_offset,
249
+ )
250
+ local_shape[shard_dim] = shard_size
251
+ shard_dim_to_global_offsets[shard_dim] = shard_offsets
252
+ if skip_offset:
253
+ return tuple(local_shape), empty_offset
254
+ global_offset = [0] * len(global_shape)
255
+ for shard_dim, global_offsets in shard_dim_to_global_offsets.items():
256
+ global_offset[shard_dim] = _get_first_offset(global_offsets)
257
+ return tuple(local_shape), tuple(global_offset)
258
+
259
+
260
+ compute_global_tensor_info = torch._C._DTensor_compute_global_tensor_info
261
+
262
+
263
+ def compute_local_tensor_info(
264
+ global_tensor: torch.Tensor,
265
+ mesh: DeviceMesh,
266
+ placements: Sequence[Placement],
267
+ ) -> tuple[list[int], list[int]]:
268
+ """
269
+ Compute the local size and stride of a DTensor from the given global tensor info.
270
+
271
+ For example, if we have a global tensor with size (4, 8, 4) and stride (32, 1, 8).
272
+ If the DTensor placements are [Shard(2)] and world_size is 2;
273
+ then the local size is (4, 8, 2) and stride is (16, 1, 8).
274
+
275
+ Args:
276
+ tensor (:class:`torch.Tensor`):
277
+ Global tensor which DTensor will distribute
278
+ mesh (:class:`DeviceMesh`):
279
+ Object which describes the mesh topology
280
+ of devices for the DTensor.
281
+ placements (Sequence[:class:`Placement`]):
282
+ The attribute of the DTensor that describes its layout
283
+ on the mesh topology.
284
+
285
+ Returns:
286
+ local_shape: A List of int which specifies the size of the local tensor.
287
+ local_stride: A List of int which specifies the stride of the local tensor.
288
+ """
289
+ local_shape = list(global_tensor.size())
290
+ local_stride = list(global_tensor.stride())
291
+
292
+ for idx, placement in enumerate(placements):
293
+ mesh_dim_size = mesh.size(idx)
294
+ if placement.is_shard():
295
+ shard_placement = cast(Shard, placement)
296
+ if shard_placement.dim < 0:
297
+ raise AssertionError(
298
+ "Shard placements should have negative dims normalized in "
299
+ f"the user-facing APIs: {shard_placement}"
300
+ )
301
+ shard_dim = shard_placement.dim
302
+ assert shard_dim < len(local_shape), (
303
+ f"Sharding dim {shard_dim} greater than tensor ndim {len(local_shape)} "
304
+ f"for placement number {idx}."
305
+ )
306
+
307
+ global_dim_size = local_shape[shard_dim]
308
+ assert global_dim_size % mesh_dim_size == 0, (
309
+ f"Global dim {global_dim_size} not divisible by mesh size {mesh_dim_size}"
310
+ )
311
+ local_shape[shard_dim] = global_dim_size // mesh_dim_size
312
+
313
+ # shrink strides that were scaled up globally
314
+ for i in range(len(local_stride)):
315
+ if (
316
+ i != shard_dim
317
+ and local_stride[i] >= local_stride[shard_dim] * mesh_dim_size
318
+ ):
319
+ local_stride[i] = local_stride[i] // mesh_dim_size
320
+
321
+ elif not isinstance(placement, (Replicate, Partial)):
322
+ raise RuntimeError(f"placement type {type(placement)} not supported!")
323
+
324
+ return local_shape, local_stride
325
+
326
+
327
+ def compute_global_tensor_shape(
328
+ shape: torch.Size, mesh: DeviceMesh, placements: Sequence[Placement]
329
+ ) -> torch.Size:
330
+ """
331
+ Compute the global size of a DTensor from the given local tensor shape,
332
+ the mesh and placements. Different from `compute_global_tensor_info`,
333
+ which assumes sharding is even, this util allgathers local shards' shapes
334
+ from all ranks and thus can support uneven sharding.
335
+ NOTE: Currently this function only supports 1D mesh.
336
+
337
+ Args:
338
+ shape (:class:`torch.Size`):
339
+ Shape of the local tensor
340
+ mesh (:class:`DeviceMesh`):
341
+ Object which describes the mesh topology
342
+ of devices for the DTensor.
343
+ placements (Sequence[:class:`Placement`]]):
344
+ The attribute of the DTensor that describes its layout
345
+ on the mesh topology.
346
+
347
+ Return:
348
+ tensor_shape: Shape of the global DTensor.
349
+ """
350
+ if len(placements) != 1:
351
+ raise NotImplementedError(
352
+ "compute_global_tensor_shape only supports 1 placement for now."
353
+ )
354
+
355
+ if len(placements) != mesh.ndim:
356
+ raise RuntimeError(
357
+ "Expected one placement per mesh dim, "
358
+ f"but found {len(placements)} placements and {mesh.ndim} mesh dims."
359
+ )
360
+
361
+ if isinstance(placements[0], Replicate):
362
+ return shape
363
+ elif isinstance(placements[0], Shard):
364
+
365
+ @maybe_run_for_local_tensor
366
+ def _create_local_shape_tensor(shape):
367
+ return torch.tensor(list(shape), device=mesh.device_type)
368
+
369
+ local_shape = _create_local_shape_tensor(shape)
370
+ gathered_shaped_tensors = [
371
+ torch.empty_like(local_shape, device=local_shape.device)
372
+ for _ in range(mesh.size())
373
+ ]
374
+ funcol.all_gather_inplace(gathered_shaped_tensors, local_shape, mesh)
375
+
376
+ @maybe_run_for_local_tensor
377
+ def _validate_and_compute_global_shape(local_shape, gathered_shaped_tensors):
378
+ sharded_dim_sum = 0
379
+ shard_dim = placements[0].dim # type: ignore[union-attr]
380
+ other_dims = [d for d in range(len(shape)) if d != shard_dim]
381
+ for shape_tensor in gathered_shaped_tensors:
382
+ if not torch.equal(local_shape[other_dims], shape_tensor[other_dims]):
383
+ raise RuntimeError(
384
+ "Non-sharded dimensions should have identical size across ranks."
385
+ )
386
+ shape_tensor_list = shape_tensor.tolist()
387
+ sharded_dim_sum += shape_tensor_list[shard_dim]
388
+ return sharded_dim_sum
389
+
390
+ sharded_dim_sum = _validate_and_compute_global_shape(
391
+ local_shape, gathered_shaped_tensors
392
+ )
393
+ global_shape = list(shape)
394
+ global_shape[placements[0].dim] = sharded_dim_sum
395
+ return torch.Size(global_shape)
396
+ else:
397
+ raise NotImplementedError(
398
+ f"Placement type {type(placements[0])} not supported."
399
+ )
400
+
401
+
402
+ def try_find_mesh_from_args(
403
+ op_call: torch._ops.OpOverload, args: Sequence[object]
404
+ ) -> DeviceMesh:
405
+ """
406
+ Find the device mesh object from args.
407
+ It returns None if no mesh is found.
408
+ NOTE: we can optimize this search if needed
409
+ """
410
+ for arg in args:
411
+ if isinstance(arg, (dtensor.DTensor, DTensorSpec)):
412
+ return arg.device_mesh
413
+ elif (
414
+ isinstance(arg, (list, tuple))
415
+ and len(arg) > 0
416
+ and isinstance(arg[0], (dtensor.DTensor, DTensorSpec))
417
+ ):
418
+ return arg[0].device_mesh
419
+
420
+ raise ValueError(f"Cannot find device mesh from args for op : {op_call}.")
421
+
422
+
423
+ def compute_local_stride(
424
+ global_stride: ShapeType, mesh: DeviceMesh, placements: Sequence[Placement]
425
+ ) -> tuple[int, ...]:
426
+ """
427
+ Compute the stride of a local tensor shard, given the global stride of the DTensor.
428
+ NOTE: Currently this function is assuming the DTensor is evenly shardable.
429
+ """
430
+ stride_divisors = [1] * len(global_stride)
431
+ for mesh_idx, p in enumerate(placements):
432
+ if p.is_shard():
433
+ i = cast(Shard, p).dim
434
+ # tensor dimension i is sharded on mesh dimension mesh_idx,
435
+ # so we need to divide all the strides larger than stride[i]
436
+ # (by the submesh size)
437
+ for j in range(len(global_stride)):
438
+ if global_stride[j] > global_stride[i]:
439
+ stride_divisors[j] *= mesh.size(mesh_idx)
440
+ return tuple(
441
+ global_stride[i] // stride_divisors[i] for i in range(len(global_stride))
442
+ )
443
+
444
+
445
+ def normalize_to_torch_size(size) -> torch.Size: # type: ignore[no-untyped-def]
446
+ """
447
+ Unify variable types of size argument to torch.Size
448
+ Acceptable types include:
449
+ int, Sequence[int], Tuple[int], Tuple[Sequence[int]],
450
+ or torch.Size
451
+ """
452
+ if isinstance(size, torch.Size):
453
+ return size
454
+
455
+ if isinstance(size, int):
456
+ torch_size = [size]
457
+ elif len(size) == 1 and isinstance(size[0], Sequence):
458
+ torch_size = list(size[0])
459
+ else:
460
+ torch_size = list(size)
461
+ return torch.Size(torch_size)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/debug/__init__.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch._C
3
+ from torch.distributed.tensor.debug._comm_mode import CommDebugMode
4
+ from torch.distributed.tensor.debug._visualize_sharding import visualize_sharding
5
+
6
+
7
+ __all__ = ["CommDebugMode", "visualize_sharding"]
8
+
9
+
10
+ def _get_python_sharding_prop_cache_info():
11
+ """
12
+ Get the cache info for the Python sharding propagation cache, used for debugging purpose only.
13
+ This would return a named tuple showing hits, misses, maxsize and cursize of the sharding
14
+ propagator cache. Note that directly calling into the sharding propagator does not share cache
15
+ state with the DTensor dispatch fast path!
16
+ """
17
+ from torch.distributed.tensor._api import DTensor
18
+
19
+ return (
20
+ DTensor._op_dispatcher.sharding_propagator.propagate_op_sharding.cache_info() # type:ignore[attr-defined]
21
+ )
22
+
23
+
24
+ def _get_fast_path_sharding_prop_cache_stats():
25
+ """
26
+ Get a tuple (hits, misses) for the fast path sharding propagation cache, used for debugging
27
+ only.
28
+ """
29
+ return torch._C._get_DTensor_sharding_propagator_cache_stats()
30
+
31
+
32
+ def _clear_python_sharding_prop_cache():
33
+ """
34
+ Clears the cache for the Python sharding propagation cache, used for debugging purpose only.
35
+ """
36
+ from torch.distributed.tensor._api import DTensor
37
+
38
+ return (
39
+ DTensor._op_dispatcher.sharding_propagator.propagate_op_sharding.cache_clear() # type:ignore[attr-defined]
40
+ )
41
+
42
+
43
+ def _clear_fast_path_sharding_prop_cache():
44
+ """
45
+ Clears the cache for the fast path sharding propagation cache, used for debugging purpose only.
46
+ """
47
+ torch._C._clear_DTensor_sharding_propagator_cache()
48
+
49
+
50
+ # Set namespace for exposed private names
51
+ CommDebugMode.__module__ = "torch.distributed.tensor.debug"
52
+ visualize_sharding.__module__ = "torch.distributed.tensor.debug"
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/debug/_comm_mode.py ADDED
@@ -0,0 +1,740 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+ import json
4
+ import re
5
+ import weakref
6
+ from collections import defaultdict
7
+ from typing import Any
8
+
9
+ import torch
10
+ import torch.nn
11
+ from torch._guards import detect_fake_mode
12
+ from torch.autograd.graph import register_multi_grad_hook
13
+ from torch.distributed._tools.mod_tracker import ModTracker
14
+ from torch.distributed.tensor._api import DTensor
15
+ from torch.nn.modules.module import (
16
+ register_module_forward_hook,
17
+ register_module_forward_pre_hook,
18
+ register_module_full_backward_pre_hook,
19
+ )
20
+ from torch.utils._python_dispatch import TorchDispatchMode
21
+ from torch.utils._pytree import tree_flatten
22
+
23
+
24
+ __all__ = ["CommDebugMode"]
25
+
26
+ funcol_native = torch.ops._c10d_functional
27
+ funcol_py = torch.ops.c10d_functional
28
+ funcol_autograd = torch.ops._c10d_functional_autograd
29
+ c10d_ops = torch.ops.c10d
30
+
31
+ NATIVE_TO_PY_MAPPING = {
32
+ funcol_native.all_gather_into_tensor: funcol_py.all_gather_into_tensor,
33
+ funcol_native.all_gather_into_tensor_coalesced: funcol_py.all_gather_into_tensor_coalesced,
34
+ funcol_native.all_reduce: funcol_py.all_reduce,
35
+ funcol_native.all_reduce_coalesced: funcol_py.all_reduce_coalesced,
36
+ funcol_native.all_to_all_single: funcol_py.all_to_all_single,
37
+ funcol_native.broadcast: funcol_py.broadcast,
38
+ funcol_native.reduce_scatter_tensor: funcol_py.reduce_scatter_tensor,
39
+ funcol_native.reduce_scatter_tensor_coalesced: funcol_py.reduce_scatter_tensor_coalesced,
40
+ # functional ops
41
+ funcol_autograd.all_to_all_single: funcol_py.all_to_all_single,
42
+ }
43
+
44
+ c10d_collective_ops = {
45
+ c10d_ops._allgather_base_,
46
+ c10d_ops._reduce_scatter_base_,
47
+ c10d_ops.allgather_,
48
+ c10d_ops.allgather_coalesced_,
49
+ c10d_ops.allgather_into_tensor_coalesced_,
50
+ c10d_ops.allreduce_,
51
+ c10d_ops.allreduce_coalesced_,
52
+ c10d_ops.alltoall_,
53
+ c10d_ops.alltoall_base_,
54
+ c10d_ops.broadcast_,
55
+ c10d_ops.gather_,
56
+ c10d_ops.scatter_,
57
+ c10d_ops.reduce_,
58
+ c10d_ops.reduce_scatter_,
59
+ c10d_ops.reduce_scatter_tensor_coalesced_,
60
+ }
61
+
62
+ trivial_ops = {
63
+ "aten.detach.default",
64
+ "aten.t.default",
65
+ "aten.view.default",
66
+ "aten._to_copy.default",
67
+ "aten.as_strided.default",
68
+ "aten.transpose.int",
69
+ }
70
+
71
+
72
+ class _CommModeModuleTracker(ModTracker):
73
+ """
74
+ Inherits ModuleTracker and expands on its functionality to track the
75
+ parameters and sharding information of a model at a module-level
76
+ """
77
+
78
+ def __init__(self):
79
+ super().__init__()
80
+ self.module_helper_dict = {}
81
+ self.module_parameters_dict = {}
82
+ self.module_parents_dict = {}
83
+ self.register_forward_hook_handles = {}
84
+ self.parent_dict = {}
85
+ self.parent_list = []
86
+ self.sharding_dict = {}
87
+ self.activation_checkpointing = False
88
+ self.name = ""
89
+
90
+ def _fw_set_module_hook(self, mod, input, output):
91
+ """
92
+ Updates the current module after module finishes running and
93
+ all other hooks are resolved
94
+ """
95
+
96
+ if self.is_bw:
97
+ self.activation_checkpointing = True
98
+ else:
99
+ self.activation_checkpointing = False
100
+
101
+ if not self.activation_checkpointing:
102
+ # module is no longer parent of next modules
103
+ self.parent_list.pop()
104
+
105
+ # set current module to previous parent module
106
+ self.name = self.parent_list[-1]
107
+
108
+ def _fw_pre_hook(self, mod, input):
109
+ """
110
+ This function is called before the forward pass of a module. It
111
+ collects the parameters and sharding information of a module and
112
+ stores it in a dictionary.
113
+ """
114
+ if self.is_bw:
115
+ self.activation_checkpointing = True
116
+ else:
117
+ self.activation_checkpointing = False
118
+
119
+ self.name = super()._get_mod_name(mod)
120
+ w_mod = weakref.ref(mod)
121
+
122
+ # adds current sub-module to module tracker parent class
123
+ super()._get_append_fn(w_mod, self.name, False)()
124
+
125
+ args, _ = tree_flatten(input)
126
+ tensors = [a for a in args if isinstance(a, torch.Tensor) and a.requires_grad]
127
+ if not self.is_bw and tensors:
128
+ register_multi_grad_hook(
129
+ tensors, super()._get_pop_fn(w_mod, self.name, True)
130
+ )
131
+
132
+ if not self.activation_checkpointing:
133
+ # contains information about module ordering and depth in the module tree
134
+ if self.name not in self.module_helper_dict:
135
+ self.module_helper_dict[self.name] = {}
136
+
137
+ self.module_helper_dict[self.name]["module_type"] = (
138
+ str(type(mod)).replace("<", "").replace(">", "")
139
+ )
140
+ self.module_helper_dict[self.name]["depth"] = len(self.parents) - 1
141
+
142
+ for param_name, param in mod.named_parameters(recurse=False):
143
+ if self.name not in self.module_parameters_dict:
144
+ self.module_parameters_dict[self.name] = {}
145
+
146
+ self.module_parameters_dict[self.name][param_name] = param.data
147
+
148
+ if isinstance(param.data, DTensor):
149
+ key_name = self.name + "." + param_name
150
+ self.sharding_dict[key_name] = param.data.placements
151
+
152
+ if "parameters" not in self.module_helper_dict[self.name]:
153
+ self.module_helper_dict[self.name]["parameters"] = {}
154
+
155
+ self.module_helper_dict[self.name]["parameters"][param_name] = str(
156
+ param.data.placements
157
+ )
158
+
159
+ # used to store module's parents to ensure correctness in backward pass/checkpointing
160
+ if self.name not in self.module_parents_dict:
161
+ self.module_parents_dict[self.name] = copy.deepcopy(self.parents)
162
+
163
+ # used to create parent-child module associations for json dumps
164
+ parent = self.parent_list[-1]
165
+ if parent not in self.parent_dict:
166
+ self.parent_dict[parent] = []
167
+
168
+ self.parent_dict[parent].append(self.name)
169
+ self.parent_list.append(self.name)
170
+
171
+ self.register_forward_hook_handles[self.name] = mod.register_forward_hook(
172
+ self._fw_set_module_hook
173
+ )
174
+
175
+ def _fw_post_hook(self, mod, input, output): # pylint: disable=useless-parent-delegation
176
+ """
177
+ This function is called when the forward pass of a module is called.
178
+ It updates the module tracker and removes the module from parent data
179
+ """
180
+
181
+ super()._fw_post_hook(mod, input, output)
182
+
183
+ def _bw_hook(self, mod, output):
184
+ """
185
+ This function is called when the backward pass of a module is called. It
186
+ updates the current module for backward passes
187
+ """
188
+ self.activation_checkpointing = False
189
+ self.name = super()._get_mod_name(mod)
190
+
191
+ def __enter__(self):
192
+ self.activation_checkpointing = False
193
+ self.module_parameters_dict.clear()
194
+ self.sharding_dict.clear()
195
+ self.parent_dict.clear()
196
+ self.parent_list = ["Global"]
197
+ self.module_helper_dict.clear()
198
+ self.module_helper_dict["Global"] = {"depth": 0}
199
+ self.module_parents_dict.clear()
200
+ self.module_parents_dict["Global"] = set()
201
+ self._fw_pre_handle = register_module_forward_pre_hook(self._fw_pre_hook)
202
+ self._fw_post_handle = register_module_forward_hook(self._fw_post_hook)
203
+ self.register_forward_hook_handles.clear()
204
+ self._bw_handle = register_module_full_backward_pre_hook(self._bw_hook)
205
+ self.name = "Global"
206
+
207
+ def __exit__(self, *args):
208
+ super().__exit__(*args)
209
+ self._bw_handle.remove()
210
+
211
+ # removes all forward_hook handles added in the pre-hook
212
+ for handle in self.register_forward_hook_handles.values():
213
+ handle.remove()
214
+
215
+ def print_paramater_info(self):
216
+ print(self.module_parameters_dict)
217
+
218
+ def print_sharding_info(self):
219
+ for key, value in self.sharding_dict.items():
220
+ print(key + ": " + str(value))
221
+
222
+
223
+ class CommDebugMode(TorchDispatchMode):
224
+ """
225
+ :class:`CommDebugMode` is a context manager that counts the number of
226
+ functional collectives within its context. It does this using a
227
+ ``TorchDispatchMode``.
228
+
229
+ .. note:: Not all collectives are supported yet.
230
+
231
+ Example usage
232
+
233
+ .. code-block:: python
234
+
235
+ mod = ...
236
+ comm_mode = CommDebugMode()
237
+ with comm_mode:
238
+ mod.sum().backward()
239
+ print(comm_mode.get_comm_counts())
240
+ """
241
+
242
+ def __init__(self):
243
+ super().__init__()
244
+ self.comm_counts: dict[Any, int] = defaultdict(int)
245
+ self.comm_module_counts = {}
246
+ self.comm_module_operation_counts = {}
247
+ self.comm_registry = set()
248
+ for native_op, py_op in NATIVE_TO_PY_MAPPING.items():
249
+ self.comm_registry.add(native_op)
250
+ self.comm_registry.add(py_op)
251
+
252
+ self.comm_registry.add(torch.ops._dtensor.shard_dim_alltoall)
253
+ self.advanced_module_tracker = _CommModeModuleTracker()
254
+
255
+ def generate_json_dump(self, file_name="comm_mode_log.json", noise_level=3):
256
+ """
257
+ Creates json file used to build browser visual
258
+ 0. prints module-level collective counts
259
+ 1. prints dTensor operations not included in trivial operations
260
+ 2. prints operations not included in trivial operations
261
+ 3. prints all operations
262
+ """
263
+
264
+ (
265
+ include_DTensor_ops,
266
+ include_module_data,
267
+ include_ops,
268
+ include_trivial_ops,
269
+ ) = self._set_noise_parameters(noise_level)
270
+
271
+ # recursively builds json data
272
+ def add_json_information(json_dict, fqn):
273
+ json_dict["fqn"] = fqn
274
+ json_dict["module_type"] = ""
275
+ json_dict["parameters"] = []
276
+ json_dict["children"] = []
277
+ json_dict["collectives_forward"] = []
278
+ json_dict["collectives_backward"] = []
279
+ json_dict["operations_forward"] = []
280
+ json_dict["operations_backward"] = []
281
+
282
+ # adds module layer type and parameters, and their sharding
283
+ if (
284
+ "module_type" in self.advanced_module_tracker.module_helper_dict[fqn]
285
+ and include_module_data
286
+ ):
287
+ json_dict["module_type"] = (
288
+ self.advanced_module_tracker.module_helper_dict[fqn]["module_type"]
289
+ )
290
+
291
+ if "parameters" in self.advanced_module_tracker.module_helper_dict[fqn]:
292
+ for (
293
+ param_name,
294
+ placement,
295
+ ) in self.advanced_module_tracker.module_helper_dict[fqn][
296
+ "parameters"
297
+ ].items():
298
+ json_dict["parameters"].append((param_name, placement))
299
+
300
+ # adds module collective information
301
+ if fqn in self.comm_module_counts:
302
+ for collective, count in self.comm_module_counts[fqn][
303
+ "forward"
304
+ ].items():
305
+ json_dict["collectives_forward"].append((str(collective), count))
306
+
307
+ for collective, count in self.comm_module_counts[fqn][
308
+ "backward"
309
+ ].items():
310
+ json_dict["collectives_backward"].append((str(collective), count))
311
+
312
+ # adds module operation information
313
+ forward_operations = []
314
+ backward_operations = []
315
+ checkpointing_operations = []
316
+
317
+ # only get operations if the minimum operation noise level is set to true
318
+ if include_DTensor_ops:
319
+ if fqn in self.comm_module_operation_counts:
320
+ (
321
+ forward_operations,
322
+ backward_operations,
323
+ checkpointing_operations,
324
+ ) = self._get_operations_list(
325
+ self.comm_module_operation_counts[fqn]
326
+ )
327
+
328
+ # remove all operations who don't have DTensor inputs
329
+ if not include_ops:
330
+ forward_operations = [
331
+ op for op in forward_operations if len(op["input_sharding"])
332
+ ]
333
+ backward_operations = [
334
+ op for op in backward_operations if len(op["input_sharding"])
335
+ ]
336
+ checkpointing_operations = [
337
+ op for op in checkpointing_operations if len(op["input_sharding"])
338
+ ]
339
+
340
+ # remove all operations in trivial operations set
341
+ if not include_trivial_ops:
342
+ forward_operations = [
343
+ op
344
+ for op in forward_operations
345
+ if str(op["name"]) not in trivial_ops
346
+ ]
347
+ backward_operations = [
348
+ op
349
+ for op in backward_operations
350
+ if str(op["name"]) not in trivial_ops
351
+ ]
352
+ checkpointing_operations = [
353
+ op
354
+ for op in checkpointing_operations
355
+ if str(op["name"]) not in trivial_ops
356
+ ]
357
+
358
+ # converts operation information into string format for json.dumps()
359
+ forward_operations = copy.deepcopy(forward_operations)
360
+ for op in forward_operations:
361
+ op["name"] = str(op["name"])
362
+
363
+ for i in range(len(op["input_sharding"])):
364
+ op["input_sharding"][i] = str(op["input_sharding"][i])
365
+ op["input_shape"][i] = str(op["input_shape"][i])
366
+
367
+ backward_operations = copy.deepcopy(backward_operations)
368
+ for op in backward_operations:
369
+ op["name"] = str(op["name"])
370
+
371
+ for i in range(len(op["input_sharding"])):
372
+ op["input_sharding"][i] = str(op["input_sharding"][i])
373
+ op["input_shape"][i] = str(op["input_shape"][i])
374
+
375
+ checkpointing_operations = copy.deepcopy(checkpointing_operations)
376
+ for op in checkpointing_operations:
377
+ op["name"] = str(op["name"])
378
+
379
+ for i in range(len(op["input_sharding"])):
380
+ op["input_sharding"][i] = str(op["input_sharding"][i])
381
+ op["input_shape"][i] = str(op["input_shape"][i])
382
+
383
+ json_dict["operations_forward"] = forward_operations
384
+ json_dict["operations_backward"] = backward_operations
385
+ json_dict["operations_checkpointing"] = checkpointing_operations
386
+
387
+ if fqn not in self.advanced_module_tracker.parent_dict:
388
+ return json_dict
389
+
390
+ # recursively adds module's children
391
+ for ele in self.advanced_module_tracker.parent_dict[fqn]:
392
+ json_dict["children"].append(add_json_information({}, ele))
393
+
394
+ return json_dict
395
+
396
+ json_dict: dict[str, Any] = {}
397
+ add_json_information(json_dict, "Global")
398
+
399
+ # converts dictionary into json file
400
+ with open(file_name, "w") as json_file:
401
+ json.dump(json_dict, json_file, indent=4)
402
+
403
+ def generate_comm_debug_tracing_table(self, noise_level=3):
404
+ """
405
+ Generates detailed table displaying operations and collective tracing information
406
+ on a module level. Amount of information is dependent on noise_level
407
+
408
+ 0. prints module-level collective counts
409
+ 1. prints dTensor operations not included in trivial operations, module information
410
+ 2. prints operations not included in trivial operations
411
+ 3. prints all operations
412
+ """
413
+
414
+ (
415
+ include_DTensor_ops,
416
+ include_module_data,
417
+ include_ops,
418
+ include_trivial_ops,
419
+ ) = self._set_noise_parameters(noise_level)
420
+
421
+ table = ""
422
+ for fqn in self.advanced_module_tracker.module_helper_dict:
423
+ # setting up indentations for table formatting
424
+ indent = " " * (
425
+ 2 * self.advanced_module_tracker.module_helper_dict[fqn]["depth"]
426
+ )
427
+ table += f"{indent}{fqn}\n"
428
+
429
+ if include_module_data:
430
+ if (
431
+ "module_type"
432
+ in self.advanced_module_tracker.module_helper_dict[fqn]
433
+ ):
434
+ module_type = self.advanced_module_tracker.module_helper_dict[fqn][
435
+ "module_type"
436
+ ]
437
+ table += f"{indent}*module type: {module_type}\n"
438
+
439
+ if "parameters" in self.advanced_module_tracker.module_helper_dict[fqn]:
440
+ table += f"{indent}*Parameter List\n"
441
+ for (
442
+ param_name,
443
+ placement,
444
+ ) in self.advanced_module_tracker.module_helper_dict[fqn][
445
+ "parameters"
446
+ ].items():
447
+ table += f"{indent} *{param_name}: {placement}\n"
448
+
449
+ indent += " "
450
+ collective_indent = " " * (
451
+ 2 * self.advanced_module_tracker.module_helper_dict[fqn]["depth"] + 2
452
+ )
453
+ operation_indent = " " * (
454
+ 2 * self.advanced_module_tracker.module_helper_dict[fqn]["depth"] + 3
455
+ )
456
+
457
+ # separate the module's collective and operations by forward and backward
458
+ forward_collectives = {}
459
+ backward_collectives = {}
460
+ if fqn in self.comm_module_counts:
461
+ forward_collectives = self.comm_module_counts[fqn]["forward"]
462
+ backward_collectives = self.comm_module_counts[fqn]["backward"]
463
+
464
+ forward_operations = []
465
+ backward_operations = []
466
+ checkpointing_operations = []
467
+
468
+ if include_DTensor_ops:
469
+ if fqn in self.comm_module_operation_counts:
470
+ (
471
+ forward_operations,
472
+ backward_operations,
473
+ checkpointing_operations,
474
+ ) = self._get_operations_list(
475
+ self.comm_module_operation_counts[fqn]
476
+ )
477
+
478
+ def add_tracing_information(table, collectives_dict, operation_list):
479
+ """
480
+ adds tracing information for module's forward or backward
481
+ """
482
+ for collective, count in collectives_dict.items():
483
+ table += (
484
+ f"\033[1;33m{collective_indent}*{collective}: {count}\033[0m\n"
485
+ )
486
+
487
+ def add_operations(
488
+ table, operation, collective_indent, operation_indent
489
+ ):
490
+ """
491
+ adds operation information to the table
492
+ """
493
+ table += f"\033[1;33m{collective_indent}**{operation_name}\033[0m\n"
494
+
495
+ if len(operation["input_shape"]):
496
+ operation_shape = operation["input_shape"]
497
+ operation_sharding = operation["input_sharding"]
498
+ operation_device_mesh = operation["device_mesh"]
499
+
500
+ table += f"\033[1;31m{operation_indent}shape: {operation_shape}\033[0m\n"
501
+ table += f"\033[1;31m{operation_indent}sharding: {operation_sharding}\033[0m\n"
502
+ table += f"\033[1;31m{operation_indent}device mesh: {operation_device_mesh}\033[0m\n"
503
+
504
+ return table
505
+
506
+ for operation in operation_list:
507
+ operation_name = str(operation["name"])
508
+
509
+ # include all operations
510
+ if include_trivial_ops:
511
+ table = add_operations(
512
+ table, operation, collective_indent, operation_indent
513
+ )
514
+
515
+ # include all operations not in trivial operations
516
+ elif include_ops and operation_name not in trivial_ops:
517
+ table = add_operations(
518
+ table, operation, collective_indent, operation_indent
519
+ )
520
+
521
+ # only include dTensor operations not in trivial set
522
+ elif (
523
+ include_DTensor_ops
524
+ and (operation_name not in trivial_ops)
525
+ and len(operation["input_shape"])
526
+ ):
527
+ table = add_operations(
528
+ table, operation, collective_indent, operation_indent
529
+ )
530
+
531
+ return table
532
+
533
+ if len(forward_collectives) or len(forward_operations):
534
+ table += f"{indent}FORWARD PASS\n"
535
+ table = add_tracing_information(
536
+ table, forward_collectives, forward_operations
537
+ )
538
+
539
+ if len(backward_collectives) or len(backward_operations):
540
+ table += f"{indent}BACKWARD PASS\n"
541
+ table = add_tracing_information(
542
+ table, backward_collectives, backward_operations
543
+ )
544
+
545
+ if len(checkpointing_operations):
546
+ table += f"{indent}ACTIVATION CHECKPOINTING\n"
547
+ table = add_tracing_information(table, {}, checkpointing_operations)
548
+
549
+ return table
550
+
551
+ def _get_operations_list(self, module_operation_counts):
552
+ forward_operations = [
553
+ op for op in module_operation_counts["operations_list"] if not op["is_bw"]
554
+ ]
555
+ backward_operations = [
556
+ op
557
+ for op in module_operation_counts["operations_list"]
558
+ if op["is_bw"] and not op["is_activation_checkpointing"]
559
+ ]
560
+ checkpointing_operations = [
561
+ op
562
+ for op in module_operation_counts["operations_list"]
563
+ if op["is_activation_checkpointing"]
564
+ ]
565
+
566
+ return forward_operations, backward_operations, checkpointing_operations
567
+
568
+ def get_total_counts(self) -> int:
569
+ return sum(self.comm_counts.values())
570
+
571
+ def get_comm_counts(self) -> dict[Any, int]:
572
+ """Returns the communication counts as a dictionary.
573
+
574
+ Returns:
575
+ Dict[Any, int]: The communication counts as a dictionary.
576
+ """
577
+ return self.comm_counts
578
+
579
+ def get_parameter_info(self) -> dict[str, dict[str, Any]]:
580
+ return self.advanced_module_tracker.module_parameters_dict
581
+
582
+ def get_sharding_info(self) -> dict[str, dict[str, Any]]:
583
+ return self.advanced_module_tracker.sharding_dict
584
+
585
+ def __enter__(self):
586
+ self.comm_counts.clear()
587
+ self.comm_module_counts.clear()
588
+ self.comm_module_counts["Global"] = {}
589
+ self.comm_module_counts["Global"]["forward"] = defaultdict(int)
590
+ self.comm_module_counts["Global"]["backward"] = defaultdict(int)
591
+
592
+ self.comm_module_operation_counts.clear()
593
+
594
+ super().__enter__()
595
+ self.advanced_module_tracker.__enter__()
596
+ return self
597
+
598
+ # pyrefly: ignore [bad-override]
599
+ def __exit__(self, *args):
600
+ self.advanced_module_tracker.__exit__()
601
+ super().__exit__(*args)
602
+
603
+ def log_comm_debug_tracing_table_to_file(
604
+ self, file_name="comm_mode_log.txt", noise_level=3
605
+ ):
606
+ """
607
+ Alternative to console CommDebugMode output, writes to file specified by the user
608
+ """
609
+ ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
610
+ table = ansi_escape.sub("", self.generate_comm_debug_tracing_table(noise_level))
611
+
612
+ with open(file_name, "w") as log_file:
613
+ log_file.write(table)
614
+
615
+ def _set_noise_parameters(self, noise_level):
616
+ """
617
+ sets variables controlling what information displays based on noise level
618
+ """
619
+ include_DTensor_ops = False
620
+ include_module_data = False
621
+ include_ops = False
622
+ include_trivial_ops = False
623
+
624
+ if noise_level > 0:
625
+ include_DTensor_ops = True
626
+ include_module_data = True
627
+
628
+ if noise_level > 1:
629
+ include_ops = True
630
+
631
+ if noise_level > 2:
632
+ include_trivial_ops = True
633
+
634
+ return (
635
+ include_DTensor_ops,
636
+ include_module_data,
637
+ include_ops,
638
+ include_trivial_ops,
639
+ )
640
+
641
+ def __torch_dispatch__(self, func, types, args=(), kwargs=None):
642
+ # When running this mode with DTensor, ordinarily all modes will
643
+ # run **before** subclasses get a chance to run.
644
+ # Returning NotImplemented here gives us a chance to let DTensor
645
+ # run and desugar into comms ops, before CommDebugMode sees them.
646
+
647
+ # sets up operation-level collective count
648
+ if self.advanced_module_tracker.name not in self.comm_module_operation_counts:
649
+ # dictionary should hold module input and output shape, operations list and collective counter
650
+ self.comm_module_operation_counts[self.advanced_module_tracker.name] = {
651
+ "operations_list": []
652
+ }
653
+ operation_dict = {}
654
+ operation_dict["name"] = func
655
+
656
+ operation_dict["input_shape"] = []
657
+ operation_dict["input_sharding"] = []
658
+ operation_dict["device_mesh"] = ""
659
+
660
+ # tracks if the operation is part of the backward pass
661
+ operation_dict["is_bw"] = self.advanced_module_tracker.is_bw
662
+
663
+ # tracks if the operation is part of activation checkpointing
664
+ operation_dict["is_activation_checkpointing"] = (
665
+ self.advanced_module_tracker.activation_checkpointing
666
+ )
667
+
668
+ if any(t == DTensor for t in types):
669
+ for ele in args:
670
+ if isinstance(ele, DTensor):
671
+ # saves shapes and placements of all DTensor args
672
+ operation_dict["input_shape"].append(ele.shape)
673
+ operation_dict["input_sharding"].append(ele.placements)
674
+ operation_dict["device_mesh"] = str(ele.device_mesh)
675
+
676
+ self.comm_module_operation_counts[self.advanced_module_tracker.name][
677
+ "operations_list"
678
+ ].append(operation_dict)
679
+
680
+ return NotImplemented
681
+
682
+ kwargs = kwargs if kwargs else {}
683
+ out = func(*args, **kwargs)
684
+ func_packet = func._overloadpacket
685
+
686
+ # We have many tests that use CommDebugMode to verify the occurrence of
687
+ # collectives. These tests do so by querying comm_counts with legacy
688
+ # funcol ops as key. For the purpose of native funcol migration, we
689
+ # need these tests to work for both legacy and native funcol. To avoid
690
+ # the need to modify all tests to accommodate the two implementations,
691
+ # we make CommDebugMode translate native funcol ops into legacy funcol
692
+ # ops until the migration finishes.
693
+
694
+ if func_packet in self.comm_registry or func_packet in c10d_collective_ops:
695
+ if func_packet in NATIVE_TO_PY_MAPPING:
696
+ func_packet = NATIVE_TO_PY_MAPPING[func_packet]
697
+ self.comm_counts[func_packet] += 1
698
+
699
+ key = "forward"
700
+ if self.advanced_module_tracker.is_bw:
701
+ key = "backward"
702
+
703
+ # adds collective count to current module
704
+ if self.advanced_module_tracker.name not in self.comm_module_counts:
705
+ self.comm_module_counts[self.advanced_module_tracker.name] = {}
706
+ self.comm_module_counts[self.advanced_module_tracker.name][
707
+ "forward"
708
+ ] = defaultdict(int)
709
+ self.comm_module_counts[self.advanced_module_tracker.name][
710
+ "backward"
711
+ ] = defaultdict(int)
712
+ self.comm_module_counts[self.advanced_module_tracker.name][key][
713
+ func_packet
714
+ ] += 1
715
+
716
+ # adds collective count to parent modules
717
+ for par in self.advanced_module_tracker.module_parents_dict[
718
+ self.advanced_module_tracker.name
719
+ ]:
720
+ # makes sure we aren't double counting when current sub-module hasn't been removed from parents
721
+ if par != self.advanced_module_tracker.name:
722
+ if par not in self.comm_module_counts:
723
+ self.comm_module_counts[par] = {}
724
+ self.comm_module_counts[par]["forward"] = defaultdict(int)
725
+ self.comm_module_counts[par]["backward"] = defaultdict(int)
726
+ self.comm_module_counts[par][key][func_packet] += 1
727
+
728
+ # if tensor op uses fake tensors, return
729
+ if detect_fake_mode(args):
730
+ return out
731
+
732
+ # add tensor operation to module operation list
733
+ self.comm_module_operation_counts[self.advanced_module_tracker.name][
734
+ "operations_list"
735
+ ].append(operation_dict)
736
+
737
+ return out
738
+
739
+ def __repr__(self):
740
+ return f"CommDebugMode(get_total_counts()={self.get_total_counts()})"
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/debug/_op_coverage.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from operator import itemgetter
3
+
4
+ import torch
5
+ import torch.fx
6
+ import torch.nn as nn
7
+ from functorch.compile import make_boxed_func
8
+ from torch._functorch.compilers import aot_module
9
+ from torch._inductor.decomposition import select_decomp_table
10
+ from torch.distributed.tensor import DTensor
11
+
12
+
13
+ inductor_decomps = select_decomp_table()
14
+
15
+ graphs: list[torch.fx.GraphModule] = []
16
+
17
+
18
+ def fwd_bwd_compiler(fx_g, _):
19
+ graphs.append(fx_g)
20
+ return make_boxed_func(fx_g)
21
+
22
+
23
+ def get_inductor_decomp_graphs(model: nn.Module, args, kwargs):
24
+ """
25
+ Obtain forward and backward graphs of a model with inductor decompositions using tracing and aot_module.
26
+
27
+ Convenient util to get the fwd and bwd graphs of an arbitrary model
28
+ with inductor decompositions. Note that this would simply do tracing
29
+ with aot_module and don't ensure correctness. This is useful to track
30
+ the ops needed in DTensor.
31
+ """
32
+ compiled_mod = aot_module(
33
+ model, fw_compiler=fwd_bwd_compiler, decompositions=inductor_decomps
34
+ )
35
+ output = compiled_mod(*args, **kwargs)
36
+
37
+ if output.ndim != 0:
38
+ # if output is not a scalar tensor, by default sum it in order to
39
+ # run backward
40
+ output = output.sum()
41
+
42
+ output.backward()
43
+
44
+ # one fwd, one bwd graph
45
+ assert len(graphs) == 2
46
+ return graphs
47
+
48
+
49
+ def print_op_coverage_summary(model: nn.Module, args, kwargs, *, output_csv=False):
50
+ """
51
+ Util to print the operator coverage summary of a certain model with tabulute.
52
+
53
+ Must have tabulate module installed.
54
+ """
55
+ # python module required for summary
56
+ import csv
57
+
58
+ from tabulate import tabulate
59
+
60
+ fwd_graph, bwd_graph = get_inductor_decomp_graphs(model, args, kwargs)
61
+
62
+ op_counts = {}
63
+
64
+ for node in fwd_graph.graph.nodes:
65
+ if node.op == "call_function" and isinstance(
66
+ node.target, torch._ops.OpOverload
67
+ ):
68
+ if node.target not in op_counts:
69
+ op_counts[node.target] = 0
70
+
71
+ op_counts[node.target] += 1
72
+
73
+ for node in bwd_graph.graph.nodes:
74
+ if node.op == "call_function" and isinstance(
75
+ node.target, torch._ops.OpOverload
76
+ ):
77
+ if node.target not in op_counts:
78
+ op_counts[node.target] = 0
79
+
80
+ op_counts[node.target] += 1
81
+
82
+ op_infos = []
83
+
84
+ for op, count in op_counts.items():
85
+ supported = op in DTensor._op_dispatcher.sharding_propagator.op_to_rules
86
+ op_infos.append([op, str(op._schema), count, supported])
87
+
88
+ # sort the op info base on the total count index
89
+ count_idx = 2
90
+ op_infos.sort(key=itemgetter(count_idx), reverse=True)
91
+
92
+ headers = ["Operator", "Schema", "Total Count", "Supported"]
93
+ # pyrefly: ignore [bad-argument-type]
94
+ print(tabulate(op_infos, headers=headers))
95
+
96
+ if output_csv:
97
+ # Open a CSV file for writing
98
+ with open("op_summary.csv", "w", newline="") as csv_file:
99
+ # Create a CSV writer object
100
+ csv_writer = csv.writer(csv_file)
101
+
102
+ csv_writer.writerow(headers)
103
+ # Write each table row to the CSV file
104
+ for row in op_infos:
105
+ # pyrefly: ignore [bad-argument-type]
106
+ csv_writer.writerow(row)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/debug/_visualize_sharding.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import importlib.util
3
+
4
+ import numpy as np
5
+
6
+ from torch._prims_common import ShapeType
7
+ from torch.distributed.tensor._utils import _compute_local_shape_and_global_offset
8
+
9
+
10
+ __all__ = ["visualize_sharding"]
11
+
12
+ Color = tuple[float, float, float]
13
+
14
+
15
+ def _create_table(
16
+ shards: list[tuple[tuple[int, int], tuple[int, int], int]], device_kind: str = ""
17
+ ):
18
+ """
19
+ Creates a tabulate table given row and column ranges with device name
20
+ """
21
+ from tabulate import tabulate
22
+
23
+ # Extract unique row and column ranges
24
+ row_ranges = sorted({block[0] for block in shards})
25
+ col_ranges = sorted({block[1] for block in shards})
26
+
27
+ # Create a matrix initialized with empty strings
28
+ matrix = [["" for _ in col_ranges] for _ in row_ranges]
29
+
30
+ # Fill the matrix with values
31
+ for block in shards:
32
+ row_index = row_ranges.index(block[0])
33
+ col_index = col_ranges.index(block[1])
34
+ if matrix[row_index][col_index] == "":
35
+ matrix[row_index][col_index] = device_kind + ":" + str(block[2])
36
+ else:
37
+ matrix[row_index][col_index] += "," + str(block[2])
38
+
39
+ # Prepare headers
40
+ row_headers = [f"Row {r[0]}-{r[1]}" for r in row_ranges]
41
+ col_headers = [f"Col {c[0]}-{c[1]}" for c in col_ranges]
42
+
43
+ return tabulate(matrix, headers=col_headers, showindex=row_headers)
44
+
45
+
46
+ def make_color_iter(color_map, num_rows, num_cols):
47
+ num_colors = num_rows * num_cols
48
+ for idx in range(num_colors):
49
+ yield color_map(idx)
50
+
51
+
52
+ def _canonicalize_color(color: Color) -> str:
53
+ if isinstance(color, str):
54
+ return color
55
+ r, g, b = (int(a * 255) for a in color)
56
+ return f"#{r:02X}{g:02X}{b:02X}"
57
+
58
+
59
+ def _get_text_color(color: str) -> str:
60
+ r, g, b = map(lambda x: int(x, 16), (color[1:3], color[3:5], color[5:7])) # noqa: C417
61
+ if (r * 0.299 + g * 0.587 + b * 0.114) > 186:
62
+ return "#000000"
63
+ return "#ffffff"
64
+
65
+
66
+ def _create_rich_table(
67
+ shape: ShapeType,
68
+ shards: list[tuple[tuple[int, int], tuple[int, int], int]],
69
+ device_kind: str = "",
70
+ scale: float = 1.0,
71
+ min_width: int = 9,
72
+ max_width: int = 80,
73
+ ):
74
+ import matplotlib
75
+ import rich.align
76
+ import rich.box
77
+ import rich.console
78
+ import rich.padding
79
+ import rich.style
80
+ import rich.table
81
+
82
+ dtensor_height = shape[0]
83
+ dtensor_width = shape[1] if len(shape) == 2 else 1
84
+
85
+ row_ranges = sorted({s[0] for s in shards})
86
+ col_ranges = sorted({s[1] for s in shards})
87
+ num_rows, num_cols = len(row_ranges), len(col_ranges)
88
+
89
+ console = rich.console.Console(width=max_width)
90
+ use_color = console.color_system
91
+ color_iter = make_color_iter(matplotlib.colormaps["tab20b"], num_rows, num_cols)
92
+
93
+ base_height = int(10 * scale)
94
+ aspect_ratio = (shape[1] if len(shape) == 2 else 1) / shape[0]
95
+ base_width = int(base_height * aspect_ratio)
96
+ height_to_width_ratio = 2.5
97
+
98
+ table = rich.table.Table(
99
+ show_header=False,
100
+ show_lines=not use_color,
101
+ padding=0,
102
+ highlight=not use_color,
103
+ pad_edge=False,
104
+ box=rich.box.SQUARE if not use_color else None,
105
+ )
106
+ for row in range(num_rows):
107
+ table_row = []
108
+ for col in range(num_cols):
109
+ entry = (
110
+ device_kind
111
+ + ":"
112
+ + ",".join(
113
+ [
114
+ str(device_id)
115
+ for row_range, col_range, device_id in shards
116
+ if row_range == row_ranges[row] and col_range == col_ranges[col]
117
+ ]
118
+ )
119
+ )
120
+ width = (col_ranges[col][1] - col_ranges[col][0]) / dtensor_width
121
+ width = int(width * base_width * height_to_width_ratio)
122
+ height = (row_ranges[row][1] - row_ranges[row][0]) / dtensor_height
123
+ height = int(height * base_height)
124
+ left_padding, remainder = divmod(width - len(entry) - 2, 2)
125
+ right_padding = left_padding + remainder
126
+ top_padding, remainder = divmod(height - 2, 2)
127
+ bottom_padding = top_padding + remainder
128
+ if use_color:
129
+ color = _canonicalize_color(next(color_iter)[:3])
130
+ text_color = _get_text_color(color)
131
+ top_padding += 1
132
+ bottom_padding += 1
133
+ left_padding += 1
134
+ right_padding += 1
135
+ else:
136
+ color = None
137
+ text_color = None
138
+ padding = (
139
+ max(top_padding, 0),
140
+ max(right_padding, 0),
141
+ max(bottom_padding, 0),
142
+ max(left_padding, 0),
143
+ )
144
+ table_row.append(
145
+ rich.padding.Padding(
146
+ rich.align.Align(entry, "center", vertical="middle"),
147
+ padding,
148
+ style=rich.style.Style(bgcolor=color, color=text_color),
149
+ )
150
+ )
151
+ table.add_row(*table_row)
152
+ console.print(table, end="\n\n")
153
+
154
+
155
+ def visualize_sharding(dtensor, header="", use_rich: bool = False):
156
+ """
157
+ Visualizes sharding in the terminal for :class:`DTensor` that are 1D or 2D.
158
+
159
+ .. note:: This requires the ``tabulate`` package, or ``rich`` and ``matplotlib``.
160
+ No sharding info will be printed for empty tensors
161
+ """
162
+ if dtensor.numel() == 0: # Do not print empty dtensors.
163
+ return
164
+
165
+ if len(dtensor.shape) >= 3:
166
+ raise RuntimeError("visualize sharding supports only 1D or 2D DTensor")
167
+
168
+ if dtensor.device_mesh.get_coordinate() is None: # current rank is not in the mesh
169
+ return
170
+
171
+ # Only display the visualization once for each DTensor, on the rank whose
172
+ # coordinate is 0 on all dimensions. For example, if the mesh is a full mesh,
173
+ # we will only print on rank 0.
174
+ local_rank_zero_on_all_dim = all(
175
+ dtensor.device_mesh.get_local_rank(mesh_dim=dim) == 0
176
+ for dim in range(dtensor.device_mesh.ndim)
177
+ )
178
+ if not local_rank_zero_on_all_dim:
179
+ return
180
+
181
+ device_coords = {
182
+ int(device_index.item()): list(coord)
183
+ for coord, device_index in np.ndenumerate(
184
+ np.array(dtensor.device_mesh.mesh.tolist())
185
+ )
186
+ }
187
+
188
+ device_shard_shape_and_offsets = {
189
+ device_index: _compute_local_shape_and_global_offset(
190
+ dtensor.shape,
191
+ dtensor.device_mesh.shape,
192
+ device_coords[device_index],
193
+ dtensor.placements,
194
+ )
195
+ for device_index in device_coords
196
+ }
197
+
198
+ # Extend shards in a 1D tensor to 2D
199
+ device_shard_shape_and_offsets = {
200
+ device_index: (
201
+ shape if len(shape) == 2 else (shape[0], 1),
202
+ offset if len(offset) == 2 else (offset[0], 0),
203
+ )
204
+ for device_index, (shape, offset) in device_shard_shape_and_offsets.items()
205
+ }
206
+
207
+ shards = [
208
+ (
209
+ (offset[0], offset[0] + shape[0] - 1),
210
+ (offset[1], offset[1] + shape[1] - 1),
211
+ device_index,
212
+ )
213
+ for device_index, (shape, offset) in device_shard_shape_and_offsets.items()
214
+ ]
215
+
216
+ if (
217
+ importlib.util.find_spec("rich")
218
+ and importlib.util.find_spec("matplotlib")
219
+ and use_rich
220
+ ):
221
+ _create_rich_table(
222
+ dtensor.shape, shards, device_kind=dtensor.device_mesh.device_type
223
+ )
224
+ elif importlib.util.find_spec("tabulate"):
225
+ print(_create_table(shards, device_kind=dtensor.device_mesh.device_type))
226
+ else:
227
+ raise ValueError("`visualize_sharding` requires either `rich` or `tabulate`.")
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/device_mesh.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from torch.distributed.device_mesh import ( # noqa: F401
2
+ _get_device_handle,
3
+ _mesh_resources,
4
+ DeviceMesh,
5
+ init_device_mesh,
6
+ )
7
+
8
+
9
+ __all__ = ["init_device_mesh", "DeviceMesh"]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/__init__.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ from collections.abc import Iterator
3
+ from contextlib import contextmanager
4
+
5
+ from torch.distributed.tensor._api import DTensor
6
+ from torch.distributed.tensor.experimental._attention import context_parallel
7
+ from torch.distributed.tensor.experimental._func_map import local_map
8
+ from torch.distributed.tensor.experimental._register_sharding import register_sharding
9
+
10
+
11
+ __all__ = ["context_parallel", "implicit_replication", "local_map", "register_sharding"]
12
+
13
+
14
+ @contextmanager
15
+ def implicit_replication() -> Iterator[None]:
16
+ """
17
+ This context manager allows :class:`DTensor` to implicitly treat all non-DTensors (``torch.Tensor``)
18
+ in the program be replicate :class:`DTensor` s during the operator computation.
19
+
20
+ .. warning:: This might possible lead to incorrect results if ``torch.Tensor`` s are not replicated
21
+ in practice, please use it at your discretion.
22
+ """
23
+ try:
24
+ DTensor._op_dispatcher._allow_implicit_replication = True
25
+ yield
26
+ finally:
27
+ DTensor._op_dispatcher._allow_implicit_replication = False
28
+
29
+
30
+ # Set namespace for exposed private names
31
+ context_parallel.__module__ = "torch.distributed.tensor.experimental"
32
+ implicit_replication.__module__ = "torch.distributed.tensor.experimental"
33
+ local_map.__module__ = "torch.distributed.tensor.experimental"
34
+ register_sharding.__module__ = "torch.distributed.tensor.experimental"
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_attention.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ # Backward compatibility stub - this module has been moved to _context_parallel/_attention.py
3
+
4
+ from ._context_parallel._attention import (
5
+ _CausalBehavior,
6
+ _context_parallel_shard,
7
+ _ContextParallel,
8
+ _cp_options,
9
+ _disable_context_parallel_dispatcher,
10
+ _enable_context_parallel_dispatcher,
11
+ _is_causal_behavior,
12
+ _RotateMethod,
13
+ _templated_ring_attention,
14
+ context_parallel,
15
+ context_parallel_unshard,
16
+ set_rotate_method,
17
+ )
18
+ from ._context_parallel._load_balancer import (
19
+ _HeadTailLoadBalancer,
20
+ _LoadBalancer,
21
+ _PerDocumentHeadTailLoadBalancer,
22
+ _PTRRLoadBalancer,
23
+ )
24
+
25
+
26
+ # TODO(fegin): add deprecation message once the final interfaces are concluded.
27
+ __all__ = [
28
+ "_CausalBehavior",
29
+ "_context_parallel_shard",
30
+ "_ContextParallel",
31
+ "_cp_options",
32
+ "_disable_context_parallel_dispatcher",
33
+ "_enable_context_parallel_dispatcher",
34
+ "_is_causal_behavior",
35
+ "_RotateMethod",
36
+ "_templated_ring_attention",
37
+ "context_parallel",
38
+ "context_parallel_unshard",
39
+ "set_rotate_method",
40
+ "_HeadTailLoadBalancer",
41
+ "_LoadBalancer",
42
+ "_PerDocumentHeadTailLoadBalancer",
43
+ "_PTRRLoadBalancer",
44
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_context_parallel/__init__.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ # Context Parallel components
3
+
4
+ from ._attention import (
5
+ _CausalBehavior,
6
+ _context_parallel_shard,
7
+ _ContextParallel,
8
+ _cp_options,
9
+ _disable_context_parallel_dispatcher,
10
+ _enable_context_parallel_dispatcher,
11
+ _is_causal_behavior,
12
+ _RotateMethod,
13
+ context_parallel,
14
+ context_parallel_unshard,
15
+ set_rotate_method,
16
+ )
17
+ from ._cp_custom_ops import flex_cp_allgather
18
+ from ._load_balancer import (
19
+ _HeadTailLoadBalancer,
20
+ _LoadBalancer,
21
+ _PerDocumentHeadTailLoadBalancer,
22
+ _PTRRLoadBalancer,
23
+ )
24
+
25
+
26
+ __all__ = [
27
+ # From _attention
28
+ "_CausalBehavior",
29
+ "_context_parallel_shard",
30
+ "_ContextParallel",
31
+ "_cp_options",
32
+ "_disable_context_parallel_dispatcher",
33
+ "_enable_context_parallel_dispatcher",
34
+ "_is_causal_behavior",
35
+ "_RotateMethod",
36
+ "context_parallel",
37
+ "context_parallel_unshard",
38
+ "set_rotate_method",
39
+ # From _cp_custom_ops
40
+ "flex_cp_allgather",
41
+ # From _load_balancer
42
+ "_HeadTailLoadBalancer",
43
+ "_LoadBalancer",
44
+ "_PerDocumentHeadTailLoadBalancer",
45
+ "_PTRRLoadBalancer",
46
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_context_parallel/_attention.py ADDED
@@ -0,0 +1,1675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import itertools
3
+ import logging
4
+ import types
5
+ from abc import ABC, abstractmethod
6
+ from collections.abc import Callable, Generator, Mapping, Sequence
7
+ from dataclasses import dataclass
8
+ from enum import auto, Enum
9
+ from functools import partial
10
+ from typing import Any, cast, Protocol, TypeAlias
11
+
12
+ import torch
13
+ import torch.distributed as dist
14
+ import torch.distributed._functional_collectives as ft_c
15
+ import torch.distributed.distributed_c10d as c10d
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from torch.distributed.device_mesh import DeviceMesh
19
+ from torch.distributed.tensor import distribute_tensor, DTensor, Shard
20
+ from torch.distributed.tensor.parallel import ParallelStyle
21
+ from torch.nn.attention.flex_attention import (
22
+ _mask_mod_signature,
23
+ BlockMask,
24
+ create_block_mask,
25
+ )
26
+ from torch.utils._pytree import tree_flatten, tree_unflatten
27
+
28
+ from ._cp_custom_ops import flex_cp_allgather
29
+ from ._load_balancer import _create_default_load_balancer, _LoadBalancer
30
+
31
+
32
+ __all__ = [
33
+ "_CausalBehavior",
34
+ "_context_parallel_shard",
35
+ "_ContextParallel",
36
+ "_cp_options",
37
+ "_disable_context_parallel_dispatcher",
38
+ "_enable_context_parallel_dispatcher",
39
+ "_is_causal_behavior",
40
+ "_RotateMethod",
41
+ "context_parallel",
42
+ "context_parallel_unshard",
43
+ "set_rotate_method",
44
+ ]
45
+
46
+
47
+ class _CausalBehavior(Enum):
48
+ SKIP = None
49
+ NOT_IS_CAUSAL = False
50
+ IS_CAUSAL = True
51
+
52
+
53
+ class _RotateMethod(Enum):
54
+ ALL_TO_ALL = auto()
55
+ ALL_GATHER = auto()
56
+
57
+
58
+ aten = torch.ops.aten
59
+ logger = logging.getLogger(__name__)
60
+
61
+
62
+ class _DispatchMode(Enum):
63
+ MONKEY_PATCH = auto()
64
+ MODULE_WRAPPER = auto()
65
+
66
+
67
+ _dispatch_mode: _DispatchMode = _DispatchMode.MONKEY_PATCH
68
+
69
+
70
+ @dataclass
71
+ class _ContextParallelOptions:
72
+ # Whether to upcast parameters and gradients to float32 to avoid accumulation
73
+ # errors. It is likely this is always True, but we currently keep this variable
74
+ # for experimental purposes.
75
+ convert_to_f32: bool = True
76
+ enable_load_balance: bool = True
77
+ rotate_method: _RotateMethod = _RotateMethod.ALL_GATHER
78
+
79
+
80
+ _cp_options = _ContextParallelOptions()
81
+
82
+
83
+ def _is_causal_behavior(
84
+ rank: int, world_size: int, i: int, is_causal: bool
85
+ ) -> _CausalBehavior:
86
+ """
87
+ Calculate is_causal behavior for each KV block. The attention can either be
88
+ calculated in full, not at all or with the causal mask applied.
89
+ """
90
+ if not is_causal:
91
+ return _CausalBehavior.NOT_IS_CAUSAL
92
+
93
+ if i == 0:
94
+ return _CausalBehavior.IS_CAUSAL
95
+
96
+ source_rank = (rank - i) % world_size
97
+ if source_rank < rank or _cp_options.enable_load_balance:
98
+ return _CausalBehavior.NOT_IS_CAUSAL
99
+ else:
100
+ return _CausalBehavior.SKIP
101
+
102
+
103
+ def _maybe_wait(tensor: torch.Tensor) -> torch.Tensor:
104
+ """
105
+ When tracing the code, the result tensor is not an AsyncCollectiveTensor,
106
+ so we cannot call ``wait()``.
107
+ """
108
+ if isinstance(tensor, ft_c.AsyncCollectiveTensor):
109
+ return tensor.wait()
110
+ return tensor
111
+
112
+
113
+ def _partial_update(
114
+ original: torch.Tensor,
115
+ new: torch.Tensor,
116
+ dim: int,
117
+ n_chunks: int,
118
+ idx: int,
119
+ add: bool,
120
+ ) -> torch.Tensor:
121
+ """
122
+ This API partially updates a chunk of ``original`` tensor. The ``original``
123
+ tensor will be first chunked along ``dim`` dimension, then the ``idx`` chunk
124
+ will be updated with ``new``. If ``add`` is True, the chunk will be added
125
+ with ``new``, otherwise the chunk will be replaced by ``new``.
126
+
127
+ The result is a tensor that is the same size as ``original``.
128
+ """
129
+ chunks = list(original.chunk(n_chunks, dim=dim))
130
+ assert chunks[idx].shape == new.shape, (original.shape, new.shape, idx)
131
+ if add:
132
+ chunks[idx] += new
133
+ else:
134
+ chunks[idx] = new
135
+ return torch.cat(chunks, dim=dim)
136
+
137
+
138
+ class _SDPAMerger:
139
+ """A class to help merge the local SDPA result."""
140
+
141
+ def __init__(self, convert_to_f32: bool, seq_dim: int):
142
+ self._seq_dim = seq_dim
143
+ self._out: torch.Tensor | None = None
144
+ self._lse: torch.Tensor | None = None
145
+ self._should_lse_squeeze = False
146
+ self._convert_to_f32 = convert_to_f32
147
+ self._out_dtype = torch.float32
148
+ self._lse_dtype = torch.float32
149
+
150
+ def _merge_one(
151
+ self, block_out: torch.Tensor, block_lse: torch.Tensor, partial: bool
152
+ ) -> None:
153
+ # The cuDNN backend preserves the last dimension for LSE.
154
+ # Apply unsqueeze only if the input does not already have
155
+ # the required dimensionality.
156
+ if len(block_lse.shape) < len(block_out.shape):
157
+ block_lse = block_lse.unsqueeze(dim=-1)
158
+ self._should_lse_squeeze = True
159
+ assert len(block_lse.shape) == len(block_out.shape)
160
+
161
+ if self._lse is None:
162
+ self._lse = block_lse
163
+ self._out = block_out
164
+ else:
165
+ ROUND_ROBIN_CYCLE = 2
166
+ assert self._lse is not None
167
+ assert self._out is not None
168
+ lse = (
169
+ self._lse.chunk(ROUND_ROBIN_CYCLE, dim=self._seq_dim)[1]
170
+ if partial
171
+ else self._lse
172
+ )
173
+ out = (
174
+ self._out.chunk(ROUND_ROBIN_CYCLE, dim=self._seq_dim)[1]
175
+ if partial
176
+ else self._out
177
+ )
178
+
179
+ # The algorithm from
180
+ # github.com/zhuzilin/ring-flash-attention/pull/34#issuecomment-2076126795
181
+ # gives a relatively stable result.
182
+ out = out - F.sigmoid(block_lse - lse) * (out - block_out)
183
+ lse = lse - F.logsigmoid(lse - block_lse)
184
+ if partial:
185
+ self._lse = _partial_update(
186
+ self._lse,
187
+ lse,
188
+ dim=self._seq_dim,
189
+ n_chunks=ROUND_ROBIN_CYCLE,
190
+ idx=1,
191
+ add=False,
192
+ )
193
+ self._out = _partial_update(
194
+ self._out,
195
+ out,
196
+ dim=self._seq_dim,
197
+ n_chunks=ROUND_ROBIN_CYCLE,
198
+ idx=1,
199
+ add=False,
200
+ )
201
+ else:
202
+ self._lse = lse
203
+ self._out = out
204
+
205
+ def step(self, out: torch.Tensor, lse: torch.Tensor, partial: bool) -> None:
206
+ self._out_dtype = out.dtype
207
+ self._lse_dtype = lse.dtype
208
+
209
+ if self._convert_to_f32:
210
+ out = out.to(torch.float32)
211
+ lse = lse.to(torch.float32)
212
+
213
+ self._merge_one(out, lse, partial)
214
+
215
+ def results(self) -> tuple[torch.Tensor, torch.Tensor]:
216
+ assert self._out is not None
217
+ assert self._lse is not None
218
+ out = self._out.to(self._out_dtype)
219
+ if self._should_lse_squeeze:
220
+ lse = self._lse.squeeze(-1).to(self._lse_dtype)
221
+ else:
222
+ lse = self._lse.to(self._lse_dtype)
223
+ return out, lse
224
+
225
+
226
+ class _AttentionOp(Protocol):
227
+ def __call__(
228
+ self,
229
+ query: torch.Tensor,
230
+ key: torch.Tensor,
231
+ value: torch.Tensor,
232
+ **kwargs: object,
233
+ ) -> tuple[torch.Tensor, ...]: ...
234
+
235
+
236
+ class _RingRotater(ABC):
237
+ @abstractmethod
238
+ def __init__(self, pg: dist.ProcessGroup, seq_dim: int) -> None: ...
239
+
240
+ @abstractmethod
241
+ def exchange_buffers(self, curr_buffer: torch.Tensor) -> None: ...
242
+
243
+ @abstractmethod
244
+ def next_buffer(self) -> torch.Tensor: ...
245
+
246
+
247
+ class _AllToAllRotater(_RingRotater):
248
+ """Use all_to_all to send the kv to the next rank."""
249
+
250
+ def __init__(self, pg: dist.ProcessGroup, seq_dim: int) -> None:
251
+ self._pg = pg
252
+ self._seq_dim = seq_dim
253
+ self._buffer: torch.Tensor | None = None
254
+
255
+ def exchange_buffers(self, curr_buffer: torch.Tensor) -> None:
256
+ curr_buffer = curr_buffer.contiguous()
257
+ size = dist.get_world_size(self._pg)
258
+ dsts = list(range(1, size)) + [0]
259
+ self._buffer = ft_c.permute_tensor(curr_buffer, dsts, self._pg)
260
+
261
+ def next_buffer(self) -> torch.Tensor:
262
+ assert self._buffer is not None
263
+ return _maybe_wait(self._buffer)
264
+
265
+
266
+ class _AllGatherRotater(_RingRotater):
267
+ """
268
+ Allgather the kv and return only the required kv.
269
+ Only one communication will be done.
270
+ """
271
+
272
+ def __init__(self, pg: dist.ProcessGroup, seq_dim: int) -> None:
273
+ self._pg = pg
274
+ self._seq_dim = seq_dim
275
+ self._aggregated_buffer: torch.Tensor | None = None
276
+ self._idx = 0
277
+
278
+ def exchange_buffers(self, curr_buffer: torch.Tensor) -> None:
279
+ # We only need to perform allgather once.
280
+ self._idx += 1
281
+ if self._aggregated_buffer is None:
282
+ self._aggregated_buffer = ft_c.all_gather_tensor(
283
+ curr_buffer.contiguous(), gather_dim=0, group=self._pg
284
+ )
285
+
286
+ def next_buffer(self) -> torch.Tensor:
287
+ rank = dist.get_rank(self._pg)
288
+ idx = rank - self._idx
289
+
290
+ assert self._aggregated_buffer is not None
291
+ self._aggregated_buffer = _maybe_wait(self._aggregated_buffer)
292
+ return self._aggregated_buffer.chunk(dist.get_world_size(self._pg))[idx]
293
+
294
+
295
+ def _create_rotater(
296
+ pg: dist.ProcessGroup, seq_dim: int, method: _RotateMethod | None = None
297
+ ) -> _RingRotater:
298
+ if method is None:
299
+ method = _cp_options.rotate_method
300
+
301
+ if method == _RotateMethod.ALL_TO_ALL:
302
+ return _AllToAllRotater(pg, seq_dim)
303
+ elif method == _RotateMethod.ALL_GATHER:
304
+ return _AllGatherRotater(pg, seq_dim)
305
+ else:
306
+ raise NotImplementedError(f"Unknown method {method}")
307
+
308
+
309
+ def _templated_ring_attention(
310
+ group: dist.ProcessGroup,
311
+ seq_dim: int,
312
+ op: _AttentionOp,
313
+ query: torch.Tensor,
314
+ key: torch.Tensor,
315
+ value: torch.Tensor,
316
+ is_causal: bool = False,
317
+ **kwargs: object,
318
+ ) -> tuple[torch.Tensor, ...]:
319
+ """
320
+ A generalized ring attention implementation that can support multiple attention ops.
321
+
322
+ Note [Context parallelism load balance algorithm for causal masking]
323
+ =====================
324
+ This explanation uses an example to illustrate the CP algorithm with causal
325
+ masking.
326
+
327
+ Consider a scenario where the sequence length of q, k, and v is 4 (e.g.,
328
+ q = (q0, q1, q2, q3)), and there are two ranks. For simplicity, we will discuss
329
+ only q and k, as v follows the same pattern as k.
330
+
331
+ The diagram below represents a complete QK^T operation without parallelism.
332
+ The `****` entries indicate that the result is not required due to causal
333
+ masking (e.g., q0k1 is marked as `****`).
334
+
335
+ +----+------------------------+
336
+ | | k0 k1 k2 k3 |
337
+ +----+------------------------+
338
+ | q0 | q0k0, ****, ****, **** |
339
+ | q1 | q1k0, q1k1, ****, **** |
340
+ | q2 | q2k0, q2k1, q2k2, **** |
341
+ | q3 | q3k0, q3k1, q3k2, q3k3 |
342
+ +----+------------------------+
343
+
344
+ ### No Load Balance:
345
+
346
+ In this scenario, each rank owns a local chunk of q, k, and v, with each chunk
347
+ containing two elements. Rank0 is responsible for managing (q0, q1) and (k0, k1),
348
+ while rank1 manages (q2, q3) and (k2, k3).
349
+
350
+ First Iteration: Both rank0 and rank1 perform SDPA with their local qkv pairs.
351
+ Causal masking is enabled as some results are not required (e.g., q0k1).
352
+
353
+ Second Iteration: Local queries remain the same, but local kv pairs are exchanged.
354
+ Rank0 now has (q0, q1) and (k2, k3); rank1 has (q2, q3) and (k0, k1). Rank0 performs
355
+ no computation, while rank1 computes locally without causal masking since all results
356
+ (q2k0, q2k1, q3k0, q3k1) are needed.
357
+
358
+ ### Round-robin Load Balance:
359
+
360
+ In this setup, each rank owns two local chunks of q, k, and v, with each chunk
361
+ containing one element. Rank0 manages (q0, q3) and (k0, k3); Rank1 manages (q1, q2)
362
+ and (k1, k2). Although the local chunks are not consecutive, they are concatenated to
363
+ enable SDPA to be performed in a single call for each step. Consequently, the chunk()
364
+ function may be required to prepare the correct q, k, and v configurations.
365
+
366
+ First Iteration: Both ranks perform SDPA with their local qkv pairs, similar to the
367
+ no-load-balance case. This iteration corresponds to the `if` of the
368
+ (`if, `elif`, `else`) in the implementation.
369
+
370
+ Second Iteration: Rank0 now has (q0, q3) and (k1, k2); rank1 has (q1, q2) and
371
+ (k0, k3). For rank0, no computation is needed for q0. However, computations for
372
+ q3k1 and q3k2 are required, so only q3 is used for SDPA. This corresponds to the
373
+ `else` of the (`if`, `elif`, `else`) in the implementation.
374
+ For rank1, k3 is not needed for q1 and q2, so only k0 is used for SDPA. This
375
+ corresponds to the `elif` of (`if`, `elif`, `else`) in the implementation.
376
+
377
+ Parameters
378
+ ----------
379
+ op:
380
+ The attention op to use
381
+ *args:
382
+ additional args are passed to the op
383
+ **kwargs:
384
+ additional kwargs are passed to the op
385
+
386
+ Returns
387
+ -------
388
+ out:
389
+ The merged attention output
390
+ softmax_lse:
391
+ The logsumexp of the merged attention output
392
+ """
393
+ if is_causal and (query.size(2) != key.size(2)):
394
+ raise NotImplementedError(
395
+ "is_causal requires the same query and context sequence lengths"
396
+ )
397
+ if not is_causal and _cp_options.enable_load_balance:
398
+ raise RuntimeError("Load balancing requires `is_causal=True`.")
399
+
400
+ assert isinstance(group, dist.ProcessGroup), (
401
+ "process group must be single dimension"
402
+ )
403
+ rank = dist.get_rank(group)
404
+ size = dist.get_world_size(group)
405
+
406
+ next_kv = None
407
+
408
+ # Without making key and value contiguous(), the loss curve is bad.
409
+ # TODO(fegin): figure out why this is a requirement since SDPA does not have
410
+ # this requirement.
411
+ key = key.contiguous()
412
+ value = value.contiguous()
413
+
414
+ sdpa_merger = _SDPAMerger(_cp_options.convert_to_f32, seq_dim=seq_dim)
415
+
416
+ rest: list[Any]
417
+ out: torch.Tensor
418
+ logsumexp: torch.Tensor
419
+
420
+ rotater = _create_rotater(group, 2)
421
+
422
+ for i in range(size):
423
+ if i > 0:
424
+ # Wait for the kv from the (cp_rank - 1) rank.
425
+ next_kv = rotater.next_buffer()
426
+ key = next_kv[: key.numel()].reshape(key.shape)
427
+ value = next_kv[key.numel() :].reshape(value.shape)
428
+
429
+ if i < (size - 1):
430
+ # Send the k, v to the next rank
431
+ next_kv = torch.cat([key.flatten(), value.flatten()])
432
+ next_kv = rotater.exchange_buffers(next_kv)
433
+
434
+ is_causal_behavior = _is_causal_behavior(
435
+ rank=rank, world_size=size, i=i, is_causal=is_causal
436
+ )
437
+
438
+ # For a detailed understanding of the load balancing algorithm, see
439
+ # Note [Context parallelism load balance algorithm for causal masking]
440
+ if is_causal_behavior == _CausalBehavior.SKIP:
441
+ # If i > rank and load balancing is not turned on.
442
+ continue
443
+
444
+ if i == 0 or (not _cp_options.enable_load_balance or not is_causal):
445
+ # When local balance is enabled, we still need to do SDPA with
446
+ # the both local chunks of q, k, v for the first iteration.
447
+ q, k, v, partial = (query, key, value, False)
448
+ elif i <= rank:
449
+ # Round-robin load balancing case, and i <= rank.
450
+ # We need to do SDPA with only the first local chunk of k, v.
451
+ # Note that q, k, v each contains two local chunks.
452
+ ROUND_ROBIN_CYCLE = 2
453
+ q, k, v, partial = (
454
+ query,
455
+ key.chunk(ROUND_ROBIN_CYCLE, dim=2)[0],
456
+ value.chunk(ROUND_ROBIN_CYCLE, dim=2)[0],
457
+ False,
458
+ )
459
+ else:
460
+ # Round-robin load balancing case, and i > rank.
461
+ # We need to do SDPA with only the second half of q, and update
462
+ # only the second part of logsumexp. So partial is True.
463
+ # Note that q, k, v each contains two chunks.
464
+ q, k, v, partial = query.chunk(2, dim=2)[1], key, value, True
465
+
466
+ # See https://github.com/pytorch/pytorch/blob/release/2.4/aten/src/ATen/native/native_functions.yaml#L14695
467
+ # for the SDPA kernel definitions.
468
+ out, logsumexp, *rest = op(
469
+ q,
470
+ k,
471
+ v,
472
+ is_causal=is_causal_behavior.value,
473
+ **kwargs,
474
+ )
475
+ sdpa_merger.step(out, logsumexp, partial)
476
+
477
+ # pyrefly: ignore [unbound-name]
478
+ return *sdpa_merger.results(), *rest
479
+
480
+
481
+ def _templated_ring_attention_backward(
482
+ group: dist.ProcessGroup,
483
+ seq_dim: int,
484
+ op: _AttentionOp,
485
+ grad_out: torch.Tensor,
486
+ grad_out_name: str,
487
+ query: torch.Tensor,
488
+ key: torch.Tensor,
489
+ value: torch.Tensor,
490
+ out: torch.Tensor,
491
+ logsumexp: torch.Tensor,
492
+ is_causal: bool,
493
+ **kwargs: Any,
494
+ ) -> tuple[torch.Tensor, ...]:
495
+ """This API implements the backward pass of the ring attention."""
496
+ if not is_causal and _cp_options.enable_load_balance:
497
+ raise RuntimeError("Load balancing requires `is_causal=True`.")
498
+ rank = dist.get_rank(group)
499
+ size = dist.get_world_size(group)
500
+ next_kv = None
501
+ next_grad_kv = None
502
+ rest: list[Any]
503
+ grad_query_, grad_key_, grad_value_ = None, None, None
504
+
505
+ accum_dtype = torch.float32 if _cp_options.convert_to_f32 else query.dtype
506
+ grad_query = torch.zeros_like(query, dtype=accum_dtype)
507
+ grad_key = torch.zeros_like(key, dtype=accum_dtype)
508
+ grad_value = torch.zeros_like(value, dtype=accum_dtype)
509
+
510
+ key = key.contiguous()
511
+ value = value.contiguous()
512
+ kv_rotater = _create_rotater(group, 2)
513
+ dkv_rotater = _create_rotater(group, 2, method=_RotateMethod.ALL_TO_ALL)
514
+ for i in range(size):
515
+ if i > 0:
516
+ # Wait for the kv from the (cp_rank - 1) rank.
517
+ buffer = kv_rotater.next_buffer()
518
+ pointer = 0
519
+ key = buffer[pointer : pointer + key.numel()].reshape(key.shape)
520
+ pointer += key.numel()
521
+ value = buffer[pointer : pointer + value.numel()].reshape(value.shape)
522
+ pointer += value.numel()
523
+
524
+ if i != size - 1:
525
+ # Send the kv to the next rank.
526
+ next_kv = torch.cat([key.flatten(), value.flatten()])
527
+ kv_rotater.exchange_buffers(next_kv)
528
+
529
+ is_causal_behavior = _is_causal_behavior(
530
+ rank=rank, world_size=size, i=i, is_causal=is_causal
531
+ )
532
+
533
+ if is_causal_behavior != _CausalBehavior.SKIP:
534
+ if i == 0 or (not _cp_options.enable_load_balance or not is_causal):
535
+ # We need to do SDPA with the full local q, k, v.
536
+ q, k, v, out_, dout, lse = (query, key, value, out, grad_out, logsumexp)
537
+ elif i <= rank:
538
+ # Round-robin load balancing case, and i <= rank.
539
+ # We need to do SDPA with only the first half of k, v.
540
+ # Note that q, k, v each contains two chunks.
541
+ q, k, v, out_, dout, lse = (
542
+ query,
543
+ key.chunk(2, dim=seq_dim)[0],
544
+ value.chunk(2, dim=seq_dim)[0],
545
+ out,
546
+ grad_out,
547
+ logsumexp,
548
+ )
549
+ else:
550
+ # Round-robin load balancing case, and i > rank.
551
+ # We need to do SDPA with only the second half of q.
552
+ # Note that q, k, v each contains two chunks.
553
+ q, k, v, out_, dout, lse = (
554
+ query.chunk(2, dim=seq_dim)[1],
555
+ key,
556
+ value,
557
+ out.chunk(2, dim=seq_dim)[1],
558
+ grad_out.chunk(2, dim=seq_dim)[1],
559
+ # Need to make logsumexp contiguous, otherwise there will
560
+ # be numerical error.
561
+ logsumexp.chunk(2, dim=seq_dim)[1].contiguous(),
562
+ )
563
+
564
+ kwargs[grad_out_name] = dout
565
+ # See https://github.com/pytorch/pytorch/blob/release/2.4/aten/src/ATen/native/native_functions.yaml#L14695
566
+ # for the SDPA kernel definitions.
567
+ grad_query_, grad_key_, grad_value_, *rest = op(
568
+ query=q,
569
+ key=k,
570
+ value=v,
571
+ out=out_,
572
+ logsumexp=lse,
573
+ is_causal=is_causal_behavior.value,
574
+ **kwargs,
575
+ )
576
+ else:
577
+ grad_query_ = torch.zeros_like(query, dtype=accum_dtype)
578
+ grad_key_ = torch.zeros_like(key, dtype=accum_dtype)
579
+ grad_value_ = torch.zeros_like(value, dtype=accum_dtype)
580
+
581
+ ROUND_ROBIN_CYCLE = 2
582
+ if i == 0:
583
+ grad_key += grad_key_
584
+ grad_value += grad_value_
585
+ else:
586
+ pointer = 0
587
+ # Wait for the kv gradient from (cp_rank - 1) rank.
588
+ next_grad_kv = dkv_rotater.next_buffer()
589
+ grad_key = next_grad_kv[pointer : pointer + grad_key.numel()].reshape(
590
+ grad_key.shape
591
+ )
592
+ pointer += grad_key.numel()
593
+ grad_value = next_grad_kv[pointer : pointer + grad_value.numel()].reshape(
594
+ grad_value.shape
595
+ )
596
+
597
+ if i <= rank and _cp_options.enable_load_balance:
598
+ grad_key = _partial_update(
599
+ grad_key,
600
+ grad_key_,
601
+ dim=seq_dim,
602
+ n_chunks=ROUND_ROBIN_CYCLE,
603
+ idx=0,
604
+ add=True,
605
+ )
606
+ grad_value = _partial_update(
607
+ grad_value,
608
+ grad_value_,
609
+ dim=seq_dim,
610
+ n_chunks=ROUND_ROBIN_CYCLE,
611
+ idx=0,
612
+ add=True,
613
+ )
614
+ else:
615
+ grad_key += grad_key_
616
+ grad_value += grad_value_
617
+
618
+ next_grad_kv = torch.cat([grad_key.flatten(), grad_value.flatten()])
619
+ # Send the grad key and grad value to the next rank.
620
+ dkv_rotater.exchange_buffers(next_grad_kv)
621
+
622
+ if i <= rank or not _cp_options.enable_load_balance:
623
+ grad_query += grad_query_
624
+ else:
625
+ grad_query = _partial_update(
626
+ grad_query,
627
+ grad_query_,
628
+ dim=seq_dim,
629
+ n_chunks=ROUND_ROBIN_CYCLE,
630
+ idx=1,
631
+ add=True,
632
+ )
633
+
634
+ assert grad_key_ is not None
635
+ assert grad_value_ is not None
636
+ grad_query = grad_query.to(query.dtype)
637
+ next_grad_kv = dkv_rotater.next_buffer().to(key.dtype)
638
+ grad_key = next_grad_kv[: grad_key.numel()].reshape(grad_key.shape)
639
+ grad_value = next_grad_kv[grad_key.numel() :].reshape(grad_value.shape)
640
+ return (
641
+ grad_query,
642
+ grad_key,
643
+ grad_value,
644
+ # pyrefly: ignore [unbound-name]
645
+ *rest,
646
+ )
647
+
648
+
649
+ def _scaled_dot_product_ring_flash_attention(
650
+ mesh: DeviceMesh,
651
+ query: torch.Tensor,
652
+ key: torch.Tensor,
653
+ value: torch.Tensor,
654
+ dropout_p: float = 0.0,
655
+ is_causal: bool = False,
656
+ return_debug_mask: bool = False,
657
+ *,
658
+ scale: float | None = None,
659
+ ) -> tuple[torch.Tensor, ...]:
660
+ if return_debug_mask:
661
+ raise NotImplementedError("return_debug_mask is not supported yet")
662
+
663
+ # TODO: remove this hardcoding
664
+ seq_dim = 2
665
+ group = mesh.get_group()
666
+ return _templated_ring_attention(
667
+ group,
668
+ seq_dim,
669
+ aten._scaled_dot_product_flash_attention,
670
+ query=query,
671
+ key=key,
672
+ value=value,
673
+ is_causal=is_causal,
674
+ dropout_p=dropout_p,
675
+ scale=scale,
676
+ )
677
+
678
+
679
+ def _scaled_dot_product_ring_efficient_attention(
680
+ mesh: DeviceMesh,
681
+ query: torch.Tensor,
682
+ key: torch.Tensor,
683
+ value: torch.Tensor,
684
+ attn_bias: torch.Tensor | None = None,
685
+ compute_log_sumexp: bool = True,
686
+ dropout_p: float = 0.0,
687
+ is_causal: bool = False,
688
+ *,
689
+ scale: float | None = None,
690
+ ) -> tuple[torch.Tensor, ...]:
691
+ if attn_bias is not None:
692
+ raise NotImplementedError("attn_bias is not supported yet")
693
+
694
+ if not compute_log_sumexp:
695
+ # CP requires compute_log_sumexp to be True because it always merges LSE
696
+ compute_log_sumexp = True
697
+
698
+ # TODO: remove this hardcoding
699
+ seq_dim = 2
700
+ group = mesh.get_group()
701
+ return _templated_ring_attention(
702
+ group,
703
+ seq_dim,
704
+ aten._scaled_dot_product_efficient_attention,
705
+ query=query,
706
+ key=key,
707
+ value=value,
708
+ is_causal=is_causal,
709
+ attn_bias=attn_bias,
710
+ dropout_p=dropout_p,
711
+ scale=scale,
712
+ compute_log_sumexp=compute_log_sumexp,
713
+ )
714
+
715
+
716
+ def _scaled_dot_product_ring_cudnn_attention(
717
+ mesh: DeviceMesh,
718
+ query: torch.Tensor,
719
+ key: torch.Tensor,
720
+ value: torch.Tensor,
721
+ attn_bias: torch.Tensor | None = None,
722
+ compute_log_sumexp: bool = True,
723
+ dropout_p: float = 0.0,
724
+ is_causal: bool = False,
725
+ return_debug_mask: bool = False,
726
+ *,
727
+ scale: float | None = None,
728
+ ) -> tuple[torch.Tensor, ...]:
729
+ if attn_bias is not None:
730
+ raise NotImplementedError("attn_bias is not supported yet")
731
+
732
+ if not compute_log_sumexp:
733
+ # CP requires compute_log_sumexp to be True because it always merges LSE
734
+ compute_log_sumexp = True
735
+
736
+ # TODO: remove this hardcoding
737
+ seq_dim = 2
738
+ group = mesh.get_group()
739
+ return _templated_ring_attention(
740
+ group,
741
+ seq_dim,
742
+ aten._scaled_dot_product_cudnn_attention,
743
+ query=query,
744
+ key=key,
745
+ value=value,
746
+ attn_bias=attn_bias,
747
+ compute_log_sumexp=compute_log_sumexp,
748
+ dropout_p=dropout_p,
749
+ is_causal=is_causal,
750
+ return_debug_mask=return_debug_mask,
751
+ scale=scale,
752
+ )
753
+
754
+
755
+ def _scaled_dot_product_ring_flash_attention_backward(
756
+ mesh: DeviceMesh,
757
+ grad_out: torch.Tensor,
758
+ query: torch.Tensor,
759
+ key: torch.Tensor,
760
+ value: torch.Tensor,
761
+ out: torch.Tensor,
762
+ logsumexp: torch.Tensor,
763
+ cum_seq_q: torch.Tensor,
764
+ cum_seq_k: torch.Tensor,
765
+ max_q: int,
766
+ max_k: int,
767
+ dropout_p: float,
768
+ is_causal: bool,
769
+ philox_seed: torch.Tensor,
770
+ philox_offset: torch.Tensor,
771
+ *,
772
+ scale: float | None = None,
773
+ ) -> tuple[torch.Tensor, ...]:
774
+ # TODO: remove this hardcoding
775
+ seq_dim = 2
776
+ group = mesh.get_group()
777
+ return _templated_ring_attention_backward(
778
+ group,
779
+ seq_dim,
780
+ aten._scaled_dot_product_flash_attention_backward.default,
781
+ grad_out=grad_out,
782
+ grad_out_name="grad_out",
783
+ query=query,
784
+ key=key,
785
+ value=value,
786
+ out=out,
787
+ logsumexp=logsumexp,
788
+ is_causal=is_causal,
789
+ cum_seq_q=cum_seq_q,
790
+ cum_seq_k=cum_seq_k,
791
+ max_q=max_q,
792
+ max_k=max_k,
793
+ dropout_p=dropout_p,
794
+ philox_seed=philox_seed,
795
+ philox_offset=philox_offset,
796
+ scale=scale,
797
+ )
798
+
799
+
800
+ def _scaled_dot_product_ring_efficient_attention_backward(
801
+ mesh: DeviceMesh,
802
+ grad_out: torch.Tensor,
803
+ query: torch.Tensor,
804
+ key: torch.Tensor,
805
+ value: torch.Tensor,
806
+ bias: torch.Tensor,
807
+ out: torch.Tensor,
808
+ logsumexp: torch.Tensor,
809
+ philox_seed: torch.Tensor,
810
+ philox_offset: torch.Tensor,
811
+ dropout_p: float,
812
+ grad_input_mask: tuple[bool, ...],
813
+ is_causal: bool = False,
814
+ *,
815
+ scale: float | None = None,
816
+ ) -> tuple[torch.Tensor, ...]:
817
+ # TODO: remove this hardcoding
818
+ seq_dim = 2
819
+ group = mesh.get_group()
820
+ return _templated_ring_attention_backward(
821
+ group,
822
+ seq_dim,
823
+ aten._scaled_dot_product_efficient_attention_backward.default,
824
+ grad_out=grad_out,
825
+ grad_out_name="grad_out_",
826
+ query=query,
827
+ key=key,
828
+ value=value,
829
+ attn_bias=bias,
830
+ out=out,
831
+ logsumexp=logsumexp,
832
+ philox_seed=philox_seed,
833
+ philox_offset=philox_offset,
834
+ dropout_p=dropout_p,
835
+ grad_input_mask=grad_input_mask,
836
+ is_causal=is_causal,
837
+ scale=scale,
838
+ )
839
+
840
+
841
+ def _scaled_dot_product_ring_cudnn_attention_backward(
842
+ mesh: DeviceMesh,
843
+ grad_out: torch.Tensor,
844
+ query: torch.Tensor,
845
+ key: torch.Tensor,
846
+ value: torch.Tensor,
847
+ out: torch.Tensor,
848
+ logsumexp: torch.Tensor,
849
+ philox_seed: torch.Tensor,
850
+ philox_offset: torch.Tensor,
851
+ attn_bias: torch.Tensor,
852
+ cum_seq_q: torch.Tensor,
853
+ cum_seq_k: torch.Tensor,
854
+ max_q: int,
855
+ max_k: int,
856
+ dropout_p: float,
857
+ is_causal: bool,
858
+ *,
859
+ scale: float | None = None,
860
+ ) -> tuple[torch.Tensor, ...]:
861
+ # TODO: remove this hardcoding
862
+ seq_dim = 2
863
+ group = mesh.get_group()
864
+ return _templated_ring_attention_backward(
865
+ group,
866
+ seq_dim,
867
+ aten._scaled_dot_product_cudnn_attention_backward.default,
868
+ grad_out=grad_out,
869
+ grad_out_name="grad_out",
870
+ query=query,
871
+ key=key,
872
+ value=value,
873
+ out=out,
874
+ logsumexp=logsumexp,
875
+ philox_seed=philox_seed,
876
+ philox_offset=philox_offset,
877
+ attn_bias=attn_bias,
878
+ cum_seq_q=cum_seq_q,
879
+ cum_seq_k=cum_seq_k,
880
+ max_q=max_q,
881
+ max_k=max_k,
882
+ dropout_p=dropout_p,
883
+ is_causal=is_causal,
884
+ scale=scale,
885
+ )
886
+
887
+
888
+ def _sdpa_handler(
889
+ op_call: torch._ops.OpOverload,
890
+ args: tuple[object, ...],
891
+ kwargs: dict[str, object],
892
+ ) -> object:
893
+ # extract local tensor and sharding infos to a OpInfo
894
+ op_info = DTensor._op_dispatcher.unwrap_to_op_info(op_call, args, kwargs)
895
+ logger.debug("Dispatching op_call: %s", op_info.schema)
896
+
897
+ # sharding propagation
898
+ # TODO: remove the context parallel strategy from the default propagation
899
+ # rule. Either figure out how to dynamically enable it or just don't call
900
+ # propagate.
901
+ DTensor._op_dispatcher.sharding_propagator.propagate(op_info)
902
+ output_sharding = op_info.output_sharding
903
+ assert output_sharding is not None, "output sharding should not be None"
904
+ assert not output_sharding.needs_redistribute, "inputs need to be redistributed"
905
+
906
+ call_maps: dict[torch._ops.OpOverload, Callable] = {
907
+ aten._scaled_dot_product_flash_attention.default: _scaled_dot_product_ring_flash_attention,
908
+ aten._scaled_dot_product_efficient_attention.default: _scaled_dot_product_ring_efficient_attention,
909
+ aten._scaled_dot_product_cudnn_attention.default: _scaled_dot_product_ring_cudnn_attention,
910
+ aten._scaled_dot_product_flash_attention_backward.default: _scaled_dot_product_ring_flash_attention_backward,
911
+ aten._scaled_dot_product_efficient_attention_backward.default: _scaled_dot_product_ring_efficient_attention_backward,
912
+ aten._scaled_dot_product_cudnn_attention_backward.default: _scaled_dot_product_ring_cudnn_attention_backward,
913
+ }
914
+ if op_call in call_maps:
915
+ local_results = call_maps[op_call](
916
+ op_info.compute_mesh,
917
+ *op_info.local_args, # type: ignore[arg-type]
918
+ **op_info.local_kwargs, # type: ignore[arg-type]
919
+ )
920
+ else:
921
+ raise NotImplementedError(
922
+ "CP only supports flash attention and memory efficient attention now."
923
+ )
924
+
925
+ return DTensor._op_dispatcher.wrap(local_results, output_sharding.output_spec)
926
+
927
+
928
+ custom_ops = {
929
+ aten._scaled_dot_product_flash_attention.default: _sdpa_handler,
930
+ aten._scaled_dot_product_flash_attention_backward.default: _sdpa_handler,
931
+ aten._scaled_dot_product_efficient_attention.default: _sdpa_handler,
932
+ aten._scaled_dot_product_efficient_attention_backward.default: _sdpa_handler,
933
+ aten._scaled_dot_product_cudnn_attention.default: _sdpa_handler,
934
+ aten._scaled_dot_product_cudnn_attention_backward.default: _sdpa_handler,
935
+ }
936
+ exitsing_custom_ops = DTensor._op_dispatcher._custom_op_handlers
937
+
938
+
939
+ ArgsType = tuple[Any, ...]
940
+ KwargsType = dict[str, Any]
941
+ InputFnType = Callable[[nn.Module | None, ArgsType, KwargsType, DeviceMesh], Any]
942
+ OutputFnType = Callable[[nn.Module | None, Any, Any, DeviceMesh], Any]
943
+
944
+ _replaced_functions: dict[Callable, tuple[str, Callable]] = {}
945
+
946
+
947
+ def _distribute_function(
948
+ fn: Callable,
949
+ fn_module: types.ModuleType,
950
+ device_mesh: DeviceMesh,
951
+ input_fn: InputFnType,
952
+ output_fn: OutputFnType,
953
+ ) -> None:
954
+ """
955
+ A helper function to replace a function with a distributed version by
956
+ using the monkey patching approach.
957
+
958
+ This function is for the CP internal usage only.
959
+ """
960
+
961
+ def wrapper(
962
+ target_fn: Callable, input_fn: InputFnType, output_fn: OutputFnType
963
+ ) -> Callable:
964
+ def inner_fn(*args: ArgsType, **kwargs: KwargsType) -> Any:
965
+ args, kwargs = input_fn(None, args, kwargs, device_mesh)
966
+ outputs = target_fn(*args, **kwargs)
967
+ return output_fn(None, (args, kwargs), outputs, device_mesh)
968
+
969
+ return inner_fn
970
+
971
+ global _replaced_functions
972
+
973
+ if fn in _replaced_functions:
974
+ return
975
+
976
+ wrapper_fn = wrapper(fn, input_fn, output_fn)
977
+ setattr(fn_module, fn.__name__, wrapper_fn)
978
+ _replaced_functions[wrapper_fn] = (fn.__name__, fn)
979
+
980
+
981
+ def _restore_function(fn: Callable, fn_module: types.ModuleType) -> None:
982
+ """Restore the function that is replaced by _distribute_function."""
983
+ if fn not in _replaced_functions:
984
+ return
985
+
986
+ original_name, original_fn = _replaced_functions[fn]
987
+ setattr(fn_module, original_name, original_fn)
988
+
989
+
990
+ def _enable_cp_dtensor_dispatcher() -> None:
991
+ """Enables DTensor dispatcher to dispatch SDPA to CP."""
992
+ # Enable custom op handlers for CP
993
+ DTensor._op_dispatcher._custom_op_handlers = {
994
+ **exitsing_custom_ops,
995
+ **custom_ops,
996
+ }
997
+ # Register CP-specific sharding rules
998
+ from ._sharding_rules import register_cp_sharding_rules
999
+
1000
+ register_cp_sharding_rules()
1001
+
1002
+
1003
+ def _disable_cp_dtensor_dispatcher() -> None:
1004
+ """Disables DTensor dispatcher to dispatch SDPA to CP."""
1005
+ # Restore original custom op handlers
1006
+ DTensor._op_dispatcher._custom_op_handlers = exitsing_custom_ops
1007
+
1008
+ # TODO: unregister_cp_sharding_rules(clear_the_cache=True) will cause
1009
+ # all DTensor sharding propagation cache being invalidated. It is not
1010
+ # easy to achieve selectively invalidating lru cache without rewriting
1011
+ # the sharding propagation wrapper.
1012
+
1013
+ from ._sharding_rules import unregister_cp_sharding_rules
1014
+
1015
+ unregister_cp_sharding_rules(clear_the_cache=False)
1016
+
1017
+
1018
+ def _enable_context_parallel_dispatcher_impl(seq_dim: int, mesh: DeviceMesh) -> None:
1019
+ sdpa_cp = _ContextParallel(
1020
+ seq_dim=seq_dim,
1021
+ attention_type=_ContextParallel.AttentionType.SDPA,
1022
+ )
1023
+
1024
+ if _dispatch_mode == _DispatchMode.MONKEY_PATCH:
1025
+ _distribute_function(
1026
+ F.scaled_dot_product_attention,
1027
+ F,
1028
+ mesh,
1029
+ sdpa_cp.sdpa_input_fn,
1030
+ sdpa_cp.sdpa_output_fn,
1031
+ )
1032
+ _enable_cp_dtensor_dispatcher()
1033
+ elif _dispatch_mode == _DispatchMode.MODULE_WRAPPER:
1034
+ _enable_cp_dtensor_dispatcher()
1035
+ else:
1036
+ raise ValueError(f"Unknown dispatch mode: {_dispatch_mode}")
1037
+
1038
+
1039
+ def _disable_context_parallel_dispatcher_impl() -> None:
1040
+ if _dispatch_mode == _DispatchMode.MONKEY_PATCH:
1041
+ _restore_function(F.scaled_dot_product_attention, F)
1042
+ elif _dispatch_mode == _DispatchMode.MODULE_WRAPPER:
1043
+ pass
1044
+ else:
1045
+ raise NotImplementedError(f"Unknown dispatch mode: {_dispatch_mode}")
1046
+
1047
+ _disable_cp_dtensor_dispatcher()
1048
+
1049
+
1050
+ _compiled_create_block_mask = None
1051
+
1052
+
1053
+ def _context_parallel_buffers(
1054
+ mesh: DeviceMesh,
1055
+ buffers: list[torch.Tensor | BlockMask],
1056
+ buffer_seq_dims: list[int],
1057
+ load_balancer: _LoadBalancer | None = None,
1058
+ ) -> list[torch.Tensor | BlockMask]:
1059
+ """
1060
+ Shard the buffers along the sequence dimensions according to CP rules.
1061
+ Args:
1062
+ mesh (:class:`DeviceMesh`): the device mesh for the context parallelism.
1063
+ buffers (List[torch.Tensor]): the buffers to be sharded.
1064
+ seq_dims (List[int]): the sequence dimensions of ``buffers``. This list
1065
+ must have the same length as ``buffers``.
1066
+ load_balancer (Optional[:class:`_LoadBalancer`]): an optional `_LoadBalancer`
1067
+ object. If this argument is `None`, it means the `buffers` need no
1068
+ rearrangement before being sharded. If this argument is a `_LoadBalancer`
1069
+ object, call its `_generate_indices(restore=False)` to generate the
1070
+ rearrangement indices such that each shard of `buffer[rearrange_idx]` is
1071
+ well-balanced (i.e., having close sparsities).
1072
+
1073
+ Returns:
1074
+ List[torch.Tensor]: the sharded buffers.
1075
+
1076
+ Note:
1077
+ For `_context_parallel_shard` we require a non-None `load_balancer` object to be
1078
+ explicitly passed if load-balancing is needed.
1079
+ """
1080
+ # generate the index tensor for rearranging the buffer if a load-balance
1081
+ # is available
1082
+ load_balance_indices = load_balancer._generate_indices() if load_balancer else None
1083
+ assert load_balance_indices is None or load_balance_indices.ndim == 2, (
1084
+ "load balance index expects shape (1, seq_len) or (B, seq_len) "
1085
+ f"but got {load_balance_indices.shape}."
1086
+ )
1087
+
1088
+ new_buffers = []
1089
+ sharded_buffer: torch.Tensor | BlockMask
1090
+ for buffer, seq_dim in zip(buffers, buffer_seq_dims):
1091
+ if isinstance(buffer, torch.Tensor):
1092
+ # TODO: the load balance doesn't perform error handling.
1093
+
1094
+ # NOTE: assuming batch dim is 0
1095
+
1096
+ if load_balance_indices is not None:
1097
+ # TODO: we should expclitly ask users to unsqueeze the batch dim.
1098
+ # But this is a BC breaking ask.
1099
+ # However, what we have done today is also not very safe.
1100
+ idx_batch_size = load_balance_indices.size(0)
1101
+ data_batch_size = buffer.size(0) if seq_dim > 0 else 1
1102
+
1103
+ if idx_batch_size != 1 and idx_batch_size != data_batch_size:
1104
+ raise ValueError(
1105
+ "Cannot rearrange buffer: "
1106
+ f"load_balance_indices has shape {load_balance_indices.shape}, "
1107
+ f"but buffer has shape {buffer.shape}."
1108
+ )
1109
+
1110
+ if seq_dim == 0:
1111
+ buffer = torch.index_select(
1112
+ buffer, dim=0, index=load_balance_indices[0]
1113
+ )
1114
+ else:
1115
+ indices = load_balance_indices
1116
+ if idx_batch_size == 1:
1117
+ size = [data_batch_size] + list(indices.size())[1:]
1118
+ indices = indices.expand(*size)
1119
+
1120
+ for i in range(data_batch_size):
1121
+ buffer[i] = torch.index_select(
1122
+ buffer[i], dim=seq_dim - 1, index=indices[i]
1123
+ )
1124
+
1125
+ # use DTensor to shard the buffer on sequence dimension, retain the local tensor
1126
+ sharded_buffer = distribute_tensor(
1127
+ buffer, mesh, [Shard(seq_dim)], src_data_rank=None
1128
+ ).to_local()
1129
+ elif isinstance(buffer, BlockMask):
1130
+ sharded_buffer = _create_cp_block_mask(
1131
+ mask_mod=buffer.mask_mod,
1132
+ B=buffer.kv_num_blocks.shape[0],
1133
+ H=buffer.kv_num_blocks.shape[1],
1134
+ Q_LEN=buffer.seq_lengths[0],
1135
+ KV_LEN=buffer.seq_lengths[1],
1136
+ device_mesh=mesh,
1137
+ load_balancer=load_balancer,
1138
+ )
1139
+ else:
1140
+ raise ValueError(f"Unknown buffer type: {type(buffer)}")
1141
+
1142
+ new_buffers.append(sharded_buffer)
1143
+
1144
+ return new_buffers
1145
+
1146
+
1147
+ def _create_cp_block_mask(
1148
+ mask_mod: _mask_mod_signature,
1149
+ B: int,
1150
+ H: int,
1151
+ Q_LEN: int,
1152
+ KV_LEN: int,
1153
+ device_mesh: DeviceMesh,
1154
+ load_balancer: _LoadBalancer | None = None,
1155
+ ) -> BlockMask:
1156
+ """
1157
+ Creates a specialized BlockMask for Context Parallel FlexAttention.
1158
+
1159
+ This function creates a BlockMask that enables computation of attention results
1160
+ for sharded Q attending to global KV. The mask appropriately handles the query
1161
+ index offset required when each rank operates on a shard of the query sequence
1162
+ while accessing the full key-value sequence.
1163
+
1164
+ The function internally rewrites the provided mask_mod function to translate local
1165
+ query indices to global query indices, ensuring that the masking logic is applied
1166
+ correctly across the distributed computation.
1167
+
1168
+ Args:
1169
+ mask_mod (Callable): Mask function that operates on global attention indices.
1170
+ B (int): Batch size.
1171
+ H (int): Number of query heads.
1172
+ Q_LEN (int): Global sequence length of the query.
1173
+ KV_LEN (int): Global sequence length of the key/value.
1174
+ device_mesh (DeviceMesh): Device mesh used for context parallelism.
1175
+ load_balancer (Optional[:class:`_LoadBalancer`]): The load-balancer used to rearrange
1176
+ QKV before sharding. This will be used to modify the block_mask generated.
1177
+
1178
+ Returns:
1179
+ BlockMask: A block mask configured for the local query shard that can be used
1180
+ with flex_attention() for the given cp_mesh.
1181
+
1182
+ Raises:
1183
+ NotImplementedError: If Q_LEN is not divisible by (CP world size * BLOCK_SIZE).
1184
+
1185
+ Warning:
1186
+ Currently requires Q_LEN to be divisible by CP mesh world size * BLOCK_SIZE
1187
+ (BLOCK_SIZE defaults to 128). This constraint exists because the BlockMask
1188
+ must handle both padding and offsets correctly. For example, if Q_LEN is 384,
1189
+ CP world size is 2, and BLOCK_SIZE is 128, the local Q_LEN would be 192. In
1190
+ such cases, both rank0 and rank1 would have paddings in their local BlockMasks.
1191
+ Support for padding in this scenario is planned for future work.
1192
+
1193
+ """
1194
+
1195
+ from torch.nn.attention.flex_attention import _DEFAULT_SPARSE_BLOCK_SIZE
1196
+
1197
+ if Q_LEN % (device_mesh.size() * _DEFAULT_SPARSE_BLOCK_SIZE) != 0:
1198
+ raise NotImplementedError(
1199
+ f"Q_LEN {Q_LEN} is not divisible by CP mesh world size {device_mesh.size()} * "
1200
+ f"BLOCK_SIZE {_DEFAULT_SPARSE_BLOCK_SIZE}. This is not supported yet. "
1201
+ )
1202
+
1203
+ global _compiled_create_block_mask
1204
+ if _compiled_create_block_mask is None:
1205
+ _compiled_create_block_mask = torch.compile(
1206
+ create_block_mask, dynamic=False, fullgraph=True
1207
+ )
1208
+ compiled_create_block_mask = _compiled_create_block_mask
1209
+
1210
+ def _rewrite_mask_mod(
1211
+ mask_mod: _mask_mod_signature,
1212
+ rank: int,
1213
+ block_size: int,
1214
+ local_q_size: int,
1215
+ qkv_rearrange_indices: torch.Tensor | None = None,
1216
+ ) -> _mask_mod_signature:
1217
+ assert qkv_rearrange_indices is None or qkv_rearrange_indices.ndim == 2, (
1218
+ "load balance index expects shape (1, seq_len) or (B, seq_len) "
1219
+ f"but got {qkv_rearrange_indices.shape}."
1220
+ )
1221
+
1222
+ def qkv_idx_restore(
1223
+ b: torch.Tensor, idx_post_rearrange: torch.Tensor
1224
+ ) -> torch.Tensor:
1225
+ if qkv_rearrange_indices is not None:
1226
+ if (
1227
+ qkv_rearrange_indices.size(0) == 1
1228
+ ): # identical load-balance in batch
1229
+ idx_pre_rearrange = qkv_rearrange_indices[0][idx_post_rearrange]
1230
+ else:
1231
+ idx_pre_rearrange = qkv_rearrange_indices[b][idx_post_rearrange]
1232
+ else:
1233
+ idx_pre_rearrange = idx_post_rearrange
1234
+
1235
+ return idx_pre_rearrange
1236
+
1237
+ def local_q_idx_to_q_idx(local_q_idx: torch.Tensor) -> torch.Tensor:
1238
+ # calculate local block_idx and block_offset
1239
+ local_blk_idx, local_blk_offset = (
1240
+ local_q_idx // block_size,
1241
+ local_q_idx % block_size,
1242
+ )
1243
+ # NOTE: load balancing is not used
1244
+ local_num_blocks = local_q_size // block_size
1245
+ blk_idx = local_num_blocks * rank + local_blk_idx
1246
+ return blk_idx * block_size + local_blk_offset
1247
+
1248
+ return lambda b, h, q_idx, kv_idx: mask_mod(
1249
+ b,
1250
+ h,
1251
+ qkv_idx_restore(b, local_q_idx_to_q_idx(q_idx)),
1252
+ qkv_idx_restore(b, kv_idx),
1253
+ )
1254
+
1255
+ cp_rank = device_mesh.get_local_rank()
1256
+ cp_group_size = device_mesh.size()
1257
+ load_balancer = load_balancer or _create_default_load_balancer(
1258
+ Q_LEN, cp_group_size, device_mesh.device_type
1259
+ )
1260
+ Q_SHARD_LEN = Q_LEN // cp_group_size
1261
+ block_size = _DEFAULT_SPARSE_BLOCK_SIZE
1262
+
1263
+ rearrange_indices = (
1264
+ load_balancer._generate_indices(restore=False) if load_balancer else None
1265
+ )
1266
+ block_mask = compiled_create_block_mask(
1267
+ _rewrite_mask_mod(
1268
+ mask_mod,
1269
+ cp_rank,
1270
+ block_size,
1271
+ Q_SHARD_LEN,
1272
+ qkv_rearrange_indices=rearrange_indices,
1273
+ ),
1274
+ B,
1275
+ H,
1276
+ Q_SHARD_LEN,
1277
+ KV_LEN,
1278
+ device=device_mesh.device_type,
1279
+ BLOCK_SIZE=(block_size, block_size),
1280
+ )
1281
+ return block_mask
1282
+
1283
+
1284
+ #####################
1285
+ # Experimental APIs
1286
+ #####################
1287
+
1288
+
1289
+ class _ContextParallel(ParallelStyle):
1290
+ class AttentionType(Enum):
1291
+ FLEX = "flex_attention"
1292
+ SDPA = "scaled_dot_product_attention"
1293
+
1294
+ def __init__(
1295
+ self,
1296
+ seq_dim: int,
1297
+ attention_type: AttentionType,
1298
+ ) -> None:
1299
+ super().__init__()
1300
+ self.seq_dim = seq_dim
1301
+ self.attention_type = attention_type
1302
+
1303
+ def _apply(self, module: nn.Module, mesh: DeviceMesh) -> nn.Module:
1304
+ if self.attention_type == self.AttentionType.FLEX:
1305
+ module.register_forward_pre_hook(
1306
+ partial(self.flex_input_fn, mesh=mesh), with_kwargs=True
1307
+ )
1308
+ return module
1309
+ elif self.attention_type == self.AttentionType.SDPA:
1310
+ module.register_forward_pre_hook(
1311
+ partial(self.sdpa_input_fn, mesh=mesh), with_kwargs=True
1312
+ )
1313
+ module.register_forward_hook(partial(self.sdpa_output_fn, mesh=mesh))
1314
+ return module
1315
+ else:
1316
+ raise ValueError(f"Unknown attention type: {self.attention_type}")
1317
+
1318
+ def flex_input_fn(
1319
+ self, module: nn.Module | None, args: Any, kwargs: Any, mesh: DeviceMesh
1320
+ ) -> Any:
1321
+ args_list = list(args)
1322
+ for idx, name in enumerate(
1323
+ ("query", "key", "value", "score_mod", "block_mask")
1324
+ ):
1325
+ if idx >= len(args):
1326
+ args_list.append(kwargs.pop(name, None))
1327
+
1328
+ query, key, value, score_mod, block_mask = args_list[:5]
1329
+ assert isinstance(query, torch.Tensor)
1330
+ assert isinstance(key, torch.Tensor)
1331
+ assert isinstance(value, torch.Tensor)
1332
+ assert isinstance(block_mask, BlockMask | tuple)
1333
+
1334
+ key = key.contiguous()
1335
+ value = value.contiguous()
1336
+
1337
+ global_key, global_value = flex_cp_allgather(
1338
+ key, value, self.seq_dim, c10d._get_process_group_name(mesh.get_group())
1339
+ )
1340
+ args_list[1] = global_key
1341
+ args_list[2] = global_value
1342
+
1343
+ return tuple(args_list), kwargs
1344
+
1345
+ def sdpa_input_fn(
1346
+ self,
1347
+ module: nn.Module | None,
1348
+ args: tuple[Any, ...],
1349
+ kwargs: dict[str, Any],
1350
+ mesh: DeviceMesh,
1351
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
1352
+ placement = [Shard(self.seq_dim)]
1353
+ all_args = []
1354
+
1355
+ for arg in itertools.chain(args, kwargs.values()):
1356
+ if isinstance(arg, torch.Tensor):
1357
+ if isinstance(arg, DTensor):
1358
+ assert arg._spec.placements == placement
1359
+ else:
1360
+ arg = DTensor.from_local(arg, mesh, placement, run_check=False)
1361
+
1362
+ all_args.append(arg)
1363
+
1364
+ new_args = tuple(all_args[0 : len(args)])
1365
+ new_kwargs = dict(zip(kwargs.keys(), all_args[len(args) :]))
1366
+ return new_args, new_kwargs
1367
+
1368
+ def sdpa_output_fn(
1369
+ self, module: nn.Module | None, inputs: Any, outputs: Any, mesh: DeviceMesh
1370
+ ) -> Any:
1371
+ new_outputs = []
1372
+ for output in [outputs] if isinstance(outputs, torch.Tensor) else outputs:
1373
+ output = output.to_local() if isinstance(output, DTensor) else output
1374
+ new_outputs.append(output)
1375
+
1376
+ if isinstance(outputs, torch.Tensor):
1377
+ return new_outputs[0]
1378
+
1379
+ return tuple(new_outputs)
1380
+
1381
+
1382
+ CPBuffer: TypeAlias = torch.Tensor | BlockMask
1383
+ CPBufferContainer: TypeAlias = Sequence[CPBuffer] | Mapping[str, CPBuffer]
1384
+ CPBufferSeqDims: TypeAlias = Sequence[int] | Mapping[str, int]
1385
+
1386
+
1387
+ def _context_parallel_shard(
1388
+ mesh: DeviceMesh,
1389
+ buffers: CPBufferContainer,
1390
+ seq_dims: CPBufferSeqDims,
1391
+ load_balancer: _LoadBalancer | None = None,
1392
+ ) -> list[torch.Tensor | BlockMask]:
1393
+ """
1394
+ Shard the buffers along the specified sequence dimensions (`seq_dims`), so that each
1395
+ rank retains only its corresponding shard according to the provided `mesh`. If a
1396
+ `load_balancer` is provided, the buffers will be rearranged by the load balancer
1397
+ before sharding to improve load balance. Buffers can be either tensors or `BlockMask`
1398
+ objects. If a buffer is a `BlockMask`, its sharding dimension is determined by the
1399
+ `BlockMask` implementation, and the corresponding `seq_dim` is ignored.
1400
+
1401
+ Note:
1402
+ For `_context_parallel_shard`, a non-None `load_balancer` must be explicitly passed
1403
+ if load balancing is required.
1404
+
1405
+ Args:
1406
+ mesh (DeviceMesh): The device mesh used for context parallelism.
1407
+ buffers (List[torch.Tensor | BlockMask]): Buffers whose usage depends on the sequence
1408
+ dimension. Examples include input batches, labels, and positional embedding buffers.
1409
+ These buffers must be sharded along the sequence dimension to ensure correctness.
1410
+ seq_dims (List[int]): The sequence dimensions for each buffer in `buffers`. Must have
1411
+ the same length as `buffers`.
1412
+ load_balancer (Optional[_LoadBalancer]): An optional load balancer object. If provided,
1413
+ it rearranges the buffers before sharding to achieve better load balance. If not
1414
+ provided, no rearrangement is performed.
1415
+
1416
+ Returns:
1417
+ List[torch.Tensor | BlockMask]: The sharded buffers, each corresponding to the local
1418
+ shard for the current rank.
1419
+ """
1420
+ # TODO: these global variables are going to bite us someday.
1421
+ # We will have to remove them soon.
1422
+ # For the new API, we only support the module wrapper mode.
1423
+ global _dispatch_mode
1424
+ _dispatch_mode = _DispatchMode.MODULE_WRAPPER
1425
+ global _cp_options
1426
+ if load_balancer is not None:
1427
+ _cp_options.enable_load_balance = True
1428
+ else:
1429
+ _cp_options.enable_load_balance = False
1430
+
1431
+ if len(buffers) != len(seq_dims):
1432
+ raise ValueError(
1433
+ "`seq_dims` must have the same number of elements as `buffers`."
1434
+ )
1435
+
1436
+ flat_buffers, spec = tree_flatten(buffers)
1437
+ flat_seq_dims, _ = tree_flatten(seq_dims)
1438
+ if len(flat_buffers) != len(flat_seq_dims):
1439
+ raise ValueError("`seq_dims` must have the pytree structure as `buffers`.")
1440
+
1441
+ if isinstance(flat_buffers[0], torch.Tensor):
1442
+ device = flat_buffers[0].device
1443
+ else:
1444
+ device = flat_buffers[0].kv_num_blocks.device
1445
+ for buffer in flat_buffers:
1446
+ if isinstance(buffer, torch.Tensor):
1447
+ assert device == buffer.device, "All buffers must be on the same device"
1448
+ else:
1449
+ assert device == buffer.kv_num_blocks.device, (
1450
+ "All buffers must be on the same device"
1451
+ )
1452
+
1453
+ flat_sharded_buffers = _context_parallel_buffers(
1454
+ mesh, flat_buffers, flat_seq_dims, load_balancer
1455
+ )
1456
+
1457
+ return tree_unflatten(flat_sharded_buffers, spec)
1458
+
1459
+
1460
+ def _enable_context_parallel_dispatcher() -> None:
1461
+ """
1462
+ Enable the context parallel dispatcher. This API is experimental and subject to change.
1463
+ """
1464
+ _enable_cp_dtensor_dispatcher()
1465
+
1466
+
1467
+ def _disable_context_parallel_dispatcher() -> None:
1468
+ """
1469
+ Disable the context parallel dispatcher. This API is experimental and subject to change.
1470
+ """
1471
+ _disable_cp_dtensor_dispatcher()
1472
+
1473
+
1474
+ #####################################################
1475
+ # Current public APIs, but are also subject to change
1476
+ #####################################################
1477
+ @contextlib.contextmanager
1478
+ @torch.no_grad()
1479
+ def context_parallel(
1480
+ mesh: DeviceMesh,
1481
+ *,
1482
+ buffers: list[torch.Tensor] | None = None,
1483
+ buffer_seq_dims: list[int] | None = None,
1484
+ no_restore_buffers: set[torch.Tensor] | None = None,
1485
+ ) -> Generator[None, None, None]:
1486
+ """
1487
+
1488
+ ``context_parallel`` is an experimental API to enable context
1489
+ parallelism (CP). This API performs two actions: 1) patch the SDPA
1490
+ (``torch.nn.functional.scaled_dot_product_attention``) with the CP-enabled
1491
+ one, 2) shard ``buffers`` along the sequence dimension and each rank will
1492
+ preserve the corresponding shard according ``mesh``.
1493
+
1494
+ Args:
1495
+ mesh (:class:`DeviceMesh`): the device mesh for the context parallelism.
1496
+ buffers (Optional[List[torch.Tensor]]): buffers that the usage depend
1497
+ on the sequence dimension. Examples are input batch, labels and
1498
+ positional embedding buffers. These buffers must be sharded along
1499
+ the sequence dimension to ensure the accuracy. The sharding will
1500
+ happen in-place, the buffer's shape will change within the context.
1501
+ The buffers will be restored after the context finishes.
1502
+ ``no_restore_buffers`` can be used to specify which buffers don't
1503
+ need to be restored. Note that ``buffers`` should not contain any
1504
+ nn.Parameter.
1505
+ buffer_seq_dims (Optional[List[int]]): the sequence dimensions of ``buffers``.
1506
+ no_restore_buffers (Optional[Set[torch.Tensor]]): buffers in these set
1507
+ won't be restored after the context exits. This set must be a subset
1508
+ of ``buffers``. If the buffers won't be used after the context exits,
1509
+ these buffers can be put in this list to avoid extra restore time.
1510
+
1511
+ .. warning::
1512
+ `torch.distributed.tensor.experimental.context_parallel` is a
1513
+ prototype feature in PyTorch. The API is subject to change.
1514
+ """
1515
+ # For the legacy API, we only support the monkey-patch mode.
1516
+ # We will deprecate this API once the new API is widely used.
1517
+ global _dispatch_mode
1518
+ _dispatch_mode = _DispatchMode.MONKEY_PATCH
1519
+
1520
+ buffers = [] if buffers is None else buffers
1521
+ buffer_seq_dims = [] if buffer_seq_dims is None else buffer_seq_dims
1522
+ no_restore_buffers = set() if no_restore_buffers is None else no_restore_buffers
1523
+
1524
+ if len(buffers) != len(buffer_seq_dims):
1525
+ raise ValueError(
1526
+ "`seq_dims` must have the same number of elements as `buffers`."
1527
+ )
1528
+
1529
+ for buffer in no_restore_buffers:
1530
+ # Cannot use `if not buffer in buffers` which will incur tensor comparison.
1531
+ if not any(b is buffer for b in buffers):
1532
+ raise ValueError("`no_restore_buffers` must be a subset of `buffers`.")
1533
+
1534
+ original_buffers = [None if b in no_restore_buffers else b.clone() for b in buffers]
1535
+
1536
+ device = buffers[0].device
1537
+ seq_length = buffers[0].shape[buffer_seq_dims[0]]
1538
+ cp_world_size = mesh.size()
1539
+
1540
+ # If `enable_load_balance` is True, the default Head-tail load balancer
1541
+ # (:class:`_HeadTailLoadBalancer`) is used to rearrange the buffers before
1542
+ # sharding. Otherwise, we don't do any load-balance rearrange by passing
1543
+ # `None` to `_context_parallel_shard()`.
1544
+ load_balancer = _create_default_load_balancer(seq_length, cp_world_size, device)
1545
+ shards = _context_parallel_buffers(
1546
+ mesh,
1547
+ cast(list[torch.Tensor | BlockMask], buffers),
1548
+ buffer_seq_dims,
1549
+ load_balancer,
1550
+ )
1551
+ for buffer, shard in zip(buffers, shards):
1552
+ assert isinstance(shard, torch.Tensor), "ContextParallel only supports Tensor"
1553
+ shard = shard.clone()
1554
+ buffer.resize_(shard.shape)
1555
+ buffer.copy_(shard)
1556
+
1557
+ _enable_context_parallel_dispatcher_impl(seq_dim=2, mesh=mesh)
1558
+ yield
1559
+ _disable_context_parallel_dispatcher_impl()
1560
+
1561
+ for buffer, original_buffer in zip(buffers, original_buffers):
1562
+ if original_buffer is not None:
1563
+ buffer.resize_(original_buffer.shape)
1564
+ buffer.copy_(original_buffer)
1565
+
1566
+
1567
+ @torch.no_grad()
1568
+ def context_parallel_unshard(
1569
+ mesh: DeviceMesh,
1570
+ buffers: list[torch.Tensor],
1571
+ seq_dims: list[int],
1572
+ load_balancer: _LoadBalancer | None = None,
1573
+ ) -> list[torch.Tensor]:
1574
+ """
1575
+ Unshard the tensors (e.g., output) that are sharded due to context parallelism.
1576
+
1577
+ Args:
1578
+ mesh (:class:`DeviceMesh`): the device mesh for the context parallelism.
1579
+ buffers (List[torch.Tensor]): the buffers to be unsharded.
1580
+ seq_dims (List[int]): the sequence dimensions of ``buffers``. This list
1581
+ must have the same length as ``buffers``.
1582
+ load_balancer (Optional[:class:`_Loadbalancer`]): an optional `_LoadBalancer`
1583
+ object. If this argument is `None`, it means the `buffers` were not
1584
+ rearranged when being sharded and there's no need to put it back to order
1585
+ after unsharding. If this argument is a `_LoadBalancer` object, call
1586
+ its `_generate_indices(restore=True)` to generate the restore indices such
1587
+ that `unsharded[restore_idx]` is the original buffer.
1588
+
1589
+ Returns:
1590
+ List[torch.Tensor]: the unsharded buffers.
1591
+
1592
+ Note:
1593
+ For `context_parallel_unshard` we require not-None `load_balancer` object be
1594
+ explicitly passed if flex_attention() is to be used and load-balancing is needed.
1595
+ This is different from the case of SDPA though we strongly suggest users follow
1596
+ the same convention.
1597
+ """
1598
+ device = buffers[0].device
1599
+ cp_world_size = mesh.size()
1600
+ seq_length = buffers[0].shape[seq_dims[0]] * cp_world_size
1601
+
1602
+ # If users don't pass in a `load_balancer`:
1603
+ # - if `enable_load_balance` is True, we use the default round-robin
1604
+ # load balancer.
1605
+ # - if `enable_load_balance` is False, we don't do any load balancing
1606
+ # by passing in `None` as `restore_indices`.
1607
+ load_balancer = load_balancer or _create_default_load_balancer(
1608
+ seq_length, cp_world_size, device
1609
+ )
1610
+ restore_indices = (
1611
+ load_balancer._generate_indices(restore=True) if load_balancer else None
1612
+ )
1613
+
1614
+ assert restore_indices is None or restore_indices.ndim == 2, (
1615
+ "load balance restore index expects shape (1, seq_len) or (B, seq_len) "
1616
+ f"but got {restore_indices.shape}."
1617
+ )
1618
+ unsharded_buffers = []
1619
+ for b, dim in zip(buffers, seq_dims):
1620
+ b = b.contiguous()
1621
+ unsharded_b = _maybe_wait(ft_c.all_gather_tensor(b, dim, mesh))
1622
+
1623
+ if restore_indices is not None:
1624
+ # NOTE: assuming batch dim is 0
1625
+ idx_batch_size = restore_indices.size(0)
1626
+ data_batch_size = unsharded_b.size(0)
1627
+ if idx_batch_size != 1 and idx_batch_size != data_batch_size:
1628
+ raise ValueError(
1629
+ "Cannot restore buffer: "
1630
+ f"restore_indices has shape {restore_indices.shape}, "
1631
+ f"but unsharded_b has shape {unsharded_b.shape}."
1632
+ )
1633
+
1634
+ for i in range(data_batch_size):
1635
+ index = (
1636
+ restore_indices[0] # identical load-balance in batch
1637
+ if idx_batch_size == 1
1638
+ else restore_indices[i]
1639
+ )
1640
+ unsharded_b_batch_i = torch.index_select(
1641
+ unsharded_b[i], dim=dim - 1, index=index
1642
+ )
1643
+ unsharded_b[i] = unsharded_b_batch_i
1644
+
1645
+ unsharded_buffers.append(unsharded_b)
1646
+
1647
+ return unsharded_buffers
1648
+
1649
+
1650
+ def set_rotate_method(rotate_method: str) -> None:
1651
+ """
1652
+ Context Parallel SDPA requires the rotation of kv shards. Users can call this
1653
+ API to specify which rotation method to use. "alltoall" shuffles the kv shards
1654
+ using all-to-all collective. While "allgather" gathers the kv shards using
1655
+ all-gather collective after the first sub-SDPA computation. If this API has not
1656
+ been called, the default rotate method is "allgather".
1657
+
1658
+ Args:
1659
+ rotate_method (str): the rotate method to use. Currently only supports
1660
+ "allgather" and "alltoall". If a different string other than these two
1661
+ is passed in, the function will raise an error.
1662
+
1663
+ Returns:
1664
+ None
1665
+ """
1666
+ logger.info("Note that FlexAttention CP doesn't support alltoall yet.")
1667
+ if rotate_method == "allgather":
1668
+ _cp_options.rotate_method = _RotateMethod.ALL_GATHER
1669
+ elif rotate_method == "alltoall":
1670
+ _cp_options.rotate_method = _RotateMethod.ALL_TO_ALL
1671
+ else:
1672
+ raise NotImplementedError(
1673
+ "Context Parallel does not support "
1674
+ f"using {rotate_method} for kv shards rotation"
1675
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_context_parallel/_cp_custom_ops.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ import torch
4
+ import torch.distributed._functional_collectives as funcol
5
+ import torch.distributed.distributed_c10d as c10d
6
+
7
+
8
+ @torch.library.custom_op("cplib::flex_cp_allgather", mutates_args=())
9
+ def flex_cp_allgather(
10
+ k: torch.Tensor, v: torch.Tensor, seq_dim: int, pg_name: c10d.GroupName
11
+ ) -> tuple[torch.Tensor, torch.Tensor]:
12
+ k = k.contiguous()
13
+ v = v.contiguous()
14
+ k = funcol.all_gather_tensor(k, seq_dim, pg_name)
15
+ v = funcol.all_gather_tensor(v, seq_dim, pg_name)
16
+ if isinstance(k, funcol.AsyncCollectiveTensor):
17
+ k = k.wait()
18
+ if isinstance(v, funcol.AsyncCollectiveTensor):
19
+ v = v.wait()
20
+ return k, v
21
+
22
+
23
+ @flex_cp_allgather.register_fake
24
+ def _(
25
+ k: torch.Tensor, v: torch.Tensor, seq_dim: int, pg_name: c10d.GroupName
26
+ ) -> tuple[torch.Tensor, torch.Tensor]:
27
+ shape_k = list(k.shape)
28
+ shape_v = list(v.shape)
29
+ shape_k[seq_dim] *= c10d._get_group_size_by_name(pg_name)
30
+ shape_v[seq_dim] *= c10d._get_group_size_by_name(pg_name)
31
+ new_k = torch.empty(shape_k, dtype=k.dtype, device=k.device)
32
+ new_v = torch.empty(shape_v, dtype=v.dtype, device=v.device)
33
+ return new_k, new_v
34
+
35
+
36
+ @torch.library.custom_op("cplib::flex_cp_allgather_backward", mutates_args=())
37
+ def flex_cp_allgather_backward(
38
+ grad_full_k: torch.Tensor,
39
+ grad_full_v: torch.Tensor,
40
+ seq_dim: int,
41
+ pg_name: c10d.GroupName,
42
+ ) -> tuple[torch.Tensor, torch.Tensor]:
43
+ grad_k = funcol.reduce_scatter_tensor(grad_full_k, "sum", seq_dim, pg_name)
44
+ if isinstance(grad_k, funcol.AsyncCollectiveTensor):
45
+ grad_k = grad_k.wait()
46
+ grad_v = funcol.reduce_scatter_tensor(grad_full_v, "sum", seq_dim, pg_name)
47
+ if isinstance(grad_v, funcol.AsyncCollectiveTensor):
48
+ grad_v = grad_v.wait()
49
+
50
+ return grad_k, grad_v
51
+
52
+
53
+ @flex_cp_allgather_backward.register_fake
54
+ def _(
55
+ grad_full_k: torch.Tensor,
56
+ grad_full_v: torch.Tensor,
57
+ seq_dim: int,
58
+ pg_name: c10d.GroupName,
59
+ ) -> tuple[torch.Tensor, torch.Tensor]:
60
+ shape_k = list(grad_full_k.shape)
61
+ shape_v = list(grad_full_v.shape)
62
+ shape_k[seq_dim] //= c10d._get_group_size_by_name(pg_name)
63
+ shape_v[seq_dim] //= c10d._get_group_size_by_name(pg_name)
64
+ new_grad_k = torch.empty(
65
+ shape_k, dtype=grad_full_k.dtype, device=grad_full_k.device
66
+ )
67
+ new_grad_v = torch.empty(
68
+ shape_v, dtype=grad_full_v.dtype, device=grad_full_v.device
69
+ )
70
+ return new_grad_k, new_grad_v
71
+
72
+
73
+ def _flex_cp_allgather_backward(
74
+ ctx: Any, grad_full_k: torch.Tensor, grad_full_v: torch.Tensor
75
+ ) -> tuple[torch.Tensor, torch.Tensor, None, None]:
76
+ grad_k, grad_v = flex_cp_allgather_backward(
77
+ grad_full_k, grad_full_v, ctx.seq_dim, ctx.pg_name
78
+ )
79
+ return grad_k, grad_v, None, None
80
+
81
+
82
+ def _flex_cp_setup_context(ctx: Any, inputs: Any, output: Any) -> None:
83
+ _, _, ctx.seq_dim, ctx.pg_name = inputs
84
+
85
+
86
+ flex_cp_allgather.register_autograd(
87
+ _flex_cp_allgather_backward, setup_context=_flex_cp_setup_context
88
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_context_parallel/_load_balancer.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # this file contains the `_LoadBalancer` class and its family of implementation
2
+ # for different load-balancing strategies in tensor sharding.
3
+ import functools
4
+ from abc import ABC, abstractmethod
5
+
6
+ import torch
7
+ from torch import Tensor
8
+ from torch.nn.attention.flex_attention import BlockMask
9
+
10
+
11
+ # make it private since it's still a prototype
12
+ class _LoadBalancer(ABC):
13
+ @abstractmethod
14
+ def _generate_indices(self, restore: bool = False) -> Tensor | None:
15
+ """
16
+ Generate indices for load balancing.
17
+ Args:
18
+ restore (bool):
19
+
20
+ Returns:
21
+ The generated indices of shape `(1, seq_len)` if the load-balancing is
22
+ identical within the batch, or `(batch_size, seq_len)` if the load-balancing
23
+ should vary within the batch.
24
+
25
+ Warning:
26
+ For Multi-Head Attention, we require the masks over the head dimension are identical
27
+ (i.e. the return value of `_generate_indices()` does not have `heads` dimension).
28
+
29
+ Example:
30
+ Here is the causal mask for attention where q_len == kv_len == 8:
31
+ KV_index
32
+ [1, 0, 0, 0, 0, 0, 0, 0]
33
+ [1, 1, 0, 0, 0, 0, 0, 0]
34
+ [1, 1, 1, 0, 0, 0, 0, 0]
35
+ Q_index [1, 1, 1, 1, 0, 0, 0, 0]
36
+ [1, 1, 1, 1, 1, 0, 0, 0]
37
+ [1, 1, 1, 1, 1, 1, 0, 0]
38
+ [1, 1, 1, 1, 1, 1, 1, 0]
39
+ [1, 1, 1, 1, 1, 1, 1, 1]
40
+
41
+ This mask matrix also represents the computation required to compute
42
+ the masked Q @ K^T by:
43
+ - mask[i, j] == 1: the computation of Q[i, :] dot K[j, :] is required
44
+ - mask[i, j] == 0: the computation should be skipped
45
+
46
+ Therefore the number of 1s in matrix represents the amount of computation
47
+ required.
48
+
49
+ Assume we want to distribute this Q @ K^T computation to 2 devices, then
50
+ the matrix is also distributed as:
51
+ KV_index
52
+ [1, 0, 0, 0, 0, 0, 0, 0]
53
+ [1, 1, 0, 0, 0, 0, 0, 0]
54
+ [1, 1, 1, 0, 0, 0, 0, 0] rank 0
55
+ [1, 1, 1, 1, 0, 0, 0, 0]
56
+ Q_index ------------------------
57
+ [1, 1, 1, 1, 1, 0, 0, 0]
58
+ [1, 1, 1, 1, 1, 1, 0, 0] rank 1
59
+ [1, 1, 1, 1, 1, 1, 1, 0]
60
+ [1, 1, 1, 1, 1, 1, 1, 1]
61
+
62
+ An imbalance of computation is observed on these 2 ranks and this could make
63
+ rank 1 the straggler when performing Context Parallel. In order to balance
64
+ the computation, we need to rearrange the QKV tensors before sharding in such a
65
+ way that the result mask matrix is evenly distributed over devices and each
66
+ rank has the number of 1s as close as possible.
67
+
68
+ This method defines the strategy of how to rearrange the QKV tensor for better
69
+ load-balance:
70
+ - when `restore == False`, this method returns an indices tensor `rearrange_idx`
71
+ such that Q[rearrange_idx] is the desired Q tensor after rearranging.
72
+ - when `restore == True`, this method returns an indices tensor `restore_idx`
73
+ such that Q[rearrange_idx][restore_idx] == Q, i.e. restoring the rearranged tensor
74
+ back to the original status before rearranging.
75
+ """
76
+
77
+
78
+ class _HeadTailLoadBalancer(_LoadBalancer):
79
+ def __init__(self, seq_length: int, world_size: int, device: str | torch.device):
80
+ self.seq_length = seq_length
81
+ self.world_size = world_size
82
+ self.device = device
83
+
84
+ def _generate_indices(self, restore: bool = False) -> Tensor:
85
+ """
86
+ Generate head-and-tail load balancing indices or restore indices.
87
+ Args:
88
+ restore:
89
+ If True, generate restore indices that map head-and-tail rearranged
90
+ positions back to original positions. If False, generate load
91
+ balance indices that rearrange original positions to head-and-tail pattern.
92
+
93
+ Returns:
94
+ The generated indices of shape `(1, seq_len)` because the load-balancing is
95
+ identical within the batch.
96
+
97
+ Warning:
98
+ For Multi-Head Attention, we require the masks over the head dimension are identical
99
+ (i.e. the return value of `_generate_indices()` does not have `heads` dimension).
100
+
101
+ Example:
102
+ Here is the causal mask for attention where q_len == kv_len == 8:
103
+ KV_index
104
+ [1, 0, 0, 0, 0, 0, 0, 0]
105
+ [1, 1, 0, 0, 0, 0, 0, 0]
106
+ [1, 1, 1, 0, 0, 0, 0, 0]
107
+ Q_index [1, 1, 1, 1, 0, 0, 0, 0]
108
+ [1, 1, 1, 1, 1, 0, 0, 0]
109
+ [1, 1, 1, 1, 1, 1, 0, 0]
110
+ [1, 1, 1, 1, 1, 1, 1, 0]
111
+ [1, 1, 1, 1, 1, 1, 1, 1]
112
+
113
+ Head-tail load-balance strategy rearranges the Q tensor by combining
114
+ Q[0:k] (on seq dim) and Q[-k:] for rank 0, Q[k:2k] and Q[-2k:-k] for
115
+ rank 1, and so on. In python code it looks like:
116
+
117
+ k = Q.size(0) // (2 * cp_world_size)
118
+ for rank in range(cp_world_size):
119
+ reordered_Q[rank * 2 * k : (rank + 1) * 2 * k] = torch.cat(
120
+ (Q[rank * k : (rank + 1) * k], Q[-(rank + 1) * k : -rank * k])
121
+ )
122
+
123
+ This can also be done by tensor slicing. For the above example, the indices
124
+ tensor for slicing is:
125
+ slice_indices = Tensor([0, 7, 1, 6, 2, 5, 3, 4])
126
+
127
+ After reordering QKV using the `slice_indices`, the corresponding mask matrix
128
+ distributing over 2 devices becomes well-balanced:
129
+ KV_index
130
+ [1, 0, 0, 0, 0, 0, 0, 0]
131
+ [1, 1, 1, 1, 1, 1, 1, 1]
132
+ [1, 1, 0, 0, 0, 0, 0, 0] rank 0
133
+ [1, 1, 1, 1, 1, 1, 1, 0]
134
+ Q_index ------------------------
135
+ [1, 1, 1, 0, 0, 0, 0, 0]
136
+ [1, 1, 1, 1, 1, 1, 0, 0] rank 1
137
+ [1, 1, 1, 1, 0, 0, 0, 0]
138
+ [1, 1, 1, 1, 1, 0, 0, 0]
139
+
140
+ To restore the reordering and putting the tensor back, slicing op can do the
141
+ trick with a `restore_indices` such that:
142
+ slice_indices[restore_indices] == Tensor([0, 1, 2, ...])
143
+
144
+ In this way, `reordered_Q[restore_indices]` will just be the original Q.
145
+ """
146
+ seq_length = self.seq_length
147
+ world_size = self.world_size
148
+ assert seq_length % (world_size * 2) == 0
149
+ chunk_size = seq_length // (world_size * 2)
150
+ all_indices = []
151
+
152
+ for rank in range(world_size):
153
+ # Generate indices for first chunk of the cp rank
154
+ first_chunk_start = rank * chunk_size
155
+ first_chunk_indices = list(
156
+ range(first_chunk_start, first_chunk_start + chunk_size)
157
+ )
158
+
159
+ # Second chunk: positions from the complementary chunk
160
+ second_chunk_idx = world_size * 2 - rank - 1
161
+ second_chunk_start = second_chunk_idx * chunk_size
162
+ second_chunk_indices = list(
163
+ range(second_chunk_start, second_chunk_start + chunk_size)
164
+ )
165
+ # combine the indices for this rank
166
+ all_indices.extend(first_chunk_indices + second_chunk_indices)
167
+
168
+ all_indices_tensor = torch.tensor(
169
+ all_indices, dtype=torch.int, device=self.device
170
+ )
171
+ if restore:
172
+ all_indices_tensor = torch.argsort(all_indices_tensor)
173
+
174
+ return all_indices_tensor.unsqueeze(0) # add batch dim
175
+
176
+
177
+ class _PerDocumentHeadTailLoadBalancer(_LoadBalancer):
178
+ def __init__(
179
+ self,
180
+ seq_length_per_doc: list[list[int]],
181
+ world_size: int,
182
+ device: str | torch.device,
183
+ ):
184
+ """
185
+ `seq_length_per_doc` has size (B, seq_len) if the load-balancing should vary
186
+ within the batch. Otherwise `seq_length_per_doc` should have size (1, seq_len).
187
+ """
188
+ self.seq_length_per_doc = seq_length_per_doc
189
+ self.world_size = world_size
190
+ self.device = device
191
+
192
+ def _generate_indices(self, restore: bool = False) -> Tensor:
193
+ """
194
+ Generate the per-document head-and-tail rearrange indices so that after rearranging
195
+ the input is load-balanced in per-document head-and-tail style.
196
+
197
+ Args:
198
+ restore:
199
+ If True, generate restore indices that map per-document head-and-tail
200
+ rearranged positions back to original positions. If False, generate load
201
+ balance indices that rearrange original positions to per-document
202
+ head-and-tail pattern.
203
+
204
+ Returns:
205
+ The generated indices of shape `(batch_size, seq_len)` if the load-balancing
206
+ should vary within the batch. Otherwise, it should have shape `(1, seq_len)`.
207
+
208
+ Warning:
209
+ For Multi-Head Attention, we require the masks over the head dimension are identical
210
+ (i.e. `seq_length_per_doc` must have size (B, seq_len) or (1, seq_len)).
211
+
212
+ Example:
213
+ Here is the document causal mask for attention where q_len == kv_len == 16:
214
+ KV_index
215
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
216
+ [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
217
+ [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
218
+ [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
219
+ [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
220
+ [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
221
+ [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
222
+ Q_index [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
223
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
224
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
225
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
226
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
227
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
228
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0]
229
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0]
230
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
231
+
232
+ The per-document head-and-tail load-balancer will apply head-and-tail
233
+ reordering within each document. After load-balancing for context-parallel
234
+ on 2 devices, the above mask matrix will look like this:
235
+ KV_index
236
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
237
+ [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
238
+ [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
239
+ [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
240
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
241
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
242
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
243
+ Q_index [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
244
+ ------------------------------------------------
245
+ [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
246
+ [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
247
+ [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
248
+ [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
249
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
250
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
251
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0]
252
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0]
253
+ """
254
+ return torch.stack(
255
+ [
256
+ self._generate_indices_for_batch(seq_lengths, restore)
257
+ for seq_lengths in self.seq_length_per_doc
258
+ ]
259
+ )
260
+
261
+ def _generate_indices_for_batch(self, seq_length_per_doc, restore) -> Tensor: # type: ignore[no-untyped-def]
262
+ world_size = self.world_size
263
+ device = self.device
264
+ assert all(
265
+ seq_length % (2 * world_size) == 0 for seq_length in seq_length_per_doc
266
+ )
267
+ chunk_length_per_doc = [
268
+ seq_length // (2 * world_size) for seq_length in seq_length_per_doc
269
+ ]
270
+
271
+ indices = []
272
+ document_start_idx = 0
273
+ for seq_length, chunk_length in zip(seq_length_per_doc, chunk_length_per_doc):
274
+ # Generate the indices for the current document
275
+ for rank in range(world_size):
276
+ head_chunk_start_idx = document_start_idx + chunk_length * rank
277
+ tail_chunk_end_idx = document_start_idx + chunk_length * (
278
+ 2 * world_size - rank
279
+ )
280
+ indices.append(
281
+ torch.arange(
282
+ head_chunk_start_idx,
283
+ head_chunk_start_idx + chunk_length,
284
+ device=device,
285
+ )
286
+ )
287
+ indices.append(
288
+ torch.arange(
289
+ tail_chunk_end_idx - chunk_length,
290
+ tail_chunk_end_idx,
291
+ device=device,
292
+ )
293
+ )
294
+
295
+ document_start_idx += seq_length
296
+
297
+ indices_tensor = torch.cat(indices)
298
+ if restore:
299
+ indices_tensor = torch.argsort(indices_tensor)
300
+
301
+ return indices_tensor
302
+
303
+
304
+ class _PTRRLoadBalancer(_LoadBalancer):
305
+ """
306
+ Processing-Time based Round-Robin (PTRR) load balancer. This load balancer should
307
+ only be used for flex_attention() since it leverages `BlockMask`.
308
+ """
309
+
310
+ def __init__(
311
+ self,
312
+ block_mask: BlockMask,
313
+ world_size: int,
314
+ ):
315
+ """
316
+ `block_mask` must have shape (B, 1, seq_len, seq_len) or (1, 1, seq_len, seq_len).
317
+ """
318
+ self.block_mask = block_mask
319
+ self.world_size = world_size
320
+
321
+ @staticmethod
322
+ def ptrr_scheduling(process_time: Tensor, group_size: int) -> Tensor:
323
+ """
324
+ Separate the tasks into `group_size` groups using PTRR scheduling.
325
+ process_time:
326
+ 1D tensor of size n, where n is the number of tasks. The value
327
+ is the process time of the task. Size `n` must be divisible by
328
+ `group_size`.
329
+ group_size:
330
+ the number of groups
331
+
332
+ Returns:
333
+ tasks_in_group (list[list[int]]):
334
+ A collection of list[int] and each list should have size `n // group_size`
335
+ (`group_size` lists in total). Each element is an index in the input
336
+ `process_time` (i.e. [0, len(process_time) - 1]).
337
+
338
+ Example:
339
+ process_time = [9, 14, 2, 20, 10, 15, 8, 14, 16, 19, 15, 3, 12, 1, 12, 10]
340
+ tasks_in_group = [
341
+ [3, 12, 13, 14], # values = [1, 12, 12, 20], sum = 45
342
+ [2, 4, 7, 9], # values = [2, 10, 14, 19], sum = 45
343
+ [1, 8, 11, 15], # values = [14, 16, 3, 10], sum = 43
344
+ [0, 5, 6, 10] # values = [9, 15, 8, 15], sum = 47
345
+ ]
346
+ """
347
+ assert process_time.ndim == 1
348
+
349
+ num_tasks = process_time.size(0)
350
+
351
+ if num_tasks % group_size != 0:
352
+ raise NotImplementedError(
353
+ f"num_tasks {num_tasks} must be divisible by group_size {group_size}"
354
+ )
355
+
356
+ device = process_time.device
357
+ _, sorted_indices_descending = torch.sort(
358
+ process_time, descending=True, stable=True
359
+ ) # if process time is tied, the order is preserved
360
+ sorted_indices_descending_reversed = torch.flip(
361
+ sorted_indices_descending.view(-1, group_size), dims=[1]
362
+ ).view(-1)
363
+ tasks_in_group = torch.where(
364
+ torch.arange(num_tasks, device=device) // group_size % 2 == 0,
365
+ sorted_indices_descending,
366
+ sorted_indices_descending_reversed,
367
+ )
368
+ tasks_in_group = tasks_in_group.view(-1, group_size).transpose(
369
+ 0, 1
370
+ ) # (group_size, n // group_size)
371
+
372
+ # sort each group. This step should not have impact on correctness
373
+ # nor execution run time, but it helps users visualize the mask
374
+ tasks_in_group, _ = torch.sort(tasks_in_group, dim=1)
375
+ return tasks_in_group
376
+
377
+ def _generate_indices(self, restore: bool = False) -> Tensor:
378
+ """
379
+ Generate the PTRR reorder indices of shape `(1, seq_len)` or `(batch_size, seq_len)`.
380
+
381
+ Args:
382
+ restore:
383
+ If True, generate restore indices that map Processing-Time based Round-Robin
384
+ (PTRR) rearranged positions back to original positions. If False, generate
385
+ load balance indices that rearrange original positions to PTRR pattern.
386
+
387
+ Returns:
388
+ The generated indices of shape `(1, seq_len)` if the load-balancing is
389
+ identical within the batch (i.e. `BlockMask.shape[0] == 1`), or
390
+ `(batch_size, seq_len)` if the load-balancing should vary within the batch.
391
+
392
+ Warning:
393
+ For Multi-Head Attention, we require the masks over the head dimension are identical
394
+ (i.e. `self.block_mask` must have shape (B, 1, seq_len, seq_len) or (1, 1, seq_len, seq_len)).
395
+
396
+ Example:
397
+ Here is the document causal mask for attention whereq_len == kv_len == 16 * BLOCK_SIZE
398
+ (each entry is a block):
399
+ KV_index
400
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 1
401
+ [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 2
402
+ [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 3
403
+ [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 4
404
+ [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 1
405
+ [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 2
406
+ [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 3
407
+ Q_index [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 4
408
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0] -> row value = 5
409
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0] -> row value = 6
410
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0] -> row value = 7
411
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0] -> row value = 8
412
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] -> row value = 1
413
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0] -> row value = 2
414
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0] -> row value = 3
415
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1] -> row value = 4
416
+
417
+ The reorder indices will be: [2, 3, 5, 6, 8, 11, 12, 13, 0, 1, 4, 7, 9, 10, 14, 15] and
418
+ the mask matrix will look like:
419
+ KV_index
420
+ [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 3
421
+ [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 4
422
+ [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 2
423
+ [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 3
424
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0] -> row value = 5 rank 0 (sum=28)
425
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0] -> row value = 8
426
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] -> row value = 1
427
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0] -> row value = 2
428
+ ------------------------------------------------
429
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 1
430
+ [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 2
431
+ [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 1
432
+ [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 4
433
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0] -> row value = 6 rank 1 (sum=28)
434
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0] -> row value = 7
435
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0] -> row value = 3
436
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1] -> row value = 4
437
+ """
438
+ block_mask = self.block_mask
439
+ kv_num_blocks = block_mask.kv_num_blocks
440
+ full_kv_num_blocks = block_mask.full_kv_num_blocks
441
+ non_sparse_kv_num_blocks = (
442
+ kv_num_blocks + full_kv_num_blocks
443
+ if full_kv_num_blocks is not None
444
+ else kv_num_blocks
445
+ )
446
+ B, H, Q = non_sparse_kv_num_blocks.shape
447
+ # requirement: the masking is identical across heads (i.e. H == 1 in BlockMask)
448
+ non_sparse_kv_num_blocks = non_sparse_kv_num_blocks.view(-1, Q) # (B, Q_BLK)
449
+
450
+ batch_ptrr = torch.vmap(
451
+ functools.partial(
452
+ _PTRRLoadBalancer.ptrr_scheduling,
453
+ group_size=self.world_size,
454
+ )
455
+ )
456
+ ptrr_indices = batch_ptrr(
457
+ non_sparse_kv_num_blocks
458
+ ) # (B, group_size, num_blks_in_group)
459
+ ptrr_indices = ptrr_indices.reshape(B, -1) # (B, num_blocks)
460
+
461
+ # NOTE: only support the case where the qkv block size are equal
462
+ q_blk_size, kv_blk_size = block_mask.BLOCK_SIZE
463
+ assert q_blk_size == kv_blk_size, (
464
+ "for now only support q_blk_size == kv_blk_size"
465
+ )
466
+
467
+ indices = torch.arange(
468
+ q_blk_size * ptrr_indices.size(1), device=ptrr_indices.device
469
+ ).view(-1, q_blk_size) # (NUM_BLOCKS, BLOCK_SIZE)
470
+ indices = indices[ptrr_indices].view(B, -1) # (B, qkv_size)
471
+
472
+ if restore:
473
+ indices = torch.vmap(torch.argsort)(indices)
474
+
475
+ return indices
476
+
477
+
478
+ def _create_default_load_balancer(
479
+ seq_length: int, world_size: int, device: str | torch.device
480
+ ) -> _LoadBalancer | None:
481
+ from ._attention import _cp_options
482
+
483
+ if _cp_options.enable_load_balance:
484
+ return _HeadTailLoadBalancer(seq_length, world_size, device)
485
+ else:
486
+ return None
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_context_parallel/_sharding_rules.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ """
3
+ Context Parallelism sharding rules for scaled_dot_product attention operators.
4
+
5
+ The sharding rules for CP cannot be embedded by default because Shard(2) is not
6
+ a valid sharding for SDPA without CP enabled. This module provides utilities to
7
+ dynamically install Shard(2) sharding rules when CP is activated.
8
+ """
9
+
10
+ from contextlib import contextmanager
11
+
12
+ import torch
13
+ from torch.distributed.tensor._op_schema import (
14
+ OpSchema,
15
+ OpStrategy,
16
+ PlacementList,
17
+ RuntimeSchemaInfo,
18
+ )
19
+ from torch.distributed.tensor._ops.registration import register_op_strategy
20
+ from torch.distributed.tensor._ops.utils import expand_to_full_mesh_op_strategy
21
+ from torch.distributed.tensor.debug import (
22
+ _clear_fast_path_sharding_prop_cache,
23
+ _clear_python_sharding_prop_cache,
24
+ )
25
+ from torch.distributed.tensor.placement_types import Replicate, Shard
26
+
27
+
28
+ aten = torch.ops.aten
29
+
30
+ SEQ_DIM = 2
31
+
32
+
33
+ @contextmanager
34
+ def _op_strategy_context(op_overload, strategy_func, schema_info=None):
35
+ """
36
+ Context manager for setting and clearing op strategies for Context Parallelism.
37
+
38
+ Args:
39
+ op_overload: The operator overload to set or clear the strategy for.
40
+ strategy_func: The strategy function to set for the operator overload.
41
+ schema_info: Optional schema information for the operator overload.
42
+
43
+ Yields:
44
+ None
45
+ """
46
+ from torch.distributed.tensor import DTensor
47
+
48
+ propagator = DTensor._op_dispatcher.sharding_propagator
49
+ _origin_op_strategy_funcs = None
50
+ _origin_op_strategy_schema = None
51
+ try:
52
+ # Save original strategy if exists
53
+ if op_overload in propagator.op_strategy_funcs:
54
+ _origin_op_strategy_funcs = propagator.op_strategy_funcs[op_overload]
55
+ if op_overload in propagator.op_to_schema_info:
56
+ _origin_op_strategy_schema = propagator.op_to_schema_info[op_overload]
57
+
58
+ # Register the new op strategy
59
+ register_op_strategy(op_overload, schema_info=schema_info)(strategy_func)
60
+ yield (_origin_op_strategy_funcs, _origin_op_strategy_schema)
61
+ finally:
62
+ # Restore original strategy
63
+ if _origin_op_strategy_funcs is None:
64
+ if op_overload in propagator.op_strategy_funcs:
65
+ del propagator.op_strategy_funcs[op_overload]
66
+ else:
67
+ propagator.op_strategy_funcs[op_overload] = _origin_op_strategy_funcs
68
+
69
+ if _origin_op_strategy_schema is None:
70
+ if op_overload in propagator.op_to_schema_info:
71
+ del propagator.op_to_schema_info[op_overload]
72
+ else:
73
+ propagator.op_to_schema_info[op_overload] = _origin_op_strategy_schema
74
+
75
+ # Ideally, we should clear the cache, but it is too expensive.
76
+ # _clear_python_sharding_prop_cache()
77
+ # _clear_fast_path_sharding_prop_cache()
78
+
79
+
80
+ # ==================== Flash Attention Strategies ====================
81
+
82
+
83
+ def _scaled_dot_product_flash_attention_cp_strategy(op_schema: OpSchema) -> OpStrategy:
84
+ """
85
+ Strategy for flash attention forward with Context Parallelism support.
86
+ This includes the base strategies plus CP-specific sequence dimension sharding.
87
+ """
88
+ # Import here to avoid circular dependency
89
+ from torch.distributed.tensor._ops._matrix_ops import (
90
+ _scaled_dot_product_flash_attention_base_strategies,
91
+ )
92
+
93
+ # Get the base strategies (without CP modifications)
94
+ mesh = op_schema.get_mesh_from_args()
95
+ single_mesh_dim_strategies = _scaled_dot_product_flash_attention_base_strategies(
96
+ op_schema
97
+ )
98
+
99
+ # Add Context Parallelism strategy: shards on the sequence dim
100
+ return_debug_mask = len(op_schema.args_schema) >= 6 and op_schema.args_schema[5]
101
+ debug_attn_mask_sharding = Shard(SEQ_DIM) if return_debug_mask else Replicate()
102
+
103
+ cp_strategy: PlacementList = [
104
+ Shard(SEQ_DIM), # output
105
+ Shard(SEQ_DIM), # logsumexp
106
+ None, # cum_seq_q
107
+ None, # cum_seq_k
108
+ None, # max_q
109
+ None, # max_k
110
+ Replicate(), # rng_state
111
+ None, # unused
112
+ debug_attn_mask_sharding, # debugattn
113
+ Shard(SEQ_DIM), # q
114
+ Shard(SEQ_DIM), # k
115
+ Shard(SEQ_DIM), # v
116
+ ]
117
+ single_mesh_dim_strategies.append(cp_strategy)
118
+
119
+ return expand_to_full_mesh_op_strategy(
120
+ mesh, op_schema, single_mesh_dim_strategies, input_index=9
121
+ )
122
+
123
+
124
+ def _scaled_dot_product_flash_attention_backward_cp_strategy(
125
+ op_schema: OpSchema,
126
+ ) -> OpStrategy:
127
+ """
128
+ Strategy for flash attention backward with Context Parallelism support.
129
+ """
130
+ from torch.distributed.tensor._ops._matrix_ops import (
131
+ _scaled_dot_product_flash_attention_backward_base_strategies,
132
+ )
133
+
134
+ mesh = op_schema.get_mesh_from_args(validate=False)
135
+ single_mesh_dim_strategies = (
136
+ _scaled_dot_product_flash_attention_backward_base_strategies(op_schema)
137
+ )
138
+
139
+ tensor_input_indices = [
140
+ i
141
+ for i, arg_spec in enumerate(op_schema.args_schema)
142
+ if isinstance(arg_spec, OpStrategy)
143
+ ]
144
+ num_tensor_inputs = len(tensor_input_indices)
145
+
146
+ # Context Parallelism: shards on the sequence dim
147
+ cp_strategy: PlacementList = [
148
+ Shard(SEQ_DIM), # grad_q
149
+ Shard(SEQ_DIM), # grad_k
150
+ Shard(SEQ_DIM), # grad_v
151
+ Shard(SEQ_DIM), # grad_output
152
+ Shard(SEQ_DIM), # q
153
+ Shard(SEQ_DIM), # k
154
+ Shard(SEQ_DIM), # v
155
+ Shard(SEQ_DIM), # output
156
+ Shard(SEQ_DIM), # logsumexp
157
+ ]
158
+ cp_strategy.extend([Replicate()] * (num_tensor_inputs - 6))
159
+ single_mesh_dim_strategies.append(cp_strategy)
160
+
161
+ return expand_to_full_mesh_op_strategy(
162
+ mesh, op_schema, single_mesh_dim_strategies, input_index=3
163
+ )
164
+
165
+
166
+ # ==================== Efficient Attention Strategies ====================
167
+
168
+
169
+ def _scaled_dot_product_efficient_attention_cp_strategy(
170
+ op_schema: OpSchema,
171
+ ) -> OpStrategy:
172
+ """
173
+ Strategy for efficient attention forward with Context Parallelism support.
174
+ """
175
+ from torch.distributed.tensor._ops._matrix_ops import (
176
+ _scaled_dot_product_efficient_attention_base_strategies,
177
+ )
178
+
179
+ mesh = op_schema.get_mesh_from_args()
180
+ single_mesh_dim_strategies = (
181
+ _scaled_dot_product_efficient_attention_base_strategies(op_schema)
182
+ )
183
+
184
+ # Add Context Parallelism strategy
185
+ has_attn_bias = op_schema.args_schema[3] is not None
186
+
187
+ cp_strategy: PlacementList = [
188
+ Shard(SEQ_DIM), # output
189
+ Shard(SEQ_DIM), # logsumexp
190
+ None, # philox_seed
191
+ None, # philox_offset
192
+ Shard(SEQ_DIM), # q
193
+ Shard(SEQ_DIM), # k
194
+ Shard(SEQ_DIM), # v
195
+ ]
196
+ if has_attn_bias:
197
+ cp_strategy.append(Replicate()) # attn bias - not sharded for CP
198
+ single_mesh_dim_strategies.append(cp_strategy)
199
+
200
+ return expand_to_full_mesh_op_strategy(
201
+ mesh, op_schema, single_mesh_dim_strategies, input_index=4
202
+ )
203
+
204
+
205
+ def _scaled_dot_product_efficient_attention_backward_cp_strategy(
206
+ op_schema: OpSchema,
207
+ ) -> OpStrategy:
208
+ """
209
+ Strategy for efficient attention backward with Context Parallelism support.
210
+ """
211
+ from torch.distributed.tensor._ops._matrix_ops import (
212
+ _scaled_dot_product_efficient_attention_backward_base_strategies,
213
+ )
214
+
215
+ mesh = op_schema.get_mesh_from_args(validate=False)
216
+ single_mesh_dim_strategies = (
217
+ _scaled_dot_product_efficient_attention_backward_base_strategies(op_schema)
218
+ )
219
+
220
+ has_attn_bias = op_schema.args_schema[4] is not None
221
+
222
+ # Context Parallelism: shards on the sequence dim
223
+ cp_strategy: PlacementList = [
224
+ Shard(SEQ_DIM), # grad_q
225
+ Shard(SEQ_DIM), # grad_k
226
+ Shard(SEQ_DIM), # grad_v
227
+ Shard(1) if has_attn_bias else None, # grad_bias
228
+ Shard(SEQ_DIM), # grad_output
229
+ Shard(SEQ_DIM), # q
230
+ Shard(SEQ_DIM), # k
231
+ Shard(SEQ_DIM), # v
232
+ Shard(SEQ_DIM), # output
233
+ Shard(SEQ_DIM), # logsumexp
234
+ ]
235
+ if has_attn_bias:
236
+ cp_strategy.insert(8, Shard(1)) # attn_bias input
237
+ cp_strategy.extend([Replicate(), Replicate()])
238
+ single_mesh_dim_strategies.append(cp_strategy)
239
+
240
+ return expand_to_full_mesh_op_strategy(
241
+ mesh, op_schema, single_mesh_dim_strategies, input_index=4
242
+ )
243
+
244
+
245
+ # ==================== cuDNN Attention Strategies ====================
246
+
247
+
248
+ def _scaled_dot_product_cudnn_attention_cp_strategy(op_schema: OpSchema) -> OpStrategy:
249
+ """
250
+ Strategy for cudnn attention forward with Context Parallelism support.
251
+ """
252
+ from torch.distributed.tensor._ops._matrix_ops import (
253
+ _scaled_dot_product_cudnn_attention_base_strategies,
254
+ )
255
+
256
+ mesh = op_schema.get_mesh_from_args()
257
+ single_mesh_dim_strategies = _scaled_dot_product_cudnn_attention_base_strategies(
258
+ op_schema
259
+ )
260
+
261
+ (
262
+ query_strategy,
263
+ _,
264
+ _,
265
+ attn_bias_strategy,
266
+ compute_log_sumexp,
267
+ *rest_args,
268
+ ) = op_schema.args_schema
269
+ return_debug_mask = len(op_schema.args_schema) >= 8 and rest_args[2]
270
+ has_attn_bias = attn_bias_strategy is not None
271
+
272
+ # Context Parallelism: shards on the sequence dim
273
+ logsumexp_sharding = Shard(SEQ_DIM) if compute_log_sumexp else Replicate()
274
+ debug_attn_mask_sharding = Shard(SEQ_DIM) if return_debug_mask else None
275
+
276
+ cp_strategy: PlacementList = [
277
+ Shard(SEQ_DIM), # output
278
+ logsumexp_sharding, # logsumexp
279
+ None, # cum_seq_q
280
+ None, # cum_seq_k
281
+ None, # max_q
282
+ None, # max_k
283
+ None, # philox_seed
284
+ None, # philox_offset
285
+ debug_attn_mask_sharding, # debug_attn_mask
286
+ Shard(SEQ_DIM), # q
287
+ Shard(SEQ_DIM), # k
288
+ Shard(SEQ_DIM), # v
289
+ ]
290
+ if has_attn_bias:
291
+ cp_strategy.append(Replicate()) # attn_bias - not sharded for CP
292
+ single_mesh_dim_strategies.append(cp_strategy)
293
+
294
+ return expand_to_full_mesh_op_strategy(
295
+ mesh, op_schema, single_mesh_dim_strategies, input_index=9
296
+ )
297
+
298
+
299
+ def _scaled_dot_product_cudnn_attention_backward_cp_strategy(
300
+ op_schema: OpSchema,
301
+ ) -> OpStrategy:
302
+ """
303
+ Strategy for cudnn attention backward with Context Parallelism support.
304
+ """
305
+ from torch.distributed.tensor._ops._matrix_ops import (
306
+ _scaled_dot_product_cudnn_attention_backward_base_strategies,
307
+ )
308
+
309
+ mesh = op_schema.get_mesh_from_args(validate=False)
310
+ single_mesh_dim_strategies = (
311
+ _scaled_dot_product_cudnn_attention_backward_base_strategies(op_schema)
312
+ )
313
+
314
+ has_attn_bias = op_schema.args_schema[8] is not None
315
+ has_scale = len(op_schema.args_schema) >= 16 and False
316
+
317
+ # Context Parallelism: shards on the sequence dim
318
+ cp_sharding_gout: PlacementList = [Shard(SEQ_DIM)] * 3 # grad_q, grad_k, grad_v
319
+ cp_sharding_ginp: PlacementList = [
320
+ Shard(SEQ_DIM)
321
+ ] * 6 # grad_output, q, k, v, output, logsumexp
322
+ cp_sharding_ginp += [Replicate()] * 2 # philox_seed, philox_offset
323
+ cp_sharding_ginp += [Shard(SEQ_DIM) if has_attn_bias else None] # attn_bias
324
+ cp_sharding_ginp += [
325
+ None
326
+ ] * 6 # cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal
327
+ if has_scale:
328
+ cp_sharding_ginp.append(None)
329
+
330
+ cp_sharding = cp_sharding_gout + cp_sharding_ginp
331
+ single_mesh_dim_strategies.append(cp_sharding)
332
+
333
+ return expand_to_full_mesh_op_strategy(
334
+ mesh, op_schema, single_mesh_dim_strategies, input_index=3
335
+ )
336
+
337
+
338
+ # Store context managers and original strategies
339
+ _cp_strategy_contexts = {}
340
+ _original_strategies = {}
341
+
342
+
343
+ def register_cp_sharding_rules():
344
+ """Register Context Parallelism sharding rules for all scaled_dot_product ops."""
345
+ global _cp_strategy_contexts, _original_strategies
346
+
347
+ # If already registered, don't register again
348
+ if _cp_strategy_contexts:
349
+ return
350
+
351
+ # Define ops and their corresponding CP strategy functions
352
+ cp_strategies = [
353
+ (
354
+ aten._scaled_dot_product_flash_attention.default,
355
+ _scaled_dot_product_flash_attention_cp_strategy,
356
+ RuntimeSchemaInfo(5),
357
+ ),
358
+ (
359
+ aten._scaled_dot_product_flash_attention_backward.default,
360
+ _scaled_dot_product_flash_attention_backward_cp_strategy,
361
+ None,
362
+ ),
363
+ (
364
+ aten._scaled_dot_product_efficient_attention.default,
365
+ _scaled_dot_product_efficient_attention_cp_strategy,
366
+ RuntimeSchemaInfo(4),
367
+ ),
368
+ (
369
+ aten._scaled_dot_product_efficient_attention_backward.default,
370
+ _scaled_dot_product_efficient_attention_backward_cp_strategy,
371
+ None,
372
+ ),
373
+ (
374
+ aten._scaled_dot_product_cudnn_attention.default,
375
+ _scaled_dot_product_cudnn_attention_cp_strategy,
376
+ RuntimeSchemaInfo(4),
377
+ ),
378
+ (
379
+ aten._scaled_dot_product_cudnn_attention_backward.default,
380
+ _scaled_dot_product_cudnn_attention_backward_cp_strategy,
381
+ None,
382
+ ),
383
+ ]
384
+
385
+ # Register each strategy
386
+ for op_overload, strategy_func, schema_info in cp_strategies:
387
+ ctx = _op_strategy_context(op_overload, strategy_func, schema_info)
388
+ orig_funcs, orig_schema = ctx.__enter__()
389
+ _cp_strategy_contexts[op_overload] = ctx
390
+ _original_strategies[op_overload] = (orig_funcs, orig_schema)
391
+
392
+
393
+ def unregister_cp_sharding_rules(clear_the_cache=False):
394
+ """Unregister Context Parallelism sharding rules and restore original strategies."""
395
+ global _cp_strategy_contexts, _original_strategies
396
+
397
+ # Exit all context managers
398
+ for ctx in _cp_strategy_contexts.values():
399
+ ctx.__exit__(None, None, None)
400
+
401
+ if clear_the_cache:
402
+ _clear_fast_path_sharding_prop_cache()
403
+ _clear_python_sharding_prop_cache()
404
+
405
+ _cp_strategy_contexts = {}
406
+ _original_strategies = {}
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_func_map.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+ import functools
4
+ from collections.abc import Callable, Sequence
5
+ from typing import Optional, Union
6
+
7
+ import torch
8
+ from torch.distributed._functional_collectives import AsyncCollectiveTensor
9
+ from torch.distributed.tensor import DeviceMesh, DTensor
10
+ from torch.distributed.tensor.placement_types import Placement
11
+
12
+
13
+ try:
14
+ from torch.utils import _cxx_pytree as pytree
15
+ except ImportError:
16
+ from torch.utils import _pytree as pytree # type: ignore[no-redef]
17
+
18
+
19
+ __all__ = ["local_map"]
20
+
21
+ PlacementType = Optional[Sequence[Placement]]
22
+ InputPlacements = Optional[tuple[PlacementType, ...]]
23
+ OutputPlacements = Union[PlacementType, tuple[PlacementType, ...]]
24
+
25
+
26
+ def local_map(
27
+ func: Callable | None = None,
28
+ out_placements: OutputPlacements = None,
29
+ in_placements: InputPlacements = None,
30
+ in_grad_placements: InputPlacements = None,
31
+ device_mesh: DeviceMesh | None = None,
32
+ *,
33
+ redistribute_inputs: bool = False,
34
+ ):
35
+ """
36
+ :meth:`local_map` is an experimental API that allows users to pass :class:`DTensor` s
37
+ to a function that is written to be applied on ``torch.Tensor`` s. It is done by extracting
38
+ the local components of :class:`DTensor`, call the function, and wrap the outputs to
39
+ :class:`DTensor` according to the ``out_placements``.
40
+
41
+ Args:
42
+ func (Callable): the function to be applied on each local shard of
43
+ :class:`DTensor` s.
44
+ out_placements (Union[`PlacementType`, Tuple[`PlacementType`, ...]]):
45
+ the desired placements of the :class:`DTensor` s in ``func``'s flattened output.
46
+ If the flattened ``output`` is a single value, the ``out_placements`` should be
47
+ of type `PlacementType`. Otherwise if the flattened ``output`` has multiple
48
+ values, the ``out_placements`` should be a tuple of `PlacementType` values 1:1
49
+ mapping to the flattened ``output``.
50
+ Besides, for :class:`Tensor` output, we use `PlacementType` as its
51
+ placements (a `Tuple[Placement]` value). For non-Tensor output, the `PlacementType`
52
+ should be `None`.
53
+ Note that the only exception is when no :class:`DTensor` argument is passed
54
+ in. In this case, even if `out_placements` is not `None`, the result function
55
+ should ignore the desired placements because the function is not running with
56
+ :class:`DTensor` s.
57
+ in_placements (Tuple[`PlacementType`, ...], optional):
58
+ the required placements of the :class:`DTensor` s in the flattened inputs of ``func``.
59
+ If ``in_placements`` is specified, :meth:`local_map` would examine whether the
60
+ placements of each :class:`DTensor` argument is the same as the required
61
+ placements or not. If the placements are not the same and
62
+ ``redistribute_inputs`` is ``False``, an exception will be raised. Otherwise if
63
+ ``redistribute_inputs`` is ``True``, the argument will be first redistributed to
64
+ the required sharding placements before passing its local tensor to ``func``.
65
+ The only exception is when required placements are not ``None`` and the
66
+ argument is a :class:`torch.Tensor`. In this case, the placements examination
67
+ will be skipped and the argument will be directly passed to ``func``.
68
+ If ``in_placements`` is ``None``, no placements examination will be performed.
69
+ Default: None
70
+ in_grad_placements (Tuple[`PlacementType`, ...], optional):
71
+ the placements hint of the :class:`DTensor` s gradient corresponds
72
+ to the flattened input DTensor. This argument is the hint that user
73
+ can give to :meth:`to_local` in case the gradient layout of the
74
+ local tensor input does not match its :class:`DTensor` input layout.
75
+ If not specified, we will assume the gradient layout of the local
76
+ tensor input remains the same as the original :class:`DTensor` input
77
+ and use that for gradient computation. Default: None.
78
+ device_mesh (:class:`DeviceMesh`, optional):
79
+ the device mesh that the output :class:`DTensor` s are placed on. If not
80
+ specified, this will be inferred from the first input :class:`DTensor`'s device
81
+ mesh. Default: None.
82
+
83
+ Keyword Args:
84
+ redistribute_inputs (bool, optional):
85
+ the bool value indicating whether to reshard the input :class:`DTensor` s when
86
+ their placements are different from the required input placements. If this
87
+ value is ``False`` and some :class:`DTensor` input has a different placement,
88
+ an exception will be raised. Default: False.
89
+
90
+ Returns:
91
+ A ``Callable`` that applies ``func`` to each local shard of the input :class:`DTensor`
92
+ and returns a :class:`DTensor` constructed from the return value of ``func``.
93
+
94
+ Raises:
95
+ AssertionError: For any non-DTensor output, we require its corresponding
96
+ output placement in ``out_placements`` be None. An AssertionError will be raised
97
+ if this is not the case.
98
+
99
+ ValueError: If ``redistribute_inputs=False`` but the input :class:`DTensor` needs
100
+ a redistribution according to ``in_placements``.
101
+
102
+ Example:
103
+ >>> # xdoctest: +SKIP("distributed")
104
+ >>> def mm_allreduce_forward(device_mesh, W, X):
105
+ >>> partial_sum_tensor = torch.mm(W, X)
106
+ >>> reduced_tensor = funcol.all_reduce(partial_sum_tensor, "sum", device_mesh)
107
+ >>> return reduced_tensor
108
+ >>>
109
+ >>> W = torch.randn(12, 8, requires_grad=False)
110
+ >>> X = torch.randn(8, 16, requires_grad=False)
111
+ >>> Y = torch.mm(W, X)
112
+ >>> row_wise = [Shard(0)] # row-wise sharding placements on 1-d mesh
113
+ >>> col_wise = [Shard(1)] # col-wise sharding placements on 1-d mesh
114
+ >>>
115
+ >>> # local_mm_allreduce_forward is the function wrapped with DTensor/Tensor conversion
116
+ >>> local_mm_allreduce_forward = local_map(
117
+ >>> mm_allreduce_forward,
118
+ >>> out_placements=[Replicate()],
119
+ >>> in_placements=[col_wise, row_wise],
120
+ >>> device_mesh=device_mesh,
121
+ >>> )
122
+ >>>
123
+ >>> W_dt = distribute_tensor(
124
+ ... W, device_mesh, (col_wise)
125
+ ... ) # col-wisely sharded W tensor
126
+ >>> X_dt = distribute_tensor(
127
+ ... X, device_mesh, (row_wise)
128
+ ... ) # row-wisely sharded X tensor
129
+ >>> Y_dt = local_mm_allreduce_forward(
130
+ ... device_mesh, W_dt, X_dt
131
+ ... ) # apply local_mm_allreduce_forward to DTensors
132
+
133
+ .. note:: This API is currently experimental and subject to change
134
+ """
135
+
136
+ if func is None:
137
+ # decorator mode
138
+ def decorated(func):
139
+ return local_map(
140
+ func=func,
141
+ out_placements=out_placements,
142
+ in_placements=in_placements,
143
+ in_grad_placements=in_grad_placements,
144
+ device_mesh=device_mesh,
145
+ redistribute_inputs=redistribute_inputs,
146
+ )
147
+
148
+ return decorated
149
+
150
+ return functools.partial(
151
+ _local_map_wrapped,
152
+ func,
153
+ out_placements,
154
+ in_placements,
155
+ in_grad_placements,
156
+ device_mesh,
157
+ redistribute_inputs,
158
+ )
159
+
160
+
161
+ def _local_map_wrapped(
162
+ func: Callable,
163
+ out_placements: OutputPlacements,
164
+ in_placements: InputPlacements,
165
+ in_grad_placements: InputPlacements,
166
+ device_mesh: DeviceMesh | None,
167
+ redistribute_inputs: bool,
168
+ *args,
169
+ **kwargs,
170
+ ):
171
+ # process input args
172
+ flat_args, args_spec = pytree.tree_flatten(args)
173
+ if in_placements is not None:
174
+ assert len(in_placements) == len(flat_args), (
175
+ f"in_placements length {len(in_placements)} does not match the number "
176
+ f"of input args {len(flat_args)}!"
177
+ )
178
+
179
+ # we assume every DTensor object is placed on the same device mesh
180
+ flat_local_args = []
181
+ seen_dtensor_arg = False
182
+ for idx, arg in enumerate(flat_args):
183
+ if isinstance(arg, DTensor):
184
+ # TODO: the current code doesn't consider the uneven sharding case
185
+ # Need to think about what the consequence is when the input DTensor
186
+ # is uneven sharded.
187
+ if device_mesh is None: # infer device mesh from the DTensor arg
188
+ device_mesh = arg.device_mesh
189
+
190
+ # this function is applied to at least one DTensor argument
191
+ seen_dtensor_arg = True
192
+
193
+ if in_placements is not None:
194
+ spec = in_placements[idx]
195
+ assert spec is not None, (
196
+ f"DTensor input {arg} expects placements but received {spec}!"
197
+ )
198
+
199
+ if not isinstance(spec, tuple):
200
+ spec = tuple(spec)
201
+
202
+ if arg.placements != spec:
203
+ if redistribute_inputs:
204
+ # redistribute to input placements
205
+ arg = arg.redistribute(placements=spec)
206
+ else:
207
+ raise ValueError(
208
+ f"arg {arg} in local_map has a mismatched placements: "
209
+ f"arg placements is {arg.placements} but the input "
210
+ f"placements is {spec}! "
211
+ "If redistribute_inputs is wanted, set "
212
+ "redistribute_inputs=True to local_map."
213
+ )
214
+
215
+ if in_grad_placements is not None:
216
+ spec = in_grad_placements[idx]
217
+ assert spec is not None, (
218
+ f"DTensor input {arg} expects in grad placements but received {spec}!"
219
+ )
220
+ if not isinstance(spec, tuple):
221
+ spec = tuple(spec)
222
+ local_arg = arg.to_local(grad_placements=spec)
223
+ else:
224
+ local_arg = arg.to_local()
225
+
226
+ if isinstance(local_arg, AsyncCollectiveTensor):
227
+ local_arg = local_arg.wait()
228
+
229
+ flat_local_args.append(local_arg)
230
+ else:
231
+ # Non-Tensor input must have None in `in_placements`
232
+ if in_placements is not None and not isinstance(arg, torch.Tensor):
233
+ spec = in_placements[idx]
234
+ assert spec is None, (
235
+ f"Non-Tensor input {arg} expects None placements "
236
+ f"but received {spec}!"
237
+ )
238
+
239
+ flat_local_args.append(arg)
240
+
241
+ # pyrefly: ignore [bad-argument-type]
242
+ local_args = pytree.tree_unflatten(flat_local_args, args_spec)
243
+
244
+ out = func(*local_args, **kwargs)
245
+
246
+ if seen_dtensor_arg:
247
+ # process output to be DTensor if we've seen DTensor inputs
248
+ flat_out, out_spec = pytree.tree_flatten(out)
249
+
250
+ flat_dist_out = []
251
+ out_placements_tuple = (
252
+ out_placements if isinstance(out_placements, tuple) else (out_placements,)
253
+ )
254
+ assert len(flat_out) == len(out_placements_tuple), (
255
+ "local_map requires one PlacementType be provided for each output value,"
256
+ f" received {len(out_placements_tuple)} out_placements but"
257
+ f" {len(flat_out)} is expected!"
258
+ )
259
+ for out, spec in zip(flat_out, out_placements_tuple):
260
+ if isinstance(out, torch.Tensor):
261
+ assert not isinstance(out, DTensor), (
262
+ f"torch.Tensor output expected but received {type(out)}: {out}"
263
+ )
264
+
265
+ flat_dist_out.append(
266
+ DTensor.from_local(out, device_mesh, spec, run_check=False)
267
+ )
268
+ else:
269
+ assert spec is None, (
270
+ f"Non-tensor output {out} expects None placements but received {spec}!"
271
+ )
272
+
273
+ flat_dist_out.append(out)
274
+
275
+ # pyrefly: ignore [bad-argument-type]
276
+ return pytree.tree_unflatten(flat_dist_out, out_spec)
277
+ else:
278
+ return out
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_register_sharding.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+ from collections.abc import Callable, Sequence
4
+ from functools import partial
5
+
6
+ import torch
7
+ from torch._ops import OpOverload
8
+ from torch.distributed.tensor import DTensor
9
+ from torch.distributed.tensor._op_schema import (
10
+ OpSchema,
11
+ OpStrategy,
12
+ PlacementList,
13
+ RuntimeSchemaInfo,
14
+ StrategyType,
15
+ TupleStrategy,
16
+ )
17
+ from torch.distributed.tensor._ops.utils import expand_to_full_mesh_op_strategy
18
+
19
+
20
+ __all__ = ["register_sharding"]
21
+
22
+
23
+ def register_sharding(op: OpOverload | list[OpOverload]):
24
+ """
25
+ :meth:`register_sharding` is an experimental API that allows users to register sharding
26
+ strategies for an operator when the tensor inputs and outputs are DTensor.
27
+ It can be useful when: (1) there doesn't exist a default sharding strategy for ``op``,
28
+ e.g. when ``op`` is a custom operator that is not supported by :class:`DTensor`; (2)
29
+ when users would like to overwrite default sharding strategies of existing operators.
30
+
31
+ Args:
32
+ op (Union[OpOverload, List[OpOverload]]):
33
+ An op or a list of ops to register the customized sharding function.
34
+
35
+ Returns:
36
+ A function decorator which can be used to wrap a function that defines the sharding
37
+ strategy for the operator specified in ``op``. The defined sharding strategy will be
38
+ registered to DTensor and will override the default sharding strategy if DTensor has
39
+ already implemented the operator. The customized sharding function takes the same inputs
40
+ as the original op (except that if an arg is a :class:`torch.Tensor`, it will be
41
+ replaced by a tensor-like object that DTensor uses internally). The function should
42
+ return a sequence of 2-tuples, each specifying acceptable output placements and its
43
+ corresponding input placements.
44
+
45
+ Example:
46
+ >>> # xdoctest: +SKIP("distributed")
47
+ >>> @register_sharding(aten._softmax.default)
48
+ >>> def custom_softmax_sharding(x, dim, half_to_float):
49
+ >>> softmax_dim = dim if dim >= 0 else dim + x.ndim
50
+ >>> acceptable_shardings = []
51
+ >>>
52
+ >>> all_replicate = ([Replicate()], [Replicate(), None, None])
53
+ >>> acceptable_shardings.append(all_replicate)
54
+ >>>
55
+ >>> for sharding_dim in range(x.ndim):
56
+ >>> if sharding_dim != softmax_dim:
57
+ >>> all_sharded = (
58
+ >>> [Shard(sharding_dim)],
59
+ >>> [Shard(sharding_dim), None, None],
60
+ >>> )
61
+ >>> acceptable_shardings.append(all_sharded)
62
+ >>>
63
+ >>> return acceptable_shardings
64
+
65
+ .. note:: This API is currently experimental and subject to change
66
+ """
67
+
68
+ def custom_strategy(
69
+ custom_sharding_fn: Callable[
70
+ ..., Sequence[tuple[PlacementList, PlacementList]]
71
+ ],
72
+ op_schema: OpSchema,
73
+ ) -> StrategyType:
74
+ def strategy_to_spec(strategy: object) -> object:
75
+ if isinstance(strategy, OpStrategy):
76
+ # take the output spec from the first strategy
77
+ return strategy.strategies[0].output_spec
78
+ elif isinstance(strategy, TupleStrategy):
79
+ return tuple(strategy_to_spec(s) for s in strategy.children)
80
+ else:
81
+ return strategy
82
+
83
+ mesh = op_schema.get_mesh_from_args()
84
+
85
+ args_schema = tuple(strategy_to_spec(i) for i in op_schema.args_schema)
86
+ kwargs_schema = {
87
+ k: strategy_to_spec(v) for k, v in op_schema.kwargs_schema.items()
88
+ }
89
+
90
+ acceptable_shardings = custom_sharding_fn(*args_schema, **kwargs_schema)
91
+
92
+ single_mesh_dim_strategies: list[PlacementList] = []
93
+ for output_specs, input_specs in acceptable_shardings:
94
+ single_mesh_dim_strategies.append(output_specs + input_specs)
95
+
96
+ # TODO: handle out variant ops
97
+ return expand_to_full_mesh_op_strategy(
98
+ mesh,
99
+ op_schema,
100
+ single_mesh_dim_strategies,
101
+ input_index=len(op_schema.op._schema.returns),
102
+ inplace_op=op_schema.is_inplace_op(),
103
+ )
104
+
105
+ def wrapper(custom_sharding_fn):
106
+ def derive_schema_info(op):
107
+ # NOTE: without user directly providing RuntimeSchemaInfo, for now
108
+ # we create it in a conservative fashion as follows:
109
+ # 1. let static_argnum be the first int argument
110
+ # 2. let static_kwargkey include all the int type kwargs
111
+ # 3. always set needs_pytree=True
112
+ static_argnum = 100
113
+ static_kwargkey: list[str] = []
114
+ for i, arg in enumerate(op._schema.arguments):
115
+ if isinstance(arg.type, torch.IntType) or (
116
+ isinstance(arg.type, torch.OptionalType)
117
+ and isinstance(arg.type.getElementType(), torch.IntType)
118
+ ):
119
+ static_argnum = min(i, static_argnum)
120
+ if arg.kwarg_only:
121
+ static_kwargkey.append(arg.name)
122
+ return RuntimeSchemaInfo(
123
+ static_argnum, static_kwargkey or None, needs_pytree=True
124
+ )
125
+
126
+ overloads = op if isinstance(op, list) else [op]
127
+ for overload in overloads:
128
+ DTensor._op_dispatcher.sharding_propagator.register_op_strategy(
129
+ overload,
130
+ partial(custom_strategy, custom_sharding_fn),
131
+ derive_schema_info(overload),
132
+ )
133
+
134
+ return custom_sharding_fn
135
+
136
+ return wrapper
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/experimental/_tp_transform.py ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+ import operator
4
+ from collections.abc import Sequence
5
+ from typing import Any, cast
6
+
7
+ import torch
8
+ from torch._subclasses.fake_tensor import FakeTensor
9
+ from torch.distributed.tensor import DeviceMesh, distribute_tensor, DTensor
10
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
11
+ from torch.distributed.tensor._op_schema import (
12
+ OpSchema,
13
+ OpSpec,
14
+ OutputSharding,
15
+ OutputSpecType,
16
+ )
17
+ from torch.distributed.tensor._redistribute import redistribute_local_tensor
18
+ from torch.distributed.tensor.parallel.style import ColwiseParallel, ParallelStyle
19
+ from torch.distributed.tensor.placement_types import Placement, Replicate, Shard
20
+ from torch.export import ExportedProgram
21
+ from torch.export.exported_program import ExportGraphSignature
22
+ from torch.fx import GraphModule
23
+ from torch.fx.experimental.proxy_tensor import make_fx
24
+ from torch.fx.node import Node
25
+ from torch.fx.passes.infra.pass_base import PassBase, PassResult
26
+ from torch.fx.passes.shape_prop import _extract_tensor_metadata
27
+ from torch.utils import _pytree as pytree
28
+
29
+
30
+ __all__ = ["tensor_parallel_transformation"]
31
+
32
+ aten = torch.ops.aten
33
+
34
+
35
+ def tensor_parallel_transformation(
36
+ exported_program: ExportedProgram,
37
+ rank: int,
38
+ world_size: int,
39
+ device_type: str,
40
+ parallel_strategies: dict[str, ParallelStyle],
41
+ ) -> ExportedProgram:
42
+ """
43
+ The entry point function to perform graph transformations on an exported program
44
+ to transform a single-device graph into a tensor parallel graph.
45
+
46
+ .. warning::
47
+ This API is experimental and subject to change.
48
+ """
49
+
50
+ gm = exported_program.graph_module
51
+ sig = copy.deepcopy(exported_program.graph_signature)
52
+ state_dict = copy.copy(exported_program.state_dict)
53
+
54
+ with gm._set_replace_hook(sig.get_replace_hook()):
55
+ res = _TensorParallelTransformPass(
56
+ rank,
57
+ world_size,
58
+ device_type,
59
+ state_dict,
60
+ exported_program.graph_signature,
61
+ parallel_strategies,
62
+ )(gm)
63
+ assert res is not None
64
+ gm = res.graph_module
65
+
66
+ return exported_program._update(gm, sig, state_dict=state_dict)
67
+
68
+
69
+ class _TensorParallelTransformPass(PassBase):
70
+ """
71
+ This pass is responsible for transforming a single-device graph into a tensor parallel
72
+ graph. It will mark the OpSpec of each node in the graph, partition the graph into
73
+ distributed graph, then shard the parameters/buffers accordingly.
74
+ """
75
+
76
+ def __init__(
77
+ self,
78
+ rank: int,
79
+ world_size: int,
80
+ device_type: str,
81
+ state_dict: dict[str, torch.Tensor],
82
+ graph_signature: ExportGraphSignature,
83
+ parallel_strategies: dict[str, ParallelStyle],
84
+ ) -> None:
85
+ super().__init__()
86
+ self.rank = rank
87
+ self.mesh = DeviceMesh(device_type, torch.arange(world_size))
88
+ self.state_dict: dict[str, torch.Tensor] = state_dict
89
+ self.graph_signature = graph_signature
90
+ self.parallel_strategies = parallel_strategies
91
+
92
+ def call(self, graph_module) -> PassResult:
93
+ gm = copy.deepcopy(graph_module)
94
+
95
+ parameter_placements = _generate_parameter_and_buffer_placements(
96
+ list(self.state_dict.keys()), self.parallel_strategies
97
+ )
98
+ placement_strategies = _mark_sharding(
99
+ gm, self.graph_signature, self.mesh, parameter_placements
100
+ )
101
+ _partitioner(gm)
102
+ _shard_state_dict(
103
+ self.state_dict, placement_strategies, self.graph_signature, self.mesh
104
+ )
105
+ return PassResult(gm, True)
106
+
107
+
108
+ def _generate_parameter_and_buffer_placements(
109
+ params_and_buffers: list[str],
110
+ parallel_strategies: dict[str, ParallelStyle],
111
+ ) -> dict[str, Placement]:
112
+ """
113
+ Build parameter placements based on the give parallel style of linear layers.
114
+ """
115
+ parameter_placements: dict[str, Placement] = {}
116
+ for linear_fqn, parallel_style in parallel_strategies.items():
117
+ weight_fqn = f"{linear_fqn}.weight"
118
+ bias_fqn = f"{linear_fqn}.bias"
119
+ assert weight_fqn in params_and_buffers
120
+ parameter_placements[weight_fqn] = (
121
+ Shard(0) if parallel_style == ColwiseParallel else Shard(1)
122
+ )
123
+ if bias_fqn in params_and_buffers:
124
+ parameter_placements[bias_fqn] = (
125
+ Shard(0) if parallel_style == ColwiseParallel else Replicate()
126
+ )
127
+ return parameter_placements
128
+
129
+
130
+ def _mark_tensor_parallel_shardings(
131
+ gm: GraphModule,
132
+ graph_signature: ExportGraphSignature,
133
+ mesh: DeviceMesh,
134
+ parameter_placements: dict[str, Placement],
135
+ ) -> dict[Node, OpSpec]:
136
+ """
137
+ Mark the placement strategies of the parameter and buffer placeholder nodes.
138
+ """
139
+ placement_strategies: dict[Node, OpSpec] = {}
140
+ num_params_and_buffers = len(graph_signature.inputs_to_parameters) + len(
141
+ graph_signature.inputs_to_buffers
142
+ )
143
+ placeholder_idx: int = 0
144
+ for node in gm.graph.nodes:
145
+ if node.op == "placeholder":
146
+ if placeholder_idx < num_params_and_buffers:
147
+ fqn: str = _get_input_node_fqn(node.name, graph_signature)
148
+ placement: Placement = (
149
+ parameter_placements[fqn]
150
+ if fqn in parameter_placements
151
+ else Replicate()
152
+ )
153
+ placement_strategies[node] = _create_placement_strategy(
154
+ node,
155
+ mesh,
156
+ placements=(placement,),
157
+ )
158
+ placeholder_idx += 1
159
+ else:
160
+ placement_strategies[node] = _create_placement_strategy(
161
+ node,
162
+ mesh,
163
+ placements=(Replicate(),),
164
+ )
165
+ return placement_strategies
166
+
167
+
168
+ def _get_input_node_fqn(input_name: str, graph_signature: ExportGraphSignature) -> str:
169
+ """
170
+ Return the FQN of an input node.
171
+ """
172
+ if input_name in graph_signature.inputs_to_parameters:
173
+ return graph_signature.inputs_to_parameters[input_name]
174
+ elif input_name in graph_signature.inputs_to_buffers:
175
+ return graph_signature.inputs_to_buffers[input_name]
176
+ else:
177
+ raise ValueError(
178
+ f"{input_name} not found in inputs_to_parameters or inputs_to_buffers"
179
+ )
180
+
181
+
182
+ def _mark_sharding(
183
+ gm: GraphModule,
184
+ graph_signature: ExportGraphSignature,
185
+ mesh: DeviceMesh,
186
+ parameter_placements: dict[str, Placement],
187
+ ) -> dict[Node, OpSpec]:
188
+ """
189
+ Mark the sharding strategy for each node in the graph module.
190
+ """
191
+ placement_strategies: dict[Node, OpSpec] = _mark_tensor_parallel_shardings(
192
+ gm,
193
+ graph_signature,
194
+ mesh,
195
+ parameter_placements,
196
+ )
197
+
198
+ for node in gm.graph.nodes:
199
+ if node.op == "placeholder":
200
+ if node not in placement_strategies:
201
+ placement_strategies[node] = _create_placement_strategy(
202
+ node, mesh, placements=(Replicate(),)
203
+ )
204
+ node.meta["sharding"] = placement_strategies[node]
205
+ elif node.op == "call_function":
206
+ if node.target is operator.getitem:
207
+ input_nodes = node.all_input_nodes
208
+ assert len(input_nodes) == 1, (
209
+ f"non-compute op only support one input now, found node: {node} with length of inputs: {len(node.args)}"
210
+ )
211
+ arg_strategy = placement_strategies[input_nodes[0]]
212
+ placement_strategies[node] = _create_placement_strategy(
213
+ node,
214
+ mesh,
215
+ placements=arg_strategy.output_spec.placements,
216
+ input_specs=_get_input_node_specs(node, placement_strategies),
217
+ )
218
+ node.meta["sharding"] = placement_strategies[node]
219
+ else:
220
+ op_schema = _get_op_schema(node, placement_strategies)
221
+
222
+ # get DTensor specs for inputs and outputs
223
+ if (
224
+ op_schema.op
225
+ not in DTensor._op_dispatcher.sharding_propagator.op_strategy_funcs
226
+ and op_schema.op
227
+ not in DTensor._op_dispatcher.sharding_propagator.op_to_rules
228
+ ):
229
+ # Mark all as replicated
230
+ output_sharding = _generate_default_output_sharding(
231
+ node,
232
+ mesh,
233
+ op_schema,
234
+ )
235
+ else:
236
+ output_sharding = DTensor._op_dispatcher.sharding_propagator.propagate_op_sharding( # type: ignore[assignment]
237
+ op_schema,
238
+ )
239
+ placement_strategies[node] = OpSpec(
240
+ # pyrefly: ignore [bad-argument-type]
241
+ output_specs=_get_output_spec_from_output_sharding(output_sharding),
242
+ # pyrefly: ignore [missing-attribute]
243
+ input_specs=output_sharding.redistribute_schema.args_spec
244
+ # pyrefly: ignore [missing-attribute]
245
+ if output_sharding.redistribute_schema is not None
246
+ else _get_input_node_specs(node, placement_strategies),
247
+ )
248
+ node.meta["sharding"] = placement_strategies[node]
249
+ elif node.op == "output":
250
+ node.meta["sharding"] = None
251
+ else:
252
+ raise RuntimeError(f"op code {node.op} not supported")
253
+ return placement_strategies
254
+
255
+
256
+ def _get_output_spec_from_output_sharding(
257
+ output_sharding: OutputSharding,
258
+ ) -> DTensorSpec:
259
+ """
260
+ Util function to extract output spec from output sharding.
261
+ """
262
+ if isinstance(output_sharding.output_spec, DTensorSpec):
263
+ return output_sharding.output_spec
264
+ else:
265
+ # For ops that return multiple outputs, the outputs should have the same output spec
266
+ assert isinstance(output_sharding.output_spec, Sequence)
267
+ assert output_sharding.output_spec[0] is not None
268
+ output_sharding.output_spec[0].tensor_meta = None
269
+ return output_sharding.output_spec[0]
270
+
271
+
272
+ def _create_placement_strategy(
273
+ node: Node,
274
+ mesh: DeviceMesh,
275
+ placements: tuple[Placement, ...],
276
+ input_specs: Sequence[DTensorSpec] | None = None,
277
+ ) -> OpSpec:
278
+ """
279
+ Util function to construct an OpSpec for a given node.
280
+ """
281
+ placement = OpSpec(
282
+ input_specs=input_specs,
283
+ output_specs=DTensorSpec(
284
+ mesh=mesh,
285
+ placements=placements,
286
+ ),
287
+ )
288
+ _populate_tensor_meta(node, placement.output_specs)
289
+ return placement
290
+
291
+
292
+ def _populate_tensor_meta(node: Node, output_spec: OutputSpecType) -> None:
293
+ """
294
+ Util function to populate tensor meta of output_spec based on node metadata.
295
+ """
296
+ if isinstance(node.meta["val"], Sequence):
297
+ assert isinstance(output_spec, Sequence)
298
+ for spec, fake_tensor in zip(output_spec, node.meta["val"]):
299
+ assert spec is not None
300
+ spec.tensor_meta = TensorMeta(
301
+ shape=fake_tensor.shape,
302
+ stride=fake_tensor.stride(),
303
+ dtype=fake_tensor.dtype,
304
+ )
305
+ else:
306
+ assert isinstance(output_spec, DTensorSpec)
307
+ output_spec.tensor_meta = TensorMeta(
308
+ shape=node.meta["val"].shape,
309
+ stride=node.meta["val"].stride(),
310
+ dtype=node.meta["val"].dtype,
311
+ )
312
+
313
+
314
+ def _generate_default_output_sharding(
315
+ node: Node,
316
+ mesh: DeviceMesh,
317
+ op_schema: OpSchema,
318
+ ) -> OutputSharding:
319
+ """
320
+ Util function to create a default output sharding that suggests Replicate placement for both args and outputs.
321
+ """
322
+
323
+ def update_arg_spec(arg_spec: DTensorSpec) -> DTensorSpec:
324
+ return DTensorSpec(
325
+ mesh=arg_spec.mesh,
326
+ placements=(Replicate(),),
327
+ tensor_meta=arg_spec.tensor_meta,
328
+ )
329
+
330
+ new_op_schema = OpSchema(
331
+ op=op_schema.op,
332
+ args_schema=pytree.tree_map_only(
333
+ DTensorSpec, update_arg_spec, op_schema.args_schema
334
+ ),
335
+ kwargs_schema=op_schema.kwargs_schema,
336
+ )
337
+
338
+ def create_output_spec(tensor: FakeTensor) -> DTensorSpec:
339
+ return DTensorSpec(
340
+ mesh=mesh,
341
+ placements=(Replicate(),),
342
+ tensor_meta=TensorMeta(
343
+ shape=tensor.shape,
344
+ stride=tensor.stride(),
345
+ dtype=tensor.dtype,
346
+ ),
347
+ )
348
+
349
+ return OutputSharding(
350
+ output_spec=pytree.tree_map_only(
351
+ FakeTensor, create_output_spec, node.meta["val"]
352
+ ),
353
+ redistribute_schema=new_op_schema,
354
+ needs_redistribute=True,
355
+ )
356
+
357
+
358
+ def _partitioner(gm: torch.fx.GraphModule) -> torch.fx.GraphModule:
359
+ """
360
+ Graph partitioner that partitions the single device graph
361
+ to distributed graph
362
+ """
363
+ for node in gm.graph.nodes:
364
+ node_sharding = node.meta["sharding"]
365
+ if node.op == "placeholder":
366
+ out_spec = node_sharding.output_spec
367
+ local_val = _partition_val(node.meta["val"], out_spec)
368
+ # update node value
369
+ node.meta["val"] = local_val
370
+ elif node.op == "call_function":
371
+ out_spec = node_sharding.output_spec
372
+ # check if there's misaligned sharding, insert reshard if there is
373
+ expected_input_specs = node_sharding.input_specs
374
+ for idx, input_arg in enumerate(node.all_input_nodes):
375
+ input_arg_sharding = input_arg.meta["sharding"]
376
+ input_arg_spec = input_arg_sharding.output_spec
377
+ desired_spec = (
378
+ out_spec
379
+ if expected_input_specs is None
380
+ else expected_input_specs[idx]
381
+ )
382
+ if input_arg_spec != desired_spec:
383
+ _insert_reshard_gm(
384
+ gm, node, input_arg, input_arg_spec, desired_spec
385
+ )
386
+ # convert output val to its local component
387
+ output_val = node.meta["val"]
388
+ node.meta["val"] = _partition_val(output_val, out_spec)
389
+ elif node.op == "output":
390
+ for input_arg in node.all_input_nodes:
391
+ # input args of output should be Replicate, otherwise redistribution is needed.
392
+ input_args_to_check: Sequence[Node] = (
393
+ input_arg if isinstance(input_arg, Sequence) else [input_arg]
394
+ )
395
+ for arg in input_args_to_check:
396
+ arg_sharding = arg.meta["sharding"]
397
+ arg_spec = arg_sharding.output_spec
398
+ desired_spec = copy.copy(arg_spec)
399
+ desired_spec.placements = (Replicate(),)
400
+ if arg_spec != desired_spec:
401
+ _insert_reshard_gm(gm, node, arg, arg_spec, desired_spec)
402
+ else:
403
+ raise RuntimeError(f"op code {node} not supported")
404
+
405
+ _clean_up_graph_metadata(gm)
406
+ gm.graph.lint()
407
+ gm.recompile()
408
+ return gm
409
+
410
+
411
+ def _partition_val(val: Any, spec: DTensorSpec) -> Any:
412
+ """
413
+ util function to convert a full tensor val to its local component
414
+ """
415
+ if isinstance(val, torch.Tensor):
416
+ local_shard = val
417
+ if val.ndim == 0:
418
+ # If it's already a scalar tensor, it is already local, we don't
419
+ # need to do anything
420
+ return local_shard
421
+
422
+ for idx, placement in enumerate(spec.placements):
423
+ if placement.is_shard():
424
+ placement = cast(Shard, placement)
425
+ num_chunks = spec.mesh.size(mesh_dim=idx)
426
+ my_coord = spec.mesh.get_coordinate()
427
+ assert my_coord is not None, "current rank not in mesh!"
428
+ my_coord_on_mesh_dim = my_coord[idx]
429
+ local_shard = placement._split_tensor(
430
+ local_shard, num_chunks, with_padding=False, contiguous=True
431
+ )[0][my_coord_on_mesh_dim]
432
+ return local_shard
433
+ elif isinstance(val, (list, tuple)):
434
+ return val.__class__(_partition_val(v, spec) for v in val)
435
+ else:
436
+ raise RuntimeError(f"val type {type(val)} not supported")
437
+
438
+
439
+ def _insert_reshard_gm(
440
+ gm: torch.fx.GraphModule,
441
+ node: Node,
442
+ input_arg: Node,
443
+ input_arg_spec: DTensorSpec,
444
+ desired_spec: DTensorSpec,
445
+ ) -> None:
446
+ """
447
+ Transform the graph for tensor redistribution.
448
+ """
449
+ input_arg_spec.tensor_meta = input_arg.meta["tensor_meta"]
450
+ desired_spec.tensor_meta = input_arg.meta["tensor_meta"]
451
+ input_arg_tensor = input_arg.meta["val"]
452
+
453
+ # insert reshard operation
454
+ def reshard_fn(local_tensor: torch.Tensor) -> torch.Tensor:
455
+ return redistribute_local_tensor(
456
+ local_tensor,
457
+ input_arg_spec,
458
+ desired_spec,
459
+ )
460
+
461
+ reshard_gm = make_fx(reshard_fn)(input_arg_tensor)
462
+ reshard_gm_nodes = list(reshard_gm.graph.nodes)
463
+ input_node = reshard_gm_nodes[0]
464
+ with gm.graph.inserting_before(node):
465
+ # copy nn_module_stack metadata for output, all-reduce nodes
466
+ for reshard_node in reshard_gm.graph.nodes:
467
+ if reshard_node.op not in ["placeholder", "output"]:
468
+ reshard_node.meta["nn_module_stack"] = (
469
+ copy.copy(input_arg.meta["nn_module_stack"])
470
+ if input_arg.op != "placeholder"
471
+ else copy.copy(node.meta["nn_module_stack"])
472
+ )
473
+ output_node = gm.graph.graph_copy(
474
+ reshard_gm.graph,
475
+ val_map={
476
+ input_node: input_arg,
477
+ },
478
+ )
479
+ node.replace_input_with(input_arg, output_node) # type: ignore[arg-type]
480
+
481
+
482
+ def _clean_up_graph_metadata(gm: torch.fx.GraphModule) -> None:
483
+ """
484
+ Clean up the graph by removing sharding and partitioning related metadata
485
+ """
486
+ for node in gm.graph.nodes:
487
+ if "sharding" in node.meta:
488
+ del node.meta["sharding"]
489
+ if "val" in node.meta and isinstance(node.meta["val"], torch.Tensor):
490
+ local_tensor_meta = _extract_tensor_metadata(node.meta["val"])
491
+ node.meta["tensor_meta"] = local_tensor_meta
492
+
493
+
494
+ def _get_input_node_specs(
495
+ node: Node, placement_strategies: dict[Node, OpSpec]
496
+ ) -> tuple[DTensorSpec, ...]:
497
+ """
498
+ Get the input specs of a node.
499
+ """
500
+ input_specs_list: list[DTensorSpec] = []
501
+ for input_arg in node.all_input_nodes:
502
+ if input_arg in placement_strategies:
503
+ output_spec = placement_strategies[input_arg].output_specs
504
+ assert isinstance(output_spec, DTensorSpec)
505
+ input_specs_list.append(output_spec)
506
+ else:
507
+ raise ValueError(f"{input_arg} does not have output_spec populated.")
508
+ return tuple(input_specs_list)
509
+
510
+
511
+ def _get_op_schema(node: Node, placement_strategies: dict[Node, OpSpec]) -> OpSchema:
512
+ """
513
+ Util function to construct the operator schema of a node.
514
+ """
515
+ args_schema_list = pytree.tree_map_only(
516
+ Node, lambda arg: placement_strategies[arg].output_specs, node.args
517
+ )
518
+ op_schema = OpSchema(
519
+ op=cast(torch._ops.OpOverload, node.target),
520
+ args_schema=tuple(args_schema_list),
521
+ kwargs_schema=cast(dict[str, object], node.kwargs),
522
+ )
523
+ return op_schema
524
+
525
+
526
+ def _shard_state_dict(
527
+ state_dict: dict[str, torch.Tensor],
528
+ placement_strategies: dict[Node, OpSpec],
529
+ graph_signature: ExportGraphSignature,
530
+ mesh: DeviceMesh,
531
+ ) -> None:
532
+ """
533
+ Inplace partition the weights based on the OpSpec
534
+ """
535
+ for node, op_spec in placement_strategies.items():
536
+ if node.op != "placeholder":
537
+ continue
538
+ if node.name in graph_signature.inputs_to_parameters:
539
+ fqn = graph_signature.inputs_to_parameters[node.name]
540
+ elif node.name in graph_signature.inputs_to_buffers:
541
+ fqn = graph_signature.inputs_to_buffers[node.name]
542
+ else:
543
+ continue
544
+ assert fqn in state_dict, f"{fqn} not found in state dict: {state_dict.keys()}"
545
+
546
+ original_param = state_dict[fqn]
547
+ dtensor_param = distribute_tensor(
548
+ original_param,
549
+ mesh,
550
+ op_spec.output_spec.placements,
551
+ )
552
+ local_param = dtensor_param.to_local()
553
+ state_dict[fqn] = (
554
+ torch.nn.Parameter(local_param)
555
+ if isinstance(original_param, torch.nn.Parameter)
556
+ else local_param
557
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ from torch.distributed.tensor.parallel.api import parallelize_module
3
+ from torch.distributed.tensor.parallel.loss import loss_parallel
4
+ from torch.distributed.tensor.parallel.style import (
5
+ ColwiseParallel,
6
+ ParallelStyle,
7
+ PrepareModuleInput,
8
+ PrepareModuleInputOutput,
9
+ PrepareModuleOutput,
10
+ RowwiseParallel,
11
+ SequenceParallel,
12
+ )
13
+
14
+
15
+ __all__ = [
16
+ "ColwiseParallel",
17
+ "ParallelStyle",
18
+ "PrepareModuleInput",
19
+ "PrepareModuleInputOutput",
20
+ "PrepareModuleOutput",
21
+ "RowwiseParallel",
22
+ "SequenceParallel",
23
+ "parallelize_module",
24
+ "loss_parallel",
25
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/_data_parallel_utils.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+ from typing import no_type_check
3
+
4
+ import torch
5
+ from torch.distributed._functional_collectives import AsyncCollectiveTensor
6
+ from torch.distributed.tensor import DTensor
7
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec
8
+
9
+
10
+ @no_type_check
11
+ def sync_grad_hook(grad, *, device_handle=None, compute_stream=None):
12
+ if isinstance(grad, AsyncCollectiveTensor):
13
+ if compute_stream is not None:
14
+ with device_handle.stream(compute_stream):
15
+ grad = grad.wait()
16
+ else:
17
+ grad = grad.wait()
18
+
19
+ return grad
20
+
21
+
22
+ def _flatten_tensor(
23
+ tensor: torch.Tensor,
24
+ ) -> tuple[torch.Tensor, DTensorSpec | None]:
25
+ if isinstance(tensor, DTensor):
26
+ tensor._local_tensor.requires_grad_()
27
+ return tensor._local_tensor, tensor._spec
28
+ return tensor, None
29
+
30
+
31
+ @no_type_check
32
+ def _unflatten_tensor(tensor, spec, *, device_handle=None, compute_stream=None):
33
+ # unflatten would mainly be called every time FSDP allgather parameters.
34
+ result = DTensor.from_local(
35
+ tensor,
36
+ spec.mesh,
37
+ spec.placements,
38
+ run_check=False,
39
+ shape=spec.shape,
40
+ stride=spec.stride,
41
+ )
42
+ if tensor.requires_grad:
43
+ # only register the hook if the tensor requires grad
44
+ tensor.register_hook(
45
+ partial(
46
+ sync_grad_hook,
47
+ device_handle=device_handle,
48
+ compute_stream=compute_stream,
49
+ )
50
+ )
51
+ return result
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/api.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ import warnings
3
+ from fnmatch import fnmatch
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from torch.distributed.device_mesh import _mesh_resources, DeviceMesh
8
+ from torch.distributed.tensor.parallel.style import ParallelStyle
9
+
10
+
11
+ __all__ = ["parallelize_module"]
12
+
13
+
14
+ def parallelize_module( # type: ignore[return]
15
+ module: nn.Module,
16
+ device_mesh: DeviceMesh | None = None,
17
+ parallelize_plan: ParallelStyle | dict[str, ParallelStyle] | None = None,
18
+ *,
19
+ src_data_rank: int | None = 0,
20
+ ) -> nn.Module:
21
+ """
22
+ Apply Tensor Parallelism in PyTorch by parallelizing modules or sub-modules based on a user-specified plan.
23
+
24
+ We parallelize module or sub_modules based on a parallelize_plan. The parallelize_plan contains
25
+ :class:`ParallelStyle`, which indicates how user wants the module or sub_module
26
+ to be parallelized.
27
+
28
+ User can also specify different parallel style per module fully qualified name (FQN).
29
+
30
+ Note that ``parallelize_module`` only accepts a 1-D :class:`DeviceMesh`, if you have a 2-D or N-D :class:`DeviceMesh`,
31
+ slice the DeviceMesh to a 1-D sub DeviceMesh first then pass to this API(i.e. ``device_mesh[\"tp\"]``)
32
+
33
+ Args:
34
+ module (:class:`nn.Module`):
35
+ Module to be parallelized.
36
+ device_mesh (:class:`DeviceMesh`, optional):
37
+ Object which describes the mesh topology of devices for the DTensor.
38
+ If not specified, the call must be under a DeviceMesh context.
39
+ parallelize_plan (Union[:class:`ParallelStyle`, Dict[str, :class:`ParallelStyle`]], optional):
40
+ The plan used to parallelize the module. It can be either a
41
+ :class:`ParallelStyle` object which contains how we prepare
42
+ input/output for Tensor Parallelism or it can be a dict of module
43
+ FQN and its corresponding :class:`ParallelStyle` object. If not
44
+ specified, the call will do nothing at the moment.
45
+ Keyword args:
46
+ src_data_rank (int, optional): the rank of the source data for the logical/global tensor, it is used by
47
+ :meth:`distribute_tensor` to scatter/broadcast the shards/replicas to other ranks. By default,
48
+ we use ``group_rank=0`` on each DeviceMesh dimension as the source data to preserve the single-device
49
+ semantic. If passing ``None`` explicitly, :meth:`parallelize_module` simply uses its local data instead
50
+ of trying to preserve the single-device semantic via scatter/broadcast. Default: 0
51
+ Return:
52
+ A :class:`nn.Module` object parallelized.
53
+
54
+ Example::
55
+ >>> # xdoctest: +SKIP("distributed")
56
+ >>> from torch.distributed.tensor.parallel import parallelize_module, ColwiseParallel
57
+ >>> from torch.distributed.device_mesh import init_device_mesh
58
+ >>>
59
+ >>> # Define the module.
60
+ >>> m = Model(...)
61
+ >>> tp_mesh = init_device_mesh("cuda", (8,))
62
+ >>> m = parallelize_module(m, tp_mesh, {"w1": ColwiseParallel(), "w2": RowwiseParallel()})
63
+ >>>
64
+
65
+ .. note:: For complex module architecture like Attention, MLP layers, we recommend composing
66
+ different ParallelStyles together (i.e. ``ColwiseParallel`` and ``RowwiseParallel``) and pass
67
+ as a parallelize_plan, to achieves the desired sharding computation.
68
+ """
69
+ torch._C._log_api_usage_once("torch.distributed.tensor.parallel.parallelize_module")
70
+
71
+ device_mesh = device_mesh or _mesh_resources.get_current_mesh()
72
+
73
+ if parallelize_plan is None:
74
+ warnings.warn(
75
+ "No parallelize_plan is provided and auto-parallel is not supported "
76
+ "at the moment, so this parallelize_module call will do nothing.",
77
+ stacklevel=2,
78
+ )
79
+ return module
80
+
81
+ # note: The RNG tracker will be initialized in distribute_tensor() call if it hasn't
82
+ # been initialized.
83
+
84
+ if isinstance(parallelize_plan, ParallelStyle):
85
+ parallelize_plan.src_data_rank = src_data_rank
86
+ return parallelize_plan._apply(module, device_mesh)
87
+ elif isinstance(parallelize_plan, dict):
88
+ for module_path, parallelize_style in parallelize_plan.items():
89
+ if module_path == "":
90
+ # shortcut: empty string means to apply the plan to the current module
91
+ parallelize_module(module, device_mesh, parallelize_style)
92
+ continue
93
+
94
+ path_splits = module_path.split(".")
95
+ # Instead of blindly popping tokens, first check the match,
96
+ # we only consume/pop the token if we found a match.
97
+ token = path_splits[0]
98
+
99
+ matched_children = list(
100
+ filter(
101
+ # `t[0]` is child name
102
+ lambda t: fnmatch(t[0], token),
103
+ module.named_children(),
104
+ )
105
+ )
106
+ if not matched_children:
107
+ # No match at this level. Log a warning and process next plan entry.
108
+ warnings.warn(
109
+ f"Parallelize plan key '{module_path}' could not be resolved: "
110
+ f"no submodule matching token '{token}' in module {module}, "
111
+ f"skipping this plan entry.",
112
+ stacklevel=2,
113
+ )
114
+ continue
115
+
116
+ # Now that we have a match, we can consume the token.
117
+ path_splits.pop(0)
118
+ # apply the plan to all matched submodules
119
+ for _, submodule in matched_children:
120
+ if path_splits:
121
+ # we haven't reached the leaf, apply in dict style
122
+ leaf_path = ".".join(path_splits) # rest of the path after `token`
123
+ parallelize_module(
124
+ submodule,
125
+ device_mesh,
126
+ {leaf_path: parallelize_style},
127
+ src_data_rank=src_data_rank,
128
+ )
129
+ else:
130
+ # otherwise, directly apply style to this submodule
131
+ parallelize_module(
132
+ submodule,
133
+ device_mesh,
134
+ parallelize_style,
135
+ src_data_rank=src_data_rank,
136
+ )
137
+ return module
138
+ else:
139
+ raise TypeError( # pyre-ignore[7]
140
+ "Expect Union[ParallelStyle, Dict[str, ParallelStyle]] for"
141
+ f" parallelize_plan, {type(parallelize_plan)} found!"
142
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/ddp.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Any
3
+
4
+ import torch.nn as nn
5
+ from torch.distributed.tensor.parallel._data_parallel_utils import (
6
+ _flatten_tensor,
7
+ _unflatten_tensor,
8
+ )
9
+
10
+
11
+ __all__ = [] # type: ignore[var-annotated]
12
+
13
+
14
+ def _get_submodule_n_params(module: nn.Module, path: str):
15
+ """
16
+ Get submodule and the direct path of parameter from the module
17
+ """
18
+ if "." in path:
19
+ path_list = path.split(".")
20
+ parent_module_path = ".".join(path_list[:-1])
21
+ module = module.get_submodule(parent_module_path)
22
+ path = path_list[-1]
23
+ return module, path
24
+
25
+
26
+ def _update_module_param(param_list: list[tuple[nn.Module, str, nn.Parameter]]):
27
+ """
28
+ Update parameters within the module
29
+ """
30
+ for item in param_list:
31
+ parent_module, module_path, t = item
32
+ assert hasattr(parent_module, module_path)
33
+ delattr(parent_module, module_path)
34
+ setattr(parent_module, module_path, t)
35
+
36
+
37
+ def _reconstruct_dtensor(module: nn.Module, _input: Any):
38
+ """
39
+ Reconstruct DTensor parameters from local tensors
40
+ """
41
+ param_list = []
42
+ # TODO: To add perf optimizations to this iterations
43
+ for name, t in module.named_parameters():
44
+ if hasattr(t, "_st_info"):
45
+ dtensor = _unflatten_tensor(t, t._st_info)
46
+ param_list.append((*_get_submodule_n_params(module, name), dtensor))
47
+ _update_module_param(param_list) # type: ignore[arg-type]
48
+
49
+
50
+ def _localize_dtensor(
51
+ module: nn.Module, *_: Any, ignored_params: set[nn.Parameter] | None = None
52
+ ):
53
+ """
54
+ Convert DTensor parameters to local tensors
55
+ """
56
+ if ignored_params is None:
57
+ ignored_params = set()
58
+ param_list = []
59
+ for name, param in module.named_parameters():
60
+ if param in ignored_params:
61
+ continue
62
+ t, sharding_info = _flatten_tensor(param)
63
+ if sharding_info is not None:
64
+ t = nn.Parameter(t)
65
+ t._st_info = sharding_info # type: ignore[attr-defined]
66
+ param_list.append((*_get_submodule_n_params(module, name), t))
67
+ _update_module_param(param_list) # type: ignore[arg-type]
68
+
69
+
70
+ def _pre_dp_module_transform(module: nn.Module):
71
+ """
72
+ Enable the composability between Tensor Parallelism (TP) and Data
73
+ Parallelism(DP) in PyTorch when using DDP. We need to convert Parameters which
74
+ are DTensors to local tensors before wrapping with data parallelism API.
75
+ We then register two hooks, one for converting local tensors back to DTensor
76
+ preforward and one to convert DTensors back to tensors after Forward. By
77
+ integrating this way, we avoid any special handling of DTensor parameters by DDP
78
+ and get DTensor's gradients propagated back to DP, e.g. gradient buckets of DDP.
79
+
80
+ For now, this API only works with ``DistributedDataParallel``. It will later support
81
+ other DP methods such as FSDP.
82
+
83
+ Args:
84
+ module (:class:`nn.Module`):
85
+ Module which has been applied TP on.
86
+
87
+ Example::
88
+ >>> # xdoctest: +SKIP("distributed")
89
+ >>> from torch.distributed.tensor.parallel import parallelize_module, PairwiseParallel
90
+ >>> from torch.nn.parallel import DistributedDataParallel as DDP
91
+ >>> from torch.distributed.tensor.parallel.ddp import pre_dp_module_transform
92
+ >>>
93
+ >>> # Define the module.
94
+ >>> m = module(...)
95
+ >>> parallelize_module(m, PairwiseParallel())
96
+ >>> m = pre_dp_module_transform(m)
97
+ >>> m = DDP(m)
98
+ >>>
99
+ """
100
+
101
+ _localize_dtensor(module, None, None)
102
+ # TODO: To add test cases and ensure that it works for nested modules
103
+ module.register_forward_pre_hook(_reconstruct_dtensor)
104
+ module.register_forward_hook(_localize_dtensor)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/fsdp.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+ from typing import Any, cast
4
+
5
+ import torch
6
+ import torch.distributed as dist
7
+ import torch.distributed._shard.sharding_spec as shard_spec
8
+ import torch.distributed.distributed_c10d as c10d
9
+ from torch.distributed._shard.sharded_tensor import (
10
+ Shard,
11
+ ShardedTensor,
12
+ ShardedTensorMetadata,
13
+ TensorProperties,
14
+ )
15
+ from torch.distributed._shard.sharding_spec import ShardMetadata
16
+ from torch.distributed._shard.sharding_spec.chunk_sharding_spec import ChunkShardingSpec
17
+ from torch.distributed.fsdp._common_utils import _set_fsdp_flattened
18
+ from torch.distributed.fsdp._fsdp_extensions import FSDPExtensions
19
+ from torch.distributed.fsdp._shard_utils import _create_chunk_sharded_tensor
20
+ from torch.distributed.remote_device import _remote_device
21
+ from torch.distributed.tensor import DeviceMesh, DTensor, Replicate, Shard as DShard
22
+ from torch.distributed.tensor.parallel._data_parallel_utils import (
23
+ _flatten_tensor,
24
+ _unflatten_tensor,
25
+ )
26
+
27
+
28
+ __all__ = ["DTensorExtensions"]
29
+
30
+
31
+ def _get_box(tensor: DTensor) -> tuple[torch.Size, torch.Size]:
32
+ device_mesh = tensor.device_mesh
33
+ assert device_mesh.ndim == 1, "Only 1D DeviceMeshes currently handled"
34
+
35
+ placement = tensor.placements[0]
36
+ offsets = [0] * len(tensor.size())
37
+ num_chunks = device_mesh.size(mesh_dim=0)
38
+
39
+ if tensor.placements[0].is_shard():
40
+ shard_dim = cast(DShard, placement).dim
41
+ chunk_size = tensor.size(shard_dim) // num_chunks
42
+ offsets[shard_dim] = chunk_size
43
+
44
+ return (torch.Size(offsets), tensor._local_tensor.size())
45
+
46
+
47
+ def _get_box_for(tensor: DTensor, idx: int) -> tuple[torch.Size, torch.Size]:
48
+ offsets, size = _get_box(tensor)
49
+ return (torch.Size([val * idx for val in offsets]), size)
50
+
51
+
52
+ def _get_local_box(tensor: DTensor) -> tuple[torch.Size, torch.Size]:
53
+ device_mesh = tensor.device_mesh
54
+ coord = device_mesh.get_coordinate()
55
+ assert coord is not None
56
+ return _get_box_for(tensor, coord[0])
57
+
58
+
59
+ def _create_shard_md_from_dt(dt: DTensor, current_rank: int) -> ShardMetadata:
60
+ mesh = dt.device_mesh
61
+ assert mesh.ndim == 1, "Only 1D DeviceMeshes currently handled"
62
+
63
+ offsets, sizes = _get_local_box(dt)
64
+ return ShardMetadata(
65
+ shard_offsets=list(offsets),
66
+ shard_sizes=list(sizes),
67
+ placement=f"rank:{current_rank}/{dt._local_tensor.device}",
68
+ )
69
+
70
+
71
+ def _create_sharded_tensor_md_from_dt(
72
+ dt: DTensor, dt_pg: c10d.ProcessGroup
73
+ ) -> ShardedTensorMetadata:
74
+ # This is where it gets tricky, we have to produce a ShardedTensor that has full coverage
75
+ # and yet has only one valid shard for the current rank.
76
+
77
+ shards_md = []
78
+ my_rank = dist.get_rank(dt_pg)
79
+ scapegoat_rank = 0 if my_rank > 0 else 1
80
+
81
+ if dt.placements[0].is_shard():
82
+ shard_count = dt_pg.size()
83
+ else:
84
+ shard_count = 1
85
+
86
+ for i in range(shard_count):
87
+ offsets, sizes = _get_box_for(dt, i)
88
+ shards_md.append(
89
+ ShardMetadata(
90
+ shard_offsets=list(offsets),
91
+ shard_sizes=list(sizes),
92
+ placement=(
93
+ f"rank:{scapegoat_rank if i > 0 else my_rank}/{dt._local_tensor.device}"
94
+ ),
95
+ )
96
+ )
97
+
98
+ return ShardedTensorMetadata(
99
+ shards_metadata=shards_md,
100
+ size=dt.size(),
101
+ tensor_properties=TensorProperties(
102
+ dtype=dt.dtype,
103
+ layout=dt.layout,
104
+ requires_grad=dt.requires_grad,
105
+ # ignore memory_format and pin_memory as those are not supported by DT
106
+ ),
107
+ )
108
+
109
+
110
+ def _get_dt_pg(dt: DTensor) -> c10d.ProcessGroup:
111
+ mesh = dt.device_mesh
112
+ assert mesh.ndim == 1, "Only 1D DeviceMeshes currently handled"
113
+ return mesh.get_group()
114
+
115
+
116
+ def _rewrite_spec_if_needed(
117
+ spec: shard_spec.ShardingSpec, tensor: torch.Tensor, rank: int
118
+ ) -> shard_spec.ShardingSpec:
119
+ """
120
+ Rewrite ``spec`` to match the device of ``tensor``.
121
+
122
+ FSDP.sharded_optim_state_dict sneakly ships optimizer state to CPU so if the original ShardingSpec
123
+ produces CUDA metadata, ST construction bombs.
124
+ """
125
+ if not isinstance(spec, ChunkShardingSpec):
126
+ return spec
127
+
128
+ # let's see if we need
129
+ rewrite = False
130
+ for p in spec.placements:
131
+ p = cast(_remote_device, p)
132
+ if p.rank() == rank and p.device() != tensor.device:
133
+ rewrite = True
134
+ break
135
+ if rewrite:
136
+ spec = copy.deepcopy(spec)
137
+ # pyrefly: ignore [missing-attribute]
138
+ for i, placement in enumerate(spec.placements):
139
+ placement = cast(_remote_device, placement)
140
+ if placement.rank() == rank and placement.device() != tensor.device:
141
+ # pyrefly: ignore [missing-attribute]
142
+ spec.placements[i] = _remote_device(f"rank:{rank}/{tensor.device}")
143
+
144
+ return spec
145
+
146
+
147
+ def _chunk_tensor(
148
+ tensor: torch.Tensor,
149
+ rank: int,
150
+ world_size: int,
151
+ num_devices_per_node: int,
152
+ pg: dist.ProcessGroup,
153
+ ) -> torch.Tensor:
154
+ if type(tensor) is ShardedTensor:
155
+ assert len(tensor.local_shards()) == 1
156
+
157
+ inner_param = tensor.local_tensor()
158
+ inner_st = _create_chunk_sharded_tensor(
159
+ inner_param,
160
+ rank,
161
+ world_size,
162
+ num_devices_per_node,
163
+ pg,
164
+ )
165
+
166
+ outer_local_shard = tensor.local_shards()[0]
167
+ shards: list[Shard] = [
168
+ Shard(inner_st, copy.deepcopy(outer_local_shard.metadata))
169
+ ]
170
+ st_meta = copy.deepcopy(tensor.metadata())
171
+ st_meta.tensor_properties.requires_grad = False
172
+
173
+ st_outer = ShardedTensor._init_from_local_shards_and_global_metadata(
174
+ shards,
175
+ sharded_tensor_metadata=st_meta,
176
+ process_group=tensor._process_group,
177
+ init_rrefs=False,
178
+ )
179
+ return st_outer
180
+ elif type(tensor) is DTensor:
181
+ device_mesh = tensor.device_mesh
182
+ assert device_mesh.ndim == 1, "Only 1D DeviceMeshes currently handled"
183
+
184
+ inner_param = tensor._local_tensor
185
+
186
+ inner_st = _create_chunk_sharded_tensor(
187
+ inner_param,
188
+ rank,
189
+ world_size,
190
+ torch.accelerator.device_count(),
191
+ pg,
192
+ )
193
+
194
+ dt_pg = _get_dt_pg(tensor)
195
+ # We do this differently here, we create a ST with no local shards then patch it
196
+ shards = [
197
+ Shard(inner_st, _create_shard_md_from_dt(tensor, dist.get_rank(dt_pg)))
198
+ ]
199
+
200
+ st_meta = _create_sharded_tensor_md_from_dt(tensor, dt_pg)
201
+ st_meta.tensor_properties.requires_grad = False
202
+
203
+ st_outer = ShardedTensor._init_from_local_shards_and_global_metadata(
204
+ shards,
205
+ sharded_tensor_metadata=st_meta,
206
+ process_group=dt_pg,
207
+ init_rrefs=False,
208
+ )
209
+
210
+ return st_outer
211
+ else:
212
+ return _create_chunk_sharded_tensor(
213
+ tensor,
214
+ rank,
215
+ world_size,
216
+ num_devices_per_node,
217
+ pg,
218
+ )
219
+
220
+
221
+ def _chunk_dtensor(
222
+ tensor: torch.Tensor,
223
+ rank: int,
224
+ device_mesh: DeviceMesh,
225
+ ) -> DTensor:
226
+ """
227
+ Shard a tensor to chunks along the first dimension.
228
+
229
+ The local rank will gets its corresponding chunk as the local tensor to create a DTensor.
230
+ """
231
+ root_mesh = device_mesh._get_root_mesh() if device_mesh is not None else None
232
+ if root_mesh is None:
233
+ raise RuntimeError("No parent device_mesh is found for FSDP device_mesh.")
234
+ if root_mesh.ndim < 2:
235
+ raise RuntimeError(
236
+ f"Found parent device_mesh of ndim={root_mesh.ndim},",
237
+ "but meshes must be at least 2D.",
238
+ )
239
+
240
+ # We need to explicitly call .detach() to return a new tensor detached from the current graph.
241
+ tensor = tensor.detach().clone()
242
+
243
+ # When a layer is not involved in TP, then the tensor will not be a DTensor.
244
+ # e.g. When a layer is not sppecified in the parallelize_plan, TP will have no effect on the layer.
245
+ # e.g. When you do PairwiseParallel on a 3 layer model, TP will have no effect on the third layer.
246
+ if isinstance(tensor, torch.Tensor) and not isinstance(tensor, DTensor):
247
+ # For tensors, it is replicated across tp dimension and sharded across FSDP dimension.
248
+ # TP is the inner dimension and FSDP is the outer dimension.
249
+ # Therefore, shard placements for tensor is (Shard(0), Replicate()).
250
+ replicate_placements = [Replicate() for _ in range(root_mesh.ndim)]
251
+ shard_placements = [Replicate() for _ in range(root_mesh.ndim)]
252
+ shard_placements[0] = DShard(0) # type: ignore[call-overload]
253
+
254
+ return DTensor.from_local(
255
+ tensor, root_mesh, replicate_placements, run_check=False
256
+ ).redistribute(
257
+ device_mesh=root_mesh,
258
+ placements=shard_placements,
259
+ )
260
+
261
+ else:
262
+ tp_placements = tensor.placements
263
+ tp_placement = tp_placements[0]
264
+
265
+ tensor = tensor.to_local()
266
+
267
+ # For DTensors, it is sharded across tp dimension first and then sharded across FSDP dimension.
268
+ # TP is the inner dimension and FSDP is the outer dimension.
269
+ # Therefore, shard placements for tensor is (Shard(0), tp_placement).
270
+ # For higher dimensional meshes, it is replicated across other dimensions. For example, with
271
+ # HSDP the shard placements for tensor is (Replicate, Shard(0), tp_placement).
272
+ replicate_placements = [Replicate() for _ in range(root_mesh.ndim)]
273
+ replicate_placements[-1] = tp_placement # type: ignore[call-overload]
274
+ shard_placements = [Replicate() for i in range(root_mesh.ndim)] # type: ignore[misc]
275
+ shard_placements[-2] = DShard(0) # type: ignore[call-overload]
276
+ shard_placements[-1] = tp_placement # type: ignore[call-overload]
277
+
278
+ return DTensor.from_local(
279
+ tensor, root_mesh, replicate_placements, run_check=False
280
+ ).redistribute(
281
+ device_mesh=root_mesh,
282
+ placements=shard_placements,
283
+ )
284
+
285
+
286
+ def _pre_load_state_dict(
287
+ tensor: torch.Tensor,
288
+ ) -> tuple[torch.Tensor, list[Shard]]:
289
+ shards = cast(ShardedTensor, tensor).local_shards()
290
+ if len(shards) == 1 and type(shards[0].tensor) is ShardedTensor:
291
+ inner_tensor = shards[0].tensor
292
+ shards = inner_tensor.local_shards() # pyre-ignore[16]
293
+ tensor = inner_tensor
294
+
295
+ return (tensor, shards if len(shards) > 0 else [])
296
+
297
+
298
+ def _all_gather_dtensor(
299
+ tensor: DTensor,
300
+ parent_mesh: DeviceMesh | None,
301
+ ) -> torch.Tensor:
302
+ """All gather a DTensor in its FSDP dimension and return the local tensor."""
303
+ assert parent_mesh == tensor.device_mesh
304
+
305
+ placements = list(copy.deepcopy(tensor.placements))
306
+ # FSDP + TP: [Shard(0), tp_placement] -> [Replicate(), tp_placement]
307
+ # HSDP + TP: [Replicate(), Shard(0), tp_placement] -> [Replicate(), Replicate(), tp_placement]
308
+ for i in range(len(placements) - 1):
309
+ placements[i] = Replicate()
310
+ tensor = tensor.redistribute(
311
+ device_mesh=tensor.device_mesh,
312
+ placements=placements,
313
+ )
314
+
315
+ return tensor.to_local()
316
+
317
+
318
+ class DTensorExtensions(FSDPExtensions):
319
+ """
320
+ DTensorExtension is the TensorFlattener extension needed for 2D FSDP + TP.
321
+
322
+ This is the implementation for FSDPExtensions defined in
323
+ https://github.com/pytorch/pytorch/blob/main/torch/distributed/fsdp/_fsdp_extensions.py
324
+ """
325
+
326
+ def __init__(self, device_handle) -> None:
327
+ super().__init__()
328
+ self.compute_stream = None
329
+ self.device_handle = device_handle
330
+ # we have to use the dynamo disable this way to disable dynamo as the decorator way would
331
+ # trigger build failure with torch deploy...
332
+ self.post_unflatten_transform = torch._dynamo.disable( # type: ignore[method-assign]
333
+ self.post_unflatten_transform
334
+ )
335
+
336
+ def pre_flatten_transform(
337
+ self,
338
+ tensor: torch.Tensor,
339
+ ) -> tuple[torch.Tensor, Any | None]:
340
+ return _flatten_tensor(tensor)
341
+
342
+ def post_unflatten_transform(
343
+ self, tensor: torch.Tensor, param_extension: Any
344
+ ) -> torch.Tensor:
345
+ stream = self.compute_stream or self.device_handle.current_stream()
346
+ with self.device_handle.stream(stream):
347
+ # runtime we put the unflattened tensor call on the compute stream since
348
+ # the unflattened tensor might contain computations in fwd/bwd where we
349
+ # need to sync properly.
350
+ # TODO: this is a short term fix and we should make the get_unflat_views
351
+ # directly happen in the compute stream.
352
+ result = _unflatten_tensor(
353
+ tensor,
354
+ param_extension,
355
+ device_handle=self.device_handle,
356
+ compute_stream=self.compute_stream,
357
+ )
358
+ _set_fsdp_flattened(result)
359
+ return result
360
+
361
+ def chunk_tensor(
362
+ self,
363
+ tensor: torch.Tensor,
364
+ rank: int,
365
+ world_size: int,
366
+ num_devices_per_node: int,
367
+ pg: dist.ProcessGroup,
368
+ device: torch.device | None = None,
369
+ ) -> torch.Tensor:
370
+ return _chunk_tensor(tensor, rank, world_size, num_devices_per_node, pg)
371
+
372
+ def chunk_dtensor(
373
+ self,
374
+ tensor: torch.Tensor,
375
+ rank: int,
376
+ device_mesh: DeviceMesh,
377
+ ) -> torch.Tensor:
378
+ return _chunk_dtensor(tensor, rank, device_mesh)
379
+
380
+ def pre_load_state_dict_transform(
381
+ self,
382
+ tensor: torch.Tensor,
383
+ ) -> tuple[torch.Tensor, list[Shard]]:
384
+ return _pre_load_state_dict(tensor)
385
+
386
+ def all_gather_dtensor(
387
+ self,
388
+ tensor: DTensor,
389
+ parent_mesh: DeviceMesh | None,
390
+ ) -> torch.Tensor:
391
+ return _all_gather_dtensor(tensor, parent_mesh)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/input_reshard.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ from functools import partial
3
+ from typing import Any
4
+
5
+ import torch
6
+ from torch.distributed.tensor import DeviceMesh, DTensor, Replicate, Shard
7
+
8
+
9
+ __all__ = [
10
+ "input_reshard",
11
+ ]
12
+
13
+
14
+ def input_reshard(
15
+ module: torch.nn.Module,
16
+ tp_device_mesh: DeviceMesh,
17
+ input_reshard_dim: int | None = None,
18
+ ) -> torch.nn.Module:
19
+ """
20
+ Register hooks to an nn.Module for input resharding, enabling sharding and restoration during backward computation.
21
+
22
+ Register hooks to an nn.Module with input resharding so that we can shard
23
+ per the given `tp_device_mesh` and `input_reshard_dim` and restore the
24
+ input back when recomputing the activations in the backward. The reason
25
+ why we can do this is that for Tensor Parallel(TP), the input are same
26
+ across all TP ranks.
27
+
28
+ Args:
29
+ module (:class:`nn.Module`):
30
+ Module to be registered with input resharding.
31
+ tp_device_mesh (:class:`DeviceMesh`):
32
+ Object which describes the mesh topology
33
+ of devices for Tensor Parallel.
34
+ input_reshard_dim (Optional[int]):
35
+ The dimension of where we perform the sharding
36
+ of input. If set None, there is no sharding of input.
37
+ Default: None
38
+
39
+ Return:
40
+ A :class:`nn.Module` object registered with TP input resharding.
41
+ """
42
+ if input_reshard_dim is None:
43
+ return module
44
+
45
+ cx: torch.autograd.graph.saved_tensors_hooks | None = None
46
+
47
+ def input_reshard_forward_pre_hook(_: torch.nn.Module, _i: tuple[Any, ...]) -> None:
48
+ saved_tensor_hooks = torch.autograd.graph.saved_tensors_hooks(
49
+ partial(_pack_hook_tp, tp_device_mesh, input_reshard_dim),
50
+ partial(_unpack_hook_tp, tp_device_mesh, input_reshard_dim),
51
+ )
52
+ saved_tensor_hooks.__enter__()
53
+ nonlocal cx
54
+ cx = saved_tensor_hooks # type: ignore[name-defined]
55
+
56
+ def input_reshard_backward_hook(
57
+ _: torch.nn.Module, _i: tuple[Any, ...], _o: Any
58
+ ) -> Any:
59
+ nonlocal cx
60
+ cx.__exit__() # type: ignore[name-defined, union-attr]
61
+
62
+ module.register_forward_pre_hook(input_reshard_forward_pre_hook)
63
+ module.register_forward_hook(input_reshard_backward_hook)
64
+ return module
65
+
66
+
67
+ def _pack_hook_tp(mesh: DeviceMesh, input_reshard_dim: int, x: torch.Tensor) -> Any: # noqa: D401
68
+ """Hook function called after FWD to shard input."""
69
+ if isinstance(x, DTensor) and all(p.is_replicate() for p in x._spec.placements):
70
+ return x.redistribute(device_mesh=mesh, placements=[Shard(input_reshard_dim)])
71
+ elif (
72
+ not isinstance(x, DTensor)
73
+ and isinstance(x, torch.Tensor)
74
+ and x.numel() >= mesh.size()
75
+ ):
76
+ return (
77
+ DTensor.from_local(x, device_mesh=mesh)
78
+ .redistribute(device_mesh=mesh, placements=[Shard(input_reshard_dim)])
79
+ .to_local()
80
+ )
81
+ else:
82
+ return x
83
+
84
+
85
+ def _unpack_hook_tp(mesh: DeviceMesh, input_reshard_dim: int, x: Any) -> torch.Tensor: # noqa: D401
86
+ """Hook function called before activation recomputing in BWD to restore input."""
87
+ if (
88
+ isinstance(x, DTensor)
89
+ and len(x._spec.placements) == 1
90
+ and x._spec.placements[0].is_shard()
91
+ ):
92
+ return x.redistribute(device_mesh=mesh, placements=[Replicate()])
93
+ elif (
94
+ not isinstance(x, DTensor)
95
+ and isinstance(x, torch.Tensor)
96
+ and x.numel() >= mesh.size()
97
+ ):
98
+ return (
99
+ DTensor.from_local(
100
+ x, device_mesh=mesh, placements=[Shard(input_reshard_dim)]
101
+ )
102
+ .redistribute(device_mesh=mesh, placements=[Replicate()])
103
+ .to_local()
104
+ )
105
+ else:
106
+ return x
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/loss.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+ import contextlib
4
+ from typing import cast
5
+
6
+ import torch
7
+ import torch._prims_common as utils
8
+ import torch.distributed._functional_collectives as funcol
9
+ import torch.distributed.distributed_c10d as c10d
10
+ from torch import Tensor
11
+ from torch.distributed.device_mesh import DeviceMesh
12
+ from torch.distributed.tensor import DTensor, Replicate, Shard
13
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
14
+ from torch.distributed.tensor._ops._embedding_ops import MaskPartial
15
+ from torch.distributed.tensor._ops._math_ops import (
16
+ _skip_dim,
17
+ Reduction,
18
+ replicate_reduction_dims,
19
+ )
20
+ from torch.distributed.tensor._ops.utils import normalize_dim
21
+ from torch.distributed.tensor.placement_types import Placement
22
+
23
+
24
+ aten = torch.ops.aten
25
+
26
+
27
+ __all__ = ["loss_parallel"]
28
+
29
+
30
+ @contextlib.contextmanager
31
+ def loss_parallel():
32
+ """
33
+ A context manager that enables loss parallelism, where efficient parallelized loss computation
34
+ can be performed when the input is sharded on the class dimension. Currently only the cross-entropy
35
+ loss is supported.
36
+
37
+ Within this context manager, one can use :func:`~torch.nn.functional.cross_entropy` or
38
+ :class:`~torch.nn.CrossEntropyLoss` as usual, with the following assumptions on the input parameters.
39
+ The corresponding ``backward()`` call, if any, also needs to happen under this context manager.
40
+
41
+ Args:
42
+ input (:class:`DTensor`):
43
+ Input logits. Assumed to be sharded on the class dimension.
44
+ target (Union[:class:`torch.Tensor`, :class:`DTensor`]):
45
+ Must be ground truth class indices (class probabilities currently not supported).
46
+ Assumed to be replicated across the ``DeviceMesh``.
47
+ weight (Union[:class:`torch.Tensor`, :class:`DTensor`], optional):
48
+ If given, assumed to be replicated across the ``DeviceMesh``.
49
+ label_smoothing:
50
+ Currently not supported.
51
+
52
+ Returns:
53
+ A replicated :class:`DTensor`.
54
+
55
+ Example:
56
+ A sharded DTensor is manually created here to showcase the usage.
57
+ In practice, it is usually the output of a TP module.
58
+
59
+ >>> # xdoctest: +SKIP("distributed")
60
+ >>> from torch.distributed.tensor.parallel import loss_parallel
61
+ >>> from torch.distributed.device_mesh import init_device_mesh
62
+ >>> ...
63
+ >>> device_mesh = init_device_mesh("cuda", (8,))
64
+ >>> input = torch.randn(4, 16, device="cuda", requires_grad=True)
65
+ >>> dist_input = distribute_tensor(input, device_mesh, placements=[Shard(1)])
66
+ >>> target = torch.randint(16, (4,), device="cuda")
67
+ >>> with loss_parallel():
68
+ >>> loss = F.cross_entropy(dist_input, target, reduction="mean")
69
+ >>> loss.backward()
70
+ >>> ...
71
+ """
72
+ _enable_custom_loss_ops()
73
+
74
+ yield
75
+
76
+ _disable_custom_loss_ops()
77
+
78
+
79
+ # Currently only needs to support one dimensional DeviceMesh; in general return
80
+ # the mesh_dim with placements[mesh_dim].is_shard(dim)
81
+ def _find_all_reduce_mesh_dim(placements: tuple[Placement, ...], dim: int) -> int:
82
+ if not len(placements) == 1:
83
+ raise ValueError(
84
+ "Currently loss_parallel() only supports input on one-dimensional DeviceMesh."
85
+ )
86
+ if not placements[0].is_shard(dim):
87
+ raise ValueError(
88
+ f"loss_parallel() should be enabled only when the input tensor is sharded on dimension {dim}."
89
+ )
90
+ return 0
91
+
92
+
93
+ def _cast_to_dtensor(
94
+ tensor, placements: tuple[Placement, ...], mesh: DeviceMesh
95
+ ) -> DTensor:
96
+ if isinstance(tensor, DTensor):
97
+ if tensor.placements == placements:
98
+ return tensor
99
+ else:
100
+ raise RuntimeError(f"Expected {placements} but got {tensor.placements}.")
101
+ elif isinstance(tensor, torch.Tensor):
102
+ return DTensor.from_local(
103
+ tensor, device_mesh=mesh, placements=placements, run_check=False
104
+ )
105
+ else:
106
+ raise TypeError(f"Unsupported type {type(tensor)}")
107
+
108
+
109
+ def _propagate_tensor_meta(
110
+ op_call: torch._ops.OpOverload,
111
+ args: tuple[object, ...],
112
+ kwargs: dict[str, object],
113
+ ) -> TensorMeta:
114
+ op_info = DTensor._op_dispatcher.unwrap_to_op_info(op_call, args, kwargs)
115
+ tensor_meta = DTensor._op_dispatcher.sharding_propagator.propagate_tensor_meta(
116
+ op_info.schema
117
+ )
118
+ if isinstance(tensor_meta, TensorMeta):
119
+ return tensor_meta
120
+ elif isinstance(tensor_meta, tuple):
121
+ return tensor_meta[0]
122
+ else:
123
+ raise RuntimeError(f"Unexpected tensor meta type: {type(tensor_meta)}.")
124
+
125
+
126
+ # NOTE: The implementation follows torch._decomp.decomposition._log_softmax,
127
+ # with all_reduce manually inserted to perform distributed computation.
128
+ def _log_softmax(x, dim, half_to_float, mesh, mesh_dim):
129
+ if half_to_float:
130
+ assert x.dtype == torch.half
131
+ computation_dtype, result_dtype = utils.elementwise_dtypes(
132
+ x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
133
+ )
134
+ x = x.to(dtype=computation_dtype, memory_format=torch.contiguous_format)
135
+ if x.numel() == 0:
136
+ shifted = x
137
+ else:
138
+ x_max = torch.amax(x, dim, keepdim=True)
139
+ x_max = funcol.all_reduce(
140
+ x_max, reduceOp=c10d.ReduceOp.MAX.name, group=(mesh, mesh_dim)
141
+ )
142
+ shifted = x - x_max
143
+ shifted_sumexp = torch.sum(torch.exp(shifted), dim, keepdim=True)
144
+ shifted_sumexp = funcol.all_reduce(
145
+ shifted_sumexp, reduceOp=c10d.ReduceOp.SUM.name, group=(mesh, mesh_dim)
146
+ )
147
+ shifted_logsumexp = torch.log(shifted_sumexp)
148
+ result = shifted - shifted_logsumexp
149
+ if not half_to_float:
150
+ result = result.to(result_dtype)
151
+ return result
152
+
153
+
154
+ def _log_softmax_handler(
155
+ op_call: torch._ops.OpOverload,
156
+ args: tuple[object, ...],
157
+ kwargs: dict[str, object],
158
+ ) -> object:
159
+ x = cast(DTensor, args[0])
160
+ dim = cast(int, args[1])
161
+ half_to_float = cast(bool, args[2])
162
+
163
+ spec = x._spec
164
+ dim = normalize_dim(dim, x.dim())
165
+ mesh_dim = _find_all_reduce_mesh_dim(spec.placements, dim)
166
+
167
+ output_tensor_meta = _propagate_tensor_meta(op_call, args, kwargs)
168
+
169
+ res = _log_softmax(x._local_tensor, dim, half_to_float, spec.mesh, mesh_dim)
170
+
171
+ res_spec = DTensorSpec(
172
+ spec.mesh,
173
+ spec.placements,
174
+ tensor_meta=output_tensor_meta,
175
+ )
176
+
177
+ # pyrefly: ignore [bad-argument-type]
178
+ return DTensor(
179
+ # pyrefly: ignore [bad-argument-count]
180
+ res,
181
+ res_spec,
182
+ # pyrefly: ignore [unexpected-keyword]
183
+ requires_grad=res.requires_grad,
184
+ )
185
+
186
+
187
+ # NOTE: As explained below at _nll_loss_and_log_softmax_backward, the
188
+ # _log_softmax_backward_handler does not actually do any computation.
189
+ def _log_softmax_backward_handler(
190
+ op_call: torch._ops.OpOverload,
191
+ args: tuple[object, ...],
192
+ kwargs: dict[str, object],
193
+ ) -> object:
194
+ grad_output = cast(DTensor, args[0])
195
+ input_dtype = cast(torch.dtype, args[3])
196
+ return grad_output.to(input_dtype)
197
+
198
+
199
+ # NOTE: The implementation follows torch._decomp.decomposition._nll_loss_forward,
200
+ # with customized communication inserted to perform distributed computation.
201
+ def _nll_loss_forward(
202
+ x: Tensor,
203
+ target: Tensor,
204
+ weight: Tensor | None,
205
+ local_weight: Tensor | None,
206
+ reduction: int,
207
+ ignore_index: int,
208
+ input_shape: torch.Size,
209
+ channel_dim: int,
210
+ mesh: DeviceMesh,
211
+ mesh_dim: int,
212
+ ) -> tuple[Tensor, Tensor]:
213
+ n_dims = x.dim()
214
+ channel_dim = 1
215
+ if n_dims < 2:
216
+ channel_dim = 0
217
+
218
+ def _weight_view(weight: Tensor) -> Tensor:
219
+ if n_dims > 1:
220
+ shape = [
221
+ 1,
222
+ ] * n_dims
223
+ shape[channel_dim] = weight.shape[0]
224
+ w = weight.view(shape)
225
+ else:
226
+ w = weight
227
+ return w
228
+
229
+ if weight is not None:
230
+ w = _weight_view(weight)
231
+ assert local_weight is not None
232
+ local_w = _weight_view(local_weight)
233
+ x = x * local_w
234
+ safe_target = torch.where(target != ignore_index, target, 0)
235
+ safe_target_ = safe_target.unsqueeze(channel_dim)
236
+
237
+ # The following code block is a distributed version of
238
+ # result = -torch.gather(self, channel_dim, safe_target_).squeeze(channel_dim)
239
+ partial_placement = MaskPartial(offset_shape=input_shape, offset_dim=channel_dim)
240
+ safe_target_partial_ = partial_placement._partition_value(
241
+ safe_target_, mesh, mesh_dim
242
+ )
243
+ result_partial = torch.gather(x, channel_dim, safe_target_partial_)
244
+ # an all_reduce happens here
245
+ result_reduced = partial_placement._reduce_value(result_partial, mesh, mesh_dim)
246
+ result = -result_reduced.squeeze(channel_dim)
247
+
248
+ result = torch.where(target != ignore_index, result, 0)
249
+
250
+ if reduction == Reduction.NONE.value and n_dims > 1:
251
+ total_weight = x.new_full((), 0.0)
252
+ return result, total_weight
253
+
254
+ if weight is not None:
255
+ new_shape = list(x.shape)
256
+ new_shape[channel_dim] = -1
257
+ # pyrefly: ignore [unbound-name]
258
+ w = w.expand(new_shape)
259
+ wsum = torch.gather(w, channel_dim, safe_target_).squeeze(channel_dim)
260
+ wsum = torch.where(target != ignore_index, wsum, 0)
261
+ total_weight = wsum.sum()
262
+ else:
263
+ total_weight = (target != ignore_index).sum().to(x)
264
+
265
+ # NOTE: this is correct only on 1D DeviceMesh; o/w additional
266
+ # all-reduce on result and total_weight is needed
267
+ if reduction == Reduction.SUM.value:
268
+ result = result.sum()
269
+ elif reduction == Reduction.MEAN.value:
270
+ result = result.sum() / total_weight
271
+
272
+ return result, total_weight
273
+
274
+
275
+ def _nll_loss_forward_handler(
276
+ op_call: torch._ops.OpOverload,
277
+ args: tuple[object, ...],
278
+ kwargs: dict[str, object],
279
+ ) -> object:
280
+ x = cast(DTensor, args[0])
281
+ target = args[1]
282
+ weight = args[2]
283
+ reduction = cast(int, args[3])
284
+ ignore_index = cast(int, args[4])
285
+
286
+ channel_dim = 1 if x.dim() >= 2 else 0
287
+ spec = x._spec
288
+ mesh_dim = _find_all_reduce_mesh_dim(spec.placements, channel_dim)
289
+
290
+ # Check user input: if target and weight are not DTensors, convert them to DTensors;
291
+ # if they are DTensors, check that they have the desired placements.
292
+ target_placements = _skip_dim(
293
+ replicate_reduction_dims(spec.placements, [channel_dim]), channel_dim
294
+ )
295
+ all_replicate_placements = (Replicate(),) * spec.mesh.ndim
296
+ target = _cast_to_dtensor(target, target_placements, spec.mesh)
297
+ local_weight = None
298
+ if weight is not None:
299
+ weight = _cast_to_dtensor(weight, all_replicate_placements, spec.mesh)
300
+ # For local computation, both (replicated) weight and (sharded) local_weight
301
+ # are needed in _nll_loss_forward(). local_weight is generated here using
302
+ # DTensor API, without incurring any communication.
303
+ sharded_placements = [
304
+ Shard(0) if i == mesh_dim else Replicate() for i in range(spec.mesh.ndim)
305
+ ]
306
+ local_weight = weight.redistribute(spec.mesh, sharded_placements)._local_tensor
307
+ assert local_weight.shape[0] == x._local_tensor.shape[channel_dim]
308
+
309
+ if reduction == Reduction.NONE.value:
310
+ output_placements = target_placements
311
+ else:
312
+ output_placements = all_replicate_placements
313
+
314
+ # tensor inputs to _propagate_tensor_meta need to be DTensors
315
+ # pyrefly: ignore [bad-assignment]
316
+ args = list(args)
317
+ # pyrefly: ignore [unsupported-operation]
318
+ args[1], args[2] = target, weight
319
+ output_tensor_meta = _propagate_tensor_meta(op_call, tuple(args), kwargs)
320
+
321
+ result, total_weight = _nll_loss_forward(
322
+ x._local_tensor,
323
+ target._local_tensor,
324
+ weight._local_tensor if weight is not None else None,
325
+ local_weight,
326
+ reduction,
327
+ ignore_index,
328
+ x.shape,
329
+ channel_dim,
330
+ spec.mesh,
331
+ mesh_dim,
332
+ )
333
+ out_spec = DTensorSpec(spec.mesh, output_placements, tensor_meta=output_tensor_meta)
334
+
335
+ return (
336
+ # pyrefly: ignore [bad-argument-type]
337
+ DTensor(
338
+ # pyrefly: ignore [bad-argument-count]
339
+ result,
340
+ out_spec,
341
+ # pyrefly: ignore [unexpected-keyword]
342
+ requires_grad=result.requires_grad,
343
+ ),
344
+ total_weight,
345
+ )
346
+
347
+
348
+ # NOTE: The backward computation of cross_entropy goes through two steps:
349
+ # backward for nll_loss and then backward for log_softmax. In loss parallel,
350
+ # the two steps are fused into the following function (called by _nll_loss_backward_handler)
351
+ # to avoid communication when target contains class indices not class probabilities.
352
+ # Also note that the _log_softmax_backward_handler does not perform computation.
353
+ # The implementation resembles _nll_loss_backward and _log_softmax_backward_data
354
+ # from torch._decomp.decomposition.
355
+ def _nll_loss_and_log_softmax_backward(
356
+ grad_output: Tensor,
357
+ x: Tensor,
358
+ target: Tensor,
359
+ weight: Tensor | None,
360
+ reduction: int,
361
+ ignore_index: int,
362
+ total_weight: Tensor,
363
+ input_shape: torch.Size,
364
+ channel_dim: int,
365
+ mesh: DeviceMesh,
366
+ mesh_dim: int,
367
+ ) -> Tensor:
368
+ channel_dim = 0 if x.dim() < 2 else 1
369
+ if reduction == Reduction.MEAN.value:
370
+ grad_output = grad_output / total_weight
371
+
372
+ target = target.unsqueeze(channel_dim)
373
+ safe_target = torch.where(target != ignore_index, target, 0)
374
+ grad_input = torch.zeros_like(x)
375
+
376
+ # The following code block is a distributed version of
377
+ # grad_input = torch.scatter(grad_input, channel_dim, safe_target, -1.0)
378
+ partial_placement = MaskPartial(offset_shape=input_shape, offset_dim=channel_dim)
379
+ safe_target = safe_target.squeeze(channel_dim).flatten()
380
+ masked_safe_target = partial_placement._partition_value(safe_target, mesh, mesh_dim)
381
+ # only update grad_input to -1 if not masked
382
+ assert partial_placement.mask_buffer.data is not None
383
+ grad_update = partial_placement.mask_buffer.data.to(grad_input.dtype) - 1.0
384
+ arange_1d = torch.arange(
385
+ masked_safe_target.shape[0], device=masked_safe_target.device
386
+ )
387
+ # The first two cases with x.dim() <= 2 are for aten.nll_loss_backward.default;
388
+ # the last case is for aten.nll_loss2d_backward.default.
389
+ if x.dim() == 1:
390
+ grad_input[masked_safe_target] = grad_update
391
+ elif x.dim() == 2:
392
+ grad_input[arange_1d, masked_safe_target] = grad_update
393
+ else:
394
+ grad_input_t = grad_input.transpose(channel_dim, -1)
395
+ intermidate_shape = grad_input_t.shape
396
+ grad_input_2d = grad_input_t.reshape(-1, x.shape[channel_dim])
397
+ grad_input_2d[arange_1d, masked_safe_target] = grad_update
398
+ grad_input = grad_input_2d.view(intermidate_shape).transpose(channel_dim, -1)
399
+
400
+ if grad_input.dim() > grad_output.dim() > 0:
401
+ grad_output = grad_output.unsqueeze(channel_dim)
402
+
403
+ if weight is not None:
404
+ new_shape = [1 for _ in range(x.dim())]
405
+ new_shape[channel_dim] = weight.shape[0]
406
+ weight = weight.reshape(new_shape)
407
+ # In order for fused computation to work, the following line is rewritten.
408
+ # grad_output = grad_output * weight
409
+ new_shape = list(x.shape)
410
+ new_shape[channel_dim] = -1
411
+ w = weight.expand(new_shape)
412
+ w_target = torch.gather(w, channel_dim, target)
413
+ grad_output = grad_output * w_target
414
+
415
+ grad_output = torch.where(target != ignore_index, grad_output, 0)
416
+
417
+ # NOTE: Instead of directly returning the grad_input as grad_output for log_softmax,
418
+ # here we perform backward computation for log_softmax altogether to avoid the
419
+ # otherwise extra all_gather communication.
420
+ # return grad_input * grad_output
421
+ return (grad_input + torch.exp(x)) * grad_output
422
+
423
+
424
+ def _nll_loss_backward_handler(
425
+ op_call: torch._ops.OpOverload,
426
+ args: tuple[object, ...],
427
+ kwargs: dict[str, object],
428
+ ) -> object:
429
+ grad_output = cast(DTensor, args[0])
430
+ x = cast(DTensor, args[1])
431
+ target = args[2]
432
+ weight = args[3]
433
+ reduction = cast(int, args[4])
434
+ ignore_index = cast(int, args[5])
435
+ total_weight = cast(Tensor, args[6])
436
+
437
+ channel_dim = 1 if x.dim() >= 2 else 0
438
+ spec = x._spec
439
+ mesh_dim = _find_all_reduce_mesh_dim(spec.placements, channel_dim)
440
+
441
+ # if target and weight are not DTensors, convert them to DTensors
442
+ target_placements = _skip_dim(
443
+ replicate_reduction_dims(spec.placements, [channel_dim]), channel_dim
444
+ )
445
+ all_replicate_placements = (Replicate(),) * spec.mesh.ndim
446
+ target = _cast_to_dtensor(target, target_placements, spec.mesh)
447
+ if weight is not None:
448
+ weight = _cast_to_dtensor(weight, all_replicate_placements, spec.mesh)
449
+
450
+ # tensor inputs to _propagate_tensor_meta need to be DTensors
451
+ # pyrefly: ignore [bad-assignment]
452
+ args = list(args)
453
+ # pyrefly: ignore [unsupported-operation]
454
+ args[2], args[3] = target, weight
455
+ # pyrefly: ignore [unsupported-operation]
456
+ args[6] = _cast_to_dtensor(total_weight, all_replicate_placements, spec.mesh)
457
+ output_tensor_meta = _propagate_tensor_meta(op_call, tuple(args), kwargs)
458
+
459
+ result = _nll_loss_and_log_softmax_backward(
460
+ grad_output._local_tensor,
461
+ x._local_tensor,
462
+ target._local_tensor,
463
+ weight._local_tensor if weight is not None else None,
464
+ reduction,
465
+ ignore_index,
466
+ total_weight,
467
+ x.shape,
468
+ channel_dim,
469
+ spec.mesh,
470
+ mesh_dim,
471
+ )
472
+ # the output sharding is the same as input sharding: Shard(channel_dim) on mesh_dim
473
+ out_spec = DTensorSpec(
474
+ spec.mesh,
475
+ spec.placements,
476
+ tensor_meta=output_tensor_meta,
477
+ )
478
+
479
+ # pyrefly: ignore [bad-argument-type]
480
+ return DTensor(
481
+ # pyrefly: ignore [bad-argument-count]
482
+ result,
483
+ out_spec,
484
+ # pyrefly: ignore [unexpected-keyword]
485
+ requires_grad=result.requires_grad,
486
+ )
487
+
488
+
489
+ customized_loss_ops = {
490
+ aten._log_softmax.default: _log_softmax_handler,
491
+ aten._log_softmax_backward_data.default: _log_softmax_backward_handler,
492
+ aten.nll_loss_forward.default: _nll_loss_forward_handler,
493
+ aten.nll_loss2d_forward.default: _nll_loss_forward_handler,
494
+ aten.nll_loss_backward.default: _nll_loss_backward_handler,
495
+ aten.nll_loss2d_backward.default: _nll_loss_backward_handler,
496
+ }
497
+
498
+
499
+ def _enable_custom_loss_ops():
500
+ DTensor._op_dispatcher._custom_op_handlers.update(customized_loss_ops)
501
+
502
+
503
+ def _disable_custom_loss_ops():
504
+ for custom_op in customized_loss_ops:
505
+ DTensor._op_dispatcher._custom_op_handlers.pop(custom_op)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/parallel/style.py ADDED
@@ -0,0 +1,810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+ from abc import ABC, abstractmethod
4
+ from functools import partial
5
+ from typing import Any
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ from torch.distributed.tensor import (
10
+ DeviceMesh,
11
+ distribute_module,
12
+ distribute_tensor,
13
+ DTensor,
14
+ Replicate,
15
+ Shard,
16
+ )
17
+ from torch.distributed.tensor.placement_types import Placement
18
+
19
+
20
+ __all__ = [
21
+ "ParallelStyle",
22
+ "RowwiseParallel",
23
+ "SequenceParallel",
24
+ "ColwiseParallel",
25
+ "PrepareModuleInput",
26
+ "PrepareModuleInputOutput",
27
+ "PrepareModuleOutput",
28
+ ]
29
+
30
+
31
+ class ParallelStyle(ABC):
32
+ """
33
+ The parallel style contract defines how the module or submodule should be parallelized.
34
+
35
+ It only defines the ``apply`` method for ``parallelize_module`` to use, this allows maximum
36
+ flexibility for different kind of style implementations.
37
+ """
38
+
39
+ src_data_rank: int | None = 0
40
+
41
+ @abstractmethod
42
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module: ...
43
+
44
+
45
+ class ColwiseParallel(ParallelStyle):
46
+ """
47
+ Partition a compatible nn.Module in a column-wise fashion. Currently supports nn.Linear and nn.Embedding.
48
+ Users can compose it together with RowwiseParallel to achieve the sharding of more complicated modules.
49
+ (i.e. MLP, Attention)
50
+
51
+ Keyword Args:
52
+ input_layouts (Placement, optional):
53
+ The DTensor layout of input tensor for the nn.Module, this is used to annotate the input tensor to
54
+ become a DTensor. If not specified, we assume the input tensor to be replicated.
55
+ output_layouts (Placement, optional):
56
+ The DTensor layout of the output for the nn.Module, this is used to ensure the output of the nn.Module
57
+ with the user desired layout. If not specified, the output tensor is sharded on the last dimension.
58
+ use_local_output (bool, optional):
59
+ Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: True.
60
+ Returns:
61
+ A :class:`ParallelStyle` object that represents Colwise sharding of the nn.Module.
62
+
63
+ Example::
64
+ >>> # xdoctest: +SKIP(failing)
65
+ >>> from torch.distributed.tensor.parallel import parallelize_module, ColwiseParallel
66
+ >>> from torch.distributed.device_mesh import init_device_mesh
67
+ >>> ...
68
+ >>> m = Model(...) # m is a nn.Module that contains a "w1" nn.Linear submodule
69
+ >>> tp_mesh = init_device_mesh("cuda", (8,))
70
+ >>>
71
+ >>> # By default, the input of the "w1" Linear will be converted to Replicated DTensor
72
+ >>> # and the output of "w1" will return :class:`torch.Tensor` that shards on the last dim.
73
+ >>>
74
+ >>> sharded_mod = parallelize_module(m, tp_mesh, {"w1": ColwiseParallel()})
75
+ >>> ...
76
+
77
+ .. note:: By default ``ColwiseParallel`` output is sharded on the last dimension if the ``output_layouts`` not
78
+ specified, if there're operators that require specific tensor shape (i.e. before the paired ``RowwiseParallel``),
79
+ keep in mind that if the output is sharded the operator might need to be adjusted to the sharded size.
80
+ """
81
+
82
+ def __init__(
83
+ self,
84
+ *,
85
+ input_layouts: Placement | None = None,
86
+ output_layouts: Placement | None = None,
87
+ use_local_output: bool = True,
88
+ ):
89
+ super().__init__()
90
+ self.input_layouts = (input_layouts or Replicate(),)
91
+ self.output_layouts = (output_layouts or Shard(-1),)
92
+ # colwise linear runtime sharding (desired sharding):
93
+ # 1. requires replicate input
94
+ # 2. shard output on last dim
95
+ self.desired_input_layouts = (Replicate(),)
96
+ self.use_local_output = use_local_output
97
+
98
+ @staticmethod
99
+ def _prepare_input_fn(
100
+ input_layouts, desired_input_layouts, mod, inputs, device_mesh
101
+ ):
102
+ # TODO: figure out dynamo support for instance method and switch this to instance method
103
+
104
+ # annotate module input placements/sharding with input_layouts
105
+ input_tensor = inputs[0]
106
+ if not isinstance(input_tensor, DTensor):
107
+ input_tensor = DTensor.from_local(
108
+ input_tensor, device_mesh, input_layouts, run_check=False
109
+ )
110
+
111
+ # transform the input layouts to the desired layouts of ColwiseParallel
112
+ if input_layouts != desired_input_layouts:
113
+ input_tensor = input_tensor.redistribute(
114
+ placements=desired_input_layouts, async_op=True
115
+ )
116
+ return input_tensor
117
+
118
+ def _partition_linear_fn(self, name, module, device_mesh):
119
+ # colwise shard weight/bias to Shard(0), weight be Shard(0)
120
+ # means Colwise as Linear is input * weight^T + bias, where
121
+ # weight would become Shard(1)
122
+ for name, param in module.named_parameters():
123
+ dist_param = nn.Parameter(
124
+ distribute_tensor(
125
+ param, device_mesh, [Shard(0)], src_data_rank=self.src_data_rank
126
+ )
127
+ )
128
+ module.register_parameter(name, dist_param)
129
+
130
+ def _partition_embedding_fn(self, name, module, device_mesh):
131
+ # colwise shard embedding.weight is straight forward as Shard(1)
132
+ for name, param in module.named_parameters():
133
+ dist_param = nn.Parameter(
134
+ distribute_tensor(
135
+ param, device_mesh, [Shard(1)], src_data_rank=self.src_data_rank
136
+ )
137
+ )
138
+ module.register_parameter(name, dist_param)
139
+
140
+ @staticmethod
141
+ def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh):
142
+ # outputs is a shard on last dimension DTensor, i.e. Shard(-1)
143
+ if outputs.placements != output_layouts:
144
+ outputs = outputs.redistribute(placements=output_layouts, async_op=True)
145
+ # back to local tensor
146
+ return outputs.to_local() if use_local_output else outputs
147
+
148
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
149
+ if isinstance(module, nn.Linear):
150
+ partition_fn = self._partition_linear_fn
151
+ elif isinstance(module, nn.Embedding):
152
+ partition_fn = self._partition_embedding_fn
153
+ else:
154
+ raise NotImplementedError(
155
+ "ColwiseParallel currently only support nn.Linear and nn.Embedding!"
156
+ )
157
+
158
+ return distribute_module(
159
+ module,
160
+ device_mesh,
161
+ partition_fn,
162
+ partial(
163
+ self._prepare_input_fn, self.input_layouts, self.desired_input_layouts
164
+ ),
165
+ partial(
166
+ self._prepare_output_fn, self.output_layouts, self.use_local_output
167
+ ),
168
+ )
169
+
170
+ def __repr__(self) -> str:
171
+ tmpstr = self.__class__.__name__ + "("
172
+ tmpstr += f"input_layouts={self.input_layouts}, "
173
+ tmpstr += f"output_layouts={self.output_layouts}, "
174
+ tmpstr += f"use_local_output={self.use_local_output}"
175
+ tmpstr += ")"
176
+ return tmpstr
177
+
178
+
179
+ class RowwiseParallel(ParallelStyle):
180
+ """
181
+ Partition a compatible nn.Module in a row-wise fashion. Currently supports nn.Linear and nn.Embedding.
182
+ Users can compose it with ColwiseParallel to achieve the sharding of more complicated modules.
183
+ (i.e. MLP, Attention)
184
+
185
+ Keyword Args:
186
+ input_layouts (Placement, optional):
187
+ The DTensor layout of input tensor for the nn.Module, this is used to annotate the input tensor to
188
+ become a DTensor. If not specified, we assume the input tensor to be sharded on the last dimension.
189
+ output_layouts (Placement, optional):
190
+ The DTensor layout of the output for the nn.Module, this is used to ensure the output of the nn.Module
191
+ with the user desired layout. If not specified, the output tensor is replicated.
192
+ use_local_output (bool, optional):
193
+ Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: True.
194
+ Returns:
195
+ A :class:`ParallelStyle` object that represents Rowwise sharding of the nn.Module.
196
+
197
+ Example::
198
+ >>> # xdoctest: +SKIP(failing)
199
+ >>> from torch.distributed.tensor.parallel import parallelize_module, RowwiseParallel
200
+ >>> from torch.distributed.device_mesh import init_device_mesh
201
+ >>> ...
202
+ >>> m = Model(...) # m is a nn.Module that contains a "w2" nn.Linear submodule
203
+ >>> tp_mesh = init_device_mesh("cuda", (8,))
204
+ >>>
205
+ >>> # By default, the input of the "w2" Linear will be converted to DTensor that shards on the last dim
206
+ >>> # and the output of "w2" will return a replicated :class:`torch.Tensor`.
207
+ >>>
208
+ >>> sharded_mod = parallelize_module(m, tp_mesh, {"w2": RowwiseParallel()}),
209
+ >>> ...
210
+ """
211
+
212
+ def __init__(
213
+ self,
214
+ *,
215
+ input_layouts: Placement | None = None,
216
+ output_layouts: Placement | None = None,
217
+ use_local_output: bool = True,
218
+ ):
219
+ super().__init__()
220
+ self.input_layouts = (input_layouts or Shard(-1),)
221
+ self.output_layouts = (output_layouts or Replicate(),)
222
+ self.use_local_output = use_local_output
223
+
224
+ @staticmethod
225
+ def _prepare_input_fn(
226
+ input_layouts, desired_input_layouts, mod, inputs, device_mesh
227
+ ):
228
+ input_tensor = inputs[0]
229
+ if not isinstance(input_tensor, DTensor):
230
+ input_tensor = DTensor.from_local(
231
+ input_tensor, device_mesh, input_layouts, run_check=False
232
+ )
233
+
234
+ if input_layouts != desired_input_layouts:
235
+ input_tensor = input_tensor.redistribute(
236
+ placements=desired_input_layouts, async_op=True
237
+ )
238
+ return input_tensor
239
+
240
+ def _partition_linear_fn(self, name, module, device_mesh):
241
+ # Rowwise shard weight to Shard(1), bias to Replicate(), weight be Shard(1)
242
+ # means Rowwise as nn.Linear is input * weight^T + bias, where
243
+ # weight would become Shard(0)
244
+ module.register_parameter(
245
+ "weight",
246
+ nn.Parameter(
247
+ distribute_tensor(
248
+ module.weight,
249
+ device_mesh,
250
+ [Shard(1)],
251
+ src_data_rank=self.src_data_rank,
252
+ )
253
+ ),
254
+ )
255
+ if getattr(module, "bias", None) is not None:
256
+ # The Linear module has bias
257
+ module.register_parameter(
258
+ "bias",
259
+ nn.Parameter(
260
+ distribute_tensor(
261
+ module.bias,
262
+ device_mesh,
263
+ [Replicate()],
264
+ src_data_rank=self.src_data_rank,
265
+ )
266
+ ),
267
+ )
268
+
269
+ def _partition_embedding_fn(self, name, module, device_mesh):
270
+ # rowwise shard embedding.weight is Shard(0)
271
+ for name, param in module.named_parameters():
272
+ dist_param = nn.Parameter(
273
+ distribute_tensor(
274
+ param, device_mesh, [Shard(0)], src_data_rank=self.src_data_rank
275
+ )
276
+ )
277
+ module.register_parameter(name, dist_param)
278
+
279
+ @staticmethod
280
+ def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh):
281
+ # Rowwise sharding produces partial output, depending on output layouts:
282
+ # 1. to replicate -> allreduce
283
+ # 2. to shard -> reduce_scatter
284
+ if outputs.placements != output_layouts:
285
+ outputs = outputs.redistribute(placements=output_layouts, async_op=True)
286
+ # back to local tensor if use_local_output is True
287
+ return outputs.to_local() if use_local_output else outputs
288
+
289
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
290
+ if isinstance(module, nn.Linear):
291
+ partition_fn = self._partition_linear_fn
292
+ # rowwise linear runtime sharding requires input tensor shard on last dim
293
+ self.desired_input_layouts: tuple[Placement, ...] = (Shard(-1),)
294
+ elif isinstance(module, nn.Embedding):
295
+ partition_fn = self._partition_embedding_fn
296
+ # rowwise embedding runtime sharding requires input tensor replicated
297
+ self.desired_input_layouts = (Replicate(),)
298
+ else:
299
+ raise NotImplementedError(
300
+ "RowwiseParallel currently only support nn.Linear and nn.Embedding!"
301
+ )
302
+
303
+ return distribute_module(
304
+ module,
305
+ device_mesh,
306
+ partition_fn,
307
+ partial(
308
+ self._prepare_input_fn, self.input_layouts, self.desired_input_layouts
309
+ ),
310
+ partial(
311
+ self._prepare_output_fn, self.output_layouts, self.use_local_output
312
+ ),
313
+ )
314
+
315
+ def __repr__(self) -> str:
316
+ tmpstr = self.__class__.__name__ + "("
317
+ tmpstr += f"input_layouts={self.input_layouts}, "
318
+ tmpstr += f"output_layouts={self.output_layouts}, "
319
+ tmpstr += f"use_local_output={self.use_local_output}"
320
+ tmpstr += ")"
321
+ return tmpstr
322
+
323
+
324
+ class SequenceParallel(ParallelStyle):
325
+ """
326
+ SequenceParallel replicates a compatible ``nn.Module`` parameters and runs the sharded computation with
327
+ input sharded on the sequence dimension. This currently supports ``nn.LayerNorm``, ``nn.Dropout``, and the
328
+ `RMSNorm python implementation <https://github.com/facebookresearch/llama/blob/main/llama/model.py#L34>`__
329
+
330
+ This style implements the operation that is described in the paper
331
+ `Reducing Activation Recomputation in Large Transformer Models <https://arxiv.org/abs/2205.05198>`__
332
+
333
+ If the input passed in to this ``nn.Module`` is a :class:`torch.Tensor`, it assumes that the input is already sharded
334
+ on the sequence dimension and converts the input to a :class:`DTensor` sharded on the sequence dimension. If the input
335
+ passed in to this ``nn.Module`` is already a :class:`DTensor` but is not sharded on the sequence dimension, it would
336
+ redistribute the input to be sharded on the sequence dimension.
337
+
338
+ The output of the ``nn.Module`` will be sharded on the sequence dimension.
339
+
340
+ Keyword Args:
341
+ sequence_dim (int, optional):
342
+ The sequence dimension of the input tensor for the ``nn.Module``, this is used to annotate the input tensor to
343
+ become a DTensor that is sharded on the sequence dimension, default: 1.
344
+ use_local_output (bool, optional):
345
+ Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: False.
346
+ Returns:
347
+ A :class:`ParallelStyle` object that represents Sequence Parallel of the ``nn.Module``.
348
+
349
+ Example::
350
+ >>> # xdoctest: +SKIP(failing)
351
+ >>> from torch.distributed.tensor.parallel import parallelize_module, SequenceParallel
352
+ >>> from torch.distributed.device_mesh import init_device_mesh
353
+ >>> ...
354
+ >>> m = Model(...) # m is a nn.Module that contains a "norm" nn.LayerNorm submodule
355
+ >>> tp_mesh = init_device_mesh("cuda", (8,))
356
+ >>>
357
+ >>> # By default, the input of the "norm" will be converted to DTensor that shards on the sequence dim
358
+ >>> # and the output of "norm" will return a sharded on sequence dimension :class:`DTensor`.
359
+ >>>
360
+ >>> sharded_mod = parallelize_module(m, tp_mesh, {"norm": SequenceParallel()}),
361
+ >>> ...
362
+
363
+ .. note:: SequenceParallel style assumes ones initialization if there are weights in the nn.Module (i.e.
364
+ ``nn.LayerNorm`` or ``RMSNorm``, and they by default have ones initialization). If you have custom
365
+ inits for the weights on those modules, you need to broadcast the weights before/after parallelizing
366
+ to ensure that they are replicated.
367
+ """
368
+
369
+ def __init__(self, *, sequence_dim: int = 1, use_local_output: bool = False):
370
+ super().__init__()
371
+ self.sequence_sharding = (Shard(sequence_dim),)
372
+ self.use_local_output = use_local_output
373
+
374
+ def _replicate_module_fn(
375
+ self, name: str, module: nn.Module, device_mesh: DeviceMesh
376
+ ):
377
+ for p_name, param in module.named_parameters():
378
+ # simple replication with fixed ones_ init from LayerNorm/RMSNorm, which allow
379
+ # us to simply just use from_local
380
+ replicated_param = torch.nn.Parameter(
381
+ DTensor.from_local(param, device_mesh, [Replicate()], run_check=False)
382
+ )
383
+ module.register_parameter(p_name, replicated_param)
384
+
385
+ @staticmethod
386
+ def _prepare_input_fn(sequence_sharding, mod, inputs, device_mesh):
387
+ input_tensor = inputs[0]
388
+ if isinstance(input_tensor, DTensor):
389
+ # if the passed in input DTensor is not sharded on the sequence dim, we need to redistribute it
390
+ if input_tensor.placements != sequence_sharding:
391
+ input_tensor = input_tensor.redistribute(
392
+ placements=sequence_sharding, async_op=True
393
+ )
394
+ return input_tensor
395
+ elif isinstance(input_tensor, torch.Tensor):
396
+ # assume the input passed in already sharded on the sequence dim and create the DTensor
397
+ return DTensor.from_local(
398
+ input_tensor, device_mesh, sequence_sharding, run_check=False
399
+ )
400
+ else:
401
+ raise ValueError(
402
+ f"expecting input of {mod} to be a torch.Tensor or DTensor, but got {input_tensor}"
403
+ )
404
+
405
+ @staticmethod
406
+ def _prepare_output_fn(use_local_output, mod, outputs, device_mesh):
407
+ return outputs.to_local() if use_local_output else outputs
408
+
409
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
410
+ return distribute_module(
411
+ module,
412
+ device_mesh,
413
+ self._replicate_module_fn,
414
+ partial(self._prepare_input_fn, self.sequence_sharding),
415
+ partial(self._prepare_output_fn, self.use_local_output),
416
+ )
417
+
418
+ def __repr__(self) -> str:
419
+ tmpstr = self.__class__.__name__ + "("
420
+ if len(self.sequence_sharding) == 1:
421
+ tmpstr += f"sequence_dim={self.sequence_sharding[0].dim}, "
422
+ tmpstr += f"use_local_output={self.use_local_output}"
423
+ tmpstr += ")"
424
+ return tmpstr
425
+
426
+
427
+ class PrepareModuleInput(ParallelStyle):
428
+ """
429
+ Configure the nn.Module's inputs to convert the input tensors of the nn.Module to DTensors at runtime according to
430
+ ``input_layouts``, and perform layout redistribution according to the ``desired_input_layouts``.
431
+
432
+ Keyword Args:
433
+ input_layouts (Union[Placement, Tuple[Optional[Placement]]]):
434
+ The DTensor layouts of input tensors for the nn.Module, this is used to convert the input tensors to
435
+ DTensors. If some inputs are not torch.Tensor or no need to convert to DTensors, ``None`` need to be specified
436
+ as a placeholder. default: None.
437
+ desired_input_layouts (Union[Placement, Tuple[Optional[Placement]]]):
438
+ The desired DTensor layout of input tensors for the nn.Module, this is used to ensure the inputs of the nn.Module
439
+ have the desired DTensor layouts. This argument needs to have the same length with ``input_layouts``. default: None.
440
+ input_kwarg_layouts (Dict[str, Placement]):
441
+ The DTensor layouts of input kwargs for the nn.Module, this is used to convert the input kwarg tensors to DTensors.
442
+ default: None
443
+ desired_input_kwarg_layouts: (Dict[str, Placement]):
444
+ The desired DTensor layout of input kwargs for the nn.Module, this is used to ensure the inputs of the nn.Module
445
+ have the desired DTensor layouts. default: None.
446
+ use_local_output (bool, optional):
447
+ Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module inputs, default: False.
448
+ Returns:
449
+ A :class:`ParallelStyle` object that prepares the sharding layouts of the nn.Module's inputs.
450
+
451
+ Example::
452
+ >>> # xdoctest: +SKIP(failing)
453
+ >>> from torch.distributed.tensor.parallel import parallelize_module, PrepareModuleInput
454
+ >>> from torch.distributed.device_mesh import init_device_mesh
455
+ >>> ...
456
+ >>> block = TransformerBlock(...) # block is a nn.Module that contains an "attn" Attention submodule
457
+ >>> tp_mesh = init_device_mesh("cuda", (8,))
458
+ >>>
459
+ >>> # According to the style specified below, the first input of attn will be annotated to Sharded DTensor
460
+ >>> # and then redistributed to Replicated DTensor.
461
+ >>> parallelize_module(
462
+ >>> block, # this can be a submodule or module
463
+ >>> tp_mesh,
464
+ >>> parallelize_plan={
465
+ >>> "attn": PrepareModuleInput(
466
+ >>> input_layouts=(Shard(0), None, None, ...),
467
+ >>> desired_input_layouts=(Replicate(), None, None, ...)
468
+ >>> ),
469
+ >>> }
470
+ >>> )
471
+ """
472
+
473
+ def __init__(
474
+ self,
475
+ *,
476
+ input_layouts: Placement | tuple[Placement | None, ...] | None = None,
477
+ desired_input_layouts: Placement | tuple[Placement | None, ...] | None = None,
478
+ input_kwarg_layouts: dict[str, Placement] | None = None,
479
+ desired_input_kwarg_layouts: dict[str, Placement] | None = None,
480
+ use_local_output: bool = False,
481
+ ):
482
+ self.input_layouts = (
483
+ (input_layouts,) if isinstance(input_layouts, Placement) else input_layouts
484
+ )
485
+ self.desired_input_layouts = (
486
+ (desired_input_layouts,)
487
+ if isinstance(desired_input_layouts, Placement)
488
+ else desired_input_layouts
489
+ )
490
+ self.use_local_output = use_local_output
491
+ if self.input_layouts is not None:
492
+ assert self.desired_input_layouts is not None, (
493
+ "desired module inputs should not be None!"
494
+ )
495
+ assert len(self.input_layouts) == len(self.desired_input_layouts), (
496
+ "input_layouts and desired_input_layouts should have same length!"
497
+ )
498
+ self.with_kwargs = input_kwarg_layouts is not None
499
+ self.input_kwarg_layouts = input_kwarg_layouts or {}
500
+ self.desired_input_kwarg_layouts = desired_input_kwarg_layouts or {}
501
+ if self.with_kwargs:
502
+ assert len(self.input_kwarg_layouts) == len(
503
+ self.desired_input_kwarg_layouts
504
+ ), (
505
+ "input_kwarg_layouts and desired_input_kwarg_layouts should have same length!"
506
+ )
507
+
508
+ def _prepare_input_arg(
509
+ self,
510
+ input: Any,
511
+ mesh: DeviceMesh,
512
+ input_layout: Placement | None,
513
+ desired_layout: Placement | None,
514
+ ):
515
+ if input_layout is not None:
516
+ if isinstance(input, DTensor):
517
+ # TODO: re-enable the check once we fix the compile path
518
+ # assert inp.placements[0] == input_layout
519
+ dt_inp = input
520
+ else:
521
+ assert isinstance(input, torch.Tensor), (
522
+ "expecting input to be a torch.Tensor!"
523
+ )
524
+ dt_inp = DTensor.from_local(
525
+ input, mesh, (input_layout,), run_check=False
526
+ )
527
+
528
+ if desired_layout is not None and input_layout != desired_layout:
529
+ dt_inp = dt_inp.redistribute(placements=(desired_layout,))
530
+
531
+ return dt_inp.to_local() if self.use_local_output else dt_inp
532
+ else:
533
+ return input
534
+
535
+ def _prepare_input_fn(self, inputs, device_mesh):
536
+ if self.input_layouts is None:
537
+ return inputs
538
+ prepared_inputs = []
539
+ if not isinstance(inputs, tuple):
540
+ inputs = (inputs,)
541
+ if len(inputs) != len(self.input_layouts):
542
+ raise ValueError("module inputs and input_layouts should have same length!")
543
+
544
+ assert self.desired_input_layouts is not None, (
545
+ "desired module inputs should not be None!"
546
+ )
547
+
548
+ for inp, input_layout, desired_layout in zip(
549
+ inputs, self.input_layouts, self.desired_input_layouts
550
+ ):
551
+ prepared_inputs.append(
552
+ self._prepare_input_arg(inp, device_mesh, input_layout, desired_layout)
553
+ )
554
+ return tuple(prepared_inputs)
555
+
556
+ def _prepare_input_kwarg_fn(self, inputs, kwarg_inputs, device_mesh):
557
+ prepared_arg_inputs = self._prepare_input_fn(inputs, device_mesh)
558
+ prepared_kwarg_inputs = {}
559
+ for kwarg_key in kwarg_inputs:
560
+ kwarg_val = kwarg_inputs[kwarg_key]
561
+ input_layout = self.input_kwarg_layouts.get(kwarg_key)
562
+ desired_input_layout = self.desired_input_kwarg_layouts.get(kwarg_key)
563
+
564
+ prepared_kwarg_inputs[kwarg_key] = self._prepare_input_arg(
565
+ kwarg_val, device_mesh, input_layout, desired_input_layout
566
+ )
567
+
568
+ return (prepared_arg_inputs, prepared_kwarg_inputs)
569
+
570
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
571
+ if self.with_kwargs:
572
+ module.register_forward_pre_hook(
573
+ lambda _, inputs, kwargs: self._prepare_input_kwarg_fn(
574
+ inputs, kwargs, device_mesh
575
+ ),
576
+ with_kwargs=True,
577
+ ) # type: ignore[misc]
578
+ else:
579
+ module.register_forward_pre_hook(
580
+ lambda _, inputs: self._prepare_input_fn(inputs, device_mesh)
581
+ ) # type: ignore[misc, call-arg]
582
+ return module
583
+
584
+ def __repr__(self) -> str:
585
+ tmpstr = self.__class__.__name__ + "("
586
+ tmpstr += f"input_layouts={self.input_layouts}, "
587
+ tmpstr += f"desired_input_layouts={self.desired_input_layouts}, "
588
+ tmpstr += f"input_kwarg_layouts={self.input_kwarg_layouts}, "
589
+ tmpstr += f"desired_input_kwarg_layouts={self.desired_input_kwarg_layouts}, "
590
+ tmpstr += f"use_local_output={self.use_local_output}"
591
+ tmpstr += ")"
592
+ return tmpstr
593
+
594
+
595
+ class PrepareModuleOutput(ParallelStyle):
596
+ """
597
+ Configure the nn.Module's outputs to convert the output tensors of the nn.Module to DTensors at runtime according to
598
+ ``output_layouts``, and perform layout redistribution according to the ``desired_output_layouts``.
599
+
600
+ Keyword Args:
601
+ output_layouts (Union[Placement, Tuple[Placement]]):
602
+ The DTensor layouts of output tensors for the nn.Module, this is used to convert the output tensors to
603
+ DTensors if they are :class:`torch.Tensor`. If some outputs are not torch.Tensor or no need to convert to DTensors,
604
+ ``None`` need to be specified as a placeholder.
605
+ desired_output_layouts (Union[Placement, Tuple[Placement]]):
606
+ The desired DTensor layouts of output tensors for the nn.Module, this is used to ensure the outputs of the nn.Module
607
+ have the desired DTensor layouts.
608
+ use_local_output (bool, optional):
609
+ Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module outputs, default: True.
610
+ Returns:
611
+ A ParallelStyle object that prepares the sharding layouts of the nn.Module's outputs.
612
+
613
+ Example::
614
+ >>> # xdoctest: +SKIP(failing)
615
+ >>> from torch.distributed.tensor.parallel import parallelize_module, PrepareModuleOutput
616
+ >>> from torch.distributed.device_mesh import init_device_mesh
617
+ >>> ...
618
+ >>> block = TransformerBlock(...) # block is a nn.Module that contains an "attn" Attention submodule
619
+ >>> tp_mesh = init_device_mesh("cuda", (8,))
620
+ >>>
621
+ >>> # According to the style specified below, the output of the TransformerBlock will be converted to Replicated DTensor
622
+ >>> # and then redistributed to Sharded DTensor.
623
+ >>> parallelize_module(
624
+ >>> block, # this can be a submodule or module
625
+ >>> tp_mesh,
626
+ >>> parallelize_plan = PrepareModuleOutput(
627
+ >>> output_layouts=Replicate(),
628
+ >>> desired_output_layouts=Shard(0)
629
+ >>> )
630
+ >>> )
631
+ """
632
+
633
+ def __init__(
634
+ self,
635
+ *,
636
+ output_layouts: Placement | tuple[Placement | None, ...],
637
+ desired_output_layouts: Placement | tuple[Placement, ...],
638
+ use_local_output: bool = True,
639
+ ):
640
+ self.output_layouts = (
641
+ (output_layouts,)
642
+ if isinstance(output_layouts, Placement)
643
+ else output_layouts
644
+ )
645
+ self.desired_output_layouts = (
646
+ (desired_output_layouts,)
647
+ if isinstance(desired_output_layouts, Placement)
648
+ else desired_output_layouts
649
+ )
650
+ self.use_local_output = use_local_output
651
+ assert len(self.output_layouts) == len(self.desired_output_layouts), (
652
+ "output_layouts and desired_output_layouts should have same length!"
653
+ )
654
+
655
+ def _prepare_out_fn(self, outputs, device_mesh):
656
+ prepared_outputs = []
657
+ if not isinstance(outputs, tuple):
658
+ outputs = (outputs,)
659
+ if len(outputs) != len(self.output_layouts):
660
+ raise ValueError(
661
+ "module outputs and output_layouts should have same length!"
662
+ )
663
+
664
+ for out, out_layout, desired_out_layout in zip(
665
+ outputs, self.output_layouts, self.desired_output_layouts
666
+ ):
667
+ if out_layout is not None:
668
+ if isinstance(out, DTensor):
669
+ # TODO: re-enable the check once we fix the compile path
670
+ # assert out.placements[0] == out_layout
671
+ dt_out = out
672
+ else:
673
+ dt_out = DTensor.from_local(
674
+ out, device_mesh, (out_layout,), run_check=False
675
+ )
676
+
677
+ if out_layout != desired_out_layout:
678
+ dt_out = dt_out.redistribute(placements=(desired_out_layout,))
679
+ prepared_outputs.append(
680
+ dt_out.to_local() if self.use_local_output else dt_out
681
+ )
682
+ else:
683
+ prepared_outputs.append(out)
684
+ if len(prepared_outputs) == 1:
685
+ return prepared_outputs[0]
686
+ else:
687
+ return tuple(prepared_outputs)
688
+
689
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
690
+ module.register_forward_hook(
691
+ lambda _, inputs, outputs: self._prepare_out_fn(outputs, device_mesh)
692
+ ) # type: ignore[misc, call-arg]
693
+ return module
694
+
695
+ def __repr__(self) -> str:
696
+ tmpstr = self.__class__.__name__ + "("
697
+ tmpstr += f"output_layouts={self.output_layouts}, "
698
+ tmpstr += f"desired_output_layouts={self.desired_output_layouts}, "
699
+ tmpstr += f"use_local_output={self.use_local_output}"
700
+ tmpstr += ")"
701
+ return tmpstr
702
+
703
+
704
+ class PrepareModuleInputOutput(ParallelStyle):
705
+ """
706
+ Configure the nn.Module's inputs (and outputs) to convert the input tensors (and output tensors, respectively) of the nn.Module
707
+ to DTensors at runtime according to ``input_layouts`` (and output_layouts, respectively), and perform layout redistribution
708
+ according to the ``desired_input_layouts`` (and ``desired_output_layouts``, respectively). This is a combination of
709
+ :class:`PrepareModuleInput` and :class:`PrepareModuleOutput`.
710
+
711
+ Keyword Args:
712
+ input_layouts (Union[Placement, Tuple[Optional[Placement]]]):
713
+ The DTensor layouts of input tensors for the nn.Module, this is used to convert the input tensors to
714
+ DTensors. If some inputs are not torch.Tensor or no need to convert to DTensors, ``None`` need to be specified
715
+ as a placeholder. default: None.
716
+ desired_input_layouts (Union[Placement, Tuple[Optional[Placement]]]):
717
+ The desired DTensor layout of input tensors for the nn.Module, this is used to ensure the inputs of the nn.Module
718
+ have the desired DTensor layouts. This argument needs to have the same length with ``input_layouts``. default: None.
719
+ input_kwarg_layouts (Dict[str, Placement]):
720
+ The DTensor layouts of input kwargs for the nn.Module, this is used to convert the input kwarg tensors to DTensors.
721
+ default: None
722
+ desired_input_kwarg_layouts: (Dict[str, Placement]):
723
+ The desired DTensor layout of input kwargs for the nn.Module, this is used to ensure the inputs of the nn.Module
724
+ have the desired DTensor layouts. default: None.
725
+ use_local_input (bool, optional):
726
+ Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module inputs, default: False.
727
+ output_layouts (Union[Placement, Tuple[Placement]]):
728
+ The DTensor layouts of output tensors for the nn.Module, this is used to convert the output tensors to
729
+ DTensors if they are :class:`torch.Tensor`. If some outputs are not torch.Tensor or no need to convert to DTensors,
730
+ ``None`` need to be specified as a placeholder.
731
+ desired_output_layouts (Union[Placement, Tuple[Placement]]):
732
+ The desired DTensor layouts of output tensors for the nn.Module, this is used to ensure the outputs of the nn.Module
733
+ have the desired DTensor layouts.
734
+ use_local_output (bool, optional):
735
+ Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module outputs, default: True.
736
+ Returns:
737
+ A :class:`ParallelStyle` object that prepares the sharding layouts of the nn.Module's inputs and outputs.
738
+
739
+ Example::
740
+ >>> # xdoctest: +SKIP(failing)
741
+ >>> from torch.distributed.tensor.parallel import parallelize_module, PrepareModuleInputOutput
742
+ >>> from torch.distributed.device_mesh import init_device_mesh
743
+ >>> ...
744
+ >>> block = TransformerBlock(...) # block is a nn.Module that contains an "attn" Attention submodule
745
+ >>> tp_mesh = init_device_mesh("cuda", (8,))
746
+ >>>
747
+ >>> # According to the style specified below, the first input of attn will be annotated as Sharded DTensor
748
+ >>> # and then redistributed to Replicated DTensor, and the output of the TransformerBlock will be annotated
749
+ >>> # as Replicated DTensor and then redistributed to Sharded DTensor.
750
+ >>> parallelize_module(
751
+ >>> block, # this can be a submodule or module
752
+ >>> tp_mesh,
753
+ >>> parallelize_plan={
754
+ >>> "attn": PrepareModuleInputOutput(
755
+ >>> input_layouts=(Shard(0), None, None, ...),
756
+ >>> desired_input_layouts=(Replicate(), None, None, ...),
757
+ >>> output_layouts=Replicate(),
758
+ >>> desired_output_layouts=Shard(0),
759
+ >>> ),
760
+ >>> }
761
+ >>> )
762
+ """
763
+
764
+ def __init__(
765
+ self,
766
+ *,
767
+ input_layouts: Placement | tuple[Placement | None, ...] | None = None,
768
+ desired_input_layouts: Placement | tuple[Placement | None, ...] | None = None,
769
+ input_kwarg_layouts: dict[str, Placement] | None = None,
770
+ desired_input_kwarg_layouts: dict[str, Placement] | None = None,
771
+ use_local_input: bool = False,
772
+ output_layouts: Placement | tuple[Placement | None, ...],
773
+ desired_output_layouts: Placement | tuple[Placement, ...],
774
+ use_local_output: bool = True,
775
+ ):
776
+ self.prepare_module_input = PrepareModuleInput(
777
+ input_layouts=input_layouts,
778
+ desired_input_layouts=desired_input_layouts,
779
+ input_kwarg_layouts=input_kwarg_layouts,
780
+ desired_input_kwarg_layouts=desired_input_kwarg_layouts,
781
+ use_local_output=use_local_input,
782
+ )
783
+ self.prepare_module_output = PrepareModuleOutput(
784
+ output_layouts=output_layouts,
785
+ desired_output_layouts=desired_output_layouts,
786
+ use_local_output=use_local_output,
787
+ )
788
+
789
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
790
+ self.prepare_module_input._apply(module, device_mesh)
791
+ self.prepare_module_output._apply(module, device_mesh)
792
+
793
+ return module
794
+
795
+ def __repr__(self) -> str:
796
+ tmpstr = self.__class__.__name__ + "("
797
+ tmpstr += f"input_layouts={self.prepare_module_input.input_layouts}, "
798
+ tmpstr += (
799
+ f"desired_input_layouts={self.prepare_module_input.desired_input_layouts}, "
800
+ )
801
+ tmpstr += (
802
+ f"input_kwarg_layouts={self.prepare_module_input.input_kwarg_layouts}, "
803
+ )
804
+ tmpstr += f"desired_input_kwarg_layouts={self.prepare_module_input.desired_input_kwarg_layouts}, "
805
+ tmpstr += f"use_local_input={self.prepare_module_input.use_local_output}, "
806
+ tmpstr += f"output_layouts={self.prepare_module_output.output_layouts}, "
807
+ tmpstr += f"desired_output_layouts={self.prepare_module_output.desired_output_layouts}, "
808
+ tmpstr += f"use_local_output={self.prepare_module_output.use_local_output}"
809
+ tmpstr += ")"
810
+ return tmpstr
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributed/tensor/placement_types.py ADDED
@@ -0,0 +1,1114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+
4
+ from dataclasses import dataclass, field
5
+ from typing import cast, Optional
6
+
7
+ import torch
8
+ import torch._C
9
+ import torch.distributed._functional_collectives as funcol
10
+ from torch._C._distributed import Placement
11
+ from torch.distributed._local_tensor import maybe_run_for_local_tensor
12
+ from torch.distributed.device_mesh import DeviceMesh
13
+ from torch.distributed.tensor._collective_utils import (
14
+ fill_empty_tensor_to_shards,
15
+ mesh_broadcast,
16
+ mesh_scatter,
17
+ pad_tensor,
18
+ shard_dim_alltoall,
19
+ unpad_tensor,
20
+ )
21
+ from torch.distributed.tensor._ops._mask_buffer import MaskBuffer
22
+
23
+
24
+ __all__ = ["Placement", "Shard", "Replicate", "Partial", "MaskPartial"]
25
+
26
+
27
+ # Appease TestPublicBindings.test_correct_module_names
28
+ Placement.__module__ = "torch.distributed.tensor.placement_types"
29
+
30
+
31
+ class Shard(torch._C._distributed.Shard):
32
+ """
33
+ The ``Shard(dim)`` placement describes the DTensor sharding on tensor dimension
34
+ ``dim`` over a corresponding ``DeviceMesh`` dimension, where each rank on the
35
+ DeviceMesh dimension only holds a shard/piece of the global Tensor. The
36
+ ``Shard(dim)`` placement follows the ``torch.chunk(dim)`` semantic, where the
37
+ last few shards on the DeviceMesh dimension might be empty when the tensor dimension
38
+ is not evenly divisible on the DeviceMesh dimension. The ``Shard`` placement can be
39
+ used by all DTensor APIs (i.e. distribute_tensor, from_local, etc.)
40
+
41
+ Args:
42
+ dim (int): The tensor dimension that describes the DTensor is sharded over its
43
+ corresponding DeviceMesh dimension.
44
+
45
+ .. warning:: sharding on a tensor dimension where the tensor dimension size is not
46
+ evenly divisible on a DeviceMesh dimension is currently experimental and subject to change.
47
+ """
48
+
49
+ def _split_tensor(
50
+ self,
51
+ tensor: torch.Tensor,
52
+ num_chunks: int,
53
+ *,
54
+ with_padding: bool = True,
55
+ contiguous: bool = True,
56
+ ) -> tuple[list[torch.Tensor], list[int]]:
57
+ """
58
+ This function uses torch.chunk to split a tensor into num_chunks shards along
59
+ the Shard placement dimension, and return a list of shards with their pad sizes.
60
+
61
+ Keyword args:
62
+ with_padding (bool, optional): when True, we pad the tensor on the last
63
+ few ranks before calling the collectives (i.e. scatter/all_gather, etc.).
64
+ This is because collectives usually require equal size tensor inputs
65
+ """
66
+ assert self.dim <= tensor.ndim, (
67
+ f"Sharding dim {self.dim} greater than tensor ndim {tensor.ndim}"
68
+ )
69
+
70
+ # chunk tensor over dimension `dim` into n slices
71
+ tensor_list = list(torch.chunk(tensor, num_chunks, dim=self.dim))
72
+ tensor_list = fill_empty_tensor_to_shards(
73
+ tensor_list, self.dim, num_chunks - len(tensor_list)
74
+ )
75
+
76
+ # compute the chunk size inline with ``torch.chunk`` to calculate padding
77
+ full_chunk_size = (tensor.size(self.dim) + num_chunks - 1) // num_chunks
78
+
79
+ shard_list: list[torch.Tensor] = []
80
+ pad_sizes: list[int] = []
81
+ for shard in tensor_list:
82
+ if with_padding:
83
+ pad_size = Shard._get_shard_pad_size(full_chunk_size, shard, self.dim)
84
+ shard = pad_tensor(shard, self.dim, pad_size)
85
+ pad_sizes.append(pad_size)
86
+ if contiguous:
87
+ shard = shard.contiguous()
88
+ shard_list.append(shard)
89
+ return shard_list, pad_sizes
90
+
91
+ @staticmethod
92
+ @maybe_run_for_local_tensor
93
+ def local_shard_size_and_offset(
94
+ curr_local_size: int,
95
+ num_chunks: int,
96
+ rank: int,
97
+ ) -> tuple[int, int]:
98
+ """
99
+ Given the size of the current local tensor (which may already be sharded on some dimensions),
100
+ computes the new local shard size and offset given the desired number of chunks
101
+ (num_chunks is generally equal to the size of the current sharding dim).
102
+
103
+ Note: new local shard offset is relative to the current sharded tensor, not the global tensor.
104
+ See `_utils.compute_local_shape_and_global_offset` for computing global offset.
105
+
106
+ Returns (new local shard size, offset)
107
+
108
+ """
109
+ # Compute the chunk size inline with ``torch.chunk``
110
+ if curr_local_size % num_chunks == 0:
111
+ full_chunk_size = curr_local_size // num_chunks
112
+ return full_chunk_size, full_chunk_size * rank
113
+
114
+ # uneven sharding case
115
+ full_chunk_size = (curr_local_size + num_chunks - 1) // num_chunks
116
+ shard_starting_idx = full_chunk_size * rank
117
+
118
+ if curr_local_size < shard_starting_idx:
119
+ return 0, curr_local_size
120
+ else:
121
+ local_shard_size = (
122
+ min(curr_local_size, shard_starting_idx + full_chunk_size)
123
+ - shard_starting_idx
124
+ )
125
+ return local_shard_size, shard_starting_idx
126
+
127
+ def _local_shard_size_and_offset(
128
+ self,
129
+ curr_local_size: int,
130
+ num_chunks: int,
131
+ rank: int,
132
+ ) -> tuple[int, int | None]:
133
+ return Shard.local_shard_size_and_offset(curr_local_size, num_chunks, rank)
134
+
135
+ @staticmethod
136
+ @maybe_run_for_local_tensor
137
+ def _maybe_unpad_tensor_with_sizes(
138
+ dim, local_tensor, pad_sizes, mesh_dim_local_rank, make_contiguous
139
+ ) -> torch.Tensor:
140
+ # Only unpad if the local_tensor was padded on the dimension.
141
+ if pad_sizes[mesh_dim_local_rank] > 0:
142
+ local_tensor = unpad_tensor(
143
+ local_tensor, dim, pad_sizes[mesh_dim_local_rank]
144
+ )
145
+ if make_contiguous:
146
+ local_tensor = local_tensor.contiguous()
147
+ return local_tensor
148
+
149
+ def _shard_tensor(
150
+ self,
151
+ tensor: torch.Tensor,
152
+ mesh: DeviceMesh,
153
+ mesh_dim: int,
154
+ src_data_rank: int | None = 0,
155
+ ) -> torch.Tensor:
156
+ """
157
+ Shard and scatter a tensor on a mesh dimension (use coordinate 0 on the
158
+ mesh dimension as source of truth).
159
+
160
+ Create the local tensor for this rank following the given Shard
161
+ placement. If src_data_rank is None, perform only local splitting.
162
+ Otherwise, additionally scatter data from src_data_rank. Unlike
163
+ ``_split_tensor``, which supports uneven sharding via padding, this
164
+ method requires the tensor dimension to be evenly divisible by the
165
+ number of chunks (mesh dimension size).
166
+ """
167
+ my_coordinate = mesh.get_coordinate()
168
+ num_chunks = mesh.size(mesh_dim=mesh_dim)
169
+
170
+ if my_coordinate is None:
171
+ # if rank is not part of mesh, we simply return an empty tensor
172
+ return tensor.new_empty(0, requires_grad=tensor.requires_grad)
173
+
174
+ mesh_dim_local_rank = my_coordinate[mesh_dim]
175
+
176
+ if src_data_rank is None:
177
+ # src_data_rank specified as None explicitly means to skip the
178
+ # communications, simply split
179
+ scatter_list, _ = self._split_tensor(
180
+ tensor, num_chunks, with_padding=False, contiguous=True
181
+ )
182
+
183
+ return self._select_shard(scatter_list, mesh_dim_local_rank)
184
+
185
+ scatter_list, pad_sizes = self._split_tensor(
186
+ tensor, num_chunks, with_padding=True, contiguous=True
187
+ )
188
+
189
+ it = iter(scatter_list)
190
+ first = next(it)
191
+ # Tensors in the scatter list are expected to have the same shape because
192
+ # split is requested with padding.
193
+ assert all(first.shape == v.shape for v in it)
194
+
195
+ output = torch.empty_like(first)
196
+
197
+ # perform scatter from the src_data_rank as data source when it is not None
198
+ mesh_scatter(
199
+ output, scatter_list, mesh, mesh_dim=mesh_dim, group_src=src_data_rank
200
+ )
201
+
202
+ return Shard._maybe_unpad_tensor_with_sizes(
203
+ self.dim, output, pad_sizes, mesh_dim_local_rank, True
204
+ )
205
+
206
+ @classmethod
207
+ def _make_shard_tensor(
208
+ cls,
209
+ dim: int,
210
+ tensor: torch.Tensor,
211
+ mesh: DeviceMesh,
212
+ mesh_dim: int,
213
+ src_data_rank: int | None = 0,
214
+ ) -> torch.Tensor:
215
+ shard_placement = cls(dim)
216
+ return shard_placement._shard_tensor(tensor, mesh, mesh_dim, src_data_rank)
217
+
218
+ def _reduce_shard_tensor(
219
+ self,
220
+ tensor: torch.Tensor,
221
+ mesh: DeviceMesh,
222
+ reduce_op: str,
223
+ mesh_dim: int,
224
+ ) -> torch.Tensor:
225
+ """
226
+ reduce and scatter a tensor on a mesh dimension
227
+ """
228
+ my_coordinate = mesh.get_coordinate()
229
+ num_chunks = mesh.size(mesh_dim=mesh_dim)
230
+
231
+ if my_coordinate is None:
232
+ # if rank is not part of mesh, we simply return local_tensor,
233
+ # which should be an empty tensor
234
+ return tensor
235
+
236
+ is_padded = tensor.size(self.dim) % num_chunks != 0
237
+ pad_sizes = None
238
+ if is_padded:
239
+ scattered_list, pad_sizes = self._split_tensor(
240
+ tensor, num_chunks, with_padding=True, contiguous=True
241
+ )
242
+ tensor = torch.cat(scattered_list, dim=self.dim)
243
+ elif not tensor.is_contiguous():
244
+ tensor = tensor.contiguous()
245
+
246
+ output = funcol.reduce_scatter_tensor(
247
+ tensor, reduce_op, scatter_dim=self.dim, group=(mesh, mesh_dim)
248
+ )
249
+
250
+ if is_padded:
251
+ assert pad_sizes is not None
252
+ output = Shard._maybe_unpad_tensor_with_sizes(
253
+ self.dim, output, pad_sizes, my_coordinate[mesh_dim], False
254
+ )
255
+ return output
256
+
257
+ @maybe_run_for_local_tensor
258
+ def _maybe_pad_tensor(
259
+ self,
260
+ local_tensor: torch.Tensor,
261
+ logical_dim_size: int,
262
+ num_chunks: int,
263
+ ) -> torch.Tensor:
264
+ is_padded = logical_dim_size % num_chunks != 0
265
+
266
+ if is_padded:
267
+ full_chunk_size = (logical_dim_size + num_chunks - 1) // num_chunks
268
+ pad_size = full_chunk_size - local_tensor.size(self.dim)
269
+ local_tensor = pad_tensor(local_tensor, self.dim, pad_size)
270
+
271
+ if not local_tensor.is_contiguous():
272
+ local_tensor = local_tensor.contiguous()
273
+
274
+ return local_tensor
275
+
276
+ @maybe_run_for_local_tensor
277
+ def _maybe_unpad_tensor(
278
+ self,
279
+ local_tensor: torch.Tensor,
280
+ logical_dim_size: int,
281
+ num_chunks: int,
282
+ ) -> torch.Tensor:
283
+ is_padded = logical_dim_size % num_chunks != 0
284
+
285
+ if is_padded:
286
+ full_chunk_size = (logical_dim_size + num_chunks - 1) // num_chunks
287
+ unpad_size = full_chunk_size * num_chunks - logical_dim_size # type: ignore[possibly-undefined]
288
+ local_tensor = unpad_tensor(local_tensor, self.dim, unpad_size)
289
+
290
+ return local_tensor
291
+
292
+ def _to_replicate_tensor(
293
+ self,
294
+ local_tensor: torch.Tensor,
295
+ mesh: DeviceMesh,
296
+ mesh_dim: int,
297
+ current_logical_shape: list[int],
298
+ ) -> torch.Tensor:
299
+ """
300
+ This function all_gather all shards and return a tensor that
301
+ is replicated on the previously sharded mesh dimension
302
+ """
303
+ num_chunks = mesh.size(mesh_dim=mesh_dim)
304
+ logical_dim_size = current_logical_shape[self.dim]
305
+
306
+ local_tensor = self._maybe_pad_tensor(
307
+ local_tensor, logical_dim_size, num_chunks
308
+ )
309
+
310
+ result = funcol.all_gather_tensor(
311
+ local_tensor,
312
+ gather_dim=self.dim,
313
+ group=(mesh, mesh_dim),
314
+ )
315
+
316
+ result = self._maybe_unpad_tensor(result, logical_dim_size, num_chunks)
317
+
318
+ return result
319
+
320
+ @staticmethod
321
+ @maybe_run_for_local_tensor
322
+ def _select_shard(shards: list[torch.Tensor], shard_index) -> torch.Tensor:
323
+ return shards[shard_index].clone()
324
+
325
+ def _replicate_to_shard(
326
+ self,
327
+ local_tensor: torch.Tensor,
328
+ mesh: DeviceMesh,
329
+ mesh_dim: int,
330
+ shard_index: int,
331
+ ) -> torch.Tensor:
332
+ """
333
+ transform from replicated tensor to a sharded tensor on
334
+ the current rank, which would perform a local chunk
335
+ """
336
+ num_chunks = mesh.size(mesh_dim=mesh_dim)
337
+ shards, _ = self._split_tensor(
338
+ local_tensor,
339
+ num_chunks,
340
+ with_padding=False,
341
+ contiguous=False,
342
+ )
343
+
344
+ return Shard._select_shard(shards, shard_index)
345
+
346
+ @staticmethod
347
+ @maybe_run_for_local_tensor
348
+ def _get_shard_pad_size(
349
+ full_size: int, local_tensor: torch.Tensor, dim: int
350
+ ) -> int:
351
+ """
352
+ Get the padding size of the local tensor on the shard dimension.
353
+ """
354
+ return full_size - local_tensor.size(dim)
355
+
356
+ @staticmethod
357
+ def _compute_padding_info(
358
+ current_logical_shape: list[int],
359
+ num_chunks: int,
360
+ old_shard_dim: int,
361
+ new_shard_dim: int,
362
+ ) -> tuple[bool, int, int, bool, int, int]:
363
+ results = []
364
+ for shard_dim in [old_shard_dim, new_shard_dim]:
365
+ dim_logical_size = current_logical_shape[shard_dim]
366
+ dim_padding = dim_logical_size % num_chunks != 0
367
+ dim_full_chunk_size = (dim_logical_size + num_chunks - 1) // num_chunks
368
+ results.append((dim_padding, dim_logical_size, dim_full_chunk_size))
369
+
370
+ return results[0] + results[1]
371
+
372
+ @staticmethod
373
+ @maybe_run_for_local_tensor
374
+ def _pad_for_new_shard_dim(
375
+ current_logical_shape: list[int],
376
+ local_tensor: torch.Tensor,
377
+ num_chunks: int,
378
+ old_shard_dim: int,
379
+ new_shard_dim: int,
380
+ ) -> torch.Tensor:
381
+ (
382
+ old_dim_padding,
383
+ _,
384
+ old_dim_full_chunk_size,
385
+ new_dim_padding,
386
+ _,
387
+ new_dim_full_chunk_size,
388
+ ) = Shard._compute_padding_info(
389
+ current_logical_shape, num_chunks, old_shard_dim, new_shard_dim
390
+ )
391
+
392
+ if old_dim_padding:
393
+ old_dim_pad_size = Shard._get_shard_pad_size(
394
+ old_dim_full_chunk_size, local_tensor, old_shard_dim
395
+ )
396
+ local_tensor = pad_tensor(local_tensor, old_shard_dim, old_dim_pad_size)
397
+ if new_dim_padding:
398
+ new_dim_pad_size = Shard._get_shard_pad_size(
399
+ new_dim_full_chunk_size * num_chunks, local_tensor, new_shard_dim
400
+ )
401
+ local_tensor = pad_tensor(local_tensor, new_shard_dim, new_dim_pad_size)
402
+
403
+ if not local_tensor.is_contiguous():
404
+ local_tensor = local_tensor.contiguous()
405
+ return local_tensor
406
+
407
+ @staticmethod
408
+ @maybe_run_for_local_tensor
409
+ def _unpad_for_new_shard_dim(
410
+ current_logical_shape: list[int],
411
+ local_tensor: torch.Tensor,
412
+ num_chunks: int,
413
+ old_shard_dim: int,
414
+ new_shard_dim: int,
415
+ local_rank: int,
416
+ ) -> torch.Tensor:
417
+ (
418
+ old_dim_padding,
419
+ _,
420
+ old_dim_full_chunk_size,
421
+ new_dim_padding,
422
+ new_dim_logical_size,
423
+ new_dim_full_chunk_size,
424
+ ) = Shard._compute_padding_info(
425
+ current_logical_shape, num_chunks, old_shard_dim, new_shard_dim
426
+ )
427
+
428
+ if old_dim_padding:
429
+ old_dim_unpad_size = (
430
+ old_dim_full_chunk_size * num_chunks
431
+ - current_logical_shape[old_shard_dim] # type: ignore[possibly-undefined]
432
+ )
433
+ local_tensor = unpad_tensor(local_tensor, old_shard_dim, old_dim_unpad_size) # type: ignore[possibly-undefined]
434
+
435
+ if new_dim_padding:
436
+ local_shard_size_on_new_dim = Shard.local_shard_size_and_offset(
437
+ new_dim_logical_size, num_chunks, local_rank
438
+ )[0]
439
+ new_dim_unpad_size = new_dim_full_chunk_size - local_shard_size_on_new_dim # type: ignore[possibly-undefined]
440
+ local_tensor = unpad_tensor(local_tensor, new_shard_dim, new_dim_unpad_size) # type: ignore[possibly-undefined]
441
+
442
+ return local_tensor
443
+
444
+ def _to_new_shard_dim(
445
+ self,
446
+ local_tensor: torch.Tensor,
447
+ mesh: DeviceMesh,
448
+ mesh_dim: int,
449
+ current_logical_shape: list[int],
450
+ new_shard_dim: int,
451
+ ) -> torch.Tensor:
452
+ """
453
+ transform from existing sharded tensor to a new sharded tensor on
454
+ that shard on a new dimension, which performs an alltoall
455
+ """
456
+ my_coordinate = mesh.get_coordinate()
457
+ if my_coordinate is None:
458
+ # if rank is not part of mesh, we simply return local_tensor,
459
+ # which should be an empty tensor
460
+ return local_tensor
461
+
462
+ num_chunks = mesh.size(mesh_dim=mesh_dim)
463
+
464
+ local_tensor = Shard._pad_for_new_shard_dim(
465
+ current_logical_shape, local_tensor, num_chunks, self.dim, new_shard_dim
466
+ )
467
+
468
+ new_tensor = shard_dim_alltoall(
469
+ local_tensor, self.dim, new_shard_dim, mesh, mesh_dim
470
+ )
471
+
472
+ new_tensor = Shard._unpad_for_new_shard_dim(
473
+ current_logical_shape,
474
+ new_tensor,
475
+ num_chunks,
476
+ self.dim,
477
+ new_shard_dim,
478
+ my_coordinate[mesh_dim],
479
+ )
480
+
481
+ return new_tensor
482
+
483
+ def __hash__(self) -> int:
484
+ return hash(self.dim)
485
+
486
+ def __repr__(self) -> str:
487
+ """
488
+ machine readable representation of the Shard placement
489
+ """
490
+ return f"Shard(dim={self.dim})"
491
+
492
+ def __str__(self) -> str:
493
+ """human readable representation of the Shard placement"""
494
+ return f"S({self.dim})"
495
+
496
+
497
+ class _StridedShard(torch._C._distributed.StridedShard):
498
+ """
499
+ _StridedShard is only introduced to support 2D FSDP2 + TP sharding where the tensor
500
+ is sharded on the TP mesh dimension first, then sharded on the FSDP mesh dimension.
501
+ We call this right-to-left sharding which is the opposite of the default
502
+ left-to-right sharding. See the example below:
503
+ tensor shape: [8, 8]
504
+ mesh: [[0, 1], [2, 3]], names=("dp", "tp")
505
+ placements: [Shard(0), Shard(0)]
506
+
507
+ The default sharding behavior shards the tensor on "dp" mesh dimension first then
508
+ "tp" dimension. The sharding result will be:
509
+ Rank | Mesh Coordinate | Shard Index
510
+ ------------------------------------------------
511
+ 0 | (0, 0) | 0 (row 0-1)
512
+ 1 | (0, 1) | 1 (row 2-3)
513
+ 2 | (1, 0) | 2 (row 4-5)
514
+ 3 | (1, 1) | 3 (row 6-7)
515
+
516
+ While the FSDP2 + TP sharding behavior does the opposite: it shards the tensor on
517
+ "tp" mesh dim first then "dp" dim. This right-to-left sharding will produce the
518
+ result:
519
+ Rank | Mesh Coordinate | Shard Index
520
+ ------------------------------------------------
521
+ 0 | (0, 0) | 0 (row 0-1)
522
+ 1 | (0, 1) | 2 (row 4-5)
523
+ 2 | (1, 0) | 1 (row 2-3)
524
+ 3 | (1, 1) | 3 (row 6-7)
525
+
526
+ The consequence is, any attempt to redistribute this DTensor to a full replica will
527
+ produce a wrong result because the shard-to-replicate redistribution always happens
528
+ right-to-left, regardless it's left-to-right sharding or right-to-left. To address
529
+ this, we use _StridedShard placement to make this right-to-left sharding compatible
530
+ with our left-to-right convention on both tensor distribution and redistribution.
531
+
532
+ Now with _StridedShard, the right-to-left sharding above can be represented as:
533
+ tensor shape: [8, 8]
534
+ mesh: [[0, 1], [2, 3]], names=("dp", "tp")
535
+ placements: [_StridedShard(0, split_factor=2), Shard(0)]
536
+
537
+ And a left-to-right processing of `placements` will produce the same result, which is
538
+ different from using the `Shard` placement:
539
+ Rank | Mesh Coordinate | Shard Index
540
+ ------------------------------------------------
541
+ 0 | (0, 0) | 0 (row 0-1)
542
+ 1 | (0, 1) | 2 (row 4-5)
543
+ 2 | (1, 0) | 1 (row 2-3)
544
+ 3 | (1, 1) | 3 (row 6-7)
545
+
546
+ The argument `split_factor` is the number of existing shards over the tensor sharding
547
+ dimension before processing the _StridedShard placement, as if the sharding happened
548
+ right-to-left. In the example above, the tensor should first be sharded on the "tp"
549
+ dimension into 2 shards before being sharded on the "dp" dimension. Therefore, the
550
+ `split_factor` of the _StridedShard placement on "dp" dim is 2.
551
+
552
+ TODO: we should remove _StridedShard placement once we can unify it with Shard
553
+ """
554
+
555
+ def __hash__(self) -> int:
556
+ return hash((self.dim, self.split_factor))
557
+
558
+ def __repr__(self) -> str:
559
+ """
560
+ machine readable representation of the _StridedShard placement
561
+ """
562
+ return f"_StridedShard(dim={self.dim}, sf={self.split_factor})"
563
+
564
+ def __str__(self) -> str:
565
+ """human readable representation of the _StridedShard placement"""
566
+ return f"_S({self.dim}, {self.split_factor})"
567
+
568
+ @staticmethod
569
+ @maybe_run_for_local_tensor
570
+ def _select_shard(shards: list[torch.Tensor], shard_index) -> torch.Tensor:
571
+ return shards[shard_index].clone()
572
+
573
+ @classmethod
574
+ def _make_shard_tensor(
575
+ cls,
576
+ dim: int,
577
+ tensor: torch.Tensor,
578
+ mesh: DeviceMesh,
579
+ mesh_dim: int,
580
+ src_data_rank: int | None = 0,
581
+ split_factor: int = 1,
582
+ ) -> torch.Tensor:
583
+ strided_shard_placement = cls(dim=dim, split_factor=split_factor)
584
+ return strided_shard_placement._shard_tensor(
585
+ tensor, mesh, mesh_dim, src_data_rank
586
+ )
587
+
588
+ def _shard_tensor(
589
+ self,
590
+ tensor: torch.Tensor,
591
+ mesh: DeviceMesh,
592
+ mesh_dim: int,
593
+ src_data_rank: Optional[int] = 0,
594
+ ) -> torch.Tensor:
595
+ """
596
+ Shard and scatter a tensor on a mesh dimension (use coordinate 0 on the
597
+ mesh dimension as source of truth).
598
+
599
+ Create the local tensor for this rank following the given StridedShard
600
+ placement. If src_data_rank is None, perform only local splitting.
601
+ Otherwise, additionally scatter data from src_data_rank. Unlike
602
+ ``_split_tensor``, which supports uneven sharding via padding, this
603
+ method requires the tensor dimension to be evenly divisible by the
604
+ number of chunks (mesh dimension size).
605
+ """
606
+ my_coordinate = mesh.get_coordinate()
607
+ num_chunks = mesh.size(mesh_dim=mesh_dim)
608
+
609
+ if my_coordinate is None:
610
+ # if rank is not part of mesh, we simply return an empty tensor
611
+ return tensor.new_empty(0, requires_grad=tensor.requires_grad)
612
+
613
+ mesh_dim_local_rank = my_coordinate[mesh_dim]
614
+
615
+ if src_data_rank is None:
616
+ # src_data_rank specified as None explicitly means to skip the
617
+ # communications, simply split
618
+ scatter_list, _ = self._split_tensor(
619
+ tensor, num_chunks, with_padding=False, contiguous=True
620
+ )
621
+
622
+ return self._select_shard(scatter_list, mesh_dim_local_rank)
623
+
624
+ scatter_list, pad_sizes = self._split_tensor(
625
+ tensor, num_chunks, with_padding=True, contiguous=True
626
+ )
627
+
628
+ it = iter(scatter_list)
629
+ first = next(it)
630
+ # Tensors in the scatter list are expected to have the same shape because
631
+ # split is requested with padding.
632
+ assert all(first.shape == v.shape for v in it)
633
+
634
+ output = torch.empty_like(first)
635
+
636
+ # perform scatter from the src_data_rank as data source when it is not None
637
+ mesh_scatter(
638
+ output, scatter_list, mesh, mesh_dim=mesh_dim, group_src=src_data_rank
639
+ )
640
+
641
+ return Shard._maybe_unpad_tensor_with_sizes(
642
+ self.dim, output, pad_sizes, mesh_dim_local_rank, True
643
+ )
644
+
645
+ def _split_tensor(
646
+ self,
647
+ tensor: torch.Tensor,
648
+ num_chunks: int,
649
+ *,
650
+ with_padding: bool = True,
651
+ contiguous: bool = True,
652
+ ) -> tuple[list[torch.Tensor], list[int]]:
653
+ assert self.dim <= tensor.ndim, (
654
+ f"Sharding dim {self.dim} greater than tensor ndim {tensor.ndim}"
655
+ )
656
+
657
+ # Essentially _StridedShard express the right-to-left sharding in the
658
+ # reversed order. Here we perform first_split as the virtual "right" sharding,
659
+ # and then second_split as the virtual "left" sharding, and finally assemble
660
+ # results in the transposed left-first order.
661
+
662
+ # First split: chunk into split_factor pieces
663
+ first_split = list(torch.chunk(tensor, self.split_factor, dim=self.dim))
664
+ first_split = fill_empty_tensor_to_shards(
665
+ first_split, self.dim, self.split_factor - len(first_split)
666
+ )
667
+
668
+ # Second split: chunk each piece into num_chunks pieces
669
+ second_split = []
670
+ for s in first_split:
671
+ chunks = list(torch.chunk(s, num_chunks, dim=self.dim))
672
+ chunks = fill_empty_tensor_to_shards(
673
+ chunks, self.dim, num_chunks - len(chunks)
674
+ )
675
+ second_split.append(chunks)
676
+
677
+ shard_list: list[torch.Tensor] = []
678
+ for i in range(num_chunks):
679
+ shard = torch.cat(
680
+ [second_split[j][i] for j in range(self.split_factor)],
681
+ dim=self.dim,
682
+ )
683
+ if contiguous:
684
+ shard = shard.contiguous()
685
+ shard_list.append(shard)
686
+
687
+ # The amount of padding is determined by the local chunk with the largest size.
688
+ pad_sizes: list[int] = []
689
+ max_chunk_size = max([shard.size(self.dim) for shard in shard_list])
690
+ if with_padding:
691
+ pad_sizes = [max_chunk_size - shard.size(self.dim) for shard in shard_list]
692
+
693
+ return shard_list, pad_sizes
694
+
695
+ def _to_replicate_tensor(
696
+ self,
697
+ local_tensor: torch.Tensor,
698
+ mesh: DeviceMesh,
699
+ mesh_dim: int,
700
+ current_logical_shape: list[int],
701
+ ) -> torch.Tensor:
702
+ """
703
+ replay the replicate-to-shard process to understand how to stitch shards back
704
+ """
705
+ num_chunks = mesh.size(mesh_dim=mesh_dim)
706
+ logical_dim_size = current_logical_shape[self.dim]
707
+
708
+ # indices_tensor is 1D torch.arange(logical_dim_size) unsqueezed
709
+ # so that we can reuse self._split_tensor which splits on self.dim
710
+ shape = [1] * self.dim + [logical_dim_size]
711
+ indices_tensor = torch.arange(
712
+ logical_dim_size, device=local_tensor.device
713
+ ).view(shape)
714
+
715
+ sharded_indices, _ = self._split_tensor(
716
+ indices_tensor,
717
+ num_chunks,
718
+ with_padding=False,
719
+ contiguous=False,
720
+ )
721
+ # squeeze back to 1D indices tensor
722
+ sharded_indices = [shard.view(-1) for shard in sharded_indices]
723
+
724
+ max_chunk_size = max([len(shard) for shard in sharded_indices])
725
+ local_pad_size = max_chunk_size - local_tensor.size(self.dim)
726
+ local_tensor_padded = pad_tensor(local_tensor, self.dim, local_pad_size)
727
+
728
+ if not local_tensor_padded.is_contiguous():
729
+ local_tensor_padded = local_tensor_padded.contiguous()
730
+
731
+ replicate_tensor_permuted_padded = funcol.all_gather_tensor(
732
+ local_tensor_padded,
733
+ gather_dim=self.dim,
734
+ group=(mesh, mesh_dim),
735
+ )
736
+ if isinstance(replicate_tensor_permuted_padded, funcol.AsyncCollectiveTensor):
737
+ replicate_tensor_permuted_padded = replicate_tensor_permuted_padded.wait()
738
+
739
+ if replicate_tensor_permuted_padded.shape[self.dim] > logical_dim_size:
740
+ replicate_tensor_permuted = unpad_tensor(
741
+ replicate_tensor_permuted_padded,
742
+ self.dim,
743
+ replicate_tensor_permuted_padded.shape[self.dim] - logical_dim_size,
744
+ )
745
+ else:
746
+ replicate_tensor_permuted = replicate_tensor_permuted_padded
747
+
748
+ permutation = torch.cat(sharded_indices)
749
+ inv_permutation = torch.argsort(permutation)
750
+ replicate_tensor = torch.index_select(
751
+ replicate_tensor_permuted, self.dim, inv_permutation
752
+ )
753
+
754
+ return replicate_tensor.contiguous()
755
+
756
+ @staticmethod
757
+ @maybe_run_for_local_tensor
758
+ def _local_shard_size(sharded_indices: list[torch.Tensor], rank: int) -> int:
759
+ return len(sharded_indices[rank])
760
+
761
+ # delete pyre-ignore once separating _StridedShard from Shard
762
+ def _local_shard_size_and_offset( # pyre-ignore[bad-override]
763
+ self,
764
+ curr_local_size: int,
765
+ num_chunks: int,
766
+ rank: int,
767
+ return_first_offset: bool = True,
768
+ ) -> tuple[int, int | list[int]]:
769
+ return _StridedShard.local_shard_size_and_offset(
770
+ self, curr_local_size, num_chunks, rank, return_first_offset
771
+ )
772
+
773
+ @staticmethod
774
+ @maybe_run_for_local_tensor
775
+ def local_shard_size_and_offset( # pyre-ignore[bad-override]
776
+ self,
777
+ curr_local_size: int,
778
+ num_chunks: int,
779
+ rank: int,
780
+ return_first_offset: bool = True,
781
+ ) -> tuple[int, list[int] | int]:
782
+ """
783
+ Compute the local shard size and offset(s) for a _StridedShard placement.
784
+
785
+ Unlike the regular Shard placement which produces contiguous offsets, _StridedShard
786
+ produces non-contiguous (strided) offsets due to the right-to-left sharding semantics.
787
+ This method computes the actual indices that belong to the local shard.
788
+
789
+ Args:
790
+ self (_StridedShard): The _StridedShard placement instance.
791
+ curr_local_size (int): The current size of the tensor dimension to be sharded.
792
+ num_chunks (int): Number of chunks to split the dimension into (typically the mesh dimension size).
793
+ rank (int): The rank index to compute the shard for.
794
+ return_first_offset (bool): If True, return only the first offset as an int. If False,
795
+ return all offsets as a list. Defaults to True.
796
+
797
+ Returns:
798
+ tuple: A tuple containing:
799
+ - local_shard_size (int): The number of elements in the local shard for this rank.
800
+ - offset (int | list[int]): If return_first_offset is True, returns the first offset
801
+ as an int. If False or if the shard size is 0, returns a list of all offsets
802
+ (which may be empty for empty shards).
803
+ """
804
+ # indices_tensor is 1D torch.arange(logical_dim_size) unsqueezed
805
+ # so that we can reuse self._split_tensor which splits on self.dim
806
+ shape = [1] * self.dim + [curr_local_size]
807
+ indices_tensor = torch.arange(
808
+ curr_local_size,
809
+ ).view(shape)
810
+
811
+ sharded_indices, _ = self._split_tensor(
812
+ indices_tensor,
813
+ num_chunks,
814
+ with_padding=False,
815
+ contiguous=False,
816
+ )
817
+ # squeeze back to 1D indices tensor
818
+ sharded_indices = [shard.view(-1) for shard in sharded_indices]
819
+
820
+ local_shard_size = _StridedShard._local_shard_size(sharded_indices, rank)
821
+ if local_shard_size > 0:
822
+ offsets = sharded_indices[rank].tolist()
823
+ else:
824
+ offsets = []
825
+
826
+ if return_first_offset:
827
+ # Always return an int for consistency across ranks.
828
+ # For empty shards, return -1 as an invalid offset indicator.
829
+ offsets = offsets[0] if len(offsets) > 0 else -1
830
+
831
+ return local_shard_size, offsets
832
+
833
+
834
+ class Replicate(torch._C._distributed.Replicate):
835
+ """
836
+ The ``Replicate()`` placement describes the DTensor replicating on a corresponding
837
+ ``DeviceMesh`` dimension, where each rank on the DeviceMesh dimension holds a
838
+ replica of the global Tensor. The ``Replicate`` placement can be used by all
839
+ DTensor APIs (i.e. ``distribute_tensor``, ``DTensor.from_local``, etc.)
840
+ """
841
+
842
+ def __hash__(self) -> int:
843
+ # every replicate placement is the same
844
+ return -1
845
+
846
+ def __repr__(self) -> str:
847
+ """
848
+ machine readable representation of the Replicate placement
849
+ """
850
+ return "Replicate()"
851
+
852
+ def __str__(self) -> str:
853
+ """
854
+ human readable representation of the Replicate placement
855
+ """
856
+ return "R"
857
+
858
+ @classmethod
859
+ def _make_replicate_tensor(
860
+ cls,
861
+ tensor: torch.Tensor,
862
+ mesh: DeviceMesh,
863
+ mesh_dim: int,
864
+ src_data_rank: int | None = 0,
865
+ ) -> torch.Tensor:
866
+ """
867
+ Replicate (broadcast) a torch.Tensor on a mesh dimension (use
868
+ the first coordinate on the mesh dimension as source of truth)
869
+ """
870
+ my_coordinate = mesh.get_coordinate()
871
+ if my_coordinate is None:
872
+ # if rank is not part of mesh, we simply return an empty tensor
873
+ return tensor.new_empty(0, requires_grad=tensor.requires_grad)
874
+
875
+ tensor = tensor.contiguous()
876
+
877
+ if src_data_rank is not None:
878
+ # perform broadcast from the src_data_rank as data source when it is not None
879
+ mesh_broadcast(tensor, mesh, mesh_dim=mesh_dim, group_src=src_data_rank)
880
+ return tensor
881
+
882
+ def _replicate_tensor(
883
+ self,
884
+ tensor: torch.Tensor,
885
+ mesh: DeviceMesh,
886
+ mesh_dim: int,
887
+ src_data_rank: int | None = 0,
888
+ ) -> torch.Tensor:
889
+ return Replicate._make_replicate_tensor(tensor, mesh, mesh_dim, src_data_rank)
890
+
891
+
892
+ class Partial(torch._C._distributed.Partial):
893
+ """
894
+ The ``Partial(reduce_op)`` placement describes the DTensor that is pending
895
+ reduction on a specified ``DeviceMesh`` dimension, where each rank on the
896
+ DeviceMesh dimension holds the partial value of the global Tensor. User can
897
+ redistribute the ``Partial`` DTensor to a ``Replicate`` or ``Shard(dim)``
898
+ placement on the specified ``DeviceMesh`` dimension using ``redistribute``,
899
+ which would trigger necessary communication operations under the hood (i.e.
900
+ ``allreduce``, ``reduce_scatter``).
901
+
902
+ Args:
903
+ reduce_op (str, optional): The reduction op to be used for the partial DTensor
904
+ to produce Replicated/Sharded DTensor. Only element-wise reduction operations
905
+ are supported, including: "sum", "avg", "product", "max", "min", default: "sum".
906
+
907
+ .. note:: The ``Partial`` placement can be generated as a result of the DTensor operators,
908
+ and can only be used by the ``DTensor.from_local`` API.
909
+ """
910
+
911
+ def _reduce_value(
912
+ self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
913
+ ) -> torch.Tensor:
914
+ # Partial placement contract #1:
915
+ # _reduce_value: reduce the value of the tensor on the mesh dimension
916
+ return funcol.all_reduce(
917
+ tensor, reduceOp=self.reduce_op, group=(mesh, mesh_dim)
918
+ )
919
+
920
+ def _reduce_shard_value(
921
+ self,
922
+ tensor: torch.Tensor,
923
+ mesh: DeviceMesh,
924
+ mesh_dim: int,
925
+ shard_spec: Placement,
926
+ ) -> torch.Tensor:
927
+ # Partial placement contract #2:
928
+ # _reduce_shard_value: reduce_scatter the value of the tensor over the mesh dimension
929
+ shard_spec = cast(Shard, shard_spec)
930
+ return shard_spec._reduce_shard_tensor(tensor, mesh, self.reduce_op, mesh_dim)
931
+
932
+ def _partition_value(
933
+ self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
934
+ ) -> torch.Tensor:
935
+ # Partial placement contract #3:
936
+ # _partition_value: partition the value of a replicated tensor on the mesh dimension
937
+
938
+ # _partition_value is the conjugate operation of _reduce_value, e.g.
939
+ # - _partition_value on a sum reduce op is just a division operation
940
+ # - _reduce_value on a sum reduce op would just be a sum(allreduce) operation
941
+ num_chunks = mesh.size(mesh_dim=mesh_dim)
942
+ if self.reduce_op == "sum":
943
+ return tensor / num_chunks
944
+ elif self.reduce_op in ("avg", "min", "max"):
945
+ return tensor
946
+ else:
947
+ raise ValueError(
948
+ f"Replicate to Partial({self.reduce_op}) conversion is not supported."
949
+ )
950
+
951
+ def __hash__(self) -> int:
952
+ return 1 + hash(self.reduce_op)
953
+
954
+ def __repr__(self) -> str:
955
+ """
956
+ machine readable representation of the Partial placement
957
+ """
958
+ return f"Partial({self.reduce_op})"
959
+
960
+ def __str__(self) -> str:
961
+ """
962
+ human readable representation of the Partial placement
963
+ """
964
+ return f"P({self.reduce_op})"
965
+
966
+
967
+ # We keep the old _Partial name for a while for BC reason
968
+ _Partial = Partial
969
+
970
+
971
+ @dataclass(frozen=True)
972
+ class MaskPartial(Partial):
973
+ """
974
+ A partial mask placement devised for rowwise sharded embedding op, where we need
975
+ to mask and adjust the indices to the local embedding shard, embedding masking
976
+ is a special type of the Partial placement
977
+
978
+ NOTE: the lifecycle of this MaskPartial placement follows the corresponding DTensor
979
+ lifecycle, i.e. the indices_mask would only be alive during the lifetime of the DTensor.
980
+ """
981
+
982
+ mask_buffer: MaskBuffer = field(default_factory=MaskBuffer)
983
+
984
+ # required fields for computing the local offset and deriving the mask
985
+ offset_shape: torch.Size | None = None
986
+ offset_dim: int = 0
987
+
988
+ def __init__(
989
+ self,
990
+ reduce_op=None,
991
+ mask_buffer=None,
992
+ offset_shape=None,
993
+ offset_dim=0,
994
+ *args,
995
+ **kwargs,
996
+ ):
997
+ super().__init__(reduce_op)
998
+ if mask_buffer is None:
999
+ mask_buffer = MaskBuffer()
1000
+ object.__setattr__(self, "mask_buffer", mask_buffer)
1001
+ object.__setattr__(self, "offset_shape", offset_shape)
1002
+ object.__setattr__(self, "offset_dim", offset_dim)
1003
+
1004
+ @staticmethod
1005
+ @maybe_run_for_local_tensor
1006
+ def _mask_tensor(
1007
+ tensor: torch.Tensor, local_offset_on_dim: int, local_shard_size: int
1008
+ ) -> tuple[torch.Tensor, torch.Tensor]:
1009
+ # Build the input mask and save it for the current partial placement
1010
+ # this is so that the output of embedding op can reuse the same partial
1011
+ # placement saved mask to perform mask + reduction
1012
+ mask = (tensor < local_offset_on_dim) | (
1013
+ tensor >= local_offset_on_dim + local_shard_size
1014
+ )
1015
+ # mask the input tensor
1016
+ masked_tensor = tensor.clone() - local_offset_on_dim
1017
+ masked_tensor[mask] = 0
1018
+ return mask, masked_tensor
1019
+
1020
+ def _partition_value(
1021
+ self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
1022
+ ) -> torch.Tensor:
1023
+ my_coordinate = mesh.get_coordinate()
1024
+ assert my_coordinate is not None, "my_coordinate should not be None"
1025
+ # override parent logic to perform partial mask for embedding
1026
+ num_chunks = mesh.size(mesh_dim)
1027
+ # get local shard size and offset on the embedding_dim
1028
+ assert self.offset_shape is not None, (
1029
+ "offset_shape needs to be set for MaskPartial"
1030
+ )
1031
+ local_shard_size, local_offset_on_dim = Shard.local_shard_size_and_offset(
1032
+ self.offset_shape[self.offset_dim],
1033
+ num_chunks,
1034
+ my_coordinate[mesh_dim],
1035
+ )
1036
+ mask, masked_tensor = MaskPartial._mask_tensor(
1037
+ tensor, local_offset_on_dim, local_shard_size
1038
+ )
1039
+ # materialize the mask buffer to be used for reduction
1040
+ self.mask_buffer.materialize_mask(mask)
1041
+ return masked_tensor
1042
+
1043
+ def _reduce_value(
1044
+ self, tensor: torch.Tensor, mesh: DeviceMesh, mesh_dim: int
1045
+ ) -> torch.Tensor:
1046
+ # by the time we need reduction, we should have already saved the mask
1047
+ assert self.mask_buffer.data is not None
1048
+
1049
+ # apply the mask to the tensor that pending reduction
1050
+ self.mask_buffer.apply_mask(tensor)
1051
+
1052
+ # clear the mask buffer
1053
+ self.mask_buffer.release_mask()
1054
+
1055
+ # perform sum reduction
1056
+ return funcol.all_reduce(
1057
+ tensor, reduceOp=self.reduce_op, group=(mesh, mesh_dim)
1058
+ )
1059
+
1060
+ def _reduce_shard_value(
1061
+ self,
1062
+ tensor: torch.Tensor,
1063
+ mesh: DeviceMesh,
1064
+ mesh_dim: int,
1065
+ shard_spec: Placement,
1066
+ ) -> torch.Tensor:
1067
+ # by the time we need reduction, we should have already saved the mask
1068
+ assert self.mask_buffer.data is not None
1069
+
1070
+ # apply the mask to the tensor that pending reduction
1071
+ self.mask_buffer.apply_mask(tensor)
1072
+
1073
+ # clear the mask buffer
1074
+ self.mask_buffer.release_mask()
1075
+
1076
+ # call reduce_shard_tensor of the shard_spec.
1077
+ shard_spec = cast(Shard, shard_spec)
1078
+ return shard_spec._reduce_shard_tensor(tensor, mesh, self.reduce_op, mesh_dim)
1079
+
1080
+ def __eq__(self, other: object) -> bool:
1081
+ if not isinstance(other, MaskPartial):
1082
+ return False
1083
+
1084
+ # if either data is not None, we invalidate the sharding cache, as this indicates
1085
+ # the current MaskPartial placement is still in use and should not be used for cache hit.
1086
+ if self.mask_buffer.data is not None or other.mask_buffer.data is not None:
1087
+ return False
1088
+
1089
+ return (
1090
+ self.reduce_op == other.reduce_op
1091
+ and self.offset_shape == other.offset_shape
1092
+ and self.offset_dim == other.offset_dim
1093
+ )
1094
+
1095
+ def __hash__(self) -> int:
1096
+ return 1 + hash(
1097
+ (
1098
+ self.reduce_op,
1099
+ self.offset_shape,
1100
+ self.offset_dim,
1101
+ )
1102
+ )
1103
+
1104
+ def __repr__(self) -> str:
1105
+ """
1106
+ machine readable representation of the MaskPartial placement
1107
+ """
1108
+ return f"MaskPartial(reduce_op={self.reduce_op}, offset_shape={self.offset_shape}, offset_dim={self.offset_dim})"
1109
+
1110
+ def __str__(self) -> str:
1111
+ """
1112
+ human readable representation of the MaskPartial placement
1113
+ """
1114
+ return f"MaskP({self.reduce_op}, {self.offset_shape}, {self.offset_dim})"
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/__init__.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ The ``distributions`` package contains parameterizable probability distributions
3
+ and sampling functions. This allows the construction of stochastic computation
4
+ graphs and stochastic gradient estimators for optimization. This package
5
+ generally follows the design of the `TensorFlow Distributions`_ package.
6
+
7
+ .. _`TensorFlow Distributions`:
8
+ https://arxiv.org/abs/1711.10604
9
+
10
+ It is not possible to directly backpropagate through random samples. However,
11
+ there are two main methods for creating surrogate functions that can be
12
+ backpropagated through. These are the score function estimator/likelihood ratio
13
+ estimator/REINFORCE and the pathwise derivative estimator. REINFORCE is commonly
14
+ seen as the basis for policy gradient methods in reinforcement learning, and the
15
+ pathwise derivative estimator is commonly seen in the reparameterization trick
16
+ in variational autoencoders. Whilst the score function only requires the value
17
+ of samples :math:`f(x)`, the pathwise derivative requires the derivative
18
+ :math:`f'(x)`. The next sections discuss these two in a reinforcement learning
19
+ example. For more details see
20
+ `Gradient Estimation Using Stochastic Computation Graphs`_ .
21
+
22
+ .. _`Gradient Estimation Using Stochastic Computation Graphs`:
23
+ https://arxiv.org/abs/1506.05254
24
+
25
+ Score function
26
+ ^^^^^^^^^^^^^^
27
+
28
+ When the probability density function is differentiable with respect to its
29
+ parameters, we only need :meth:`~torch.distributions.Distribution.sample` and
30
+ :meth:`~torch.distributions.Distribution.log_prob` to implement REINFORCE:
31
+
32
+ .. math::
33
+
34
+ \Delta\theta = \alpha r \frac{\partial\log p(a|\pi^\theta(s))}{\partial\theta}
35
+
36
+ where :math:`\theta` are the parameters, :math:`\alpha` is the learning rate,
37
+ :math:`r` is the reward and :math:`p(a|\pi^\theta(s))` is the probability of
38
+ taking action :math:`a` in state :math:`s` given policy :math:`\pi^\theta`.
39
+
40
+ In practice we would sample an action from the output of a network, apply this
41
+ action in an environment, and then use ``log_prob`` to construct an equivalent
42
+ loss function. Note that we use a negative because optimizers use gradient
43
+ descent, whilst the rule above assumes gradient ascent. With a categorical
44
+ policy, the code for implementing REINFORCE would be as follows::
45
+
46
+ probs = policy_network(state)
47
+ # Note that this is equivalent to what used to be called multinomial
48
+ m = Categorical(probs)
49
+ action = m.sample()
50
+ next_state, reward = env.step(action)
51
+ loss = -m.log_prob(action) * reward
52
+ loss.backward()
53
+
54
+ Pathwise derivative
55
+ ^^^^^^^^^^^^^^^^^^^
56
+
57
+ The other way to implement these stochastic/policy gradients would be to use the
58
+ reparameterization trick from the
59
+ :meth:`~torch.distributions.Distribution.rsample` method, where the
60
+ parameterized random variable can be constructed via a parameterized
61
+ deterministic function of a parameter-free random variable. The reparameterized
62
+ sample therefore becomes differentiable. The code for implementing the pathwise
63
+ derivative would be as follows::
64
+
65
+ params = policy_network(state)
66
+ m = Normal(*params)
67
+ # Any distribution with .has_rsample == True could work based on the application
68
+ action = m.rsample()
69
+ next_state, reward = env.step(action) # Assuming that reward is differentiable
70
+ loss = -reward
71
+ loss.backward()
72
+ """
73
+
74
+ from . import transforms
75
+ from .bernoulli import Bernoulli
76
+ from .beta import Beta
77
+ from .binomial import Binomial
78
+ from .categorical import Categorical
79
+ from .cauchy import Cauchy
80
+ from .chi2 import Chi2
81
+ from .constraint_registry import biject_to, transform_to
82
+ from .continuous_bernoulli import ContinuousBernoulli
83
+ from .dirichlet import Dirichlet
84
+ from .distribution import Distribution
85
+ from .exp_family import ExponentialFamily
86
+ from .exponential import Exponential
87
+ from .fishersnedecor import FisherSnedecor
88
+ from .gamma import Gamma
89
+ from .generalized_pareto import GeneralizedPareto
90
+ from .geometric import Geometric
91
+ from .gumbel import Gumbel
92
+ from .half_cauchy import HalfCauchy
93
+ from .half_normal import HalfNormal
94
+ from .independent import Independent
95
+ from .inverse_gamma import InverseGamma
96
+ from .kl import _add_kl_info, kl_divergence, register_kl
97
+ from .kumaraswamy import Kumaraswamy
98
+ from .laplace import Laplace
99
+ from .lkj_cholesky import LKJCholesky
100
+ from .log_normal import LogNormal
101
+ from .logistic_normal import LogisticNormal
102
+ from .lowrank_multivariate_normal import LowRankMultivariateNormal
103
+ from .mixture_same_family import MixtureSameFamily
104
+ from .multinomial import Multinomial
105
+ from .multivariate_normal import MultivariateNormal
106
+ from .negative_binomial import NegativeBinomial
107
+ from .normal import Normal
108
+ from .one_hot_categorical import OneHotCategorical, OneHotCategoricalStraightThrough
109
+ from .pareto import Pareto
110
+ from .poisson import Poisson
111
+ from .relaxed_bernoulli import RelaxedBernoulli
112
+ from .relaxed_categorical import RelaxedOneHotCategorical
113
+ from .studentT import StudentT
114
+ from .transformed_distribution import TransformedDistribution
115
+ from .transforms import * # noqa: F403
116
+ from .uniform import Uniform
117
+ from .von_mises import VonMises
118
+ from .weibull import Weibull
119
+ from .wishart import Wishart
120
+
121
+
122
+ _add_kl_info()
123
+ del _add_kl_info
124
+
125
+ __all__ = [
126
+ "Bernoulli",
127
+ "Beta",
128
+ "Binomial",
129
+ "Categorical",
130
+ "Cauchy",
131
+ "Chi2",
132
+ "ContinuousBernoulli",
133
+ "Dirichlet",
134
+ "Distribution",
135
+ "Exponential",
136
+ "ExponentialFamily",
137
+ "FisherSnedecor",
138
+ "Gamma",
139
+ "GeneralizedPareto",
140
+ "Geometric",
141
+ "Gumbel",
142
+ "HalfCauchy",
143
+ "HalfNormal",
144
+ "Independent",
145
+ "InverseGamma",
146
+ "Kumaraswamy",
147
+ "LKJCholesky",
148
+ "Laplace",
149
+ "LogNormal",
150
+ "LogisticNormal",
151
+ "LowRankMultivariateNormal",
152
+ "MixtureSameFamily",
153
+ "Multinomial",
154
+ "MultivariateNormal",
155
+ "NegativeBinomial",
156
+ "Normal",
157
+ "OneHotCategorical",
158
+ "OneHotCategoricalStraightThrough",
159
+ "Pareto",
160
+ "RelaxedBernoulli",
161
+ "RelaxedOneHotCategorical",
162
+ "StudentT",
163
+ "Poisson",
164
+ "Uniform",
165
+ "VonMises",
166
+ "Weibull",
167
+ "Wishart",
168
+ "TransformedDistribution",
169
+ "biject_to",
170
+ "kl_divergence",
171
+ "register_kl",
172
+ "transform_to",
173
+ ]
174
+ __all__.extend(transforms.__all__)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/bernoulli.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Optional, Union
3
+
4
+ import torch
5
+ from torch import nan, Tensor
6
+ from torch.distributions import constraints
7
+ from torch.distributions.exp_family import ExponentialFamily
8
+ from torch.distributions.utils import (
9
+ broadcast_all,
10
+ lazy_property,
11
+ logits_to_probs,
12
+ probs_to_logits,
13
+ )
14
+ from torch.nn.functional import binary_cross_entropy_with_logits
15
+ from torch.types import _Number, Number
16
+
17
+
18
+ __all__ = ["Bernoulli"]
19
+
20
+
21
+ class Bernoulli(ExponentialFamily):
22
+ r"""
23
+ Creates a Bernoulli distribution parameterized by :attr:`probs`
24
+ or :attr:`logits` (but not both).
25
+
26
+ Samples are binary (0 or 1). They take the value `1` with probability `p`
27
+ and `0` with probability `1 - p`.
28
+
29
+ Example::
30
+
31
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
32
+ >>> m = Bernoulli(torch.tensor([0.3]))
33
+ >>> m.sample() # 30% chance 1; 70% chance 0
34
+ tensor([ 0.])
35
+
36
+ Args:
37
+ probs (Number, Tensor): the probability of sampling `1`
38
+ logits (Number, Tensor): the log-odds of sampling `1`
39
+ validate_args (bool, optional): whether to validate arguments, None by default
40
+ """
41
+
42
+ # pyrefly: ignore [bad-override]
43
+ arg_constraints = {"probs": constraints.unit_interval, "logits": constraints.real}
44
+ support = constraints.boolean
45
+ has_enumerate_support = True
46
+ _mean_carrier_measure = 0
47
+
48
+ def __init__(
49
+ self,
50
+ probs: Optional[Union[Tensor, Number]] = None,
51
+ logits: Optional[Union[Tensor, Number]] = None,
52
+ validate_args: Optional[bool] = None,
53
+ ) -> None:
54
+ if (probs is None) == (logits is None):
55
+ raise ValueError(
56
+ "Either `probs` or `logits` must be specified, but not both."
57
+ )
58
+ if probs is not None:
59
+ is_scalar = isinstance(probs, _Number)
60
+ # pyrefly: ignore [read-only]
61
+ (self.probs,) = broadcast_all(probs)
62
+ else:
63
+ assert logits is not None # helps mypy
64
+ is_scalar = isinstance(logits, _Number)
65
+ # pyrefly: ignore [read-only]
66
+ (self.logits,) = broadcast_all(logits)
67
+ self._param = self.probs if probs is not None else self.logits
68
+ if is_scalar:
69
+ batch_shape = torch.Size()
70
+ else:
71
+ batch_shape = self._param.size()
72
+ super().__init__(batch_shape, validate_args=validate_args)
73
+
74
+ def expand(self, batch_shape, _instance=None):
75
+ new = self._get_checked_instance(Bernoulli, _instance)
76
+ batch_shape = torch.Size(batch_shape)
77
+ if "probs" in self.__dict__:
78
+ new.probs = self.probs.expand(batch_shape)
79
+ new._param = new.probs
80
+ if "logits" in self.__dict__:
81
+ new.logits = self.logits.expand(batch_shape)
82
+ new._param = new.logits
83
+ super(Bernoulli, new).__init__(batch_shape, validate_args=False)
84
+ new._validate_args = self._validate_args
85
+ return new
86
+
87
+ def _new(self, *args, **kwargs):
88
+ return self._param.new(*args, **kwargs)
89
+
90
+ @property
91
+ def mean(self) -> Tensor:
92
+ return self.probs
93
+
94
+ @property
95
+ def mode(self) -> Tensor:
96
+ mode = (self.probs >= 0.5).to(self.probs)
97
+ mode[self.probs == 0.5] = nan
98
+ return mode
99
+
100
+ @property
101
+ def variance(self) -> Tensor:
102
+ return self.probs * (1 - self.probs)
103
+
104
+ @lazy_property
105
+ def logits(self) -> Tensor:
106
+ return probs_to_logits(self.probs, is_binary=True)
107
+
108
+ @lazy_property
109
+ def probs(self) -> Tensor:
110
+ return logits_to_probs(self.logits, is_binary=True)
111
+
112
+ @property
113
+ def param_shape(self) -> torch.Size:
114
+ return self._param.size()
115
+
116
+ def sample(self, sample_shape=torch.Size()):
117
+ shape = self._extended_shape(sample_shape)
118
+ with torch.no_grad():
119
+ return torch.bernoulli(self.probs.expand(shape))
120
+
121
+ def log_prob(self, value):
122
+ if self._validate_args:
123
+ self._validate_sample(value)
124
+ logits, value = broadcast_all(self.logits, value)
125
+ return -binary_cross_entropy_with_logits(logits, value, reduction="none")
126
+
127
+ def entropy(self):
128
+ return binary_cross_entropy_with_logits(
129
+ self.logits, self.probs, reduction="none"
130
+ )
131
+
132
+ def enumerate_support(self, expand=True):
133
+ values = torch.arange(2, dtype=self._param.dtype, device=self._param.device)
134
+ values = values.view((-1,) + (1,) * len(self._batch_shape))
135
+ if expand:
136
+ values = values.expand((-1,) + self._batch_shape)
137
+ return values
138
+
139
+ @property
140
+ def _natural_params(self) -> tuple[Tensor]:
141
+ return (torch.logit(self.probs),)
142
+
143
+ # pyrefly: ignore [bad-override]
144
+ def _log_normalizer(self, x):
145
+ return torch.log1p(torch.exp(x))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/beta.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Optional, Union
3
+
4
+ import torch
5
+ from torch import Tensor
6
+ from torch.distributions import constraints
7
+ from torch.distributions.dirichlet import Dirichlet
8
+ from torch.distributions.exp_family import ExponentialFamily
9
+ from torch.distributions.utils import broadcast_all
10
+ from torch.types import _Number, _size
11
+
12
+
13
+ __all__ = ["Beta"]
14
+
15
+
16
+ class Beta(ExponentialFamily):
17
+ r"""
18
+ Beta distribution parameterized by :attr:`concentration1` and :attr:`concentration0`.
19
+
20
+ Example::
21
+
22
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
23
+ >>> m = Beta(torch.tensor([0.5]), torch.tensor([0.5]))
24
+ >>> m.sample() # Beta distributed with concentration concentration1 and concentration0
25
+ tensor([ 0.1046])
26
+
27
+ Args:
28
+ concentration1 (float or Tensor): 1st concentration parameter of the distribution
29
+ (often referred to as alpha)
30
+ concentration0 (float or Tensor): 2nd concentration parameter of the distribution
31
+ (often referred to as beta)
32
+ """
33
+
34
+ # pyrefly: ignore [bad-override]
35
+ arg_constraints = {
36
+ "concentration1": constraints.positive,
37
+ "concentration0": constraints.positive,
38
+ }
39
+ support = constraints.unit_interval
40
+ has_rsample = True
41
+
42
+ def __init__(
43
+ self,
44
+ concentration1: Union[Tensor, float],
45
+ concentration0: Union[Tensor, float],
46
+ validate_args: Optional[bool] = None,
47
+ ) -> None:
48
+ if isinstance(concentration1, _Number) and isinstance(concentration0, _Number):
49
+ concentration1_concentration0 = torch.tensor(
50
+ [float(concentration1), float(concentration0)]
51
+ )
52
+ else:
53
+ concentration1, concentration0 = broadcast_all(
54
+ concentration1, concentration0
55
+ )
56
+ concentration1_concentration0 = torch.stack(
57
+ [concentration1, concentration0], -1
58
+ )
59
+ self._dirichlet = Dirichlet(
60
+ concentration1_concentration0, validate_args=validate_args
61
+ )
62
+ super().__init__(self._dirichlet._batch_shape, validate_args=validate_args)
63
+
64
+ def expand(self, batch_shape, _instance=None):
65
+ new = self._get_checked_instance(Beta, _instance)
66
+ batch_shape = torch.Size(batch_shape)
67
+ new._dirichlet = self._dirichlet.expand(batch_shape)
68
+ super(Beta, new).__init__(batch_shape, validate_args=False)
69
+ new._validate_args = self._validate_args
70
+ return new
71
+
72
+ @property
73
+ def mean(self) -> Tensor:
74
+ return self.concentration1 / (self.concentration1 + self.concentration0)
75
+
76
+ @property
77
+ def mode(self) -> Tensor:
78
+ return self._dirichlet.mode[..., 0]
79
+
80
+ @property
81
+ def variance(self) -> Tensor:
82
+ total = self.concentration1 + self.concentration0
83
+ return self.concentration1 * self.concentration0 / (total.pow(2) * (total + 1))
84
+
85
+ def rsample(self, sample_shape: _size = ()) -> Tensor:
86
+ return self._dirichlet.rsample(sample_shape).select(-1, 0)
87
+
88
+ def log_prob(self, value):
89
+ if self._validate_args:
90
+ self._validate_sample(value)
91
+ heads_tails = torch.stack([value, 1.0 - value], -1)
92
+ return self._dirichlet.log_prob(heads_tails)
93
+
94
+ def entropy(self):
95
+ return self._dirichlet.entropy()
96
+
97
+ @property
98
+ def concentration1(self) -> Tensor:
99
+ result = self._dirichlet.concentration[..., 0]
100
+ if isinstance(result, _Number):
101
+ return torch.tensor([result])
102
+ else:
103
+ return result
104
+
105
+ @property
106
+ def concentration0(self) -> Tensor:
107
+ result = self._dirichlet.concentration[..., 1]
108
+ if isinstance(result, _Number):
109
+ return torch.tensor([result])
110
+ else:
111
+ return result
112
+
113
+ @property
114
+ def _natural_params(self) -> tuple[Tensor, Tensor]:
115
+ return (self.concentration1, self.concentration0)
116
+
117
+ # pyrefly: ignore [bad-override]
118
+ def _log_normalizer(self, x, y):
119
+ return torch.lgamma(x) + torch.lgamma(y) - torch.lgamma(x + y)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/binomial.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Optional, Union
3
+
4
+ import torch
5
+ from torch import Tensor
6
+ from torch.distributions import constraints
7
+ from torch.distributions.distribution import Distribution
8
+ from torch.distributions.utils import (
9
+ broadcast_all,
10
+ lazy_property,
11
+ logits_to_probs,
12
+ probs_to_logits,
13
+ )
14
+
15
+
16
+ __all__ = ["Binomial"]
17
+
18
+
19
+ def _clamp_by_zero(x):
20
+ # works like clamp(x, min=0) but has grad at 0 is 0.5
21
+ return (x.clamp(min=0) + x - x.clamp(max=0)) / 2
22
+
23
+
24
+ class Binomial(Distribution):
25
+ r"""
26
+ Creates a Binomial distribution parameterized by :attr:`total_count` and
27
+ either :attr:`probs` or :attr:`logits` (but not both). :attr:`total_count` must be
28
+ broadcastable with :attr:`probs`/:attr:`logits`.
29
+
30
+ Example::
31
+
32
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
33
+ >>> m = Binomial(100, torch.tensor([0 , .2, .8, 1]))
34
+ >>> x = m.sample()
35
+ tensor([ 0., 22., 71., 100.])
36
+
37
+ >>> m = Binomial(torch.tensor([[5.], [10.]]), torch.tensor([0.5, 0.8]))
38
+ >>> x = m.sample()
39
+ tensor([[ 4., 5.],
40
+ [ 7., 6.]])
41
+
42
+ Args:
43
+ total_count (int or Tensor): number of Bernoulli trials
44
+ probs (Tensor): Event probabilities
45
+ logits (Tensor): Event log-odds
46
+ """
47
+
48
+ # pyrefly: ignore [bad-override]
49
+ arg_constraints = {
50
+ "total_count": constraints.nonnegative_integer,
51
+ "probs": constraints.unit_interval,
52
+ "logits": constraints.real,
53
+ }
54
+ has_enumerate_support = True
55
+
56
+ def __init__(
57
+ self,
58
+ total_count: Union[Tensor, int] = 1,
59
+ probs: Optional[Tensor] = None,
60
+ logits: Optional[Tensor] = None,
61
+ validate_args: Optional[bool] = None,
62
+ ) -> None:
63
+ if (probs is None) == (logits is None):
64
+ raise ValueError(
65
+ "Either `probs` or `logits` must be specified, but not both."
66
+ )
67
+ if probs is not None:
68
+ (
69
+ self.total_count,
70
+ # pyrefly: ignore [read-only]
71
+ self.probs,
72
+ ) = broadcast_all(total_count, probs)
73
+ self.total_count = self.total_count.type_as(self.probs)
74
+ else:
75
+ assert logits is not None # helps mypy
76
+ (
77
+ self.total_count,
78
+ # pyrefly: ignore [read-only]
79
+ self.logits,
80
+ ) = broadcast_all(total_count, logits)
81
+ self.total_count = self.total_count.type_as(self.logits)
82
+
83
+ self._param = self.probs if probs is not None else self.logits
84
+ batch_shape = self._param.size()
85
+ super().__init__(batch_shape, validate_args=validate_args)
86
+
87
+ def expand(self, batch_shape, _instance=None):
88
+ new = self._get_checked_instance(Binomial, _instance)
89
+ batch_shape = torch.Size(batch_shape)
90
+ new.total_count = self.total_count.expand(batch_shape)
91
+ if "probs" in self.__dict__:
92
+ new.probs = self.probs.expand(batch_shape)
93
+ new._param = new.probs
94
+ if "logits" in self.__dict__:
95
+ new.logits = self.logits.expand(batch_shape)
96
+ new._param = new.logits
97
+ super(Binomial, new).__init__(batch_shape, validate_args=False)
98
+ new._validate_args = self._validate_args
99
+ return new
100
+
101
+ def _new(self, *args, **kwargs):
102
+ return self._param.new(*args, **kwargs)
103
+
104
+ @constraints.dependent_property(is_discrete=True, event_dim=0)
105
+ # pyrefly: ignore [bad-override]
106
+ def support(self):
107
+ return constraints.integer_interval(0, self.total_count)
108
+
109
+ @property
110
+ def mean(self) -> Tensor:
111
+ return self.total_count * self.probs
112
+
113
+ @property
114
+ def mode(self) -> Tensor:
115
+ return ((self.total_count + 1) * self.probs).floor().clamp(max=self.total_count)
116
+
117
+ @property
118
+ def variance(self) -> Tensor:
119
+ return self.total_count * self.probs * (1 - self.probs)
120
+
121
+ @lazy_property
122
+ def logits(self) -> Tensor:
123
+ return probs_to_logits(self.probs, is_binary=True)
124
+
125
+ @lazy_property
126
+ def probs(self) -> Tensor:
127
+ return logits_to_probs(self.logits, is_binary=True)
128
+
129
+ @property
130
+ def param_shape(self) -> torch.Size:
131
+ return self._param.size()
132
+
133
+ def sample(self, sample_shape=torch.Size()):
134
+ shape = self._extended_shape(sample_shape)
135
+ with torch.no_grad():
136
+ return torch.binomial(
137
+ self.total_count.expand(shape), self.probs.expand(shape)
138
+ )
139
+
140
+ def log_prob(self, value):
141
+ if self._validate_args:
142
+ self._validate_sample(value)
143
+ log_factorial_n = torch.lgamma(self.total_count + 1)
144
+ log_factorial_k = torch.lgamma(value + 1)
145
+ log_factorial_nmk = torch.lgamma(self.total_count - value + 1)
146
+ # k * log(p) + (n - k) * log(1 - p) = k * (log(p) - log(1 - p)) + n * log(1 - p)
147
+ # (case logit < 0) = k * logit - n * log1p(e^logit)
148
+ # (case logit > 0) = k * logit - n * (log(p) - log(1 - p)) + n * log(p)
149
+ # = k * logit - n * logit - n * log1p(e^-logit)
150
+ # (merge two cases) = k * logit - n * max(logit, 0) - n * log1p(e^-|logit|)
151
+ normalize_term = (
152
+ self.total_count * _clamp_by_zero(self.logits)
153
+ + self.total_count * torch.log1p(torch.exp(-torch.abs(self.logits)))
154
+ - log_factorial_n
155
+ )
156
+ return (
157
+ value * self.logits - log_factorial_k - log_factorial_nmk - normalize_term
158
+ )
159
+
160
+ def entropy(self):
161
+ total_count = int(self.total_count.max())
162
+ if not self.total_count.min() == total_count:
163
+ raise NotImplementedError(
164
+ "Inhomogeneous total count not supported by `entropy`."
165
+ )
166
+
167
+ log_prob = self.log_prob(self.enumerate_support(False))
168
+ return -(torch.exp(log_prob) * log_prob).sum(0)
169
+
170
+ def enumerate_support(self, expand=True):
171
+ total_count = int(self.total_count.max())
172
+ if not self.total_count.min() == total_count:
173
+ raise NotImplementedError(
174
+ "Inhomogeneous total count not supported by `enumerate_support`."
175
+ )
176
+ values = torch.arange(
177
+ 1 + total_count, dtype=self._param.dtype, device=self._param.device
178
+ )
179
+ values = values.view((-1,) + (1,) * len(self._batch_shape))
180
+ if expand:
181
+ values = values.expand((-1,) + self._batch_shape)
182
+ return values
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/categorical.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Optional
3
+
4
+ import torch
5
+ from torch import nan, Tensor
6
+ from torch.distributions import constraints
7
+ from torch.distributions.distribution import Distribution
8
+ from torch.distributions.utils import lazy_property, logits_to_probs, probs_to_logits
9
+
10
+
11
+ __all__ = ["Categorical"]
12
+
13
+
14
+ class Categorical(Distribution):
15
+ r"""
16
+ Creates a categorical distribution parameterized by either :attr:`probs` or
17
+ :attr:`logits` (but not both).
18
+
19
+ .. note::
20
+ It is equivalent to the distribution that :func:`torch.multinomial`
21
+ samples from.
22
+
23
+ Samples are integers from :math:`\{0, \ldots, K-1\}` where `K` is ``probs.size(-1)``.
24
+
25
+ If `probs` is 1-dimensional with length-`K`, each element is the relative probability
26
+ of sampling the class at that index.
27
+
28
+ If `probs` is N-dimensional, the first N-1 dimensions are treated as a batch of
29
+ relative probability vectors.
30
+
31
+ .. note:: The `probs` argument must be non-negative, finite and have a non-zero sum,
32
+ and it will be normalized to sum to 1 along the last dimension. :attr:`probs`
33
+ will return this normalized value.
34
+ The `logits` argument will be interpreted as unnormalized log probabilities
35
+ and can therefore be any real number. It will likewise be normalized so that
36
+ the resulting probabilities sum to 1 along the last dimension. :attr:`logits`
37
+ will return this normalized value.
38
+
39
+ See also: :func:`torch.multinomial`
40
+
41
+ Example::
42
+
43
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
44
+ >>> m = Categorical(torch.tensor([ 0.25, 0.25, 0.25, 0.25 ]))
45
+ >>> m.sample() # equal probability of 0, 1, 2, 3
46
+ tensor(3)
47
+
48
+ Args:
49
+ probs (Tensor): event probabilities
50
+ logits (Tensor): event log probabilities (unnormalized)
51
+ """
52
+
53
+ # pyrefly: ignore [bad-override]
54
+ arg_constraints = {"probs": constraints.simplex, "logits": constraints.real_vector}
55
+ has_enumerate_support = True
56
+
57
+ def __init__(
58
+ self,
59
+ probs: Optional[Tensor] = None,
60
+ logits: Optional[Tensor] = None,
61
+ validate_args: Optional[bool] = None,
62
+ ) -> None:
63
+ if (probs is None) == (logits is None):
64
+ raise ValueError(
65
+ "Either `probs` or `logits` must be specified, but not both."
66
+ )
67
+ if probs is not None:
68
+ if probs.dim() < 1:
69
+ raise ValueError("`probs` parameter must be at least one-dimensional.")
70
+ # pyrefly: ignore [read-only]
71
+ self.probs = probs / probs.sum(-1, keepdim=True)
72
+ else:
73
+ assert logits is not None # helps mypy
74
+ if logits.dim() < 1:
75
+ raise ValueError("`logits` parameter must be at least one-dimensional.")
76
+ # Normalize
77
+ # pyrefly: ignore [read-only]
78
+ self.logits = logits - logits.logsumexp(dim=-1, keepdim=True)
79
+ self._param = self.probs if probs is not None else self.logits
80
+ self._num_events = self._param.size()[-1]
81
+ batch_shape = (
82
+ self._param.size()[:-1] if self._param.ndimension() > 1 else torch.Size()
83
+ )
84
+ super().__init__(batch_shape, validate_args=validate_args)
85
+
86
+ def expand(self, batch_shape, _instance=None):
87
+ new = self._get_checked_instance(Categorical, _instance)
88
+ batch_shape = torch.Size(batch_shape)
89
+ param_shape = batch_shape + torch.Size((self._num_events,))
90
+ if "probs" in self.__dict__:
91
+ new.probs = self.probs.expand(param_shape)
92
+ new._param = new.probs
93
+ if "logits" in self.__dict__:
94
+ new.logits = self.logits.expand(param_shape)
95
+ new._param = new.logits
96
+ new._num_events = self._num_events
97
+ super(Categorical, new).__init__(batch_shape, validate_args=False)
98
+ new._validate_args = self._validate_args
99
+ return new
100
+
101
+ def _new(self, *args, **kwargs):
102
+ return self._param.new(*args, **kwargs)
103
+
104
+ @constraints.dependent_property(is_discrete=True, event_dim=0)
105
+ # pyrefly: ignore [bad-override]
106
+ def support(self):
107
+ return constraints.integer_interval(0, self._num_events - 1)
108
+
109
+ @lazy_property
110
+ def logits(self) -> Tensor:
111
+ return probs_to_logits(self.probs)
112
+
113
+ @lazy_property
114
+ def probs(self) -> Tensor:
115
+ return logits_to_probs(self.logits)
116
+
117
+ @property
118
+ def param_shape(self) -> torch.Size:
119
+ return self._param.size()
120
+
121
+ @property
122
+ def mean(self) -> Tensor:
123
+ return torch.full(
124
+ self._extended_shape(),
125
+ nan,
126
+ dtype=self.probs.dtype,
127
+ device=self.probs.device,
128
+ )
129
+
130
+ @property
131
+ def mode(self) -> Tensor:
132
+ return self.probs.argmax(dim=-1)
133
+
134
+ @property
135
+ def variance(self) -> Tensor:
136
+ return torch.full(
137
+ self._extended_shape(),
138
+ nan,
139
+ dtype=self.probs.dtype,
140
+ device=self.probs.device,
141
+ )
142
+
143
+ def sample(self, sample_shape=torch.Size()):
144
+ if not isinstance(sample_shape, torch.Size):
145
+ sample_shape = torch.Size(sample_shape)
146
+ probs_2d = self.probs.reshape(-1, self._num_events)
147
+ samples_2d = torch.multinomial(probs_2d, sample_shape.numel(), True).T
148
+ return samples_2d.reshape(self._extended_shape(sample_shape))
149
+
150
+ def log_prob(self, value):
151
+ if self._validate_args:
152
+ self._validate_sample(value)
153
+ value = value.long().unsqueeze(-1)
154
+ value, log_pmf = torch.broadcast_tensors(value, self.logits)
155
+ value = value[..., :1]
156
+ return log_pmf.gather(-1, value).squeeze(-1)
157
+
158
+ def entropy(self):
159
+ min_real = torch.finfo(self.logits.dtype).min
160
+ logits = torch.clamp(self.logits, min=min_real)
161
+ p_log_p = logits * self.probs
162
+ return -p_log_p.sum(-1)
163
+
164
+ def enumerate_support(self, expand=True):
165
+ num_events = self._num_events
166
+ values = torch.arange(num_events, dtype=torch.long, device=self._param.device)
167
+ values = values.view((-1,) + (1,) * len(self._batch_shape))
168
+ if expand:
169
+ values = values.expand((-1,) + self._batch_shape)
170
+ return values
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/cauchy.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import math
3
+ from typing import Optional, Union
4
+
5
+ import torch
6
+ from torch import inf, nan, Tensor
7
+ from torch.distributions import constraints
8
+ from torch.distributions.distribution import Distribution
9
+ from torch.distributions.utils import broadcast_all
10
+ from torch.types import _Number, _size
11
+
12
+
13
+ __all__ = ["Cauchy"]
14
+
15
+
16
+ class Cauchy(Distribution):
17
+ r"""
18
+ Samples from a Cauchy (Lorentz) distribution. The distribution of the ratio of
19
+ independent normally distributed random variables with means `0` follows a
20
+ Cauchy distribution.
21
+
22
+ Example::
23
+
24
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
25
+ >>> m = Cauchy(torch.tensor([0.0]), torch.tensor([1.0]))
26
+ >>> m.sample() # sample from a Cauchy distribution with loc=0 and scale=1
27
+ tensor([ 2.3214])
28
+
29
+ Args:
30
+ loc (float or Tensor): mode or median of the distribution.
31
+ scale (float or Tensor): half width at half maximum.
32
+ """
33
+
34
+ # pyrefly: ignore [bad-override]
35
+ arg_constraints = {"loc": constraints.real, "scale": constraints.positive}
36
+ support = constraints.real
37
+ has_rsample = True
38
+
39
+ def __init__(
40
+ self,
41
+ loc: Union[Tensor, float],
42
+ scale: Union[Tensor, float],
43
+ validate_args: Optional[bool] = None,
44
+ ) -> None:
45
+ self.loc, self.scale = broadcast_all(loc, scale)
46
+ if isinstance(loc, _Number) and isinstance(scale, _Number):
47
+ batch_shape = torch.Size()
48
+ else:
49
+ batch_shape = self.loc.size()
50
+ super().__init__(batch_shape, validate_args=validate_args)
51
+
52
+ def expand(self, batch_shape, _instance=None):
53
+ new = self._get_checked_instance(Cauchy, _instance)
54
+ batch_shape = torch.Size(batch_shape)
55
+ new.loc = self.loc.expand(batch_shape)
56
+ new.scale = self.scale.expand(batch_shape)
57
+ super(Cauchy, new).__init__(batch_shape, validate_args=False)
58
+ new._validate_args = self._validate_args
59
+ return new
60
+
61
+ @property
62
+ def mean(self) -> Tensor:
63
+ return torch.full(
64
+ self._extended_shape(), nan, dtype=self.loc.dtype, device=self.loc.device
65
+ )
66
+
67
+ @property
68
+ def mode(self) -> Tensor:
69
+ return self.loc
70
+
71
+ @property
72
+ def variance(self) -> Tensor:
73
+ return torch.full(
74
+ self._extended_shape(), inf, dtype=self.loc.dtype, device=self.loc.device
75
+ )
76
+
77
+ def rsample(self, sample_shape: _size = torch.Size()) -> Tensor:
78
+ shape = self._extended_shape(sample_shape)
79
+ eps = self.loc.new(shape).cauchy_()
80
+ return self.loc + eps * self.scale
81
+
82
+ def log_prob(self, value):
83
+ if self._validate_args:
84
+ self._validate_sample(value)
85
+ return (
86
+ -math.log(math.pi)
87
+ - self.scale.log()
88
+ - (((value - self.loc) / self.scale) ** 2).log1p()
89
+ )
90
+
91
+ def cdf(self, value):
92
+ if self._validate_args:
93
+ self._validate_sample(value)
94
+ return torch.atan((value - self.loc) / self.scale) / math.pi + 0.5
95
+
96
+ def icdf(self, value):
97
+ return torch.tan(math.pi * (value - 0.5)) * self.scale + self.loc
98
+
99
+ def entropy(self):
100
+ return math.log(4 * math.pi) + self.scale.log()
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/chi2.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Optional, Union
3
+
4
+ from torch import Tensor
5
+ from torch.distributions import constraints
6
+ from torch.distributions.gamma import Gamma
7
+
8
+
9
+ __all__ = ["Chi2"]
10
+
11
+
12
+ class Chi2(Gamma):
13
+ r"""
14
+ Creates a Chi-squared distribution parameterized by shape parameter :attr:`df`.
15
+ This is exactly equivalent to ``Gamma(alpha=0.5*df, beta=0.5)``
16
+
17
+ Example::
18
+
19
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
20
+ >>> m = Chi2(torch.tensor([1.0]))
21
+ >>> m.sample() # Chi2 distributed with shape df=1
22
+ tensor([ 0.1046])
23
+
24
+ Args:
25
+ df (float or Tensor): shape parameter of the distribution
26
+ """
27
+
28
+ arg_constraints = {"df": constraints.positive}
29
+
30
+ def __init__(
31
+ self,
32
+ df: Union[Tensor, float],
33
+ validate_args: Optional[bool] = None,
34
+ ) -> None:
35
+ super().__init__(0.5 * df, 0.5, validate_args=validate_args)
36
+
37
+ def expand(self, batch_shape, _instance=None):
38
+ new = self._get_checked_instance(Chi2, _instance)
39
+ return super().expand(batch_shape, new)
40
+
41
+ @property
42
+ def df(self) -> Tensor:
43
+ return self.concentration * 2
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/constraint_registry.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ r"""
3
+ PyTorch provides two global :class:`ConstraintRegistry` objects that link
4
+ :class:`~torch.distributions.constraints.Constraint` objects to
5
+ :class:`~torch.distributions.transforms.Transform` objects. These objects both
6
+ input constraints and return transforms, but they have different guarantees on
7
+ bijectivity.
8
+
9
+ 1. ``biject_to(constraint)`` looks up a bijective
10
+ :class:`~torch.distributions.transforms.Transform` from ``constraints.real``
11
+ to the given ``constraint``. The returned transform is guaranteed to have
12
+ ``.bijective = True`` and should implement ``.log_abs_det_jacobian()``.
13
+ 2. ``transform_to(constraint)`` looks up a not-necessarily bijective
14
+ :class:`~torch.distributions.transforms.Transform` from ``constraints.real``
15
+ to the given ``constraint``. The returned transform is not guaranteed to
16
+ implement ``.log_abs_det_jacobian()``.
17
+
18
+ The ``transform_to()`` registry is useful for performing unconstrained
19
+ optimization on constrained parameters of probability distributions, which are
20
+ indicated by each distribution's ``.arg_constraints`` dict. These transforms often
21
+ overparameterize a space in order to avoid rotation; they are thus more
22
+ suitable for coordinate-wise optimization algorithms like Adam::
23
+
24
+ loc = torch.zeros(100, requires_grad=True)
25
+ unconstrained = torch.zeros(100, requires_grad=True)
26
+ scale = transform_to(Normal.arg_constraints["scale"])(unconstrained)
27
+ loss = -Normal(loc, scale).log_prob(data).sum()
28
+
29
+ The ``biject_to()`` registry is useful for Hamiltonian Monte Carlo, where
30
+ samples from a probability distribution with constrained ``.support`` are
31
+ propagated in an unconstrained space, and algorithms are typically rotation
32
+ invariant.::
33
+
34
+ dist = Exponential(rate)
35
+ unconstrained = torch.zeros(100, requires_grad=True)
36
+ sample = biject_to(dist.support)(unconstrained)
37
+ potential_energy = -dist.log_prob(sample).sum()
38
+
39
+ .. note::
40
+
41
+ An example where ``transform_to`` and ``biject_to`` differ is
42
+ ``constraints.simplex``: ``transform_to(constraints.simplex)`` returns a
43
+ :class:`~torch.distributions.transforms.SoftmaxTransform` that simply
44
+ exponentiates and normalizes its inputs; this is a cheap and mostly
45
+ coordinate-wise operation appropriate for algorithms like SVI. In
46
+ contrast, ``biject_to(constraints.simplex)`` returns a
47
+ :class:`~torch.distributions.transforms.StickBreakingTransform` that
48
+ bijects its input down to a one-fewer-dimensional space; this a more
49
+ expensive less numerically stable transform but is needed for algorithms
50
+ like HMC.
51
+
52
+ The ``biject_to`` and ``transform_to`` objects can be extended by user-defined
53
+ constraints and transforms using their ``.register()`` method either as a
54
+ function on singleton constraints::
55
+
56
+ transform_to.register(my_constraint, my_transform)
57
+
58
+ or as a decorator on parameterized constraints::
59
+
60
+ @transform_to.register(MyConstraintClass)
61
+ def my_factory(constraint):
62
+ assert isinstance(constraint, MyConstraintClass)
63
+ return MyTransform(constraint.param1, constraint.param2)
64
+
65
+ You can create your own registry by creating a new :class:`ConstraintRegistry`
66
+ object.
67
+ """
68
+
69
+ from torch.distributions import constraints, transforms
70
+ from torch.types import _Number
71
+
72
+
73
+ __all__ = [
74
+ "ConstraintRegistry",
75
+ "biject_to",
76
+ "transform_to",
77
+ ]
78
+
79
+
80
+ class ConstraintRegistry:
81
+ """
82
+ Registry to link constraints to transforms.
83
+ """
84
+
85
+ def __init__(self):
86
+ self._registry = {}
87
+ super().__init__()
88
+
89
+ def register(self, constraint, factory=None):
90
+ """
91
+ Registers a :class:`~torch.distributions.constraints.Constraint`
92
+ subclass in this registry. Usage::
93
+
94
+ @my_registry.register(MyConstraintClass)
95
+ def construct_transform(constraint):
96
+ assert isinstance(constraint, MyConstraint)
97
+ return MyTransform(constraint.arg_constraints)
98
+
99
+ Args:
100
+ constraint (subclass of :class:`~torch.distributions.constraints.Constraint`):
101
+ A subclass of :class:`~torch.distributions.constraints.Constraint`, or
102
+ a singleton object of the desired class.
103
+ factory (Callable): A callable that inputs a constraint object and returns
104
+ a :class:`~torch.distributions.transforms.Transform` object.
105
+ """
106
+ # Support use as decorator.
107
+ if factory is None:
108
+ return lambda factory: self.register(constraint, factory)
109
+
110
+ # Support calling on singleton instances.
111
+ if isinstance(constraint, constraints.Constraint):
112
+ constraint = type(constraint)
113
+
114
+ if not isinstance(constraint, type) or not issubclass(
115
+ constraint, constraints.Constraint
116
+ ):
117
+ raise TypeError(
118
+ f"Expected constraint to be either a Constraint subclass or instance, but got {constraint}"
119
+ )
120
+
121
+ self._registry[constraint] = factory
122
+ return factory
123
+
124
+ def __call__(self, constraint):
125
+ """
126
+ Looks up a transform to constrained space, given a constraint object.
127
+ Usage::
128
+
129
+ constraint = Normal.arg_constraints["scale"]
130
+ scale = transform_to(constraint)(torch.zeros(1)) # constrained
131
+ u = transform_to(constraint).inv(scale) # unconstrained
132
+
133
+ Args:
134
+ constraint (:class:`~torch.distributions.constraints.Constraint`):
135
+ A constraint object.
136
+
137
+ Returns:
138
+ A :class:`~torch.distributions.transforms.Transform` object.
139
+
140
+ Raises:
141
+ `NotImplementedError` if no transform has been registered.
142
+ """
143
+ # Look up by Constraint subclass.
144
+ try:
145
+ factory = self._registry[type(constraint)]
146
+ except KeyError:
147
+ raise NotImplementedError(
148
+ f"Cannot transform {type(constraint).__name__} constraints"
149
+ ) from None
150
+ return factory(constraint)
151
+
152
+
153
+ biject_to = ConstraintRegistry()
154
+ transform_to = ConstraintRegistry()
155
+
156
+
157
+ ################################################################################
158
+ # Registration Table
159
+ ################################################################################
160
+
161
+
162
+ @biject_to.register(constraints.real)
163
+ @transform_to.register(constraints.real)
164
+ def _transform_to_real(constraint):
165
+ return transforms.identity_transform
166
+
167
+
168
+ @biject_to.register(constraints.independent)
169
+ def _biject_to_independent(constraint):
170
+ base_transform = biject_to(constraint.base_constraint)
171
+ return transforms.IndependentTransform(
172
+ base_transform, constraint.reinterpreted_batch_ndims
173
+ )
174
+
175
+
176
+ @transform_to.register(constraints.independent)
177
+ def _transform_to_independent(constraint):
178
+ base_transform = transform_to(constraint.base_constraint)
179
+ return transforms.IndependentTransform(
180
+ base_transform, constraint.reinterpreted_batch_ndims
181
+ )
182
+
183
+
184
+ @biject_to.register(constraints.positive)
185
+ @biject_to.register(constraints.nonnegative)
186
+ @transform_to.register(constraints.positive)
187
+ @transform_to.register(constraints.nonnegative)
188
+ def _transform_to_positive(constraint):
189
+ return transforms.ExpTransform()
190
+
191
+
192
+ @biject_to.register(constraints.greater_than)
193
+ @biject_to.register(constraints.greater_than_eq)
194
+ @transform_to.register(constraints.greater_than)
195
+ @transform_to.register(constraints.greater_than_eq)
196
+ def _transform_to_greater_than(constraint):
197
+ return transforms.ComposeTransform(
198
+ [
199
+ transforms.ExpTransform(),
200
+ transforms.AffineTransform(constraint.lower_bound, 1),
201
+ ]
202
+ )
203
+
204
+
205
+ @biject_to.register(constraints.less_than)
206
+ @transform_to.register(constraints.less_than)
207
+ def _transform_to_less_than(constraint):
208
+ return transforms.ComposeTransform(
209
+ [
210
+ transforms.ExpTransform(),
211
+ transforms.AffineTransform(constraint.upper_bound, -1),
212
+ ]
213
+ )
214
+
215
+
216
+ @biject_to.register(constraints.interval)
217
+ @biject_to.register(constraints.half_open_interval)
218
+ @transform_to.register(constraints.interval)
219
+ @transform_to.register(constraints.half_open_interval)
220
+ def _transform_to_interval(constraint):
221
+ # Handle the special case of the unit interval.
222
+ lower_is_0 = (
223
+ isinstance(constraint.lower_bound, _Number) and constraint.lower_bound == 0
224
+ )
225
+ upper_is_1 = (
226
+ isinstance(constraint.upper_bound, _Number) and constraint.upper_bound == 1
227
+ )
228
+ if lower_is_0 and upper_is_1:
229
+ return transforms.SigmoidTransform()
230
+
231
+ loc = constraint.lower_bound
232
+ scale = constraint.upper_bound - constraint.lower_bound
233
+ return transforms.ComposeTransform(
234
+ [transforms.SigmoidTransform(), transforms.AffineTransform(loc, scale)]
235
+ )
236
+
237
+
238
+ @biject_to.register(constraints.simplex)
239
+ def _biject_to_simplex(constraint):
240
+ return transforms.StickBreakingTransform()
241
+
242
+
243
+ @transform_to.register(constraints.simplex)
244
+ def _transform_to_simplex(constraint):
245
+ return transforms.SoftmaxTransform()
246
+
247
+
248
+ # TODO define a bijection for LowerCholeskyTransform
249
+ @transform_to.register(constraints.lower_cholesky)
250
+ def _transform_to_lower_cholesky(constraint):
251
+ return transforms.LowerCholeskyTransform()
252
+
253
+
254
+ @transform_to.register(constraints.positive_definite)
255
+ @transform_to.register(constraints.positive_semidefinite)
256
+ def _transform_to_positive_definite(constraint):
257
+ return transforms.PositiveDefiniteTransform()
258
+
259
+
260
+ @biject_to.register(constraints.corr_cholesky)
261
+ @transform_to.register(constraints.corr_cholesky)
262
+ def _transform_to_corr_cholesky(constraint):
263
+ return transforms.CorrCholeskyTransform()
264
+
265
+
266
+ @biject_to.register(constraints.cat)
267
+ def _biject_to_cat(constraint):
268
+ return transforms.CatTransform(
269
+ [biject_to(c) for c in constraint.cseq], constraint.dim, constraint.lengths
270
+ )
271
+
272
+
273
+ @transform_to.register(constraints.cat)
274
+ def _transform_to_cat(constraint):
275
+ return transforms.CatTransform(
276
+ [transform_to(c) for c in constraint.cseq], constraint.dim, constraint.lengths
277
+ )
278
+
279
+
280
+ @biject_to.register(constraints.stack)
281
+ def _biject_to_stack(constraint):
282
+ return transforms.StackTransform(
283
+ [biject_to(c) for c in constraint.cseq], constraint.dim
284
+ )
285
+
286
+
287
+ @transform_to.register(constraints.stack)
288
+ def _transform_to_stack(constraint):
289
+ return transforms.StackTransform(
290
+ [transform_to(c) for c in constraint.cseq], constraint.dim
291
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/constraints.py ADDED
@@ -0,0 +1,738 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ from collections.abc import Callable
4
+ from typing import Any, Optional
5
+
6
+
7
+ r"""
8
+ The following constraints are implemented:
9
+
10
+ - ``constraints.boolean``
11
+ - ``constraints.cat``
12
+ - ``constraints.corr_cholesky``
13
+ - ``constraints.dependent``
14
+ - ``constraints.greater_than(lower_bound)``
15
+ - ``constraints.greater_than_eq(lower_bound)``
16
+ - ``constraints.independent(constraint, reinterpreted_batch_ndims)``
17
+ - ``constraints.integer_interval(lower_bound, upper_bound)``
18
+ - ``constraints.interval(lower_bound, upper_bound)``
19
+ - ``constraints.less_than(upper_bound)``
20
+ - ``constraints.lower_cholesky``
21
+ - ``constraints.lower_triangular``
22
+ - ``constraints.MixtureSameFamilyConstraint(base_constraint)``
23
+ - ``constraints.multinomial``
24
+ - ``constraints.nonnegative``
25
+ - ``constraints.nonnegative_integer``
26
+ - ``constraints.one_hot``
27
+ - ``constraints.positive_integer``
28
+ - ``constraints.positive``
29
+ - ``constraints.positive_semidefinite``
30
+ - ``constraints.positive_definite``
31
+ - ``constraints.real_vector``
32
+ - ``constraints.real``
33
+ - ``constraints.simplex``
34
+ - ``constraints.symmetric``
35
+ - ``constraints.stack``
36
+ - ``constraints.square``
37
+ - ``constraints.symmetric``
38
+ - ``constraints.unit_interval``
39
+ """
40
+
41
+ import torch
42
+
43
+
44
+ __all__ = [
45
+ "Constraint",
46
+ "boolean",
47
+ "cat",
48
+ "corr_cholesky",
49
+ "dependent",
50
+ "dependent_property",
51
+ "greater_than",
52
+ "greater_than_eq",
53
+ "independent",
54
+ "integer_interval",
55
+ "interval",
56
+ "half_open_interval",
57
+ "is_dependent",
58
+ "less_than",
59
+ "lower_cholesky",
60
+ "lower_triangular",
61
+ "MixtureSameFamilyConstraint",
62
+ "multinomial",
63
+ "nonnegative",
64
+ "nonnegative_integer",
65
+ "one_hot",
66
+ "positive",
67
+ "positive_semidefinite",
68
+ "positive_definite",
69
+ "positive_integer",
70
+ "real",
71
+ "real_vector",
72
+ "simplex",
73
+ "square",
74
+ "stack",
75
+ "symmetric",
76
+ "unit_interval",
77
+ ]
78
+
79
+
80
+ class Constraint:
81
+ """
82
+ Abstract base class for constraints.
83
+
84
+ A constraint object represents a region over which a variable is valid,
85
+ e.g. within which a variable can be optimized.
86
+
87
+ Attributes:
88
+ is_discrete (bool): Whether constrained space is discrete.
89
+ Defaults to False.
90
+ event_dim (int): Number of rightmost dimensions that together define
91
+ an event. The :meth:`check` method will remove this many dimensions
92
+ when computing validity.
93
+ """
94
+
95
+ is_discrete = False # Default to continuous.
96
+ event_dim = 0 # Default to univariate.
97
+
98
+ def check(self, value):
99
+ """
100
+ Returns a byte tensor of ``sample_shape + batch_shape`` indicating
101
+ whether each event in value satisfies this constraint.
102
+ """
103
+ raise NotImplementedError
104
+
105
+ def __repr__(self):
106
+ return self.__class__.__name__[1:] + "()"
107
+
108
+
109
+ class _Dependent(Constraint):
110
+ """
111
+ Placeholder for variables whose support depends on other variables.
112
+ These variables obey no simple coordinate-wise constraints.
113
+
114
+ Args:
115
+ is_discrete (bool): Optional value of ``.is_discrete`` in case this
116
+ can be computed statically. If not provided, access to the
117
+ ``.is_discrete`` attribute will raise a NotImplementedError.
118
+ event_dim (int): Optional value of ``.event_dim`` in case this
119
+ can be computed statically. If not provided, access to the
120
+ ``.event_dim`` attribute will raise a NotImplementedError.
121
+ """
122
+
123
+ def __init__(self, *, is_discrete=NotImplemented, event_dim=NotImplemented):
124
+ self._is_discrete = is_discrete
125
+ self._event_dim = event_dim
126
+ super().__init__()
127
+
128
+ @property
129
+ def is_discrete(self) -> bool: # type: ignore[override]
130
+ if self._is_discrete is NotImplemented:
131
+ raise NotImplementedError(".is_discrete cannot be determined statically")
132
+ return self._is_discrete
133
+
134
+ @property
135
+ def event_dim(self) -> int: # type: ignore[override]
136
+ if self._event_dim is NotImplemented:
137
+ raise NotImplementedError(".event_dim cannot be determined statically")
138
+ return self._event_dim
139
+
140
+ def __call__(self, *, is_discrete=NotImplemented, event_dim=NotImplemented):
141
+ """
142
+ Support for syntax to customize static attributes::
143
+
144
+ constraints.dependent(is_discrete=True, event_dim=1)
145
+ """
146
+ if is_discrete is NotImplemented:
147
+ is_discrete = self._is_discrete
148
+ if event_dim is NotImplemented:
149
+ event_dim = self._event_dim
150
+ return _Dependent(is_discrete=is_discrete, event_dim=event_dim)
151
+
152
+ def check(self, x):
153
+ raise ValueError("Cannot determine validity of dependent constraint")
154
+
155
+
156
+ def is_dependent(constraint):
157
+ """
158
+ Checks if ``constraint`` is a ``_Dependent`` object.
159
+
160
+ Args:
161
+ constraint : A ``Constraint`` object.
162
+
163
+ Returns:
164
+ ``bool``: True if ``constraint`` can be refined to the type ``_Dependent``, False otherwise.
165
+
166
+ Examples:
167
+ >>> import torch
168
+ >>> from torch.distributions import Bernoulli
169
+ >>> from torch.distributions.constraints import is_dependent
170
+
171
+ >>> dist = Bernoulli(probs=torch.tensor([0.6], requires_grad=True))
172
+ >>> constraint1 = dist.arg_constraints["probs"]
173
+ >>> constraint2 = dist.arg_constraints["logits"]
174
+
175
+ >>> for constraint in [constraint1, constraint2]:
176
+ >>> if is_dependent(constraint):
177
+ >>> continue
178
+ """
179
+ return isinstance(constraint, _Dependent)
180
+
181
+
182
+ class _DependentProperty(property, _Dependent):
183
+ """
184
+ Decorator that extends @property to act like a `Dependent` constraint when
185
+ called on a class and act like a property when called on an object.
186
+
187
+ Example::
188
+
189
+ class Uniform(Distribution):
190
+ def __init__(self, low, high):
191
+ self.low = low
192
+ self.high = high
193
+
194
+ @constraints.dependent_property(is_discrete=False, event_dim=0)
195
+ def support(self):
196
+ return constraints.interval(self.low, self.high)
197
+
198
+ Args:
199
+ fn (Callable): The function to be decorated.
200
+ is_discrete (bool): Optional value of ``.is_discrete`` in case this
201
+ can be computed statically. If not provided, access to the
202
+ ``.is_discrete`` attribute will raise a NotImplementedError.
203
+ event_dim (int): Optional value of ``.event_dim`` in case this
204
+ can be computed statically. If not provided, access to the
205
+ ``.event_dim`` attribute will raise a NotImplementedError.
206
+ """
207
+
208
+ def __init__(
209
+ self,
210
+ fn: Optional[Callable[..., Any]] = None,
211
+ *,
212
+ is_discrete: Optional[bool] = NotImplemented,
213
+ event_dim: Optional[int] = NotImplemented,
214
+ ) -> None:
215
+ super().__init__(fn)
216
+ self._is_discrete = is_discrete
217
+ self._event_dim = event_dim
218
+
219
+ def __call__(self, fn: Callable[..., Any]) -> "_DependentProperty": # type: ignore[override]
220
+ """
221
+ Support for syntax to customize static attributes::
222
+
223
+ @constraints.dependent_property(is_discrete=True, event_dim=1)
224
+ def support(self): ...
225
+ """
226
+ return _DependentProperty(
227
+ fn, is_discrete=self._is_discrete, event_dim=self._event_dim
228
+ )
229
+
230
+
231
+ class _IndependentConstraint(Constraint):
232
+ """
233
+ Wraps a constraint by aggregating over ``reinterpreted_batch_ndims``-many
234
+ dims in :meth:`check`, so that an event is valid only if all its
235
+ independent entries are valid.
236
+ """
237
+
238
+ def __init__(self, base_constraint, reinterpreted_batch_ndims):
239
+ assert isinstance(base_constraint, Constraint)
240
+ assert isinstance(reinterpreted_batch_ndims, int)
241
+ assert reinterpreted_batch_ndims >= 0
242
+ self.base_constraint = base_constraint
243
+ self.reinterpreted_batch_ndims = reinterpreted_batch_ndims
244
+ super().__init__()
245
+
246
+ @property
247
+ def is_discrete(self) -> bool: # type: ignore[override]
248
+ return self.base_constraint.is_discrete
249
+
250
+ @property
251
+ def event_dim(self) -> int: # type: ignore[override]
252
+ return self.base_constraint.event_dim + self.reinterpreted_batch_ndims
253
+
254
+ def check(self, value):
255
+ result = self.base_constraint.check(value)
256
+ if result.dim() < self.reinterpreted_batch_ndims:
257
+ expected = self.base_constraint.event_dim + self.reinterpreted_batch_ndims
258
+ raise ValueError(
259
+ f"Expected value.dim() >= {expected} but got {value.dim()}"
260
+ )
261
+ result = result.reshape(
262
+ result.shape[: result.dim() - self.reinterpreted_batch_ndims] + (-1,)
263
+ )
264
+ result = result.all(-1)
265
+ return result
266
+
267
+ def __repr__(self):
268
+ return f"{self.__class__.__name__[1:]}({repr(self.base_constraint)}, {self.reinterpreted_batch_ndims})"
269
+
270
+
271
+ class MixtureSameFamilyConstraint(Constraint):
272
+ """
273
+ Constraint for the :class:`~torch.distribution.MixtureSameFamily`
274
+ distribution that adds back the rightmost batch dimension before
275
+ performing the validity check with the component distribution
276
+ constraint.
277
+
278
+ Args:
279
+ base_constraint: The ``Constraint`` object of
280
+ the component distribution of
281
+ the :class:`~torch.distribution.MixtureSameFamily` distribution.
282
+ """
283
+
284
+ def __init__(self, base_constraint):
285
+ assert isinstance(base_constraint, Constraint)
286
+ self.base_constraint = base_constraint
287
+ super().__init__()
288
+
289
+ @property
290
+ def is_discrete(self) -> bool: # type: ignore[override]
291
+ return self.base_constraint.is_discrete
292
+
293
+ @property
294
+ def event_dim(self) -> int: # type: ignore[override]
295
+ return self.base_constraint.event_dim
296
+
297
+ def check(self, value):
298
+ """
299
+ Check validity of ``value`` as a possible outcome of sampling
300
+ the :class:`~torch.distribution.MixtureSameFamily` distribution.
301
+ """
302
+ unsqueezed_value = value.unsqueeze(-1 - self.event_dim)
303
+ result = self.base_constraint.check(unsqueezed_value)
304
+ if value.dim() < self.event_dim:
305
+ raise ValueError(
306
+ f"Expected value.dim() >= {self.event_dim} but got {value.dim()}"
307
+ )
308
+ num_dim_to_keep = value.dim() - self.event_dim
309
+ result = result.reshape(result.shape[:num_dim_to_keep] + (-1,))
310
+ result = result.all(-1)
311
+ return result
312
+
313
+ def __repr__(self):
314
+ return f"{self.__class__.__name__}({repr(self.base_constraint)})"
315
+
316
+
317
+ class _Boolean(Constraint):
318
+ """
319
+ Constrain to the two values `{0, 1}`.
320
+ """
321
+
322
+ is_discrete = True
323
+
324
+ def check(self, value):
325
+ return (value == 0) | (value == 1)
326
+
327
+
328
+ class _OneHot(Constraint):
329
+ """
330
+ Constrain to one-hot vectors.
331
+ """
332
+
333
+ is_discrete = True
334
+ event_dim = 1
335
+
336
+ def check(self, value):
337
+ is_boolean = (value == 0) | (value == 1)
338
+ is_normalized = value.sum(-1).eq(1)
339
+ return is_boolean.all(-1) & is_normalized
340
+
341
+
342
+ class _IntegerInterval(Constraint):
343
+ """
344
+ Constrain to an integer interval `[lower_bound, upper_bound]`.
345
+ """
346
+
347
+ is_discrete = True
348
+
349
+ def __init__(self, lower_bound, upper_bound):
350
+ self.lower_bound = lower_bound
351
+ self.upper_bound = upper_bound
352
+ super().__init__()
353
+
354
+ def check(self, value):
355
+ return (
356
+ (value % 1 == 0) & (self.lower_bound <= value) & (value <= self.upper_bound)
357
+ )
358
+
359
+ def __repr__(self):
360
+ fmt_string = self.__class__.__name__[1:]
361
+ fmt_string += (
362
+ f"(lower_bound={self.lower_bound}, upper_bound={self.upper_bound})"
363
+ )
364
+ return fmt_string
365
+
366
+
367
+ class _IntegerLessThan(Constraint):
368
+ """
369
+ Constrain to an integer interval `(-inf, upper_bound]`.
370
+ """
371
+
372
+ is_discrete = True
373
+
374
+ def __init__(self, upper_bound):
375
+ self.upper_bound = upper_bound
376
+ super().__init__()
377
+
378
+ def check(self, value):
379
+ return (value % 1 == 0) & (value <= self.upper_bound)
380
+
381
+ def __repr__(self):
382
+ fmt_string = self.__class__.__name__[1:]
383
+ fmt_string += f"(upper_bound={self.upper_bound})"
384
+ return fmt_string
385
+
386
+
387
+ class _IntegerGreaterThan(Constraint):
388
+ """
389
+ Constrain to an integer interval `[lower_bound, inf)`.
390
+ """
391
+
392
+ is_discrete = True
393
+
394
+ def __init__(self, lower_bound):
395
+ self.lower_bound = lower_bound
396
+ super().__init__()
397
+
398
+ def check(self, value):
399
+ return (value % 1 == 0) & (value >= self.lower_bound)
400
+
401
+ def __repr__(self):
402
+ fmt_string = self.__class__.__name__[1:]
403
+ fmt_string += f"(lower_bound={self.lower_bound})"
404
+ return fmt_string
405
+
406
+
407
+ class _Real(Constraint):
408
+ """
409
+ Trivially constrain to the extended real line `[-inf, inf]`.
410
+ """
411
+
412
+ def check(self, value):
413
+ return value == value # False for NANs.
414
+
415
+
416
+ class _GreaterThan(Constraint):
417
+ """
418
+ Constrain to a real half line `(lower_bound, inf]`.
419
+ """
420
+
421
+ def __init__(self, lower_bound):
422
+ self.lower_bound = lower_bound
423
+ super().__init__()
424
+
425
+ def check(self, value):
426
+ return self.lower_bound < value
427
+
428
+ def __repr__(self):
429
+ fmt_string = self.__class__.__name__[1:]
430
+ fmt_string += f"(lower_bound={self.lower_bound})"
431
+ return fmt_string
432
+
433
+
434
+ class _GreaterThanEq(Constraint):
435
+ """
436
+ Constrain to a real half line `[lower_bound, inf)`.
437
+ """
438
+
439
+ def __init__(self, lower_bound):
440
+ self.lower_bound = lower_bound
441
+ super().__init__()
442
+
443
+ def check(self, value):
444
+ return self.lower_bound <= value
445
+
446
+ def __repr__(self):
447
+ fmt_string = self.__class__.__name__[1:]
448
+ fmt_string += f"(lower_bound={self.lower_bound})"
449
+ return fmt_string
450
+
451
+
452
+ class _LessThan(Constraint):
453
+ """
454
+ Constrain to a real half line `[-inf, upper_bound)`.
455
+ """
456
+
457
+ def __init__(self, upper_bound):
458
+ self.upper_bound = upper_bound
459
+ super().__init__()
460
+
461
+ def check(self, value):
462
+ return value < self.upper_bound
463
+
464
+ def __repr__(self):
465
+ fmt_string = self.__class__.__name__[1:]
466
+ fmt_string += f"(upper_bound={self.upper_bound})"
467
+ return fmt_string
468
+
469
+
470
+ class _Interval(Constraint):
471
+ """
472
+ Constrain to a real interval `[lower_bound, upper_bound]`.
473
+ """
474
+
475
+ def __init__(self, lower_bound, upper_bound):
476
+ self.lower_bound = lower_bound
477
+ self.upper_bound = upper_bound
478
+ super().__init__()
479
+
480
+ def check(self, value):
481
+ return (self.lower_bound <= value) & (value <= self.upper_bound)
482
+
483
+ def __repr__(self):
484
+ fmt_string = self.__class__.__name__[1:]
485
+ fmt_string += (
486
+ f"(lower_bound={self.lower_bound}, upper_bound={self.upper_bound})"
487
+ )
488
+ return fmt_string
489
+
490
+
491
+ class _HalfOpenInterval(Constraint):
492
+ """
493
+ Constrain to a real interval `[lower_bound, upper_bound)`.
494
+ """
495
+
496
+ def __init__(self, lower_bound, upper_bound):
497
+ self.lower_bound = lower_bound
498
+ self.upper_bound = upper_bound
499
+ super().__init__()
500
+
501
+ def check(self, value):
502
+ return (self.lower_bound <= value) & (value < self.upper_bound)
503
+
504
+ def __repr__(self):
505
+ fmt_string = self.__class__.__name__[1:]
506
+ fmt_string += (
507
+ f"(lower_bound={self.lower_bound}, upper_bound={self.upper_bound})"
508
+ )
509
+ return fmt_string
510
+
511
+
512
+ class _Simplex(Constraint):
513
+ """
514
+ Constrain to the unit simplex in the innermost (rightmost) dimension.
515
+ Specifically: `x >= 0` and `x.sum(-1) == 1`.
516
+ """
517
+
518
+ event_dim = 1
519
+
520
+ def check(self, value):
521
+ return torch.all(value >= 0, dim=-1) & ((value.sum(-1) - 1).abs() < 1e-6)
522
+
523
+
524
+ class _Multinomial(Constraint):
525
+ """
526
+ Constrain to nonnegative integer values summing to at most an upper bound.
527
+
528
+ Note due to limitations of the Multinomial distribution, this currently
529
+ checks the weaker condition ``value.sum(-1) <= upper_bound``. In the future
530
+ this may be strengthened to ``value.sum(-1) == upper_bound``.
531
+ """
532
+
533
+ is_discrete = True
534
+ event_dim = 1
535
+
536
+ def __init__(self, upper_bound):
537
+ self.upper_bound = upper_bound
538
+
539
+ def check(self, x):
540
+ return (x >= 0).all(dim=-1) & (x.sum(dim=-1) <= self.upper_bound)
541
+
542
+
543
+ class _LowerTriangular(Constraint):
544
+ """
545
+ Constrain to lower-triangular square matrices.
546
+ """
547
+
548
+ event_dim = 2
549
+
550
+ def check(self, value):
551
+ value_tril = value.tril()
552
+ return (value_tril == value).view(value.shape[:-2] + (-1,)).min(-1)[0]
553
+
554
+
555
+ class _LowerCholesky(Constraint):
556
+ """
557
+ Constrain to lower-triangular square matrices with positive diagonals.
558
+ """
559
+
560
+ event_dim = 2
561
+
562
+ def check(self, value):
563
+ value_tril = value.tril()
564
+ lower_triangular = (
565
+ (value_tril == value).view(value.shape[:-2] + (-1,)).min(-1)[0]
566
+ )
567
+
568
+ positive_diagonal = (value.diagonal(dim1=-2, dim2=-1) > 0).min(-1)[0]
569
+ return lower_triangular & positive_diagonal
570
+
571
+
572
+ class _CorrCholesky(Constraint):
573
+ """
574
+ Constrain to lower-triangular square matrices with positive diagonals and each
575
+ row vector being of unit length.
576
+ """
577
+
578
+ event_dim = 2
579
+
580
+ def check(self, value):
581
+ tol = (
582
+ torch.finfo(value.dtype).eps * value.size(-1) * 10
583
+ ) # 10 is an adjustable fudge factor
584
+ row_norm = torch.linalg.norm(value.detach(), dim=-1)
585
+ unit_row_norm = (row_norm - 1.0).abs().le(tol).all(dim=-1)
586
+ return _LowerCholesky().check(value) & unit_row_norm
587
+
588
+
589
+ class _Square(Constraint):
590
+ """
591
+ Constrain to square matrices.
592
+ """
593
+
594
+ event_dim = 2
595
+
596
+ def check(self, value):
597
+ return torch.full(
598
+ size=value.shape[:-2],
599
+ fill_value=(value.shape[-2] == value.shape[-1]),
600
+ dtype=torch.bool,
601
+ device=value.device,
602
+ )
603
+
604
+
605
+ class _Symmetric(_Square):
606
+ """
607
+ Constrain to Symmetric square matrices.
608
+ """
609
+
610
+ def check(self, value):
611
+ square_check = super().check(value)
612
+ if not square_check.all():
613
+ return square_check
614
+ return torch.isclose(value, value.mT, atol=1e-6).all(-2).all(-1)
615
+
616
+
617
+ class _PositiveSemidefinite(_Symmetric):
618
+ """
619
+ Constrain to positive-semidefinite matrices.
620
+ """
621
+
622
+ def check(self, value):
623
+ sym_check = super().check(value)
624
+ if not sym_check.all():
625
+ return sym_check
626
+ return torch.linalg.eigvalsh(value).ge(0).all(-1)
627
+
628
+
629
+ class _PositiveDefinite(_Symmetric):
630
+ """
631
+ Constrain to positive-definite matrices.
632
+ """
633
+
634
+ def check(self, value):
635
+ sym_check = super().check(value)
636
+ if not sym_check.all():
637
+ return sym_check
638
+ return torch.linalg.cholesky_ex(value).info.eq(0)
639
+
640
+
641
+ class _Cat(Constraint):
642
+ """
643
+ Constraint functor that applies a sequence of constraints
644
+ `cseq` at the submatrices at dimension `dim`,
645
+ each of size `lengths[dim]`, in a way compatible with :func:`torch.cat`.
646
+ """
647
+
648
+ def __init__(self, cseq, dim=0, lengths=None):
649
+ assert all(isinstance(c, Constraint) for c in cseq)
650
+ self.cseq = list(cseq)
651
+ if lengths is None:
652
+ lengths = [1] * len(self.cseq)
653
+ self.lengths = list(lengths)
654
+ assert len(self.lengths) == len(self.cseq)
655
+ self.dim = dim
656
+ super().__init__()
657
+
658
+ @property
659
+ def is_discrete(self) -> bool: # type: ignore[override]
660
+ return any(c.is_discrete for c in self.cseq)
661
+
662
+ @property
663
+ def event_dim(self) -> int: # type: ignore[override]
664
+ return max(c.event_dim for c in self.cseq)
665
+
666
+ def check(self, value):
667
+ assert -value.dim() <= self.dim < value.dim()
668
+ checks = []
669
+ start = 0
670
+ for constr, length in zip(self.cseq, self.lengths):
671
+ v = value.narrow(self.dim, start, length)
672
+ checks.append(constr.check(v))
673
+ start = start + length # avoid += for jit compat
674
+ return torch.cat(checks, self.dim)
675
+
676
+
677
+ class _Stack(Constraint):
678
+ """
679
+ Constraint functor that applies a sequence of constraints
680
+ `cseq` at the submatrices at dimension `dim`,
681
+ in a way compatible with :func:`torch.stack`.
682
+ """
683
+
684
+ def __init__(self, cseq, dim=0):
685
+ assert all(isinstance(c, Constraint) for c in cseq)
686
+ self.cseq = list(cseq)
687
+ self.dim = dim
688
+ super().__init__()
689
+
690
+ @property
691
+ def is_discrete(self) -> bool: # type: ignore[override]
692
+ return any(c.is_discrete for c in self.cseq)
693
+
694
+ @property
695
+ def event_dim(self) -> int: # type: ignore[override]
696
+ dim = max(c.event_dim for c in self.cseq)
697
+ if self.dim + dim < 0:
698
+ dim += 1
699
+ return dim
700
+
701
+ def check(self, value):
702
+ assert -value.dim() <= self.dim < value.dim()
703
+ vs = [value.select(self.dim, i) for i in range(value.size(self.dim))]
704
+ return torch.stack(
705
+ [constr.check(v) for v, constr in zip(vs, self.cseq)], self.dim
706
+ )
707
+
708
+
709
+ # Public interface.
710
+ dependent = _Dependent()
711
+ dependent_property = _DependentProperty
712
+ independent = _IndependentConstraint
713
+ boolean = _Boolean()
714
+ one_hot = _OneHot()
715
+ nonnegative_integer = _IntegerGreaterThan(0)
716
+ positive_integer = _IntegerGreaterThan(1)
717
+ integer_interval = _IntegerInterval
718
+ real = _Real()
719
+ real_vector = independent(real, 1)
720
+ positive = _GreaterThan(0.0)
721
+ nonnegative = _GreaterThanEq(0.0)
722
+ greater_than = _GreaterThan
723
+ greater_than_eq = _GreaterThanEq
724
+ less_than = _LessThan
725
+ multinomial = _Multinomial
726
+ unit_interval = _Interval(0.0, 1.0)
727
+ interval = _Interval
728
+ half_open_interval = _HalfOpenInterval
729
+ simplex = _Simplex()
730
+ lower_triangular = _LowerTriangular()
731
+ lower_cholesky = _LowerCholesky()
732
+ corr_cholesky = _CorrCholesky()
733
+ square = _Square()
734
+ symmetric = _Symmetric()
735
+ positive_semidefinite = _PositiveSemidefinite()
736
+ positive_definite = _PositiveDefinite()
737
+ cat = _Cat
738
+ stack = _Stack
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/continuous_bernoulli.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import math
3
+ from typing import Optional, Union
4
+
5
+ import torch
6
+ from torch import Tensor
7
+ from torch.distributions import constraints
8
+ from torch.distributions.exp_family import ExponentialFamily
9
+ from torch.distributions.utils import (
10
+ broadcast_all,
11
+ clamp_probs,
12
+ lazy_property,
13
+ logits_to_probs,
14
+ probs_to_logits,
15
+ )
16
+ from torch.nn.functional import binary_cross_entropy_with_logits
17
+ from torch.types import _Number, _size, Number
18
+
19
+
20
+ __all__ = ["ContinuousBernoulli"]
21
+
22
+
23
+ class ContinuousBernoulli(ExponentialFamily):
24
+ r"""
25
+ Creates a continuous Bernoulli distribution parameterized by :attr:`probs`
26
+ or :attr:`logits` (but not both).
27
+
28
+ The distribution is supported in [0, 1] and parameterized by 'probs' (in
29
+ (0,1)) or 'logits' (real-valued). Note that, unlike the Bernoulli, 'probs'
30
+ does not correspond to a probability and 'logits' does not correspond to
31
+ log-odds, but the same names are used due to the similarity with the
32
+ Bernoulli. See [1] for more details.
33
+
34
+ Example::
35
+
36
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
37
+ >>> m = ContinuousBernoulli(torch.tensor([0.3]))
38
+ >>> m.sample()
39
+ tensor([ 0.2538])
40
+
41
+ Args:
42
+ probs (Number, Tensor): (0,1) valued parameters
43
+ logits (Number, Tensor): real valued parameters whose sigmoid matches 'probs'
44
+
45
+ [1] The continuous Bernoulli: fixing a pervasive error in variational
46
+ autoencoders, Loaiza-Ganem G and Cunningham JP, NeurIPS 2019.
47
+ https://arxiv.org/abs/1907.06845
48
+ """
49
+
50
+ # pyrefly: ignore [bad-override]
51
+ arg_constraints = {"probs": constraints.unit_interval, "logits": constraints.real}
52
+ support = constraints.unit_interval
53
+ _mean_carrier_measure = 0
54
+ has_rsample = True
55
+
56
+ def __init__(
57
+ self,
58
+ probs: Optional[Union[Tensor, Number]] = None,
59
+ logits: Optional[Union[Tensor, Number]] = None,
60
+ lims: tuple[float, float] = (0.499, 0.501),
61
+ validate_args: Optional[bool] = None,
62
+ ) -> None:
63
+ if (probs is None) == (logits is None):
64
+ raise ValueError(
65
+ "Either `probs` or `logits` must be specified, but not both."
66
+ )
67
+ if probs is not None:
68
+ is_scalar = isinstance(probs, _Number)
69
+ # pyrefly: ignore [read-only]
70
+ (self.probs,) = broadcast_all(probs)
71
+ # validate 'probs' here if necessary as it is later clamped for numerical stability
72
+ # close to 0 and 1, later on; otherwise the clamped 'probs' would always pass
73
+ if validate_args is not None:
74
+ if not self.arg_constraints["probs"].check(self.probs).all():
75
+ raise ValueError("The parameter probs has invalid values")
76
+ # pyrefly: ignore [read-only]
77
+ self.probs = clamp_probs(self.probs)
78
+ else:
79
+ assert logits is not None # helps mypy
80
+ is_scalar = isinstance(logits, _Number)
81
+ # pyrefly: ignore [read-only]
82
+ (self.logits,) = broadcast_all(logits)
83
+ self._param = self.probs if probs is not None else self.logits
84
+ if is_scalar:
85
+ batch_shape = torch.Size()
86
+ else:
87
+ batch_shape = self._param.size()
88
+ self._lims = lims
89
+ super().__init__(batch_shape, validate_args=validate_args)
90
+
91
+ def expand(self, batch_shape, _instance=None):
92
+ new = self._get_checked_instance(ContinuousBernoulli, _instance)
93
+ new._lims = self._lims
94
+ batch_shape = torch.Size(batch_shape)
95
+ if "probs" in self.__dict__:
96
+ new.probs = self.probs.expand(batch_shape)
97
+ new._param = new.probs
98
+ if "logits" in self.__dict__:
99
+ new.logits = self.logits.expand(batch_shape)
100
+ new._param = new.logits
101
+ super(ContinuousBernoulli, new).__init__(batch_shape, validate_args=False)
102
+ new._validate_args = self._validate_args
103
+ return new
104
+
105
+ def _new(self, *args, **kwargs):
106
+ return self._param.new(*args, **kwargs)
107
+
108
+ def _outside_unstable_region(self):
109
+ return torch.max(
110
+ torch.le(self.probs, self._lims[0]), torch.gt(self.probs, self._lims[1])
111
+ )
112
+
113
+ def _cut_probs(self):
114
+ return torch.where(
115
+ self._outside_unstable_region(),
116
+ self.probs,
117
+ self._lims[0] * torch.ones_like(self.probs),
118
+ )
119
+
120
+ def _cont_bern_log_norm(self):
121
+ """computes the log normalizing constant as a function of the 'probs' parameter"""
122
+ cut_probs = self._cut_probs()
123
+ cut_probs_below_half = torch.where(
124
+ torch.le(cut_probs, 0.5), cut_probs, torch.zeros_like(cut_probs)
125
+ )
126
+ cut_probs_above_half = torch.where(
127
+ torch.ge(cut_probs, 0.5), cut_probs, torch.ones_like(cut_probs)
128
+ )
129
+ log_norm = torch.log(
130
+ torch.abs(torch.log1p(-cut_probs) - torch.log(cut_probs))
131
+ ) - torch.where(
132
+ torch.le(cut_probs, 0.5),
133
+ torch.log1p(-2.0 * cut_probs_below_half),
134
+ torch.log(2.0 * cut_probs_above_half - 1.0),
135
+ )
136
+ x = torch.pow(self.probs - 0.5, 2)
137
+ taylor = math.log(2.0) + (4.0 / 3.0 + 104.0 / 45.0 * x) * x
138
+ return torch.where(self._outside_unstable_region(), log_norm, taylor)
139
+
140
+ @property
141
+ def mean(self) -> Tensor:
142
+ cut_probs = self._cut_probs()
143
+ mus = cut_probs / (2.0 * cut_probs - 1.0) + 1.0 / (
144
+ torch.log1p(-cut_probs) - torch.log(cut_probs)
145
+ )
146
+ x = self.probs - 0.5
147
+ taylor = 0.5 + (1.0 / 3.0 + 16.0 / 45.0 * torch.pow(x, 2)) * x
148
+ return torch.where(self._outside_unstable_region(), mus, taylor)
149
+
150
+ @property
151
+ def stddev(self) -> Tensor:
152
+ return torch.sqrt(self.variance)
153
+
154
+ @property
155
+ def variance(self) -> Tensor:
156
+ cut_probs = self._cut_probs()
157
+ vars = cut_probs * (cut_probs - 1.0) / torch.pow(
158
+ 1.0 - 2.0 * cut_probs, 2
159
+ ) + 1.0 / torch.pow(torch.log1p(-cut_probs) - torch.log(cut_probs), 2)
160
+ x = torch.pow(self.probs - 0.5, 2)
161
+ taylor = 1.0 / 12.0 - (1.0 / 15.0 - 128.0 / 945.0 * x) * x
162
+ return torch.where(self._outside_unstable_region(), vars, taylor)
163
+
164
+ @lazy_property
165
+ def logits(self) -> Tensor:
166
+ return probs_to_logits(self.probs, is_binary=True)
167
+
168
+ @lazy_property
169
+ def probs(self) -> Tensor:
170
+ return clamp_probs(logits_to_probs(self.logits, is_binary=True))
171
+
172
+ @property
173
+ def param_shape(self) -> torch.Size:
174
+ return self._param.size()
175
+
176
+ def sample(self, sample_shape=torch.Size()):
177
+ shape = self._extended_shape(sample_shape)
178
+ u = torch.rand(shape, dtype=self.probs.dtype, device=self.probs.device)
179
+ with torch.no_grad():
180
+ return self.icdf(u)
181
+
182
+ def rsample(self, sample_shape: _size = torch.Size()) -> Tensor:
183
+ shape = self._extended_shape(sample_shape)
184
+ u = torch.rand(shape, dtype=self.probs.dtype, device=self.probs.device)
185
+ return self.icdf(u)
186
+
187
+ def log_prob(self, value):
188
+ if self._validate_args:
189
+ self._validate_sample(value)
190
+ logits, value = broadcast_all(self.logits, value)
191
+ return (
192
+ -binary_cross_entropy_with_logits(logits, value, reduction="none")
193
+ + self._cont_bern_log_norm()
194
+ )
195
+
196
+ def cdf(self, value):
197
+ if self._validate_args:
198
+ self._validate_sample(value)
199
+ cut_probs = self._cut_probs()
200
+ cdfs = (
201
+ torch.pow(cut_probs, value) * torch.pow(1.0 - cut_probs, 1.0 - value)
202
+ + cut_probs
203
+ - 1.0
204
+ ) / (2.0 * cut_probs - 1.0)
205
+ unbounded_cdfs = torch.where(self._outside_unstable_region(), cdfs, value)
206
+ return torch.where(
207
+ torch.le(value, 0.0),
208
+ torch.zeros_like(value),
209
+ torch.where(torch.ge(value, 1.0), torch.ones_like(value), unbounded_cdfs),
210
+ )
211
+
212
+ def icdf(self, value):
213
+ cut_probs = self._cut_probs()
214
+ return torch.where(
215
+ self._outside_unstable_region(),
216
+ (
217
+ torch.log1p(-cut_probs + value * (2.0 * cut_probs - 1.0))
218
+ - torch.log1p(-cut_probs)
219
+ )
220
+ / (torch.log(cut_probs) - torch.log1p(-cut_probs)),
221
+ value,
222
+ )
223
+
224
+ def entropy(self):
225
+ log_probs0 = torch.log1p(-self.probs)
226
+ log_probs1 = torch.log(self.probs)
227
+ return (
228
+ self.mean * (log_probs0 - log_probs1)
229
+ - self._cont_bern_log_norm()
230
+ - log_probs0
231
+ )
232
+
233
+ @property
234
+ def _natural_params(self) -> tuple[Tensor]:
235
+ return (self.logits,)
236
+
237
+ # pyrefly: ignore [bad-override]
238
+ def _log_normalizer(self, x):
239
+ """computes the log normalizing constant as a function of the natural parameter"""
240
+ out_unst_reg = torch.max(
241
+ torch.le(x, self._lims[0] - 0.5), torch.gt(x, self._lims[1] - 0.5)
242
+ )
243
+ cut_nat_params = torch.where(
244
+ out_unst_reg, x, (self._lims[0] - 0.5) * torch.ones_like(x)
245
+ )
246
+ log_norm = torch.log(
247
+ torch.abs(torch.special.expm1(cut_nat_params))
248
+ ) - torch.log(torch.abs(cut_nat_params))
249
+ taylor = 0.5 * x + torch.pow(x, 2) / 24.0 - torch.pow(x, 4) / 2880.0
250
+ return torch.where(out_unst_reg, log_norm, taylor)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/distributions/dirichlet.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Optional
3
+
4
+ import torch
5
+ from torch import Tensor
6
+ from torch.autograd import Function
7
+ from torch.autograd.function import once_differentiable
8
+ from torch.distributions import constraints
9
+ from torch.distributions.exp_family import ExponentialFamily
10
+ from torch.types import _size
11
+
12
+
13
+ __all__ = ["Dirichlet"]
14
+
15
+
16
+ # This helper is exposed for testing.
17
+ def _Dirichlet_backward(x, concentration, grad_output):
18
+ total = concentration.sum(-1, True).expand_as(concentration)
19
+ grad = torch._dirichlet_grad(x, concentration, total)
20
+ return grad * (grad_output - (x * grad_output).sum(-1, True))
21
+
22
+
23
+ class _Dirichlet(Function):
24
+ @staticmethod
25
+ # pyrefly: ignore [bad-override]
26
+ def forward(ctx, concentration):
27
+ x = torch._sample_dirichlet(concentration)
28
+ ctx.save_for_backward(x, concentration)
29
+ return x
30
+
31
+ @staticmethod
32
+ @once_differentiable
33
+ # pyrefly: ignore [bad-override]
34
+ def backward(ctx, grad_output):
35
+ x, concentration = ctx.saved_tensors
36
+ return _Dirichlet_backward(x, concentration, grad_output)
37
+
38
+
39
+ class Dirichlet(ExponentialFamily):
40
+ r"""
41
+ Creates a Dirichlet distribution parameterized by concentration :attr:`concentration`.
42
+
43
+ Example::
44
+
45
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
46
+ >>> m = Dirichlet(torch.tensor([0.5, 0.5]))
47
+ >>> m.sample() # Dirichlet distributed with concentration [0.5, 0.5]
48
+ tensor([ 0.1046, 0.8954])
49
+
50
+ Args:
51
+ concentration (Tensor): concentration parameter of the distribution
52
+ (often referred to as alpha)
53
+ """
54
+
55
+ # pyrefly: ignore [bad-override]
56
+ arg_constraints = {
57
+ "concentration": constraints.independent(constraints.positive, 1)
58
+ }
59
+ support = constraints.simplex
60
+ has_rsample = True
61
+
62
+ def __init__(
63
+ self,
64
+ concentration: Tensor,
65
+ validate_args: Optional[bool] = None,
66
+ ) -> None:
67
+ if concentration.dim() < 1:
68
+ raise ValueError(
69
+ "`concentration` parameter must be at least one-dimensional."
70
+ )
71
+ self.concentration = concentration
72
+ batch_shape, event_shape = concentration.shape[:-1], concentration.shape[-1:]
73
+ super().__init__(batch_shape, event_shape, validate_args=validate_args)
74
+
75
+ def expand(self, batch_shape, _instance=None):
76
+ new = self._get_checked_instance(Dirichlet, _instance)
77
+ batch_shape = torch.Size(batch_shape)
78
+ new.concentration = self.concentration.expand(batch_shape + self.event_shape)
79
+ super(Dirichlet, new).__init__(
80
+ batch_shape, self.event_shape, validate_args=False
81
+ )
82
+ new._validate_args = self._validate_args
83
+ return new
84
+
85
+ def rsample(self, sample_shape: _size = ()) -> Tensor:
86
+ shape = self._extended_shape(sample_shape)
87
+ concentration = self.concentration.expand(shape)
88
+ return _Dirichlet.apply(concentration)
89
+
90
+ def log_prob(self, value):
91
+ if self._validate_args:
92
+ self._validate_sample(value)
93
+ return (
94
+ torch.xlogy(self.concentration - 1.0, value).sum(-1)
95
+ + torch.lgamma(self.concentration.sum(-1))
96
+ - torch.lgamma(self.concentration).sum(-1)
97
+ )
98
+
99
+ @property
100
+ def mean(self) -> Tensor:
101
+ return self.concentration / self.concentration.sum(-1, True)
102
+
103
+ @property
104
+ def mode(self) -> Tensor:
105
+ concentrationm1 = (self.concentration - 1).clamp(min=0.0)
106
+ mode = concentrationm1 / concentrationm1.sum(-1, True)
107
+ mask = (self.concentration < 1).all(dim=-1)
108
+ mode[mask] = torch.nn.functional.one_hot(
109
+ mode[mask].argmax(dim=-1), concentrationm1.shape[-1]
110
+ ).to(mode)
111
+ return mode
112
+
113
+ @property
114
+ def variance(self) -> Tensor:
115
+ con0 = self.concentration.sum(-1, True)
116
+ return (
117
+ self.concentration
118
+ * (con0 - self.concentration)
119
+ / (con0.pow(2) * (con0 + 1))
120
+ )
121
+
122
+ def entropy(self):
123
+ k = self.concentration.size(-1)
124
+ a0 = self.concentration.sum(-1)
125
+ return (
126
+ torch.lgamma(self.concentration).sum(-1)
127
+ - torch.lgamma(a0)
128
+ - (k - a0) * torch.digamma(a0)
129
+ - ((self.concentration - 1.0) * torch.digamma(self.concentration)).sum(-1)
130
+ )
131
+
132
+ @property
133
+ def _natural_params(self) -> tuple[Tensor]:
134
+ return (self.concentration,)
135
+
136
+ # pyrefly: ignore [bad-override]
137
+ def _log_normalizer(self, x):
138
+ return x.lgamma().sum(-1) - torch.lgamma(x.sum(-1))