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,399 @@
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 copy import deepcopy
9
+ from typing import (
10
+ Any,
11
+ Callable,
12
+ Collection,
13
+ Dict,
14
+ List,
15
+ Mapping,
16
+ Optional,
17
+ Set,
18
+ Tuple,
19
+ Union,
20
+ )
21
+
22
+ import torch
23
+ from torch import optim
24
+ from torchrec.distributed.types import ShardedTensor
25
+
26
+
27
+ OptimizerFactory = Callable[[List[Union[torch.Tensor, ShardedTensor]]], optim.Optimizer]
28
+
29
+
30
+ class KeyedOptimizer(optim.Optimizer):
31
+ """
32
+ Takes a dict of parameters and exposes state_dict by parameter key.
33
+
34
+ This implementation is much stricter than the one in torch.Optimizer:
35
+ it requires implementations to fully initialize their state during first optimization iteration,
36
+ and it prohibits loading an empty state into already initialized KeyedOptimizer and vise versa.
37
+
38
+ It also doesn't expose param_groups in state_dict() by default
39
+ Old behavior can be switch on by setting save_param_groups flag.
40
+ The reason is that during distributed training not all parameters are present on all ranks
41
+ and we identify param_group by its parameters.
42
+ In addition to that, param_groups are typically re-set during training initialization,
43
+ so it makes little sense to save them as a part of the state to begin with.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ params: Mapping[str, Union[torch.Tensor, ShardedTensor]],
49
+ # pyre-ignore [2]
50
+ state: Mapping[Any, Any],
51
+ param_groups: Collection[Mapping[str, Any]],
52
+ ) -> None:
53
+ torch._C._log_api_usage_once(f"torchrec.optim.{self.__class__.__name__}")
54
+ # pyre-ignore [4]
55
+ self.state: Mapping[Any, Any] = state
56
+ self.param_groups: Collection[Mapping[str, Any]] = param_groups
57
+ self.params = params
58
+ self.defaults: Dict[str, Any] = {"_save_param_groups": False}
59
+
60
+ params_set = set(params.values())
61
+ non_param_state_keys = [key for key in self.state if key not in params_set]
62
+ if len(non_param_state_keys) > 0:
63
+ raise ValueError(
64
+ "All state keys must be params. The following keys are not: {}.".format(
65
+ non_param_state_keys
66
+ )
67
+ )
68
+
69
+ def state_dict(self) -> Dict[str, Any]:
70
+ """
71
+ Returned state and param_groups will contain parameter keys
72
+ instead of parameter indices in torch.Optimizer.
73
+ This allows for advanced functionality like optimizer re-sharding to be implemented.
74
+ """
75
+
76
+ state = self.state
77
+ param_groups = self.param_groups
78
+ params = self.params
79
+ param_to_key = {param: key for key, param in params.items()}
80
+
81
+ ret_state = {
82
+ param_to_key[param]: state_val for param, state_val in state.items()
83
+ }
84
+
85
+ ret_groups = []
86
+ for group in param_groups:
87
+ param_keys = []
88
+ for param in group["params"]:
89
+ param_keys.append(param_to_key[param])
90
+ ret_group = {"params": sorted(param_keys)}
91
+ for k, v in group.items():
92
+ if k != "params":
93
+ ret_group[k] = deepcopy(v)
94
+ ret_groups.append(ret_group)
95
+
96
+ ret: Dict[str, object] = {"state": ret_state}
97
+ if self.defaults["_save_param_groups"]:
98
+ ret["param_groups"] = ret_groups
99
+ return ret
100
+
101
+ def post_load_state_dict(self) -> None:
102
+ pass
103
+
104
+ def load_state_dict(self, state_dict: Mapping[str, Any]) -> None:
105
+ """
106
+ This implementation is much stricter than the one in torch.Optimizer:
107
+ it requires implementations to fully initialize their state during first optimization iteration,
108
+ and it prohibits loading an empty state into already initialized KeyedOptimizer and vise versa.
109
+
110
+ Because of introduced strictness it allows us to:
111
+ * do compatibility checks for state and param_groups, which improves usability
112
+ * avoid state duplication by directly copying into state tensors, e.g.
113
+ optimizer.step() # make sure optimizer is initialized
114
+ sd = optimizer.state_dict()
115
+ load_checkpoint(sd) # copy state directly into tensors, re-shard if needed
116
+ optimizer.load_state_dict(sd) # replace param_groups
117
+ """
118
+
119
+ new_state = state_dict["state"]
120
+ state = self.state
121
+ params = self.params
122
+
123
+ # Load state
124
+ if len(state) != len(new_state):
125
+ raise ValueError(
126
+ f"Different parameter count: {len(state)} vs {len(new_state)}"
127
+ )
128
+ for param_key, param in params.items():
129
+ if param not in state:
130
+ continue
131
+ if param_key not in new_state:
132
+ raise ValueError(f"Parameter {param_key} not found")
133
+ if len(state[param]) != len(new_state[param_key]):
134
+ raise ValueError(
135
+ f"Different state size: {len(state[param])} vs {len(new_state[param_key])}"
136
+ )
137
+ for state_key, state_val in state[param].items():
138
+ if state_key not in new_state[param_key]:
139
+ raise ValueError(
140
+ f"State key {state_key} not found for param {param_key}"
141
+ )
142
+
143
+ new_state_val = new_state[param_key][state_key]
144
+ if isinstance(state_val, ShardedTensor):
145
+ assert isinstance(new_state_val, ShardedTensor)
146
+ num_shards = len(state_val.local_shards())
147
+ num_new_shards = len(new_state_val.local_shards())
148
+ if num_shards != num_new_shards:
149
+ raise ValueError(
150
+ f"Different number of shards {num_shards} vs {num_new_shards} for {param_key}/{state_key}"
151
+ )
152
+ for shard, new_shard in zip(
153
+ state_val.local_shards(), new_state_val.local_shards()
154
+ ):
155
+ shard.tensor.detach().copy_(new_shard.tensor)
156
+ elif isinstance(state_val, torch.Tensor):
157
+ assert isinstance(new_state_val, torch.Tensor)
158
+ state_val.detach().copy_(new_state_val)
159
+ else:
160
+ state[param][state_key] = deepcopy(new_state_val)
161
+
162
+ # Load param_groups.
163
+ if self.defaults["_save_param_groups"]:
164
+ new_param_groups = state_dict["param_groups"]
165
+ param_groups = self.param_groups
166
+
167
+ if len(param_groups) != len(new_param_groups):
168
+ raise ValueError(
169
+ f"Different param_groups count: {len(param_groups)} vs {len(new_param_groups)}"
170
+ )
171
+ param_to_key = {param: key for key, param in params.items()}
172
+ group_map = {}
173
+ for group in param_groups:
174
+ param_keys = []
175
+ for param in group["params"]:
176
+ param_keys.append(param_to_key[param])
177
+ group_map["/".join(sorted(param_keys))] = group
178
+ new_group_map = {}
179
+ for new_group in new_param_groups:
180
+ param_keys = []
181
+ for param_key in new_group["params"]:
182
+ param_keys.append(param_key)
183
+ new_group_map["/".join(sorted(param_keys))] = new_group
184
+ for group_key, group in group_map.items():
185
+ if group_key not in new_group_map:
186
+ raise ValueError(f"Group {group_key} not found")
187
+ new_group = new_group_map[group_key]
188
+ if len(group) != len(new_group):
189
+ raise ValueError(
190
+ f"Different param_group size: {len(group)} vs {len(new_group)}"
191
+ )
192
+ for k in group:
193
+ if k not in new_group:
194
+ raise ValueError(
195
+ f"Group key {k} not found for group {group_key}"
196
+ )
197
+ if k != "params":
198
+ group[k] = deepcopy(new_group[k])
199
+
200
+ self.post_load_state_dict()
201
+
202
+ # pyre-ignore [2]
203
+ def add_param_group(self, param_group: Any) -> None:
204
+ raise NotImplementedError()
205
+
206
+ def init_state(
207
+ self,
208
+ sparse_grad_parameter_names: Optional[Set[str]] = None,
209
+ ) -> None:
210
+ """
211
+ Runs a dummy optimizer step, which allows to initialize
212
+ optimizer state, which is typically lazy.
213
+ This allows us to do in-place loading of optimizer state from a checkpoint.
214
+ """
215
+ for key, param in self.params.items():
216
+ if param.requires_grad:
217
+ # pyre-fixme[6]: For 1st param expected `Tensor` but got
218
+ # `Union[Tensor, ShardedTensor]`.
219
+ t = torch.zeros_like(param)
220
+ if (
221
+ sparse_grad_parameter_names is not None
222
+ and key in sparse_grad_parameter_names
223
+ ):
224
+ t = t.to_sparse()
225
+ # pyre-fixme[16]: `ShardedTensor` has no attribute `grad`.
226
+ # pyre-fixme[8]: Attribute has type `Optional[Tensor]`; used as
227
+ # `Variable`.
228
+ # pyre-fixme[19]: Expected 0 positional arguments.
229
+ param.grad = torch.autograd.Variable(t)
230
+ self.step(closure=None)
231
+
232
+ def save_param_groups(self, save: bool) -> None:
233
+ self.defaults["_save_param_groups"] = save
234
+
235
+ def __getstate__(self) -> Dict[str, Any]:
236
+ return self.__dict__
237
+
238
+
239
+ class CombinedOptimizer(KeyedOptimizer):
240
+ """
241
+ Combines multiple KeyedOptimizers into one.
242
+
243
+ Meant to combine different optimizers for different submodules
244
+ """
245
+
246
+ def __init__(
247
+ self, optims: List[Union[KeyedOptimizer, Tuple[str, KeyedOptimizer]]]
248
+ ) -> None:
249
+ self.defaults: Dict[str, Any] = {}
250
+ # Append empty optimizer key if not passed.
251
+ self._optims: List[Tuple[str, KeyedOptimizer]] = []
252
+ for key_value in optims:
253
+ if isinstance(key_value, KeyedOptimizer):
254
+ key_value = ("", key_value)
255
+ self._optims.append(key_value)
256
+
257
+ all_keys: Set[str] = set()
258
+ self.defaults["_save_param_groups"] = (
259
+ False
260
+ if len(self._optims) == 0
261
+ else self._optims[0][1].defaults["_save_param_groups"]
262
+ )
263
+ for opt_key, opt in self._optims:
264
+ assert (
265
+ self.defaults["_save_param_groups"]
266
+ == opt.defaults["_save_param_groups"]
267
+ )
268
+
269
+ for param_key in opt.params.keys():
270
+ new_param = CombinedOptimizer._prepend_opt_key(param_key, opt_key)
271
+ if new_param in all_keys:
272
+ raise ValueError(f"Duplicate param key {new_param}")
273
+ all_keys.add(new_param)
274
+
275
+ def __repr__(self) -> str:
276
+ ret = []
277
+ for _, opt in self._optims:
278
+ ret.append(opt.__repr__())
279
+ return ",".join(ret)
280
+
281
+ def zero_grad(self, set_to_none: bool = False) -> None:
282
+ for _, opt in self._optims:
283
+ opt.zero_grad(set_to_none=set_to_none)
284
+
285
+ # pyre-ignore [2]
286
+ def step(self, closure: Any = None) -> None:
287
+ for _, opt in self._optims:
288
+ opt.step(closure=closure)
289
+
290
+ @property
291
+ def optimizers(self) -> List[Tuple[str, KeyedOptimizer]]:
292
+ return self._optims
293
+
294
+ @staticmethod
295
+ def _prepend_opt_key(name: str, opt_key: str) -> str:
296
+ return opt_key + ("." if opt_key else "") + name
297
+
298
+ @property
299
+ def param_groups(self) -> Collection[Mapping[str, Any]]:
300
+ return [
301
+ param_group for _, opt in self._optims for param_group in opt.param_groups
302
+ ]
303
+
304
+ @property
305
+ def params(self) -> Mapping[str, Union[torch.Tensor, ShardedTensor]]:
306
+ ret = {}
307
+ for opt_key, opt in self._optims:
308
+ for param_key, param in opt.params.items():
309
+ ret[CombinedOptimizer._prepend_opt_key(param_key, opt_key)] = param
310
+ return ret
311
+
312
+ @property
313
+ # pyre-ignore [3]
314
+ def state(self) -> Mapping[torch.Tensor, Any]:
315
+ ret = {}
316
+ for _, opt in self._optims:
317
+ for param, state in opt.state.items():
318
+ ret[param] = state
319
+ return ret
320
+
321
+ def post_load_state_dict(self) -> None:
322
+ for _, opt in self._optims:
323
+ opt.post_load_state_dict()
324
+
325
+ def save_param_groups(self, save: bool) -> None:
326
+ self.defaults["_save_param_groups"] = save
327
+ for _, opt in self._optims:
328
+ opt.save_param_groups(save)
329
+
330
+
331
+ class KeyedOptimizerWrapper(KeyedOptimizer):
332
+ """
333
+ Takes a dict of parameters and exposes state_dict by parameter key.
334
+
335
+ Convenience wrapper to take in optim_factory callable to create KeyedOptimizer
336
+ """
337
+
338
+ def __init__(
339
+ self,
340
+ params: Mapping[str, Union[torch.Tensor, ShardedTensor]],
341
+ optim_factory: OptimizerFactory,
342
+ ) -> None:
343
+ self._optimizer: optim.Optimizer = optim_factory(list(params.values()))
344
+ super().__init__(params, self._optimizer.state, self._optimizer.param_groups)
345
+
346
+ def zero_grad(self, set_to_none: bool = False) -> None:
347
+ self._optimizer.zero_grad()
348
+
349
+ # pyre-ignore [2]
350
+ def step(self, closure: Any = None) -> None:
351
+ self._optimizer.step(closure=closure)
352
+
353
+
354
+ class OptimizerWrapper(KeyedOptimizer):
355
+ """
356
+ Wrapper which takes in a KeyedOptimizer and is a KeyedOptimizer
357
+
358
+ Subclass for Optimizers like GradientClippingOptimizer and WarmupOptimizer
359
+ """
360
+
361
+ def __init__(self, optimizer: KeyedOptimizer) -> None:
362
+ self._optimizer = optimizer
363
+ self.params: Mapping[str, Union[torch.Tensor, ShardedTensor]] = optimizer.params
364
+ # pyre-ignore [4]
365
+ self.state: Mapping[Any, Any] = optimizer.state
366
+ self.param_groups: Collection[Mapping[str, Any]] = optimizer.param_groups
367
+ self.defaults: Dict[str, Any] = {"_save_param_groups": False}
368
+
369
+ def __repr__(self) -> str:
370
+ return self._optimizer.__repr__()
371
+
372
+ def zero_grad(self, set_to_none: bool = False) -> None:
373
+ self._optimizer.zero_grad(set_to_none=set_to_none)
374
+
375
+ # pyre-ignore [2]
376
+ def step(self, closure: Any = None) -> None:
377
+ self._optimizer.step(closure=closure)
378
+
379
+ # pyre-ignore [2]
380
+ def add_param_group(self, param_group: Any) -> None:
381
+ raise NotImplementedError()
382
+
383
+ def state_dict(self) -> Dict[str, Any]:
384
+ return self._optimizer.state_dict()
385
+
386
+ def post_load_state_dict(self) -> None:
387
+ self._optimizer.post_load_state_dict()
388
+
389
+ def load_state_dict(self, state_dict: Mapping[str, Any]) -> None:
390
+ self._optimizer.load_state_dict(state_dict)
391
+ # Reassign references because self._optimizer receives new state and param_group
392
+ # references after load_state_dict.
393
+ self.state = self._optimizer.state
394
+ self.param_groups = self._optimizer.param_groups
395
+
396
+ self.post_load_state_dict()
397
+
398
+ def save_param_groups(self, save: bool) -> None:
399
+ self._optimizer.save_param_groups(save)
@@ -0,0 +1,222 @@
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
+ #!/usr/bin/env python3
9
+
10
+ from typing import Any, Dict, Iterable, List
11
+
12
+ import torch
13
+ from torch import Tensor
14
+
15
+ from torch.optim.optimizer import Optimizer
16
+
17
+
18
+ class RowWiseAdagrad(Optimizer):
19
+ r"""Implements Row wise Adagrad algorithm. This is an extension of the Adagrad algorithm
20
+ https://github.com/pytorch/pytorch/blob/master/torch/optim/adagrad.py, for use with
21
+ EmbeddingBag parameters, where we want the adaptive learning rate to be the same within an
22
+ embedding row. Since we only need to store state for an embedding row, rather than every single
23
+ parameter, we can have drastic memory savings (factor of embedding_dim).
24
+
25
+ Note that this implementation does not currently support sparse gradients.
26
+
27
+ Args:
28
+ params (iterable): iterable of parameters to optimize or dicts defining
29
+ parameter groups
30
+ lr (float, optional): learning rate (default: 1e-2)
31
+ lr_decay (float, optional): learning rate decay (default: 0)
32
+ weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
33
+ eps (float, optional): term added to the denominator to improve
34
+ numerical stability (default: 1e-10)
35
+ maximize (bool, optional): maximize the params based on the objective, instead of
36
+ minimizing (default: False)
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ params: Iterable[torch.nn.Parameter],
42
+ lr: float = 1e-2,
43
+ lr_decay: float = 0.0,
44
+ weight_decay: float = 0.0,
45
+ initial_accumulator_value: float = 0.0,
46
+ eps: float = 1e-10,
47
+ *,
48
+ maximize: bool = False,
49
+ ) -> None:
50
+ if not 0.0 <= lr:
51
+ raise ValueError("Invalid learning rate: {}".format(lr))
52
+ if not 0.0 <= lr_decay:
53
+ raise ValueError("Invalid lr_decay value: {}".format(lr_decay))
54
+ if not 0.0 <= weight_decay:
55
+ raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
56
+ if not 0.0 <= initial_accumulator_value:
57
+ raise ValueError(
58
+ "Invalid initial_accumulator_value value: {}".format(
59
+ initial_accumulator_value
60
+ )
61
+ )
62
+ if not 0.0 <= eps:
63
+ raise ValueError("Invalid epsilon value: {}".format(eps))
64
+
65
+ defaults = dict(
66
+ lr=lr,
67
+ lr_decay=lr_decay,
68
+ eps=eps,
69
+ weight_decay=weight_decay,
70
+ initial_accumulator_value=initial_accumulator_value,
71
+ maximize=maximize,
72
+ )
73
+ super().__init__(params, defaults)
74
+
75
+ for group in self.param_groups:
76
+ for p in group["params"]:
77
+ state = self.state[p]
78
+ state["step"] = torch.tensor(0.0)
79
+ init_value = (
80
+ complex(initial_accumulator_value, initial_accumulator_value)
81
+ if torch.is_complex(p)
82
+ else initial_accumulator_value
83
+ )
84
+ state["sum"] = (
85
+ # pyre-fixme[28]: Unexpected keyword argument `axis`.
86
+ # pyre-fixme[6]: For 2nd param expected `Union[bool, float,
87
+ # int]` but got `complex`.
88
+ torch.full_like(p, init_value, memory_format=torch.preserve_format)
89
+ .mean(axis=1)
90
+ .view(-1, 1)
91
+ )
92
+
93
+ def __setstate__(self, state: Dict[str, Any]) -> None:
94
+ super().__setstate__(state)
95
+ for group in self.param_groups:
96
+ group.setdefault("maximize", False)
97
+
98
+ state_values = list(self.state.values())
99
+ step_is_tensor = (len(state_values) != 0) and torch.is_tensor(
100
+ state_values[0]["step"]
101
+ )
102
+ if not step_is_tensor:
103
+ for s in state_values:
104
+ s["step"] = torch.tensor(float(s["step"]))
105
+
106
+ def share_memory(self) -> None:
107
+ for group in self.param_groups:
108
+ for p in group["params"]:
109
+ state = self.state[p]
110
+ state["sum"].share_memory_()
111
+
112
+ @torch.no_grad()
113
+ # pyre-ignore
114
+ def step(self, closure=None) -> torch.Tensor:
115
+ """Performs a single optimization step.
116
+ Args:
117
+ closure (callable, optional): A closure that reevaluates the model
118
+ and returns the loss.
119
+ """
120
+ loss = None
121
+
122
+ if closure is not None:
123
+ with torch.enable_grad():
124
+ loss = closure()
125
+
126
+ for group in self.param_groups:
127
+ params_with_grad = []
128
+ grads = []
129
+ state_sums = []
130
+ state_steps = []
131
+
132
+ for p in group["params"]:
133
+ if p.grad is not None:
134
+ params_with_grad.append(p)
135
+ grads.append(p.grad)
136
+ state = self.state[p]
137
+ state_sums.append(state["sum"])
138
+ state_steps.append(state["step"])
139
+
140
+ adagrad(
141
+ params_with_grad,
142
+ grads,
143
+ state_sums,
144
+ state_steps,
145
+ lr=group["lr"],
146
+ weight_decay=group["weight_decay"],
147
+ lr_decay=group["lr_decay"],
148
+ eps=group["eps"],
149
+ maximize=group["maximize"],
150
+ )
151
+
152
+ return loss
153
+
154
+
155
+ def adagrad(
156
+ params: List[Tensor],
157
+ grads: List[Tensor],
158
+ state_sums: List[Tensor],
159
+ state_steps: List[Tensor],
160
+ # kwonly args with defaults are not supported by functions compiled with torchscript issue #70627
161
+ # setting these as kwargs for now as functional API is compiled by torch/distributed/optim
162
+ *,
163
+ lr: float,
164
+ weight_decay: float,
165
+ lr_decay: float,
166
+ eps: float,
167
+ maximize: bool,
168
+ ) -> None:
169
+ r"""Functional API that performs Adagrad algorithm computation.
170
+ See :class:`~torch.optim.Adagrad` for details.
171
+ """
172
+
173
+ if not all([isinstance(t, torch.Tensor) for t in state_steps]):
174
+ raise RuntimeError(
175
+ "API has changed, `state_steps` argument must contain a list of singleton tensors"
176
+ )
177
+
178
+ _single_tensor_adagrad(
179
+ params,
180
+ grads,
181
+ state_sums,
182
+ state_steps,
183
+ lr=lr,
184
+ weight_decay=weight_decay,
185
+ lr_decay=lr_decay,
186
+ eps=eps,
187
+ maximize=maximize,
188
+ )
189
+
190
+
191
+ def _single_tensor_adagrad(
192
+ params: List[Tensor],
193
+ grads: List[Tensor],
194
+ state_sums: List[Tensor],
195
+ state_steps: List[Tensor],
196
+ *,
197
+ lr: float,
198
+ weight_decay: float,
199
+ lr_decay: float,
200
+ eps: float,
201
+ maximize: bool,
202
+ ) -> None:
203
+
204
+ for (param, grad, state_sum, step_t) in zip(params, grads, state_sums, state_steps):
205
+ if grad.is_sparse:
206
+ raise RuntimeError("RowWise adagrad cannot be used with sparse gradients")
207
+ # update step
208
+ step_t += 1
209
+ step = step_t.item()
210
+ grad = grad if not maximize else -grad
211
+
212
+ row_wise_grad = grad.mean(axis=1).view(-1, 1)
213
+ if weight_decay != 0:
214
+
215
+ grad = grad.add(param, alpha=weight_decay)
216
+ row_wise_grad = grad.add(param, alpha=weight_decay)
217
+
218
+ clr = lr / (1 + (step - 1) * lr_decay)
219
+
220
+ state_sum.addcmul_(row_wise_grad, row_wise_grad, value=1)
221
+ std = state_sum.sqrt().add_(eps)
222
+ param.addcdiv_(row_wise_grad, std, value=-clr)
@@ -0,0 +1,19 @@
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 Any
9
+
10
+ from torchrec.optim.keyed import KeyedOptimizer
11
+
12
+
13
+ class DummyKeyedOptimizer(KeyedOptimizer):
14
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
15
+ super().__init__(*args, **kwargs)
16
+
17
+ # pyre-ignore[2]
18
+ def step(self, closure: Any) -> None:
19
+ pass # Override NotImplementedError.