torchrec 0.2.0.dev0__37-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. examples/__init__.py +0 -0
  2. examples/datasets/__init__.py +8 -0
  3. examples/datasets/criteo_dataframes.py +101 -0
  4. examples/ray/__init__.py +0 -0
  5. examples/ray/compute_world_size.py +51 -0
  6. examples/ray/train_torchrec.py +133 -0
  7. examples/retrieval/__init__.py +6 -0
  8. examples/retrieval/data/__init__.py +6 -0
  9. examples/retrieval/data/dataloader.py +44 -0
  10. examples/retrieval/knn_index.py +67 -0
  11. examples/retrieval/modules/__init__.py +6 -0
  12. examples/retrieval/modules/two_tower.py +229 -0
  13. examples/retrieval/two_tower_retrieval.py +192 -0
  14. examples/retrieval/two_tower_train.py +253 -0
  15. examples/torcharrow/__init__.py +8 -0
  16. examples/torcharrow/dataloader.py +116 -0
  17. examples/torcharrow/run.py +126 -0
  18. fbgemm_gpu/__init__.py +16 -0
  19. fbgemm_gpu/batched_unary_embeddings_ops.py +82 -0
  20. fbgemm_gpu/enums.py +21 -0
  21. fbgemm_gpu/fbgemm_gpu_py.so +0 -0
  22. fbgemm_gpu/permute_pooled_embedding_modules.py +73 -0
  23. fbgemm_gpu/permute_pooled_embedding_modules_split.py +76 -0
  24. fbgemm_gpu/split_embedding_codegen_lookup_invokers/__init__.py +19 -0
  25. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adagrad.py +120 -0
  26. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adam.py +149 -0
  27. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad.py +128 -0
  28. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_counter.py +134 -0
  29. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_weight_decay.py +128 -0
  30. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_sgd.py +105 -0
  31. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_args.py +54 -0
  32. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lamb.py +149 -0
  33. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lars_sgd.py +128 -0
  34. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_adam.py +149 -0
  35. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_lamb.py +149 -0
  36. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad.py +128 -0
  37. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_counter.py +134 -0
  38. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_weight_decay.py +128 -0
  39. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_weighted_adagrad.py +130 -0
  40. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_sgd.py +105 -0
  41. fbgemm_gpu/split_embedding_configs.py +182 -0
  42. fbgemm_gpu/split_embedding_inference_converter.py +208 -0
  43. fbgemm_gpu/split_table_batched_embeddings_ops.py +2503 -0
  44. fbgemm_gpu/uvm.py +35 -0
  45. torchrec/__init__.py +27 -0
  46. torchrec/datasets/__init__.py +31 -0
  47. torchrec/datasets/criteo.py +831 -0
  48. torchrec/datasets/movielens.py +140 -0
  49. torchrec/datasets/random.py +188 -0
  50. torchrec/datasets/scripts/__init__.py +0 -0
  51. torchrec/datasets/scripts/contiguous_preproc_criteo.py +75 -0
  52. torchrec/datasets/scripts/npy_preproc_criteo.py +73 -0
  53. torchrec/datasets/test_utils/__init__.py +0 -0
  54. torchrec/datasets/test_utils/criteo_test_utils.py +139 -0
  55. torchrec/datasets/utils.py +341 -0
  56. torchrec/distributed/__init__.py +55 -0
  57. torchrec/distributed/batched_embedding_kernel.py +697 -0
  58. torchrec/distributed/collective_utils.py +71 -0
  59. torchrec/distributed/comm.py +149 -0
  60. torchrec/distributed/comm_ops.py +930 -0
  61. torchrec/distributed/dist_data.py +949 -0
  62. torchrec/distributed/embedding.py +638 -0
  63. torchrec/distributed/embedding_kernel.py +326 -0
  64. torchrec/distributed/embedding_lookup.py +760 -0
  65. torchrec/distributed/embedding_sharding.py +660 -0
  66. torchrec/distributed/embedding_tower_sharding.py +992 -0
  67. torchrec/distributed/embedding_types.py +369 -0
  68. torchrec/distributed/embeddingbag.py +731 -0
  69. torchrec/distributed/fused_embeddingbag.py +148 -0
  70. torchrec/distributed/grouped_position_weighted.py +103 -0
  71. torchrec/distributed/model_parallel.py +555 -0
  72. torchrec/distributed/planner/__init__.py +24 -0
  73. torchrec/distributed/planner/constants.py +77 -0
  74. torchrec/distributed/planner/enumerators.py +353 -0
  75. torchrec/distributed/planner/parallelized_planners.py +307 -0
  76. torchrec/distributed/planner/partitioners.py +280 -0
  77. torchrec/distributed/planner/perf_models.py +24 -0
  78. torchrec/distributed/planner/planners.py +290 -0
  79. torchrec/distributed/planner/proposers.py +270 -0
  80. torchrec/distributed/planner/shard_estimators.py +971 -0
  81. torchrec/distributed/planner/stats.py +477 -0
  82. torchrec/distributed/planner/storage_reservations.py +168 -0
  83. torchrec/distributed/planner/types.py +423 -0
  84. torchrec/distributed/planner/utils.py +30 -0
  85. torchrec/distributed/quant_embedding.py +307 -0
  86. torchrec/distributed/quant_embedding_kernel.py +295 -0
  87. torchrec/distributed/quant_embeddingbag.py +288 -0
  88. torchrec/distributed/sharding/__init__.py +0 -0
  89. torchrec/distributed/sharding/cw_sequence_sharding.py +71 -0
  90. torchrec/distributed/sharding/cw_sharding.py +242 -0
  91. torchrec/distributed/sharding/dp_sequence_sharding.py +87 -0
  92. torchrec/distributed/sharding/dp_sharding.py +217 -0
  93. torchrec/distributed/sharding/rw_sequence_sharding.py +130 -0
  94. torchrec/distributed/sharding/rw_sharding.py +393 -0
  95. torchrec/distributed/sharding/sequence_sharding.py +69 -0
  96. torchrec/distributed/sharding/tw_sequence_sharding.py +211 -0
  97. torchrec/distributed/sharding/tw_sharding.py +469 -0
  98. torchrec/distributed/sharding/twcw_sharding.py +32 -0
  99. torchrec/distributed/sharding/twrw_sharding.py +543 -0
  100. torchrec/distributed/sharding/vb_cw_sharding.py +91 -0
  101. torchrec/distributed/sharding/vb_rw_sharding.py +250 -0
  102. torchrec/distributed/sharding/vb_sharding.py +54 -0
  103. torchrec/distributed/sharding/vb_tw_sharding.py +148 -0
  104. torchrec/distributed/sharding/vb_twrw_sharding.py +388 -0
  105. torchrec/distributed/test_utils/__init__.py +0 -0
  106. torchrec/distributed/test_utils/multi_process.py +132 -0
  107. torchrec/distributed/test_utils/test_model.py +818 -0
  108. torchrec/distributed/test_utils/test_model_parallel.py +74 -0
  109. torchrec/distributed/test_utils/test_model_parallel_base.py +117 -0
  110. torchrec/distributed/test_utils/test_sharding.py +280 -0
  111. torchrec/distributed/train_pipeline.py +531 -0
  112. torchrec/distributed/types.py +594 -0
  113. torchrec/distributed/utils.py +186 -0
  114. torchrec/fused_planner.py +57 -0
  115. torchrec/fx/__init__.py +15 -0
  116. torchrec/fx/tracer.py +78 -0
  117. torchrec/inference/__init__.py +25 -0
  118. torchrec/inference/client.py +127 -0
  119. torchrec/inference/model_packager.py +102 -0
  120. torchrec/inference/modules.py +155 -0
  121. torchrec/inference/state_dict_transform.py +103 -0
  122. torchrec/metrics/__init__.py +0 -0
  123. torchrec/metrics/auc.py +159 -0
  124. torchrec/metrics/calibration.py +108 -0
  125. torchrec/metrics/ctr.py +104 -0
  126. torchrec/metrics/metric_module.py +358 -0
  127. torchrec/metrics/metrics_config.py +152 -0
  128. torchrec/metrics/metrics_namespace.py +114 -0
  129. torchrec/metrics/model_utils.py +85 -0
  130. torchrec/metrics/mse.py +134 -0
  131. torchrec/metrics/ne.py +164 -0
  132. torchrec/metrics/rec_metric.py +686 -0
  133. torchrec/metrics/throughput.py +174 -0
  134. torchrec/models/__init__.py +27 -0
  135. torchrec/models/deepfm.py +346 -0
  136. torchrec/models/dlrm.py +708 -0
  137. torchrec/modules/__init__.py +34 -0
  138. torchrec/modules/activation.py +55 -0
  139. torchrec/modules/crossnet.py +446 -0
  140. torchrec/modules/deepfm.py +213 -0
  141. torchrec/modules/embedding_configs.py +148 -0
  142. torchrec/modules/embedding_modules.py +381 -0
  143. torchrec/modules/embedding_tower.py +150 -0
  144. torchrec/modules/feature_processor.py +74 -0
  145. torchrec/modules/fused_embedding_modules.py +625 -0
  146. torchrec/modules/lazy_extension.py +258 -0
  147. torchrec/modules/mlp.py +172 -0
  148. torchrec/modules/utils.py +117 -0
  149. torchrec/optim/__init__.py +35 -0
  150. torchrec/optim/clipping.py +53 -0
  151. torchrec/optim/fused.py +42 -0
  152. torchrec/optim/keyed.py +399 -0
  153. torchrec/optim/rowwise_adagrad.py +222 -0
  154. torchrec/optim/test_utils/__init__.py +19 -0
  155. torchrec/optim/warmup.py +147 -0
  156. torchrec/quant/__init__.py +34 -0
  157. torchrec/quant/embedding_modules.py +545 -0
  158. torchrec/sparse/__init__.py +33 -0
  159. torchrec/sparse/jagged_tensor.py +1281 -0
  160. torchrec/sparse/test_utils/__init__.py +45 -0
  161. torchrec/streamable.py +46 -0
  162. torchrec/test_utils/__init__.py +111 -0
  163. torchrec-0.2.dev0.dist-info/LICENSE +29 -0
  164. torchrec-0.2.dev0.dist-info/METADATA +175 -0
  165. torchrec-0.2.dev0.dist-info/RECORD +167 -0
  166. torchrec-0.2.dev0.dist-info/WHEEL +5 -0
  167. torchrec-0.2.dev0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,258 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import functools
9
+ import inspect
10
+ from typing import Any, Callable
11
+
12
+ import torch
13
+ import torch.utils.hooks as hooks
14
+ from torch.nn.modules.lazy import _LazyProtocol, LazyModuleMixin
15
+ from torch.nn.modules.module import (
16
+ _global_backward_hooks,
17
+ _global_forward_hooks,
18
+ _global_forward_pre_hooks,
19
+ )
20
+
21
+
22
+ def _apply_functions_after_first_forward(
23
+ module: torch.nn.Module,
24
+ # pyre-ignore[2]
25
+ input: Any,
26
+ # pyre-ignore[2]
27
+ output: Any,
28
+ ) -> None:
29
+ _functions_to_lazy_apply = getattr(module, "_functions_to_lazy_apply", None)
30
+ if _functions_to_lazy_apply is not None:
31
+ # pyre-fixme[29]:
32
+ # `Union[BoundMethod[typing.Callable(torch.Tensor.__iter__)[[Named(self,
33
+ # torch.Tensor)], typing.Iterator[typing.Any]], torch.Tensor], torch.Tensor,
34
+ # torch.nn.modules.module.Module]` is not a function.
35
+ for fn in _functions_to_lazy_apply:
36
+ module.apply(fn)
37
+ delattr(module, "_functions_to_lazy_apply")
38
+ # pyre-ignore[16]
39
+ module._lazy_apply_hook.remove()
40
+ delattr(module, "_lazy_apply_hook")
41
+
42
+
43
+ def lazy_apply(
44
+ module: torch.nn.Module, fn: Callable[[torch.nn.Module], None]
45
+ ) -> torch.nn.Module:
46
+ """Attaches a function to a module, which will be applied recursively to every
47
+ submodule (as returned by `.children()`) of the module as well as the module itself
48
+ right after the first forward pass (i.e. after all submodules and parameters have
49
+ been initialized).
50
+
51
+ Typical use includes initializing the numerical value of the parameters of a lazy
52
+ module (i.e. modules inherited from `LazyModuleMixin`).
53
+
54
+ NOTE:
55
+ `lazy_apply()` can be used on both lazy and non-lazy modules.
56
+
57
+ Args:
58
+ module (torch.nn.Module): module to recursively apply `fn` on.
59
+ fn (Callable[[torch.nn.Module], None]): function to be attached to `module` and
60
+ later be applied to each submodule of `module` and the `module` itself.
61
+
62
+ Returns:
63
+ torch.nn.Module: `module` with `fn` attached.
64
+
65
+ Example::
66
+
67
+ @torch.no_grad()
68
+ def init_weights(m):
69
+ print(m)
70
+ if type(m) == torch.nn.LazyLinear:
71
+ m.weight.fill_(1.0)
72
+ print(m.weight)
73
+
74
+ linear = torch.nn.LazyLinear(2)
75
+ lazy_apply(linear, init_weights) # doesn't run `init_weights` immediately
76
+ input = torch.randn(2, 10)
77
+ linear(input) # runs `init_weights` only once, right after first forward pass
78
+
79
+ seq = torch.nn.Sequential(torch.nn.LazyLinear(2), torch.nn.LazyLinear(2))
80
+ lazy_apply(seq, init_weights) # doesn't run `init_weights` immediately
81
+ input = torch.randn(2, 10)
82
+ seq(input) # runs `init_weights` only once, right after first forward pass
83
+ """
84
+
85
+ if not hasattr(module, "_functions_to_lazy_apply"):
86
+ # pyre-ignore[16]
87
+ module._functions_to_lazy_apply = []
88
+ if not hasattr(module, "_lazy_apply_hook"):
89
+ # pyre-ignore[16]
90
+ module._lazy_apply_hook = module.register_forward_hook(
91
+ _apply_functions_after_first_forward
92
+ )
93
+ # pyre-ignore[16]
94
+ module._functions_to_lazy_apply.append(fn)
95
+ return module
96
+
97
+
98
+ class _LazyExtensionProtocol(_LazyProtocol):
99
+ # pyre-ignore[2,3]
100
+ def _call_impl(self, *input, **kwargs):
101
+ ...
102
+
103
+
104
+ class LazyModuleExtensionMixin(LazyModuleMixin):
105
+ """
106
+ This is a temporary extension of `LazyModuleMixin` to support passing keyword
107
+ arguments to lazy module's `forward` method.
108
+
109
+ The long-term plan is to upstream this feature to `LazyModuleMixin`. Please see
110
+ https://github.com/pytorch/pytorch/issues/59923 for details.
111
+
112
+ Please see `TestLazyModuleExtensionMixin`, which contains unit tests that ensure:
113
+ * `LazyModuleExtensionMixin._infer_parameters` has source code parity with
114
+ torch.nn.modules.lazy.LazyModuleMixin._infer_parameters, except that the former
115
+ can accept keyword arguments.
116
+ * `LazyModuleExtensionMixin._call_impl` has source code parity with
117
+ `torch.nn.Module._call_impl`, except that the former can pass keyword arguments
118
+ to forward pre hooks."
119
+ """
120
+
121
+ def apply(self, fn: Callable[[torch.nn.Module], None]) -> torch.nn.Module:
122
+ """Applies `fn` recursively to every submodule (as returned by `.children()`)
123
+ as well as self. Typical use includes initializing the parameters of a model.
124
+
125
+ NOTE:
126
+ Calling `apply()` on an uninitialized lazy-module will result in an error.
127
+ User is required to initialize a lazy-module (by doing a dummy forward pass)
128
+ before calling `apply()` on the lazy-module.
129
+
130
+ Args:
131
+ fn (torch.nn.Module -> None): function to be applied to each submodule.
132
+
133
+ Returns:
134
+ torch.nn.Module: self
135
+
136
+ Example::
137
+
138
+ @torch.no_grad()
139
+ def init_weights(m):
140
+ print(m)
141
+ if type(m) == torch.nn.LazyLinear:
142
+ m.weight.fill_(1.0)
143
+ print(m.weight)
144
+
145
+ linear = torch.nn.LazyLinear(2)
146
+ linear.apply(init_weights) # this fails, because `linear` (a lazy-module) hasn't been initialized yet
147
+
148
+ input = torch.randn(2, 10)
149
+ linear(input) # run a dummy forward pass to initialize the lazy-module
150
+
151
+ linear.apply(init_weights) # this works now
152
+ """
153
+
154
+ if hasattr(self, "_initialize_hook"):
155
+ raise RuntimeError(
156
+ "Module {} has not been initialized. ".format(self)
157
+ + "Please run a dummy forward pass on the model to initialize all modules, "
158
+ + "or use torchrec.modules.lazy_extension.lazy_apply to attach a function "
159
+ + "to this module which would be applied after this module is initialized."
160
+ )
161
+ # If the module is already initialized, call `super().apply(fn)` to
162
+ # run the usual apply logic.
163
+ # pyre-ignore[16]
164
+ return super().apply(fn)
165
+
166
+ # fmt: off
167
+ # pyre-ignore[2, 14, 47]
168
+ def _infer_parameters(self: _LazyExtensionProtocol, module, input, kwargs) -> None:
169
+ r"""Infers the size and initializes the parameters according to the
170
+ provided input batch.
171
+ Given a module that contains parameters that were declared inferrable
172
+ using :class:`torch.nn.parameter.ParameterMode.Infer`, runs a forward pass
173
+ in the complete module using the provided input to initialize all the parameters
174
+ as needed.
175
+ The module is set into evaluation mode before running the forward pass in order
176
+ to avoid saving statistics or calculating gradients
177
+ """
178
+ module.initialize_parameters(*input, **kwargs)
179
+ if module.has_uninitialized_params():
180
+ raise RuntimeError('module {} has not been fully initialized'.format(self._get_name()))
181
+ module._initialize_hook.remove()
182
+ module._load_hook.remove()
183
+ delattr(module, '_initialize_hook')
184
+ delattr(module, '_load_hook')
185
+ if module.cls_to_become is not None:
186
+ module.__class__ = module.cls_to_become
187
+ # fmt: on
188
+
189
+ # fmt: off
190
+ # pyre-ignore[2,3]
191
+ def _call_impl(self, *input, **kwargs): # noqa: C901
192
+ # pyre-ignore[16]
193
+ forward_call = (self._slow_forward if torch._C._get_tracing_state() else self.forward)
194
+ # If we don't have any hooks, we want to skip the rest of the logic in
195
+ # this function, and just call forward.
196
+ # pyre-ignore[16]
197
+ if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
198
+ or _global_forward_hooks or _global_forward_pre_hooks):
199
+ return forward_call(*input, **kwargs)
200
+ # Do not call functions when jit is used
201
+ full_backward_hooks, non_full_backward_hooks = [], []
202
+ if self._backward_hooks or _global_backward_hooks:
203
+ # pyre-ignore[16]
204
+ full_backward_hooks, non_full_backward_hooks = self._get_backward_hooks()
205
+ if _global_forward_pre_hooks or self._forward_pre_hooks:
206
+ # pyre-ignore[60]: Concatenation not yet support for multiple variadic
207
+ # tuples: `*torch.nn.modules.module._global_forward_pre_hooks.values(),
208
+ # *self._forward_pre_hooks.values()`.
209
+ for hook in (*_global_forward_pre_hooks.values(), *self._forward_pre_hooks.values()):
210
+ if len(inspect.signature(hook).parameters) == 3:
211
+ result = hook(self, input, kwargs)
212
+ else:
213
+ result = hook(self, input)
214
+ if result is not None:
215
+ if not isinstance(result, tuple):
216
+ result = (result,)
217
+ input = result
218
+
219
+ bw_hook = None
220
+ if full_backward_hooks:
221
+ bw_hook = hooks.BackwardHook(self, full_backward_hooks)
222
+ input = bw_hook.setup_input_hook(input)
223
+
224
+ result = forward_call(*input, **kwargs)
225
+ if _global_forward_hooks or self._forward_hooks:
226
+ # pyre-ignore[60]: Concatenation not yet support for multiple variadic
227
+ # tuples: `*torch.nn.modules.module._global_forward_hooks.values(),
228
+ # *self._forward_hooks.values()`.
229
+ for hook in (*_global_forward_hooks.values(), *self._forward_hooks.values()):
230
+ hook_result = hook(self, input, result)
231
+ if hook_result is not None:
232
+ result = hook_result
233
+
234
+ if bw_hook:
235
+ result = bw_hook.setup_output_hook(result)
236
+
237
+ # Handle the non-full backward hooks
238
+ if non_full_backward_hooks:
239
+ var = result
240
+ while not isinstance(var, torch.Tensor):
241
+ if isinstance(var, dict):
242
+ var = next((v for v in var.values() if isinstance(v, torch.Tensor)))
243
+ else:
244
+ var = var[0]
245
+ grad_fn = var.grad_fn
246
+ if grad_fn is not None:
247
+ for hook in non_full_backward_hooks:
248
+ wrapper = functools.partial(hook, self)
249
+ functools.update_wrapper(wrapper, hook)
250
+ grad_fn.register_hook(wrapper)
251
+ # pyre-ignore[16]
252
+ self._maybe_warn_non_full_backward_hook(input, result, grad_fn)
253
+
254
+ return result
255
+ # fmt: on
256
+
257
+ # pyre-ignore[4]
258
+ __call__: Callable[..., Any] = _call_impl
@@ -0,0 +1,172 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ from typing import Callable, List, Optional, Union
9
+
10
+ import torch
11
+ from torch import nn
12
+ from torchrec.modules.activation import SwishLayerNorm
13
+ from torchrec.modules.utils import extract_module_or_tensor_callable
14
+
15
+
16
+ class Perceptron(torch.nn.Module):
17
+ """
18
+ Applies a linear transformation and activation.
19
+
20
+ Args:
21
+ in_size (int): number of elements in each input sample.
22
+ out_size (int): number of elements in each output sample.
23
+ bias (bool): if set to ``False``, the layer will not learn an additive bias.
24
+ Default: ``True``.
25
+ activation (Union[torch.nn.Module, Callable[[torch.Tensor], torch.Tensor]]):
26
+ the activation function to apply to the output of linear transformation.
27
+ Default: torch.relu.
28
+ device (Optional[torch.device]): default compute device.
29
+
30
+ Example::
31
+
32
+ batch_size = 3
33
+ in_size = 40
34
+ input = torch.randn(batch_size, in_size)
35
+
36
+ out_size = 16
37
+ perceptron = Perceptron(in_size, out_size, bias=True)
38
+
39
+ output = perceptron(input)
40
+ assert list(output) == [batch_size, out_size]
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ in_size: int,
46
+ out_size: int,
47
+ bias: bool = True,
48
+ activation: Union[
49
+ torch.nn.Module,
50
+ Callable[[torch.Tensor], torch.Tensor],
51
+ ] = torch.relu,
52
+ device: Optional[torch.device] = None,
53
+ ) -> None:
54
+ super().__init__()
55
+ torch._C._log_api_usage_once(f"torchrec.modules.{self.__class__.__name__}")
56
+ self._out_size = out_size
57
+ self._in_size = in_size
58
+ self._linear: nn.Linear = nn.Linear(
59
+ self._in_size, self._out_size, bias=bias, device=device
60
+ )
61
+ self._activation_fn: Callable[[torch.Tensor], torch.Tensor] = activation
62
+
63
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
64
+ """
65
+ Args:
66
+ input (torch.Tensor): tensor of shape (B, I) where I is number of elements
67
+ in each input sample.
68
+
69
+ Returns:
70
+ torch.Tensor: tensor of shape (B, O) where O is number of elements per
71
+ channel in each output sample (i.e. `out_size`).
72
+ """
73
+ return self._activation_fn(self._linear(input))
74
+
75
+
76
+ class MLP(torch.nn.Module):
77
+ """
78
+ Applies a stack of Perceptron modules sequentially (i.e. Multi-Layer Perceptron).
79
+
80
+ Args:
81
+ in_size (int): `in_size` of the input.
82
+ layer_sizes (List[int]): `out_size` of each Perceptron module.
83
+ bias (bool): if set to False, the layer will not learn an additive bias.
84
+ Default: True.
85
+ activation (str, Union[Callable[[], torch.nn.Module], torch.nn.Module, Callable[[torch.Tensor], torch.Tensor]]):
86
+ the activation function to apply to the output of linear transformation of
87
+ each Perceptron module.
88
+ If `activation` is a `str`, we currently only support the follow strings, as
89
+ "relu", "sigmoid", and "swish_layernorm".
90
+ If `activation` is a `Callable[[], torch.nn.Module]`, `activation()` will be
91
+ called once per Perceptron module to generate the activation module for that
92
+ Perceptron module, and the parameters won't be shared between those activation
93
+ modules.
94
+ One use case is when all the activation modules share the same constructor
95
+ arguments, but don't share the actual module parameters.
96
+ Default: torch.relu.
97
+ device (Optional[torch.device]): default compute device.
98
+
99
+ Example::
100
+
101
+ batch_size = 3
102
+ in_size = 40
103
+ input = torch.randn(batch_size, in_size)
104
+
105
+ layer_sizes = [16, 8, 4]
106
+ mlp_module = MLP(in_size, layer_sizes, bias=True)
107
+ output = mlp_module(input)
108
+ assert list(output.shape) == [batch_size, layer_sizes[-1]]
109
+ """
110
+
111
+ def __init__(
112
+ self,
113
+ in_size: int,
114
+ layer_sizes: List[int],
115
+ bias: bool = True,
116
+ activation: Union[
117
+ str,
118
+ Callable[[], torch.nn.Module],
119
+ torch.nn.Module,
120
+ Callable[[torch.Tensor], torch.Tensor],
121
+ ] = torch.relu,
122
+ device: Optional[torch.device] = None,
123
+ ) -> None:
124
+ super().__init__()
125
+
126
+ if activation == "relu":
127
+ activation = torch.relu
128
+ elif activation == "sigmoid":
129
+ activation = torch.sigmoid
130
+
131
+ if not isinstance(activation, str):
132
+ self._mlp: torch.nn.Module = torch.nn.Sequential(
133
+ *[
134
+ Perceptron(
135
+ layer_sizes[i - 1] if i > 0 else in_size,
136
+ layer_sizes[i],
137
+ bias=bias,
138
+ activation=extract_module_or_tensor_callable(activation),
139
+ device=device,
140
+ )
141
+ for i in range(len(layer_sizes))
142
+ ]
143
+ )
144
+ else:
145
+ if activation == "swish_layernorm":
146
+ self._mlp: torch.nn.Module = torch.nn.Sequential(
147
+ *[
148
+ Perceptron(
149
+ layer_sizes[i - 1] if i > 0 else in_size,
150
+ layer_sizes[i],
151
+ bias=bias,
152
+ activation=SwishLayerNorm(layer_sizes[i], device=device),
153
+ device=device,
154
+ )
155
+ for i in range(len(layer_sizes))
156
+ ]
157
+ )
158
+ else:
159
+ assert (
160
+ ValueError
161
+ ), "This MLP only support str version activation function of relu, sigmoid, and swish_layernorm"
162
+
163
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
164
+ """
165
+ Args:
166
+ input (torch.Tensor): tensor of shape (B, I) where I is number of elements
167
+ in each input sample.
168
+
169
+ Returns:
170
+ torch.Tensor: tensor of shape (B, O) where O is `out_size` of the last Perceptron module.
171
+ """
172
+ return self._mlp(input)
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import copy
9
+ from typing import Callable, Iterable, Tuple, Union
10
+
11
+ import torch
12
+
13
+
14
+ def extract_module_or_tensor_callable(
15
+ module_or_callable: Union[
16
+ Callable[[], torch.nn.Module],
17
+ torch.nn.Module,
18
+ Callable[[torch.Tensor], torch.Tensor],
19
+ ]
20
+ ) -> Union[torch.nn.Module, Callable[[torch.Tensor], torch.Tensor]]:
21
+ try:
22
+ # pyre-ignore[20]: PositionalOnly call expects argument in position 0
23
+ module = module_or_callable()
24
+ if isinstance(module, torch.nn.Module):
25
+ return module
26
+ else:
27
+ raise ValueError(
28
+ "Expected callable that takes no input to return "
29
+ "a torch.nn.Module, but got: {}".format(type(module))
30
+ )
31
+ except TypeError as e:
32
+ if "required positional argument" in str(e):
33
+ # pyre-ignore[7]: Expected `Union[typing.Callable[[torch.Tensor], torch.Tensor], torch.nn.Module]`
34
+ return module_or_callable
35
+ raise
36
+
37
+
38
+ def get_module_output_dimension(
39
+ module: Union[Callable[[torch.Tensor], torch.Tensor], torch.nn.Module],
40
+ in_features: int,
41
+ ) -> int:
42
+ input = torch.zeros(1, in_features)
43
+ output = module(input)
44
+ return output.size(-1)
45
+
46
+
47
+ def check_module_output_dimension(
48
+ module: Union[Iterable[torch.nn.Module], torch.nn.Module],
49
+ in_features: int,
50
+ out_features: int,
51
+ ) -> bool:
52
+ """
53
+ Verify that the out_features of a given module or a list of modules matches the
54
+ specified number. If a list of modules or a ModuleList is given, recursively check
55
+ all the submodules.
56
+ """
57
+ if isinstance(module, list) or isinstance(module, torch.nn.ModuleList):
58
+ return all(
59
+ check_module_output_dimension(submodule, in_features, out_features)
60
+ for submodule in module
61
+ )
62
+ else:
63
+ # pyre-fixme[6]: Expected `Union[typing.Callable[[torch.Tensor],
64
+ # torch.Tensor], torch.nn.Module]` for 1st param but got
65
+ # `Union[Iterable[torch.nn.Module], torch.nn.Module]`.
66
+ return get_module_output_dimension(module, in_features) == out_features
67
+
68
+
69
+ def init_mlp_weights_xavier_uniform(m: torch.nn.Module) -> None:
70
+ if isinstance(m, torch.nn.Linear):
71
+ torch.nn.init.xavier_uniform_(m.weight)
72
+ m.bias.data.fill_(0.0)
73
+
74
+
75
+ def construct_modulelist_from_single_module(
76
+ module: torch.nn.Module, sizes: Tuple[int, ...]
77
+ ) -> torch.nn.Module:
78
+ """
79
+ Given a single module, construct a (nested) ModuleList of size of sizes by making
80
+ copies of the provided module and reinitializing the Linear layers.
81
+ """
82
+ if len(sizes) == 1:
83
+ return torch.nn.ModuleList(
84
+ [
85
+ copy.deepcopy(module).apply(init_mlp_weights_xavier_uniform)
86
+ for _ in range(sizes[0])
87
+ ]
88
+ )
89
+ else:
90
+ # recursively create nested ModuleList
91
+ return torch.nn.ModuleList(
92
+ [
93
+ construct_modulelist_from_single_module(module, sizes[1:])
94
+ for _ in range(sizes[0])
95
+ ]
96
+ )
97
+
98
+
99
+ def convert_list_of_modules_to_modulelist(
100
+ modules: Iterable[torch.nn.Module], sizes: Tuple[int, ...]
101
+ ) -> torch.nn.Module:
102
+ assert (
103
+ # pyre-fixme[6]: Expected `Sized` for 1st param but got
104
+ # `Iterable[torch.nn.Module]`.
105
+ len(modules)
106
+ == sizes[0]
107
+ ), f"the counts of modules ({len(modules)}) do not match with the required counts {sizes}"
108
+ if len(sizes) == 1:
109
+ return torch.nn.ModuleList(modules)
110
+ else:
111
+ # recursively create nested list
112
+ return torch.nn.ModuleList(
113
+ # pyre-fixme[6]: Expected `Iterable[torch.nn.Module]` for 1st param but
114
+ # got `Module`.
115
+ convert_list_of_modules_to_modulelist(m, sizes[1:])
116
+ for m in modules
117
+ )
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ """Torchrec Optimizers
9
+
10
+ Torchrec contains a special optimizer called KeyedOptimizer. KeyedOptimizer exposes the state_dict with meaningful keys- it enables loading both
11
+ torch.tensor and `ShardedTensor <https://github.com/pytorch/pytorch/issues/55207>`_ in place, and it prohibits loading an empty state into already initialized KeyedOptimizer and vise versa.
12
+
13
+ It also contains
14
+ - several modules wrapping KeyedOptimizer, called CombinedOptimizer and OptimizerWrapper
15
+ - Optimizers used in RecSys: e.g. rowwise adagrad/adam/etc
16
+ """
17
+
18
+ from torchrec.optim.clipping import GradientClipping, GradientClippingOptimizer # noqa
19
+ from torchrec.optim.fused import FusedOptimizer, FusedOptimizerModule # noqa
20
+ from torchrec.optim.keyed import ( # noqa
21
+ CombinedOptimizer,
22
+ KeyedOptimizer,
23
+ KeyedOptimizerWrapper,
24
+ OptimizerWrapper,
25
+ )
26
+ from torchrec.optim.rowwise_adagrad import RowWiseAdagrad # noqa
27
+ from torchrec.optim.warmup import WarmupOptimizer, WarmupPolicy, WarmupStage # noqa
28
+
29
+ from . import ( # noqa # noqa # noqa # noqa
30
+ clipping,
31
+ fused,
32
+ keyed,
33
+ rowwise_adagrad,
34
+ warmup,
35
+ )
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ from enum import Enum, unique
9
+ from typing import Any, List
10
+
11
+ import torch
12
+ from torchrec.optim.keyed import KeyedOptimizer, OptimizerWrapper
13
+
14
+
15
+ @unique
16
+ class GradientClipping(Enum):
17
+ NORM = "norm"
18
+ VALUE = "value"
19
+ NONE = "none"
20
+
21
+
22
+ class GradientClippingOptimizer(OptimizerWrapper):
23
+ """
24
+ Clips gradients before doing optimization step.
25
+
26
+ Args:
27
+ optimizer (KeyedOptimizer): optimizer to wrap
28
+ clipping (GradientClipping): how to clip gradients
29
+ max_gradient (float): max value for clipping
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ optimizer: KeyedOptimizer,
35
+ clipping: GradientClipping = GradientClipping.NONE,
36
+ max_gradient: float = 0.1,
37
+ ) -> None:
38
+ super().__init__(optimizer)
39
+ self._clipping = clipping
40
+ self._max_gradient = max_gradient
41
+
42
+ self._params: List[torch.Tensor] = []
43
+ for param_group in self.param_groups:
44
+ self._params += list(param_group["params"])
45
+
46
+ # pyre-ignore [2]
47
+ def step(self, closure: Any = None) -> None:
48
+ if self._clipping == GradientClipping.NORM:
49
+ torch.nn.utils.clip_grad_norm_(self._params, self._max_gradient)
50
+ elif self._clipping == GradientClipping.VALUE:
51
+ torch.nn.utils.clip_grad_value_(self._params, self._max_gradient)
52
+
53
+ super().step(closure)
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import abc
9
+ from typing import Any
10
+
11
+ from torch import optim
12
+ from torchrec.optim.keyed import KeyedOptimizer
13
+
14
+
15
+ class FusedOptimizer(KeyedOptimizer, abc.ABC):
16
+ """
17
+ Assumes that weight update is done during backward pass,
18
+ thus step() is a no-op.
19
+ """
20
+
21
+ @abc.abstractmethod
22
+ # pyre-ignore [2]
23
+ def step(self, closure: Any = None) -> None:
24
+ ...
25
+
26
+ @abc.abstractmethod
27
+ def zero_grad(self, set_to_none: bool = False) -> None:
28
+ ...
29
+
30
+ def __repr__(self) -> str:
31
+ return optim.Optimizer.__repr__(self)
32
+
33
+
34
+ class FusedOptimizerModule(abc.ABC):
35
+ """
36
+ Module, which does weight update during backward pass.
37
+ """
38
+
39
+ @property
40
+ @abc.abstractmethod
41
+ def fused_optimizer(self) -> KeyedOptimizer:
42
+ ...