ADAPT-Chase commited on
Commit
341e2e4
·
verified ·
1 Parent(s): b8e5831

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. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/__init__.cpython-312.pyc +0 -0
  2. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_api.cpython-312.pyc +0 -0
  3. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_collective_utils.cpython-312.pyc +0 -0
  4. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_dispatch.cpython-312.pyc +0 -0
  5. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_dtensor_spec.cpython-312.pyc +0 -0
  6. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_op_schema.cpython-312.pyc +0 -0
  7. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_random.cpython-312.pyc +0 -0
  8. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_redistribute.cpython-312.pyc +0 -0
  9. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_sharding_prop.cpython-312.pyc +0 -0
  10. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_shards_wrapper.cpython-312.pyc +0 -0
  11. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_tp_conv.cpython-312.pyc +0 -0
  12. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_utils.cpython-312.pyc +0 -0
  13. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/device_mesh.cpython-312.pyc +0 -0
  14. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/placement_types.cpython-312.pyc +0 -0
  15. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/__init__.cpython-312.pyc +0 -0
  16. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_common_rules.cpython-312.pyc +0 -0
  17. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_conv_ops.cpython-312.pyc +0 -0
  18. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_einsum_strategy.cpython-312.pyc +0 -0
  19. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_embedding_ops.cpython-312.pyc +0 -0
  20. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_experimental_ops.cpython-312.pyc +0 -0
  21. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_math_ops.cpython-312.pyc +0 -0
  22. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_matrix_ops.cpython-312.pyc +0 -0
  23. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_pointwise_ops.cpython-312.pyc +0 -0
  24. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_random_ops.cpython-312.pyc +0 -0
  25. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_tensor_ops.cpython-312.pyc +0 -0
  26. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_view_ops.cpython-312.pyc +0 -0
  27. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/utils.cpython-312.pyc +0 -0
  28. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/debug/__pycache__/__init__.cpython-312.pyc +0 -0
  29. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/debug/__pycache__/_comm_mode.cpython-312.pyc +0 -0
  30. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/debug/__pycache__/_op_coverage.cpython-312.pyc +0 -0
  31. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/debug/__pycache__/_visualize_sharding.cpython-312.pyc +0 -0
  32. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/experimental/__pycache__/__init__.cpython-312.pyc +0 -0
  33. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/experimental/__pycache__/_attention.cpython-312.pyc +0 -0
  34. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/experimental/__pycache__/_func_map.cpython-312.pyc +0 -0
  35. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/experimental/__pycache__/_register_sharding.cpython-312.pyc +0 -0
  36. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/experimental/__pycache__/_tp_transform.cpython-312.pyc +0 -0
  37. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/__init__.cpython-312.pyc +0 -0
  38. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/_data_parallel_utils.cpython-312.pyc +0 -0
  39. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/_utils.cpython-312.pyc +0 -0
  40. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/api.cpython-312.pyc +0 -0
  41. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/ddp.cpython-312.pyc +0 -0
  42. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/fsdp.cpython-312.pyc +0 -0
  43. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/input_reshard.cpython-312.pyc +0 -0
  44. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/loss.cpython-312.pyc +0 -0
  45. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/style.cpython-312.pyc +0 -0
  46. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/fsdp.py +390 -0
  47. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/input_reshard.py +106 -0
  48. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/loss.py +488 -0
  49. tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/style.py +658 -0
  50. tool_server/.venv/lib/python3.12/site-packages/torch/distributions/__pycache__/__init__.cpython-312.pyc +0 -0
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (1.62 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_api.cpython-312.pyc ADDED
Binary file (54.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_collective_utils.cpython-312.pyc ADDED
Binary file (15.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_dispatch.cpython-312.pyc ADDED
Binary file (19.9 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_dtensor_spec.cpython-312.pyc ADDED
Binary file (13.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_op_schema.cpython-312.pyc ADDED
Binary file (26.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_random.cpython-312.pyc ADDED
Binary file (19.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_redistribute.cpython-312.pyc ADDED
Binary file (11.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_sharding_prop.cpython-312.pyc ADDED
Binary file (19.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_shards_wrapper.cpython-312.pyc ADDED
Binary file (16.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_tp_conv.cpython-312.pyc ADDED
Binary file (12.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/_utils.cpython-312.pyc ADDED
Binary file (11.7 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/device_mesh.cpython-312.pyc ADDED
Binary file (392 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/__pycache__/placement_types.cpython-312.pyc ADDED
Binary file (28.2 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (446 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_common_rules.cpython-312.pyc ADDED
Binary file (10 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_conv_ops.cpython-312.pyc ADDED
Binary file (4.15 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_einsum_strategy.cpython-312.pyc ADDED
Binary file (6.16 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_embedding_ops.cpython-312.pyc ADDED
Binary file (10.6 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_experimental_ops.cpython-312.pyc ADDED
Binary file (1.44 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_math_ops.cpython-312.pyc ADDED
Binary file (40.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_matrix_ops.cpython-312.pyc ADDED
Binary file (20.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_pointwise_ops.cpython-312.pyc ADDED
Binary file (40 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_random_ops.cpython-312.pyc ADDED
Binary file (1.75 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_tensor_ops.cpython-312.pyc ADDED
Binary file (31.2 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/_view_ops.cpython-312.pyc ADDED
Binary file (33.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/_ops/__pycache__/utils.cpython-312.pyc ADDED
Binary file (12 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/debug/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (1.11 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/debug/__pycache__/_comm_mode.cpython-312.pyc ADDED
Binary file (29.7 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/debug/__pycache__/_op_coverage.cpython-312.pyc ADDED
Binary file (4.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/debug/__pycache__/_visualize_sharding.cpython-312.pyc ADDED
Binary file (6.77 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/experimental/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (1.65 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/experimental/__pycache__/_attention.cpython-312.pyc ADDED
Binary file (59.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/experimental/__pycache__/_func_map.cpython-312.pyc ADDED
Binary file (10.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/experimental/__pycache__/_register_sharding.cpython-312.pyc ADDED
Binary file (7.06 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/experimental/__pycache__/_tp_transform.cpython-312.pyc ADDED
Binary file (23.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (652 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/_data_parallel_utils.cpython-312.pyc ADDED
Binary file (2.18 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/_utils.cpython-312.pyc ADDED
Binary file (2.71 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/api.cpython-312.pyc ADDED
Binary file (5.78 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/ddp.cpython-312.pyc ADDED
Binary file (4.64 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/fsdp.cpython-312.pyc ADDED
Binary file (16.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/input_reshard.cpython-312.pyc ADDED
Binary file (5.44 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/loss.cpython-312.pyc ADDED
Binary file (20 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/__pycache__/style.cpython-312.pyc ADDED
Binary file (30.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/fsdp.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+ from typing import Any, cast, Optional
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.device_mesh import _mesh_resources
18
+ from torch.distributed.fsdp._common_utils import _set_fsdp_flattened
19
+ from torch.distributed.fsdp._fsdp_extensions import FSDPExtensions
20
+ from torch.distributed.fsdp._shard_utils import _create_chunk_sharded_tensor
21
+ from torch.distributed.remote_device import _remote_device
22
+ from torch.distributed.tensor import DeviceMesh, DTensor, Replicate, Shard as DShard
23
+ from torch.distributed.tensor.parallel._data_parallel_utils import (
24
+ _flatten_tensor,
25
+ _unflatten_tensor,
26
+ )
27
+
28
+
29
+ __all__ = ["DTensorExtensions"]
30
+
31
+
32
+ def _get_box(tensor: DTensor) -> tuple[torch.Size, torch.Size]:
33
+ device_mesh = tensor.device_mesh
34
+ assert device_mesh.ndim == 1, "Only 1D DeviceMeshes currently handled"
35
+
36
+ placement = tensor.placements[0]
37
+ offsets = [0] * len(tensor.size())
38
+ num_chunks = device_mesh.size(mesh_dim=0)
39
+
40
+ if tensor.placements[0].is_shard():
41
+ shard_dim = cast(DShard, placement).dim
42
+ chunk_size = tensor.size(shard_dim) // num_chunks
43
+ offsets[shard_dim] = chunk_size
44
+
45
+ return (torch.Size(offsets), tensor._local_tensor.size())
46
+
47
+
48
+ def _get_box_for(tensor: DTensor, idx: int) -> tuple[torch.Size, torch.Size]:
49
+ offsets, size = _get_box(tensor)
50
+ return (torch.Size([val * idx for val in offsets]), size)
51
+
52
+
53
+ def _get_local_box(tensor: DTensor) -> tuple[torch.Size, torch.Size]:
54
+ device_mesh = tensor.device_mesh
55
+ coord = device_mesh.get_coordinate()
56
+ assert coord is not None
57
+ return _get_box_for(tensor, coord[0])
58
+
59
+
60
+ def _create_shard_md_from_dt(dt: DTensor, current_rank: int) -> ShardMetadata:
61
+ mesh = dt.device_mesh
62
+ assert mesh.ndim == 1, "Only 1D DeviceMeshes currently handled"
63
+
64
+ offsets, sizes = _get_local_box(dt)
65
+ return ShardMetadata(
66
+ shard_offsets=list(offsets),
67
+ shard_sizes=list(sizes),
68
+ placement=f"rank:{current_rank}/{dt._local_tensor.device}",
69
+ )
70
+
71
+
72
+ def _create_sharded_tensor_md_from_dt(
73
+ dt: DTensor, dt_pg: c10d.ProcessGroup
74
+ ) -> ShardedTensorMetadata:
75
+ # This is where it gets tricky, we have to produce a ShardedTensor that has full coverage
76
+ # and yet has only one valid shard for the current rank.
77
+
78
+ shards_md = []
79
+ my_rank = dist.get_rank(dt_pg)
80
+ scapegoat_rank = 0 if my_rank > 0 else 1
81
+
82
+ if dt.placements[0].is_shard():
83
+ shard_count = dt_pg.size()
84
+ else:
85
+ shard_count = 1
86
+
87
+ for i in range(shard_count):
88
+ offsets, sizes = _get_box_for(dt, i)
89
+ shards_md.append(
90
+ ShardMetadata(
91
+ shard_offsets=list(offsets),
92
+ shard_sizes=list(sizes),
93
+ placement=(
94
+ f"rank:{scapegoat_rank if i > 0 else my_rank}/{dt._local_tensor.device}"
95
+ ),
96
+ )
97
+ )
98
+
99
+ return ShardedTensorMetadata(
100
+ shards_metadata=shards_md,
101
+ size=dt.size(),
102
+ tensor_properties=TensorProperties(
103
+ dtype=dt.dtype,
104
+ layout=dt.layout,
105
+ requires_grad=dt.requires_grad,
106
+ # ignore memory_format and pin_memory as those are not supported by DT
107
+ ),
108
+ )
109
+
110
+
111
+ def _get_dt_pg(dt: DTensor) -> c10d.ProcessGroup:
112
+ mesh = dt.device_mesh
113
+ assert mesh.ndim == 1, "Only 1D DeviceMeshes currently handled"
114
+ return mesh.get_group()
115
+
116
+
117
+ def _rewrite_spec_if_needed(
118
+ spec: shard_spec.ShardingSpec, tensor: torch.Tensor, rank: int
119
+ ) -> shard_spec.ShardingSpec:
120
+ """
121
+ Rewrite ``spec`` to match the device of ``tensor``.
122
+
123
+ FSDP.sharded_optim_state_dict sneakly ships optimizer state to CPU so if the original ShardingSpec
124
+ produces CUDA metadata, ST construction bombs.
125
+ """
126
+ if not isinstance(spec, ChunkShardingSpec):
127
+ return spec
128
+
129
+ # let's see if we need
130
+ rewrite = False
131
+ for p in spec.placements:
132
+ p = cast(_remote_device, p)
133
+ if p.rank() == rank and p.device() != tensor.device:
134
+ rewrite = True
135
+ break
136
+ if rewrite:
137
+ spec = copy.deepcopy(spec)
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
+ spec.placements[i] = _remote_device(f"rank:{rank}/{tensor.device}")
142
+
143
+ return spec
144
+
145
+
146
+ def _chunk_tensor(
147
+ tensor: torch.Tensor,
148
+ rank: int,
149
+ world_size: int,
150
+ num_devices_per_node: int,
151
+ pg: dist.ProcessGroup,
152
+ ) -> torch.Tensor:
153
+ if type(tensor) is ShardedTensor:
154
+ assert len(tensor.local_shards()) == 1
155
+
156
+ inner_param = tensor.local_tensor()
157
+ inner_st = _create_chunk_sharded_tensor(
158
+ inner_param,
159
+ rank,
160
+ world_size,
161
+ num_devices_per_node,
162
+ pg,
163
+ )
164
+
165
+ outer_local_shard = tensor.local_shards()[0]
166
+ shards: list[Shard] = [
167
+ Shard(inner_st, copy.deepcopy(outer_local_shard.metadata))
168
+ ]
169
+ st_meta = copy.deepcopy(tensor.metadata())
170
+ st_meta.tensor_properties.requires_grad = False
171
+
172
+ st_outer = ShardedTensor._init_from_local_shards_and_global_metadata(
173
+ shards,
174
+ sharded_tensor_metadata=st_meta,
175
+ process_group=tensor._process_group,
176
+ init_rrefs=False,
177
+ )
178
+ return st_outer
179
+ elif type(tensor) is DTensor:
180
+ device_mesh = tensor.device_mesh
181
+ assert device_mesh.ndim == 1, "Only 1D DeviceMeshes currently handled"
182
+
183
+ inner_param = tensor._local_tensor
184
+
185
+ inner_st = _create_chunk_sharded_tensor(
186
+ inner_param,
187
+ rank,
188
+ world_size,
189
+ torch.accelerator.device_count(),
190
+ pg,
191
+ )
192
+
193
+ dt_pg = _get_dt_pg(tensor)
194
+ # We do this differently here, we create a ST with no local shards then patch it
195
+ shards = [
196
+ Shard(inner_st, _create_shard_md_from_dt(tensor, dist.get_rank(dt_pg)))
197
+ ]
198
+
199
+ st_meta = _create_sharded_tensor_md_from_dt(tensor, dt_pg)
200
+ st_meta.tensor_properties.requires_grad = False
201
+
202
+ st_outer = ShardedTensor._init_from_local_shards_and_global_metadata(
203
+ shards,
204
+ sharded_tensor_metadata=st_meta,
205
+ process_group=dt_pg,
206
+ init_rrefs=False,
207
+ )
208
+
209
+ return st_outer
210
+ else:
211
+ return _create_chunk_sharded_tensor(
212
+ tensor,
213
+ rank,
214
+ world_size,
215
+ num_devices_per_node,
216
+ pg,
217
+ )
218
+
219
+
220
+ def _chunk_dtensor(
221
+ tensor: torch.Tensor,
222
+ rank: int,
223
+ device_mesh: DeviceMesh,
224
+ ) -> DTensor:
225
+ """
226
+ Shard a tensor to chunks along the first dimension.
227
+
228
+ The local rank will gets its corresponding chunk as the local tensor to create a DTensor.
229
+ """
230
+ root_mesh = _mesh_resources.get_root_mesh(device_mesh)
231
+ if root_mesh is None:
232
+ raise RuntimeError("No parent device_mesh is found for FSDP device_mesh.")
233
+ if root_mesh.ndim < 2:
234
+ raise RuntimeError(
235
+ f"Found parent device_mesh of ndim={root_mesh.ndim},",
236
+ "but meshes must be at least 2D.",
237
+ )
238
+
239
+ # We need to explicitly call .detach() to return a new tensor detached from the current graph.
240
+ tensor = tensor.detach().clone()
241
+
242
+ # When a layer is not involved in TP, then the tensor will not be a DTensor.
243
+ # e.g. When a layer is not sppecified in the parallelize_plan, TP will have no effect on the layer.
244
+ # e.g. When you do PairwiseParallel on a 3 layer model, TP will have no effect on the third layer.
245
+ if isinstance(tensor, torch.Tensor) and not isinstance(tensor, DTensor):
246
+ # For tensors, it is replicated across tp dimension and sharded across FSDP dimension.
247
+ # TP is the inner dimension and FSDP is the outer dimension.
248
+ # Therefore, shard placements for tensor is (Shard(0), Replicate()).
249
+ replicate_placements = [Replicate() for _ in range(root_mesh.ndim)]
250
+ shard_placements = [Replicate() for _ in range(root_mesh.ndim)]
251
+ shard_placements[0] = DShard(0) # type: ignore[call-overload]
252
+
253
+ return DTensor.from_local(
254
+ tensor, root_mesh, replicate_placements, run_check=False
255
+ ).redistribute(
256
+ device_mesh=root_mesh,
257
+ placements=shard_placements,
258
+ )
259
+
260
+ else:
261
+ tp_placements = tensor.placements
262
+ tp_placement = tp_placements[0]
263
+
264
+ tensor = tensor.to_local()
265
+
266
+ # For DTensors, it is sharded across tp dimension first and then sharded across FSDP dimension.
267
+ # TP is the inner dimension and FSDP is the outer dimension.
268
+ # Therefore, shard placements for tensor is (Shard(0), tp_placement).
269
+ # For higher dimensional meshes, it is replicated across other dimensions. For example, with
270
+ # HSDP the shard placements for tensor is (Replicate, Shard(0), tp_placement).
271
+ replicate_placements = [Replicate() for _ in range(root_mesh.ndim)]
272
+ replicate_placements[-1] = tp_placement # type: ignore[call-overload]
273
+ shard_placements = [Replicate() for i in range(root_mesh.ndim)] # type: ignore[misc]
274
+ shard_placements[-2] = DShard(0) # type: ignore[call-overload]
275
+ shard_placements[-1] = tp_placement # type: ignore[call-overload]
276
+
277
+ return DTensor.from_local(
278
+ tensor, root_mesh, replicate_placements, run_check=False
279
+ ).redistribute(
280
+ device_mesh=root_mesh,
281
+ placements=shard_placements,
282
+ )
283
+
284
+
285
+ def _pre_load_state_dict(
286
+ tensor: torch.Tensor,
287
+ ) -> tuple[torch.Tensor, list[Shard]]:
288
+ shards = cast(ShardedTensor, tensor).local_shards()
289
+ if len(shards) == 1 and type(shards[0].tensor) is ShardedTensor:
290
+ inner_tensor = shards[0].tensor
291
+ shards = inner_tensor.local_shards() # pyre-ignore[16]
292
+ tensor = inner_tensor
293
+
294
+ return (tensor, shards if len(shards) > 0 else [])
295
+
296
+
297
+ def _all_gather_dtensor(
298
+ tensor: DTensor,
299
+ parent_mesh: Optional[DeviceMesh],
300
+ ) -> torch.Tensor:
301
+ """All gather a DTensor in its FSDP dimension and return the local tensor."""
302
+ assert parent_mesh == tensor.device_mesh
303
+
304
+ placements = list(copy.deepcopy(tensor.placements))
305
+ # FSDP + TP: [Shard(0), tp_placement] -> [Replicate(), tp_placement]
306
+ # HSDP + TP: [Replicate(), Shard(0), tp_placement] -> [Replicate(), Replicate(), tp_placement]
307
+ for i in range(0, len(placements) - 1):
308
+ placements[i] = Replicate()
309
+ tensor = tensor.redistribute(
310
+ device_mesh=tensor.device_mesh,
311
+ placements=placements,
312
+ )
313
+
314
+ return tensor.to_local()
315
+
316
+
317
+ class DTensorExtensions(FSDPExtensions):
318
+ """
319
+ DTensorExtension is the TensorFlattener extension needed for 2D FSDP + TP.
320
+
321
+ This is the implementation for FSDPExtensions defined in
322
+ https://github.com/pytorch/pytorch/blob/main/torch/distributed/fsdp/_fsdp_extensions.py
323
+ """
324
+
325
+ def __init__(self, device_handle) -> None:
326
+ super().__init__()
327
+ self.compute_stream = None
328
+ self.device_handle = device_handle
329
+ # we have to use the dynamo disable this way to disable dynamo as the decorater way would
330
+ # trigger build failure with torch deploy...
331
+ self.post_unflatten_transform = torch._dynamo.disable( # type: ignore[method-assign]
332
+ self.post_unflatten_transform
333
+ )
334
+
335
+ def pre_flatten_transform(
336
+ self,
337
+ tensor: torch.Tensor,
338
+ ) -> tuple[torch.Tensor, Optional[Any]]:
339
+ return _flatten_tensor(tensor)
340
+
341
+ def post_unflatten_transform(
342
+ self, tensor: torch.Tensor, param_extension: Any
343
+ ) -> torch.Tensor:
344
+ stream = self.compute_stream or self.device_handle.current_stream()
345
+ with self.device_handle.stream(stream):
346
+ # runtime we put the unflattened tensor call on the compute stream since
347
+ # the unflattened tensor might contain computations in fwd/bwd where we
348
+ # need to sync properly.
349
+ # TODO: this is a short term fix and we should make the get_unflat_views
350
+ # directly happen in the compute stream.
351
+ result = _unflatten_tensor(
352
+ tensor,
353
+ param_extension,
354
+ device_handle=self.device_handle,
355
+ compute_stream=self.compute_stream,
356
+ )
357
+ _set_fsdp_flattened(result)
358
+ return result
359
+
360
+ def chunk_tensor(
361
+ self,
362
+ tensor: torch.Tensor,
363
+ rank: int,
364
+ world_size: int,
365
+ num_devices_per_node: int,
366
+ pg: dist.ProcessGroup,
367
+ device: Optional[torch.device] = None,
368
+ ) -> torch.Tensor:
369
+ return _chunk_tensor(tensor, rank, world_size, num_devices_per_node, pg)
370
+
371
+ def chunk_dtensor(
372
+ self,
373
+ tensor: torch.Tensor,
374
+ rank: int,
375
+ device_mesh: DeviceMesh,
376
+ ) -> torch.Tensor:
377
+ return _chunk_dtensor(tensor, rank, device_mesh)
378
+
379
+ def pre_load_state_dict_transform(
380
+ self,
381
+ tensor: torch.Tensor,
382
+ ) -> tuple[torch.Tensor, list[Shard]]:
383
+ return _pre_load_state_dict(tensor)
384
+
385
+ def all_gather_dtensor(
386
+ self,
387
+ tensor: DTensor,
388
+ parent_mesh: Optional[DeviceMesh],
389
+ ) -> torch.Tensor:
390
+ return _all_gather_dtensor(tensor, parent_mesh)
tool_server/.venv/lib/python3.12/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, Optional
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: Optional[int] = 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: Optional[torch.autograd.graph.saved_tensors_hooks] = 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
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/loss.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+ import contextlib
4
+ from typing import cast, Optional
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.placement_types import Placement
21
+
22
+
23
+ aten = torch.ops.aten
24
+
25
+
26
+ __all__ = ["loss_parallel"]
27
+
28
+
29
+ @contextlib.contextmanager
30
+ def loss_parallel():
31
+ """
32
+ A context manager that enables loss parallelism, where efficient parallelized loss computation
33
+ can be performed when the input is sharded on the class dimension. Currently only the cross-entropy
34
+ loss is supported.
35
+
36
+ Within this context manager, one can use :func:`~torch.nn.functional.cross_entropy` or
37
+ :class:`~torch.nn.CrossEntropyLoss` as usual, with the following assumptions on the input parameters.
38
+ The corresponding ``backward()`` call, if any, also needs to happen under this context manager.
39
+
40
+ Args:
41
+ input (:class:`DTensor`):
42
+ Input logits. Assumed to be sharded on the class dimension.
43
+ target (Union[:class:`torch.Tensor`, :class:`DTensor`]):
44
+ Must be ground truth class indices (class probabilities currently not supported).
45
+ Assumed to be replicated across the ``DeviceMesh``.
46
+ weight (Union[:class:`torch.Tensor`, :class:`DTensor`], optional):
47
+ If given, assumed to be replicated across the ``DeviceMesh``.
48
+ label_smoothing:
49
+ Currently not supported.
50
+
51
+ Returns:
52
+ A replicated :class:`DTensor`.
53
+
54
+ Example:
55
+ A sharded DTensor is manually created here to showcase the usage.
56
+ In practice, it is usually the output of a TP module.
57
+
58
+ >>> # xdoctest: +SKIP("distributed")
59
+ >>> from torch.distributed.tensor.parallel import loss_parallel
60
+ >>> from torch.distributed.device_mesh import init_device_mesh
61
+ >>> ...
62
+ >>> device_mesh = init_device_mesh("cuda", (8,))
63
+ >>> input = torch.randn(4, 16, device="cuda", requires_grad=True)
64
+ >>> dist_input = distribute_tensor(input, device_mesh, placements=[Shard(1)])
65
+ >>> target = torch.randint(16, (4,), device="cuda")
66
+ >>> with loss_parallel():
67
+ >>> loss = F.cross_entropy(dist_input, target, reduction="mean")
68
+ >>> loss.backward()
69
+ >>> ...
70
+ """
71
+ _enable_custom_loss_ops()
72
+
73
+ yield
74
+
75
+ _disable_custom_loss_ops()
76
+
77
+
78
+ # Currently only needs to support one dimensional DeviceMesh; in general return
79
+ # the mesh_dim with placements[mesh_dim].is_shard(dim)
80
+ def _find_all_reduce_mesh_dim(placements: tuple[Placement, ...], dim: int) -> int:
81
+ if not len(placements) == 1:
82
+ raise ValueError(
83
+ "Currently loss_parallel() only supports input on one-dimensional DeviceMesh."
84
+ )
85
+ if not placements[0].is_shard(dim):
86
+ raise ValueError(
87
+ f"loss_parallel() should be enabled only when the input tensor is sharded on dimension {dim}."
88
+ )
89
+ return 0
90
+
91
+
92
+ def _cast_to_dtensor(
93
+ tensor, placements: tuple[Placement, ...], mesh: DeviceMesh
94
+ ) -> DTensor:
95
+ if isinstance(tensor, DTensor):
96
+ if tensor.placements == placements:
97
+ return tensor
98
+ else:
99
+ raise RuntimeError(f"Expected {placements} but got {tensor.placements}.")
100
+ elif isinstance(tensor, torch.Tensor):
101
+ return DTensor.from_local(
102
+ tensor, device_mesh=mesh, placements=placements, run_check=False
103
+ )
104
+ else:
105
+ raise TypeError(f"Unsupported type {type(tensor)}")
106
+
107
+
108
+ def _propagate_tensor_meta(
109
+ op_call: torch._ops.OpOverload,
110
+ args: tuple[object, ...],
111
+ kwargs: dict[str, object],
112
+ ) -> TensorMeta:
113
+ op_info = DTensor._op_dispatcher.unwrap_to_op_info(op_call, args, kwargs)
114
+ tensor_meta = DTensor._op_dispatcher.sharding_propagator._propagate_tensor_meta(
115
+ op_info.schema
116
+ )
117
+ if isinstance(tensor_meta, TensorMeta):
118
+ return tensor_meta
119
+ elif isinstance(tensor_meta, tuple):
120
+ return tensor_meta[0]
121
+ else:
122
+ raise RuntimeError(f"Unexpected tensor meta type: {type(tensor_meta)}.")
123
+
124
+
125
+ # NOTE: The implementation follows torch._decomp.decomposition._log_softmax,
126
+ # with all_reduce manually inserted to perform distributed computation.
127
+ def _log_softmax(x, dim, half_to_float, mesh, mesh_dim):
128
+ if half_to_float:
129
+ assert x.dtype == torch.half
130
+ computation_dtype, result_dtype = utils.elementwise_dtypes(
131
+ x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
132
+ )
133
+ x = x.to(dtype=computation_dtype, memory_format=torch.contiguous_format)
134
+ if x.numel() == 0:
135
+ shifted = x
136
+ else:
137
+ x_max = torch.amax(x, dim, keepdim=True)
138
+ x_max = funcol.all_reduce(
139
+ x_max, reduceOp=c10d.ReduceOp.MAX.name, group=(mesh, mesh_dim)
140
+ )
141
+ shifted = x - x_max
142
+ shifted_sumexp = torch.sum(torch.exp(shifted), dim, keepdim=True)
143
+ shifted_sumexp = funcol.all_reduce(
144
+ shifted_sumexp, reduceOp=c10d.ReduceOp.SUM.name, group=(mesh, mesh_dim)
145
+ )
146
+ shifted_logsumexp = torch.log(shifted_sumexp)
147
+ result = shifted - shifted_logsumexp
148
+ if not half_to_float:
149
+ result = result.to(result_dtype)
150
+ return result
151
+
152
+
153
+ def _log_softmax_handler(
154
+ op_call: torch._ops.OpOverload,
155
+ args: tuple[object, ...],
156
+ kwargs: dict[str, object],
157
+ ) -> object:
158
+ x = cast(DTensor, args[0])
159
+ dim = cast(int, args[1])
160
+ half_to_float = cast(bool, args[2])
161
+
162
+ spec = x._spec
163
+ mesh_dim = _find_all_reduce_mesh_dim(spec.placements, dim)
164
+
165
+ output_tensor_meta = _propagate_tensor_meta(op_call, args, kwargs)
166
+
167
+ res = _log_softmax(x._local_tensor, dim, half_to_float, spec.mesh, mesh_dim)
168
+
169
+ res_spec = DTensorSpec(
170
+ spec.mesh,
171
+ spec.placements,
172
+ tensor_meta=output_tensor_meta,
173
+ )
174
+
175
+ return DTensor(
176
+ res,
177
+ res_spec,
178
+ requires_grad=res.requires_grad,
179
+ )
180
+
181
+
182
+ # NOTE: As explained below at _nll_loss_and_log_softmax_backward, the
183
+ # _log_softmax_backward_handler does not actually do any computation.
184
+ def _log_softmax_backward_handler(
185
+ op_call: torch._ops.OpOverload,
186
+ args: tuple[object, ...],
187
+ kwargs: dict[str, object],
188
+ ) -> object:
189
+ grad_output = cast(DTensor, args[0])
190
+ input_dtype = cast(torch.dtype, args[3])
191
+ return grad_output.to(input_dtype)
192
+
193
+
194
+ # NOTE: The implementation follows torch._decomp.decomposition._nll_loss_forward,
195
+ # with customized communication inserted to perform distributed computation.
196
+ def _nll_loss_forward(
197
+ x: Tensor,
198
+ target: Tensor,
199
+ weight: Optional[Tensor],
200
+ local_weight: Optional[Tensor],
201
+ reduction: int,
202
+ ignore_index: int,
203
+ input_shape: torch.Size,
204
+ channel_dim: int,
205
+ mesh: DeviceMesh,
206
+ mesh_dim: int,
207
+ ) -> tuple[Tensor, Tensor]:
208
+ n_dims = x.dim()
209
+ channel_dim = 1
210
+ if n_dims < 2:
211
+ channel_dim = 0
212
+
213
+ def _weight_view(weight: Tensor) -> Tensor:
214
+ if n_dims > 1:
215
+ shape = [
216
+ 1,
217
+ ] * n_dims
218
+ shape[channel_dim] = weight.shape[0]
219
+ w = weight.view(shape)
220
+ else:
221
+ w = weight
222
+ return w
223
+
224
+ if weight is not None:
225
+ w = _weight_view(weight)
226
+ assert local_weight is not None
227
+ local_w = _weight_view(local_weight)
228
+ x = x * local_w
229
+ safe_target = torch.where(target != ignore_index, target, 0)
230
+ safe_target_ = safe_target.unsqueeze(channel_dim)
231
+
232
+ # The following code block is a distributed version of
233
+ # result = -torch.gather(self, channel_dim, safe_target_).squeeze(channel_dim)
234
+ partial_placement = _MaskPartial(offset_shape=input_shape, offset_dim=channel_dim)
235
+ safe_target_partial_ = partial_placement._partition_value(
236
+ safe_target_, mesh, mesh_dim
237
+ )
238
+ result_partial = torch.gather(x, channel_dim, safe_target_partial_)
239
+ # an all_reduce happens here
240
+ result_reduced = partial_placement._reduce_value(result_partial, mesh, mesh_dim)
241
+ result = -result_reduced.squeeze(channel_dim)
242
+
243
+ result = torch.where(target != ignore_index, result, 0)
244
+
245
+ if reduction == Reduction.NONE.value and n_dims > 1:
246
+ total_weight = x.new_full((), 0.0)
247
+ return result, total_weight
248
+
249
+ if weight is not None:
250
+ new_shape = list(x.shape)
251
+ new_shape[channel_dim] = -1
252
+ w = w.expand(new_shape)
253
+ wsum = torch.gather(w, channel_dim, safe_target_).squeeze(channel_dim)
254
+ wsum = torch.where(target != ignore_index, wsum, 0)
255
+ total_weight = wsum.sum()
256
+ else:
257
+ total_weight = (target != ignore_index).sum().to(x)
258
+
259
+ # NOTE: this is correct only on 1D DeviceMesh; o/w additional
260
+ # all-reduce on result and total_weight is needed
261
+ if reduction == Reduction.SUM.value:
262
+ result = result.sum()
263
+ elif reduction == Reduction.MEAN.value:
264
+ result = result.sum() / total_weight
265
+
266
+ return result, total_weight
267
+
268
+
269
+ def _nll_loss_forward_handler(
270
+ op_call: torch._ops.OpOverload,
271
+ args: tuple[object, ...],
272
+ kwargs: dict[str, object],
273
+ ) -> object:
274
+ x = cast(DTensor, args[0])
275
+ target = args[1]
276
+ weight = args[2]
277
+ reduction = cast(int, args[3])
278
+ ignore_index = cast(int, args[4])
279
+
280
+ channel_dim = 1 if x.dim() >= 2 else 0
281
+ spec = x._spec
282
+ mesh_dim = _find_all_reduce_mesh_dim(spec.placements, channel_dim)
283
+
284
+ # Check user input: if target and weight are not DTensors, convert them to DTensors;
285
+ # if they are DTensors, check that they have the desired placements.
286
+ target_placements = _skip_dim(
287
+ replicate_reduction_dims(spec.placements, [channel_dim]), channel_dim
288
+ )
289
+ all_replicate_placements = (Replicate(),) * spec.mesh.ndim
290
+ target = _cast_to_dtensor(target, target_placements, spec.mesh)
291
+ local_weight = None
292
+ if weight is not None:
293
+ weight = _cast_to_dtensor(weight, all_replicate_placements, spec.mesh)
294
+ # For local computation, both (replicated) weight and (sharded) local_weight
295
+ # are needed in _nll_loss_forward(). local_weight is generated here using
296
+ # DTensor API, without incurring any communication.
297
+ sharded_placements = [
298
+ Shard(0) if i == mesh_dim else Replicate() for i in range(spec.mesh.ndim)
299
+ ]
300
+ local_weight = weight.redistribute(spec.mesh, sharded_placements)._local_tensor
301
+ assert local_weight.shape[0] == x._local_tensor.shape[channel_dim]
302
+
303
+ if reduction == Reduction.NONE.value:
304
+ output_placements = target_placements
305
+ else:
306
+ output_placements = all_replicate_placements
307
+
308
+ # tensor inputs to _propagate_tensor_meta need to be DTensors
309
+ args = list(args)
310
+ args[1], args[2] = target, weight
311
+ output_tensor_meta = _propagate_tensor_meta(op_call, tuple(args), kwargs)
312
+
313
+ result, total_weight = _nll_loss_forward(
314
+ x._local_tensor,
315
+ target._local_tensor,
316
+ weight._local_tensor if weight is not None else None,
317
+ local_weight,
318
+ reduction,
319
+ ignore_index,
320
+ x.shape,
321
+ channel_dim,
322
+ spec.mesh,
323
+ mesh_dim,
324
+ )
325
+ out_spec = DTensorSpec(spec.mesh, output_placements, tensor_meta=output_tensor_meta)
326
+
327
+ return (
328
+ DTensor(
329
+ result,
330
+ out_spec,
331
+ requires_grad=result.requires_grad,
332
+ ),
333
+ total_weight,
334
+ )
335
+
336
+
337
+ # NOTE: The backward computation of cross_entropy goes through two steps:
338
+ # backward for nll_loss and then backward for log_softmax. In loss parallel,
339
+ # the two steps are fused into the following function (called by _nll_loss_backward_handler)
340
+ # to avoid communication when target contains class indices not class probabilities.
341
+ # Also note that the _log_softmax_backward_handler does not perform computation.
342
+ # The implementation resembles _nll_loss_backward and _log_softmax_backward_data
343
+ # from torch._decomp.decomposition.
344
+ def _nll_loss_and_log_softmax_backward(
345
+ grad_output: Tensor,
346
+ x: Tensor,
347
+ target: Tensor,
348
+ weight: Optional[Tensor],
349
+ reduction: int,
350
+ ignore_index: int,
351
+ total_weight: Tensor,
352
+ input_shape: torch.Size,
353
+ channel_dim: int,
354
+ mesh: DeviceMesh,
355
+ mesh_dim: int,
356
+ ) -> Tensor:
357
+ channel_dim = 0 if x.dim() < 2 else 1
358
+ if reduction == Reduction.MEAN.value:
359
+ grad_output = grad_output / total_weight
360
+
361
+ target = target.unsqueeze(channel_dim)
362
+ safe_target = torch.where(target != ignore_index, target, 0)
363
+ grad_input = torch.zeros_like(x)
364
+
365
+ # The following code block is a distributed version of
366
+ # grad_input = torch.scatter(grad_input, channel_dim, safe_target, -1.0)
367
+ partial_placement = _MaskPartial(offset_shape=input_shape, offset_dim=channel_dim)
368
+ safe_target = safe_target.squeeze(channel_dim).flatten()
369
+ masked_safe_target = partial_placement._partition_value(safe_target, mesh, mesh_dim)
370
+ # only update grad_input to -1 if not masked
371
+ assert partial_placement.mask_buffer.data is not None
372
+ grad_update = partial_placement.mask_buffer.data.to(grad_input.dtype) - 1.0
373
+ arange_1d = torch.arange(
374
+ masked_safe_target.shape[0], device=masked_safe_target.device
375
+ )
376
+ # The first two cases with x.dim() <= 2 are for aten.nll_loss_backward.default;
377
+ # the last case is for aten.nll_loss2d_backward.default.
378
+ if x.dim() == 1:
379
+ grad_input[masked_safe_target] = grad_update
380
+ elif x.dim() == 2:
381
+ grad_input[arange_1d, masked_safe_target] = grad_update
382
+ else:
383
+ grad_input_t = grad_input.transpose(channel_dim, -1)
384
+ intermidate_shape = grad_input_t.shape
385
+ grad_input_2d = grad_input_t.reshape(-1, x.shape[channel_dim])
386
+ grad_input_2d[arange_1d, masked_safe_target] = grad_update
387
+ grad_input = grad_input_2d.view(intermidate_shape).transpose(channel_dim, -1)
388
+
389
+ if grad_input.dim() > grad_output.dim() > 0:
390
+ grad_output = grad_output.unsqueeze(channel_dim)
391
+
392
+ if weight is not None:
393
+ new_shape = [1 for _ in range(x.dim())]
394
+ new_shape[channel_dim] = weight.shape[0]
395
+ weight = weight.reshape(new_shape)
396
+ # In order for fused computation to work, the following line is rewritten.
397
+ # grad_output = grad_output * weight
398
+ new_shape = list(x.shape)
399
+ new_shape[channel_dim] = -1
400
+ w = weight.expand(new_shape)
401
+ w_target = torch.gather(w, channel_dim, target)
402
+ grad_output = grad_output * w_target
403
+
404
+ grad_output = torch.where(target != ignore_index, grad_output, 0)
405
+
406
+ # NOTE: Instead of directly returning the grad_input as grad_output for log_softmax,
407
+ # here we perform backward computation for log_softmax altogether to avoid the
408
+ # otherwise extra all_gather communication.
409
+ # return grad_input * grad_output
410
+ return (grad_input + torch.exp(x)) * grad_output
411
+
412
+
413
+ def _nll_loss_backward_handler(
414
+ op_call: torch._ops.OpOverload,
415
+ args: tuple[object, ...],
416
+ kwargs: dict[str, object],
417
+ ) -> object:
418
+ grad_output = cast(DTensor, args[0])
419
+ x = cast(DTensor, args[1])
420
+ target = args[2]
421
+ weight = args[3]
422
+ reduction = cast(int, args[4])
423
+ ignore_index = cast(int, args[5])
424
+ total_weight = cast(Tensor, args[6])
425
+
426
+ channel_dim = 1 if x.dim() >= 2 else 0
427
+ spec = x._spec
428
+ mesh_dim = _find_all_reduce_mesh_dim(spec.placements, channel_dim)
429
+
430
+ # if target and weight are not DTensors, convert them to DTensors
431
+ target_placements = _skip_dim(
432
+ replicate_reduction_dims(spec.placements, [channel_dim]), channel_dim
433
+ )
434
+ all_replicate_placements = (Replicate(),) * spec.mesh.ndim
435
+ target = _cast_to_dtensor(target, target_placements, spec.mesh)
436
+ if weight is not None:
437
+ weight = _cast_to_dtensor(weight, all_replicate_placements, spec.mesh)
438
+
439
+ # tensor inputs to _propagate_tensor_meta need to be DTensors
440
+ args = list(args)
441
+ args[2], args[3] = target, weight
442
+ args[6] = _cast_to_dtensor(total_weight, all_replicate_placements, spec.mesh)
443
+ output_tensor_meta = _propagate_tensor_meta(op_call, tuple(args), kwargs)
444
+
445
+ result = _nll_loss_and_log_softmax_backward(
446
+ grad_output._local_tensor,
447
+ x._local_tensor,
448
+ target._local_tensor,
449
+ weight._local_tensor if weight is not None else None,
450
+ reduction,
451
+ ignore_index,
452
+ total_weight,
453
+ x.shape,
454
+ channel_dim,
455
+ spec.mesh,
456
+ mesh_dim,
457
+ )
458
+ # the output sharding is the same as input sharding: Shard(channel_dim) on mesh_dim
459
+ out_spec = DTensorSpec(
460
+ spec.mesh,
461
+ spec.placements,
462
+ tensor_meta=output_tensor_meta,
463
+ )
464
+
465
+ return DTensor(
466
+ result,
467
+ out_spec,
468
+ requires_grad=result.requires_grad,
469
+ )
470
+
471
+
472
+ customized_loss_ops = {
473
+ aten._log_softmax.default: _log_softmax_handler,
474
+ aten._log_softmax_backward_data.default: _log_softmax_backward_handler,
475
+ aten.nll_loss_forward.default: _nll_loss_forward_handler,
476
+ aten.nll_loss2d_forward.default: _nll_loss_forward_handler,
477
+ aten.nll_loss_backward.default: _nll_loss_backward_handler,
478
+ aten.nll_loss2d_backward.default: _nll_loss_backward_handler,
479
+ }
480
+
481
+
482
+ def _enable_custom_loss_ops():
483
+ DTensor._op_dispatcher._custom_op_handlers.update(customized_loss_ops)
484
+
485
+
486
+ def _disable_custom_loss_ops():
487
+ for custom_op in customized_loss_ops:
488
+ DTensor._op_dispatcher._custom_op_handlers.pop(custom_op)
tool_server/.venv/lib/python3.12/site-packages/torch/distributed/tensor/parallel/style.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Optional, Union
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
+ "PrepareModuleOutput",
27
+ ]
28
+
29
+
30
+ class ParallelStyle(ABC):
31
+ """
32
+ The parallel style contract defines how the module or submodule should be parallelized.
33
+
34
+ It only defines the ``apply`` method for ``parallelize_module`` to use, this allows maximum
35
+ flexibility for different kind of style implementations.
36
+ """
37
+
38
+ src_data_rank: Optional[int] = 0
39
+
40
+ @abstractmethod
41
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module: ...
42
+
43
+
44
+ class ColwiseParallel(ParallelStyle):
45
+ """
46
+ Partition a compatible nn.Module in a column-wise fashion. Currently supports nn.Linear and nn.Embedding.
47
+ Users can compose it together with RowwiseParallel to achieve the sharding of more complicated modules.
48
+ (i.e. MLP, Attention)
49
+
50
+ Keyword Args:
51
+ input_layouts (Placement, optional):
52
+ The DTensor layout of input tensor for the nn.Module, this is used to annotate the input tensor to
53
+ become a DTensor. If not specified, we assume the input tensor to be replicated.
54
+ output_layouts (Placement, optional):
55
+ The DTensor layout of the output for the nn.Module, this is used to ensure the output of the nn.Module
56
+ with the user desired layout. If not specified, the output tensor is sharded on the last dimension.
57
+ use_local_output (bool, optional):
58
+ Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: True.
59
+ Returns:
60
+ A :class:`ParallelStyle` object that represents Colwise sharding of the nn.Module.
61
+
62
+ Example::
63
+ >>> # xdoctest: +SKIP(failing)
64
+ >>> from torch.distributed.tensor.parallel import parallelize_module, ColwiseParallel
65
+ >>> from torch.distributed.device_mesh import init_device_mesh
66
+ >>> ...
67
+ >>> m = Model(...) # m is a nn.Module that contains a "w1" nn.Linear submodule
68
+ >>> tp_mesh = init_device_mesh("cuda", (8,))
69
+ >>>
70
+ >>> # By default, the input of the "w1" Linear will be converted to Replicated DTensor
71
+ >>> # and the output of "w1" will return :class:`torch.Tensor` that shards on the last dim.
72
+ >>>
73
+ >>> sharded_mod = parallelize_module(m, tp_mesh, {"w1": ColwiseParallel()})
74
+ >>> ...
75
+
76
+ .. note:: By default ``ColwiseParallel`` output is sharded on the last dimension if the ``output_layouts`` not
77
+ specified, if there're operators that require specific tensor shape (i.e. before the paired ``RowwiseParallel``),
78
+ keep in mind that if the output is sharded the operator might need to be adjusted to the sharded size.
79
+ """
80
+
81
+ def __init__(
82
+ self,
83
+ *,
84
+ input_layouts: Optional[Placement] = None,
85
+ output_layouts: Optional[Placement] = None,
86
+ use_local_output: bool = True,
87
+ ):
88
+ super().__init__()
89
+ self.input_layouts = (input_layouts or Replicate(),)
90
+ self.output_layouts = (output_layouts or Shard(-1),)
91
+ # colwise linear runtime sharding (desired sharding):
92
+ # 1. requires replicate input
93
+ # 2. shard output on last dim
94
+ self.desired_input_layouts = (Replicate(),)
95
+ self.use_local_output = use_local_output
96
+
97
+ @staticmethod
98
+ def _prepare_input_fn(
99
+ input_layouts, desired_input_layouts, mod, inputs, device_mesh
100
+ ):
101
+ # TODO: figure out dynamo support for instance method and switch this to instance method
102
+
103
+ # annotate module input placements/sharding with input_layouts
104
+ input_tensor = inputs[0]
105
+ if not isinstance(input_tensor, DTensor):
106
+ input_tensor = DTensor.from_local(
107
+ input_tensor, device_mesh, input_layouts, run_check=False
108
+ )
109
+
110
+ # transform the input layouts to the desired layouts of ColwiseParallel
111
+ if input_layouts != desired_input_layouts:
112
+ input_tensor = input_tensor.redistribute(
113
+ placements=desired_input_layouts, async_op=True
114
+ )
115
+ return input_tensor
116
+
117
+ def _partition_linear_fn(self, name, module, device_mesh):
118
+ # colwise shard weight/bias to Shard(0), weight be Shard(0)
119
+ # means Colwise as Linear is input * weight^T + bias, where
120
+ # weight would become Shard(1)
121
+ for name, param in module.named_parameters():
122
+ dist_param = nn.Parameter(
123
+ distribute_tensor(
124
+ param, device_mesh, [Shard(0)], src_data_rank=self.src_data_rank
125
+ )
126
+ )
127
+ module.register_parameter(name, dist_param)
128
+
129
+ def _partition_embedding_fn(self, name, module, device_mesh):
130
+ # colwise shard embedding.weight is straight forward as Shard(1)
131
+ for name, param in module.named_parameters():
132
+ dist_param = nn.Parameter(
133
+ distribute_tensor(
134
+ param, device_mesh, [Shard(1)], src_data_rank=self.src_data_rank
135
+ )
136
+ )
137
+ module.register_parameter(name, dist_param)
138
+
139
+ @staticmethod
140
+ def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh):
141
+ # outputs is a shard on last dimension DTensor, i.e. Shard(-1)
142
+ if outputs.placements != output_layouts:
143
+ outputs = outputs.redistribute(placements=output_layouts, async_op=True)
144
+ # back to local tensor
145
+ return outputs.to_local() if use_local_output else outputs
146
+
147
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
148
+ if isinstance(module, nn.Linear):
149
+ partition_fn = self._partition_linear_fn
150
+ elif isinstance(module, nn.Embedding):
151
+ partition_fn = self._partition_embedding_fn
152
+ else:
153
+ raise NotImplementedError(
154
+ "ColwiseParallel currently only support nn.Linear and nn.Embedding!"
155
+ )
156
+
157
+ return distribute_module(
158
+ module,
159
+ device_mesh,
160
+ partition_fn,
161
+ partial(
162
+ self._prepare_input_fn, self.input_layouts, self.desired_input_layouts
163
+ ),
164
+ partial(
165
+ self._prepare_output_fn, self.output_layouts, self.use_local_output
166
+ ),
167
+ )
168
+
169
+
170
+ class RowwiseParallel(ParallelStyle):
171
+ """
172
+ Partition a compatible nn.Module in a row-wise fashion. Currently supports nn.Linear and nn.Embedding.
173
+ Users can compose it with ColwiseParallel to achieve the sharding of more complicated modules.
174
+ (i.e. MLP, Attention)
175
+
176
+ Keyword Args:
177
+ input_layouts (Placement, optional):
178
+ The DTensor layout of input tensor for the nn.Module, this is used to annotate the input tensor to
179
+ become a DTensor. If not specified, we assume the input tensor to be sharded on the last dimension.
180
+ output_layouts (Placement, optional):
181
+ The DTensor layout of the output for the nn.Module, this is used to ensure the output of the nn.Module
182
+ with the user desired layout. If not specified, the output tensor is replicated.
183
+ use_local_output (bool, optional):
184
+ Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: True.
185
+ Returns:
186
+ A :class:`ParallelStyle` object that represents Rowwise sharding of the nn.Module.
187
+
188
+ Example::
189
+ >>> # xdoctest: +SKIP(failing)
190
+ >>> from torch.distributed.tensor.parallel import parallelize_module, RowwiseParallel
191
+ >>> from torch.distributed.device_mesh import init_device_mesh
192
+ >>> ...
193
+ >>> m = Model(...) # m is a nn.Module that contains a "w2" nn.Linear submodule
194
+ >>> tp_mesh = init_device_mesh("cuda", (8,))
195
+ >>>
196
+ >>> # By default, the input of the "w2" Linear will be converted to DTensor that shards on the last dim
197
+ >>> # and the output of "w2" will return a replicated :class:`torch.Tensor`.
198
+ >>>
199
+ >>> sharded_mod = parallelize_module(m, tp_mesh, {"w2": RowwiseParallel()}),
200
+ >>> ...
201
+ """
202
+
203
+ def __init__(
204
+ self,
205
+ *,
206
+ input_layouts: Optional[Placement] = None,
207
+ output_layouts: Optional[Placement] = None,
208
+ use_local_output: bool = True,
209
+ ):
210
+ super().__init__()
211
+ self.input_layouts = (input_layouts or Shard(-1),)
212
+ self.output_layouts = (output_layouts or Replicate(),)
213
+ self.use_local_output = use_local_output
214
+
215
+ @staticmethod
216
+ def _prepare_input_fn(
217
+ input_layouts, desired_input_layouts, mod, inputs, device_mesh
218
+ ):
219
+ input_tensor = inputs[0]
220
+ if not isinstance(input_tensor, DTensor):
221
+ input_tensor = DTensor.from_local(
222
+ input_tensor, device_mesh, input_layouts, run_check=False
223
+ )
224
+
225
+ if input_layouts != desired_input_layouts:
226
+ input_tensor = input_tensor.redistribute(
227
+ placements=desired_input_layouts, async_op=True
228
+ )
229
+ return input_tensor
230
+
231
+ def _partition_linear_fn(self, name, module, device_mesh):
232
+ # Rowwise shard weight to Shard(1), bias to Replicate(), weight be Shard(1)
233
+ # means Rowwise as nn.Linear is input * weight^T + bias, where
234
+ # weight would become Shard(0)
235
+ module.register_parameter(
236
+ "weight",
237
+ nn.Parameter(
238
+ distribute_tensor(
239
+ module.weight,
240
+ device_mesh,
241
+ [Shard(1)],
242
+ src_data_rank=self.src_data_rank,
243
+ )
244
+ ),
245
+ )
246
+ if getattr(module, "bias", None) is not None:
247
+ # The Linear module has bias
248
+ module.register_parameter(
249
+ "bias",
250
+ nn.Parameter(
251
+ distribute_tensor(
252
+ module.bias,
253
+ device_mesh,
254
+ [Replicate()],
255
+ src_data_rank=self.src_data_rank,
256
+ )
257
+ ),
258
+ )
259
+
260
+ def _partition_embedding_fn(self, name, module, device_mesh):
261
+ # rowwise shard embedding.weight is Shard(0)
262
+ for name, param in module.named_parameters():
263
+ dist_param = nn.Parameter(
264
+ distribute_tensor(
265
+ param, device_mesh, [Shard(0)], src_data_rank=self.src_data_rank
266
+ )
267
+ )
268
+ module.register_parameter(name, dist_param)
269
+
270
+ @staticmethod
271
+ def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh):
272
+ # Rowwise sharding produces partial output, depending on output layouts:
273
+ # 1. to replicate -> allreduce
274
+ # 2. to shard -> reduce_scatter
275
+ if outputs.placements != output_layouts:
276
+ outputs = outputs.redistribute(placements=output_layouts, async_op=True)
277
+ # back to local tensor if use_local_output is True
278
+ return outputs.to_local() if use_local_output else outputs
279
+
280
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
281
+ if isinstance(module, nn.Linear):
282
+ partition_fn = self._partition_linear_fn
283
+ # rowwise linear runtime sharding requires input tensor shard on last dim
284
+ self.desired_input_layouts: tuple[Placement, ...] = (Shard(-1),)
285
+ elif isinstance(module, nn.Embedding):
286
+ partition_fn = self._partition_embedding_fn
287
+ # rowwise embedding runtime sharding requires input tensor replicated
288
+ self.desired_input_layouts = (Replicate(),)
289
+ else:
290
+ raise NotImplementedError(
291
+ "RowwiseParallel currently only support nn.Linear and nn.Embedding!"
292
+ )
293
+
294
+ return distribute_module(
295
+ module,
296
+ device_mesh,
297
+ partition_fn,
298
+ partial(
299
+ self._prepare_input_fn, self.input_layouts, self.desired_input_layouts
300
+ ),
301
+ partial(
302
+ self._prepare_output_fn, self.output_layouts, self.use_local_output
303
+ ),
304
+ )
305
+
306
+
307
+ class SequenceParallel(ParallelStyle):
308
+ """
309
+ SequenceParallel replicates a compatible ``nn.Module`` parameters and runs the sharded computation with
310
+ input sharded on the sequence dimension. This currently supports ``nn.LayerNorm``, ``nn.Dropout``, and the
311
+ `RMSNorm python implementation <https://github.com/facebookresearch/llama/blob/main/llama/model.py#L34>`__
312
+
313
+ This style implements the operation that is described in the paper
314
+ `Reducing Activation Recomputation in Large Transformer Models <https://arxiv.org/abs/2205.05198>`__
315
+
316
+ If the input passed in to this ``nn.Module`` is a :class:`torch.Tensor`, it assumes that the input is already sharded
317
+ on the sequence dimension and converts the input to a :class:`DTensor` sharded on the sequence dimension. If the input
318
+ passed in to this ``nn.Module`` is already a :class:`DTensor` but is not sharded on the sequence dimension, it would
319
+ redistribute the input to be sharded on the sequence dimension.
320
+
321
+ The output of the ``nn.Module`` will be sharded on the sequence dimension.
322
+
323
+ Keyword Args:
324
+ sequence_dim (int, optional):
325
+ The sequence dimension of the input tensor for the ``nn.Module``, this is used to annotate the input tensor to
326
+ become a DTensor that is sharded on the sequence dimension, default: 1.
327
+ use_local_output (bool, optional):
328
+ Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: False.
329
+ Returns:
330
+ A :class:`ParallelStyle` object that represents Sequence Parallel of the ``nn.Module``.
331
+
332
+ Example::
333
+ >>> # xdoctest: +SKIP(failing)
334
+ >>> from torch.distributed.tensor.parallel import parallelize_module, SequenceParallel
335
+ >>> from torch.distributed.device_mesh import init_device_mesh
336
+ >>> ...
337
+ >>> m = Model(...) # m is a nn.Module that contains a "norm" nn.LayerNorm submodule
338
+ >>> tp_mesh = init_device_mesh("cuda", (8,))
339
+ >>>
340
+ >>> # By default, the input of the "norm" will be converted to DTensor that shards on the sequence dim
341
+ >>> # and the output of "norm" will return a sharded on sequence dimension :class:`DTensor`.
342
+ >>>
343
+ >>> sharded_mod = parallelize_module(m, tp_mesh, {"norm": SequenceParallel()}),
344
+ >>> ...
345
+
346
+ .. note:: SequenceParallel style assumes ones initialization if there are weights in the nn.Module (i.e.
347
+ ``nn.LayerNorm`` or ``RMSNorm``, and they by default have ones initialization). If you have custom
348
+ inits for the weights on those modules, you need to broadcast the weights before/after parallelizing
349
+ to ensure that they are replicated.
350
+ """
351
+
352
+ def __init__(self, *, sequence_dim: int = 1, use_local_output: bool = False):
353
+ super().__init__()
354
+ self.sequence_sharding = (Shard(sequence_dim),)
355
+ self.use_local_output = use_local_output
356
+
357
+ def _replicate_module_fn(
358
+ self, name: str, module: nn.Module, device_mesh: DeviceMesh
359
+ ):
360
+ for p_name, param in module.named_parameters():
361
+ # simple replication with fixed ones_ init from LayerNorm/RMSNorm, which allow
362
+ # us to simply just use from_local
363
+ replicated_param = torch.nn.Parameter(
364
+ DTensor.from_local(param, device_mesh, [Replicate()], run_check=False)
365
+ )
366
+ module.register_parameter(p_name, replicated_param)
367
+
368
+ @staticmethod
369
+ def _prepare_input_fn(sequence_sharding, mod, inputs, device_mesh):
370
+ input_tensor = inputs[0]
371
+ if isinstance(input_tensor, DTensor):
372
+ # if the passed in input DTensor is not sharded on the sequence dim, we need to redistribute it
373
+ if input_tensor.placements != sequence_sharding:
374
+ input_tensor = input_tensor.redistribute(
375
+ placements=sequence_sharding, async_op=True
376
+ )
377
+ return input_tensor
378
+ elif isinstance(input_tensor, torch.Tensor):
379
+ # assume the input passed in already sharded on the sequence dim and create the DTensor
380
+ return DTensor.from_local(
381
+ input_tensor, device_mesh, sequence_sharding, run_check=False
382
+ )
383
+ else:
384
+ raise ValueError(
385
+ f"expecting input of {mod} to be a torch.Tensor or DTensor, but got {input_tensor}"
386
+ )
387
+
388
+ @staticmethod
389
+ def _prepare_output_fn(use_local_output, mod, outputs, device_mesh):
390
+ return outputs.to_local() if use_local_output else outputs
391
+
392
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
393
+ return distribute_module(
394
+ module,
395
+ device_mesh,
396
+ self._replicate_module_fn,
397
+ partial(self._prepare_input_fn, self.sequence_sharding),
398
+ partial(self._prepare_output_fn, self.use_local_output),
399
+ )
400
+
401
+
402
+ class PrepareModuleInput(ParallelStyle):
403
+ """
404
+ Configure the nn.Module's inputs to convert the input tensors of the nn.Module to DTensors at runtime according to
405
+ ``input_layouts``, and perform layout redistribution according to the ``desired_input_layouts``.
406
+
407
+ Keyword Args:
408
+ input_layouts (Union[Placement, Tuple[Optional[Placement]]]):
409
+ The DTensor layouts of input tensors for the nn.Module, this is used to convert the input tensors to
410
+ DTensors. If some inputs are not torch.Tensor or no need to convert to DTensors, ``None`` need to be specified
411
+ as a placeholder. default: None.
412
+ desired_input_layouts (Union[Placement, Tuple[Optional[Placement]]]):
413
+ The desired DTensor layout of input tensors for the nn.Module, this is used to ensure the inputs of the nn.Module
414
+ have the desired DTensor layouts. This argument needs to have the same length with ``input_layouts``. default: None.
415
+ input_kwarg_layouts (Dict[str, Placement]):
416
+ The DTensor layouts of input kwargs for the nn.Module, this is used to convert the input kwarg tensors to DTensors.
417
+ default: None
418
+ desired_input_kwarg_layouts: (Dict[str, Placement]):
419
+ The desired DTensor layout of input kwargs for the nn.Module, this is used to ensure the inputs of the nn.Module
420
+ have the desired DTensor layouts. default: None.
421
+ use_local_output (bool, optional):
422
+ Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module inputs, default: False.
423
+ Returns:
424
+ A :class:`ParallelStyle` object that prepares the sharding layouts of the nn.Module's inputs.
425
+
426
+ Example::
427
+ >>> # xdoctest: +SKIP(failing)
428
+ >>> from torch.distributed.tensor.parallel import parallelize_module, PrepareModuleInput
429
+ >>> from torch.distributed.device_mesh import init_device_mesh
430
+ >>> ...
431
+ >>> block = TransformerBlock(...) # block is a nn.Module that contains an "attn" Attention submodule
432
+ >>> tp_mesh = init_device_mesh("cuda", (8,))
433
+ >>>
434
+ >>> # According to the style specified below, the first input of attn will be annotated to Sharded DTensor
435
+ >>> # and then redistributed to Replicated DTensor.
436
+ >>> parallelize_module(
437
+ >>> block, # this can be a submodule or module
438
+ >>> tp_mesh,
439
+ >>> parallelize_plan={
440
+ >>> "attn": PrepareModuleInput(
441
+ >>> input_layouts=(Shard(0), None, None, ...),
442
+ >>> desired_input_layouts=(Replicate(), None, None, ...)
443
+ >>> ),
444
+ >>> }
445
+ >>> )
446
+ """
447
+
448
+ def __init__(
449
+ self,
450
+ *,
451
+ input_layouts: Optional[Union[Placement, tuple[Optional[Placement]]]] = None,
452
+ desired_input_layouts: Optional[
453
+ Union[Placement, tuple[Optional[Placement]]]
454
+ ] = None,
455
+ input_kwarg_layouts: Optional[dict[str, Placement]] = None,
456
+ desired_input_kwarg_layouts: Optional[dict[str, Placement]] = None,
457
+ use_local_output: bool = False,
458
+ ):
459
+ self.input_layouts = (
460
+ (input_layouts,) if isinstance(input_layouts, Placement) else input_layouts
461
+ )
462
+ self.desired_input_layouts = (
463
+ (desired_input_layouts,)
464
+ if isinstance(desired_input_layouts, Placement)
465
+ else desired_input_layouts
466
+ )
467
+ self.use_local_output = use_local_output
468
+ if self.input_layouts is not None:
469
+ assert self.desired_input_layouts is not None, (
470
+ "desired module inputs should not be None!"
471
+ )
472
+ assert len(self.input_layouts) == len(self.desired_input_layouts), (
473
+ "input_layouts and desired_input_layouts should have same length!"
474
+ )
475
+ self.with_kwargs = input_kwarg_layouts is not None
476
+ self.input_kwarg_layouts = input_kwarg_layouts or {}
477
+ self.desired_input_kwarg_layouts = desired_input_kwarg_layouts or {}
478
+ if self.with_kwargs:
479
+ assert len(self.input_kwarg_layouts) == len(
480
+ self.desired_input_kwarg_layouts
481
+ ), (
482
+ "input_kwarg_layouts and desired_input_kwarg_layouts should have same length!"
483
+ )
484
+
485
+ def _prepare_input_arg(
486
+ self,
487
+ input: Any,
488
+ mesh: DeviceMesh,
489
+ input_layout: Optional[Placement],
490
+ desired_layout: Optional[Placement],
491
+ ):
492
+ if input_layout is not None:
493
+ if isinstance(input, DTensor):
494
+ # TODO: re-enable the check once we fix the compile path
495
+ # assert inp.placements[0] == input_layout
496
+ dt_inp = input
497
+ else:
498
+ assert isinstance(input, torch.Tensor), (
499
+ "expecting input to be a torch.Tensor!"
500
+ )
501
+ dt_inp = DTensor.from_local(
502
+ input, mesh, (input_layout,), run_check=False
503
+ )
504
+
505
+ if desired_layout is not None and input_layout != desired_layout:
506
+ dt_inp = dt_inp.redistribute(placements=(desired_layout,))
507
+
508
+ return dt_inp.to_local() if self.use_local_output else dt_inp
509
+ else:
510
+ return input
511
+
512
+ def _prepare_input_fn(self, inputs, device_mesh):
513
+ if self.input_layouts is None:
514
+ return inputs
515
+ prepared_inputs = []
516
+ if not isinstance(inputs, tuple):
517
+ inputs = (inputs,)
518
+ if len(inputs) != len(self.input_layouts):
519
+ raise ValueError("module inputs and input_layouts should have same length!")
520
+
521
+ assert self.desired_input_layouts is not None, (
522
+ "desired module inputs should not be None!"
523
+ )
524
+ for inp, input_layout, desired_layout in zip(
525
+ inputs, self.input_layouts, self.desired_input_layouts
526
+ ):
527
+ prepared_inputs.append(
528
+ self._prepare_input_arg(inp, device_mesh, input_layout, desired_layout)
529
+ )
530
+ return tuple(prepared_inputs)
531
+
532
+ def _prepare_input_kwarg_fn(self, inputs, kwarg_inputs, device_mesh):
533
+ prepared_arg_inputs = self._prepare_input_fn(inputs, device_mesh)
534
+ prepared_kwarg_inputs = {}
535
+ for kwarg_key in kwarg_inputs.keys():
536
+ kwarg_val = kwarg_inputs[kwarg_key]
537
+ input_layout = self.input_kwarg_layouts.get(kwarg_key)
538
+ desired_input_layout = self.desired_input_kwarg_layouts.get(kwarg_key)
539
+
540
+ prepared_kwarg_inputs[kwarg_key] = self._prepare_input_arg(
541
+ kwarg_val, device_mesh, input_layout, desired_input_layout
542
+ )
543
+
544
+ return (prepared_arg_inputs, prepared_kwarg_inputs)
545
+
546
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
547
+ if self.with_kwargs:
548
+ module.register_forward_pre_hook(
549
+ lambda _, inputs, kwargs: self._prepare_input_kwarg_fn(
550
+ inputs, kwargs, device_mesh
551
+ ),
552
+ with_kwargs=True,
553
+ ) # type: ignore[misc]
554
+ else:
555
+ module.register_forward_pre_hook(
556
+ lambda _, inputs: self._prepare_input_fn(inputs, device_mesh)
557
+ ) # type: ignore[misc, call-arg]
558
+ return module
559
+
560
+
561
+ class PrepareModuleOutput(ParallelStyle):
562
+ """
563
+ Configure the nn.Module's outputs to convert the output tensors of the nn.Module to DTensors at runtime according to
564
+ ``output_layouts``, and perform layout redistribution according to the ``desired_output_layouts``.
565
+
566
+ Keyword Args:
567
+ output_layouts (Union[Placement, Tuple[Placement]]):
568
+ The DTensor layouts of output tensors for the nn.Module, this is used to convert the output tensors to
569
+ DTensors if they are :class:`torch.Tensor`. If some outputs are not torch.Tensor or no need to convert to DTensors,
570
+ ``None`` need to be specified as a placeholder.
571
+ desired_output_layouts (Union[Placement, Tuple[Placement]]):
572
+ The desired DTensor layouts of output tensors for the nn.Module, this is used to ensure the outputs of the nn.Module
573
+ have the desired DTensor layouts.
574
+ use_local_output (bool, optional):
575
+ Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module outputs, default: True.
576
+ Returns:
577
+ A ParallelStyle object that prepares the sharding layouts of the nn.Module's outputs.
578
+
579
+ Example::
580
+ >>> # xdoctest: +SKIP(failing)
581
+ >>> from torch.distributed.tensor.parallel import parallelize_module, PrepareModuleOutput
582
+ >>> from torch.distributed.device_mesh import init_device_mesh
583
+ >>> ...
584
+ >>> block = TransformerBlock(...) # block is a nn.Module that contains an "attn" Attention submodule
585
+ >>> tp_mesh = init_device_mesh("cuda", (8,))
586
+ >>>
587
+ >>> # According to the style specified below, the output of the TransformerBlock will be converted to Replicated DTensor
588
+ >>> # and then redistributed to Sharded DTensor.
589
+ >>> parallelize_module(
590
+ >>> block, # this can be a submodule or module
591
+ >>> tp_mesh,
592
+ >>> parallelize_plan = PrepareModuleOutput(
593
+ >>> output_layouts=Replicate(),
594
+ >>> desired_output_layouts=Shard(0)
595
+ >>> )
596
+ >>> )
597
+ """
598
+
599
+ def __init__(
600
+ self,
601
+ *,
602
+ output_layouts: Union[Placement, tuple[Placement]],
603
+ desired_output_layouts: Union[Placement, tuple[Placement]],
604
+ use_local_output: bool = True,
605
+ ):
606
+ self.output_layouts = (
607
+ (output_layouts,)
608
+ if isinstance(output_layouts, Placement)
609
+ else output_layouts
610
+ )
611
+ self.desired_output_layouts = (
612
+ (desired_output_layouts,)
613
+ if isinstance(desired_output_layouts, Placement)
614
+ else desired_output_layouts
615
+ )
616
+ self.use_local_output = use_local_output
617
+ assert len(self.output_layouts) == len(self.desired_output_layouts), (
618
+ "output_layouts and desired_output_layouts should have same length!"
619
+ )
620
+
621
+ def _prepare_out_fn(self, outputs, device_mesh):
622
+ prepared_outputs = []
623
+ if not isinstance(outputs, tuple):
624
+ outputs = (outputs,)
625
+ if len(outputs) != len(self.output_layouts):
626
+ raise ValueError(
627
+ "module outputs and output_layouts should have same length!"
628
+ )
629
+ for out, out_layout, desired_out_layout in zip(
630
+ outputs, self.output_layouts, self.desired_output_layouts
631
+ ):
632
+ if out_layout is not None:
633
+ if isinstance(out, DTensor):
634
+ # TODO: re-enable the check once we fix the compile path
635
+ # assert out.placements[0] == out_layout
636
+ dt_out = out
637
+ else:
638
+ dt_out = DTensor.from_local(
639
+ out, device_mesh, (out_layout,), run_check=False
640
+ )
641
+
642
+ if out_layout != desired_out_layout:
643
+ dt_out = dt_out.redistribute(placements=(desired_out_layout,))
644
+ prepared_outputs.append(
645
+ dt_out.to_local() if self.use_local_output else dt_out
646
+ )
647
+ else:
648
+ prepared_outputs.append(out)
649
+ if len(prepared_outputs) == 1:
650
+ return prepared_outputs[0]
651
+ else:
652
+ return tuple(prepared_outputs)
653
+
654
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
655
+ module.register_forward_hook(
656
+ lambda _, inputs, outputs: self._prepare_out_fn(outputs, device_mesh)
657
+ ) # type: ignore[misc, call-arg]
658
+ return module
tool_server/.venv/lib/python3.12/site-packages/torch/distributions/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (6.12 kB). View file