assassinlike commited on
Commit
e092176
·
verified ·
1 Parent(s): fba273d

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/_sharded_tensor/__pycache__/__init__.cpython-310.pyc +0 -0
  2. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/__init__.cpython-310.pyc +0 -0
  3. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/common_utils.cpython-310.pyc +0 -0
  4. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/fake_collectives.cpython-310.pyc +0 -0
  5. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/fsdp2_mem_tracker.cpython-310.pyc +0 -0
  6. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/ilp_utils.cpython-310.pyc +0 -0
  7. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/mem_tracker.cpython-310.pyc +0 -0
  8. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/memory_tracker.cpython-310.pyc +0 -0
  9. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/mod_tracker.cpython-310.pyc +0 -0
  10. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/sac_estimator.cpython-310.pyc +0 -0
  11. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/sac_ilp.cpython-310.pyc +0 -0
  12. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/launcher/__pycache__/__init__.cpython-310.pyc +0 -0
  13. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/launcher/__pycache__/api.cpython-310.pyc +0 -0
  14. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/__pycache__/__init__.cpython-310.pyc +0 -0
  15. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/__pycache__/functional.cpython-310.pyc +0 -0
  16. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/api/__init__.py +0 -0
  17. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/api/__pycache__/__init__.cpython-310.pyc +0 -0
  18. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/api/__pycache__/remote_module.cpython-310.pyc +0 -0
  19. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/api/remote_module.py +754 -0
  20. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/__init__.py +0 -0
  21. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/__pycache__/__init__.cpython-310.pyc +0 -0
  22. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/__pycache__/instantiator.cpython-310.pyc +0 -0
  23. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/instantiator.py +156 -0
  24. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/templates/__init__.py +0 -0
  25. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/templates/__pycache__/__init__.cpython-310.pyc +0 -0
  26. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/templates/__pycache__/remote_module_template.cpython-310.pyc +0 -0
  27. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/templates/remote_module_template.py +108 -0
  28. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/__init__.cpython-310.pyc +0 -0
  29. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/_deprecation_warning.cpython-310.pyc +0 -0
  30. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/apply_optimizer_in_backward.cpython-310.pyc +0 -0
  31. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_adadelta.cpython-310.pyc +0 -0
  32. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_adagrad.cpython-310.pyc +0 -0
  33. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_adam.cpython-310.pyc +0 -0
  34. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_adamax.cpython-310.pyc +0 -0
  35. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_adamw.cpython-310.pyc +0 -0
  36. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_rmsprop.cpython-310.pyc +0 -0
  37. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_rprop.cpython-310.pyc +0 -0
  38. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_sgd.cpython-310.pyc +0 -0
  39. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/named_optimizer.cpython-310.pyc +0 -0
  40. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/optimizer.cpython-310.pyc +0 -0
  41. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/post_localSGD_optimizer.cpython-310.pyc +0 -0
  42. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/utils.cpython-310.pyc +0 -0
  43. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/zero_redundancy_optimizer.cpython-310.pyc +0 -0
  44. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/__init__.cpython-310.pyc +0 -0
  45. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/_utils.cpython-310.pyc +0 -0
  46. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/api.cpython-310.pyc +0 -0
  47. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/backend_registry.cpython-310.pyc +0 -0
  48. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/constants.cpython-310.pyc +0 -0
  49. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/functions.cpython-310.pyc +0 -0
  50. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/internal.cpython-310.pyc +0 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_sharded_tensor/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (692 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (596 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/common_utils.cpython-310.pyc ADDED
Binary file (1.34 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/fake_collectives.cpython-310.pyc ADDED
Binary file (6.98 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/fsdp2_mem_tracker.cpython-310.pyc ADDED
Binary file (16.7 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/ilp_utils.cpython-310.pyc ADDED
Binary file (7.74 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/mem_tracker.cpython-310.pyc ADDED
Binary file (32.4 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/memory_tracker.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/mod_tracker.cpython-310.pyc ADDED
Binary file (9.46 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/sac_estimator.cpython-310.pyc ADDED
Binary file (31.3 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/sac_ilp.cpython-310.pyc ADDED
Binary file (7.11 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/launcher/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (315 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/launcher/__pycache__/api.cpython-310.pyc ADDED
Binary file (9.63 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (349 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/__pycache__/functional.cpython-310.pyc ADDED
Binary file (15 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/api/__init__.py ADDED
File without changes
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/api/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (198 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/api/__pycache__/remote_module.cpython-310.pyc ADDED
Binary file (27.8 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/api/remote_module.py ADDED
@@ -0,0 +1,754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # mypy: allow-untyped-defs
3
+ import collections
4
+ import io
5
+ import sys
6
+ import types
7
+ from collections.abc import Iterator, Mapping
8
+ from typing import Any, Callable, Optional, TypeVar, Union
9
+ from typing_extensions import Self
10
+
11
+ import torch
12
+ import torch.distributed.rpc as rpc
13
+ from torch import device, dtype, nn, Tensor
14
+ from torch.distributed import _remote_device
15
+ from torch.distributed.nn.jit import instantiator
16
+ from torch.distributed.rpc.internal import _internal_rpc_pickler
17
+ from torch.nn import Module
18
+ from torch.nn.parameter import Parameter
19
+ from torch.utils.hooks import RemovableHandle
20
+
21
+
22
+ __all__ = ["RemoteModule"]
23
+
24
+ _grad_t = Union[tuple[Tensor, ...], Tensor]
25
+ # See https://mypy.readthedocs.io/en/latest/generics.html#generic-methods-and-generic-self for the use
26
+ # of `T` to annotate `self`. Many methods of `Module` return `self` and we want those return values to be
27
+ # the type of the subclass, not the looser type of `Module`.
28
+ T = TypeVar("T", bound="Module")
29
+
30
+ _NON_SCRIPTABLE_REMOTE_MODULE_MODULE = (
31
+ instantiator.instantiate_non_scriptable_remote_module_template()
32
+ )
33
+
34
+ _REMOTE_MODULE_PICKLED_ATTRIBUTES = (
35
+ "on",
36
+ "device",
37
+ "is_device_map_set",
38
+ "is_scriptable",
39
+ "generated_methods",
40
+ "module_rref",
41
+ )
42
+
43
+ _SerializedRemoteModule = collections.namedtuple( # type: ignore[misc]
44
+ "_SerializedRemoteModule",
45
+ _REMOTE_MODULE_PICKLED_ATTRIBUTES,
46
+ )
47
+
48
+ # These attributes are mostly from RemoteModule's parent class and are intentionally not pickled.
49
+ # A new attribute of RemoteModule should be either in _REMOTE_MODULE_PICKLED_ATTRIBUTES
50
+ # or _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING.
51
+ # Otherwise, it will not be pickled.
52
+ _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING = (
53
+ "training",
54
+ "_parameters",
55
+ "_buffers",
56
+ "_non_persistent_buffers_set",
57
+ "_backward_hooks",
58
+ "_backward_pre_hooks",
59
+ "_is_full_backward_hook",
60
+ "_forward_hooks",
61
+ "_forward_hooks_with_kwargs",
62
+ "_forward_hooks_always_called",
63
+ "_forward_pre_hooks",
64
+ "_forward_pre_hooks_with_kwargs",
65
+ "_state_dict_hooks",
66
+ "_state_dict_pre_hooks",
67
+ "_load_state_dict_pre_hooks",
68
+ "_load_state_dict_post_hooks",
69
+ "_state_dict_pre_hooks",
70
+ "_modules",
71
+ # The two attributes below are generated methods, not available at pickling time.
72
+ "forward_async",
73
+ "forward",
74
+ )
75
+
76
+
77
+ # RPC handler.
78
+ def _instantiate_template(module_interface_cls, enable_moving_cpu_tensors_to_cuda):
79
+ instantiator.instantiate_scriptable_remote_module_template(
80
+ module_interface_cls, enable_moving_cpu_tensors_to_cuda
81
+ )
82
+
83
+
84
+ def _create_module(module_cls, args, kwargs, device):
85
+ module = module_cls(*args, **kwargs)
86
+ if not isinstance(module, nn.Module):
87
+ raise ValueError(
88
+ "Expect `module_cls(*args, **kwargs)` returns an instance of <class nn.Module>, "
89
+ f"but it returns an instance of {type(module)}."
90
+ )
91
+ module.to(device)
92
+ return module
93
+
94
+
95
+ def _create_module_with_interface(
96
+ module_cls, args, kwargs, device, module_interface_cls
97
+ ):
98
+ module = _create_module(module_cls, args, kwargs, device)
99
+ if module_interface_cls is not None:
100
+ module = torch.jit.script(module)
101
+ return rpc.RRef(module, module_interface_cls)
102
+
103
+
104
+ def _param_rrefs(module_rref, recurse) -> list[rpc.RRef[Parameter]]:
105
+ ret: list[rpc.RRef[Parameter]] = [
106
+ rpc.RRef(param) for param in module_rref.local_value().parameters(recurse)
107
+ ]
108
+ return ret
109
+
110
+
111
+ def _raise_not_supported(name: str) -> None:
112
+ raise ValueError(f"Method ``{name}`` not supported for RemoteModule")
113
+
114
+
115
+ class _RemoteModule(nn.Module):
116
+ def __new__(cls, *args, **kwargs):
117
+ # Use __new__ for logging purposes.
118
+ torch._C._log_api_usage_once("torch.distributed.nn.api.remote_module")
119
+ return super().__new__(cls)
120
+
121
+ def __init__(
122
+ self,
123
+ remote_device: str,
124
+ module_cls: type[nn.Module],
125
+ args: Optional[tuple] = None,
126
+ kwargs: Optional[dict[str, Any]] = None,
127
+ _module_interface_cls: Any = None,
128
+ ):
129
+ """
130
+ RemoteModule instance can only be created after RPC initialization.
131
+
132
+ It creates a user-specified module on a specified remote node.
133
+ It behaves like a regular ``nn.Module`` except that the ``forward`` method is
134
+ executed on the remote node.
135
+ It takes care of autograd recording to ensure the backward pass propagates
136
+ gradients back to the corresponding remote module.
137
+ It can be shared across processors using `RPC framework <https://pytorch.org/docs/stable/rpc.html>`__,
138
+ without incurring any overheads of copying the actual module,
139
+ which is equivalent to an :class:`~torch.distributed.rpc.RRef`
140
+ pointing to the remote module.
141
+
142
+ The arguments of ``forward_async`` and ``forward`` are the same as
143
+ the ``forward`` method of the module returned by the ``module_cls``.
144
+
145
+ Apart from ``forward_async`` and ``forward``, no other methods are supported from nn.Module for now.
146
+
147
+ Particularly, to create a hybrid model, typically the local modules should be
148
+ created outside of remote modules, rather than as submodules of any remote module (by calling ``add_module``).
149
+ Hybrid Example:
150
+ >>> class HybridModel(nn.Module):
151
+ >>> def __init__(self) -> None:
152
+ >>> nn.Module.__init__(self)
153
+ >>> self.remote_embedding = RemoteModule(...)
154
+ >>> self.local_linear = nn.Linear(...)
155
+
156
+ For example, if ``module_cls`` returns an instance of ``nn.Linear``,
157
+ that has ``forward`` method signature, ``def forward(input: Tensor) -> Tensor:``,
158
+ the generated ``RemoteModule`` will have 2 methods in signature of
159
+ ``def forward(input: Tensor) -> Tensor:`` and
160
+ ``def forward_async(input: Tensor) -> Future[Tensor]:``.
161
+
162
+ .. note::
163
+ If the remote module is placed on a cuda device,
164
+ any input CPU tensors will be automatically moved to the same cuda device,
165
+ and GPU tensors are returned over the wire according to the device map of the remote worker on TensorPipe RPC backend.
166
+
167
+ Args:
168
+ remote_device (str): Device on the destination worker where we'd like to place this module.
169
+ The device can be a local device or a remote device specified by one of the following remote
170
+ formats:
171
+
172
+ 1. "rank:<rank>/<device>" (ex: "rank:0/cuda:0").
173
+ 2. "<worker_name>/<device>" (ex: "trainer0/cuda:0").
174
+
175
+ In addition, the device field can be optional and the default value is "cpu".
176
+ module_cls (nn.Module): For example,
177
+ >>> class MyModule(nn.Module):
178
+ >>> def forward(input):
179
+ >>> return input + 1
180
+ >>>
181
+ >>> module_cls = MyModule
182
+ args (Sequence, optional): args to be passed to ``module_cls``.
183
+ kwargs (Dict, optional): kwargs to be passed to ``module_cls``.
184
+ _module_interface_cls (type, optional): The TorchScript interface type for the module
185
+ to be created. The type object should be decorated by @torch.jit.interface.
186
+ If not provided, the generated RemoteModule is not torchscript-able.
187
+ Warning, this is an experimental API and susceptible to frequent changes.
188
+
189
+ Returns:
190
+ A remote module instance which wraps the :class:`~nn.Module` created by the
191
+ user-provided ``module_cls``, it has a blocking ``forward`` method and an
192
+ asynchronous ``forward_async`` method that returns a future of the ``forward`` call
193
+ on the user-provided module on the remote side.
194
+
195
+ Example::
196
+ Run the following code in two different processes:
197
+
198
+ >>> # xdoctest: +SKIP("distributed")
199
+ >>> # On worker 0:
200
+ >>> import torch
201
+ >>> import torch.distributed.rpc as rpc
202
+ >>> from torch import nn, Tensor
203
+ >>> from torch.distributed.nn.api.remote_module import RemoteModule
204
+ >>>
205
+ >>> rpc.init_rpc("worker0", rank=0, world_size=2)
206
+ >>> remote_linear_module = RemoteModule(
207
+ >>> "worker1/cpu", nn.Linear, args=(20, 30),
208
+ >>> )
209
+ >>> input = torch.randn(128, 20)
210
+ >>> ret_fut = remote_linear_module.forward_async(input)
211
+ >>> ret = ret_fut.wait()
212
+ >>> rpc.shutdown()
213
+
214
+ >>> # On worker 1:
215
+ >>> import torch
216
+ >>> import torch.distributed.rpc as rpc
217
+ >>>
218
+ >>> rpc.init_rpc("worker1", rank=1, world_size=2)
219
+ >>> rpc.shutdown()
220
+ """
221
+ super().__init__()
222
+
223
+ enable_moving_cpu_tensors_to_cuda = self._prepare_init(remote_device)
224
+
225
+ # Default arguments preparation.
226
+ args = args if args is not None else ()
227
+ kwargs = kwargs if kwargs is not None else {}
228
+
229
+ if _module_interface_cls is not None:
230
+ # Users reply on this field to know if this generated RemoteModule is TorchScript-able.
231
+ self.is_scriptable = True
232
+
233
+ # Instantiate template on remote side.
234
+ fut = rpc.rpc_async(
235
+ self.on,
236
+ _instantiate_template,
237
+ (_module_interface_cls, enable_moving_cpu_tensors_to_cuda),
238
+ )
239
+
240
+ self._init_template(
241
+ _module_interface_cls, enable_moving_cpu_tensors_to_cuda
242
+ )
243
+
244
+ # Instantiate template on remote side.
245
+ fut = rpc.rpc_async(
246
+ self.on,
247
+ _instantiate_template,
248
+ (_module_interface_cls, enable_moving_cpu_tensors_to_cuda),
249
+ )
250
+
251
+ # Create the module on the remote side.
252
+ fut.wait() # Ensure remote_module_cls is available on remote side.
253
+
254
+ # TODO: We need to change this to rpc.remote, and make it async (see the else branch below).
255
+ # For that we need to be able to apply _module_interface_cls to the RRef returned by rpc.remote
256
+ # See https://github.com/pytorch/pytorch/issues/58098 for more context.
257
+ self.module_rref = rpc.rpc_sync(
258
+ self.on,
259
+ _create_module_with_interface,
260
+ (module_cls, args, kwargs, self.device, _module_interface_cls),
261
+ )
262
+ else:
263
+ self.is_scriptable = False
264
+ self.generated_methods = (
265
+ _NON_SCRIPTABLE_REMOTE_MODULE_MODULE._generated_methods
266
+ )
267
+ # Create the module on the remote side.
268
+ self.module_rref = rpc.remote(
269
+ self.on,
270
+ _create_module,
271
+ (module_cls, args, kwargs, self.device),
272
+ )
273
+
274
+ self._install_generated_methods()
275
+ self._check_attribute_picklability()
276
+
277
+ def remote_parameters(self, recurse: bool = True) -> list[rpc.RRef[Parameter]]:
278
+ """
279
+ Return a list of :class:`~torch.distributed.rpc.RRef` pointing to the remote module's parameters.
280
+
281
+ This can typically be used in conjunction
282
+ with :class:`~torch.distributed.optim.DistributedOptimizer`.
283
+
284
+ Args:
285
+ recurse (bool): if True, then returns parameters of the remote
286
+ module and all submodules of the remote module. Otherwise,
287
+ returns only parameters that are direct members of the
288
+ remote module.
289
+
290
+ Returns:
291
+ A list of :class:`~torch.distributed.rpc.RRef` (``List[RRef[nn.Parameter]]``)
292
+ to remote module's parameters.
293
+ """
294
+ return rpc.rpc_sync(self.on, _param_rrefs, args=(self.module_rref, recurse))
295
+
296
+ def get_module_rref(self) -> rpc.RRef[nn.Module]:
297
+ """Return an :class:`~torch.distributed.rpc.RRef` (``RRef[nn.Module]``) pointing to the remote module."""
298
+ return self.module_rref
299
+
300
+ @torch.jit.export
301
+ def __getstate__(self):
302
+ raise RuntimeError(
303
+ "Cannot pickle RemoteModule in python pickler. RemoteModule can only be pickled when using RPC"
304
+ )
305
+
306
+ @torch.jit.export
307
+ def __setstate__(self, state):
308
+ raise RuntimeError(
309
+ "Cannot unpickle RemoteModule in python pickler. RemoteModule can only be unpickled when using RPC"
310
+ )
311
+
312
+ def register_buffer(
313
+ self, name: str, tensor: Optional[Tensor], persistent: bool = True
314
+ ) -> None:
315
+ _raise_not_supported(self.register_buffer.__name__)
316
+
317
+ def register_parameter(self, name: str, param: Optional[Parameter]) -> None:
318
+ _raise_not_supported(self.register_parameter.__name__)
319
+
320
+ def add_module(self, name: str, module: Optional[Module]) -> None:
321
+ _raise_not_supported(self.add_module.__name__)
322
+
323
+ def apply(self, fn: Callable[[Module], None]) -> Self: # type: ignore[return]
324
+ _raise_not_supported(self.apply.__name__)
325
+
326
+ def cuda(self, device: Optional[Union[int, device]] = None) -> Self: # type: ignore[return]
327
+ _raise_not_supported(self.cuda.__name__)
328
+
329
+ def ipu(self, device: Optional[Union[int, device]] = None) -> Self: # type: ignore[return]
330
+ _raise_not_supported(self.ipu.__name__)
331
+
332
+ def xpu(self, device: Optional[Union[int, device]] = None) -> Self: # type: ignore[return]
333
+ _raise_not_supported(self.xpu.__name__)
334
+
335
+ def cpu(self) -> Self: # type: ignore[return]
336
+ _raise_not_supported(self.cpu.__name__)
337
+
338
+ def type(self, dst_type: Union[dtype, str]) -> Self: # type: ignore[return]
339
+ _raise_not_supported(self.type.__name__)
340
+
341
+ def float(self) -> Self: # type: ignore[return]
342
+ _raise_not_supported(self.float.__name__)
343
+
344
+ def double(self) -> Self: # type: ignore[return]
345
+ _raise_not_supported(self.double.__name__)
346
+
347
+ def half(self) -> Self: # type: ignore[return]
348
+ _raise_not_supported(self.half.__name__)
349
+
350
+ def bfloat16(self) -> Self: # type: ignore[return]
351
+ _raise_not_supported(self.bfloat16.__name__)
352
+
353
+ def to(self, *args, **kwargs) -> T: # type: ignore[misc, return, type-var]
354
+ _raise_not_supported(self.to.__name__)
355
+
356
+ def register_backward_hook( # type: ignore[return]
357
+ self, hook: Callable[[Module, _grad_t, _grad_t], Union[None, _grad_t]]
358
+ ) -> RemovableHandle:
359
+ _raise_not_supported(self.register_backward_hook.__name__)
360
+
361
+ def register_forward_pre_hook( # type: ignore[return]
362
+ self,
363
+ hook: Union[
364
+ Callable[[T, tuple[Any, ...]], Optional[Any]],
365
+ Callable[
366
+ [T, tuple[Any, ...], dict[str, Any]],
367
+ Optional[tuple[Any, dict[str, Any]]],
368
+ ],
369
+ ],
370
+ prepend: bool = False,
371
+ with_kwargs: bool = False,
372
+ ) -> RemovableHandle:
373
+ _raise_not_supported(self.register_forward_pre_hook.__name__)
374
+
375
+ def register_forward_hook( # type: ignore[return, override]
376
+ self,
377
+ hook: Union[
378
+ Callable[[T, tuple[Any, ...], Any], Optional[Any]],
379
+ Callable[[T, tuple[Any, ...], dict[str, Any], Any], Optional[Any]],
380
+ ],
381
+ prepend: bool = False,
382
+ with_kwargs: bool = False,
383
+ ) -> RemovableHandle:
384
+ _raise_not_supported(self.register_forward_hook.__name__)
385
+
386
+ def state_dict(self, *args, **kwargs):
387
+ _raise_not_supported(self.state_dict.__name__)
388
+
389
+ def load_state_dict(
390
+ self,
391
+ state_dict: Mapping[str, Any],
392
+ strict: bool = True,
393
+ assign: bool = False,
394
+ ):
395
+ _raise_not_supported(self.load_state_dict.__name__)
396
+
397
+ def parameters(self, recurse: bool = True) -> Iterator[Parameter]:
398
+ raise ValueError(
399
+ "Method ``parameters`` not supported for RemoteModule. Please use ``remote_parameters`` instead."
400
+ )
401
+
402
+ def named_parameters( # type: ignore[return]
403
+ self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
404
+ ) -> Iterator[tuple[str, Parameter]]:
405
+ _raise_not_supported(self.named_parameters.__name__)
406
+
407
+ def buffers(self, recurse: bool = True) -> Iterator[Tensor]: # type: ignore[return]
408
+ _raise_not_supported(self.buffers.__name__)
409
+
410
+ def named_buffers( # type: ignore[return]
411
+ self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True
412
+ ) -> Iterator[tuple[str, Tensor]]:
413
+ _raise_not_supported(self.named_buffers.__name__)
414
+
415
+ def children(self) -> Iterator[Module]: # type: ignore[return]
416
+ _raise_not_supported(self.children.__name__)
417
+
418
+ def named_children(self) -> Iterator[tuple[str, Module]]: # type: ignore[return]
419
+ _raise_not_supported(self.named_children.__name__)
420
+
421
+ def modules(self) -> Iterator[Module]: # type: ignore[return]
422
+ _raise_not_supported(self.modules.__name__)
423
+
424
+ def named_modules(
425
+ self,
426
+ memo: Optional[set[Module]] = None,
427
+ prefix: str = "",
428
+ remove_duplicate: bool = True,
429
+ ):
430
+ _raise_not_supported(self.named_modules.__name__)
431
+
432
+ def train(self, mode: bool = True) -> Self:
433
+ return self.module_rref.rpc_sync().train() # type: ignore[operator, union-attr]
434
+
435
+ def eval(self) -> Self:
436
+ return self.module_rref.rpc_sync().eval() # type: ignore[operator, union-attr]
437
+
438
+ def requires_grad_(self, requires_grad: bool = True) -> Self: # type: ignore[return]
439
+ _raise_not_supported(self.requires_grad_.__name__)
440
+
441
+ def zero_grad(self, set_to_none: bool = True) -> None:
442
+ _raise_not_supported(self.zero_grad.__name__)
443
+
444
+ def share_memory(self) -> Self: # type: ignore[return]
445
+ _raise_not_supported(self.share_memory.__name__)
446
+
447
+ def extra_repr(self) -> str: # type: ignore[return]
448
+ _raise_not_supported(self.extra_repr.__name__)
449
+
450
+ def _prepare_init(self, remote_device_str: str) -> bool:
451
+ """Prepare the initialization and returns whether to enable automatically moving CPU tensors to CUDA devices."""
452
+ # Sanity check.
453
+ assert rpc._is_current_rpc_agent_set(), "RemoteModule only works in RPC."
454
+
455
+ remote_device = _remote_device(remote_device_str)
456
+ self.on = (
457
+ remote_device.worker_name()
458
+ if remote_device.worker_name() is not None
459
+ else remote_device.rank()
460
+ )
461
+ self.device = str(remote_device.device())
462
+ agent = rpc._get_current_rpc_agent()
463
+ # If the device map of the remote worker is set,
464
+ # then enable moving any input CPU tensors to the same cuda device.
465
+ self.is_device_map_set = bool(
466
+ agent._get_device_map(agent.get_worker_info(self.on)) # type: ignore[arg-type]
467
+ )
468
+ # ``enable_moving_cpu_tensors_to_cuda`` is less strict than ``is_device_map_set``:
469
+ # If ``enable_moving_cpu_tensors_to_cuda`` is true, but the device map is not set,
470
+ # then any CPU tensors can still be moved to a cuda device to run forward,
471
+ # but the output must be moved back to CPU before being sent over the wire.
472
+ enable_moving_cpu_tensors_to_cuda = torch.device(self.device).type == "cuda"
473
+ return enable_moving_cpu_tensors_to_cuda
474
+
475
+ def _init_template(self, module_interface_cls, enable_moving_cpu_tensors_to_cuda):
476
+ """Instantiate template on local side."""
477
+ generated_module = instantiator.instantiate_scriptable_remote_module_template(
478
+ module_interface_cls, enable_moving_cpu_tensors_to_cuda
479
+ )
480
+ self.generated_methods = generated_module._generated_methods
481
+
482
+ def _check_attribute_picklability(self):
483
+ """Check if all the attribute has explicitly defined whether to be pickled (i.e., picklability)."""
484
+ for k in self.__dict__.keys():
485
+ if (
486
+ k not in _REMOTE_MODULE_PICKLED_ATTRIBUTES
487
+ and k not in _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING
488
+ ):
489
+ raise AttributeError(
490
+ f"Attribute {k} must be either in ``_REMOTE_MODULE_PICKLED_ATTRIBUTES`` or "
491
+ "``_REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING``."
492
+ )
493
+
494
+ def _install_generated_methods(self):
495
+ for method in self.generated_methods:
496
+ method_name = method.__name__
497
+ method = torch.jit.export(method)
498
+ setattr(self, method_name, types.MethodType(method, self))
499
+
500
+ @staticmethod
501
+ def init_from_module_rref(
502
+ remote_device: str,
503
+ module_rref: rpc.RRef[nn.Module],
504
+ _module_interface_cls: Any = None,
505
+ ):
506
+ """
507
+ Besides the constructor, a RemoteModule instance can also be initialized given a module RRef.
508
+
509
+ This alternate initialization method can be particularly useful if we want to create multiple
510
+ RemoteModule instances that share the same underlying module and reduce memory consumption.
511
+
512
+ Moreover, this also provides a workaround for passing script RemoteModule over RPC,
513
+ which is not supported. The recommended way is as follows:
514
+
515
+ 1. the sender creates a RemoteModule;
516
+ 2. the sender sends its ``module_rref`` over RPC;
517
+ 3. the receiver calls this method to initialize another RemoteModule using the same ``module_rref``.
518
+
519
+ Example::
520
+ Run the following code in two different processes:
521
+
522
+ >>> # xdoctest: +SKIP("distributed")
523
+ >>> # On worker 0:
524
+ >>> import torch
525
+ >>> import torch.distributed.rpc as rpc
526
+ >>> from torch import nn, Tensor
527
+ >>> from torch.distributed.nn.api.remote_module import RemoteModule
528
+ >>>
529
+ >>> rpc.init_rpc("worker0", rank=0, world_size=2)
530
+ >>> remote_module = RemoteModule(
531
+ >>> "worker1/cpu", nn.Linear, args=(20, 30),
532
+ >>> )
533
+ >>>
534
+ >>> remote_module1 = rpc.rpc_sync(
535
+ >>> "worker1/cpu",
536
+ >>> RemoteModule.init_from_module_rref,
537
+ >>> ("worker1/cpu", remote_module1.get_module_rref()),
538
+ >>> )
539
+ >>> rpc.shutdown()
540
+
541
+ >>> # On worker 1:
542
+ >>> import torch
543
+ >>> import torch.distributed.rpc as rpc
544
+ >>>
545
+ >>> rpc.init_rpc("worker1", rank=1, world_size=2)
546
+ >>> rpc.shutdown()
547
+
548
+ Args:
549
+ remote_device (str): Device on the destination worker where we'd like to place this module.
550
+ The device can be a local device or a remote device specified by one of the following remote
551
+ formats:
552
+
553
+ 1. "rank:<rank>/<device>" (ex: "rank:0/cuda:0").
554
+ 2. "<worker_name>/<device>" (ex: "trainer0/cuda:0").
555
+
556
+ In addition, the device field can be optional and the default value is "cpu".
557
+ module_rref (RRef[nn.Module]): The module reference shared by both the caller and
558
+ the created remote module.
559
+ _module_interface_cls (type, optional): The TorchScript interface type for the module
560
+ to be created. The type object should be decorated by @torch.jit.interface.
561
+ If not provided, the generated RemoteModule is not torchscript-able.
562
+ Warning, this is an experimental API and susceptible to frequent changes.
563
+
564
+ Returns:
565
+ A remote module instance which wraps the :class:`~nn.Module` created by the
566
+ user-provided ``module_rref``, it has a blocking ``forward`` method and an
567
+ asynchronous ``forward_async`` method that returns a future of the ``forward`` call
568
+ on the user-provided module on the remote side.
569
+ """
570
+ # NOTE: if a new attribute is added to this class, also need to add it
571
+ # to ``_REMOTE_MODULE_PICKLED_ATTRIBUTES`` for pickling/unpickling.
572
+
573
+ remote_module = object.__new__(RemoteModule)
574
+
575
+ enable_moving_cpu_tensors_to_cuda = remote_module._prepare_init(remote_device)
576
+
577
+ if _module_interface_cls is not None:
578
+ # Users reply on this field to know if this generated RemoteModule is TorchScript-able.
579
+ remote_module.is_scriptable = True
580
+
581
+ remote_module._init_template(
582
+ _module_interface_cls, enable_moving_cpu_tensors_to_cuda
583
+ )
584
+ else:
585
+ remote_module.is_scriptable = False
586
+ remote_module.generated_methods = (
587
+ _NON_SCRIPTABLE_REMOTE_MODULE_MODULE._generated_methods
588
+ )
589
+ remote_module.module_rref = module_rref
590
+
591
+ remote_module._install_generated_methods()
592
+ remote_module._check_attribute_picklability()
593
+
594
+ return remote_module
595
+
596
+
597
+ class RemoteModule(_RemoteModule):
598
+ """
599
+ A RemoteModule instance can only be created after RPC initialization.
600
+
601
+ It creates a user-specified module on a specified remote node.
602
+ It behaves like a regular ``nn.Module`` except that the ``forward`` method is
603
+ executed on the remote node.
604
+ It takes care of autograd recording to ensure the backward pass propagates
605
+ gradients back to the corresponding remote module.
606
+
607
+ It generates two methods ``forward_async`` and ``forward`` based on the
608
+ signature of the ``forward`` method of ``module_cls``. ``forward_async``
609
+ runs asynchronously and returns a Future. The arguments of ``forward_async``
610
+ and ``forward`` are the same as the ``forward`` method of the module
611
+ returned by the ``module_cls``.
612
+
613
+ For example, if ``module_cls`` returns an instance of ``nn.Linear``,
614
+ that has ``forward`` method signature: ``def forward(input: Tensor) -> Tensor:``,
615
+ the generated ``RemoteModule`` will have 2 methods with the signatures:
616
+
617
+ | ``def forward(input: Tensor) -> Tensor:``
618
+ | ``def forward_async(input: Tensor) -> Future[Tensor]:``
619
+
620
+ Args:
621
+ remote_device (str): Device on the destination worker where we'd like to place this module.
622
+ The format should be "<workername>/<device>", where the device field can be parsed as torch.device type.
623
+ E.g., "trainer0/cpu", "trainer0", "ps0/cuda:0".
624
+ In addition, the device field can be optional and the default value is "cpu".
625
+ module_cls (nn.Module): Class for the module to be created remotely. For example,
626
+
627
+ >>> class MyModule(nn.Module):
628
+ >>> def forward(input):
629
+ >>> return input + 1
630
+ >>>
631
+ >>> module_cls = MyModule
632
+
633
+ args (Sequence, optional): args to be passed to ``module_cls``.
634
+ kwargs (Dict, optional): kwargs to be passed to ``module_cls``.
635
+
636
+ Returns:
637
+ A remote module instance which wraps the :class:`~nn.Module` created by the
638
+ user-provided ``module_cls``, it has a blocking ``forward`` method and an
639
+ asynchronous ``forward_async`` method that returns a future of the ``forward`` call
640
+ on the user-provided module on the remote side.
641
+
642
+ Example::
643
+ Run the following code in two different processes:
644
+
645
+ >>> # xdoctest: +SKIP("distributed")
646
+ >>> # On worker 0:
647
+ >>> import torch
648
+ >>> import torch.distributed.rpc as rpc
649
+ >>> from torch import nn, Tensor
650
+ >>> from torch.distributed.nn.api.remote_module import RemoteModule
651
+ >>>
652
+ >>> rpc.init_rpc("worker0", rank=0, world_size=2)
653
+ >>> remote_linear_module = RemoteModule(
654
+ >>> "worker1/cpu", nn.Linear, args=(20, 30),
655
+ >>> )
656
+ >>> input = torch.randn(128, 20)
657
+ >>> ret_fut = remote_linear_module.forward_async(input)
658
+ >>> ret = ret_fut.wait()
659
+ >>> rpc.shutdown()
660
+
661
+ >>> # On worker 1:
662
+ >>> import torch
663
+ >>> import torch.distributed.rpc as rpc
664
+ >>>
665
+ >>> rpc.init_rpc("worker1", rank=1, world_size=2)
666
+ >>> rpc.shutdown()
667
+
668
+ Furthermore, a more practical example that is combined with
669
+ `DistributedDataParallel <https://pytorch.org/docs/stable/nn.html#torch.nn.parallel.DistributedDataParallel>`__ (DDP)
670
+ can be found in this `tutorial <https://pytorch.org/tutorials/advanced/rpc_ddp_tutorial.html>`__.
671
+ """
672
+
673
+ def __init__(
674
+ self,
675
+ remote_device: str,
676
+ module_cls: type[nn.Module],
677
+ args: Optional[tuple] = None,
678
+ kwargs: Optional[dict[str, Any]] = None,
679
+ ):
680
+ super().__init__(remote_device, module_cls, args, kwargs)
681
+
682
+
683
+ def _remote_module_receiver(
684
+ *remote_module_pickled_attrs,
685
+ ):
686
+ """Deserializes a RemoteModule."""
687
+ serialized_remote_module = _SerializedRemoteModule._make(
688
+ remote_module_pickled_attrs
689
+ )
690
+ m = object.__new__(RemoteModule)
691
+ m.__dict__.update(serialized_remote_module._asdict())
692
+
693
+ # Unpickling the attribute `module_rref` must invoke RRef's `_deserialize()` method.
694
+ m.module_rref = rpc.PyRRef._deserialize(m.module_rref)
695
+
696
+ # Install generated methods when unpickled.
697
+ for method in m.generated_methods:
698
+ method_name = method.__name__
699
+ method = torch.jit.export(method)
700
+ setattr(m, method_name, types.MethodType(method, m))
701
+
702
+ return m
703
+
704
+
705
+ def _remote_module_reducer(remote_module):
706
+ """Serialize a RemoteModule."""
707
+ pickled_attrs = {}
708
+ for k, v in remote_module.__dict__.items():
709
+ # Pickling the attribute `module_rref` must invoke RRef's `_serialize()` method.
710
+ if k == "module_rref":
711
+ pickled_attrs[k] = v._serialize()
712
+ elif k in _REMOTE_MODULE_PICKLED_ATTRIBUTES:
713
+ pickled_attrs[k] = v
714
+ # Check if unpickled attributes are all in _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING.
715
+ elif k not in _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING:
716
+ print(
717
+ f"The new attribute ``{k}`` of RemoteModule is ignored during RPC pickling. "
718
+ "To pickle this attribute, please add it to ``_REMOTE_MODULE_PICKLED_ATTRIBUTES``. "
719
+ "Otherwise, please explicitly add it to ``_REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING``.",
720
+ file=sys.stderr,
721
+ )
722
+
723
+ return (
724
+ _remote_module_receiver,
725
+ tuple(pickled_attrs.values()),
726
+ )
727
+
728
+
729
+ def _recursive_script_module_receiver(
730
+ recursive_script_module_serialized,
731
+ ):
732
+ """Deserializes a RecursiveScriptModule that does not contain a script RemoteModule."""
733
+ f = io.BytesIO(recursive_script_module_serialized)
734
+ m = torch.jit.load(f)
735
+ return m
736
+
737
+
738
+ def _recursive_script_module_reducer(recursive_script_module):
739
+ """Serialize a RecursiveScriptModule that does not contain a script RemoteModule, and raises an error otherwise."""
740
+ if hasattr(recursive_script_module._c, "module_rref"):
741
+ raise RuntimeError(
742
+ "Passing a script RemoteModule over RPC is not supported. Please create a RemoteModule in the sender, "
743
+ "send the `module_rref` to the receiver, and create a new instance on the receiver end by passing this `module_rref`."
744
+ )
745
+
746
+ f = io.BytesIO()
747
+ torch.jit.save(recursive_script_module, f)
748
+ return (_recursive_script_module_receiver, (f.getvalue(),))
749
+
750
+
751
+ _internal_rpc_pickler._register_reducer(RemoteModule, _remote_module_reducer)
752
+ _internal_rpc_pickler._register_reducer(
753
+ torch.jit.RecursiveScriptModule, _recursive_script_module_reducer
754
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/__init__.py ADDED
File without changes
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (198 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/__pycache__/instantiator.cpython-310.pyc ADDED
Binary file (3.89 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/instantiator.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # mypy: allow-untyped-defs
3
+ import atexit
4
+ import importlib
5
+ import logging
6
+ import os
7
+ import sys
8
+ import tempfile
9
+ from typing import Optional
10
+
11
+ import torch
12
+ from torch.distributed.nn.jit.templates.remote_module_template import (
13
+ get_remote_module_template,
14
+ )
15
+
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ _FILE_PREFIX = "_remote_module_"
21
+ _TEMP_DIR = tempfile.TemporaryDirectory()
22
+ INSTANTIATED_TEMPLATE_DIR_PATH = _TEMP_DIR.name
23
+ atexit.register(_TEMP_DIR.cleanup)
24
+ logger.info("Created a temporary directory at %s", INSTANTIATED_TEMPLATE_DIR_PATH)
25
+ sys.path.append(INSTANTIATED_TEMPLATE_DIR_PATH)
26
+
27
+
28
+ def get_arg_return_types_from_interface(module_interface):
29
+ assert getattr(module_interface, "__torch_script_interface__", False), (
30
+ "Expect a TorchScript class interface decorated by @torch.jit.interface."
31
+ )
32
+ qualified_name = torch._jit_internal._qualified_name(module_interface)
33
+ cu = torch.jit._state._python_cu
34
+ module_interface_c = cu.get_interface(qualified_name)
35
+ assert "forward" in module_interface_c.getMethodNames(), (
36
+ f"Expect forward in interface methods, while it has {module_interface_c.getMethodNames()}"
37
+ )
38
+ method_schema = module_interface_c.getMethod("forward")
39
+
40
+ arg_str_list = []
41
+ arg_type_str_list = []
42
+ assert method_schema is not None
43
+ for argument in method_schema.arguments:
44
+ arg_str_list.append(argument.name)
45
+
46
+ if argument.has_default_value():
47
+ default_value_str = f" = {argument.default_value}"
48
+ else:
49
+ default_value_str = ""
50
+ arg_type_str = f"{argument.name}: {argument.type}{default_value_str}"
51
+ arg_type_str_list.append(arg_type_str)
52
+
53
+ arg_str_list = arg_str_list[1:] # Remove "self".
54
+ args_str = ", ".join(arg_str_list)
55
+
56
+ arg_type_str_list = arg_type_str_list[1:] # Remove "self".
57
+ arg_types_str = ", ".join(arg_type_str_list)
58
+
59
+ assert len(method_schema.returns) == 1
60
+ argument = method_schema.returns[0]
61
+ return_type_str = str(argument.type)
62
+
63
+ return args_str, arg_types_str, return_type_str
64
+
65
+
66
+ def _write(out_path, text):
67
+ old_text: Optional[str]
68
+ try:
69
+ with open(out_path) as f:
70
+ old_text = f.read()
71
+ except OSError:
72
+ old_text = None
73
+ if old_text != text:
74
+ with open(out_path, "w") as f:
75
+ logger.info("Writing %s", out_path)
76
+ f.write(text)
77
+ else:
78
+ logger.info("Skipped writing %s", out_path)
79
+
80
+
81
+ def _do_instantiate_remote_module_template(
82
+ generated_module_name, str_dict, enable_moving_cpu_tensors_to_cuda
83
+ ):
84
+ generated_code_text = get_remote_module_template(
85
+ enable_moving_cpu_tensors_to_cuda
86
+ ).format(**str_dict)
87
+ out_path = os.path.join(
88
+ INSTANTIATED_TEMPLATE_DIR_PATH, f"{generated_module_name}.py"
89
+ )
90
+ _write(out_path, generated_code_text)
91
+
92
+ # From importlib doc,
93
+ # > If you are dynamically importing a module that was created since
94
+ # the interpreter began execution (e.g., created a Python source file),
95
+ # you may need to call invalidate_caches() in order for the new module
96
+ # to be noticed by the import system.
97
+ importlib.invalidate_caches()
98
+ generated_module = importlib.import_module(f"{generated_module_name}")
99
+ return generated_module
100
+
101
+
102
+ def instantiate_scriptable_remote_module_template(
103
+ module_interface_cls, enable_moving_cpu_tensors_to_cuda=True
104
+ ):
105
+ if not getattr(module_interface_cls, "__torch_script_interface__", False):
106
+ raise ValueError(
107
+ f"module_interface_cls {module_interface_cls} must be a type object decorated by "
108
+ "@torch.jit.interface"
109
+ )
110
+
111
+ # Generate the template instance name.
112
+ module_interface_cls_name = torch._jit_internal._qualified_name(
113
+ module_interface_cls
114
+ ).replace(".", "_")
115
+ generated_module_name = f"{_FILE_PREFIX}{module_interface_cls_name}"
116
+
117
+ # Generate type annotation strs.
118
+ assign_module_interface_cls_str = (
119
+ f"from {module_interface_cls.__module__} import "
120
+ f"{module_interface_cls.__name__} as module_interface_cls"
121
+ )
122
+ args_str, arg_types_str, return_type_str = get_arg_return_types_from_interface(
123
+ module_interface_cls
124
+ )
125
+ kwargs_str = ""
126
+ arrow_and_return_type_str = f" -> {return_type_str}"
127
+ arrow_and_future_return_type_str = f" -> Future[{return_type_str}]"
128
+
129
+ str_dict = dict(
130
+ assign_module_interface_cls=assign_module_interface_cls_str,
131
+ arg_types=arg_types_str,
132
+ arrow_and_return_type=arrow_and_return_type_str,
133
+ arrow_and_future_return_type=arrow_and_future_return_type_str,
134
+ args=args_str,
135
+ kwargs=kwargs_str,
136
+ jit_script_decorator="@torch.jit.script",
137
+ )
138
+ return _do_instantiate_remote_module_template(
139
+ generated_module_name, str_dict, enable_moving_cpu_tensors_to_cuda
140
+ )
141
+
142
+
143
+ def instantiate_non_scriptable_remote_module_template():
144
+ generated_module_name = f"{_FILE_PREFIX}non_scriptable"
145
+ str_dict = dict(
146
+ assign_module_interface_cls="module_interface_cls = None",
147
+ args="*args",
148
+ kwargs="**kwargs",
149
+ arg_types="*args, **kwargs",
150
+ arrow_and_return_type="",
151
+ arrow_and_future_return_type="",
152
+ jit_script_decorator="",
153
+ )
154
+ # For a non-scriptable template, always enable moving CPU tensors to a cuda device,
155
+ # because there is no syntax limitation on the extra handling caused by the script.
156
+ return _do_instantiate_remote_module_template(generated_module_name, str_dict, True)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/templates/__init__.py ADDED
File without changes
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/templates/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (208 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/templates/__pycache__/remote_module_template.cpython-310.pyc ADDED
Binary file (3.24 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/nn/jit/templates/remote_module_template.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # mypy: allow-untyped-defs
3
+
4
+
5
+ def get_remote_module_template(enable_moving_cpu_tensors_to_cuda: bool):
6
+ return _TEMPLATE_PREFIX + (
7
+ _REMOTE_FORWARD_TEMPLATE_ENABLE_MOVING_CPU_TENSORS_TO_CUDA
8
+ if enable_moving_cpu_tensors_to_cuda
9
+ else _REMOTE_FORWARD_TEMPLATE
10
+ )
11
+
12
+
13
+ _TEMPLATE_PREFIX = """from typing import *
14
+
15
+ import torch
16
+ import torch.distributed.rpc as rpc
17
+ from torch import Tensor
18
+ from torch._jit_internal import Future
19
+ from torch.distributed.rpc import RRef
20
+ from typing import Tuple # pyre-ignore: unused import
21
+
22
+
23
+ {assign_module_interface_cls}
24
+
25
+
26
+ def forward_async(self, {arg_types}){arrow_and_future_return_type}:
27
+ args = (self.module_rref, self.device, self.is_device_map_set, {args})
28
+ kwargs = {{{kwargs}}}
29
+ return rpc.rpc_async(
30
+ self.module_rref.owner(),
31
+ _remote_forward,
32
+ args,
33
+ kwargs,
34
+ )
35
+
36
+
37
+ def forward(self, {arg_types}){arrow_and_return_type}:
38
+ args = (self.module_rref, self.device, self.is_device_map_set, {args})
39
+ kwargs = {{{kwargs}}}
40
+ ret_fut = rpc.rpc_async(
41
+ self.module_rref.owner(),
42
+ _remote_forward,
43
+ args,
44
+ kwargs,
45
+ )
46
+ return ret_fut.wait()
47
+
48
+
49
+ _generated_methods = [
50
+ forward_async,
51
+ forward,
52
+ ]
53
+
54
+
55
+ {jit_script_decorator}
56
+ """
57
+
58
+ # This template may cause typing error (the mismatch between ``Tuple[()]`` and ``Tuple[Any]``)
59
+ # even if the code is only used for instantiation but not execution.
60
+ # Therefore, only include handling moving CPU tensors to a cuda device if necessary.
61
+ # TODO: Merge these two templates together in the future once TorchScript syntax is improved.
62
+ _REMOTE_FORWARD_TEMPLATE_ENABLE_MOVING_CPU_TENSORS_TO_CUDA = """
63
+ def _remote_forward(
64
+ module_rref: RRef[module_interface_cls], device: str, is_device_map_set: bool, {arg_types}){arrow_and_return_type}:
65
+ module = module_rref.local_value()
66
+ device = torch.device(device)
67
+
68
+ if device.type != "cuda":
69
+ return module.forward({args}, {kwargs})
70
+
71
+ # If the module is on a cuda device,
72
+ # move any CPU tensor in args or kwargs to the same cuda device.
73
+ # Since torch script does not support generator expression,
74
+ # have to use concatenation instead of
75
+ # ``tuple(i.to(device) if isinstance(i, Tensor) else i for i in *args)``.
76
+ args = ({args},)
77
+ out_args: Tuple[()] = ()
78
+ for arg in args:
79
+ arg = (arg.to(device),) if isinstance(arg, Tensor) else (arg,)
80
+ out_args = out_args + arg
81
+
82
+ kwargs = {{{kwargs}}}
83
+ for k, v in kwargs.items():
84
+ if isinstance(v, Tensor):
85
+ kwargs[k] = kwargs[k].to(device)
86
+
87
+ if is_device_map_set:
88
+ return module.forward(*out_args, {kwargs})
89
+
90
+ # If the device map is empty, then only CPU tensors are allowed to send over wire,
91
+ # so have to move any GPU tensor to CPU in the output.
92
+ # Since torch script does not support generator expression,
93
+ # have to use concatenation instead of
94
+ # ``tuple(i.cpu() if isinstance(i, Tensor) else i for i in module.forward(*out_args, {kwargs}))``.
95
+ ret: Tuple[()] = ()
96
+ for i in module.forward(*out_args, {kwargs}):
97
+ i = (i.cpu(),) if isinstance(i, Tensor) else (i,)
98
+ ret = ret + i
99
+ return ret
100
+ """
101
+
102
+ _REMOTE_FORWARD_TEMPLATE = """
103
+ def _remote_forward(
104
+ module_rref: RRef[module_interface_cls], device: str, is_device_map_set: bool, {arg_types}){arrow_and_return_type}:
105
+ module = module_rref.local_value()
106
+
107
+ return module.forward({args}, {kwargs})
108
+ """
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.59 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/_deprecation_warning.cpython-310.pyc ADDED
Binary file (788 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/apply_optimizer_in_backward.cpython-310.pyc ADDED
Binary file (4.19 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_adadelta.cpython-310.pyc ADDED
Binary file (2.62 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_adagrad.cpython-310.pyc ADDED
Binary file (2.82 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_adam.cpython-310.pyc ADDED
Binary file (4.14 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_adamax.cpython-310.pyc ADDED
Binary file (2.98 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_adamw.cpython-310.pyc ADDED
Binary file (4.04 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_rmsprop.cpython-310.pyc ADDED
Binary file (2.88 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_rprop.cpython-310.pyc ADDED
Binary file (2.62 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/functional_sgd.cpython-310.pyc ADDED
Binary file (3.38 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/named_optimizer.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/optimizer.cpython-310.pyc ADDED
Binary file (8.94 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/post_localSGD_optimizer.cpython-310.pyc ADDED
Binary file (5.23 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/utils.cpython-310.pyc ADDED
Binary file (2.15 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/optim/__pycache__/zero_redundancy_optimizer.cpython-310.pyc ADDED
Binary file (54 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (6.75 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/_utils.cpython-310.pyc ADDED
Binary file (1.22 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/api.cpython-310.pyc ADDED
Binary file (28.4 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/backend_registry.cpython-310.pyc ADDED
Binary file (9.89 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/constants.cpython-310.pyc ADDED
Binary file (775 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/functions.cpython-310.pyc ADDED
Binary file (7.48 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torch/distributed/rpc/__pycache__/internal.cpython-310.pyc ADDED
Binary file (8.37 kB). View file