assassinlike commited on
Commit
5aa4cf4
·
verified ·
1 Parent(s): 73ef0fd

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. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/__init__.cpython-310.pyc +0 -0
  2. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/_checkpointable.cpython-310.pyc +0 -0
  3. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/_composable_state.cpython-310.pyc +0 -0
  4. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/_functional_collectives.cpython-310.pyc +0 -0
  5. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/_functional_collectives_impl.cpython-310.pyc +0 -0
  6. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/_serialization.cpython-310.pyc +0 -0
  7. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/_state_dict_utils.cpython-310.pyc +0 -0
  8. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/argparse_util.cpython-310.pyc +0 -0
  9. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/c10d_logger.cpython-310.pyc +0 -0
  10. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/collective_utils.cpython-310.pyc +0 -0
  11. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/constants.cpython-310.pyc +0 -0
  12. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/device_mesh.cpython-310.pyc +0 -0
  13. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/launch.cpython-310.pyc +0 -0
  14. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/logging_handlers.cpython-310.pyc +0 -0
  15. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/remote_device.cpython-310.pyc +0 -0
  16. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/rendezvous.cpython-310.pyc +0 -0
  17. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/run.cpython-310.pyc +0 -0
  18. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/utils.cpython-310.pyc +0 -0
  19. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/__init__.py +1 -0
  20. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/_utils.py +32 -0
  21. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/api.py +306 -0
  22. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/common_op_utils.py +65 -0
  23. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/metadata.py +64 -0
  24. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/op_registry_utils.py +41 -0
  25. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/sharder.py +29 -0
  26. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_sharded_tensor/__init__.py +21 -0
  27. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_symmetric_memory/__init__.py +1730 -0
  28. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_symmetric_memory/_nvshmem_triton.py +181 -0
  29. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/algorithms/__init__.py +1 -0
  30. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/algorithms/join.py +348 -0
  31. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/__init__.py +16 -0
  32. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_async_process_executor.py +330 -0
  33. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_async_thread_executor.py +39 -0
  34. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_checkpointer.py +100 -0
  35. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_dedup_tensors.py +62 -0
  36. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_fsspec_filesystem.py +167 -0
  37. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_hf_utils.py +105 -0
  38. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_nested_dict.py +69 -0
  39. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_sharded_tensor_utils.py +107 -0
  40. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_state_dict_stager.py +354 -0
  41. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_storage_utils.py +49 -0
  42. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_traverse.py +198 -0
  43. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_version.py +6 -0
  44. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/api.py +42 -0
  45. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/default_planner.py +669 -0
  46. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/hf_storage.py +334 -0
  47. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/logger.py +118 -0
  48. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/logging_handlers.py +14 -0
  49. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/metadata.py +184 -0
  50. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/optimizer.py +357 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (4.52 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/_checkpointable.cpython-310.pyc ADDED
Binary file (1.76 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/_composable_state.cpython-310.pyc ADDED
Binary file (1.51 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/_functional_collectives.cpython-310.pyc ADDED
Binary file (32.6 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/_functional_collectives_impl.cpython-310.pyc ADDED
Binary file (2.61 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/_serialization.cpython-310.pyc ADDED
Binary file (4.82 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/_state_dict_utils.cpython-310.pyc ADDED
Binary file (21.3 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/argparse_util.cpython-310.pyc ADDED
Binary file (3.95 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/c10d_logger.cpython-310.pyc ADDED
Binary file (3.12 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/collective_utils.cpython-310.pyc ADDED
Binary file (5.58 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/constants.cpython-310.pyc ADDED
Binary file (564 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/device_mesh.cpython-310.pyc ADDED
Binary file (31.8 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/launch.cpython-310.pyc ADDED
Binary file (7.84 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/logging_handlers.cpython-310.pyc ADDED
Binary file (371 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/remote_device.cpython-310.pyc ADDED
Binary file (3.8 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/rendezvous.cpython-310.pyc ADDED
Binary file (8.81 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/run.cpython-310.pyc ADDED
Binary file (27.2 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/__pycache__/utils.cpython-310.pyc ADDED
Binary file (12.3 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .api import _shard_tensor, load_with_process_group, shard_module, shard_parameter
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/_utils.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence
2
+
3
+ import torch
4
+ from torch.distributed._shard.metadata import ShardMetadata
5
+
6
+
7
+ DEPRECATE_MSG = "Please use DTensor instead and we are deprecating ShardedTensor."
8
+
9
+
10
+ def narrow_tensor_by_index(
11
+ tensor: torch.Tensor,
12
+ offsets: Sequence[int],
13
+ sizes: Sequence[int],
14
+ ) -> torch.Tensor:
15
+ """
16
+ Narrow the tensor according to ``offsets`` and ``sizes``.
17
+ """
18
+ narrowed_tensor = tensor
19
+ for idx, (offset, size) in enumerate(zip(offsets, sizes)):
20
+ if size < tensor.size(idx):
21
+ # Reshape to get shard for this rank and we don't want autograd
22
+ # recording here for the narrow op and 'local_shard' should be a
23
+ # leaf variable in the autograd graph.
24
+ narrowed_tensor = narrowed_tensor.narrow(idx, offset, size)
25
+ return narrowed_tensor
26
+
27
+
28
+ def narrow_tensor(tensor: torch.Tensor, metadata: ShardMetadata) -> torch.Tensor:
29
+ """
30
+ Narrow the tensor according to the metadata
31
+ """
32
+ return narrow_tensor_by_index(tensor, metadata.shard_offsets, metadata.shard_sizes)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/api.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from contextlib import contextmanager
3
+ from typing import Optional
4
+
5
+ import torch
6
+ import torch.distributed as dist
7
+ import torch.nn as nn
8
+ from torch.distributed import distributed_c10d
9
+ from torch.distributed._shard.sharded_tensor import ShardedTensor
10
+
11
+ from .sharder import Sharder
12
+ from .sharding_plan import ShardingPlan
13
+ from .sharding_spec import ChunkShardingSpec, ShardingSpec
14
+
15
+
16
+ def _shard_tensor(
17
+ tensor: torch.Tensor, sharding_spec: ShardingSpec, src_rank=0, process_group=None
18
+ ) -> ShardedTensor:
19
+ """
20
+ Given a :class:`torch.Tensor`, it shards that tensor according to the provided
21
+ ``sharding_spec``. ``src_rank`` denotes the source rank which would be
22
+ used as the ground truth of the data which would be scattered as shards
23
+ across the rest of the ranks.
24
+
25
+ Args:
26
+ tensor (:class:`torch.Tensor`): Tensor needs to be sharded.
27
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
28
+ describing how to shard the Tensor.
29
+
30
+ Keyword args:
31
+ src_rank (int, optional): The source rank which is used as the ground truth of
32
+ the data for the parameter that would be sharded and scattered
33
+ across the rest of the ranks.
34
+ Default: 0.
35
+ process_group (ProcessGroup, optional): The process group to work on. If None,
36
+ the default process group will be used.
37
+
38
+ Returns:
39
+ A :class:`ShardedTensor` sharded from the given tensor.
40
+
41
+ .. warning::
42
+ Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is
43
+ currently supported as the ``sharding_spec``.
44
+ """
45
+ if not tensor.is_contiguous():
46
+ raise ValueError("input tensor is not a contiguous Tensor")
47
+
48
+ pg = (
49
+ process_group
50
+ if process_group is not None
51
+ else distributed_c10d._get_default_group()
52
+ )
53
+ world_size = dist.get_world_size(pg)
54
+ current_rank = dist.get_rank(pg)
55
+
56
+ # Validate src_rank and sharding_spec are same across all ranks.
57
+ gathered_list = [None] * world_size
58
+ dist.all_gather_object(gathered_list, (src_rank, sharding_spec), group=pg)
59
+
60
+ for idx, entry in enumerate(gathered_list):
61
+ if src_rank != entry[0]: # type: ignore[index]
62
+ raise ValueError(
63
+ f"src_rank={src_rank} on rank: {current_rank} does not " # type: ignore[index]
64
+ f"match with src_rank={entry[0]} on rank: {idx}" # type: ignore[index]
65
+ )
66
+ if sharding_spec != entry[1]: # type: ignore[index]
67
+ raise ValueError(
68
+ f"sharding_spec={sharding_spec} on rank: {current_rank} does not " # type: ignore[index]
69
+ f"match with sharding_spec={entry[1]} on rank: {idx}" # type: ignore[index]
70
+ )
71
+
72
+ st = sharding_spec.shard(tensor, src_rank=src_rank, process_group=pg)
73
+
74
+ return st
75
+
76
+
77
+ def shard_parameter(
78
+ module: torch.nn.Module,
79
+ param_name: str,
80
+ sharding_spec: ShardingSpec,
81
+ src_rank=0,
82
+ process_group=None,
83
+ ):
84
+ """
85
+ Given a :class:`torch.nn.Module`, a ``param_name`` for a parameter in that
86
+ module, it shards that parameter according to the provided
87
+ ``sharding_spec``. ``src_rank`` denotes the source rank which would be
88
+ used as the ground truth of the data which would be scattered as shards
89
+ across the rest of the ranks.
90
+
91
+ This method replaces ``module.param_name`` with a
92
+ :class:`torch.distributed._sharded_tensor.ShardedTensor`
93
+
94
+ Args:
95
+ module (:class:`torch.nn.Module`): Module whose parameter needs to be sharded.
96
+ param_name (str): Name of the parameter of ``module`` that needs to be sharded.
97
+ sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
98
+ describing how to shard the Tensor.
99
+
100
+ Keyword args:
101
+ src_rank (int, optional): The source rank which is used as the ground truth of
102
+ the data for the parameter that would be sharded and scattered
103
+ across the rest of the ranks.
104
+ Default: 0.
105
+ process_group (ProcessGroup, optional): The process group to work on. If None,
106
+ the default process group will be used.
107
+
108
+ .. warning::
109
+ Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is
110
+ currently supported as the ``sharding_spec``.
111
+ """
112
+ # Perform some validation first.
113
+ if not hasattr(module, param_name):
114
+ raise AttributeError(f"{module._get_name()} has no attribute `{param_name}`")
115
+
116
+ tensor = getattr(module, param_name)
117
+ if not isinstance(tensor, torch.Tensor):
118
+ raise ValueError(
119
+ f"Expected {type(module).__name__}.{param_name} to be a Tensor, but found {type(tensor).__name__}"
120
+ )
121
+
122
+ if not tensor.is_contiguous():
123
+ raise ValueError(f"param: {param_name} is not a contiguous Tensor")
124
+
125
+ st = _shard_tensor(tensor, sharding_spec, src_rank, process_group)
126
+
127
+ # Replace param with ShardedTensor.
128
+ module.register_parameter(param_name, nn.Parameter(st))
129
+
130
+
131
+ # Tracks the current process group in the load context manager.
132
+ _CURRENT_PROCESS_GROUP: Optional[dist.ProcessGroup] = None
133
+
134
+
135
+ @contextmanager
136
+ def load_with_process_group(process_group):
137
+ """
138
+ Context manager to set the process group with which to load a ShardedTensor.
139
+ """
140
+ global _CURRENT_PROCESS_GROUP
141
+ if _CURRENT_PROCESS_GROUP is not None:
142
+ raise RuntimeError(
143
+ 'ProcessGroup already set by previous "load_with_process_group" '
144
+ "context manager"
145
+ )
146
+ _CURRENT_PROCESS_GROUP = process_group
147
+ try:
148
+ yield process_group
149
+ finally:
150
+ _CURRENT_PROCESS_GROUP = None
151
+
152
+
153
+ def _get_current_process_group():
154
+ """
155
+ Retrieves the current process group set by ``load_with_process_group``.
156
+ If not set, it just returns the default group.
157
+ """
158
+ global _CURRENT_PROCESS_GROUP
159
+ if _CURRENT_PROCESS_GROUP is None:
160
+ return distributed_c10d._get_default_group()
161
+ else:
162
+ return _CURRENT_PROCESS_GROUP
163
+
164
+
165
+ def _reshard_output(
166
+ module: torch.nn.Module, resharding_spec: ShardingSpec
167
+ ) -> torch.nn.Module:
168
+ """
169
+ Hook a module with output resharding in the forward pass according
170
+ to the given ``resharding_spec``.
171
+
172
+ Args:
173
+ module (:class:`torch.nn.Module`): Module whose output needs to be resharded.
174
+ resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`):
175
+ The specification describing how the output of the module will be resharded.
176
+
177
+ Returns:
178
+ A :class:`torch.nn.Module` object with reshard API hooked.
179
+ """
180
+
181
+ def hook_func(_module, _input, output):
182
+ if isinstance(output, ShardedTensor):
183
+ return output.reshard(resharding_spec)
184
+ return output
185
+
186
+ module.register_forward_hook(hook_func)
187
+ return module
188
+
189
+
190
+ def _collect_local_shard(module: torch.nn.Module) -> torch.nn.Module:
191
+ """
192
+ Hook a module with local shards collection in the forward pass.
193
+
194
+ This API is typically used to convert a sharded representation back to data parallel
195
+ representation. In particular, it returns the local tensor for this Shard. If the
196
+ size along the sharding dimension for the local tensor is 1, this dimension is removed
197
+ from the final result. For example a [4, 16] ShardedTensor across 4 ranks is typically
198
+ a local Tensor of size [16] across each rank and not [1, 16] across each rank.
199
+
200
+ Args:
201
+ module (:class:`torch.nn.Module`): Module whose output is ShardedTensor and the
202
+ local tensor value needs to be returned.
203
+
204
+ Returns:
205
+ A :class:`torch.nn.Module` object with collection API hooked.
206
+ """
207
+
208
+ def hook_func(_module, _input, output):
209
+ if isinstance(output, ShardedTensor):
210
+ local_tensor = output.local_tensor()
211
+ # Squeeze the # of dimensions manually, only applicable to ChunkShardingSpec
212
+ sharding_spec = output._sharding_spec
213
+ if (
214
+ isinstance(sharding_spec, ChunkShardingSpec)
215
+ and local_tensor.size(sharding_spec.dim) == 1 # type: ignore[attr-defined, arg-type]
216
+ ):
217
+ local_tensor = local_tensor.squeeze(
218
+ output._sharding_spec.dim # type: ignore[attr-defined]
219
+ )
220
+ return local_tensor
221
+
222
+ module.register_forward_hook(hook_func)
223
+ return module
224
+
225
+
226
+ def shard_module(module: nn.Module, plan: ShardingPlan, src_rank=0, process_group=None):
227
+ """
228
+ Shards a given module according to the provided sharding `plan`. This method
229
+ first shards all the parameters according to the given sharding `plan`. Then if
230
+ `output_plan` and `return_local_tensor` are specified in the sharding `plan`, it
231
+ will tag the output of modules according `output_plan`, convert the module's
232
+ output back to data parallel according to `return_local_tensor`.
233
+
234
+ Needs to be called on all ranks in an SPMD fashion.
235
+
236
+ Args:
237
+ module (:class:`torch.nn.Module`): The module to apply sharding to
238
+ plan (:class:`torch.distributed._shard.sharding_plan.ShardingPlan`):
239
+ The ShardingPlan which specified param name to ShardingSpec to apply to
240
+ each parameter.
241
+
242
+ Keyword args:
243
+ src_rank (int, optional): The source rank which is used as the ground truth of
244
+ the data for the module that would be sharded and scattered across the rest
245
+ of the ranks.
246
+ Default: 0.
247
+ process_group (ProcessGroup, optional): The process group to work on. If None,
248
+ the default process group will be used.
249
+ """
250
+ # record Sharder paths for sanity check on the plan to ensure items in the plan
251
+ # does not conflict with the submodule tree that the Sharder is working with
252
+ sharder_paths = []
253
+ for name, spec in plan.plan.items():
254
+ if isinstance(spec, Sharder):
255
+ sharder_paths.append(name)
256
+
257
+ # shard the parameter according to the ShardingPlan
258
+ for name, spec in plan.plan.items():
259
+ if isinstance(spec, ShardingSpec):
260
+ # if found a sharding spec, try to shard the parameter
261
+ module_path, _, param_name = name.rpartition(".")
262
+
263
+ for sharder_path in sharder_paths:
264
+ if module_path.startswith(sharder_path):
265
+ raise RuntimeError(
266
+ f"ShardingPlan is in-valid, trying to shard a parameter: {name},"
267
+ f" but there's already a Sharder entry for module {sharder_path},"
268
+ f" parameter sharding should not conflict with the submodule tree"
269
+ f" that a Sharder is working with!"
270
+ )
271
+
272
+ mod = module.get_submodule(module_path)
273
+ shard_parameter(
274
+ mod, param_name, spec, src_rank=src_rank, process_group=process_group
275
+ )
276
+ elif isinstance(spec, Sharder):
277
+ parent_mod_path, _, _mod_name = name.rpartition(".")
278
+ if name == "":
279
+ raise KeyError("Module path must not be empty for custom sharder!")
280
+ mod = module.get_submodule(name)
281
+ parent_mod = module.get_submodule(parent_mod_path)
282
+ sharded_mod = spec.shard(mod)
283
+ # swap this submodule with the sharded module
284
+ parent_mod.mod_name = sharded_mod
285
+ else:
286
+ raise TypeError(
287
+ f"Only `ShardingSpec` and `Sharder` are supported to shard '{name}'"
288
+ )
289
+
290
+ # reshard output if there's an entry in `reshard_output` for this module
291
+ if plan.output_plan is not None:
292
+ for module_path, output_spec in plan.output_plan.items():
293
+ if isinstance(output_spec, ShardingSpec):
294
+ mod = module.get_submodule(module_path)
295
+ _reshard_output(mod, output_spec)
296
+ else:
297
+ raise TypeError(
298
+ f"Only `ShardingSpec` is supported as output_plan for '{module_path}'"
299
+ )
300
+ # convert the output back to data parallel for the modules appears in
301
+ # `return_local_tensor` of the plan, we will call `_collect_local_shard`
302
+ # to collect the local tensor for output of modules
303
+ if plan.return_local_tensor is not None:
304
+ for module_path in plan.return_local_tensor:
305
+ mod = module.get_submodule(module_path)
306
+ _collect_local_shard(mod)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/common_op_utils.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Optional
3
+
4
+ import torch
5
+ from torch.utils import _pytree as pytree
6
+
7
+
8
+ def _basic_validation(op, args=(), kwargs=None):
9
+ """
10
+ Common validation across all ops go in here.
11
+ """
12
+ from torch.distributed._shard.sharded_tensor import ShardedTensor
13
+
14
+ if len(args) == 0 and (kwargs is None or len(kwargs) == 0):
15
+ raise ValueError(f" No input for '{op.__name__}'!")
16
+
17
+ # Validate types
18
+ has_distributed_tensor = False
19
+
20
+ def is_distributed_tensor(e):
21
+ nonlocal has_distributed_tensor
22
+ if isinstance(e, ShardedTensor):
23
+ has_distributed_tensor = True
24
+
25
+ pytree.tree_map_(is_distributed_tensor, args)
26
+ pytree.tree_map_(is_distributed_tensor, kwargs)
27
+
28
+ if not has_distributed_tensor:
29
+ raise TypeError(
30
+ f"torch function '{op.__name__}', with args: {args} and "
31
+ f"kwargs: {kwargs} are called without any distributed tensor!"
32
+ )
33
+
34
+ # Validate all distributed tensors use the same PG.
35
+ cur_pg: Optional[torch.distributed.ProcessGroup] = None
36
+
37
+ def validate_pg(e):
38
+ nonlocal cur_pg
39
+ if isinstance(e, ShardedTensor):
40
+ if cur_pg is not None and e._process_group is not cur_pg:
41
+ raise RuntimeError(
42
+ "All distributed tensors should use the "
43
+ "same ProcessGroup if used together in an op."
44
+ )
45
+ cur_pg = e._process_group
46
+
47
+ pytree.tree_map_(validate_pg, args)
48
+ pytree.tree_map_(validate_pg, kwargs)
49
+
50
+
51
+ def _register_default_op(op, decorator):
52
+ @decorator(op)
53
+ def tensor_default_op(types, args=(), kwargs=None, pg=None):
54
+ """
55
+ Handles ``__torch_function__`` dispatch for the default tensor ops that
56
+ behave the same as ``torch.Tensor`` such as ``torch.Tensor.shape`` or
57
+ ``torch.Tensor.dtype``. We simply lower to the real op call with
58
+ DisableTorchFunctionSubclass context like ``torch.Tensor.__torch_function__``
59
+ to avoid recursions.
60
+ """
61
+ if kwargs is None:
62
+ kwargs = {}
63
+
64
+ with torch._C.DisableTorchFunctionSubclass():
65
+ return op(*args, **kwargs)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/metadata.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from dataclasses import dataclass
3
+ from functools import reduce
4
+ from typing import Optional, Union
5
+
6
+ from torch.distributed.remote_device import _remote_device
7
+
8
+
9
+ @dataclass
10
+ class ShardMetadata:
11
+ """
12
+ Represents a shard of the overall Tensor including its
13
+ offsets, lengths and device placement.
14
+
15
+ Args:
16
+ shard_offsets(List[int]): Offsets in the original tensor indicating
17
+ the start offsets for this shard. Should have the same rank as
18
+ the original tensor.
19
+ shard_sizes(List[int]): Integers indicating the size of each
20
+ dimension for this shard. Should have the same rank as the
21
+ original tensor.
22
+ placement(:class:`torch.distributed._remote_device`):
23
+ Specifies the placement of this shard.
24
+ """
25
+
26
+ __slots__ = ["shard_offsets", "shard_sizes", "placement"]
27
+
28
+ shard_offsets: list[int]
29
+ shard_sizes: list[int]
30
+ placement: Optional[_remote_device]
31
+
32
+ def __init__(
33
+ self,
34
+ shard_offsets: list[int],
35
+ shard_sizes: list[int],
36
+ placement: Optional[Union[str, _remote_device]] = None,
37
+ ):
38
+ self.shard_offsets = shard_offsets
39
+ self.shard_sizes = shard_sizes
40
+ if isinstance(placement, str):
41
+ self.placement = _remote_device(placement)
42
+ else:
43
+ self.placement = placement
44
+ if len(self.shard_offsets) != len(self.shard_sizes):
45
+ raise ValueError(
46
+ f"shard_offsets and shard_sizes should have "
47
+ f"the same number of elements, found {len(self.shard_offsets)} "
48
+ f"and {self.shard_sizes} respectively"
49
+ )
50
+
51
+ for i in range(len(self.shard_offsets)):
52
+ if self.shard_offsets[i] < 0:
53
+ raise ValueError("shard_offsets should be >=0")
54
+ if self.shard_sizes[i] < 0:
55
+ raise ValueError("shard_sizes should be >= 0")
56
+
57
+ def __hash__(self):
58
+ def _hash_reduce(a, b):
59
+ return (a << 8) + hash(b)
60
+
61
+ res = reduce(_hash_reduce, self.shard_offsets, 37)
62
+ res = reduce(_hash_reduce, self.shard_sizes, res)
63
+ res = _hash_reduce(res, self.placement)
64
+ return res
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/op_registry_utils.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ from inspect import signature
4
+
5
+ from .common_op_utils import _basic_validation
6
+
7
+
8
+ """
9
+ Common utilities to register ops on ShardedTensor
10
+ and PartialTensor.
11
+ """
12
+
13
+
14
+ def _register_op(op, func, op_table):
15
+ """
16
+ Performs basic validation and registers the provided op in the given
17
+ op_table.
18
+ """
19
+ if len(signature(func).parameters) != 4:
20
+ raise TypeError(
21
+ f"Custom sharded op function expects signature: "
22
+ f"(types, args, kwargs, process_group), but received "
23
+ f"signature: {signature(func)}"
24
+ )
25
+
26
+ op_table[op] = func
27
+
28
+
29
+ def _decorator_func(wrapped_func, op, op_table):
30
+ """
31
+ Decorator function to register the given ``op`` in the provided
32
+ ``op_table``
33
+ """
34
+
35
+ @functools.wraps(wrapped_func)
36
+ def wrapper(types, args, kwargs, process_group):
37
+ _basic_validation(op, args, kwargs)
38
+ return wrapped_func(types, args, kwargs, process_group)
39
+
40
+ _register_op(op, wrapper, op_table)
41
+ return wrapper
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_shard/sharder.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+
3
+ import torch.nn as nn
4
+
5
+
6
+ class Sharder(abc.ABC):
7
+ """
8
+ This is an interface which allows user to create more advanced
9
+ sharding strategies that are not easily be composed by the
10
+ `ShardingSpec`.
11
+
12
+ :class:`torch.distributed._shard.sharding_plan.ShardingPlan` could
13
+ take an object of the `Sharder` and call `shard` to shard the module,
14
+ then replace the original module with sharded module returned.
15
+ """
16
+
17
+ @abc.abstractmethod
18
+ def shard(self, module: nn.Module) -> nn.Module:
19
+ """
20
+ Shard a module base on the implementation of this method, and
21
+ return the sharded version of the module.
22
+
23
+ Args:
24
+ module (:class:`torch.nn.Module`):
25
+ The module to apply sharding to.
26
+ Returns:
27
+ A :class:`torch.nn.Module` object that represents a module
28
+ that's already been sharded.
29
+ """
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_sharded_tensor/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Keep old package for BC purposes, this file should be removed once
2
+ # everything moves to the `torch.distributed._shard` package.
3
+ import sys
4
+ import warnings
5
+
6
+ import torch
7
+ from torch.distributed._shard.sharded_tensor import * # noqa: F403
8
+
9
+
10
+ with warnings.catch_warnings():
11
+ warnings.simplefilter("always")
12
+ warnings.warn(
13
+ "`torch.distributed._sharded_tensor` will be deprecated, "
14
+ "use `torch.distributed._shard.sharded_tensor` instead",
15
+ DeprecationWarning,
16
+ stacklevel=2,
17
+ )
18
+
19
+ sys.modules["torch.distributed._sharded_tensor"] = (
20
+ torch.distributed._shard.sharded_tensor
21
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_symmetric_memory/__init__.py ADDED
@@ -0,0 +1,1730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import socket
4
+ import uuid
5
+ from collections.abc import Generator
6
+ from contextlib import contextmanager
7
+ from datetime import timedelta
8
+ from enum import Enum
9
+ from functools import partial
10
+ from typing import Any, Callable, Optional
11
+
12
+ import torch
13
+ import torch.distributed._functional_collectives as funcol
14
+ import torch.distributed.distributed_c10d as c10d
15
+ from torch._C._autograd import DeviceType
16
+ from torch._C._distributed_c10d import _SymmetricMemory, Work as _Work
17
+
18
+
19
+ _group_name_to_store: dict[str, c10d.Store] = {}
20
+
21
+
22
+ def enable_symm_mem_for_group(group_name: str) -> None:
23
+ """
24
+ Enables symmetric memory for a process group.
25
+
26
+ Args:
27
+ group_name (str): the name of the process group.
28
+ """
29
+ if group_name in _group_name_to_store:
30
+ return
31
+
32
+ group = c10d._resolve_process_group(group_name)
33
+ global_ranks = sorted(c10d._world.pg_group_ranks[group].keys())
34
+ # Different subgroups with the same name should use different stores
35
+ global_ranks_str = "_".join(map(str, global_ranks))
36
+ store = c10d.PrefixStore(
37
+ f"symmetric_memory-{global_ranks_str}",
38
+ c10d._get_process_group_store(group),
39
+ )
40
+ _group_name_to_store[group_name] = store
41
+ _SymmetricMemory.set_group_info(
42
+ group_name,
43
+ group.rank(),
44
+ group.size(),
45
+ store,
46
+ )
47
+
48
+
49
+ _is_test_mode: bool = False
50
+ _mocked_group_names: Optional[set[str]] = None
51
+
52
+
53
+ @contextmanager
54
+ def _test_mode(group_names: Optional[set[str]] = None) -> Generator[None, None, None]:
55
+ """
56
+ Forces ``is_symm_mem_enabled_for_group()`` to return ``True`` and the ops
57
+ defined in the ``symm_mem`` namespace to use fallback implementations.
58
+
59
+ The context manager is not thread safe.
60
+ """
61
+ global _is_test_mode
62
+ global _mocked_group_names
63
+ prev = _is_test_mode
64
+ prev_group_names = _mocked_group_names
65
+ try:
66
+ _is_test_mode = True
67
+ _mocked_group_names = group_names
68
+ yield
69
+ finally:
70
+ _is_test_mode = prev
71
+ _mocked_group_names = prev_group_names
72
+
73
+
74
+ def is_symm_mem_enabled_for_group(group_name: str) -> bool:
75
+ """
76
+ Check if symmetric memory is enabled for a process group.
77
+
78
+ Args:
79
+ group_name (str): the name of the process group.
80
+ """
81
+ if _is_test_mode:
82
+ return _mocked_group_names is None or group_name in _mocked_group_names
83
+ return group_name in _group_name_to_store
84
+
85
+
86
+ _group_name_to_workspace_tensor: dict[str, Optional[torch.Tensor]] = {}
87
+
88
+
89
+ def get_symm_mem_workspace(group_name: str, min_size: int) -> _SymmetricMemory:
90
+ """
91
+ Get the symmetric memory workspace associated with the process group. If
92
+ ``min_size`` is greater than the workspace associated with ``group_name``,
93
+ the workspace will be re-allocated and re-rendezvous'd.
94
+
95
+ Args:
96
+ group_name (str): the name of the process group.
97
+ min_size (int): the size requirement for the workspace in bytes.
98
+
99
+ Returns:
100
+ _SymmetricMemory: the symmetric memory workspace associated with the
101
+ group.
102
+ """
103
+ enable_symm_mem_for_group(group_name)
104
+
105
+ tensor = _group_name_to_workspace_tensor.get(group_name)
106
+ size = tensor.numel() * tensor.element_size() if tensor is not None else 0
107
+ if tensor is None or size < min_size:
108
+ if torch.cuda.is_current_stream_capturing():
109
+ curr_size = 0 if tensor is None else tensor.numel() * tensor.element_size()
110
+ raise RuntimeError(
111
+ f"get_symm_mem_workspace(): the requested size ({min_size} bytes) "
112
+ "is greater than the size of the currently allocated workspace "
113
+ f"({curr_size} bytes). It's currently not possible to expand the "
114
+ "workspace size during graph capture. Please invoke "
115
+ f'`get_symm_mem_workspace(group_name="{group_name}", '
116
+ f'min_size="{min_size}")` before initiating the graph capture '
117
+ "and try again."
118
+ )
119
+ tensor = _SymmetricMemory.empty_strided_p2p(
120
+ (max(size, min_size),),
121
+ [1],
122
+ torch.uint8,
123
+ torch.device(f"cuda:{torch.cuda.current_device()}"),
124
+ group_name,
125
+ )
126
+ _group_name_to_workspace_tensor[group_name] = tensor
127
+ return _SymmetricMemory.rendezvous(tensor)
128
+
129
+
130
+ _backend_streams: dict[int, torch.cuda.Stream] = {}
131
+
132
+
133
+ def _get_backend_stream(priority: int = 0) -> torch.cuda.Stream:
134
+ if priority not in _backend_streams:
135
+ _backend_streams[priority] = torch.cuda.Stream(priority=priority)
136
+ return _backend_streams[priority]
137
+
138
+
139
+ def _pipelined_multi_all_gather_and_consume(
140
+ shard: list[torch.Tensor],
141
+ shard_consumer: Callable[[list[torch.Tensor], int], None],
142
+ ag_out: list[torch.Tensor],
143
+ group_name: str,
144
+ ag_out_needed: bool = True,
145
+ ) -> None:
146
+ """
147
+ Perform the following logic with micro-pipelined computation and
148
+ communication:
149
+
150
+ gathered = [
151
+ all_gather_tensor(x, gather_dim=0, group=group)
152
+ for x in shard
153
+ ]
154
+
155
+ shards = [[] for _ in range(group_size)]
156
+ for x in ag_out:
157
+ for i, y in enumerate(x.chunk(group_size)):
158
+ shards[i].append(y)
159
+
160
+ for src_rank, shard in enumerate(shards):
161
+ shard_consumer(shard, src_rank)
162
+ """
163
+ p2p_workspace_size_req = 0
164
+ for x in shard:
165
+ p2p_workspace_size_req += x.numel() * x.element_size()
166
+ symm_mem = get_symm_mem_workspace(group_name, min_size=p2p_workspace_size_req)
167
+ group_size = symm_mem.world_size
168
+ rank = symm_mem.rank
169
+
170
+ symm_mem.barrier(channel=0)
171
+ backend_stream = _get_backend_stream()
172
+ backend_stream.wait_stream(torch.cuda.current_stream())
173
+
174
+ for x, y in zip(shard, ag_out):
175
+ assert x.is_contiguous(), (
176
+ "_pipelined_all_gather_and_consume: all tensors "
177
+ "in `shard` must be contiguous"
178
+ )
179
+ assert y.is_contiguous(), (
180
+ "_pipelined_all_gather_and_consume: all tensors "
181
+ "in `ag_out` must be contiguous"
182
+ )
183
+ assert x.shape[0] * group_size == y.shape[0]
184
+ assert x.shape[1:] == y.shape[1:]
185
+
186
+ def copy_shard(dst: list[torch.Tensor], src: list[torch.Tensor]) -> None:
187
+ for d, s in zip(dst, src):
188
+ d.copy_(s)
189
+
190
+ def get_p2p_bufs(remote_rank: int) -> list[torch.Tensor]:
191
+ offset_bytes = 0
192
+ bufs = []
193
+ for x in shard:
194
+ buf = symm_mem.get_buffer(
195
+ remote_rank,
196
+ x.shape,
197
+ x.dtype,
198
+ storage_offset=offset_bytes // x.element_size(),
199
+ )
200
+ bufs.append(buf)
201
+ offset_bytes += buf.numel() * buf.element_size()
202
+ return bufs
203
+
204
+ local_p2p_bufs = get_p2p_bufs(rank)
205
+
206
+ # shards[i] => shard from rank i
207
+ shards: list[list[torch.Tensor]] = [[] for _ in range(group_size)]
208
+ for x in ag_out:
209
+ for i, y in enumerate(x.chunk(group_size)):
210
+ shards[i].append(y)
211
+
212
+ # Parallelization strategy: after each rank copies its shard into its local
213
+ # p2p buffer, every rank issues independent p2p copy -> shard_consumer
214
+ # sequences to two streams. In addition to computation/communication
215
+ # overlapping, the strategy allows for computation/computation overlapping,
216
+ # greatly reducing quantization inefficiency.
217
+ #
218
+ # Notation:
219
+ # - "mv" for the copy to local buffer
220
+ # - "cp" for p2p copies
221
+ # - "b" for barriers
222
+ #
223
+ # Constraints:
224
+ # - The GPU scheduler may or may not overlap "mv" with the first shard_consumer.
225
+ # - "cp" from different streams cannot overlap.
226
+ #
227
+ # Ideal scenario 0 - "mv" overlaps with the first shard_consumer:
228
+ #
229
+ # stream 0: [ shard_consumer ][ cp ][ shard_consumer ]
230
+ # stream 1: [ mv ][b][ cp ][ shard_consumer ]
231
+ #
232
+ # Ideal scenario 1 - "mv" is scheduled before the first shard_consumer:
233
+ #
234
+ # stream 0: [ shard_consumer ][ cp ][ shard_consumer ]
235
+ # stream 1: [ mv ][b][ cp ][ shard_consumer ]
236
+ #
237
+ # Suboptimal scenario 0 - "mv" is scheduled after the first shard_consumer:
238
+ #
239
+ # stream 0: [ shard_consumer ] [ cp ][ shard_consumer ]
240
+ # stream 1: [ mv ][b][ cp ][ shard_consumer ]
241
+ #
242
+ # Suboptimal scenario 0 - "b" is scheduled after the first shard_consumer:
243
+ #
244
+ # stream 0: [ shard_consumer ] [ cp ][ shard_consumer ]
245
+ # stream 1: [ mv ] [b][ cp ][ shard_consumer ]
246
+ #
247
+ # We haven't yet figured out a way to ensure "mv" and "b" are either
248
+ # overlapped with or scheduled before the first shard_consumer. Thus, to
249
+ # prevent suboptimal scenarios, we are giving up the chance to overlap "mv"
250
+ # and "b" with the first shard_consumer for now.
251
+ copy_shard(dst=local_p2p_bufs, src=shard)
252
+ symm_mem.barrier(channel=1)
253
+ backend_stream.wait_stream(torch.cuda.current_stream())
254
+
255
+ # At this point, all ranks have copied their local shard to
256
+ # their local p2p buffer. Each rank can now copy and consume
257
+ # remote shards.
258
+ shard_consumer(shard, rank)
259
+
260
+ for step in range(1, group_size):
261
+ if step % 2 == 0:
262
+ stream = torch.cuda.current_stream()
263
+ else:
264
+ stream = backend_stream
265
+ remote_rank = (step + rank) % group_size
266
+ remote_p2p_bufs = get_p2p_bufs(remote_rank)
267
+ with stream:
268
+ copy_shard(dst=shards[remote_rank], src=remote_p2p_bufs)
269
+ shard_consumer(shards[remote_rank], remote_rank)
270
+
271
+ if ag_out_needed:
272
+ # Copy from input to the all-gather output. Opportunistically overlap
273
+ # it with the last shard_consumer.
274
+ if group_size % 2 == 0:
275
+ stream = torch.cuda.current_stream()
276
+ else:
277
+ stream = backend_stream
278
+ with stream:
279
+ copy_shard(dst=shards[rank], src=shard)
280
+
281
+ torch.cuda.current_stream().wait_stream(backend_stream)
282
+ symm_mem.barrier(channel=0)
283
+
284
+
285
+ def _pipelined_all_gather_and_consume(
286
+ shard: torch.Tensor,
287
+ shard_consumer: Callable[[torch.Tensor, int], None],
288
+ ag_out: torch.Tensor,
289
+ group_name: str,
290
+ ag_out_needed: bool = True,
291
+ ) -> None:
292
+ """
293
+ Perform the following logic with micro-pipelined computation and
294
+ communication:
295
+
296
+ ag_out = all_gather_tensor(shard, gather_dim=0, group=group)
297
+ shards = ag_out.chunk(group.size())
298
+ for src_rank, shard in enumerate(shards):
299
+ shard_consumer(shard, src_rank)
300
+ """
301
+
302
+ def adapter(shard: list[torch.Tensor], rank: int) -> None:
303
+ shard_consumer(shard[0], rank)
304
+
305
+ _pipelined_multi_all_gather_and_consume(
306
+ [shard],
307
+ adapter,
308
+ [ag_out],
309
+ group_name,
310
+ ag_out_needed,
311
+ )
312
+
313
+
314
+ def _pipelined_produce_and_all2all(
315
+ chunk_producer: Callable[[int, torch.Tensor], None],
316
+ output: torch.Tensor,
317
+ group_name: str,
318
+ ) -> None:
319
+ """
320
+ Perform the following logic with micro-pipelined computation and
321
+ communication:
322
+
323
+ chunks = [
324
+ chunk_producer(dst_rank, chunks[dst_rank])
325
+ for dst_rank in range(group_size):
326
+ ]
327
+ dist.all_to_all_single(output=output, input=torch.cat(chunks))
328
+ """
329
+ out_chunks = output.chunk(c10d._get_group_size_by_name(group_name))
330
+ p2p_workspace_size_req = out_chunks[0].numel() * out_chunks[0].element_size() * 2
331
+ symm_mem = get_symm_mem_workspace(group_name, min_size=p2p_workspace_size_req)
332
+ group_size = symm_mem.world_size
333
+ rank = symm_mem.rank
334
+
335
+ symm_mem.barrier(channel=0)
336
+ backend_stream = _get_backend_stream()
337
+ backend_stream.wait_stream(torch.cuda.current_stream())
338
+
339
+ def get_p2p_buf(rank: int, idx: int) -> torch.Tensor:
340
+ assert idx in (0, 1)
341
+ offset = 0 if idx == 0 else out_chunks[0].numel()
342
+ return symm_mem.get_buffer(
343
+ rank, out_chunks[0].shape, out_chunks[0].dtype, offset
344
+ )
345
+
346
+ # Prepare two local p2p buffers, so that a remote rank can pull the result
347
+ # of step [i] in one p2p buffer while the local rank can compute the
348
+ # result of step [i+1] and write it directly the other p2p buffer.
349
+ local_p2p_buf_0 = get_p2p_buf(rank, 0)
350
+ local_p2p_buf_1 = get_p2p_buf(rank, 1)
351
+
352
+ for step in range(1, group_size):
353
+ remote_rank = (rank - step) % group_size
354
+ if step % 2 == 0:
355
+ stream = torch.cuda.current_stream()
356
+ p2p_buf = local_p2p_buf_1
357
+ remote_p2p_buf = get_p2p_buf(remote_rank, 1)
358
+ else:
359
+ stream = backend_stream
360
+ p2p_buf = local_p2p_buf_0
361
+ remote_p2p_buf = get_p2p_buf(remote_rank, 0)
362
+ with stream:
363
+ # Parallelization strategy: every rank issues independent compute
364
+ # -> barrier -> p2p copy sequences on two streams. In addition to
365
+ # computation/communication overlapping, the strategy allows for
366
+ # computation/computation overlapping, greatly reducing
367
+ # quantization inefficiency.
368
+ #
369
+ # Ideally, stream activities would look like this ("b" for
370
+ # barriers, "cp" for p2p copies):
371
+ #
372
+ # [rank 0]
373
+ # stream 0: [ chunk_producer ][b][ cp ][ chunk_producer ][b][ cp ]
374
+ # stream 1: [ chunk_producer ][b][ cp ][ chunk_producer ][b][ cp ]
375
+ #
376
+ # [rank 1]
377
+ # stream 0: [ chunk_producer ][b][ cp ][ chunk_producer ][b][ cp ]
378
+ # stream 1: [ chunk_producer ][b][ cp ][ chunk_producer ][b][ cp ]
379
+ #
380
+ # Note that the barriers synchronize streams with the same ID
381
+ # across ranks. They don't synchronize streams on the same rank.
382
+ #
383
+ # Since the work on both streams is independent, there's no
384
+ # guarantee that the chunk_producer from stream 0 or stream 1 will
385
+ # be scheduled first. If there is a scheduling mismatch across
386
+ # ranks, the barrier forces all ranks to wait for the slowest.
387
+ #
388
+ # When scheduling mismatches occur among ranks, the stream
389
+ # activities might look like this (note that p2p copies from
390
+ # different streams cannot overlap with each other):
391
+ #
392
+ # [rank 0]
393
+ # stream 0: [ chunk_producer ][b ][ cp ][ chunk_producer ][b ][ cp ]
394
+ # stream 1: [ chunk_producer ][b] [ cp ][ chunk_producer ][b] [ cp ]
395
+ #
396
+ # [rank 1]
397
+ # stream 0: [ chunk_producer ][b] [ cp ][ chunk_producer ][b] [ cp ]
398
+ # stream 1: [ chunk_producer ][b ][ cp ][ chunk_producer ][b ][ cp ]
399
+ #
400
+ # To prevent this, we need to ensure that the chunk_producer on
401
+ # stream 1 gets scheduled first on every rank. Without access to
402
+ # the underlying kernels, CUDA offers no API to control the
403
+ # scheduling order of two independent, overlapping kernels. Our
404
+ # solution is to issue a small sleep kernel in stream 0. The sleep
405
+ # duration is insignificant, but having an extra task in stream 0
406
+ # will almost guarantee that the chunk_producer on stream 1 gets
407
+ # scheduled first. Once the first chunk_producer is scheduled in
408
+ # the correct order, there's very little room for the scheduling
409
+ # order of subsequent kernels to be inconsistent across ranks.
410
+ if step == 2:
411
+ torch.cuda._sleep(100)
412
+ chunk_producer((rank + step) % group_size, p2p_buf)
413
+ symm_mem.barrier(channel=step % 2)
414
+ out_chunks[remote_rank].copy_(remote_p2p_buf)
415
+ # The local P2P buffer can only be overwritten by the next
416
+ # chunk_producer after all peers have finished reading from it.
417
+ symm_mem.barrier(channel=step % 2)
418
+
419
+ # If the sleep wasn't issued in the above loop, do it now.
420
+ if group_size == 2:
421
+ torch.cuda._sleep(100)
422
+
423
+ chunk_producer(rank, out_chunks[rank])
424
+ torch.cuda.current_stream().wait_stream(backend_stream)
425
+ symm_mem.barrier(channel=0)
426
+
427
+
428
+ lib = torch.library.Library("symm_mem", "DEF") # noqa: TOR901
429
+ lib.define(
430
+ "fused_all_gather_matmul("
431
+ "Tensor A, Tensor[] Bs, int gather_dim, str group_name, *, bool return_A = True) -> (Tensor?, Tensor[])",
432
+ tags=[torch._C.Tag.needs_fixed_stride_order],
433
+ )
434
+ lib.define(
435
+ "fused_all_gather_scaled_matmul("
436
+ "Tensor A, Tensor[] Bs, Tensor A_scale, Tensor[] B_scales, "
437
+ "int gather_dim, str group_name, "
438
+ "Tensor?[] biases, "
439
+ "Tensor?[] result_scales, "
440
+ "ScalarType?[] out_dtypes, "
441
+ "bool[] use_fast_accum) -> (Tensor, Tensor[])",
442
+ tags=[torch._C.Tag.needs_fixed_stride_order],
443
+ )
444
+ lib.define(
445
+ "fused_matmul_reduce_scatter(Tensor A, Tensor B, str reduce_op, int scatter_dim, str group_name) -> Tensor",
446
+ tags=[torch._C.Tag.needs_fixed_stride_order],
447
+ )
448
+ lib.define(
449
+ "fused_scaled_matmul_reduce_scatter("
450
+ "Tensor A, Tensor B, Tensor A_scale, Tensor B_scale, "
451
+ "str reduce_op, int orig_scatter_dim, int scatter_dim_after_maybe_reshape, str group_name, int[]? output_shape, "
452
+ "Tensor? bias = None, "
453
+ "Tensor? result_scale = None, "
454
+ "ScalarType? out_dtype = None, "
455
+ "bool use_fast_accum = False) -> Tensor",
456
+ tags=[torch._C.Tag.needs_fixed_stride_order],
457
+ )
458
+ lib.define("_low_contention_all_gather(Tensor tensor, str group_name) -> Tensor")
459
+ lib.define(
460
+ "_low_contention_reduce_scatter(Tensor tensor, str reduce_op, str group_name) -> Tensor"
461
+ )
462
+
463
+
464
+ class _ScaleMode(Enum):
465
+ UNSCALED = "unscaled"
466
+ TENSOR_WISE = "tensor-wise"
467
+ ROW_WISE_SHARDED = "row-wise-sharded"
468
+ ROW_WISE_REPLICATED = "row-wise-replicated"
469
+
470
+
471
+ def _check_and_verify_fp8_all_gather_scale_mode(
472
+ shard: torch.Tensor, scale: Optional[torch.Tensor], gather_dim: int, group_size: int
473
+ ) -> _ScaleMode:
474
+ full_shape = list(shard.shape)
475
+ full_shape[gather_dim] *= group_size
476
+
477
+ if scale is None:
478
+ return _ScaleMode.UNSCALED
479
+ elif scale.shape[:-1] == shard.shape[:-1] and scale.shape[-1] == 1:
480
+ # Row-wise scaling
481
+ #
482
+ # NOTE: when the last dim of both A_shard and A_scale is one, we can't
483
+ # tell if A_scale is replicated tensor-wise scale or sharded row-wise
484
+ # scale. Treating it as row-wise scaling for safety.
485
+ return _ScaleMode.ROW_WISE_SHARDED
486
+ elif scale.numel() == 1:
487
+ return _ScaleMode.TENSOR_WISE
488
+ elif list(scale.shape[:-1]) == full_shape[:-1]:
489
+ return _ScaleMode.ROW_WISE_REPLICATED
490
+ else:
491
+ raise ValueError(
492
+ "Invalid scale shape for fp8 all-gather "
493
+ f"(shard shape: {shard.shape}, scale shape: {scale.shape})"
494
+ )
495
+
496
+
497
+ def _fused_all_gather_matmul_impl(
498
+ mm_out_op: torch._ops.OpOverload,
499
+ A_shard: torch.Tensor,
500
+ Bs: list[torch.Tensor],
501
+ A_scale: Optional[torch.Tensor],
502
+ kwargs_list: list[dict[str, Any]],
503
+ out_dtypes: list[Optional[torch.dtype]],
504
+ gather_dim: int,
505
+ group_name: str,
506
+ return_A: bool,
507
+ ) -> tuple[Optional[torch.Tensor], list[torch.Tensor]]:
508
+ if A_shard.dim() < 2:
509
+ raise ValueError("A_shard must be a matrix")
510
+ for B in Bs:
511
+ if B.dim() != 2:
512
+ raise ValueError("B must be a matrix")
513
+ if len(out_dtypes) != len(Bs):
514
+ raise ValueError("len(out_types) must be the same as len(Bs)")
515
+ if len(kwargs_list) != len(Bs):
516
+ raise ValueError("len(kwargs_list) must be the same as len(Bs)")
517
+ if gather_dim < 0 or gather_dim >= A_shard.dim():
518
+ raise ValueError("Invalid gather_dim")
519
+
520
+ group = c10d._resolve_process_group(group_name)
521
+
522
+ # Move the gather_dim to the front and flatten the tensor into a 2D matrix.
523
+ # The flattened tensor doesn't need to be contiguous (for computation
524
+ # efficiency), as _pipelined_all_gather_and_consume guarantees that shards
525
+ # passed to shard_consumer are contiguous.
526
+ A_shard_flat = A_shard.movedim(gather_dim, 0)
527
+ leading_dims = [group.size()] + list(A_shard_flat.shape[:-1])
528
+ A_shard_flat = A_shard_flat.flatten(0, -2)
529
+
530
+ # Helper function for reverting the above transformation
531
+ def unflatten(t: torch.Tensor) -> torch.Tensor:
532
+ return t.view(*leading_dims, -1).flatten(0, 1).movedim(0, gather_dim)
533
+
534
+ A_flat = A_shard_flat.new_empty(
535
+ A_shard_flat.shape[0] * group.size(),
536
+ A_shard_flat.shape[1],
537
+ )
538
+
539
+ outputs = [
540
+ A_flat.new_empty(A_flat.shape[0], B.shape[1], dtype=out_dtype or B.dtype)
541
+ for B, out_dtype in zip(Bs, out_dtypes)
542
+ ]
543
+ output_shards = [output.chunk(group.size()) for output in outputs]
544
+
545
+ scale_mode = _check_and_verify_fp8_all_gather_scale_mode(
546
+ shard=A_shard, scale=A_scale, gather_dim=gather_dim, group_size=group.size()
547
+ )
548
+
549
+ # Computing block-wise matmul along the first dim of A
550
+ if scale_mode == _ScaleMode.ROW_WISE_SHARDED:
551
+ assert A_scale is not None
552
+ A_scale_shard = A_scale.movedim(gather_dim, 0).flatten(0, -2)
553
+ A_scale_flat = A_scale_shard.new_empty(
554
+ A_scale_shard.shape[0] * group.size(),
555
+ A_scale_shard.shape[1],
556
+ )
557
+
558
+ def row_wise_sharded_consumer(shard: list[torch.Tensor], rank: int) -> None:
559
+ for idx, (B, kwargs) in enumerate(zip(Bs, kwargs_list)):
560
+ mm_out_op(
561
+ shard[0],
562
+ B,
563
+ scale_a=shard[1],
564
+ **kwargs,
565
+ out=output_shards[idx][rank],
566
+ )
567
+
568
+ _pipelined_multi_all_gather_and_consume(
569
+ [A_shard_flat, A_scale_shard],
570
+ row_wise_sharded_consumer,
571
+ [A_flat, A_scale_flat],
572
+ group_name,
573
+ return_A,
574
+ )
575
+ elif scale_mode == _ScaleMode.ROW_WISE_REPLICATED:
576
+ assert A_scale is not None
577
+ A_scale_shards = (
578
+ A_scale.movedim(gather_dim, 0).flatten(0, -2).chunk(group.size())
579
+ )
580
+
581
+ def row_wise_replicated_consumer(shard: torch.Tensor, rank: int) -> None:
582
+ for idx, (B, kwargs) in enumerate(zip(Bs, kwargs_list)):
583
+ mm_out_op(
584
+ shard,
585
+ B,
586
+ scale_a=A_scale_shards[rank],
587
+ **kwargs,
588
+ out=output_shards[idx][rank],
589
+ )
590
+
591
+ _pipelined_all_gather_and_consume(
592
+ A_shard_flat,
593
+ row_wise_replicated_consumer,
594
+ A_flat,
595
+ group_name,
596
+ return_A,
597
+ )
598
+ else:
599
+ if scale_mode == _ScaleMode.TENSOR_WISE:
600
+ assert A_scale is not None
601
+ for kwargs in kwargs_list:
602
+ kwargs["scale_a"] = A_scale
603
+ else:
604
+ assert scale_mode == _ScaleMode.UNSCALED
605
+
606
+ def default_consumer(shard: torch.Tensor, rank: int) -> None:
607
+ for idx, (B, kwargs) in enumerate(zip(Bs, kwargs_list)):
608
+ mm_out_op(shard, B, **kwargs, out=output_shards[idx][rank])
609
+
610
+ _pipelined_all_gather_and_consume(
611
+ A_shard_flat,
612
+ default_consumer,
613
+ A_flat,
614
+ group_name,
615
+ return_A,
616
+ )
617
+
618
+ A = unflatten(A_flat) if return_A else None
619
+ return A, [unflatten(output) for output in outputs]
620
+
621
+
622
+ @torch.library.impl(lib, "fused_all_gather_matmul", "Meta")
623
+ def _fused_all_gather_matmul_fallback(
624
+ A_shard: torch.Tensor,
625
+ Bs: list[torch.Tensor],
626
+ gather_dim: int,
627
+ group_name: str,
628
+ *,
629
+ return_A: bool = True,
630
+ ) -> tuple[Optional[torch.Tensor], list[torch.Tensor]]:
631
+ group_size = c10d._get_group_size_by_name(group_name)
632
+ A = torch.ops._c10d_functional.all_gather_into_tensor(
633
+ A_shard.contiguous(), group_size, group_name
634
+ )
635
+ A = torch.ops._c10d_functional.wait_tensor(A)
636
+ A = A.view(group_size, *A_shard.shape).movedim(gather_dim + 1, 1).flatten(0, 1)
637
+ res = [torch.matmul(A, B).movedim(0, gather_dim) for B in Bs]
638
+ if return_A:
639
+ return A.movedim(0, gather_dim), res
640
+ else:
641
+ return None, res
642
+
643
+
644
+ @torch.library.impl(lib, "fused_all_gather_matmul", "CUDA")
645
+ def _fused_all_gather_matmul(
646
+ A_shard: torch.Tensor,
647
+ Bs: list[torch.Tensor],
648
+ gather_dim: int,
649
+ group_name: str,
650
+ *,
651
+ return_A: bool = True,
652
+ ) -> tuple[Optional[torch.Tensor], list[torch.Tensor]]:
653
+ """
654
+ Perform the following logic with micro-pipelined computation and
655
+ communication:
656
+
657
+ all_gather_tensor(A_shard, gather_dim, group_name) @ B
658
+
659
+ Optimal stride order for A_shard - if A_shard.movedim(gather_dim, 0) is
660
+ contiguous, no extra copy is required for input layout transformation.
661
+ Otherwise A_shard needs to be copied once.
662
+ """
663
+ if _is_test_mode:
664
+ return _fused_all_gather_matmul_fallback(
665
+ A_shard, Bs, gather_dim, group_name, return_A=return_A
666
+ )
667
+
668
+ if _should_use_fused_all_gather_matmul_native(A_shard, Bs, gather_dim, group_name):
669
+ group = c10d._resolve_process_group(group_name)
670
+ leading_dims = list(A_shard.shape[:-1])
671
+ leading_dims[0] *= group.size()
672
+ A, out = _fused_all_gather_matmul_native(
673
+ A_shard.flatten(0, -2), Bs[0], group_name
674
+ )
675
+ return A.view(*leading_dims, -1), [out.view(*leading_dims, -1)]
676
+
677
+ if _should_use_multimem_all_gather_matmul(
678
+ A_shard, gather_dim, group_name, return_A
679
+ ):
680
+ return None, _multimem_all_gather_matmul(A_shard, Bs, group_name)
681
+
682
+ with torch.profiler.record_function("fused_all_gather_matmul"):
683
+ return _fused_all_gather_matmul_impl(
684
+ torch.ops.aten.mm.out,
685
+ A_shard,
686
+ Bs,
687
+ None,
688
+ [{} for B in Bs],
689
+ [B.dtype for B in Bs],
690
+ gather_dim,
691
+ group_name,
692
+ return_A,
693
+ )
694
+
695
+
696
+ def _should_use_fused_all_gather_matmul_native(
697
+ A_shard: torch.Tensor,
698
+ Bs: list[torch.Tensor],
699
+ gather_dim: int,
700
+ group_name: str,
701
+ ) -> bool:
702
+ group = c10d._resolve_process_group(group_name)
703
+ local_M = math.prod(A_shard.shape[:-1])
704
+
705
+ return (
706
+ "TORCH_SYMM_MEM_ENABLE_NATIVE_ASYNC_TP" in os.environ
707
+ and A_shard.is_contiguous()
708
+ and gather_dim == 0
709
+ # _async_input_mm requires local_M to be divisible by world_size.
710
+ and local_M % group.size() == 0
711
+ # _async_input_mm outperforms the decomposition-based approach when the
712
+ # global M is small.
713
+ and 2048 < local_M * group.size() <= 4096
714
+ # _async_input_mm only supports a single B.
715
+ and len(Bs) == 1
716
+ )
717
+
718
+
719
+ def _fused_all_gather_matmul_native(
720
+ A_shard: torch.Tensor,
721
+ B: torch.Tensor,
722
+ group_name: str,
723
+ ) -> tuple[torch.Tensor, torch.Tensor]:
724
+ symm_mem = rendezvous(A_shard, group_name)
725
+ if symm_mem is None:
726
+ symm_mem = get_symm_mem_workspace(
727
+ group_name, A_shard.numel() * A_shard.element_size()
728
+ )
729
+ symm_mem.barrier()
730
+ buf = symm_mem.get_buffer(symm_mem.rank, A_shard.shape, A_shard.dtype)
731
+ buf.copy_(A_shard)
732
+ A_shard = buf
733
+
734
+ rank = symm_mem.rank
735
+ world_size = symm_mem.world_size
736
+
737
+ current_stream = torch.cuda.current_stream()
738
+ backend_stream = _get_backend_stream(priority=-1)
739
+
740
+ symm_mem.barrier()
741
+ backend_stream.wait_stream(current_stream)
742
+ current_stream.wait_stream(backend_stream)
743
+
744
+ A = A_shard.new_empty(A_shard.shape[0] * world_size, A_shard.shape[1])
745
+ A_signals = torch.zeros(world_size, dtype=torch.uint32, device=A_shard.device)
746
+ A_shards = A.chunk(world_size)
747
+
748
+ A_shards[rank].copy_(A_shard)
749
+ if not torch.cuda.is_current_stream_capturing():
750
+ _SymmetricMemory.stream_write_value32(A_signals, rank, 1)
751
+ else:
752
+ _SymmetricMemory.memset32(A_signals, offset=rank, val=1, count=1)
753
+
754
+ out = torch.ops.symm_mem._async_input_mm(A, B, A_signals, rank)
755
+ for step in range(1, world_size):
756
+ src_rank = (rank + step) % world_size
757
+ src_buf = symm_mem.get_buffer(src_rank, A_shard.shape, A_shard.dtype)
758
+ with backend_stream:
759
+ A_shards[src_rank].copy_(src_buf)
760
+ if not torch.cuda.is_current_stream_capturing():
761
+ # cuStreamWriteValue32 issues a system level fence before the write
762
+ _SymmetricMemory.stream_write_value32(A_signals, src_rank, 1)
763
+ else:
764
+ _SymmetricMemory.memset32(A_signals, offset=src_rank, val=1, count=1)
765
+
766
+ current_stream.wait_stream(backend_stream)
767
+ backend_stream.wait_stream(current_stream)
768
+
769
+ symm_mem.barrier()
770
+ return A, out
771
+
772
+
773
+ def _should_use_multimem_all_gather_matmul(
774
+ A_shard: torch.Tensor,
775
+ gather_dim: int,
776
+ group_name: str,
777
+ return_A: bool,
778
+ ) -> bool:
779
+ group = c10d._resolve_process_group(group_name)
780
+ local_M = math.prod(A_shard.shape[:-1])
781
+ has_multicast_support = (
782
+ A_shard.device.type == "cuda"
783
+ and _SymmetricMemory.has_multicast_support(
784
+ DeviceType.CUDA, A_shard.device.index
785
+ )
786
+ )
787
+
788
+ return (
789
+ has_multicast_support
790
+ and not return_A
791
+ and A_shard.is_contiguous()
792
+ and gather_dim == 0
793
+ # The heuristic is empirical. We could refine it with a more
794
+ # sophisticated perf model.
795
+ and local_M * group.size() <= 2048
796
+ )
797
+
798
+
799
+ def _multimem_all_gather_matmul(
800
+ A_shard: torch.Tensor,
801
+ Bs: list[torch.Tensor],
802
+ group_name: str,
803
+ ) -> list[torch.Tensor]:
804
+ group = c10d._resolve_process_group(group_name)
805
+ A_shape = torch.Size((A_shard.shape[0] * group.size(), *A_shard.shape[1:]))
806
+ symm_mem = get_symm_mem_workspace(
807
+ group_name, A_shape.numel() * A_shard.element_size()
808
+ )
809
+ A = symm_mem.get_buffer(symm_mem.rank, A_shape, A_shard.dtype)
810
+ torch.ops.symm_mem.multimem_all_gather_out(A_shard, group_name, A)
811
+ return [torch.matmul(A, B) for B in Bs]
812
+
813
+
814
+ @torch.library.impl(lib, "fused_all_gather_scaled_matmul", "Meta")
815
+ def _fused_all_gather_scaled_matmul_fallback(
816
+ A_shard: torch.Tensor,
817
+ Bs: list[torch.Tensor],
818
+ A_scale: torch.Tensor,
819
+ B_scales: list[torch.Tensor],
820
+ gather_dim: int,
821
+ group_name: str,
822
+ biases: list[Optional[torch.Tensor]],
823
+ result_scales: list[Optional[torch.Tensor]],
824
+ out_dtypes: list[Optional[torch.dtype]],
825
+ use_fast_accum: list[bool],
826
+ ) -> tuple[torch.Tensor, list[torch.Tensor]]:
827
+ out_dtypes = _maybe_convert_scalar_types_to_dtypes(out_dtypes)
828
+
829
+ group_size = c10d._get_group_size_by_name(group_name)
830
+ A = torch.ops._c10d_functional.all_gather_into_tensor(
831
+ A_shard.contiguous(), group_size, group_name
832
+ )
833
+ A = torch.ops._c10d_functional.wait_tensor(A)
834
+ A = A.view(group_size, *A_shard.shape).movedim(gather_dim + 1, 1).flatten(0, 1)
835
+
836
+ scale_mode = _check_and_verify_fp8_all_gather_scale_mode(
837
+ shard=A_shard, scale=A_scale, gather_dim=gather_dim, group_size=group_size
838
+ )
839
+ if scale_mode == _ScaleMode.ROW_WISE_SHARDED:
840
+ A_scale_shard = A_scale
841
+ A_scale = torch.ops._c10d_functional.all_gather_into_tensor(
842
+ A_scale.contiguous(), group_size, group_name
843
+ )
844
+ A_scale = torch.ops._c10d_functional.wait_tensor(A_scale)
845
+ A_scale = (
846
+ A_scale.view(group_size, *A_scale_shard.shape)
847
+ .movedim(gather_dim + 1, 1)
848
+ .flatten(0, -2)
849
+ )
850
+ elif scale_mode == _ScaleMode.ROW_WISE_REPLICATED:
851
+ A_scale = A_scale.movedim(gather_dim, 0).flatten(0, -2)
852
+ else:
853
+ assert scale_mode == _ScaleMode.TENSOR_WISE
854
+
855
+ def scaled_matmul(
856
+ A: torch.Tensor,
857
+ B: torch.Tensor,
858
+ A_scale: torch.Tensor,
859
+ B_scale: torch.Tensor,
860
+ bias: Optional[torch.Tensor],
861
+ result_scale: Optional[torch.Tensor],
862
+ out_dtype: Optional[torch.dtype],
863
+ use_fast_accum: bool,
864
+ ) -> torch.Tensor:
865
+ leading_dims = A.shape[:-1]
866
+ res = torch.ops.aten._scaled_mm(
867
+ A.flatten(0, -2),
868
+ B,
869
+ A_scale,
870
+ B_scale,
871
+ bias,
872
+ result_scale,
873
+ out_dtype=out_dtype,
874
+ use_fast_accum=use_fast_accum,
875
+ )
876
+ return res.unflatten(0, leading_dims)
877
+
878
+ return A.movedim(0, gather_dim), [
879
+ scaled_matmul(
880
+ A, B, A_scale, B_scale, bias, result_scale, out_dtype, fast_accum
881
+ ).movedim(0, gather_dim)
882
+ for B, B_scale, bias, result_scale, out_dtype, fast_accum in zip(
883
+ Bs, B_scales, biases, result_scales, out_dtypes, use_fast_accum
884
+ )
885
+ ]
886
+
887
+
888
+ @torch.library.impl(lib, "fused_all_gather_scaled_matmul", "CUDA")
889
+ def _fused_all_gather_scaled_matmul(
890
+ A_shard: torch.Tensor,
891
+ Bs: list[torch.Tensor],
892
+ A_scale: torch.Tensor,
893
+ B_scales: list[torch.Tensor],
894
+ gather_dim: int,
895
+ group_name: str,
896
+ biases: list[Optional[torch.Tensor]],
897
+ result_scales: list[Optional[torch.Tensor]],
898
+ out_dtypes: list[Optional[torch.dtype]],
899
+ use_fast_accum: list[bool],
900
+ ) -> tuple[torch.Tensor, list[torch.Tensor]]:
901
+ """
902
+ Perform the following logic with micro-pipelined computation and
903
+ communication:
904
+
905
+ A = all_gather_tensor(A_shard, gather_dim, group_name)
906
+ leading_dims = A.shape[:-1]
907
+ res = torch.ops.aten._scaled_mm(A.flatten(0, -2), B, A_scale, B_scale)
908
+ res = res.unflatten(0, leading_dims)
909
+
910
+ The input `A_scale` can be tensor-wise, row-wise-sharded or
911
+ row-wise-replicated.
912
+
913
+ Optimal stride order for `A_shard` - if `A_shard.movedim(gather_dim, 0)` is
914
+ contiguous, no extra copy is required for input layout transformation.
915
+ Otherwise A_shard needs to be copied once.
916
+ """
917
+ out_dtypes = _maybe_convert_scalar_types_to_dtypes(out_dtypes)
918
+
919
+ if len(biases) != len(Bs):
920
+ raise ValueError("len(biases) must be the same as len(Bs)")
921
+ if len(result_scales) != len(Bs):
922
+ raise ValueError("len(result_scales) must be the same as len(Bs)")
923
+ if len(out_dtypes) != len(Bs):
924
+ raise ValueError("len(out_dtypes) must be the same as len(Bs)")
925
+ if len(use_fast_accum) != len(Bs):
926
+ raise ValueError("len(use_gast_accum_list) must be the same as len(Bs)")
927
+
928
+ if _is_test_mode:
929
+ return _fused_all_gather_scaled_matmul_fallback(
930
+ A_shard,
931
+ Bs,
932
+ A_scale,
933
+ B_scales,
934
+ gather_dim,
935
+ group_name,
936
+ biases,
937
+ result_scales,
938
+ out_dtypes,
939
+ use_fast_accum,
940
+ )
941
+
942
+ with torch.profiler.record_function("fused_all_gather_scaled_matmul"):
943
+ A, res = _fused_all_gather_matmul_impl(
944
+ torch.ops.aten._scaled_mm.out,
945
+ A_shard,
946
+ Bs,
947
+ A_scale,
948
+ [
949
+ {
950
+ "scale_b": B_scale,
951
+ "bias": bias,
952
+ "scale_result": result_scale,
953
+ "out_dtype": out_dtype,
954
+ "use_fast_accum": fast_accum,
955
+ }
956
+ for B_scale, bias, result_scale, out_dtype, fast_accum in zip(
957
+ B_scales, biases, result_scales, out_dtypes, use_fast_accum
958
+ )
959
+ ],
960
+ out_dtypes,
961
+ gather_dim,
962
+ group_name,
963
+ True,
964
+ )
965
+ assert A is not None
966
+ return A, res
967
+
968
+
969
+ def make_contiguous_for_perm(
970
+ t: torch.Tensor,
971
+ perm: list[int],
972
+ ) -> torch.Tensor:
973
+ """
974
+ Restride `t` such that `t.permute(perm)` is contiguous.
975
+ """
976
+ inv_perm = [0] * len(perm)
977
+ for i, p in enumerate(perm):
978
+ inv_perm[p] = i
979
+ return t.permute(perm).contiguous().permute(inv_perm)
980
+
981
+
982
+ def restride_A_shard_for_fused_all_gather_matmul(
983
+ t: torch.Tensor,
984
+ gather_dim: int,
985
+ ) -> torch.Tensor:
986
+ """
987
+ Restride the `A_shard` arg of `fused_all_gather_matmul` for optimal perf.
988
+ See the doc for `fused_all_gather_matmul` for detail.
989
+ """
990
+ perm = list(range(len(t.shape)))
991
+ perm.insert(0, perm.pop(gather_dim))
992
+ return make_contiguous_for_perm(t, perm)
993
+
994
+
995
+ @torch.library.impl(lib, "fused_matmul_reduce_scatter", "CUDA")
996
+ def _fused_matmul_reduce_scatter(
997
+ A: torch.Tensor,
998
+ B: torch.Tensor,
999
+ reduce_op: str,
1000
+ scatter_dim: int,
1001
+ group_name: str,
1002
+ ) -> torch.Tensor:
1003
+ """
1004
+ Perform the following logic with micro-pipelined computation and
1005
+ communication:
1006
+
1007
+ reduce_scatter_tensor(A @ B, reduce_op, scatter_dim, group_name)
1008
+
1009
+ Optimal stride order for A - if A.movedim(scatter_dim, 0) is contiguous, no
1010
+ extra copy is required for input layout transformation. Otherwise A needs
1011
+ to be copied once.
1012
+ """
1013
+ if _is_test_mode:
1014
+ return _fused_matmul_reduce_scatter_fallback(
1015
+ A, B, reduce_op, scatter_dim, group_name
1016
+ )
1017
+
1018
+ with torch.profiler.record_function("fused_matmul_reduce_scatter"):
1019
+ return _fused_matmul_reduce_scatter_impl(
1020
+ mm_out_op=torch.ops.aten.mm.out,
1021
+ A=A,
1022
+ B=B,
1023
+ kwargs={},
1024
+ out_dtype=A.dtype,
1025
+ reduce_op=reduce_op,
1026
+ scatter_dim=scatter_dim,
1027
+ group_name=group_name,
1028
+ )
1029
+
1030
+
1031
+ @torch.library.impl(lib, "fused_matmul_reduce_scatter", "Meta")
1032
+ def _fused_matmul_reduce_scatter_fallback(
1033
+ A: torch.Tensor,
1034
+ B: torch.Tensor,
1035
+ reduce_op: str,
1036
+ scatter_dim: int,
1037
+ group_name: str,
1038
+ ) -> torch.Tensor:
1039
+ res = funcol.reduce_scatter_tensor(A @ B, reduce_op, scatter_dim, group_name)
1040
+ res = funcol.wait_tensor(res)
1041
+ return res
1042
+
1043
+
1044
+ def _fused_matmul_reduce_scatter_impl(
1045
+ mm_out_op: torch._ops.OpOverload,
1046
+ A: torch.Tensor,
1047
+ B: torch.Tensor,
1048
+ kwargs: dict[str, Any],
1049
+ out_dtype: Optional[torch.dtype],
1050
+ reduce_op: str,
1051
+ scatter_dim: int,
1052
+ group_name: str,
1053
+ ) -> torch.Tensor:
1054
+ if A.dim() < 2:
1055
+ raise ValueError("A_shard must be a matrix")
1056
+ if scatter_dim < 0 or scatter_dim >= A.dim():
1057
+ raise ValueError("Invalid gather_dim")
1058
+ if B.dim() != 2:
1059
+ raise ValueError("B must be a matrix")
1060
+ if reduce_op == "sum":
1061
+ reduce_fn = partial(torch.sum, dim=0)
1062
+ elif reduce_op == "avg":
1063
+ reduce_fn = partial(torch.mean, dim=0)
1064
+ else:
1065
+ raise ValueError("reduce_op must be sum or avg")
1066
+
1067
+ group = c10d._resolve_process_group(group_name)
1068
+ out_shape = [*A.shape[:-1], B.shape[1]]
1069
+ out_shape[scatter_dim] //= group.size()
1070
+
1071
+ # Move the scatter_dim to the front and flatten the tensor into a 2D matrix
1072
+ x = A.movedim(scatter_dim, 0)
1073
+ leading_dims = [group.size()] + list(x.shape[:-1])
1074
+ leading_dims[1] //= group.size()
1075
+ x = x.flatten(0, -2)
1076
+ A_shards = x.chunk(group.size())
1077
+
1078
+ # Computing block-wise matmul along the first dim of A
1079
+ def chunk_producer(rank: int, out: torch.Tensor) -> None:
1080
+ mm_out_op(A_shards[rank], B, **kwargs, out=out)
1081
+
1082
+ stacked_partials = x.new_empty(x.shape[0], B.shape[1], dtype=out_dtype or A.dtype)
1083
+
1084
+ _pipelined_produce_and_all2all(
1085
+ chunk_producer,
1086
+ stacked_partials,
1087
+ group_name,
1088
+ )
1089
+
1090
+ # Ensures that the transpose and reduction produce contiguous result
1091
+ # in a single reduction kernel.
1092
+ return reduce_fn(
1093
+ stacked_partials.view(*leading_dims, -1)
1094
+ .movedim(1, scatter_dim + 1)
1095
+ .movedim(0, scatter_dim),
1096
+ dim=scatter_dim,
1097
+ )
1098
+
1099
+
1100
+ @torch.library.impl(lib, "fused_scaled_matmul_reduce_scatter", "CUDA")
1101
+ def _fused_scaled_matmul_reduce_scatter(
1102
+ A: torch.Tensor,
1103
+ B: torch.Tensor,
1104
+ A_scale: torch.Tensor,
1105
+ B_scale: torch.Tensor,
1106
+ reduce_op: str,
1107
+ orig_scatter_dim: int,
1108
+ scatter_dim_after_maybe_reshape: int,
1109
+ group_name: str,
1110
+ output_shape: list[int],
1111
+ bias: Optional[torch.Tensor] = None,
1112
+ result_scale: Optional[torch.Tensor] = None,
1113
+ out_dtype: Optional[torch.dtype] = None,
1114
+ use_fast_accum: bool = False,
1115
+ ) -> torch.Tensor:
1116
+ if _is_test_mode:
1117
+ return _fused_scaled_matmul_reduce_scatter_fallback(
1118
+ A,
1119
+ B,
1120
+ A_scale,
1121
+ B_scale,
1122
+ reduce_op,
1123
+ orig_scatter_dim,
1124
+ scatter_dim_after_maybe_reshape,
1125
+ group_name,
1126
+ output_shape,
1127
+ bias,
1128
+ result_scale,
1129
+ out_dtype,
1130
+ use_fast_accum,
1131
+ )
1132
+ with torch.profiler.record_function("fused_scaled_matmul_reduce_scatter"):
1133
+ return _fused_scaled_matmul_reduce_scatter_impl(
1134
+ mm_out_op=torch.ops.aten._scaled_mm.out,
1135
+ A=A,
1136
+ B=B,
1137
+ A_scale=A_scale,
1138
+ kwargs={
1139
+ "scale_b": B_scale,
1140
+ "bias": bias,
1141
+ "scale_result": result_scale,
1142
+ "out_dtype": out_dtype,
1143
+ "use_fast_accum": use_fast_accum,
1144
+ },
1145
+ out_dtype=out_dtype,
1146
+ reduce_op=reduce_op,
1147
+ orig_scatter_dim=orig_scatter_dim,
1148
+ scatter_dim_after_maybe_reshape=scatter_dim_after_maybe_reshape,
1149
+ group_name=group_name,
1150
+ output_shape=output_shape,
1151
+ )
1152
+
1153
+
1154
+ @torch.library.impl(lib, "fused_scaled_matmul_reduce_scatter", "Meta")
1155
+ def _fused_scaled_matmul_reduce_scatter_fallback(
1156
+ A: torch.Tensor,
1157
+ B: torch.Tensor,
1158
+ A_scale: torch.Tensor,
1159
+ B_scale: torch.Tensor,
1160
+ reduce_op: str,
1161
+ orig_scatter_dim: int,
1162
+ scatter_dim_after_maybe_reshape: int,
1163
+ group_name: str,
1164
+ output_shape: list[int],
1165
+ bias: Optional[torch.Tensor] = None,
1166
+ result_scale: Optional[torch.Tensor] = None,
1167
+ out_dtype: Optional[torch.dtype] = None,
1168
+ use_fast_accum: bool = False,
1169
+ ) -> torch.Tensor:
1170
+ if A_scale.numel() > 1:
1171
+ if A_scale.shape[:-1] != A.shape[:-1]:
1172
+ raise ValueError(
1173
+ "For row-wise scaling, the leading dims of A_scale "
1174
+ "must match the leading dims of A "
1175
+ f"(A shape: {A.shape}, A_scale shape: {A_scale.shape})"
1176
+ )
1177
+ A_scale = A_scale.flatten(0, -2).contiguous()
1178
+ elif A_scale.numel() != 1:
1179
+ raise ValueError(
1180
+ "Invalid A_scale shape "
1181
+ f"(A shape: {A.shape}, A_scale shape: {A_scale.shape})"
1182
+ )
1183
+
1184
+ C = torch._scaled_mm(
1185
+ A.flatten(0, -2).contiguous(),
1186
+ B,
1187
+ A_scale,
1188
+ B_scale,
1189
+ bias,
1190
+ result_scale,
1191
+ out_dtype,
1192
+ use_fast_accum,
1193
+ )
1194
+ C = C.view(*output_shape[:-1], B.shape[1])
1195
+ res = funcol.reduce_scatter_tensor(
1196
+ C,
1197
+ reduce_op,
1198
+ orig_scatter_dim, # need original scatter dim for 3D+ output tensor here
1199
+ group_name,
1200
+ )
1201
+ res = funcol.wait_tensor(res)
1202
+ return res
1203
+
1204
+
1205
+ def _fused_scaled_matmul_reduce_scatter_impl(
1206
+ mm_out_op: torch._ops.OpOverload,
1207
+ A: torch.Tensor,
1208
+ B: torch.Tensor,
1209
+ A_scale: torch.Tensor,
1210
+ kwargs: dict[str, Any],
1211
+ out_dtype: Optional[torch.dtype],
1212
+ reduce_op: str,
1213
+ orig_scatter_dim: int,
1214
+ scatter_dim_after_maybe_reshape: int,
1215
+ group_name: str,
1216
+ output_shape: list[int],
1217
+ ) -> torch.Tensor:
1218
+ if A.dim() < 2:
1219
+ raise ValueError("A_shard must be a matrix")
1220
+ if (
1221
+ scatter_dim_after_maybe_reshape < 0
1222
+ or scatter_dim_after_maybe_reshape >= A.dim()
1223
+ ):
1224
+ raise ValueError("Invalid scatter dim for 2D tensor input to scaled_mm")
1225
+ if orig_scatter_dim < 0 or orig_scatter_dim >= len(output_shape):
1226
+ raise ValueError("Invalid scatter dim for 3D+ output tensor")
1227
+ if B.dim() != 2:
1228
+ raise ValueError("B must be a matrix")
1229
+ if reduce_op == "sum":
1230
+ reduce_fn = partial(torch.sum, dim=0)
1231
+ elif reduce_op == "avg":
1232
+ reduce_fn = partial(torch.mean, dim=0)
1233
+ else:
1234
+ raise ValueError("reduce_op must be sum or avg")
1235
+
1236
+ group = c10d._resolve_process_group(group_name)
1237
+
1238
+ # Move scatter to first dim, then shard the tensor along the first dim, so the chunk producer
1239
+ # can perform matmuls along the first dim.
1240
+ A_with_scatter_dim_0 = A.movedim(scatter_dim_after_maybe_reshape, 0)
1241
+
1242
+ # To handle case where A is 3D+, reshape to 2D to prepare for mm which requires 2D inputs.
1243
+ A_2D_with_scatter_dim_0 = A_with_scatter_dim_0.flatten(0, -2)
1244
+
1245
+ # Partition A along the first dim to prepare for sharding across TP process group.
1246
+ A_shards = A_2D_with_scatter_dim_0.chunk(group.size())
1247
+
1248
+ # Now that 'A' is sharded along the first dim, we need to update its scale(s) accordingly.
1249
+ # How we do this depends on if we are using tensorwise scaling, rowwise scaling, or no scaling.
1250
+ tensorwise_scaling = A_scale is not None and A_scale.numel() == 1
1251
+ rowwise_scaling = A_scale is not None and A_scale.numel() > 1
1252
+
1253
+ # For tensorwise scaling, the scale should be replicated so each shard has a copy.
1254
+ if tensorwise_scaling:
1255
+ A_scale_shards = [A_scale] * group.size()
1256
+
1257
+ # For rowwise scaling, we need to move the scatter dim to the first dim to match the
1258
+ # dim swap of the 'A' tensor. Then we can shard the scales along the first dim, just like
1259
+ # the 'A' tensor.
1260
+ elif rowwise_scaling:
1261
+ if A_scale.shape[:-1] != A.shape[:-1]:
1262
+ raise ValueError(
1263
+ "For row-wise scaling, the leading dims of A_scale "
1264
+ "must match the leading dims of A "
1265
+ f"(A shape: {A.shape}, A_scale shape: {A_scale.shape})"
1266
+ )
1267
+ A_scale = (
1268
+ A_scale.movedim(scatter_dim_after_maybe_reshape, 0)
1269
+ .contiguous()
1270
+ .flatten(0, -2)
1271
+ )
1272
+ A_scale_shards = list(A_scale.chunk(group.size()))
1273
+ else:
1274
+ raise ValueError("A_scale cannot be none for scaled_mm")
1275
+
1276
+ # Computing block-wise matmul along the first dim of A
1277
+ def chunk_producer(rank: int, out: torch.Tensor) -> None:
1278
+ mm_out_op(A_shards[rank], B, scale_a=A_scale_shards[rank], **kwargs, out=out)
1279
+
1280
+ # Stacked partials will be the 2D outputs of the the pipelined scaled mm, and will
1281
+ # have the shape (A_with_scatter_dim_0_tensor.shape[0], B.shape[1]) to align with the formula:
1282
+ # (a*b,c) @ (c,d) = (a*b,d)
1283
+ stacked_partials = A_with_scatter_dim_0.new_empty(
1284
+ A_2D_with_scatter_dim_0.shape[0], B.shape[1], dtype=out_dtype or A.dtype
1285
+ )
1286
+
1287
+ # Execute the pipelined mm/scaled_mm.
1288
+ _pipelined_produce_and_all2all(
1289
+ chunk_producer,
1290
+ stacked_partials,
1291
+ group_name,
1292
+ )
1293
+
1294
+ # We now need to transform the *unreduced* stacked 2D partial mm outputs to an *unreduced* 3D+ output,
1295
+ # then reduce-scatter. To do this, we first need to determine the shape of the unreduced 3D+ output,
1296
+ # to reshape our stacked partials so we can apply the reduce-scatter.
1297
+ #
1298
+ # The *unreduced* 3D+ tensor will have dim 0 = `group_size`, as we have `group_size` instances of
1299
+ # stacked partial outputs. The next dims will be A's leading dims (sharded along the original scatter dim),
1300
+ # as it was the left operand of the mm op. We can use -1 as the final dim of the view to populate the rest.
1301
+ stacked_partials_3D_leading_dims = [group.size()] + list(
1302
+ # We use A from after the dim swap 0<=>scatter_dim, but before the flatten,
1303
+ # to get the leading dims of the 3D+ view of stacked partials.
1304
+ A_with_scatter_dim_0.shape[:-1]
1305
+ )
1306
+
1307
+ # The `group_size` leading dim has been prepended to `stacked_partials_3D_leading_dims`,
1308
+ # to capture the partial output from each rank. We need to divide the sharding/scatter dim
1309
+ # by the group size. If the original scatter dim was 0, then it is now dim 1 in this
1310
+ # tensor, since this new `group_size` dim was prepended.
1311
+ stacked_partial_scatter_dim = orig_scatter_dim if orig_scatter_dim > 0 else 1
1312
+ stacked_partials_3D_leading_dims[stacked_partial_scatter_dim] //= group.size()
1313
+
1314
+ # Ensures that the transpose and reduction produce contiguous result
1315
+ # in a single reduction kernel.
1316
+ reduced_out = reduce_fn(
1317
+ # View 2D stacked partials as 3D+ tensor of shape (`group_size`, ...)
1318
+ stacked_partials.view(*stacked_partials_3D_leading_dims, -1)
1319
+ # We originally swapped 0<=>scatter_dim_after_maybe_reshape. Now after
1320
+ # prepending the `group_size` dim, to undo this original swap, we
1321
+ # must swap 1<=>scatter_dim_after_maybe_reshape+1.
1322
+ .movedim(1, scatter_dim_after_maybe_reshape + 1),
1323
+ # Reduce along the `group_size` dim (0).
1324
+ dim=0,
1325
+ )
1326
+
1327
+ # Output shape must be scattered along original scatter dim as well.
1328
+ output_shape[orig_scatter_dim] //= group.size()
1329
+ out = reduced_out.view(*output_shape)
1330
+ return out
1331
+
1332
+
1333
+ def restride_A_for_fused_matmul_reduce_scatter(
1334
+ t: torch.Tensor,
1335
+ scatter_dim: int,
1336
+ ) -> torch.Tensor:
1337
+ """
1338
+ Restride the `A_shard` arg of `fused_matmul_reduce_scatter` for optimal
1339
+ perf. See the doc for `fused_matmul_reduce_scatter` for detail.
1340
+ """
1341
+ perm = list(range(len(t.shape)))
1342
+ perm.insert(0, perm.pop(scatter_dim))
1343
+ return make_contiguous_for_perm(t, perm)
1344
+
1345
+
1346
+ def _maybe_convert_scalar_types_to_dtypes(
1347
+ scalar_types: list[Any],
1348
+ ) -> list[Optional[torch.dtype]]:
1349
+ """
1350
+ When a list of `torch.dtype`s is passed through the dispatcher as
1351
+ `ScalarType[]`, it is converted to a list of scalar type enum values. This
1352
+ function converts it back to a list of `torch.dtype`s.
1353
+ """
1354
+ # Order defined in https://github.com/pytorch/pytorch/blob/344defc9733a45fee8d0c4d3f5530f631e823196/c10/core/ScalarType.h
1355
+ _SCALAR_TYPE_TO_DTYPE = {
1356
+ 0: torch.uint8,
1357
+ 1: torch.int8,
1358
+ 2: torch.short,
1359
+ 3: torch.int,
1360
+ 4: torch.int64,
1361
+ 5: torch.half,
1362
+ 6: torch.float,
1363
+ 7: torch.double,
1364
+ 8: torch.complex32,
1365
+ 9: torch.complex64,
1366
+ 10: torch.complex128,
1367
+ 11: torch.bool,
1368
+ 12: torch.qint8,
1369
+ 13: torch.quint8,
1370
+ 14: torch.qint32,
1371
+ 15: torch.bfloat16,
1372
+ 16: torch.float8_e5m2,
1373
+ 17: torch.float8_e4m3fn,
1374
+ 18: torch.float8_e5m2fnuz,
1375
+ 19: torch.float8_e4m3fnuz,
1376
+ }
1377
+ if any(not isinstance(x, (type(None), int)) for x in scalar_types):
1378
+ return scalar_types
1379
+
1380
+ dtypes: list[Optional[torch.dtype]] = []
1381
+ for scalar_type in scalar_types:
1382
+ if scalar_type is None:
1383
+ dtypes.append(scalar_type)
1384
+ elif scalar_type not in _SCALAR_TYPE_TO_DTYPE:
1385
+ raise ValueError("Unrecognized scalar type {scalar_type}")
1386
+ else:
1387
+ dtypes.append(_SCALAR_TYPE_TO_DTYPE[scalar_type])
1388
+ return dtypes
1389
+
1390
+
1391
+ class Work(_Work):
1392
+ def __init__(self) -> None:
1393
+ super().__init__()
1394
+ self.event = torch.cuda.Event()
1395
+ self.event.record()
1396
+
1397
+ def wait(self, timeout: timedelta = timedelta(seconds=0)) -> bool:
1398
+ self.event.wait()
1399
+ return True
1400
+
1401
+
1402
+ """
1403
+ NOTE [low-contention collectives]
1404
+ When a collective is overlapped with abundant compute, it makes sense to
1405
+ prioritize reducing the contention between the collective and the overlapped
1406
+ compute, even at the cost of a slightly slower collective.
1407
+
1408
+ Common collective implementations (e.g., NCCL without user buffer
1409
+ registration) optimize for throughput with no ambient compute. However, such
1410
+ implementations may not be optimal when they are overlapped with compute:
1411
+ - These implementations typically fuse the entire collective into a single
1412
+ kernel and reserve SM resources based on the most demanding portion of the
1413
+ collective, even when a large portion of the collective does not require this
1414
+ much resource.
1415
+ - These implementations often use SM-based P2P copy as opposed to copy
1416
+ engine-based P2P copy. Copy engine-based P2P copy may not have a significant
1417
+ advantage when there's no ambient compute. However, it may significantly
1418
+ improve overall resource utilization in the presence of ambient compute.
1419
+
1420
+ When overlapped with intensive compute (e.g., persistent matmul kernels), the
1421
+ SM-usage of a collective can lead to inefficient overlapping.
1422
+
1423
+ Low-contention collectives achieve their goals with the following strategies:
1424
+ - Use copy engine-based copy whenever possible.
1425
+ - Break down portions of a collective with different resource requirements
1426
+ into multiple kernels. This improves the overlapping efficiency at the cost
1427
+ of additional launching overhead.
1428
+ """
1429
+
1430
+
1431
+ @torch.library.impl(lib, "_low_contention_all_gather", "Meta")
1432
+ def _low_contention_all_gather_meta(
1433
+ tensor: torch.Tensor,
1434
+ group_name: str,
1435
+ ) -> torch.Tensor:
1436
+ group_size = c10d._get_group_size_by_name(group_name)
1437
+ return tensor.new_empty(tensor.shape[0] * group_size, *tensor.shape[1:])
1438
+
1439
+
1440
+ @torch.library.impl(lib, "_low_contention_all_gather", "CUDA")
1441
+ def _low_contention_all_gather(
1442
+ tensor: torch.Tensor,
1443
+ group_name: str,
1444
+ ) -> torch.Tensor:
1445
+ """
1446
+ Performs all-gather with symmetric memory in a low-contention fashion.
1447
+
1448
+ When `tensor` is already in symmetric memory:
1449
+ - The collective is carried out without using SMs.
1450
+ - No symmetric memory workspace is required.
1451
+
1452
+ When `tensor` is not in symmetric memory:
1453
+ - An extra SM-based copy is performed to copy the input data into the
1454
+ symmetric memory workspace.
1455
+ - Symmetric memory workspace size requirement: the size of `tensor`.
1456
+ """
1457
+ symm_mem = rendezvous(tensor, group_name)
1458
+ if symm_mem is not None:
1459
+ input_is_symm_mem = True
1460
+ else:
1461
+ symm_mem = get_symm_mem_workspace(
1462
+ group_name, tensor.numel() * tensor.element_size()
1463
+ )
1464
+ input_is_symm_mem = False
1465
+
1466
+ rank = symm_mem.rank
1467
+ world_size = symm_mem.world_size
1468
+
1469
+ output = tensor.new_empty(tensor.shape[0] * world_size, *tensor.shape[1:])
1470
+ chunks = output.chunk(world_size)
1471
+
1472
+ _get_backend_stream().wait_stream(torch.cuda.current_stream())
1473
+ with _get_backend_stream():
1474
+ if not input_is_symm_mem:
1475
+ local_buf = symm_mem.get_buffer(rank, tensor.shape, tensor.dtype)
1476
+ local_buf.copy_(tensor)
1477
+ # pull
1478
+ symm_mem.barrier()
1479
+ for step in range(0, world_size):
1480
+ remote_rank = (rank - step) % world_size
1481
+ src_buf = symm_mem.get_buffer(remote_rank, tensor.shape, tensor.dtype)
1482
+ chunks[remote_rank].copy_(src_buf)
1483
+ symm_mem.barrier()
1484
+ torch._C._distributed_c10d._register_work(output, Work())
1485
+ return output
1486
+
1487
+
1488
+ @torch.library.impl(lib, "_low_contention_reduce_scatter", "Meta")
1489
+ def _low_contention_reduce_scatter_meta(
1490
+ tensor: torch.Tensor,
1491
+ reduce_op: str,
1492
+ group_name: str,
1493
+ ) -> torch.Tensor:
1494
+ group_size = c10d._get_group_size_by_name(group_name)
1495
+ return tensor.unflatten(0, (group_size, -1)).mean(dim=0)
1496
+
1497
+
1498
+ def _low_contention_reduce_scatter_with_symm_mem_input(
1499
+ tensor: torch.Tensor,
1500
+ reduce_op: str,
1501
+ symm_mem: _SymmetricMemory,
1502
+ ) -> torch.Tensor:
1503
+ rank = symm_mem.rank
1504
+ world_size = symm_mem.world_size
1505
+
1506
+ assert tensor.shape[0] % world_size == 0
1507
+ a2a_res = torch.empty_like(tensor)
1508
+ chunks = a2a_res.chunk(world_size)
1509
+
1510
+ _get_backend_stream().wait_stream(torch.cuda.current_stream())
1511
+ with _get_backend_stream():
1512
+ # pull + offline reduction
1513
+ symm_mem.barrier()
1514
+ for step in range(0, world_size):
1515
+ remote_rank = (rank - step) % world_size
1516
+ src_buf = symm_mem.get_buffer(
1517
+ remote_rank,
1518
+ chunks[0].shape,
1519
+ chunks[0].dtype,
1520
+ chunks[0].numel() * rank,
1521
+ )
1522
+ chunks[remote_rank].copy_(src_buf)
1523
+ symm_mem.barrier()
1524
+
1525
+ ret = a2a_res.unflatten(0, (world_size, -1))
1526
+ if reduce_op == "sum":
1527
+ ret = ret.sum(dim=0)
1528
+ elif reduce_op == "avg":
1529
+ ret = ret.mean(dim=0)
1530
+ else:
1531
+ raise ValueError(f"reduce_op ({reduce_op}) is not supported")
1532
+ torch._C._distributed_c10d._register_work(ret, Work())
1533
+ return ret
1534
+
1535
+
1536
+ def _low_contention_reduce_scatter_with_workspace(
1537
+ tensor: torch.Tensor,
1538
+ reduce_op: str,
1539
+ workspace: _SymmetricMemory,
1540
+ ) -> torch.Tensor:
1541
+ rank = workspace.rank
1542
+ world_size = workspace.world_size
1543
+
1544
+ assert tensor.shape[0] % world_size == 0
1545
+ chunks = tensor.chunk(world_size)
1546
+
1547
+ _get_backend_stream().wait_stream(torch.cuda.current_stream())
1548
+ with _get_backend_stream():
1549
+ # push + offline reduction
1550
+ workspace.barrier()
1551
+ for step in range(0, world_size):
1552
+ remote_rank = (rank - step) % world_size
1553
+ dst_buf = workspace.get_buffer(
1554
+ remote_rank, chunks[0].shape, chunks[0].dtype, chunks[0].numel() * rank
1555
+ )
1556
+ dst_buf.copy_(chunks[remote_rank])
1557
+ workspace.barrier()
1558
+
1559
+ buf = workspace.get_buffer(rank, tensor.shape, tensor.dtype)
1560
+ ret = buf.unflatten(0, (world_size, -1))
1561
+ if reduce_op == "sum":
1562
+ ret = ret.sum(dim=0)
1563
+ elif reduce_op == "avg":
1564
+ ret = ret.mean(dim=0)
1565
+ else:
1566
+ raise ValueError(f"reduce_op ({reduce_op}) is not supported")
1567
+ torch._C._distributed_c10d._register_work(ret, Work())
1568
+ return ret
1569
+
1570
+
1571
+ @torch.library.impl(lib, "_low_contention_reduce_scatter", "CUDA")
1572
+ def _low_contention_reduce_scatter(
1573
+ tensor: torch.Tensor,
1574
+ reduce_op: str,
1575
+ group_name: str,
1576
+ ) -> torch.Tensor:
1577
+ """
1578
+ Performs reduce-scatter with symmetric memory in a low-contention fashion.
1579
+
1580
+ This implementation performs a P2P-based all-to-all followed by an offline
1581
+ reduction.
1582
+
1583
+ When `tensor` is already in symmetric memory:
1584
+ - Pull-based all-to-all is used.
1585
+ - No symmetric memory workspace is required.
1586
+
1587
+ When `tensor` is not in symmetric memory:
1588
+ - Push-based all-to-all is used.
1589
+ - Symmetric memory workspace size requirement: the size of `tensor`.
1590
+
1591
+ SM-usage:
1592
+ - SM-based copy of the rank's own chunk for the all-to-all.
1593
+ - Reduction on the all-to-all result.
1594
+
1595
+ TODO(yifu): the SM-based copy can be avoided with a list-based reduction
1596
+ kernel.
1597
+ """
1598
+ symm_mem = rendezvous(tensor, group_name)
1599
+ if symm_mem is not None:
1600
+ return _low_contention_reduce_scatter_with_symm_mem_input(
1601
+ tensor, reduce_op, symm_mem
1602
+ )
1603
+ else:
1604
+ workspace = get_symm_mem_workspace(
1605
+ group_name, tensor.numel() * tensor.element_size()
1606
+ )
1607
+ return _low_contention_reduce_scatter_with_workspace(
1608
+ tensor, reduce_op, workspace
1609
+ )
1610
+
1611
+
1612
+ # =============================================================================
1613
+ # User-facing APIs
1614
+ # =============================================================================
1615
+
1616
+
1617
+ from collections.abc import Sequence
1618
+ from typing import Any, overload, TYPE_CHECKING, Union
1619
+
1620
+ from torch.types import _device, _dtype, _int
1621
+
1622
+
1623
+ if TYPE_CHECKING:
1624
+ from torch._C._distributed_c10d import ProcessGroup
1625
+
1626
+
1627
+ @overload
1628
+ def empty(
1629
+ *size: _int, dtype: Optional[_dtype] = None, device: Optional[_device] = None
1630
+ ) -> torch.Tensor: ...
1631
+
1632
+
1633
+ @overload
1634
+ def empty(
1635
+ size: Sequence[_int],
1636
+ *,
1637
+ dtype: Optional[_dtype] = None,
1638
+ device: Optional[_device] = None,
1639
+ ) -> torch.Tensor: ...
1640
+
1641
+
1642
+ def empty( # type: ignore[misc]
1643
+ *size: Any,
1644
+ dtype: Optional[_dtype] = None,
1645
+ device: Optional[_device] = None,
1646
+ ) -> torch.Tensor:
1647
+ r"""
1648
+ empty(*size, *, dtype=None, device=None) -> Tensor
1649
+
1650
+ Similar to :func:`torch.empty()`. The returned tensor can be used by
1651
+ :func:`torch._distributed._symmetric_memory.rendezvous()` to establish a
1652
+ symmetric memory tensor among participating processes.
1653
+
1654
+ Args:
1655
+ size (int...): a sequence of integers defining the shape of the output tensor.
1656
+ Can be a variable number of arguments or a collection like a list or tuple.
1657
+
1658
+ Keyword args:
1659
+ dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
1660
+ Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`).
1661
+ device (:class:`torch.device`, optional): the desired device of returned tensor.
1662
+ Default: if ``None``, uses the current device for the default tensor type
1663
+ (see :func:`torch.set_default_device`). :attr:`device` will be the CPU
1664
+ for CPU tensor types and the current CUDA device for CUDA tensor types.
1665
+ """
1666
+ if len(size) == 1 and isinstance(size[0], Sequence):
1667
+ size = tuple(size[0])
1668
+ else:
1669
+ size = tuple(size)
1670
+
1671
+ if dtype is None:
1672
+ dtype = torch.get_default_dtype()
1673
+
1674
+ if device is None:
1675
+ device = torch.get_default_device()
1676
+
1677
+ return _SymmetricMemory.empty_strided_p2p(
1678
+ size=size,
1679
+ stride=torch._prims_common.make_contiguous_strides_for(size),
1680
+ dtype=dtype,
1681
+ device=torch.device(device),
1682
+ )
1683
+
1684
+
1685
+ def rendezvous(
1686
+ tensor: torch.Tensor, group: Union[str, "ProcessGroup"]
1687
+ ) -> _SymmetricMemory:
1688
+ r"""
1689
+ rendezvous(tensor, group) -> _SymmetricMemory
1690
+
1691
+ Establish a symmetric memory tensor among participating processes. This is
1692
+ a collective operation.
1693
+
1694
+ Args:
1695
+ tensor (:class:`torch.Tensor`): the local tensor used to establish the symmetric memory tensor.
1696
+ It must be allocated via :func:`torch._distributed._symmetric_memory.empty()`. The shape,
1697
+ dtype, and device type must be identical across all participating processes.
1698
+ group (Union[str, :class:`torch.distributed.ProcessGroup`]): The group identifying the
1699
+ participating processes. This can be either a group name or a process group object.
1700
+ """
1701
+ from torch._C._distributed_c10d import ProcessGroup
1702
+
1703
+ if isinstance(group, str):
1704
+ group_name = group
1705
+ elif isinstance(group, ProcessGroup):
1706
+ group_name = group.group_name
1707
+ else:
1708
+ raise TypeError(f"rendezvous: unsupported group type: {type(group)}")
1709
+
1710
+ enable_symm_mem_for_group(group_name)
1711
+ return _SymmetricMemory.rendezvous(tensor, group_name)
1712
+
1713
+
1714
+ def is_nvshmem_available() -> bool:
1715
+ r"""
1716
+ is_nvshmem_available() -> bool
1717
+
1718
+ Check if NVSHMEM is available in current build and on current system.
1719
+ """
1720
+ try:
1721
+ from torch._C._distributed_c10d import _is_nvshmem_available
1722
+ except ImportError:
1723
+ # Not all builds have NVSHMEM support.
1724
+ return False
1725
+
1726
+ # Check if NVSHMEM is available on current system.
1727
+ return _is_nvshmem_available()
1728
+
1729
+
1730
+ __all__ = ["empty", "rendezvous", "is_nvshmem_available"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_symmetric_memory/_nvshmem_triton.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sysconfig
3
+ from typing import Optional
4
+
5
+ from torch.utils._triton import has_triton
6
+
7
+
8
+ def enable_triton(lib_dir: Optional[str] = None) -> dict[str, str]:
9
+ """
10
+ Enable NVSHMEM device functions for Triton. It performs a NVSHMEM
11
+ device-side initialization on the kernel module created by Triton.
12
+
13
+ Args:
14
+ lib_dir (Optional[str]): The directory where the NVSHMEM device library
15
+ is located. If not provided, it will use the default path where NVSHMEM
16
+ wheel is installed.
17
+
18
+ Returns:
19
+ dict[str, str]: A dictionary containing the NVSHMEM device library name
20
+ and path.
21
+ """
22
+ from triton.runtime.jit import JITFunction
23
+
24
+ from torch._C._distributed_c10d import _nvshmemx_cumodule_init
25
+
26
+ # Detect NVSHMEM device library path from python library path
27
+ if lib_dir is None:
28
+ py_lib_path = sysconfig.get_path("purelib")
29
+ lib_dir = py_lib_path + "/nvidia/nvshmem/lib"
30
+
31
+ lib_path = os.path.join(lib_dir, "libnvshmem_device.bc")
32
+ if not os.path.exists(lib_path):
33
+ raise RuntimeError("NVSHMEM device library not found")
34
+
35
+ extern_libs = {"libnvshmem_device": lib_path}
36
+
37
+ # A hook function to initialize NVSHMEM in Triton
38
+ def nvshmem_init_hook(*args, **kwargs) -> None: # type: ignore[no-untyped-def]
39
+ key = kwargs["key"]
40
+ device = kwargs["compile"]["device"]
41
+ jit_function = kwargs["fn"].jit_function
42
+ kernel_cache, _, _, _ = jit_function.device_caches[device]
43
+ kernel = kernel_cache.get(key, None)
44
+ kernel.run
45
+ _nvshmemx_cumodule_init(kernel.module)
46
+
47
+ # Register the function as a post-compile hook
48
+ JITFunction.compiled_hook = nvshmem_init_hook
49
+
50
+ # Return to user so that they can use it in Triton kernel invocation
51
+ return extern_libs
52
+
53
+
54
+ if has_triton():
55
+ from triton.language import core
56
+
57
+ @core.extern
58
+ def putmem_block(dst, src, nelems, pe, _builder=None): # type: ignore[no-untyped-def]
59
+ return core.extern_elementwise(
60
+ "",
61
+ "",
62
+ [dst, src, nelems, pe],
63
+ {
64
+ (
65
+ core.dtype("int64"),
66
+ core.dtype("int64"),
67
+ core.dtype("int64"),
68
+ core.dtype("int64"),
69
+ ): ("nvshmemx_putmem_block", core.dtype("int32"))
70
+ },
71
+ is_pure=False,
72
+ _builder=_builder,
73
+ )
74
+
75
+ @core.extern
76
+ def getmem_block(dst, src, nelems, pe, _builder=None): # type: ignore[no-untyped-def]
77
+ return core.extern_elementwise(
78
+ "",
79
+ "",
80
+ [dst, src, nelems, pe],
81
+ {
82
+ (
83
+ core.dtype("int64"),
84
+ core.dtype("int64"),
85
+ core.dtype("int64"),
86
+ core.dtype("int64"),
87
+ ): ("nvshmemx_getmem_block", core.dtype("int32"))
88
+ },
89
+ is_pure=False,
90
+ _builder=_builder,
91
+ )
92
+
93
+ @core.extern
94
+ def putmem_signal_block( # type: ignore[no-untyped-def]
95
+ dst,
96
+ src,
97
+ nelems,
98
+ sig_addr,
99
+ signal,
100
+ sig_op,
101
+ pe,
102
+ _builder=None,
103
+ ): # type: ignore[no-untyped-def]
104
+ return core.extern_elementwise(
105
+ "",
106
+ "",
107
+ [dst, src, nelems, sig_addr, signal, sig_op, pe],
108
+ {
109
+ (
110
+ core.dtype("int64"),
111
+ core.dtype("int64"),
112
+ core.dtype("int64"),
113
+ core.dtype("int64"),
114
+ core.dtype("int64"),
115
+ core.dtype("int64"),
116
+ core.dtype("int64"),
117
+ ): ("nvshmemx_putmem_signal_block", core.dtype("int32"))
118
+ },
119
+ is_pure=False,
120
+ _builder=_builder,
121
+ )
122
+
123
+ @core.extern
124
+ def wait_until(ivar, cmp, cmp_val, _builder=None): # type: ignore[no-untyped-def]
125
+ return core.extern_elementwise(
126
+ "",
127
+ "",
128
+ [ivar, cmp, cmp_val],
129
+ {
130
+ (
131
+ core.dtype("int64"),
132
+ core.dtype("int64"),
133
+ core.dtype("int64"),
134
+ ): ("nvshmem_longlong_wait_until", core.dtype("int32"))
135
+ },
136
+ is_pure=False,
137
+ _builder=_builder,
138
+ )
139
+
140
+ @core.extern
141
+ def signal_wait_until(sig_addr, cmp, cmp_val, _builder=None): # type: ignore[no-untyped-def]
142
+ return core.extern_elementwise(
143
+ "",
144
+ "",
145
+ [sig_addr, cmp, cmp_val],
146
+ {
147
+ (
148
+ core.dtype("int64"),
149
+ core.dtype("int64"),
150
+ core.dtype("int64"),
151
+ ): ("nvshmem_signal_wait_until", core.dtype("int32"))
152
+ },
153
+ is_pure=False,
154
+ _builder=_builder,
155
+ )
156
+
157
+ @core.extern
158
+ def fence(_builder=None): # type: ignore[no-untyped-def]
159
+ return core.extern_elementwise(
160
+ "",
161
+ "",
162
+ [],
163
+ {
164
+ (): ("nvshmem_fence", core.dtype("int32")),
165
+ },
166
+ is_pure=False,
167
+ _builder=_builder,
168
+ )
169
+
170
+ @core.extern
171
+ def quiet(_builder=None): # type: ignore[no-untyped-def]
172
+ return core.extern_elementwise(
173
+ "",
174
+ "",
175
+ [],
176
+ {
177
+ (): ("nvshmem_quiet", core.dtype("int32")),
178
+ },
179
+ is_pure=False,
180
+ _builder=_builder,
181
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/algorithms/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .join import Join, Joinable, JoinHook
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/algorithms/join.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import warnings
3
+ from abc import ABC, abstractmethod
4
+ from types import TracebackType
5
+ from typing import Any, NamedTuple, Optional
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+
10
+
11
+ __all__ = ["JoinHook", "Joinable", "Join"]
12
+
13
+
14
+ class JoinHook:
15
+ r"""
16
+ This defines a join hook, which provides two entry points in the join context manager.
17
+
18
+ Entry points : a main hook, which is called repeatedly while there exists a non-joined
19
+ process, and a post-hook, which is called once all processes have joined.
20
+
21
+ To implement a join hook for the generic join context manager, define a
22
+ class that inherits from :class:`JoinHook` and override ``main_hook()`` and
23
+ ``post_hook()`` as appropriate.
24
+ """
25
+
26
+ def main_hook(self) -> None:
27
+ r"""Call this hook while there exists a non-joined process to shadow collective communications in a training iteration.
28
+
29
+ Training iteration i.e., in one forward pass, backward pass, and optimizer step.
30
+ """
31
+
32
+ def post_hook(self, is_last_joiner: bool) -> None:
33
+ r"""
34
+ Call hook after all processes have joined.
35
+
36
+ It is passed an additional ``bool`` argument ``is_last_joiner``, which indicates if the rank is one of the last to join.
37
+
38
+ Arguments:
39
+ is_last_joiner (bool): ``True`` if the rank is one of the last to
40
+ join; ``False`` otherwise.
41
+ """
42
+
43
+
44
+ class Joinable(ABC):
45
+ r"""
46
+ This defines an abstract base class for joinable classes.
47
+
48
+ A joinable class
49
+ (inheriting from :class:`Joinable`) should implement :meth:`join_hook`,
50
+ which returns a :class:`JoinHook` instance, in addition to
51
+ :meth:`join_device` and :meth:`join_process_group` that return device and
52
+ process group information, respectively.
53
+ """
54
+
55
+ @abstractmethod
56
+ def __init__(self) -> None:
57
+ super().__init__()
58
+ self._join_config = _JoinConfig.construct_disabled_join_config()
59
+
60
+ @abstractmethod
61
+ def join_hook(self, **kwargs) -> JoinHook:
62
+ r"""
63
+ Return a :class:`JoinHook` instance for the given :class:`Joinable`.
64
+
65
+ Arguments:
66
+ kwargs (dict): a :class:`dict` containing any keyword arguments
67
+ to modify the behavior of the join hook at run time; all
68
+ :class:`Joinable` instances sharing the same join context
69
+ manager are forwarded the same value for ``kwargs``.
70
+ """
71
+ ...
72
+
73
+ @property
74
+ @abstractmethod
75
+ def join_device(self) -> torch.device:
76
+ r"""Return the device from which to perform collective communications needed by the join context manager."""
77
+ ...
78
+
79
+ @property
80
+ @abstractmethod
81
+ def join_process_group(self) -> Any:
82
+ r"""Returns the process group for the collective communications needed by the join context manager itself."""
83
+ ...
84
+
85
+
86
+ class _JoinConfig(NamedTuple):
87
+ r"""This includes all fields needed from a :class:`Joinable` instance for the join context manager side."""
88
+
89
+ enable: bool
90
+ throw_on_early_termination: bool
91
+ is_first_joinable: bool
92
+
93
+ @staticmethod
94
+ def construct_disabled_join_config():
95
+ r"""Return a :class:`_JoinConfig` instance indicating that join-related logic should be disabled.
96
+
97
+ e.g. if the caller is not in a join context manager.
98
+ """
99
+ return _JoinConfig(
100
+ enable=False, throw_on_early_termination=False, is_first_joinable=False
101
+ )
102
+
103
+
104
+ class Join:
105
+ r"""
106
+ This class defines the generic join context manager, which allows custom hooks to be called after a process joins.
107
+
108
+ These hooks should shadow the
109
+ collective communications of non-joined processes to prevent hanging and
110
+ erroring and to ensure algorithmic correctness. Refer to :class:`JoinHook`
111
+ for details about the hook definition.
112
+
113
+ .. warning::
114
+ The context manager requires each participating :class:`Joinable` to
115
+ call the method :meth:`notify_join_context()` before its own per-
116
+ iteration collective communications to ensure correctness.
117
+
118
+ .. warning::
119
+ The context manager requires that all ``process_group`` attributes in
120
+ the :class:`JoinHook` objects are the same. If there are multiple
121
+ :class:`JoinHook` objects, then the ``device`` of the first is used.
122
+ The process group and device information is used for checking for non-
123
+ joined processes and for notifying processes to throw an exception if
124
+ ``throw_on_early_termination`` is enabled, both of which using an all-
125
+ reduce.
126
+
127
+ Arguments:
128
+ joinables (List[Joinable]): a list of the participating
129
+ :class:`Joinable` s; their hooks are iterated over in the given
130
+ order.
131
+
132
+ enable (bool): a flag enabling uneven input detection; setting to
133
+ ``False`` disables the context manager's functionality and should
134
+ only be set when the user knows the inputs will not be uneven
135
+ (default: ``True``).
136
+
137
+ throw_on_early_termination (bool): a flag controlling whether to throw an
138
+ exception upon detecting uneven inputs (default: ``False``).
139
+
140
+ Example::
141
+
142
+ >>> import os
143
+ >>> import torch
144
+ >>> import torch.distributed as dist
145
+ >>> import torch.multiprocessing as mp
146
+ >>> # xdoctest: +SKIP
147
+ >>> import torch.nn.parallel.DistributedDataParallel as DDP
148
+ >>> import torch.distributed.optim.ZeroRedundancyOptimizer as ZeRO
149
+ >>> from torch.distributed.algorithms.join import Join
150
+ >>>
151
+ >>> # On each spawned worker
152
+ >>> def worker(rank):
153
+ >>> dist.init_process_group("nccl", rank=rank, world_size=2)
154
+ >>> model = DDP(torch.nn.Linear(1, 1).to(rank), device_ids=[rank])
155
+ >>> optim = ZeRO(model.parameters(), torch.optim.Adam, lr=0.01)
156
+ >>> # Rank 1 gets one more input than rank 0
157
+ >>> inputs = [torch.tensor([1.]).to(rank) for _ in range(10 + rank)]
158
+ >>> with Join([model, optim]):
159
+ >>> for input in inputs:
160
+ >>> loss = model(input).sum()
161
+ >>> loss.backward()
162
+ >>> optim.step()
163
+ >>> # All ranks reach here without hanging/erroring
164
+ """
165
+
166
+ def __init__(
167
+ self,
168
+ joinables: list[Joinable],
169
+ enable: bool = True,
170
+ throw_on_early_termination: bool = False,
171
+ **kwargs,
172
+ ):
173
+ if len(joinables) == 0:
174
+ raise ValueError("The join context manager requires at least one joinable")
175
+ self._joinables = joinables
176
+ self._join_hooks = [
177
+ joinable.join_hook(**kwargs) for joinable in self._joinables
178
+ ]
179
+ self._enable = enable
180
+ self._throw_on_early_termination = throw_on_early_termination
181
+ self._set_joinable_configs()
182
+ self._extract_dist_info()
183
+
184
+ def _set_joinable_configs(self) -> None:
185
+ r"""Set the :class:`_JoinConfig` of each participating :class:`Joinable`."""
186
+ assert len(self._joinables) > 0
187
+ is_first_joinable = True
188
+ for joinable in self._joinables:
189
+ joinable._join_config = _JoinConfig(
190
+ enable=self._enable,
191
+ throw_on_early_termination=self._throw_on_early_termination,
192
+ is_first_joinable=is_first_joinable,
193
+ )
194
+ is_first_joinable = False
195
+
196
+ def _extract_dist_info(self) -> None:
197
+ r"""
198
+ Extract the process group and device information from the joinables.
199
+
200
+ If there are multiple joinables, then the context manager uses the
201
+ first specified device.
202
+
203
+ Preconditions:
204
+ ``self._joinables`` is not ``None`` and is non-empty.
205
+
206
+ Raises:
207
+ ValueError
208
+ If there are multiple conflicting ``process_group`` attributes
209
+ among the ``Joinable`` objects.
210
+ """
211
+ process_group = None
212
+ device = None
213
+ for joinable in self._joinables:
214
+ if process_group is None:
215
+ process_group = joinable.join_process_group
216
+ elif process_group != joinable.join_process_group:
217
+ raise ValueError(
218
+ "Using join context manager with multiple process groups"
219
+ )
220
+ if device is None:
221
+ device = joinable.join_device
222
+ self._process_group = process_group
223
+ self._rank = dist.get_rank(self._process_group)
224
+ self._device = device
225
+
226
+ def __enter__(self): ...
227
+
228
+ def __exit__(
229
+ self,
230
+ type: Optional[type[BaseException]],
231
+ value: Optional[BaseException],
232
+ traceback: Optional[TracebackType],
233
+ ):
234
+ r"""
235
+ Repeatedly runs the main hooks until all processes join; then, runs the post-hooks.
236
+
237
+ Raises:
238
+ RuntimeError
239
+ If ``throw_on_early_termination=True``.
240
+ """
241
+ if not self._enable or type:
242
+ return # propagate the exception directly if one was raised
243
+
244
+ all_procs_joined = False
245
+ is_last_joiner = True
246
+
247
+ i = 0
248
+ WARN_THRESHOLD = 1000
249
+ warnings.simplefilter("once")
250
+
251
+ while not all_procs_joined:
252
+ if i > WARN_THRESHOLD:
253
+ warnings.warn(
254
+ "Detected uneven input skew of greater than "
255
+ f"{WARN_THRESHOLD}. This means that rank "
256
+ f"{self._rank} has at least {WARN_THRESHOLD} "
257
+ f"fewer inputs than other currently-active ranks. "
258
+ "This level of skew could lead to performance "
259
+ "degradation during training."
260
+ )
261
+ # Shadow the all-reduce in non-joined processes
262
+ num_nonjoined_procs = self._get_num_nonjoined_procs()
263
+ if num_nonjoined_procs == 0:
264
+ all_procs_joined = True
265
+ else:
266
+ if self._throw_on_early_termination:
267
+ self._notify_procs_to_terminate()
268
+
269
+ # Run main hooks
270
+ for join_hook in self._join_hooks:
271
+ join_hook.main_hook()
272
+
273
+ is_last_joiner = False
274
+ i += 1
275
+
276
+ # Run post-hooks
277
+ for join_hook in self._join_hooks:
278
+ join_hook.post_hook(is_last_joiner)
279
+
280
+ def _get_num_nonjoined_procs(self):
281
+ r"""Return the number of non-joined processes by shadowing an all-reduce in the non-joined processes."""
282
+ num_nonjoined_procs = torch.zeros(1, device=self._device)
283
+ dist.all_reduce(num_nonjoined_procs, group=self._process_group)
284
+ return num_nonjoined_procs.item()
285
+
286
+ def _notify_procs_to_terminate(self):
287
+ r"""Schedule an all-reduce to notify non-joined processes to terminate.
288
+
289
+ Also raise a ``RuntimeError`` indicating that the current process has exhausted its inputs.
290
+ """
291
+ ones = torch.ones(1, device=self._device)
292
+ dist.all_reduce(ones, group=self._process_group)
293
+ raise RuntimeError(f"Rank {self._rank} exhausted all inputs.")
294
+
295
+ @staticmethod
296
+ def notify_join_context(joinable: Joinable):
297
+ r"""
298
+ Notifies the join context manager that the calling process has not yet joined.
299
+
300
+ Then, if ``throw_on_early_termination=True``, checks if uneven inputs have been detected
301
+ (i.e. if one process has already joined) and throws an exception if so.
302
+
303
+ This method should be called from a :class:`Joinable` object before
304
+ its per-iteration collective communications. For example, this should
305
+ be called at the beginning of the forward pass in
306
+ :class:`DistributedDataParallel`.
307
+
308
+ Only the first :class:`Joinable` object passed into the context
309
+ manager performs the collective communications in this method, and
310
+ for the others, this method is vacuous.
311
+
312
+ Arguments:
313
+ joinable (Joinable): the :class:`Joinable` object calling this
314
+ method.
315
+
316
+ Returns:
317
+ An async work handle for the all-reduce meant to notify the context
318
+ manager that the process has not yet joined if ``joinable`` is the
319
+ first one passed into the context manager; ``None`` otherwise.
320
+ """
321
+ assert hasattr(joinable, "_join_config"), (
322
+ f"Check that the {type(joinable)} constructor calls the "
323
+ "``Joinable`` constructor"
324
+ )
325
+
326
+ join_config = joinable._join_config
327
+ # First joinable is responsible for the collective communications
328
+ if not join_config.is_first_joinable or not join_config.enable:
329
+ return None
330
+
331
+ device = joinable.join_device
332
+ process_group = joinable.join_process_group
333
+
334
+ # Schedule an all-reduce to indicate that the caller has not yet joined
335
+ ones = torch.ones(1, device=device)
336
+ work = dist.all_reduce(ones, group=process_group, async_op=True)
337
+
338
+ if join_config.throw_on_early_termination:
339
+ # Check if uneven inputs have been detected
340
+ zeros = torch.zeros(1, device=device)
341
+ dist.all_reduce(zeros, group=process_group)
342
+ should_throw = zeros.item()
343
+ if should_throw:
344
+ raise RuntimeError(
345
+ "Detected at least one rank that exhausted inputs. "
346
+ "Throwing across all ranks."
347
+ )
348
+ return work
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import _extension
2
+ from .api import CheckpointException
3
+ from .default_planner import DefaultLoadPlanner, DefaultSavePlanner
4
+ from .filesystem import FileSystemReader, FileSystemWriter
5
+ from .hf_storage import HuggingFaceStorageReader, HuggingFaceStorageWriter
6
+ from .metadata import (
7
+ BytesStorageMetadata,
8
+ ChunkStorageMetadata,
9
+ Metadata,
10
+ TensorStorageMetadata,
11
+ )
12
+ from .optimizer import load_sharded_optimizer_state_dict
13
+ from .planner import LoadPlan, LoadPlanner, ReadItem, SavePlan, SavePlanner, WriteItem
14
+ from .state_dict_loader import load, load_state_dict
15
+ from .state_dict_saver import async_save, save, save_state_dict
16
+ from .storage import StorageReader, StorageWriter
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_async_process_executor.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pyre-strict
2
+ # mypy: allow-untyped-defs
3
+ import logging
4
+ import os
5
+ from concurrent.futures import Future, ThreadPoolExecutor
6
+ from dataclasses import dataclass
7
+ from enum import Enum
8
+ from typing import Any, Optional, Union
9
+ from uuid import uuid4
10
+
11
+ import torch.distributed as dist
12
+ import torch.multiprocessing as mp
13
+ from torch.distributed.checkpoint._async_executor import _AsyncCheckpointExecutor
14
+ from torch.distributed.checkpoint.logger import _dcp_method_logger, _init_logger
15
+ from torch.distributed.checkpoint.metadata import Metadata, STATE_DICT_TYPE
16
+ from torch.distributed.checkpoint.planner import SavePlanner
17
+ from torch.distributed.checkpoint.storage import StorageWriter
18
+ from torch.distributed.checkpoint.utils import _DistWrapper
19
+ from torch.distributed.elastic.agent.server.api import _get_fq_hostname
20
+ from torch.distributed.elastic.utils.distributed import get_free_port
21
+
22
+
23
+ logger = logging.getLogger()
24
+
25
+
26
+ class _CheckpointSaveProcessControlOpts(Enum):
27
+ INIT_COMPLETE = "init_complete"
28
+ TERMINATE = "terminate"
29
+
30
+
31
+ @dataclass(init=False, unsafe_hash=True)
32
+ class _CheckpointRequestIdentifier:
33
+ checkpoint_id: Union[str, os.PathLike, None]
34
+ uuid: str
35
+
36
+ def __init__(self, checkpoint_id: Union[str, os.PathLike, None]):
37
+ self.checkpoint_id = checkpoint_id
38
+ self.uuid = str(uuid4())
39
+
40
+
41
+ @dataclass
42
+ class _AsyncCheckpointRequest:
43
+ staged_state_dict: STATE_DICT_TYPE
44
+ checkpoint_request_id: _CheckpointRequestIdentifier
45
+ storage_writer: Optional[StorageWriter] = None
46
+ planner: Optional[SavePlanner] = None
47
+
48
+
49
+ @dataclass(init=False)
50
+ class _ProcessGroupInitInfo:
51
+ local_rank: int
52
+ global_rank: int
53
+ world_size: int
54
+ tcp_store_master_addr: str
55
+ tcp_store_master_port: int
56
+
57
+ def __init__(self, process_group: Optional[dist.ProcessGroup] = None):
58
+ self.local_rank = dist.get_node_local_rank(fallback_rank=0)
59
+ self.global_rank = dist.get_rank(process_group)
60
+ self.world_size = dist.get_world_size(process_group)
61
+
62
+ # Let coordinator rank find a free port on the localhost.
63
+ # Broadcast the (master_addr, free_port) to all ranks; each rank in the
64
+ # checkpoint daemon process will use TCPStore (master_addr, master_port)
65
+ # for collective communication.
66
+ dist_wrapper: _DistWrapper = _DistWrapper(
67
+ group=process_group,
68
+ use_dist=True,
69
+ coordinator_rank=0,
70
+ )
71
+
72
+ def get_master_addr_and_port() -> tuple[str, int]:
73
+ master_addr = os.environ.get("MASTER_ADDR")
74
+ if master_addr is None:
75
+ master_addr = _get_fq_hostname()
76
+ return master_addr, get_free_port()
77
+
78
+ self.tcp_store_master_addr, self.tcp_store_master_port = dist_wrapper.broadcast(
79
+ step="get_master_addr_and_port",
80
+ map_fun=get_master_addr_and_port,
81
+ )
82
+
83
+
84
+ class _AsyncCheckpointProcess:
85
+ def __init__(
86
+ self,
87
+ pg_init_info: _ProcessGroupInitInfo,
88
+ ):
89
+ self.ctx = mp.get_context("spawn")
90
+ self._process_pipe, child_end = self.ctx.Pipe()
91
+
92
+ self._save_process = self.ctx.Process(
93
+ target=self._checkpointing_subprocess,
94
+ args=(
95
+ pg_init_info,
96
+ child_end,
97
+ ),
98
+ daemon=True,
99
+ )
100
+
101
+ self._save_process.start()
102
+
103
+ # Close the parent's copy of child end after we pass it into the child,
104
+ # so the recv()s on it will fail-fast if the child process dies.
105
+ child_end.close()
106
+
107
+ # Wait for the checkpoint background process to initialize.
108
+ # Using default GLOO init timeout.
109
+ response = self._wait_for_response(timeout=1800)
110
+ assert response == _CheckpointSaveProcessControlOpts.INIT_COMPLETE
111
+
112
+ def __del__(self) -> None:
113
+ if self._save_process.is_alive():
114
+ logger.info("Terminating the checkpoint background process...")
115
+ self._send(_CheckpointSaveProcessControlOpts.TERMINATE)
116
+ self._save_process.join()
117
+
118
+ def _send(self, data: Any) -> None:
119
+ self._process_pipe.send(data)
120
+
121
+ def _wait_for_response(self, timeout: Optional[float] = None) -> Any:
122
+ if not self._save_process.is_alive():
123
+ logger.info("Checkpoint background process is dead calling join()...")
124
+ self._save_process.join()
125
+ raise RuntimeError(
126
+ f"Checkpoint background process is dead. Exit code: {self._save_process.exitcode}"
127
+ )
128
+
129
+ if timeout is not None and not self._process_pipe.poll(timeout=timeout):
130
+ raise RuntimeError(
131
+ f"Timed out after {timeout}s while waiting for response from checkpointer process pid: {self._save_process.pid}"
132
+ )
133
+
134
+ try:
135
+ response = self._process_pipe.recv()
136
+ except EOFError:
137
+ raise RuntimeError( # noqa: B904
138
+ f"Checkpoint background process is dead. Exit code: {self._save_process.exitcode}"
139
+ )
140
+
141
+ if isinstance(response, BaseException):
142
+ raise response
143
+
144
+ return response
145
+
146
+ def save(
147
+ self,
148
+ staged_state_dict: STATE_DICT_TYPE,
149
+ *,
150
+ checkpoint_id: Union[str, os.PathLike, None] = None,
151
+ storage_writer: Optional[StorageWriter] = None,
152
+ planner: Optional[SavePlanner] = None,
153
+ ) -> Metadata:
154
+ # Create a unique identifier to locate requests/responses
155
+ # from the checkpoint daemon process.
156
+ checkpoint_request_id = _CheckpointRequestIdentifier(checkpoint_id)
157
+ async_cp_request = _AsyncCheckpointRequest(
158
+ staged_state_dict=staged_state_dict,
159
+ checkpoint_request_id=checkpoint_request_id,
160
+ storage_writer=storage_writer,
161
+ planner=planner,
162
+ )
163
+ self._send(async_cp_request)
164
+ result = self._wait_for_response()
165
+ assert isinstance(result, Metadata)
166
+ return result
167
+
168
+ @staticmethod
169
+ def _execute_save(
170
+ state_dict: STATE_DICT_TYPE,
171
+ *,
172
+ checkpoint_request_id: _CheckpointRequestIdentifier,
173
+ storage_writer: Optional[StorageWriter] = None,
174
+ planner: Optional[SavePlanner] = None,
175
+ ) -> Metadata:
176
+ from torch.distributed.checkpoint.state_dict_saver import save
177
+
178
+ metadata = save(
179
+ state_dict,
180
+ checkpoint_id=checkpoint_request_id.checkpoint_id,
181
+ storage_writer=storage_writer,
182
+ planner=planner,
183
+ )
184
+ return metadata
185
+
186
+ @staticmethod
187
+ def _checkpointing_subprocess(
188
+ pg_init_info: _ProcessGroupInitInfo,
189
+ parent_conn,
190
+ ) -> None:
191
+ try:
192
+ _init_logger(pg_init_info.global_rank)
193
+
194
+ # Setup environment variables for process group initialization.
195
+ os.environ["TORCHELASTIC_USE_AGENT_STORE"] = "False"
196
+ os.environ["MASTER_ADDR"] = pg_init_info.tcp_store_master_addr
197
+ os.environ["MASTER_PORT"] = str(pg_init_info.tcp_store_master_port)
198
+ os.environ["LOCAL_RANK"] = str(pg_init_info.local_rank)
199
+ os.environ["RANK"] = str(pg_init_info.global_rank)
200
+ os.environ["WORLD_SIZE"] = str(pg_init_info.world_size)
201
+
202
+ logger.info(
203
+ "Initializing dist.ProcessGroup in checkpoint background process"
204
+ )
205
+ # NOTE: GLOO backend is enforced here.
206
+ dist.init_process_group(backend=dist.Backend.GLOO)
207
+ dist.barrier()
208
+
209
+ logger.info("Checkpoint background process is running...")
210
+ parent_conn.send(_CheckpointSaveProcessControlOpts.INIT_COMPLETE)
211
+
212
+ # Serving loop.
213
+ while True:
214
+ logger.info("Waiting for checkpoint save request...")
215
+ obj = parent_conn.recv()
216
+ if (
217
+ isinstance(obj, _CheckpointSaveProcessControlOpts)
218
+ and obj == _CheckpointSaveProcessControlOpts.TERMINATE
219
+ ):
220
+ logger.info("Terminating the checkpoint background process.")
221
+ return
222
+ assert isinstance(obj, _AsyncCheckpointRequest)
223
+ logger.info(
224
+ f"Received async checkpoint request with id={obj.checkpoint_request_id.checkpoint_id}" # noqa: G004
225
+ )
226
+
227
+ response = _AsyncCheckpointProcess._execute_save(
228
+ obj.staged_state_dict,
229
+ checkpoint_request_id=obj.checkpoint_request_id,
230
+ storage_writer=obj.storage_writer,
231
+ planner=obj.planner,
232
+ )
233
+ parent_conn.send(response)
234
+ logger.info(
235
+ f"Submitted checkpoint save request for checkpoint_id={obj.checkpoint_request_id}" # noqa: G004
236
+ )
237
+ except BaseException as e:
238
+ logger.error(
239
+ f"Checkpoint background process encountered an exception: {e}" # noqa: G004
240
+ )
241
+ parent_conn.send(e)
242
+ raise
243
+ finally:
244
+ logger.info("Checkpoint background process is shutting down...")
245
+ dist.destroy_process_group()
246
+ parent_conn.close()
247
+
248
+
249
+ _CHECKPOINT_PROCESS: Optional[_AsyncCheckpointProcess] = None
250
+
251
+
252
+ class _ProcessBasedAsyncCheckpointExecutor(_AsyncCheckpointExecutor):
253
+ def __init__(self) -> None:
254
+ self._executor = ThreadPoolExecutor(max_workers=1)
255
+
256
+ @staticmethod
257
+ def _execute_save_impl(
258
+ *,
259
+ pg_init_info: Optional[_ProcessGroupInitInfo],
260
+ staged_state_dict: STATE_DICT_TYPE,
261
+ checkpoint_id: Union[str, os.PathLike, None] = None,
262
+ storage_writer: Optional[StorageWriter] = None,
263
+ planner: Optional[SavePlanner] = None,
264
+ process_group: Optional[dist.ProcessGroup] = None,
265
+ ) -> Metadata:
266
+ global _CHECKPOINT_PROCESS
267
+ if _CHECKPOINT_PROCESS is None:
268
+ assert pg_init_info is not None
269
+ ckpt_kwargs = {}
270
+ if (ckpt_id := getattr(storage_writer, "checkpoint_id", None)) is not None:
271
+ ckpt_kwargs["checkpoint_id"] = ckpt_id
272
+ ckpt_kwargs["process_group"] = process_group
273
+
274
+ @_dcp_method_logger(**ckpt_kwargs)
275
+ def create_checkpoint_daemon_process() -> None:
276
+ global _CHECKPOINT_PROCESS
277
+ _CHECKPOINT_PROCESS = _AsyncCheckpointProcess(pg_init_info=pg_init_info)
278
+
279
+ create_checkpoint_daemon_process()
280
+
281
+ assert _CHECKPOINT_PROCESS is not None
282
+ return _CHECKPOINT_PROCESS.save(
283
+ staged_state_dict=staged_state_dict,
284
+ checkpoint_id=checkpoint_id,
285
+ storage_writer=storage_writer,
286
+ planner=planner,
287
+ )
288
+
289
+ def execute_save(
290
+ self,
291
+ staged_state_dict: STATE_DICT_TYPE,
292
+ *,
293
+ checkpoint_id: Union[str, os.PathLike, None] = None,
294
+ storage_writer: Optional[StorageWriter] = None,
295
+ planner: Optional[SavePlanner] = None,
296
+ process_group: Optional[dist.ProcessGroup] = None,
297
+ ) -> Future:
298
+ """
299
+ NOTE:
300
+
301
+ - Checkpoint process is implemented as a daemon process.
302
+ The AsyncCheckpointProcess' lifetime is tied to the lifetime of the
303
+ main process (e.g. trainer process).
304
+
305
+ - The first call to execute_save_in_process() will initialize the checkpoint
306
+ daemon process. Subsequent async checkpoint requests will not need process
307
+ initialization. Therefore, the first async checkpoint request will take longer to complete.
308
+
309
+ - Process initialization can have significant overhead, dominated by latency for all ranks to spawn
310
+ a background process + process group initialization in the background process.
311
+ """
312
+
313
+ global _CHECKPOINT_PROCESS
314
+ pg_init_info: Optional[_ProcessGroupInitInfo] = None
315
+ if _CHECKPOINT_PROCESS is None:
316
+ # Find a free port on coordinator rank and broadcast
317
+ # to all ranks.
318
+ pg_init_info = _ProcessGroupInitInfo(process_group)
319
+
320
+ f: Future = self._executor.submit(
321
+ self._execute_save_impl,
322
+ pg_init_info=pg_init_info,
323
+ staged_state_dict=staged_state_dict,
324
+ checkpoint_id=checkpoint_id,
325
+ storage_writer=storage_writer,
326
+ planner=planner,
327
+ )
328
+ f.add_done_callback(lambda f: self._executor.shutdown(wait=False))
329
+
330
+ return f
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_async_thread_executor.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pyre-strict
2
+ # mypy: allow-untyped-defs
3
+ import os
4
+ from concurrent.futures import Future, ThreadPoolExecutor
5
+ from typing import Optional, Union
6
+
7
+ import torch.distributed as dist
8
+ from torch.distributed.checkpoint._async_executor import _AsyncCheckpointExecutor
9
+ from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE
10
+ from torch.distributed.checkpoint.planner import SavePlanner
11
+ from torch.distributed.checkpoint.storage import StorageWriter
12
+
13
+
14
+ class _ThreadBasedAsyncCheckpointExecutor(_AsyncCheckpointExecutor):
15
+ def __init__(self) -> None:
16
+ self._executor = ThreadPoolExecutor(max_workers=1)
17
+
18
+ def execute_save(
19
+ self,
20
+ staged_state_dict: STATE_DICT_TYPE,
21
+ *,
22
+ checkpoint_id: Union[str, os.PathLike, None] = None,
23
+ storage_writer: Optional[StorageWriter] = None,
24
+ planner: Optional[SavePlanner] = None,
25
+ process_group: Optional[dist.ProcessGroup] = None,
26
+ ) -> Future:
27
+ from torch.distributed.checkpoint.state_dict_saver import save
28
+
29
+ f: Future = self._executor.submit(
30
+ save,
31
+ staged_state_dict,
32
+ checkpoint_id=checkpoint_id,
33
+ storage_writer=storage_writer,
34
+ planner=planner,
35
+ process_group=process_group,
36
+ )
37
+ f.add_done_callback(lambda f: self._executor.shutdown(wait=False))
38
+
39
+ return f
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_checkpointer.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from concurrent.futures import Future
2
+ from typing import Any, Optional
3
+
4
+ import torch.distributed as dist
5
+ import torch.distributed.checkpoint.state_dict_loader as loader
6
+ import torch.distributed.checkpoint.state_dict_saver as saver
7
+ from torch.distributed.checkpoint.metadata import Metadata, STATE_DICT_TYPE
8
+ from torch.distributed.checkpoint.storage import (
9
+ LoadPlanner,
10
+ SavePlanner,
11
+ StorageReader,
12
+ StorageWriter,
13
+ )
14
+
15
+
16
+ __all__: list[str] = []
17
+
18
+
19
+ class _Checkpointer:
20
+ """This base class specefies a high level API for saving and loading
21
+ distributed `state_dict` 's. It provides an abstraction over the low-level APIs
22
+ provided by :py:mod:`torch.distributed.checkpoint.storage`, essentially calling
23
+ :py:meth: `torch.distributed.state_dict_saver.save` and
24
+ :py:meth: `torch.distributed.state_dict_loader.load` with the provided storage
25
+ readers and writers.
26
+
27
+ .. warning::
28
+ This feature is experimental and subject to removal/change.
29
+
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ storage_writer: StorageWriter,
35
+ storage_reader: StorageReader,
36
+ *,
37
+ process_group: Optional[dist.ProcessGroup] = None,
38
+ coordinator_rank: int = 0,
39
+ no_dist: bool = False,
40
+ load_planner: Optional[LoadPlanner] = None,
41
+ save_planner: Optional[SavePlanner] = None,
42
+ ):
43
+ """Initializes the Checkpointer instance.
44
+
45
+ Args:
46
+ storage_writer: Instance of StorageWrite use to perform writes.
47
+ storage_reader: StorageReader used to load data from.
48
+ process_group: ProcessGroup to be used for cross-rank synchronization.
49
+ coordinator_rank: Rank to use to coordinate the checkpoint. rank0 is used by default.
50
+ no_dist: If ``True``, distributed checkpoint will not load in SPMD style. (Default: ``False``)
51
+ loader_planner: Instance of LoadPlanner to use when loading.
52
+ save_planner: Instance of SavePlanner to use when saving.
53
+ """
54
+ self.storage_writer = storage_writer
55
+ self.storage_reader = storage_reader
56
+ self.process_group = process_group
57
+ self.coordinator_rank = coordinator_rank
58
+ self.no_dist = no_dist
59
+ self.load_planner = load_planner
60
+ self.save_planner = save_planner
61
+
62
+ def save(
63
+ self,
64
+ state_dict: STATE_DICT_TYPE,
65
+ ) -> Metadata:
66
+ """Calls :py:meth: `torch.distributed.state_dict_saver.save`. Utilizing values passed during initialization."""
67
+ return saver.save(
68
+ state_dict,
69
+ self.storage_writer,
70
+ process_group=self.process_group,
71
+ coordinator_rank=self.coordinator_rank,
72
+ no_dist=self.no_dist,
73
+ planner=self.save_planner,
74
+ )
75
+
76
+ def async_save(
77
+ self,
78
+ state_dict: STATE_DICT_TYPE,
79
+ ) -> Future:
80
+ """
81
+ Calls :py:meth: `torch.distributed.state_dict_saver._async_save`. Utilizing values passed during initialization.
82
+
83
+ Returns:
84
+ Future: A future holding the resultant Metadata object from `save`.
85
+ """
86
+ return saver.async_save(
87
+ state_dict,
88
+ storage_writer=self.storage_writer,
89
+ process_group=self.process_group,
90
+ planner=self.save_planner,
91
+ )
92
+
93
+ def load(self, state_dict: dict[str, Any]) -> None:
94
+ """Calls :py:meth: `torch.distributed.state_dict_loader.load`. Utilizing values passed during initialization."""
95
+ loader.load(
96
+ state_dict,
97
+ storage_reader=self.storage_reader,
98
+ process_group=self.process_group,
99
+ planner=self.load_planner,
100
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_dedup_tensors.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ import dataclasses
3
+ import logging
4
+ from typing import TYPE_CHECKING
5
+
6
+ from torch.distributed.checkpoint.planner import SavePlan
7
+
8
+
9
+ if TYPE_CHECKING:
10
+ from torch.distributed.checkpoint.metadata import MetadataIndex
11
+
12
+ __all__ = ["dedup_tensors"]
13
+
14
+
15
+ def init_logger() -> logging.Logger:
16
+ logger = logging.getLogger(__name__)
17
+ level = logging.INFO
18
+ logger.setLevel(level)
19
+ console = logging.StreamHandler()
20
+ formatter = logging.Formatter(
21
+ "%(asctime)s %(filename)s:%(lineno)s %(levelname)s p:%(processName)s t:%(threadName)s: %(message)s"
22
+ )
23
+ console.setFormatter(formatter)
24
+ console.setLevel(level)
25
+ logger.addHandler(console)
26
+ logger.propagate = False
27
+ return logger
28
+
29
+
30
+ logger = init_logger()
31
+
32
+
33
+ # TODO add docstring for dedup_tensors
34
+ def dedup_tensors(all_plans: list[SavePlan]) -> list[SavePlan]:
35
+ all_plans = list(all_plans)
36
+ key_to_plan: dict[MetadataIndex, list[int]] = {}
37
+ for plan_idx, plan in enumerate(all_plans):
38
+ for write_item in plan.items:
39
+ key_to_plan.setdefault(write_item.index, []).append(plan_idx)
40
+
41
+ replicated_items = {k: v for k, v in key_to_plan.items() if len(v) > 1}
42
+
43
+ # Remove duplicates by always keeping the first entry.
44
+ # Compute the per-rank remove set.
45
+ plan_to_keys: dict[int, list[MetadataIndex]] = {}
46
+ for key, plans in replicated_items.items():
47
+ for plan_idx in plans[1:]:
48
+ plan_to_keys.setdefault(plan_idx, []).append(key)
49
+ if len(plan_to_keys) > 0:
50
+ logger.info("Duplicate keys to remove: %s", plan_to_keys)
51
+
52
+ for plan_idx, keys in plan_to_keys.items():
53
+ key_set = set(keys)
54
+ # rewrite items and remove elements
55
+ new_items = [
56
+ write_item
57
+ for write_item in all_plans[plan_idx].items
58
+ if write_item.index not in key_set
59
+ ]
60
+ all_plans[plan_idx] = dataclasses.replace(all_plans[plan_idx], items=new_items)
61
+
62
+ return all_plans
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_fsspec_filesystem.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Mypy will not try inferring the types of any 3rd party libraries installed.
2
+ # mypy: ignore-errors
3
+
4
+ import io
5
+ import os
6
+ from collections.abc import Generator, Sequence
7
+ from contextlib import contextmanager
8
+ from pathlib import Path
9
+ from typing import Optional, TYPE_CHECKING, Union
10
+
11
+ from fsspec.core import url_to_fs
12
+
13
+ from torch.distributed.checkpoint._extension import StreamTransformExtension
14
+ from torch.distributed.checkpoint.filesystem import (
15
+ FileSystemBase,
16
+ FileSystemReader,
17
+ FileSystemWriter,
18
+ SerializationFormat,
19
+ )
20
+
21
+
22
+ if TYPE_CHECKING:
23
+ from fsspec import AbstractFileSystem
24
+
25
+
26
+ __all__ = [
27
+ "FsspecWriter",
28
+ "FsspecReader",
29
+ ]
30
+
31
+
32
+ class FileSystem(FileSystemBase):
33
+ def __init__(self) -> None:
34
+ self.fs: Optional[AbstractFileSystem] = None
35
+
36
+ @contextmanager
37
+ def create_stream(
38
+ self, path: Union[str, os.PathLike], mode: str
39
+ ) -> Generator[io.IOBase, None, None]:
40
+ assert self.fs is not None
41
+ path = os.fspath(path)
42
+
43
+ # fsspec does not support concurrent transactions, and not all
44
+ # AbstractFileSystem have working rollback implementations, so
45
+ # just manually delete the file if necessary on errors.
46
+ with self.fs.open(path, mode) as stream:
47
+ try:
48
+ yield stream
49
+ except: # noqa: B001,E722
50
+ if any(ch in mode for ch in "w+a"): # cleanup file if not read-only
51
+ try:
52
+ self.rm_file(path)
53
+ except: # noqa: B001,E722
54
+ pass
55
+ raise
56
+
57
+ def concat_path(
58
+ self, path: Union[str, os.PathLike], suffix: str
59
+ ) -> Union[str, os.PathLike]:
60
+ return os.path.join(path, suffix)
61
+
62
+ def init_path(
63
+ self, path: Union[str, os.PathLike], **kwargs
64
+ ) -> Union[str, os.PathLike]:
65
+ self.fs, _ = url_to_fs(path, **kwargs)
66
+ return path
67
+
68
+ def rename(
69
+ self, path: Union[str, os.PathLike], new_path: Union[str, os.PathLike]
70
+ ) -> None:
71
+ self.fs.rename(path, new_path)
72
+
73
+ def mkdir(self, path: Union[str, os.PathLike]) -> None:
74
+ self.fs.makedirs(path, exist_ok=True)
75
+
76
+ @classmethod
77
+ def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
78
+ if isinstance(checkpoint_id, Path):
79
+ return False
80
+
81
+ try:
82
+ url_to_fs(checkpoint_id)
83
+ except ValueError:
84
+ return False
85
+
86
+ return True
87
+
88
+ def exists(self, path: Union[str, os.PathLike]) -> bool:
89
+ return self.fs.exists(path)
90
+
91
+ def rm_file(self, path: Union[str, os.PathLike]) -> None:
92
+ self.fs.rm(path)
93
+
94
+ def ls(self, path: Union[str, os.PathLike]) -> list[str]:
95
+ # setting detail to False explicitly to keep the list[str] return type,
96
+ # instead of the list[Dict] return type when detail=True
97
+ return self.fs.ls(path, detail=False)
98
+
99
+
100
+ # TODO: add the dcp.async_save mixin
101
+ class FsspecWriter(FileSystemWriter):
102
+ """
103
+ Basic implementation of StorageWriter using FFspec.
104
+
105
+ This implementation makes the following assumptions and simplifications:
106
+
107
+ * The checkpoint path is an empty or non-existing directory.
108
+ * File creation is atomic
109
+
110
+ The checkpoint consist of one file per write request plus
111
+ a `.metadata` file with the serialized metadata.
112
+
113
+ """
114
+
115
+ def __init__(
116
+ self,
117
+ path: Union[str, os.PathLike],
118
+ single_file_per_rank: bool = True,
119
+ sync_files: bool = True,
120
+ thread_count: int = 1,
121
+ per_thread_copy_ahead: int = 10_000_000,
122
+ overwrite: bool = True,
123
+ _extensions: Optional[Sequence[StreamTransformExtension]] = None,
124
+ serialization_format: SerializationFormat = SerializationFormat.TORCH_SAVE,
125
+ **kwargs,
126
+ ) -> None:
127
+ """
128
+ Initialize the writer pointing to `path`.
129
+
130
+ Args:
131
+ path: directory where the checkpoint will be written to.
132
+ single_file_per_rank: Produce one file per rank instead of one file per tensor/blob. Default to True.
133
+ sync_files : force files to be synced to permanent storage. Default to True.
134
+ thread_count: Number of IO threads to use to write. Default to 1.
135
+ per_thread_copy_ahead: How many bytes to copy from the GPU ahead of saving then. Default 10Mb.
136
+ overwrite: Whether to allow overwriting existing checkpoints. Defaults to True.
137
+ _extensions: Extensions to apply to output streams (EXPERIMENTAL)
138
+
139
+ N. B. If sync_files is disabled, there's no guarantee that the checkpoint will be consistent in the case of a failure.
140
+ """
141
+ super().__init__(
142
+ path,
143
+ single_file_per_rank,
144
+ sync_files,
145
+ thread_count,
146
+ per_thread_copy_ahead,
147
+ overwrite=overwrite,
148
+ _extensions=_extensions,
149
+ serialization_format=serialization_format,
150
+ )
151
+ self.fs = FileSystem()
152
+ self.path = self.fs.init_path(path, **kwargs)
153
+
154
+ @classmethod
155
+ def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
156
+ return FileSystem.validate_checkpoint_id(checkpoint_id)
157
+
158
+
159
+ class FsspecReader(FileSystemReader):
160
+ def __init__(self, path: Union[str, os.PathLike], **kwargs) -> None:
161
+ super().__init__(path)
162
+ self.fs = FileSystem()
163
+ self.path = self.fs.init_path(path, **kwargs)
164
+
165
+ @classmethod
166
+ def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
167
+ return FileSystem.validate_checkpoint_id(checkpoint_id)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_hf_utils.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import json
3
+ import struct
4
+ from dataclasses import dataclass
5
+ from typing import Any, Optional
6
+
7
+ import torch
8
+
9
+
10
+ _metadata_fn: str = "model.safetensors.index.json"
11
+
12
+ FILE_NAME = "model-{cpt_idx}-of-{num_files}"
13
+ SHARDED_FILE_NAME = "shard-{shard_idx}-model-{cpt_idx}-of-{num_files}"
14
+ SUFFIX = ".safetensors"
15
+
16
+ # metadata keys
17
+ CUSTOM_METADATA_KEY = "DCP_SHARDING_INFO"
18
+ DEFAULT_EXTRA_METADATA_KEY = "__metadata__"
19
+ SAVED_OFFSETS_KEY = "saved_offsets"
20
+ SHAPE_KEY = "shape"
21
+ DATA_KEY = "data"
22
+ DTYPE_KEY = "dtype"
23
+ DATA_OFFSETS_KEY = "data_offsets"
24
+
25
+ DTYPE_MAP = {
26
+ "F16": torch.float16,
27
+ "F32": torch.float32,
28
+ "F64": torch.float64,
29
+ "I8": torch.int8,
30
+ "U8": torch.uint8,
31
+ "I16": torch.int16,
32
+ "I32": torch.int32,
33
+ "I64": torch.int64,
34
+ "BF16": torch.bfloat16,
35
+ }
36
+
37
+ HF_DCP_VERSION: float = 1.0
38
+ DCP_VERSION_KEY = "DCP_VERSION"
39
+ DCP_SHARDING_INFO_KEY = "DCP_SHARDING_INFO"
40
+
41
+ FORMAT_KEY = "format"
42
+ FORMAT_VALUE = "pt"
43
+
44
+
45
+ @dataclass
46
+ class _HFStorageInfo:
47
+ """This is the per entry storage info."""
48
+
49
+ relative_path: str
50
+ offset: int
51
+ length: int
52
+ shape: torch.Size
53
+ dtype: torch.dtype
54
+
55
+
56
+ def _gen_file_name(
57
+ index: int, largest_index: int, shard_index: Optional[int] = None
58
+ ) -> str:
59
+ if shard_index is not None:
60
+ return (
61
+ SHARDED_FILE_NAME.format(
62
+ shard_idx=f"{shard_index}".zfill(5),
63
+ cpt_idx=f"{index}".zfill(5),
64
+ num_files=f"{largest_index}".zfill(5),
65
+ )
66
+ + SUFFIX
67
+ )
68
+ else:
69
+ return (
70
+ FILE_NAME.format(
71
+ cpt_idx=f"{index}".zfill(5), num_files=f"{largest_index}".zfill(5)
72
+ )
73
+ + SUFFIX
74
+ )
75
+
76
+
77
+ def _get_safetensors_file_metadata(file_bytes: io.IOBase) -> tuple[Any, int]:
78
+ # this uses the same logic that's done in HF code base
79
+ # https://github.com/2404589803/huggingface_hub/blob/main/src/huggingface_hub/hf_api.py#L5308
80
+ # and follows their documentation on how their files are serialized
81
+ # https://huggingface.co/docs/safetensors/index#format
82
+
83
+ num_bytes_for_header_len = 8
84
+ header_len_bytes = file_bytes.read(num_bytes_for_header_len)
85
+ header_len = struct.unpack("<Q", header_len_bytes)[0]
86
+ header_json = file_bytes.read(header_len)
87
+ metadata = json.loads(header_json)
88
+ return (metadata, header_len + num_bytes_for_header_len)
89
+
90
+
91
+ def _get_dtype(dtype_str: str) -> torch.dtype:
92
+ try:
93
+ dtype = DTYPE_MAP[dtype_str]
94
+ except KeyError:
95
+ dtype = torch.get_default_dtype()
96
+
97
+ return dtype
98
+
99
+
100
+ def _get_dcp_custom_metadata(metadata: Any) -> Optional[Any]:
101
+ if DEFAULT_EXTRA_METADATA_KEY in metadata:
102
+ custom_metadata = metadata[DEFAULT_EXTRA_METADATA_KEY]
103
+ if CUSTOM_METADATA_KEY in custom_metadata:
104
+ return json.loads(custom_metadata[CUSTOM_METADATA_KEY])
105
+ return None
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_nested_dict.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+
3
+ from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE
4
+
5
+ from . import _version
6
+ from ._traverse import (
7
+ OBJ_PATH,
8
+ set_element,
9
+ STATE_DICT_ITEM,
10
+ traverse_state_dict,
11
+ traverse_state_dict_v_2_3,
12
+ )
13
+
14
+
15
+ """
16
+ TODO:
17
+ Need to add ability to handle tuple, OrderedDict, NamedTuple.
18
+ Update mappings from dict to a class.
19
+ Change set_element to recreate the right type for tuple, OrderedDict, and NamedTuple.
20
+ """
21
+
22
+
23
+ FLATTEN_MAPPING = dict[str, OBJ_PATH]
24
+
25
+
26
+ # TODO: Update Docstring for nested_dict.py
27
+ def flatten_state_dict(
28
+ state_dict: STATE_DICT_TYPE,
29
+ ) -> tuple[STATE_DICT_TYPE, FLATTEN_MAPPING]:
30
+ """
31
+ Flatten ``state_dict`` made of nested dicts and lists into a top level dictionary.
32
+
33
+ Use ``unflatten_state_dict`` to revert this process.
34
+ Returns:
35
+ A tuple with the flatten state_dict and a mapping from original to new state_dict.
36
+ N.B. The new keys are derived from the object paths, joined by dot.
37
+ For example: ``{ 'a': {'b':...}}`` results in the key `a.b`.
38
+ """
39
+ flattened: STATE_DICT_TYPE = {}
40
+ mappings: FLATTEN_MAPPING = {}
41
+
42
+ def flat_copy(path: OBJ_PATH, value: STATE_DICT_ITEM) -> None:
43
+ new_fqn = ".".join(map(str, path))
44
+ if new_fqn in flattened:
45
+ raise ValueError(f"duplicated flatten key {new_fqn}")
46
+ flattened[new_fqn] = value
47
+ mappings[new_fqn] = path
48
+
49
+ # We started to flatten dictionary since v2.4. But in order to not break
50
+ # the checkpoints that were saved before v2.4, we need to keep the old
51
+ # traversal so that we can reconstruct those checkpoints.
52
+ use_v_2_3 = (
53
+ _version._derived_version is not None and _version._derived_version == "2_3"
54
+ )
55
+ if use_v_2_3:
56
+ traverse_state_dict_v_2_3(state_dict, flat_copy)
57
+ else:
58
+ traverse_state_dict(state_dict, flat_copy)
59
+ return flattened, mappings
60
+
61
+
62
+ def unflatten_state_dict(
63
+ state_dict: STATE_DICT_TYPE, mapping: FLATTEN_MAPPING
64
+ ) -> STATE_DICT_TYPE:
65
+ """Restore the original nested state_dict according to ``mapping`` and the flattened ``state_dict``."""
66
+ nested: STATE_DICT_TYPE = {}
67
+ for key, value in state_dict.items():
68
+ set_element(nested, mapping[key], value)
69
+ return nested
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_sharded_tensor_utils.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+
3
+ import copy
4
+ from typing import TYPE_CHECKING
5
+
6
+ import torch.distributed as dist
7
+ from torch.distributed._shard.sharded_tensor import Shard, ShardedTensor, ShardMetadata
8
+ from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE
9
+ from torch.distributed.remote_device import _remote_device
10
+
11
+ from ._traverse import OBJ_PATH, set_element, STATE_DICT_ITEM, traverse_state_dict
12
+ from .utils import _element_wise_add, _normalize_device_info
13
+
14
+
15
+ if TYPE_CHECKING:
16
+ from torch.distributed._shard.sharded_tensor.metadata import ShardedTensorMetadata
17
+
18
+
19
+ # TODO: We need to refactor this code.
20
+ def _flatten_sharded_tensors(state_dict: STATE_DICT_TYPE) -> STATE_DICT_TYPE:
21
+ r"""
22
+ Transform ``state_dict`` by flattening all nested ShardedTensor instances found.
23
+
24
+ The resulting ShardedTensor instances are only correct regarding the local shard and
25
+ MUST not be used for any other purpose but checkpointing, as no operator will work with them.
26
+
27
+ This function should be used in conjunction with a state_dict produced by FSDP's
28
+ StateDictType.SHARDED_STATE_DICT methods.
29
+ """
30
+ new_state_dict: STATE_DICT_TYPE = {}
31
+
32
+ def rewrite_dict(path: OBJ_PATH, value: STATE_DICT_ITEM) -> None:
33
+ if not isinstance(value, ShardedTensor):
34
+ set_element(new_state_dict, path, value)
35
+ return
36
+ shards = value.local_shards()
37
+
38
+ if len(shards) == 0:
39
+ return
40
+ if len(shards) != 1:
41
+ set_element(new_state_dict, path, value)
42
+ return
43
+
44
+ outer_shard = shards[0]
45
+
46
+ inner_st = outer_shard.tensor
47
+ if not isinstance(inner_st, ShardedTensor):
48
+ set_element(new_state_dict, path, value)
49
+ return
50
+
51
+ if len(inner_st.local_shards()) != 1:
52
+ raise ValueError("Cannot handle inner tensor with more than 1 shard")
53
+ inner_shard = inner_st.local_shards()[0]
54
+
55
+ local_shards = [
56
+ Shard(
57
+ tensor=inner_shard.tensor,
58
+ metadata=ShardMetadata(
59
+ shard_offsets=_element_wise_add(
60
+ outer_shard.metadata.shard_offsets,
61
+ inner_shard.metadata.shard_offsets,
62
+ ),
63
+ shard_sizes=inner_shard.metadata.shard_sizes,
64
+ placement=f"rank:{dist.get_rank()}/{inner_shard.tensor.device}",
65
+ ),
66
+ )
67
+ ]
68
+
69
+ st_meta: ShardedTensorMetadata = copy.deepcopy(value.metadata())
70
+ other_rank = 0 if dist.get_rank() > 0 else 1
71
+ device_info = _normalize_device_info(inner_shard.tensor.device.type, 0)
72
+
73
+ # Remove the outer ST shard the inner ST covers
74
+ for i, shard_md in enumerate(st_meta.shards_metadata):
75
+ if shard_md.shard_offsets == outer_shard.metadata.shard_offsets:
76
+ st_meta.shards_metadata.pop(i)
77
+ break
78
+
79
+ # Attribute other rank for the other shards
80
+ for shard_md in st_meta.shards_metadata:
81
+ shard_md.placement = _remote_device(f"rank:{other_rank}/{device_info}")
82
+
83
+ # Add other inner shards from the inner tensor
84
+ for inner_md in inner_st.metadata().shards_metadata:
85
+ if inner_md.shard_offsets != inner_shard.metadata.shard_offsets:
86
+ st_meta.shards_metadata.append(
87
+ ShardMetadata(
88
+ shard_offsets=_element_wise_add(
89
+ outer_shard.metadata.shard_offsets,
90
+ inner_md.shard_offsets,
91
+ ),
92
+ shard_sizes=inner_md.shard_sizes,
93
+ placement=f"rank:{other_rank}/{device_info}",
94
+ )
95
+ )
96
+
97
+ # Finally add this shard
98
+ st_meta.shards_metadata.append(local_shards[0].metadata)
99
+
100
+ st = ShardedTensor._init_from_local_shards_and_global_metadata(
101
+ local_shards=local_shards,
102
+ sharded_tensor_metadata=st_meta,
103
+ )
104
+ set_element(new_state_dict, path, st)
105
+
106
+ traverse_state_dict(state_dict, rewrite_dict)
107
+ return new_state_dict
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_state_dict_stager.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+ import types
4
+ import weakref
5
+ from copyreg import dispatch_table
6
+ from logging import getLogger
7
+ from typing import Any
8
+
9
+ import torch
10
+ import torch.cuda._pin_memory_utils as pin_memory_utils
11
+ from torch.storage import UntypedStorage
12
+ from torch.utils.weak import WeakIdKeyDictionary
13
+
14
+
15
+ logger = getLogger()
16
+ logger.setLevel(logging.INFO)
17
+
18
+
19
+ class StateDictStager:
20
+ """
21
+ A class for optimizing storage objects during staging for async checkpointing.
22
+
23
+ StateDictStager stages the state_dict to CPU DRAM while applying optimizations
24
+ like memory sharing and pinning to improve performance. It caches storage objects
25
+ to avoid redundant copies and can be configured to automatically share memory
26
+ (for multi-process usage) and pin memory (for faster CPU-GPU transfers).
27
+
28
+ Attributes:
29
+ pin_memory (bool): Whether to pin CPU memory for faster CPU-GPU transfers
30
+ share_memory (bool): Whether to share memory across processes
31
+ _cached_storage_mapping (WeakIdKeyDictionary): Maps storage objects to optimized CPU storages using weak references
32
+ """
33
+
34
+ def __init__(self, pin_memory: bool = False, share_memory: bool = False):
35
+ if pin_memory and not torch.cuda.is_available():
36
+ logger.warning(
37
+ "Ignoring pin_memory flag for checkpoint staging as pinning memory"
38
+ "requires CUDA, but CUDA is not available. "
39
+ )
40
+ self.pin_memory = False
41
+ else:
42
+ self.pin_memory = pin_memory
43
+ self.share_memory = share_memory
44
+ # Mapping from original storage objects to CPU storages using weak references
45
+ self._cached_storage_mapping = WeakIdKeyDictionary()
46
+
47
+ def _deepcopy_atomic(x, _):
48
+ return x
49
+
50
+ def _deepcopy_list(x, memo):
51
+ y: list = []
52
+ memo[id(x)] = y
53
+ append = y.append
54
+ for a in x:
55
+ append(self.deepcopy_with_tensor_offload(a, memo))
56
+ return y
57
+
58
+ def _deepcopy_tuple(x, memo):
59
+ y = [self.deepcopy_with_tensor_offload(a, memo) for a in x]
60
+ # We're not going to put the tuple in the memo, but it's still important we
61
+ # check for it, in case the tuple contains recursive mutable structures.
62
+ try:
63
+ return memo[id(x)]
64
+ except KeyError:
65
+ pass
66
+
67
+ # Check if any elements changed during deepcopy
68
+ for k, j in zip(x, y):
69
+ if k is not j:
70
+ # At least one element changed, create new tuple
71
+ return tuple(y)
72
+
73
+ # No elements changed, return original tuple
74
+ return x
75
+
76
+ def _deepcopy_dict(x, memo):
77
+ y: dict = {}
78
+ memo[id(x)] = y
79
+ for key, value in x.items():
80
+ y[self.deepcopy_with_tensor_offload(key, memo)] = (
81
+ self.deepcopy_with_tensor_offload(value, memo)
82
+ )
83
+ return y
84
+
85
+ def _deepcopy_method(x, memo): # Copy instance methods
86
+ return type(x)(
87
+ x.__func__, self.deepcopy_with_tensor_offload(x.__self__, memo)
88
+ )
89
+
90
+ d: dict[Any, Any] = {}
91
+ self._deepcopy_dispatch = d
92
+ d[type(None)] = _deepcopy_atomic
93
+ d[int] = _deepcopy_atomic
94
+ d[float] = _deepcopy_atomic
95
+ d[bool] = _deepcopy_atomic
96
+ d[complex] = _deepcopy_atomic
97
+ d[bytes] = _deepcopy_atomic
98
+ d[str] = _deepcopy_atomic
99
+ d[types.CodeType] = _deepcopy_atomic
100
+ d[type] = _deepcopy_atomic
101
+ d[range] = _deepcopy_atomic
102
+ d[types.BuiltinFunctionType] = _deepcopy_atomic
103
+ d[types.FunctionType] = _deepcopy_atomic
104
+ d[weakref.ref] = _deepcopy_atomic
105
+ d[property] = _deepcopy_atomic
106
+ d[types.MethodType] = _deepcopy_method
107
+ d[dict] = _deepcopy_dict
108
+ d[tuple] = _deepcopy_tuple
109
+ d[list] = _deepcopy_list
110
+
111
+ def _stage_untyped_storage(
112
+ self, storage: UntypedStorage, non_blocking: bool = False
113
+ ):
114
+ """
115
+ Called from the hooked storage_deepcopy function in torch.Tensor.__deepcopy__.
116
+
117
+ This method handles the storage optimization logic for the StagingStateDict class.
118
+ It checks if the storage has already been cached, and if so, reuses it.
119
+ Otherwise, it creates a new CPU storage and applies memory optimizations.
120
+
121
+ Args:
122
+ storage: The storage to optimize
123
+
124
+ Returns:
125
+ The optimized storage
126
+ """
127
+ # Check if we've already cached this storage
128
+ if storage in self._cached_storage_mapping:
129
+ cached_storage = self._cached_storage_mapping[storage]
130
+ assert cached_storage.size() == storage.size(), (
131
+ "For async checkpointing, We cache storages in DRAM and reuse them."
132
+ "Cached storage size does not match original storage size."
133
+ "This should never happen as we track the original storage weakref "
134
+ "and clean up the cache storage. Please report this to PyTorch Distributed Checkpointing."
135
+ )
136
+ # Reuse cached storage but update with new data
137
+ cached_storage.copy_(storage, non_blocking=non_blocking)
138
+ return cached_storage
139
+
140
+ # Create new CPU storage
141
+ if self.share_memory:
142
+ new_storage = type(storage)._new_shared(storage.size(), device="cpu")
143
+ else:
144
+ new_storage = type(storage)(storage.size(), device="cpu")
145
+
146
+ if self.pin_memory and new_storage.nbytes() > 0:
147
+ pin_memory_utils.pin_memory(new_storage.data_ptr(), new_storage.nbytes())
148
+ # Set up a weak reference to unpin when cpu storage is garbage collected
149
+ f = weakref.finalize(
150
+ new_storage, pin_memory_utils.unpin_memory, new_storage.data_ptr()
151
+ )
152
+ # This makes sure that the finalizer is not called after
153
+ # cuda context is destroyed.
154
+ f.atexit = False
155
+
156
+ new_storage.copy_(storage, non_blocking=non_blocking)
157
+
158
+ # Cache the storage - WeakIdKeyDictionary will automatically clean up when storage is garbage collected
159
+ self._cached_storage_mapping[storage] = new_storage
160
+ return new_storage
161
+
162
+ @torch.no_grad()
163
+ def stage(
164
+ self,
165
+ state_dict: dict[str, Any],
166
+ non_blocking: bool = False,
167
+ ) -> dict[str, Any]:
168
+ return self.deepcopy_with_tensor_offload(state_dict, non_blocking=non_blocking)
169
+
170
+ def _offload_tensor(self, x, memo, non_blocking=False):
171
+ """
172
+ Deep copy a PyTorch tensor with optimized storage handling.
173
+
174
+ This method creates a CPU copy of a tensor while applying memory optimizations
175
+ like sharing and pinning based on the StateDictStager configuration.
176
+
177
+ Args:
178
+ x: The tensor to copy
179
+ memo: Memo dictionary for tracking already copied objects
180
+ non_blocking: Whether to perform non-blocking copies where possible
181
+
182
+ Returns:
183
+ A CPU copy of the tensor with optimized storage
184
+ """
185
+ # Create a new empty tensor on CPU
186
+ y = x.new_empty([], device="cpu")
187
+
188
+ # Store in memo dict early to handle recursive references
189
+ d = id(x)
190
+ memo[d] = y
191
+
192
+ if type(x) is torch.Tensor or x.data_ptr() != 0:
193
+ # Try to get the untyped storage and optimize it
194
+ untyped_storage = x.untyped_storage()
195
+ copied_storage = self._stage_untyped_storage(
196
+ untyped_storage, non_blocking=non_blocking
197
+ )
198
+ # Set the tensor data using the optimized storage
199
+ y.set_(copied_storage, x.storage_offset(), x.size(), x.stride())
200
+
201
+ # Copy any attributes the tensor might have
202
+ if hasattr(x, "__dict__"):
203
+ for attr_name, attr_value in x.__dict__.items():
204
+ setattr(
205
+ y,
206
+ attr_name,
207
+ self.deepcopy_with_tensor_offload(
208
+ attr_value, memo, non_blocking=non_blocking
209
+ ),
210
+ )
211
+
212
+ if hasattr(x, "__slots__"):
213
+ for slot in x.__slots__:
214
+ if hasattr(x, slot):
215
+ setattr(
216
+ y,
217
+ slot,
218
+ self.deepcopy_with_tensor_offload(
219
+ getattr(x, slot), memo, non_blocking=non_blocking
220
+ ),
221
+ )
222
+
223
+ return y
224
+
225
+ @torch.no_grad()
226
+ def deepcopy_with_tensor_offload(self, x, memo=None, _nil=[], non_blocking=False): # noqa: B006
227
+ """Deep copy operation on arbitrary Python objects with special handling for PyTorch tensors.
228
+
229
+ This implementation extends the standard deepcopy functionality to handle PyTorch tensors
230
+ and their storages in a way that optimizes memory usage and performance, similar to the
231
+ stage method. It applies memory sharing and pinning optimizations based on the StateDictStager
232
+ configuration.
233
+
234
+ Args:
235
+ x: The object to deep copy
236
+ memo: Memo dictionary for tracking already copied objects
237
+ _nil: Sentinel value for memo dictionary
238
+ non_blocking: Whether to perform non-blocking copies where possible
239
+
240
+ Returns:
241
+ A deep copy of the input object with optimized tensor storage handling
242
+ """
243
+ if memo is None:
244
+ memo = {}
245
+
246
+ d = id(x)
247
+ y = memo.get(d, _nil)
248
+ if y is not _nil:
249
+ return y
250
+
251
+ cls = type(x)
252
+
253
+ # tensors and subclasses of tensors are handled separately
254
+ if isinstance(x, torch.Tensor):
255
+ y = self._offload_tensor(x, memo, non_blocking=non_blocking)
256
+
257
+ # Use the dispatch table for standard types
258
+ copier = self._deepcopy_dispatch.get(cls)
259
+ if copier is not None:
260
+ y = copier(x, memo)
261
+ else:
262
+ if issubclass(cls, type):
263
+ y = self._deepcopy_dispatch[type](x, memo)
264
+ else:
265
+ copier = getattr(x, "__deepcopy__", None)
266
+ if copier is not None:
267
+ y = copier(memo)
268
+ else:
269
+ reductor = dispatch_table.get(cls)
270
+ if reductor:
271
+ rv = reductor(x)
272
+ else:
273
+ reductor = getattr(x, "__reduce_ex__", None)
274
+ if reductor is not None:
275
+ rv = reductor(4)
276
+ else:
277
+ reductor = getattr(x, "__reduce__", None)
278
+ if reductor:
279
+ rv = reductor()
280
+ else:
281
+ raise RuntimeError(
282
+ f"un(deep)copyable object of type {cls}"
283
+ )
284
+ if isinstance(rv, str):
285
+ y = x
286
+ else:
287
+ y = self._reconstruct(x, memo, *rv)
288
+
289
+ # If is its own copy, don't memoize.
290
+ if y is not x:
291
+ memo[d] = y
292
+ self._keep_alive(x, memo) # Make sure x lives at least as long as d
293
+ return y
294
+
295
+ def _keep_alive(self, x, memo):
296
+ """Keeps a reference to the object x in the memo.
297
+
298
+ Because we remember objects by their id, we have
299
+ to assure that possibly temporary objects are kept
300
+ alive by referencing them.
301
+ We store a reference at the id of the memo, which should
302
+ normally not be used unless someone tries to deepcopy
303
+ the memo itself...
304
+ """
305
+ try:
306
+ memo[id(memo)].append(x)
307
+ except KeyError:
308
+ # aha, this is the first one :-)
309
+ memo[id(memo)] = [x]
310
+
311
+ def _reconstruct(
312
+ self, x, memo, func, args, state=None, listiter=None, dictiter=None
313
+ ):
314
+ deep = memo is not None
315
+ if deep and args:
316
+ args = (self.deepcopy_with_tensor_offload(arg, memo) for arg in args)
317
+ y = func(*args)
318
+ if deep:
319
+ memo[id(x)] = y
320
+
321
+ if state is not None:
322
+ if deep:
323
+ state = self.deepcopy_with_tensor_offload(state, memo)
324
+ if hasattr(y, "__setstate__"):
325
+ y.__setstate__(state)
326
+ else:
327
+ if isinstance(state, tuple) and len(state) == 2:
328
+ state, slotstate = state
329
+ else:
330
+ slotstate = None
331
+ if state is not None:
332
+ y.__dict__.update(state)
333
+ if slotstate is not None:
334
+ for key, value in slotstate.items():
335
+ setattr(y, key, value)
336
+
337
+ if listiter is not None:
338
+ if deep:
339
+ for item in listiter:
340
+ item = self.deepcopy_with_tensor_offload(item, memo)
341
+ y.append(item)
342
+ else:
343
+ for item in listiter:
344
+ y.append(item)
345
+ if dictiter is not None:
346
+ if deep:
347
+ for key, value in dictiter:
348
+ key = self.deepcopy_with_tensor_offload(key, memo)
349
+ value = self.deepcopy_with_tensor_offload(value, memo)
350
+ y[key] = value
351
+ else:
352
+ for key, value in dictiter:
353
+ y[key] = value
354
+ return y
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_storage_utils.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Union
3
+
4
+ from .filesystem import FileSystemReader, FileSystemWriter
5
+ from .storage import StorageReader, StorageWriter
6
+
7
+
8
+ def _storage_setup(
9
+ storage: Union[StorageReader, StorageWriter, None],
10
+ checkpoint_id: Union[str, os.PathLike, None],
11
+ reader: bool = False,
12
+ ) -> Union[None, StorageReader, StorageWriter]:
13
+ if storage:
14
+ if checkpoint_id is not None:
15
+ storage.reset(checkpoint_id)
16
+ return storage
17
+
18
+ if not checkpoint_id:
19
+ raise RuntimeError(
20
+ "`checkpoint_id` must be specified if "
21
+ "storage_reader/storage_writer is None."
22
+ )
23
+
24
+ targets: list[type[Union[StorageReader, StorageWriter]]] = []
25
+ if reader:
26
+ targets = [
27
+ FileSystemReader,
28
+ ]
29
+ else:
30
+ targets = [
31
+ FileSystemWriter,
32
+ ]
33
+ try:
34
+ from ._fsspec_filesystem import FsspecReader, FsspecWriter
35
+
36
+ targets.append(FsspecReader if reader else FsspecWriter)
37
+ except Exception:
38
+ pass
39
+
40
+ for target in targets:
41
+ if target.validate_checkpoint_id(checkpoint_id):
42
+ storage = target(checkpoint_id) # type: ignore[call-arg]
43
+ storage.reset(checkpoint_id)
44
+ return storage
45
+
46
+ raise RuntimeError(
47
+ "Cannot detect which StorageReader or StorageWriter to use. "
48
+ "Please specify the storage_reader/storage_writer."
49
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_traverse.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ from collections.abc import Collection, Mapping, MutableMapping
3
+ from typing import Callable, cast, Optional, TypeVar, Union
4
+
5
+ import torch
6
+ from torch.distributed._shard.sharded_tensor.api import ShardedTensor
7
+ from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE
8
+ from torch.distributed.tensor import DTensor
9
+
10
+
11
+ PATH_ITEM = Union[str, int]
12
+ OBJ_PATH = tuple[PATH_ITEM, ...]
13
+ T = TypeVar("T")
14
+
15
+ STATE_DICT_ITEM = object
16
+ CONTAINER_TYPE = MutableMapping[PATH_ITEM, STATE_DICT_ITEM]
17
+
18
+ __all__ = ["traverse_state_dict", "set_element", "get_element", "print_tensor"]
19
+
20
+
21
+ def _keep_visiting_tensors(value: STATE_DICT_ITEM) -> bool:
22
+ return isinstance(value, torch.Tensor)
23
+
24
+
25
+ # TODO: update docstring for traverse.py
26
+ def traverse_state_dict(
27
+ state_dict: STATE_DICT_TYPE,
28
+ visitor: Callable[[OBJ_PATH, STATE_DICT_ITEM], None],
29
+ keep_traversing: Callable[[STATE_DICT_ITEM], bool] = _keep_visiting_tensors,
30
+ ) -> None:
31
+ """
32
+ Invoke ``visitor`` for each value recursively in ``state_dict``.
33
+ Mapping will be traversed and ``visitor`` will be applied to the leaf elements.
34
+ ``visitor`` will only be applied to elements in a list or a tuple, if the
35
+ container contains tensors or mappings.
36
+ """
37
+
38
+ def _is_terminal(value: STATE_DICT_ITEM) -> bool:
39
+ values: Collection[STATE_DICT_ITEM]
40
+ if isinstance(value, Mapping):
41
+ return False
42
+ elif isinstance(value, list):
43
+ values = value
44
+ else:
45
+ return True
46
+
47
+ for entry in values:
48
+ if isinstance(entry, (Mapping, list)) and not _is_terminal(entry):
49
+ return False
50
+ if keep_traversing is not None and keep_traversing(entry):
51
+ return False
52
+ return True
53
+
54
+ def _traverse_obj(path: OBJ_PATH, value: STATE_DICT_ITEM) -> None:
55
+ if isinstance(value, Mapping):
56
+ for k, v in value.items():
57
+ _traverse_obj(path + (str(k),), v)
58
+ elif _is_terminal(value):
59
+ visitor(path, value)
60
+ elif isinstance(value, (list, tuple)):
61
+ for i, v in enumerate(value):
62
+ _traverse_obj(path + (i,), v)
63
+
64
+ for key, value in state_dict.items():
65
+ _traverse_obj((str(key),), value)
66
+
67
+
68
+ def traverse_state_dict_v_2_3(
69
+ state_dict: STATE_DICT_TYPE,
70
+ visitor: Callable[[OBJ_PATH, STATE_DICT_ITEM], None],
71
+ keep_traversing: Callable[[STATE_DICT_ITEM], bool] = _keep_visiting_tensors,
72
+ ) -> None:
73
+ """
74
+ Traversal is short-circuited when if finds a collection for which ``keep_visiting_tensors`` evaluates
75
+ to false for all elements.
76
+ By default, all collections with at least one ``torch.Tensor`` element are traversed.
77
+ Visitor takes a path argument that is a tuple of the keys used to reach it.
78
+ """
79
+
80
+ # a value is terminal if it has no other containers values inside it
81
+ def _is_terminal(value: STATE_DICT_ITEM) -> bool:
82
+ values: Collection[STATE_DICT_ITEM]
83
+ if isinstance(value, Mapping):
84
+ values = value.values()
85
+ elif isinstance(value, list):
86
+ values = value
87
+ else:
88
+ return True
89
+
90
+ for entry in values:
91
+ if isinstance(entry, (Mapping, list)) and not _is_terminal(entry):
92
+ return False
93
+ if keep_traversing is not None and keep_traversing(entry):
94
+ return False
95
+ return True
96
+
97
+ def _traverse_obj(path: OBJ_PATH, value: STATE_DICT_ITEM) -> None:
98
+ if _is_terminal(value):
99
+ visitor(path, value)
100
+ elif isinstance(value, Mapping):
101
+ for k, v in value.items():
102
+ _traverse_obj(path + (str(k),), v)
103
+ elif isinstance(value, list):
104
+ for i, v in enumerate(value):
105
+ _traverse_obj(path + (i,), v)
106
+
107
+ for key, value in state_dict.items():
108
+ _traverse_obj((str(key),), value)
109
+
110
+
111
+ def set_element(
112
+ root_dict: STATE_DICT_TYPE, path: OBJ_PATH, value: STATE_DICT_ITEM
113
+ ) -> None:
114
+ """Set ``value`` in ``root_dict`` along the ``path`` object path."""
115
+ cur_container = cast(CONTAINER_TYPE, root_dict)
116
+
117
+ def extend_list(lst: list[STATE_DICT_ITEM], idx: int) -> None:
118
+ while len(lst) <= idx:
119
+ lst.append(None)
120
+
121
+ for i in range(1, len(path)):
122
+ prev_key = path[i - 1]
123
+ key = path[i]
124
+ def_val = cast(STATE_DICT_ITEM, {} if type(key) == str else [])
125
+
126
+ if isinstance(cur_container, Mapping):
127
+ cur_container = cast(
128
+ CONTAINER_TYPE, cur_container.setdefault(prev_key, def_val)
129
+ )
130
+ else:
131
+ extend_list(cur_container, prev_key)
132
+ if cur_container[prev_key] is None:
133
+ cur_container[prev_key] = def_val
134
+ cur_container = cur_container[prev_key]
135
+
136
+ key = path[-1]
137
+ if type(key) == int:
138
+ extend_list(cast(list[STATE_DICT_ITEM], cur_container), key)
139
+
140
+ cur_container[key] = value
141
+
142
+
143
+ def get_element(
144
+ root_dict: STATE_DICT_TYPE,
145
+ path: OBJ_PATH,
146
+ default_value: Optional[T] = None,
147
+ ) -> Optional[T]:
148
+ """Retrieve the value at ``path``from ``root_dict``, returning ``default_value`` if not found."""
149
+ cur_value = cast(CONTAINER_TYPE, root_dict)
150
+ for part in path:
151
+ if type(part) is int:
152
+ if not isinstance(cur_value, list) or len(cur_value) < part:
153
+ return default_value
154
+ elif not isinstance(cur_value, Mapping) or part not in cur_value:
155
+ return default_value
156
+
157
+ cur_value = cast(CONTAINER_TYPE, cur_value[part])
158
+ return cast(Optional[T], cur_value)
159
+
160
+
161
+ def _print_nested(
162
+ value: STATE_DICT_ITEM,
163
+ prefix: str = "",
164
+ print_fun: Callable[[str], None] = print,
165
+ ) -> None:
166
+ if type(value) is ShardedTensor:
167
+ print_fun(f"{prefix} ShardedTensor size: {value.size()}")
168
+ for shard in value.local_shards():
169
+ _print_nested(
170
+ shard.tensor,
171
+ f"{shard.metadata.shard_offsets} ",
172
+ print_fun=print_fun,
173
+ )
174
+ elif type(value) is (DTensor):
175
+ print_fun(f"{prefix} DistributedTensor size: {value.size()}")
176
+ # TODO: add local offset for _local_tensor in print_nested.
177
+ _print_nested(
178
+ value._local_tensor,
179
+ print_fun=print_fun,
180
+ )
181
+ elif isinstance(value, torch.Tensor):
182
+ print_fun(f"{prefix} Tensor size: {value.size()}")
183
+ else:
184
+ print_fun(f"{prefix} Type: {type(value)}")
185
+
186
+
187
+ def print_tensor(
188
+ path: OBJ_PATH,
189
+ value: STATE_DICT_ITEM,
190
+ print_fun: Callable[[str], None] = print,
191
+ ) -> None:
192
+ """
193
+ Use this callback with traverse_state_dict to print its content.
194
+
195
+ By default the content is printed using the builtin ``print`` but this can
196
+ be change by passing a different ``print_fun` callable.
197
+ """
198
+ _print_nested(value, prefix=str(path), print_fun=print_fun)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/_version.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+
3
+ from typing import Optional
4
+
5
+
6
+ _derived_version: Optional[str] = None
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/api.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import traceback as tb
2
+ from typing import Any
3
+
4
+
5
+ WRAPPED_EXCEPTION = tuple[BaseException, tb.StackSummary]
6
+
7
+ __all__ = ["CheckpointException"]
8
+
9
+
10
+ def _wrap_exception(exc: BaseException) -> WRAPPED_EXCEPTION:
11
+ return (exc, tb.extract_tb(exc.__traceback__))
12
+
13
+
14
+ def _is_wrapped_exception(obj: Any) -> bool:
15
+ if not isinstance(obj, tuple):
16
+ return False
17
+ if len(obj) != 2:
18
+ return False
19
+ return isinstance(obj[0], BaseException) and isinstance(obj[1], tb.StackSummary)
20
+
21
+
22
+ class CheckpointException(BaseException):
23
+ """Exception raised if failure was detected as part of a checkpoint load or save."""
24
+
25
+ def __init__(self, msg: str, failures: dict[int, WRAPPED_EXCEPTION]):
26
+ super().__init__(msg, failures)
27
+ self._failures = failures
28
+
29
+ @property
30
+ def failures(self) -> dict[int, WRAPPED_EXCEPTION]:
31
+ """Return a dictionary mapping node ranks to their associated exceptions in case of failure."""
32
+ return self._failures
33
+
34
+ def __str__(self) -> str:
35
+ str = f"CheckpointException ranks:{self._failures.keys()}\n"
36
+ for rank, exc_pair in self._failures.items():
37
+ exc, trace = exc_pair
38
+ str += f"Traceback (most recent call last): (RANK {rank})\n"
39
+ if trace is not None:
40
+ str += "".join(tb.format_list(trace))
41
+ str += "".join(tb.format_exception_only(type(exc), value=exc))
42
+ return str
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/default_planner.py ADDED
@@ -0,0 +1,669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+
4
+ import dataclasses
5
+ import io
6
+ import logging
7
+ import operator
8
+ from collections import ChainMap
9
+ from functools import reduce
10
+ from typing import Any, cast, Optional, Union
11
+
12
+ import torch
13
+ from torch.distributed._shard._utils import narrow_tensor_by_index
14
+ from torch.distributed.checkpoint._dedup_save_plans import dedup_save_plans
15
+ from torch.distributed.checkpoint._nested_dict import (
16
+ FLATTEN_MAPPING,
17
+ flatten_state_dict,
18
+ )
19
+ from torch.distributed.checkpoint._sharded_tensor_utils import _flatten_sharded_tensors
20
+ from torch.distributed.checkpoint._traverse import set_element
21
+ from torch.distributed.checkpoint.metadata import (
22
+ BytesStorageMetadata,
23
+ ChunkStorageMetadata,
24
+ Metadata,
25
+ MetadataIndex,
26
+ STATE_DICT_TYPE,
27
+ STORAGE_TYPES,
28
+ StorageMeta,
29
+ TensorStorageMetadata,
30
+ )
31
+ from torch.distributed.checkpoint.planner import (
32
+ LoadPlan,
33
+ LoadPlanner,
34
+ ReadItem,
35
+ SavePlan,
36
+ SavePlanner,
37
+ WriteItem,
38
+ WriteItemType,
39
+ )
40
+ from torch.distributed.checkpoint.planner_helpers import (
41
+ _compare_save_plans,
42
+ _contains_usable_plan,
43
+ _create_default_metadata_only_plan,
44
+ _create_read_items,
45
+ _create_write_items,
46
+ _init_state_dict,
47
+ _merge_delta_local_plans,
48
+ )
49
+ from torch.distributed.checkpoint.utils import find_state_dict_object
50
+ from torch.distributed.tensor import DTensor
51
+
52
+ from . import _version
53
+
54
+
55
+ logger: logging.Logger = logging.getLogger(__name__)
56
+
57
+
58
+ __all__ = [
59
+ "DefaultSavePlanner",
60
+ "DefaultLoadPlanner",
61
+ "create_default_local_load_plan",
62
+ "create_default_global_load_plan",
63
+ "create_default_local_save_plan",
64
+ "create_default_global_save_plan",
65
+ ]
66
+
67
+
68
+ # TODO: Update docstrings for default_planner.py
69
+ class DefaultSavePlanner(SavePlanner):
70
+ mappings: FLATTEN_MAPPING
71
+
72
+ def __init__(
73
+ self,
74
+ flatten_state_dict: bool = True,
75
+ flatten_sharded_tensors: bool = True,
76
+ dedup_replicated_tensors: Optional[bool] = None,
77
+ dedup_save_to_lowest_rank: bool = False,
78
+ enable_plan_caching: bool = False,
79
+ ) -> None:
80
+ self.flatten_state_dict = flatten_state_dict
81
+ self.flatten_sharded_tensors = flatten_sharded_tensors
82
+ self.mappings = {}
83
+ self.dedup_save_to_lowest_rank = dedup_save_to_lowest_rank
84
+ if dedup_replicated_tensors is not None:
85
+ logger.warning(
86
+ "DefaultSavePlanner's `dedup_replicated_tensors` argument is being "
87
+ "deprecated, and no longer has any effect. Please remove this argument "
88
+ "from your call."
89
+ )
90
+ self._cached_plans_key: str = self.__class__.__name__
91
+ self._enable_plan_caching = enable_plan_caching
92
+
93
+ def set_up_planner(
94
+ self,
95
+ state_dict: STATE_DICT_TYPE,
96
+ storage_meta: Optional[StorageMeta] = None,
97
+ is_coordinator: bool = False,
98
+ ) -> None:
99
+ if self.flatten_state_dict:
100
+ state_dict, self.mappings = flatten_state_dict(state_dict)
101
+ if self.flatten_sharded_tensors:
102
+ state_dict = _flatten_sharded_tensors(state_dict)
103
+ self.state_dict = state_dict
104
+ self.is_coordinator = is_coordinator
105
+
106
+ def create_local_plan(self) -> SavePlan:
107
+ plan = create_default_local_save_plan(self.state_dict, self.is_coordinator)
108
+ if self.flatten_state_dict:
109
+ plan = dataclasses.replace(plan, planner_data=self.mappings)
110
+ self.plan = plan
111
+
112
+ if self._enable_plan_caching:
113
+ # If plans are equal, we can skip sending the plan to the coordinator.
114
+ if (
115
+ self._cached_plans_key in SavePlanner._cached_save_plan
116
+ and _compare_save_plans(
117
+ plan, SavePlanner._cached_save_plan[self._cached_plans_key]
118
+ )
119
+ ):
120
+ logger.info(
121
+ "No change in the local plan. Skipping sending the plan to the coordinator"
122
+ )
123
+ return SavePlan([], usable=False)
124
+ else:
125
+ SavePlanner._cached_save_plan[self._cached_plans_key] = plan
126
+
127
+ return self.plan
128
+
129
+ def _dedup_save_plans(self, all_plans: list[SavePlan]) -> list[SavePlan]:
130
+ return dedup_save_plans(all_plans, self.dedup_save_to_lowest_rank)
131
+
132
+ def _create_global_plan(
133
+ self, all_plans: list[SavePlan]
134
+ ) -> tuple[list[SavePlan], Metadata]:
135
+ deduped_plans = self._dedup_save_plans(all_plans)
136
+
137
+ global_plan, metadata = create_default_global_save_plan(deduped_plans)
138
+
139
+ if self.flatten_state_dict:
140
+ # | does not work for Python 3.8 or older version.
141
+ # merged_mappings = reduce(
142
+ # lambda x, y: x | y, (p.planner_data for p in global_plan)
143
+ # )
144
+ planner_data_dict = [p.planner_data for p in global_plan]
145
+ merged_mappings = dict(ChainMap(*planner_data_dict))
146
+ metadata = dataclasses.replace(metadata, planner_data=merged_mappings)
147
+
148
+ if not _validate_global_plan(global_plan, metadata):
149
+ raise ValueError("Failed to validate global plan")
150
+
151
+ return global_plan, metadata
152
+
153
+ def _create_global_plan_with_caching(
154
+ self, all_plans: list[SavePlan]
155
+ ) -> tuple[list[SavePlan], list[SavePlan], Metadata]:
156
+ """
157
+ Create global plan with caching.
158
+ Returns a tuple of global_plan_delta, global_plan, metadata.
159
+ """
160
+ global_plan_delta: list[SavePlan] = []
161
+
162
+ if self._cached_plans_key not in SavePlanner._cached_all_plans:
163
+ # Case 1: If the plans are not cached, the cache will be hydrated with the
164
+ # all_plans, global_plans (Deduped), and metadata.
165
+
166
+ # Cache the original all_plans
167
+ SavePlanner._cached_all_plans[self._cached_plans_key] = all_plans
168
+ global_plan, metadata = self._create_global_plan(all_plans)
169
+ # Cache the deduped and validated global_plan
170
+ SavePlanner._cached_global_plan[self._cached_plans_key] = global_plan
171
+ # Cache the metadata
172
+ SavePlanner._cached_metadata[self._cached_plans_key] = metadata
173
+ # If plans are not cached, global_plan delta will be the same as global plan.
174
+ return global_plan, global_plan, metadata
175
+
176
+ # Case 2: Plans are cached
177
+ if not _contains_usable_plan(all_plans):
178
+ # Case 2.1: Plans are cached and the local plans have NOT changed (No usable plans).
179
+ # Global plan delta will be empty plans to avoid the collective overhead.
180
+ # We can reuse the deduped global plan and metadata from the cache directly.
181
+ global_plan_delta = [SavePlan([], usable=False)] * len(all_plans)
182
+ global_plan = SavePlanner._cached_global_plan[self._cached_plans_key]
183
+ metadata = SavePlanner._cached_metadata[self._cached_plans_key]
184
+ else:
185
+ # Case 2.2: Plans are cached but the local plans have changed.
186
+ # We will merge the changed local plans with the cached local plans.
187
+ # Updated plans will overwrite the cached plans. New global plan and metadata will be created and cached.
188
+ # Global plan delta will be created by comparing the new global plan with the cached global plan.
189
+ # Only the global plan delta (updated ones) will be sent to the coordinator to avoid the collective overhead.
190
+ merged_plans = _merge_delta_local_plans(
191
+ SavePlanner._cached_all_plans[self._cached_plans_key], all_plans
192
+ )
193
+ # Cache the updated local plans
194
+ SavePlanner._cached_all_plans[self._cached_plans_key] = merged_plans
195
+ global_plan, metadata = self._create_global_plan(merged_plans)
196
+
197
+ if self._cached_plans_key in self._cached_global_plan:
198
+ for cached_plan, new_plan in zip(
199
+ SavePlanner._cached_global_plan[self._cached_plans_key], global_plan
200
+ ):
201
+ if _compare_save_plans(cached_plan, new_plan):
202
+ global_plan_delta.append(SavePlan([], usable=False))
203
+ else:
204
+ global_plan_delta.append(new_plan)
205
+
206
+ # Cache the new global plan and the metadata
207
+ SavePlanner._cached_global_plan[self._cached_plans_key] = global_plan
208
+ SavePlanner._cached_metadata[self._cached_plans_key] = metadata
209
+
210
+ return global_plan_delta, global_plan, metadata
211
+
212
+ def create_global_plan(
213
+ self, all_plans: list[SavePlan]
214
+ ) -> tuple[list[SavePlan], Metadata]:
215
+ global_plan_delta: list[SavePlan] = []
216
+ if self._enable_plan_caching:
217
+ # If the plans are cached, we only need to send the global plan delta to be scattered
218
+ # across ranks. Ranks will use the cached final plans instead.
219
+ (
220
+ global_plan_delta,
221
+ global_plan,
222
+ metadata,
223
+ ) = self._create_global_plan_with_caching(all_plans)
224
+ else:
225
+ global_plan, metadata = self._create_global_plan(all_plans)
226
+ # If the caching is not enabled, global delta plan will always be same as the new global plan.
227
+ global_plan_delta = global_plan
228
+
229
+ self.global_plan = global_plan
230
+ self.metadata = metadata
231
+
232
+ return global_plan_delta, self.metadata
233
+
234
+ def _finish_plan_with_caching(self, new_plan: SavePlan) -> SavePlan:
235
+ finished_plan: SavePlan = new_plan
236
+
237
+ if not new_plan.usable:
238
+ finished_plan = SavePlanner._cached_final_save_plan[self._cached_plans_key]
239
+ else:
240
+ finished_plan = new_plan
241
+ SavePlanner._cached_final_save_plan[self._cached_plans_key] = new_plan
242
+ return finished_plan
243
+
244
+ def finish_plan(self, new_plan: SavePlan) -> SavePlan:
245
+ finished_plan: SavePlan = new_plan
246
+
247
+ if self._enable_plan_caching:
248
+ finished_plan = self._finish_plan_with_caching(new_plan)
249
+
250
+ self.plan = finished_plan
251
+ return self.plan
252
+
253
+ def resolve_data(self, write_item: WriteItem) -> Union[torch.Tensor, io.BytesIO]:
254
+ object = self.lookup_object(write_item.index)
255
+ return self.transform_object(write_item, object)
256
+
257
+ def lookup_object(self, index: MetadataIndex) -> Any:
258
+ """Extension from the planner interface to make it easy to extend the default planner."""
259
+ return find_state_dict_object(self.state_dict, index)
260
+
261
+ def transform_object(self, write_item: WriteItem, object: Any):
262
+ """Extension from the planner interface to make it easy to extend the default planner."""
263
+ if write_item.type == WriteItemType.BYTE_IO:
264
+ bytes = io.BytesIO()
265
+ torch.save(object, bytes)
266
+ object = bytes
267
+ return object
268
+
269
+
270
+ class DefaultLoadPlanner(LoadPlanner):
271
+ """
272
+ DefaultLoadPlanner that adds multiple features on top of LoadPlanner.
273
+
274
+ In particular it adds the following:
275
+
276
+ flatten_state_dict: Handle state_dict with nested dicts
277
+ flatten_sharded_tensors: For FSDP in 2D parallel mode
278
+ allow_partial_load: If False, will raise a runtime error if a key is present in state_dict, but not in the checkpoint.
279
+ """
280
+
281
+ original_state_dict: STATE_DICT_TYPE
282
+ mappings: FLATTEN_MAPPING
283
+
284
+ def __init__(
285
+ self,
286
+ flatten_state_dict: bool = True,
287
+ flatten_sharded_tensors: bool = True,
288
+ allow_partial_load: bool = False,
289
+ ) -> None:
290
+ self.flatten_state_dict = flatten_state_dict
291
+ self.flatten_sharded_tensors = flatten_sharded_tensors
292
+ self.original_state_dict = {}
293
+ self.mappings = {}
294
+ self.allow_partial_load = allow_partial_load
295
+
296
+ def set_up_planner(
297
+ self,
298
+ state_dict: STATE_DICT_TYPE,
299
+ metadata: Optional[Metadata] = None,
300
+ is_coordinator: bool = False,
301
+ ) -> None:
302
+ _init_state_dict(state_dict)
303
+ self.original_state_dict = state_dict
304
+
305
+ if self.flatten_sharded_tensors:
306
+ state_dict = _flatten_sharded_tensors(state_dict)
307
+
308
+ if self.flatten_state_dict:
309
+ state_dict, self.mappings = flatten_state_dict(state_dict)
310
+
311
+ self.state_dict = state_dict
312
+ self.metadata = metadata
313
+ self.is_coordinator = is_coordinator
314
+
315
+ def create_local_plan(self) -> LoadPlan:
316
+ assert self.metadata is not None
317
+ if self.flatten_state_dict:
318
+ # To support checkpoints that are saved before v2.4, we have to
319
+ # differentiate if the missing keys are due to old checkpoints.
320
+ # The contracts are:
321
+ # 1. There are 3 cases when we found a missing key.
322
+ # 1.1 Actual missing key, but allow_partial_load is False
323
+ # 1.2 Actual missing key, but allow_partial load is True
324
+ # 1.3 Old checkpoint, but allow_partial_load is False
325
+ # 1.4 Old checkpoint, but allow_partial_load is True
326
+ # 2. If we found a missing key, we first convert the keys back to
327
+ # the key format of v2.3
328
+ # 3. If the previous missing keys are in the v2.3 keys, we assume
329
+ # this is a old checkpoint.
330
+ # 4. Pass the state_dict to `create_default_local_load_plan()`,
331
+ # which has the logic to check missing for allow_partial_load.
332
+ # So for 1.2 and 1.4 cases, we delegate allow_partial_load check to
333
+ # `create_default_local_load_plan()`. The logic here is to determine
334
+ # whether the checkpoint belong to 2.3 (or before) or 2.4 (or after).
335
+ current_keys = set(self.state_dict.keys())
336
+ load_keys = set(self.metadata.state_dict_metadata.keys())
337
+ missing_keys = load_keys - current_keys
338
+ if missing_keys:
339
+ _version._derived_version = "2_3"
340
+ old_state_dict, old_mappings = flatten_state_dict(
341
+ self.original_state_dict
342
+ )
343
+ old_keys = set(old_state_dict.keys())
344
+ if old_keys & missing_keys:
345
+ self.state_dict, self.mappings = old_state_dict, old_mappings
346
+ # _derived_version is only used by flatten_state_dict now.
347
+ # Set it back to None so that later we can save to a new version.
348
+ _version._derived_version = None
349
+
350
+ return create_default_local_load_plan(
351
+ self.state_dict, self.metadata, not self.allow_partial_load
352
+ )
353
+
354
+ def create_global_plan(self, global_plan: list[LoadPlan]) -> list[LoadPlan]:
355
+ return create_default_global_load_plan(global_plan)
356
+
357
+ def finish_plan(self, new_plan: LoadPlan) -> LoadPlan:
358
+ return new_plan
359
+
360
+ def load_bytes(self, read_item: ReadItem, value: io.BytesIO) -> None:
361
+ if self.flatten_state_dict:
362
+ set_element(
363
+ self.original_state_dict,
364
+ self.mappings[read_item.dest_index.fqn],
365
+ torch.load(value, weights_only=False),
366
+ )
367
+ else:
368
+ self.state_dict[read_item.dest_index.fqn] = torch.load(
369
+ value, weights_only=False
370
+ )
371
+
372
+ def resolve_tensor(self, read_item: ReadItem):
373
+ tensor = self.lookup_tensor(read_item.dest_index)
374
+ return self.transform_tensor(read_item, tensor)
375
+
376
+ def commit_tensor(self, read_item: ReadItem, tensor: torch.Tensor) -> None:
377
+ pass
378
+
379
+ def lookup_tensor(self, index: MetadataIndex) -> torch.Tensor:
380
+ """Extension from the planner interface to make it easy to extend the default planner."""
381
+ return find_state_dict_object(self.state_dict, index)
382
+
383
+ def transform_tensor(self, read_item: ReadItem, tensor: torch.Tensor):
384
+ """Extension from the planner interface to make it easy to extend the default planner."""
385
+ return narrow_tensor_by_index(tensor, read_item.dest_offsets, read_item.lengths)
386
+
387
+
388
+ class _EmptyStateDictLoadPlanner(DefaultLoadPlanner):
389
+ """
390
+ Extension of DefaultLoadPlanner, which rebuilds state_dict from the saved metadata.
391
+ Useful for loading in state_dict without first initializing a model, such as
392
+ when converting a DCP checkpoint into a Torch save file.
393
+
394
+ . N.B. `state_dict` must be an empty dictionary when used with this LoadPlanner
395
+
396
+ .. warning::
397
+ Because the entire state dict is initialized, It's recommended to only utilize
398
+ this LoadPlanner on a single rank or process to avoid OOM.
399
+
400
+ """
401
+
402
+ def __init__(self, keys=None, *args, **kwargs):
403
+ self.keys = keys
404
+ super().__init__(*args, **kwargs)
405
+
406
+ def _should_include_key(self, key: str, metadata: Metadata) -> bool:
407
+ if self.keys is None:
408
+ return True
409
+
410
+ if key in self.keys:
411
+ True
412
+
413
+ unflattened_keys: list[str] = []
414
+ planner_data = metadata.planner_data.get(key)
415
+ for unflattened_key in planner_data:
416
+ if unflattened_keys:
417
+ unflattened_keys.append(
418
+ ".".join([unflattened_keys[-1], str(unflattened_key)])
419
+ )
420
+
421
+ else:
422
+ unflattened_keys.append(unflattened_key)
423
+
424
+ if any(unflattened_key in self.keys for unflattened_key in unflattened_keys):
425
+ return True
426
+
427
+ return False
428
+
429
+ def set_up_planner(
430
+ self,
431
+ state_dict: STATE_DICT_TYPE,
432
+ metadata: Optional[Metadata] = None,
433
+ is_coordinator: bool = False,
434
+ ) -> None:
435
+ assert not state_dict
436
+ assert metadata is not None
437
+
438
+ # rebuild the state dict from the metadata
439
+ for k, v in metadata.state_dict_metadata.items():
440
+ if not self._should_include_key(k, metadata):
441
+ continue
442
+
443
+ if isinstance(v, TensorStorageMetadata):
444
+ v = torch.empty(v.size, dtype=v.properties.dtype) # type: ignore[assignment]
445
+ if metadata.planner_data is not None and k in metadata.planner_data:
446
+ set_element(state_dict, metadata.planner_data[k], v)
447
+ else:
448
+ state_dict[k] = v
449
+
450
+ super().set_up_planner(state_dict, metadata, is_coordinator)
451
+
452
+
453
+ def create_default_local_load_plan(
454
+ state_dict: dict[str, Any], metadata: Metadata, strict: bool = True
455
+ ) -> LoadPlan:
456
+ requests = []
457
+ """
458
+ Create the ``LoadPlan`` used by DefaultLoadPlanner.
459
+
460
+ It produces one read item per value in ``state_dict`` using the metadata in ``metadata``.
461
+
462
+ The default behavior is to match key exactly between state_dict and metadata.
463
+ It handles resharding by issuing multiple read requests against storage in order to match
464
+ load requirements.
465
+ """
466
+
467
+ for fqn, obj in state_dict.items():
468
+ # ignore state_dict keys which do not exist in `state_dict` if strict=False
469
+ if fqn not in metadata.state_dict_metadata:
470
+ if strict:
471
+ raise RuntimeError(f"Missing key in checkpoint state_dict: {fqn}.")
472
+ else:
473
+ continue
474
+
475
+ md = metadata.state_dict_metadata[fqn]
476
+ if (
477
+ isinstance(md, TensorStorageMetadata)
478
+ and getattr(obj, "size", None) is not None
479
+ and md.size != obj.size()
480
+ ):
481
+ raise ValueError(
482
+ f"Size mismatch between saved {md.size} and current: {obj.size()} for {fqn}",
483
+ )
484
+ # Since DTensor supports submesh, adding extra check to ensure _create_read_items()
485
+ # gets called only when the current rank is part of the mesh for the corresponding DTensor.
486
+ if isinstance(obj, DTensor):
487
+ if obj.device_mesh.get_coordinate() is not None:
488
+ requests += _create_read_items(fqn, md, obj)
489
+ else:
490
+ requests += _create_read_items(fqn, md, obj)
491
+
492
+ return LoadPlan(requests)
493
+
494
+
495
+ def create_default_global_load_plan(
496
+ all_plans: list[LoadPlan],
497
+ ) -> list[LoadPlan]:
498
+ """
499
+ Create global load plan used by DefaultLoadPlanner.
500
+
501
+ The default load behavior involved no global coordination and this function
502
+ currently doesn't change the local plans.
503
+ """
504
+ return all_plans
505
+
506
+
507
+ def create_default_local_save_plan(
508
+ state_dict: dict[str, Any], is_coordinator: bool
509
+ ) -> SavePlan:
510
+ """
511
+ Create the ``SavePlan`` used by DefaultSavePlanner.
512
+
513
+ On non-coordinator ranks, this function ignores tensors and non-tensor objects,
514
+ only producing writes for ShardedTensor objects.
515
+
516
+ On the coordinator rank, produce writes for all values.
517
+ """
518
+ requests = []
519
+ for fqn, obj in state_dict.items():
520
+ # Since DTensor supports submesh, adding extra check to ensure _create_write_items()
521
+ # gets called only when the current rank is part of the mesh for the corresponding DTensor.
522
+ if isinstance(obj, DTensor):
523
+ if obj.device_mesh.get_coordinate() is not None:
524
+ requests += _create_write_items(fqn, obj)
525
+ else:
526
+ # For the plain tensor and non-tensor values, add the request for all
527
+ # the ranks. Coordinator will decides whether to deduplicate the
528
+ # values based on the keys.
529
+ requests += _create_write_items(fqn, obj)
530
+
531
+ return SavePlan(requests)
532
+
533
+
534
+ def create_default_global_save_plan(
535
+ all_plans: list[SavePlan],
536
+ rewrite_index_hints: bool = True,
537
+ ) -> tuple[list[SavePlan], Metadata]:
538
+ """
539
+ Create the global plan and metadata used by DefaultSavePlanner.
540
+
541
+ Metadata is produced by concatenating the metadata of all ``WriteItem`` from the supplied plans.
542
+
543
+ The only global planning change is to update index hints in all ``MetadataIndex`` objects if
544
+ ``rewrite_index_hints`` is True.
545
+ """
546
+ md: dict[str, STORAGE_TYPES] = {}
547
+ new_plans = []
548
+ for plan in all_plans:
549
+ new_items = []
550
+ for item in plan.items:
551
+ if not item.type == WriteItemType.SHARD:
552
+ assert item.index.fqn not in md
553
+
554
+ if item.type == WriteItemType.BYTE_IO:
555
+ md[item.index.fqn] = BytesStorageMetadata()
556
+ new_items.append(item)
557
+ else:
558
+ assert item.tensor_data is not None
559
+ tensor_md = cast(
560
+ TensorStorageMetadata,
561
+ md.setdefault(
562
+ item.index.fqn,
563
+ TensorStorageMetadata(
564
+ properties=item.tensor_data.properties,
565
+ size=item.tensor_data.size,
566
+ chunks=[],
567
+ ),
568
+ ),
569
+ )
570
+ new_item = item
571
+ if rewrite_index_hints:
572
+ new_index = dataclasses.replace(
573
+ item.index, index=len(tensor_md.chunks)
574
+ )
575
+ new_item = dataclasses.replace(item, index=new_index)
576
+ new_items.append(new_item)
577
+
578
+ assert item.tensor_data.chunk is not None, f"""
579
+ Cannot create MD for tensor without bounds.
580
+ FQN: {item.index.fqn}
581
+ """
582
+ tensor_md.chunks.append(item.tensor_data.chunk)
583
+ new_plans.append(dataclasses.replace(plan, items=new_items))
584
+ return (new_plans, Metadata(md))
585
+
586
+
587
+ def _create_default_local_metadata(state_dict: STATE_DICT_TYPE) -> Metadata:
588
+ """Return the ``Metadata`` if DefaultSavePlanner was used to checkpoint ``state_dict``."""
589
+ plan = _create_default_metadata_only_plan(state_dict)
590
+ _, md = create_default_global_save_plan([plan])
591
+ return md
592
+
593
+
594
+ def _check_box_overlap(box0: ChunkStorageMetadata, box1: ChunkStorageMetadata) -> bool:
595
+ """Check if two boxes overlap. Tuples are (offset, lengths)."""
596
+ # For each dim of each shard, check if one shard resides on the other
597
+ # end of second shard with respect to that dim. As an example for a 2D
598
+ # shard, we would check if one shard is above or on the left of the
599
+ # other shard.
600
+ ndims = len(box0.offsets)
601
+ for i in range(ndims):
602
+ if box0.offsets[i] >= box1.offsets[i] + box1.sizes[i]:
603
+ return False
604
+ if box1.offsets[i] >= box0.offsets[i] + box0.sizes[i]:
605
+ return False
606
+
607
+ return True
608
+
609
+
610
+ def _check_box_bounds(
611
+ outer_box_size: torch.Size, inner_box: ChunkStorageMetadata
612
+ ) -> bool:
613
+ for i in range(len(outer_box_size)):
614
+ if inner_box.offsets[i] < 0:
615
+ return False
616
+ if inner_box.sizes[i] < 0:
617
+ return False
618
+ if inner_box.offsets[i] + inner_box.sizes[i] > outer_box_size[i]:
619
+ return False
620
+
621
+ return True
622
+
623
+
624
+ def _validate_global_plan(global_plan: list[SavePlan], metadata: Metadata) -> bool:
625
+ all_good = True
626
+ for key, value in metadata.state_dict_metadata.items():
627
+ if isinstance(value, BytesStorageMetadata):
628
+ continue
629
+ if len(value.size) == 0:
630
+ continue
631
+ chunks_volume = 0
632
+ for chunk_idx, chunk0 in enumerate(value.chunks):
633
+ # Compute the volume
634
+ if not _check_box_bounds(value.size, chunk0):
635
+ logger.warning(
636
+ """
637
+ key:%s has out of bounds chunk:
638
+ tensor-size:%s chunk: %s
639
+ """,
640
+ key,
641
+ value.size,
642
+ chunk0,
643
+ )
644
+ all_good = False
645
+ chunks_volume += reduce(operator.mul, chunk0.sizes, 1)
646
+
647
+ # Check for overlap
648
+ for chunk1 in value.chunks[chunk_idx + 1 :]:
649
+ if _check_box_overlap(chunk0, chunk1):
650
+ logger.warning(
651
+ "key:%s has overlapping chunks: %s %s", key, chunk0, chunk1
652
+ )
653
+ all_good = False
654
+
655
+ # Check whether combined chunk cover the whole tensor
656
+ tensor_volume = reduce(operator.mul, value.size, 1)
657
+ if chunks_volume != tensor_volume:
658
+ logger.warning(
659
+ """
660
+ key:%s invalid fill tensor-volume:
661
+ %s chunks-volume: %s
662
+ """,
663
+ key,
664
+ tensor_volume,
665
+ chunks_volume,
666
+ )
667
+ all_good = False
668
+
669
+ return all_good
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/hf_storage.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import dataclasses
3
+ import json
4
+ import queue
5
+ from typing import Any, Optional
6
+
7
+ import torch
8
+ from torch.distributed._shard._utils import narrow_tensor_by_index
9
+ from torch.distributed.checkpoint._fsspec_filesystem import FsspecReader, FsspecWriter
10
+ from torch.distributed.checkpoint._hf_utils import (
11
+ _gen_file_name,
12
+ _get_dtype,
13
+ _get_safetensors_file_metadata,
14
+ _HFStorageInfo,
15
+ _metadata_fn,
16
+ CUSTOM_METADATA_KEY,
17
+ DATA_KEY,
18
+ DATA_OFFSETS_KEY,
19
+ DEFAULT_EXTRA_METADATA_KEY,
20
+ DTYPE_KEY,
21
+ SAVED_OFFSETS_KEY,
22
+ SHAPE_KEY,
23
+ SUFFIX,
24
+ )
25
+ from torch.distributed.checkpoint.filesystem import SerializationFormat
26
+ from torch.distributed.checkpoint.metadata import (
27
+ ChunkStorageMetadata,
28
+ Metadata,
29
+ MetadataIndex,
30
+ StorageMeta,
31
+ TensorProperties,
32
+ TensorStorageMetadata,
33
+ )
34
+ from torch.distributed.checkpoint.planner import (
35
+ LoadPlan,
36
+ LoadPlanner,
37
+ ReadItem,
38
+ SavePlan,
39
+ SavePlanner,
40
+ WriteItem,
41
+ )
42
+ from torch.distributed.checkpoint.storage import WriteResult
43
+ from torch.futures import Future
44
+
45
+
46
+ __all__ = ["HuggingFaceStorageWriter", "HuggingFaceStorageReader"]
47
+
48
+
49
+ class HuggingFaceStorageWriter(FsspecWriter):
50
+ """
51
+ A writer that writes to a huggingface repository in the huggingface format.
52
+ Uses Fsspec back-end to communicate with back-end storage.
53
+ Fsspec registration of the storage solution is required.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ path: str,
59
+ fqn_to_index_mapping: Optional[dict[str, int]] = None,
60
+ token: Optional[str] = None,
61
+ save_sharded: bool = False,
62
+ ) -> None:
63
+ """
64
+ Initialize the huggingface writer pointing to path.
65
+
66
+ Args:
67
+ path: hf directory where the checkpoint will be read from.
68
+ Needs to have .safetensors files, but can be from any fsspec supported storage,
69
+ including localFS and hf://.
70
+ fqn_to_index_mapping: A mapping from tensor FQN to the index of the file that the tensor should be written to.
71
+ Indices are from 1 to N, where N is the number of files. If not provided,
72
+ the tensors will be written to a single file. If none, then all the tensors on the
73
+ same rank will be written to the same file.
74
+ token: The token to use to authenticate with huggingface hub.
75
+ save_sharded: If True, save the checkpoint as a sharded checkpoint where every rank saves its own shard.
76
+ Default is False which assumes full tensors are being saved.
77
+
78
+ """
79
+
80
+ if token is not None:
81
+ super().__init__(
82
+ path=path,
83
+ token=token,
84
+ serialization_format=SerializationFormat.SAFETENSORS,
85
+ )
86
+ else:
87
+ super().__init__(
88
+ path=path,
89
+ serialization_format=SerializationFormat.SAFETENSORS,
90
+ )
91
+ self._fqn_to_index_mapping: Optional[dict[str, int]] = fqn_to_index_mapping
92
+ self._save_sharded = save_sharded
93
+
94
+ def prepare_global_plan(self, plans: list[SavePlan]) -> list[SavePlan]:
95
+ new_plans = []
96
+ for i, plan in enumerate(plans, start=1):
97
+ storage_data: dict[str, Any] = {}
98
+ if self._fqn_to_index_mapping is not None:
99
+ storage_data["fqn_to_index_mapping"] = self._fqn_to_index_mapping
100
+ if self._save_sharded:
101
+ storage_data["shard_index"] = i
102
+
103
+ new_plans.append(dataclasses.replace(plan, storage_data=storage_data))
104
+
105
+ return new_plans
106
+
107
+ def write_data(
108
+ self,
109
+ plan: SavePlan,
110
+ planner: SavePlanner,
111
+ ) -> Future[list[WriteResult]]:
112
+ if len(plan.items) == 0:
113
+ fut: Future = Future()
114
+ fut.set_result([])
115
+ return fut
116
+
117
+ # storage_plan is a map from key to file index
118
+ storage_data: dict[str, Any] = plan.storage_data
119
+ storage_plan: Optional[dict[str, int]] = None
120
+ shard_index: Optional[int] = None
121
+ if "fqn_to_index_mapping" in storage_data:
122
+ storage_plan = storage_data["fqn_to_index_mapping"]
123
+ if "shard_index" in storage_data:
124
+ shard_index = storage_data["shard_index"]
125
+
126
+ buckets = self._split_by_storage_plan(storage_plan, plan.items)
127
+ highest_index = max(storage_plan.values()) if storage_plan is not None else 1
128
+
129
+ file_queue: queue.Queue = queue.Queue()
130
+ for file_index, write_items in buckets.items():
131
+ file_name = _gen_file_name(file_index, highest_index, shard_index)
132
+ file_queue.put(
133
+ (self.fs.concat_path(self.path, file_name), file_name, write_items)
134
+ )
135
+
136
+ return super()._write_data(planner, file_queue)
137
+
138
+ def finish(self, metadata: Metadata, results: list[list[WriteResult]]) -> None:
139
+ if self._save_sharded:
140
+ return
141
+
142
+ metadata_to_write = {}
143
+ storage_md = {}
144
+ total_size = 0
145
+ for wr_list in results:
146
+ storage_md.update(
147
+ {wr.index.fqn: wr.storage_data.relative_path for wr in wr_list}
148
+ )
149
+ total_size += sum([wr.storage_data.length for wr in wr_list])
150
+ metadata_to_write["metadata"] = {"total_size": total_size}
151
+ metadata_to_write["weight_map"] = storage_md
152
+
153
+ metadata_path = self.fs.concat_path(self.path, f"{_metadata_fn}")
154
+ with self.fs.create_stream(metadata_path, "w") as metadata_file:
155
+ json.dump(metadata_to_write, metadata_file, indent=2)
156
+
157
+ def _split_by_storage_plan(
158
+ self, storage_plan: Optional[dict[str, int]], items: list[WriteItem]
159
+ ) -> dict[int, list[WriteItem]]:
160
+ # storage_plan is a map from key to index
161
+ if storage_plan is None:
162
+ return {1: items}
163
+
164
+ buckets = {}
165
+ for item in items:
166
+ key = item.index.fqn
167
+
168
+ idx = storage_plan[key]
169
+ if idx not in buckets:
170
+ buckets[idx] = [item]
171
+ else:
172
+ buckets[idx].append(item)
173
+
174
+ return buckets
175
+
176
+ @property
177
+ def metadata_path(self) -> str:
178
+ return _metadata_fn
179
+
180
+
181
+ class HuggingFaceStorageReader(FsspecReader):
182
+ """
183
+ A reader that reads from a huggingface repository in the huggingface format.
184
+ Uses in Fsspec back-end to communicate with storage.
185
+ Fsspec registration of the storage solution is required.
186
+ """
187
+
188
+ def __init__(self, path: str, token: Optional[str] = None) -> None:
189
+ """
190
+ Initialize the huggingface reader pointing to path.
191
+
192
+ Args:
193
+ path: hf directory where the checkpoint will be read from.
194
+ Needs to have .safetensors file, but can be from any fsspec supported storage,
195
+ including localFS and hf://.
196
+ token: The token to use to authenticate with huggingface hub.
197
+ """
198
+
199
+ if token is not None:
200
+ super().__init__(path=path, token=token)
201
+ else:
202
+ super().__init__(path=path)
203
+
204
+ def read_data(self, plan: LoadPlan, planner: LoadPlanner) -> Future[None]:
205
+ from safetensors import deserialize # type: ignore[import-not-found]
206
+
207
+ per_file: dict[str, list[ReadItem]] = {}
208
+
209
+ for read_item in plan.items:
210
+ item_md: _HFStorageInfo = self.storage_data[read_item.storage_index]
211
+ file_name = item_md.relative_path
212
+ per_file.setdefault(file_name, []).append(read_item)
213
+
214
+ for file_name, reqs in per_file.items():
215
+ with self.fs.create_stream(file_name, "rb") as stream:
216
+ # TODO: make this more efficient by doing offset reads instead of a
217
+ # full deserialization of the file
218
+ deserialized = deserialize(stream.read())
219
+ deserialized_dict: dict[str, dict[str, Any]] = {
220
+ tensor_info[0]: tensor_info[1] for tensor_info in deserialized
221
+ }
222
+
223
+ for req in reqs:
224
+ item_md = self.storage_data[req.storage_index]
225
+
226
+ tensor_bytes = deserialized_dict[req.dest_index.fqn][DATA_KEY]
227
+
228
+ tensor = torch.frombuffer(
229
+ tensor_bytes,
230
+ dtype=item_md.dtype,
231
+ )
232
+ tensor = tensor.reshape(item_md.shape)
233
+ tensor = narrow_tensor_by_index(
234
+ tensor, req.storage_offsets, req.lengths
235
+ )
236
+ target_tensor = planner.resolve_tensor(req).detach()
237
+
238
+ assert target_tensor.size() == tensor.size(), (
239
+ f"req {req.storage_index} mismatch sizes {target_tensor.size()} vs {tensor.size()}"
240
+ )
241
+
242
+ target_tensor.copy_(tensor)
243
+ planner.commit_tensor(req, target_tensor)
244
+
245
+ fut: Future = Future()
246
+ fut.set_result(None)
247
+ return fut
248
+
249
+ def read_metadata(self) -> Metadata:
250
+ state_dict_metadata: dict[str, TensorStorageMetadata] = {}
251
+ storage_data: dict[MetadataIndex, _HFStorageInfo] = {}
252
+
253
+ safetensors_files = []
254
+ for file in self.fs.ls(self.path):
255
+ if file.endswith(SUFFIX):
256
+ safetensors_files.append(file)
257
+
258
+ for safetensor_file in safetensors_files:
259
+ with self.fs.create_stream(safetensor_file, "rb") as f:
260
+ safetensors_metadata, _ = _get_safetensors_file_metadata(f)
261
+ custom_metadata = safetensors_metadata.get(DEFAULT_EXTRA_METADATA_KEY)
262
+
263
+ dcp_sharding_info = None
264
+ if custom_metadata and custom_metadata.get(CUSTOM_METADATA_KEY):
265
+ dcp_sharding_info = json.loads(
266
+ custom_metadata.get(CUSTOM_METADATA_KEY)
267
+ )
268
+
269
+ for key, val in safetensors_metadata.items():
270
+ if key == DEFAULT_EXTRA_METADATA_KEY:
271
+ continue
272
+
273
+ # construct state_dict_metadata
274
+ if dcp_sharding_info is not None:
275
+ offset = dcp_sharding_info[key][SAVED_OFFSETS_KEY]
276
+ else:
277
+ offset = [0] * len(val[SHAPE_KEY])
278
+
279
+ if key not in state_dict_metadata:
280
+ state_dict_metadata[key] = TensorStorageMetadata(
281
+ properties=TensorProperties(
282
+ dtype=_get_dtype(val[DTYPE_KEY])
283
+ ),
284
+ size=torch.Size(
285
+ [
286
+ saved + offset
287
+ for saved, offset in zip(val[SHAPE_KEY], offset)
288
+ ]
289
+ ),
290
+ chunks=[
291
+ ChunkStorageMetadata(
292
+ offsets=torch.Size(offset),
293
+ sizes=torch.Size(val[SHAPE_KEY]),
294
+ )
295
+ ],
296
+ )
297
+ else:
298
+ state_dict_metadata[key].chunks.append(
299
+ ChunkStorageMetadata(
300
+ torch.Size(offset), sizes=torch.Size(val[SHAPE_KEY])
301
+ )
302
+ )
303
+ size = list(state_dict_metadata[key].size)
304
+ for i in range(len(size)):
305
+ size[i] = max(size[i], val[SHAPE_KEY][i] + offset[i])
306
+ state_dict_metadata[key].size = torch.Size(size)
307
+
308
+ # construct storage data
309
+ if dcp_sharding_info is not None:
310
+ metadata_index = MetadataIndex(
311
+ fqn=key, offset=dcp_sharding_info[key][SAVED_OFFSETS_KEY]
312
+ )
313
+ else:
314
+ metadata_index = MetadataIndex(
315
+ fqn=key, offset=[0] * len(val[SHAPE_KEY])
316
+ )
317
+ storage_data[metadata_index] = _HFStorageInfo(
318
+ relative_path=safetensor_file,
319
+ offset=val[DATA_OFFSETS_KEY][0],
320
+ length=val[DATA_OFFSETS_KEY][1] - val[DATA_OFFSETS_KEY][0],
321
+ shape=torch.Size(val[SHAPE_KEY]),
322
+ dtype=_get_dtype(val[DTYPE_KEY]),
323
+ )
324
+
325
+ metadata = Metadata(
326
+ state_dict_metadata=state_dict_metadata, # type: ignore[arg-type]
327
+ storage_data=storage_data,
328
+ )
329
+
330
+ if getattr(metadata, "storage_meta", None) is None:
331
+ metadata.storage_meta = StorageMeta()
332
+ metadata.storage_meta.load_id = self.load_id # type: ignore[union-attr]
333
+
334
+ return metadata
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/logger.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ import logging
4
+ import time
5
+ from typing import Any, Callable, TypeVar
6
+ from typing_extensions import ParamSpec
7
+ from uuid import uuid4
8
+
9
+ import torch.distributed.c10d_logger as c10d_logger
10
+ from torch.distributed.checkpoint.logging_handlers import DCP_LOGGER_NAME
11
+
12
+
13
+ logger = logging.getLogger()
14
+
15
+
16
+ __all__: list[str] = []
17
+
18
+ global _dcp_logger
19
+ _dcp_logger = c10d_logger._get_or_create_logger(DCP_LOGGER_NAME)
20
+
21
+ _T = TypeVar("_T")
22
+ _P = ParamSpec("_P")
23
+
24
+
25
+ def _msg_dict_from_dcp_method_args(*args, **kwargs) -> dict[str, Any]:
26
+ """
27
+ Extracts log data from dcp method args
28
+ """
29
+ msg_dict = {}
30
+
31
+ # checkpoint ID can be passed in through the serializer or through the checkpoint id directly
32
+ storage_writer = kwargs.get("storage_writer", None)
33
+ storage_reader = kwargs.get("storage_reader", None)
34
+ planner = kwargs.get("planner", None)
35
+
36
+ checkpoint_id = kwargs.get("checkpoint_id", None)
37
+ if not checkpoint_id and (serializer := storage_writer or storage_reader):
38
+ checkpoint_id = getattr(serializer, "checkpoint_id", None)
39
+
40
+ msg_dict["checkpoint_id"] = (
41
+ str(checkpoint_id) if checkpoint_id is not None else checkpoint_id
42
+ )
43
+
44
+ # Uniquely identify a _dcp_method_logger wrapped function call.
45
+ msg_dict["uuid"] = str(uuid4().int)
46
+
47
+ if storage_writer:
48
+ msg_dict["storage_writer"] = storage_writer.__class__.__name__
49
+
50
+ if storage_reader:
51
+ msg_dict["storage_reader"] = storage_reader.__class__.__name__
52
+
53
+ if planner:
54
+ msg_dict["planner"] = planner.__class__.__name__
55
+
56
+ return msg_dict
57
+
58
+
59
+ def _get_msg_dict(func_name, *args, **kwargs) -> dict[str, Any]:
60
+ msg_dict = _msg_dict_from_dcp_method_args(*args, **kwargs)
61
+ msg_dict.update(c10d_logger._get_msg_dict(func_name, *args, **kwargs))
62
+
63
+ return msg_dict
64
+
65
+
66
+ def _dcp_method_logger(
67
+ log_exceptions: bool = False, **wrapper_kwargs: Any
68
+ ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: # pyre-ignore
69
+ """This method decorator logs the start, end, and exception of wrapped events."""
70
+
71
+ def decorator(func: Callable[_P, _T]):
72
+ @functools.wraps(func)
73
+ def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
74
+ msg_dict = _get_msg_dict(
75
+ func.__name__, *args, **{**wrapper_kwargs, **kwargs}
76
+ )
77
+
78
+ # log start event
79
+ msg_dict["event"] = "start"
80
+ t0 = time.time_ns()
81
+ msg_dict["time"] = t0
82
+ msg_dict["log_exceptions"] = log_exceptions
83
+ _dcp_logger.debug(msg_dict)
84
+
85
+ # exceptions
86
+ try:
87
+ result = func(*args, **kwargs)
88
+ except BaseException as error:
89
+ if log_exceptions:
90
+ msg_dict["event"] = "exception"
91
+ msg_dict["error"] = f"{error}"
92
+ msg_dict["time"] = time.time_ns()
93
+ _dcp_logger.error(msg_dict)
94
+ raise
95
+
96
+ # end event
97
+ msg_dict["event"] = "end"
98
+ t1 = time.time_ns()
99
+ msg_dict["time"] = time.time_ns()
100
+ msg_dict["times_spent"] = t1 - t0
101
+ _dcp_logger.debug(msg_dict)
102
+
103
+ return result
104
+
105
+ return wrapper
106
+
107
+ return decorator
108
+
109
+
110
+ def _init_logger(rank: int):
111
+ logger.setLevel(logging.INFO)
112
+ ch = logging.StreamHandler()
113
+ ch.setLevel(logging.INFO)
114
+ formatter = logging.Formatter(
115
+ f"[{rank}] %(asctime)s - %(name)s - %(levelname)s - %(message)s"
116
+ )
117
+ ch.setFormatter(formatter)
118
+ logger.addHandler(ch)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/logging_handlers.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from torch.distributed.logging_handlers import _log_handlers
4
+
5
+
6
+ __all__: list[str] = []
7
+
8
+ DCP_LOGGER_NAME = "dcp_logger"
9
+
10
+ _log_handlers.update(
11
+ {
12
+ DCP_LOGGER_NAME: logging.NullHandler(),
13
+ }
14
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/metadata.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import os
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass, field
5
+ from enum import Enum
6
+ from typing import Any, Optional, Union
7
+
8
+ import torch
9
+ from torch.distributed.checkpoint.stateful import StatefulT
10
+
11
+
12
+ __all__ = [
13
+ "ChunkStorageMetadata",
14
+ "TensorStorageMetadata",
15
+ "BytesStorageMetadata",
16
+ "Metadata",
17
+ "MetadataIndex",
18
+ "TensorProperties",
19
+ "StorageMeta",
20
+ ]
21
+
22
+
23
+ @dataclass
24
+ class ChunkStorageMetadata:
25
+ """
26
+ Each chunk is expected to have the same properties of the TensorStorageMetadata
27
+ that includes it.
28
+ """
29
+
30
+ offsets: torch.Size
31
+ sizes: torch.Size
32
+
33
+
34
+ class _MEM_FORMAT_ENCODING(Enum):
35
+ """Describe the memory format of a tensor."""
36
+
37
+ TORCH_CONTIGUOUS_FORMAT = 0
38
+ TORCH_CHANNELS_LAST = 1
39
+ TORCH_PRESERVE_FORMAT = 2
40
+
41
+
42
+ @dataclass
43
+ class TensorProperties:
44
+ """Properties used to create :class:`Tensor`"""
45
+
46
+ # Regular tensor fields
47
+ dtype: torch.dtype = field(default_factory=torch.get_default_dtype)
48
+ # This field is deprecated.
49
+ layout: torch.layout = field(default=torch.strided)
50
+ # This field is deprecated.
51
+ requires_grad: bool = False
52
+ # This field is deprecated.
53
+ memory_format: torch.memory_format = field(default=torch.contiguous_format)
54
+ # This field is deprecated.
55
+ pin_memory: bool = False
56
+
57
+ def __getstate__(self):
58
+ # Since torch.memory_format cannot be pickled!
59
+ memory_format = self.memory_format
60
+ if memory_format == torch.contiguous_format:
61
+ mem_format_encoding = _MEM_FORMAT_ENCODING.TORCH_CONTIGUOUS_FORMAT
62
+ elif memory_format == torch.channels_last:
63
+ mem_format_encoding = _MEM_FORMAT_ENCODING.TORCH_CHANNELS_LAST
64
+ elif memory_format == torch.preserve_format:
65
+ mem_format_encoding = _MEM_FORMAT_ENCODING.TORCH_PRESERVE_FORMAT
66
+ else:
67
+ raise RuntimeError(f"Invalid torch.memory_format: {memory_format}")
68
+
69
+ return (
70
+ self.dtype,
71
+ self.layout,
72
+ self.requires_grad,
73
+ mem_format_encoding,
74
+ self.pin_memory,
75
+ )
76
+
77
+ def __setstate__(
78
+ self,
79
+ state,
80
+ ):
81
+ (
82
+ self.dtype,
83
+ self.layout,
84
+ self.requires_grad,
85
+ mem_format_encoding,
86
+ self.pin_memory,
87
+ ) = state
88
+
89
+ if mem_format_encoding == _MEM_FORMAT_ENCODING.TORCH_CONTIGUOUS_FORMAT:
90
+ memory_format = torch.contiguous_format
91
+ elif mem_format_encoding == _MEM_FORMAT_ENCODING.TORCH_CHANNELS_LAST:
92
+ memory_format = torch.channels_last
93
+ elif mem_format_encoding == _MEM_FORMAT_ENCODING.TORCH_PRESERVE_FORMAT:
94
+ memory_format = torch.preserve_format
95
+ else:
96
+ raise RuntimeError(
97
+ f"Invalid torch.memory_format encoding: {mem_format_encoding}"
98
+ )
99
+
100
+ self.memory_format = memory_format
101
+
102
+ @staticmethod
103
+ def create_from_tensor(tensor: torch.Tensor) -> "TensorProperties":
104
+ return TensorProperties(
105
+ dtype=tensor.dtype,
106
+ layout=tensor.layout,
107
+ requires_grad=tensor.requires_grad,
108
+ memory_format=torch.contiguous_format,
109
+ pin_memory=tensor.is_pinned(),
110
+ )
111
+
112
+
113
+ @dataclass
114
+ class TensorStorageMetadata:
115
+ properties: TensorProperties
116
+ size: torch.Size
117
+ chunks: list[ChunkStorageMetadata]
118
+
119
+
120
+ @dataclass
121
+ class BytesStorageMetadata:
122
+ pass
123
+
124
+
125
+ STORAGE_TYPES = Union[TensorStorageMetadata, BytesStorageMetadata]
126
+ STATE_DICT_TYPE = dict[str, Union[StatefulT, Any]]
127
+
128
+
129
+ @dataclass
130
+ class StorageMeta:
131
+ checkpoint_id: Union[str, os.PathLike, None] = None
132
+ save_id: Optional[str] = None
133
+ load_id: Optional[str] = None
134
+ modules: list[str] = field(default_factory=list)
135
+
136
+
137
+ @dataclass
138
+ class Metadata:
139
+ """This class represents the metadata of the checkpoint."""
140
+
141
+ # Keys are the same from the `state_dict` used.
142
+ state_dict_metadata: dict[str, STORAGE_TYPES]
143
+ # It is the responsibility of the planner and storage plugins to ensure
144
+ # backward compatibility of the planner_data and storage_data. DCP will
145
+ # also ensure the backward compatibility of the metadata in this file and
146
+ # the metadata of the built-in planner and storage plugins.
147
+ planner_data: Any = None
148
+ storage_data: Any = None
149
+ storage_meta: Optional[StorageMeta] = None
150
+
151
+
152
+ @dataclass(frozen=True)
153
+ class MetadataIndex:
154
+ """This class represents a lookup key for items in a state dict or Metadata."""
155
+
156
+ fqn: str
157
+ """Fully Qualified Name of the object"""
158
+
159
+ offset: Optional[torch.Size] = None
160
+ """If the object is a tensor, offset into the tensor we're looking for"""
161
+
162
+ index: Optional[int] = field(hash=False, compare=False, default=None)
163
+ """
164
+ Index hint when searching for tensor chunk to speedup lookups (optional)
165
+
166
+ A common representation of a sharded tensor is as a list of chunks so to
167
+ find the index in such a list you need to linear search it.
168
+
169
+ When constructing an instance of MetadataIndex that points to that list,
170
+ one can provide the index as a hint and it will be probed first before
171
+ the linear search and thus making it significantly faster.
172
+ """
173
+
174
+ def __init__(
175
+ self,
176
+ fqn: str,
177
+ offset: Optional[Sequence[int]] = None,
178
+ index: Optional[int] = None,
179
+ ):
180
+ # We must use object.__setattr__ due to frozen=True
181
+ object.__setattr__(self, "fqn", fqn)
182
+ object.__setattr__(self, "index", index)
183
+ if offset is not None:
184
+ object.__setattr__(self, "offset", torch.Size(offset))
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/checkpoint/optimizer.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+
3
+ import dataclasses
4
+ from collections.abc import Sequence
5
+ from typing import cast, Optional, Union
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+ from torch._utils import _get_device_module
10
+ from torch.distributed._shard.sharded_tensor.api import ShardedTensor
11
+ from torch.distributed._shard.sharded_tensor.metadata import (
12
+ TensorProperties as ShardTensorProperties,
13
+ )
14
+ from torch.distributed._shard.sharded_tensor.shard import Shard
15
+ from torch.distributed._shard.sharding_spec.chunk_sharding_spec import ChunkShardingSpec
16
+ from torch.distributed.checkpoint._nested_dict import unflatten_state_dict
17
+ from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner
18
+ from torch.distributed.checkpoint.metadata import (
19
+ BytesStorageMetadata,
20
+ ChunkStorageMetadata,
21
+ Metadata,
22
+ MetadataIndex,
23
+ STATE_DICT_TYPE,
24
+ TensorProperties,
25
+ TensorStorageMetadata,
26
+ )
27
+ from torch.distributed.checkpoint.planner import LoadPlan, LoadPlanner
28
+ from torch.distributed.checkpoint.planner_helpers import (
29
+ _create_read_items,
30
+ create_read_items_for_chunk_list,
31
+ )
32
+ from torch.distributed.checkpoint.state_dict_loader import load_state_dict
33
+ from torch.distributed.checkpoint.storage import StorageReader
34
+ from torch.distributed.checkpoint.utils import (
35
+ _element_wise_add,
36
+ _element_wise_sub,
37
+ _normalize_device_info,
38
+ )
39
+ from torch.distributed.distributed_c10d import _get_default_group
40
+ from torch.distributed.fsdp._shard_utils import _create_chunk_sharded_tensor
41
+ from torch.distributed.remote_device import _remote_device
42
+ from torch.distributed.tensor import DTensor
43
+
44
+
45
+ STATE_DICT_2D_LAYOUT = dict[str, tuple[Optional[Sequence[int]], Sequence[int]]]
46
+
47
+
48
+ # TODO: Update docstrings for optimizer.py
49
+ __all__ = [
50
+ "load_sharded_optimizer_state_dict",
51
+ ]
52
+
53
+
54
+ def _gen_rank_device(global_rank: int, device_type: str = "cuda") -> str:
55
+ if device_type == "cpu":
56
+ return "cpu"
57
+ device_module = _get_device_module(device_type)
58
+ if device_module.is_available():
59
+ return _normalize_device_info(
60
+ device_type, global_rank % device_module.device_count()
61
+ )
62
+ return "cpu"
63
+
64
+
65
+ def _create_colwise_spec(
66
+ pg: Optional[dist.ProcessGroup] = None,
67
+ ) -> ChunkShardingSpec:
68
+ pg_device_type = dist.distributed_c10d._get_pg_default_device(pg).type
69
+ if pg is None:
70
+ placements = [
71
+ f"rank:{idx}/{_gen_rank_device(idx, pg_device_type)}"
72
+ for idx in range(dist.get_world_size())
73
+ ]
74
+ else:
75
+ placements = [
76
+ f"rank:{idx}/{_gen_rank_device(dist.get_global_rank(pg, idx), pg_device_type)}"
77
+ for idx in range(pg.size())
78
+ ]
79
+ return ChunkShardingSpec(
80
+ dim=0,
81
+ placements=cast(list[Union[_remote_device, str]], placements),
82
+ )
83
+
84
+
85
+ def _is_nested_tensor(val: torch.Tensor) -> bool:
86
+ if type(val) is ShardedTensor:
87
+ if len(val.local_shards()) == 0:
88
+ return False
89
+ if type(val.local_shards()[0].tensor) is ShardedTensor:
90
+ return True
91
+ if type(val.local_shards()[0].tensor) is DTensor:
92
+ raise ValueError("Cannot handle DTensor nested inside ShardedTensor")
93
+ elif type(val) is DTensor and (
94
+ type(val._local_tensor) is DTensor or type(val._local_tensor) is ShardedTensor
95
+ ):
96
+ raise ValueError("Cannot handle nested DTensor")
97
+ return False
98
+
99
+
100
+ def _alloc_tensor(
101
+ props: TensorProperties, size: Sequence[int], device_type: str = "cuda"
102
+ ) -> torch.Tensor:
103
+ if device_type == "cpu":
104
+ device = cast(torch.device, _get_device_module(device_type).current_device())
105
+ else:
106
+ device = torch.device(
107
+ device_type, _get_device_module(device_type).current_device()
108
+ )
109
+
110
+ return torch.empty(
111
+ size=size,
112
+ dtype=props.dtype,
113
+ layout=props.layout,
114
+ requires_grad=props.requires_grad,
115
+ pin_memory=props.pin_memory,
116
+ device=device,
117
+ )
118
+
119
+
120
+ def _get_state_dict_2d_layout(
121
+ state_dict: STATE_DICT_TYPE,
122
+ ) -> tuple[STATE_DICT_2D_LAYOUT, Optional[dist.ProcessGroup]]:
123
+ """
124
+ Load the right TP slice of the optimizer state.
125
+
126
+ This is not easy since the per-tensor slicing can't be inferred from checkpoint metadata.
127
+ We take advantage of the model state_dict producing a sliced ST to figure out what we need to load.
128
+ This is pretty fragile and it might be easier for FSDP to compute this info for us.
129
+ Returns a dictionary where keys are the same of the state_dict and the value is a tuple of
130
+ (offset, size) for the current rank TP slice.
131
+ N.B. The state_dict *MUST* come from FSDP.sharded_state_dict.
132
+ """
133
+ specs: STATE_DICT_2D_LAYOUT = {}
134
+ dp_pg: Optional[dist.ProcessGroup] = None
135
+ for key, value in state_dict.items():
136
+ specs[key] = (None, value.size())
137
+ if _is_nested_tensor(value):
138
+ assert len(value.local_shards()) == 1, (
139
+ "Cannot handle ST with multiple shards"
140
+ )
141
+ assert isinstance(value, ShardedTensor), (
142
+ "Can only handle nested ShardedTensor"
143
+ )
144
+ shard = value.local_shards()[0]
145
+ specs[key] = (
146
+ shard.metadata.shard_offsets,
147
+ shard.metadata.shard_sizes,
148
+ )
149
+ dp_pg = shard.tensor._process_group # type: ignore[attr-defined]
150
+
151
+ return (
152
+ specs,
153
+ dp_pg,
154
+ )
155
+
156
+
157
+ class _ReaderWithOffset(DefaultLoadPlanner):
158
+ translation: dict[MetadataIndex, MetadataIndex]
159
+ state_dict: STATE_DICT_TYPE
160
+ metadata: Metadata
161
+
162
+ def __init__(self, fqn_to_offset: dict[str, Sequence[int]]) -> None:
163
+ super().__init__()
164
+ self.fqn_to_offset = fqn_to_offset
165
+ self.metadata = Metadata({})
166
+ self.state_dict = {}
167
+ self.translation = {}
168
+
169
+ def create_local_plan(self) -> LoadPlan:
170
+ requests = []
171
+ self.translation = {}
172
+ for fqn, obj in self.state_dict.items():
173
+ md = self.metadata.state_dict_metadata[fqn]
174
+ if not isinstance(obj, ShardedTensor):
175
+ requests += _create_read_items(fqn, md, obj)
176
+ continue
177
+
178
+ if fqn not in self.fqn_to_offset:
179
+ requests += _create_read_items(fqn, md, obj)
180
+ continue
181
+
182
+ offset = self.fqn_to_offset[fqn]
183
+
184
+ assert len(obj.local_shards()) == 1
185
+ original_shard = obj.local_shards()[0]
186
+ local_chunks = [
187
+ ChunkStorageMetadata(
188
+ offsets=torch.Size(
189
+ _element_wise_add(original_shard.metadata.shard_offsets, offset)
190
+ ),
191
+ sizes=torch.Size(original_shard.metadata.shard_sizes),
192
+ )
193
+ ]
194
+
195
+ reqs = create_read_items_for_chunk_list(
196
+ fqn, cast(TensorStorageMetadata, md), local_chunks
197
+ )
198
+ # TODO: The ReadItems will have a displaced MetadataIndex, fix it.
199
+ # TODO: we should change _create_sharded_read_items to have more ergonomic API
200
+ for ri in reqs:
201
+ assert ri.dest_index.offset is not None
202
+ original_offset = _element_wise_sub(ri.dest_index.offset, offset)
203
+ original_index = dataclasses.replace(
204
+ ri.dest_index, offset=torch.Size(original_offset)
205
+ )
206
+ self.translation[ri.dest_index] = original_index
207
+
208
+ requests += reqs
209
+ return LoadPlan(requests)
210
+
211
+ def lookup_tensor(self, index: MetadataIndex) -> torch.Tensor:
212
+ return super().lookup_tensor(self.translation.get(index, index))
213
+
214
+
215
+ def load_sharded_optimizer_state_dict(
216
+ model_state_dict: STATE_DICT_TYPE,
217
+ optimizer_key: str,
218
+ storage_reader: StorageReader,
219
+ planner: Optional[LoadPlanner] = None,
220
+ ) -> STATE_DICT_TYPE:
221
+ """
222
+ Load a state_dict in conjunction with FSDP sharded optimizer state.
223
+
224
+ This is the current recommended way to checkpoint FSDP.
225
+ >>> # xdoctest: +SKIP
226
+ >>> import torch.distributed.checkpoint as dist_cp
227
+ >>> # Save
228
+ >>> model: torch.nn.Model
229
+ >>> optim_params = model.parameters()
230
+ >>> optim = torch.optim.SGD(optim_params, lr=0.01)
231
+ >>> # Save
232
+ >>> with FSDP.state_dict_type(model, StateDictType.SHARDED_STATE_DICT):
233
+ >>> state_dict = {
234
+ >>> "optimizer": FSDP.optim_state_dict(model, optim),
235
+ >>> "model": model.state_dict()
236
+ >>> }
237
+ >>> dist_cp.save_state_dict(
238
+ >>> state_dict=optim_state,
239
+ >>> storage_writer=dist_cp.FileSystemWriter("checkpoint"),
240
+ >>> planner=dist_cp.DefaultSavePlanner(),
241
+ >>> )
242
+ >>>
243
+ >>> # Load
244
+ >>> with FSDP.state_dict_type(model_tp, StateDictType.SHARDED_STATE_DICT):
245
+ >>> model_state_dict = model_tp.state_dict()
246
+ >>> checkpoint = {
247
+ >>> "model": model_state_dict
248
+ >>> }
249
+ >>> dist_cp.load_state_dict(
250
+ >>> state_dict=checkpoint,
251
+ >>> storage_reader=dist_cp.FileSystemReader(checkpoint_file),
252
+ >>> planner=dist_cp.DefaultLoadPlanner(),
253
+ >>> )
254
+ >>> model.load_state_dict(checkpoint["model_state"])
255
+ >>>
256
+ >>> optim_state = dist_cp.load_sharded_optimizer_state_dict(
257
+ >>> model_state_dict,
258
+ >>> optimizer_key="optimizer",
259
+ >>> storage_reader=dist_cp.FileSystemReader("checkpoint"),
260
+ >>> )
261
+ >>>
262
+ >>> flattened_osd = FSDP.optim_state_dict_to_load(
263
+ >>> model, optim, optim_state["optimizer"]
264
+ >>> )
265
+ >>>
266
+ >>> optim.load_state_dict(flattened_osd)
267
+ """
268
+ metadata = storage_reader.read_metadata()
269
+
270
+ layout_specs, dp_pg = _get_state_dict_2d_layout(model_state_dict)
271
+ dp_pg_device_type = dist.distributed_c10d._get_pg_default_device(dp_pg).type
272
+ device_module = _get_device_module(dp_pg_device_type)
273
+
274
+ if dp_pg is None:
275
+ placements = []
276
+ for i in range(dist.get_world_size()):
277
+ device_info = _normalize_device_info(
278
+ dp_pg_device_type, i % device_module.device_count()
279
+ )
280
+ placements.append(f"rank:{i}/{device_info}")
281
+ sharding_spec = ChunkShardingSpec(dim=0, placements=placements) # type: ignore[arg-type]
282
+ else:
283
+ sharding_spec = _create_colwise_spec(dp_pg)
284
+
285
+ # Create a state_dict for optimizer state
286
+ state_dict: STATE_DICT_TYPE = {}
287
+
288
+ fqn_to_offset: dict[str, Sequence[int]] = {}
289
+ for key, value in metadata.state_dict_metadata.items():
290
+ key_path = metadata.planner_data[key]
291
+ if key_path[0] != optimizer_key:
292
+ continue
293
+
294
+ if isinstance(value, BytesStorageMetadata):
295
+ state_dict[key] = "<bytes_io>"
296
+ continue
297
+
298
+ # value: TensorStorageMetadata
299
+ if value.size.numel() == 1:
300
+ state_dict[key] = _alloc_tensor(
301
+ value.properties, value.size, dp_pg_device_type
302
+ )
303
+ elif dp_pg is None:
304
+ state_dict[key] = _create_chunk_sharded_tensor(
305
+ _alloc_tensor(value.properties, value.size, dp_pg_device_type),
306
+ rank=dist.get_rank(),
307
+ world_size=dist.get_world_size(),
308
+ num_devices_per_node=device_module.device_count(),
309
+ pg=_get_default_group(),
310
+ )
311
+ else:
312
+ spec_key = key_path[2]
313
+ alloc_size = layout_specs.get(spec_key, (None, value.size))[1]
314
+
315
+ properties = ShardTensorProperties(
316
+ dtype=value.properties.dtype,
317
+ layout=value.properties.layout,
318
+ requires_grad=value.properties.requires_grad,
319
+ memory_format=value.properties.memory_format,
320
+ pin_memory=value.properties.pin_memory,
321
+ )
322
+
323
+ st_md = sharding_spec.build_metadata(torch.Size(alloc_size), properties)
324
+ local_shards = []
325
+ current_rank = dist.get_rank(dp_pg)
326
+ for shard_md in st_md.shards_metadata:
327
+ if cast(_remote_device, shard_md.placement).rank() != current_rank:
328
+ continue
329
+ local_shards.append(
330
+ Shard(
331
+ tensor=_alloc_tensor(
332
+ value.properties, shard_md.shard_sizes, dp_pg_device_type
333
+ ),
334
+ metadata=shard_md,
335
+ )
336
+ )
337
+
338
+ st = ShardedTensor._init_from_local_shards_and_global_metadata(
339
+ local_shards, st_md, process_group=dp_pg
340
+ )
341
+
342
+ if spec_key in layout_specs and layout_specs[spec_key][0] is not None:
343
+ fqn_to_offset[key] = cast(Sequence[int], layout_specs[spec_key][0])
344
+
345
+ state_dict[key] = st
346
+
347
+ # Whether we unflatten before or after doesn't matter
348
+ load_state_dict(
349
+ state_dict=state_dict,
350
+ storage_reader=storage_reader,
351
+ # FIXME the type of planner is wrong in load_state_dict
352
+ planner=_ReaderWithOffset(fqn_to_offset) if dp_pg is not None else planner,
353
+ )
354
+
355
+ state_dict = unflatten_state_dict(state_dict, metadata.planner_data)
356
+
357
+ return state_dict