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,545 @@
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 collections import OrderedDict
10
+ from typing import Any, Dict, Iterator, List, Optional, Tuple
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ from fbgemm_gpu.split_embedding_configs import SparseType
15
+ from fbgemm_gpu.split_table_batched_embeddings_ops import (
16
+ EmbeddingLocation,
17
+ IntNBitTableBatchedEmbeddingBagsCodegen,
18
+ PoolingMode,
19
+ )
20
+ from torch import Tensor
21
+ from torchrec.modules.embedding_configs import (
22
+ DATA_TYPE_NUM_BITS,
23
+ data_type_to_sparse_type,
24
+ DataType,
25
+ dtype_to_data_type,
26
+ EmbeddingBagConfig,
27
+ EmbeddingConfig,
28
+ pooling_type_to_pooling_mode,
29
+ )
30
+ from torchrec.modules.embedding_modules import (
31
+ EmbeddingBagCollection as OriginalEmbeddingBagCollection,
32
+ EmbeddingBagCollectionInterface,
33
+ EmbeddingCollection as OriginalEmbeddingCollection,
34
+ EmbeddingCollectionInterface,
35
+ get_embedding_names_by_table,
36
+ )
37
+ from torchrec.sparse.jagged_tensor import JaggedTensor, KeyedJaggedTensor, KeyedTensor
38
+
39
+
40
+ try:
41
+ torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops")
42
+ torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops_cpu")
43
+ except OSError:
44
+ pass
45
+
46
+ # OSS
47
+ try:
48
+ import fbgemm_gpu # @manual # noqa
49
+ except ImportError:
50
+ pass
51
+
52
+
53
+ def quantize_state_dict(
54
+ module: nn.Module,
55
+ table_name_to_quantized_weights: Dict[str, Tuple[Tensor, Tensor]],
56
+ data_type: DataType,
57
+ ) -> torch.device:
58
+ device = torch.device("cpu")
59
+ for key, tensor in module.state_dict().items():
60
+ # Extract table name from state dict key.
61
+ # e.g. ebc.embedding_bags.t1.weight
62
+ splits = key.split(".")
63
+ assert splits[-1] == "weight"
64
+ table_name = splits[-2]
65
+ device = tensor.device
66
+ num_bits = DATA_TYPE_NUM_BITS[data_type]
67
+ if tensor.is_meta:
68
+ quant_weight = torch.empty(
69
+ (tensor.shape[0], (tensor.shape[1] * num_bits) // 8),
70
+ device="meta",
71
+ # pyre-fixme[16]: Item `Tensor` of `Union[Tensor, Module]` has
72
+ # no attribute `weight`.
73
+ dtype=module.qconfig.weight().dtype,
74
+ )
75
+ if (
76
+ data_type == DataType.INT8
77
+ or data_type == DataType.INT4
78
+ or data_type == DataType.INT2
79
+ ):
80
+ scale_shift = torch.empty(
81
+ (tensor.shape[0], 4),
82
+ device="meta",
83
+ # pyre-fixme[16]: Item `Tensor` of `Union[Tensor, Module]` has
84
+ # no attribute `weight`.
85
+ dtype=module.qconfig.weight().dtype,
86
+ )
87
+ else:
88
+ scale_shift = None
89
+ else:
90
+ if tensor.dtype == torch.float or tensor.dtype == torch.float16:
91
+ if tensor.dtype == torch.float16 and data_type == DataType.FP16:
92
+ quant_res = tensor.view(torch.uint8)
93
+ else:
94
+ quant_res = (
95
+ torch.ops.fbgemm.FloatOrHalfToFusedNBitRowwiseQuantizedSBHalf(
96
+ tensor, num_bits
97
+ )
98
+ )
99
+ else:
100
+ raise Exception("Unsupported dtype: {tensor.dtype}")
101
+ if (
102
+ data_type == DataType.INT8
103
+ or data_type == DataType.INT4
104
+ or data_type == DataType.INT2
105
+ ):
106
+ quant_weight, scale_shift = (
107
+ quant_res[:, :-4],
108
+ quant_res[:, -4:],
109
+ )
110
+ else:
111
+ quant_weight, scale_shift = quant_res, None
112
+ table_name_to_quantized_weights[table_name] = (quant_weight, scale_shift)
113
+ return device
114
+
115
+
116
+ class EmbeddingBagCollection(EmbeddingBagCollectionInterface):
117
+ """
118
+ EmbeddingBagCollection represents a collection of pooled embeddings (EmbeddingBags).
119
+ This EmbeddingBagCollection is quantized for lower precision. It relies on fbgemm quantized ops
120
+
121
+ It processes sparse data in the form of KeyedJaggedTensor
122
+ with values of the form [F X B X L]
123
+ F: features (keys)
124
+ B: batch size
125
+ L: Length of sparse features (jagged)
126
+
127
+ and outputs a KeyedTensor with values of the form [B * (F * D)]
128
+ where
129
+ F: features (keys)
130
+ D: each feature's (key's) embedding dimension
131
+ B: batch size
132
+
133
+ Args:
134
+ table_name_to_quantized_weights (Dict[str, Tuple[Tensor, Tensor]]): map of tables to quantized weights
135
+ embedding_configs (List[EmbeddingBagConfig]): list of embedding tables
136
+ is_weighted: (bool): whether input KeyedJaggedTensor is weighted
137
+ device: (Optional[torch.device]): default compute device
138
+
139
+ Call Args:
140
+ features: KeyedJaggedTensor,
141
+
142
+ Returns:
143
+ KeyedTensor
144
+
145
+ Example::
146
+
147
+ table_0 = EmbeddingBagConfig(
148
+ name="t1", embedding_dim=3, num_embeddings=10, feature_names=["f1"]
149
+ )
150
+ table_1 = EmbeddingBagConfig(
151
+ name="t2", embedding_dim=4, num_embeddings=10, feature_names=["f2"]
152
+ )
153
+ ebc = EmbeddingBagCollection(tables=[eb1_config, eb2_config])
154
+
155
+ # 0 1 2 <-- batch
156
+ # "f1" [0,1] None [2]
157
+ # "f2" [3] [4] [5,6,7]
158
+ # ^
159
+ # feature
160
+ features = KeyedJaggedTensor(
161
+ keys=["f1", "f2"],
162
+ values=torch.tensor([0, 1, 2, 3, 4, 5, 6, 7]),
163
+ offsets=torch.tensor([0, 2, 2, 3, 4, 5, 8]),
164
+ )
165
+
166
+ ebc.qconfig = torch.quantization.QConfig(
167
+ activation=torch.quantization.PlaceholderObserver.with_args(
168
+ dtype=torch.qint8
169
+ ),
170
+ weight=torch.quantization.PlaceholderObserver.with_args(dtype=torch.qint8),
171
+ )
172
+
173
+ qebc = QuantEmbeddingBagCollection.from_float(ebc)
174
+ quantized_embeddings = qebc(features)
175
+ """
176
+
177
+ def __init__(
178
+ self,
179
+ table_name_to_quantized_weights: Dict[str, Tuple[Tensor, Tensor]],
180
+ embedding_configs: List[EmbeddingBagConfig],
181
+ is_weighted: bool,
182
+ device: torch.device,
183
+ output_dtype: torch.dtype = torch.float,
184
+ ) -> None:
185
+ super().__init__()
186
+ self._is_weighted = is_weighted
187
+ self._embedding_bag_configs: List[EmbeddingBagConfig] = embedding_configs
188
+ self.embedding_bags: nn.ModuleList = nn.ModuleList()
189
+ self._lengths_per_embedding: List[int] = []
190
+ self._output_dtype = output_dtype
191
+ table_names = set()
192
+ for emb_config in self._embedding_bag_configs:
193
+ if emb_config.name in table_names:
194
+ raise ValueError(f"Duplicate table name {emb_config.name}")
195
+ table_names.add(emb_config.name)
196
+ emb_module = IntNBitTableBatchedEmbeddingBagsCodegen(
197
+ embedding_specs=[
198
+ (
199
+ "",
200
+ emb_config.num_embeddings,
201
+ emb_config.embedding_dim,
202
+ data_type_to_sparse_type(emb_config.data_type),
203
+ EmbeddingLocation.HOST
204
+ if device.type == "cpu"
205
+ else EmbeddingLocation.DEVICE,
206
+ )
207
+ ],
208
+ pooling_mode=pooling_type_to_pooling_mode(emb_config.pooling),
209
+ weight_lists=[table_name_to_quantized_weights[emb_config.name]],
210
+ device=device,
211
+ output_dtype=data_type_to_sparse_type(dtype_to_data_type(output_dtype)),
212
+ row_alignment=16,
213
+ )
214
+ self.embedding_bags.append(emb_module)
215
+ if not emb_config.feature_names:
216
+ emb_config.feature_names = [emb_config.name]
217
+ self._lengths_per_embedding.extend(
218
+ len(emb_config.feature_names) * [emb_config.embedding_dim]
219
+ )
220
+
221
+ self._embedding_names: List[str] = [
222
+ embedding
223
+ for embeddings in get_embedding_names_by_table(embedding_configs)
224
+ for embedding in embeddings
225
+ ]
226
+
227
+ def forward(
228
+ self,
229
+ features: KeyedJaggedTensor,
230
+ ) -> KeyedTensor:
231
+ pooled_embeddings: List[Tensor] = []
232
+ length_per_key: List[int] = []
233
+ feature_dict = features.to_dict()
234
+ for emb_config, emb_module in zip(
235
+ self._embedding_bag_configs, self.embedding_bags
236
+ ):
237
+ for feature_name in emb_config.feature_names:
238
+ f = feature_dict[feature_name]
239
+ values = f.values()
240
+ offsets = f.offsets()
241
+ pooled_embeddings.append(
242
+ emb_module(
243
+ indices=values.int(),
244
+ offsets=offsets.int(),
245
+ per_sample_weights=f.weights() if self._is_weighted else None,
246
+ )
247
+ )
248
+
249
+ length_per_key.append(emb_config.embedding_dim)
250
+
251
+ return KeyedTensor(
252
+ keys=self._embedding_names,
253
+ values=torch.cat(pooled_embeddings, dim=1),
254
+ length_per_key=self._lengths_per_embedding,
255
+ )
256
+
257
+ # pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
258
+ def state_dict(
259
+ self,
260
+ destination: Optional[Dict[str, Any]] = None,
261
+ prefix: str = "",
262
+ keep_vars: bool = False,
263
+ ) -> Dict[str, Any]:
264
+ if destination is None:
265
+ destination = OrderedDict()
266
+ # pyre-ignore [16]
267
+ destination._metadata = OrderedDict()
268
+ for emb_config, emb_module in zip(
269
+ self._embedding_bag_configs,
270
+ self.embedding_bags,
271
+ ):
272
+ (weight, _) = emb_module.split_embedding_weights(split_scale_shifts=False)[
273
+ 0
274
+ ]
275
+ destination[prefix + f"embedding_bags.{emb_config.name}.weight"] = weight
276
+ return destination
277
+
278
+ def named_buffers(
279
+ self, prefix: str = "", recurse: bool = True
280
+ ) -> Iterator[Tuple[str, nn.Parameter]]:
281
+ state_dict = self.state_dict(prefix=prefix, keep_vars=True)
282
+ for key, value in state_dict.items():
283
+ yield key, value
284
+
285
+ def _get_name(self) -> str:
286
+ return "QuantizedEmbeddingBagCollection"
287
+
288
+ @classmethod
289
+ def from_float(
290
+ cls, module: OriginalEmbeddingBagCollection
291
+ ) -> "EmbeddingBagCollection":
292
+ assert hasattr(
293
+ module, "qconfig"
294
+ ), "EmbeddingBagCollection input float module must have qconfig defined"
295
+
296
+ # pyre-ignore [16]
297
+ data_type = dtype_to_data_type(module.qconfig.weight().dtype)
298
+ embedding_bag_configs = copy.deepcopy(module.embedding_bag_configs)
299
+ for config in embedding_bag_configs:
300
+ config.data_type = data_type
301
+
302
+ table_name_to_quantized_weights: Dict[str, Tuple[Tensor, Tensor]] = {}
303
+ device = quantize_state_dict(module, table_name_to_quantized_weights, data_type)
304
+ return cls(
305
+ table_name_to_quantized_weights,
306
+ embedding_bag_configs,
307
+ module.is_weighted,
308
+ device=device,
309
+ # pyre-ignore [16]
310
+ output_dtype=module.qconfig.activation().dtype,
311
+ )
312
+
313
+ @property
314
+ def embedding_bag_configs(
315
+ self,
316
+ ) -> List[EmbeddingBagConfig]:
317
+ return self._embedding_bag_configs
318
+
319
+ @property
320
+ def is_weighted(self) -> bool:
321
+ return self._is_weighted
322
+
323
+ @property
324
+ def output_dtype(self) -> torch.dtype:
325
+ return self._output_dtype
326
+
327
+
328
+ class EmbeddingCollection(EmbeddingCollectionInterface):
329
+ """
330
+ EmbeddingCollection represents a collection of non-pooled embeddings.
331
+
332
+ It processes sparse data in the form of `KeyedJaggedTensor` of the form [F X B X L]
333
+ where:
334
+
335
+ * F: features (keys)
336
+ * B: batch size
337
+ * L: length of sparse features (variable)
338
+
339
+ and outputs `Dict[feature (key), JaggedTensor]`.
340
+ Each `JaggedTensor` contains values of the form (B * L) X D
341
+ where:
342
+
343
+ * B: batch size
344
+ * L: length of sparse features (jagged)
345
+ * D: each feature's (key's) embedding dimension and lengths are of the form L
346
+
347
+ Args:
348
+ tables (List[EmbeddingConfig]): list of embedding tables.
349
+ device (Optional[torch.device]): default compute device.
350
+ need_indices (bool): if we need to pass indices to the final lookup result dict
351
+
352
+ Example::
353
+
354
+ e1_config = EmbeddingConfig(
355
+ name="t1", embedding_dim=3, num_embeddings=10, feature_names=["f1"]
356
+ )
357
+ e2_config = EmbeddingConfig(
358
+ name="t2", embedding_dim=3, num_embeddings=10, feature_names=["f2"]
359
+ )
360
+
361
+ ec = EmbeddingCollection(tables=[e1_config, e2_config])
362
+
363
+ # 0 1 2 <-- batch
364
+ # 0 [0,1] None [2]
365
+ # 1 [3] [4] [5,6,7]
366
+ # ^
367
+ # feature
368
+
369
+ features = KeyedJaggedTensor.from_offsets_sync(
370
+ keys=["f1", "f2"],
371
+ values=torch.tensor([0, 1, 2, 3, 4, 5, 6, 7]),
372
+ offsets=torch.tensor([0, 2, 2, 3, 4, 5, 8]),
373
+ )
374
+ feature_embeddings = ec(features)
375
+ print(feature_embeddings['f2'].values())
376
+ tensor([[-0.2050, 0.5478, 0.6054],
377
+ [ 0.7352, 0.3210, -3.0399],
378
+ [ 0.1279, -0.1756, -0.4130],
379
+ [ 0.7519, -0.4341, -0.0499],
380
+ [ 0.9329, -1.0697, -0.8095]], grad_fn=<EmbeddingBackward>)
381
+ """
382
+
383
+ def __init__( # noqa C901
384
+ self,
385
+ table_name_to_quantized_weights: Dict[str, Tuple[Tensor, Tensor]],
386
+ tables: List[EmbeddingConfig],
387
+ device: torch.device,
388
+ need_indices: bool = False,
389
+ output_dtype: torch.dtype = torch.float,
390
+ ) -> None:
391
+ super().__init__()
392
+ self.embeddings: nn.ModuleList = nn.ModuleList()
393
+ self._embedding_configs = tables
394
+ self._embedding_dim: int = -1
395
+ self._need_indices: bool = need_indices
396
+ self._output_dtype = output_dtype
397
+ table_names = set()
398
+ for config in tables:
399
+ if config.name in table_names:
400
+ raise ValueError(f"Duplicate table name {config.name}")
401
+ table_names.add(config.name)
402
+ self._embedding_dim = (
403
+ config.embedding_dim if self._embedding_dim < 0 else self._embedding_dim
404
+ )
405
+ if self._embedding_dim != config.embedding_dim:
406
+ raise ValueError(
407
+ "All tables in a EmbeddingCollection are required to have same embedding dimension."
408
+ )
409
+ self.embeddings.append(
410
+ IntNBitTableBatchedEmbeddingBagsCodegen(
411
+ embedding_specs=[
412
+ (
413
+ "",
414
+ config.num_embeddings,
415
+ config.embedding_dim,
416
+ data_type_to_sparse_type(config.data_type),
417
+ EmbeddingLocation.HOST
418
+ if device.type == "cpu"
419
+ else EmbeddingLocation.DEVICE,
420
+ )
421
+ ],
422
+ pooling_mode=PoolingMode.NONE,
423
+ weight_lists=[table_name_to_quantized_weights[config.name]],
424
+ device=device,
425
+ output_dtype=data_type_to_sparse_type(
426
+ dtype_to_data_type(output_dtype)
427
+ ),
428
+ row_alignment=16,
429
+ )
430
+ )
431
+ if not config.feature_names:
432
+ config.feature_names = [config.name]
433
+
434
+ self._embedding_names_by_table: List[List[str]] = get_embedding_names_by_table(
435
+ tables
436
+ )
437
+
438
+ def forward(
439
+ self,
440
+ features: KeyedJaggedTensor,
441
+ ) -> Dict[str, JaggedTensor]:
442
+ """
443
+ Args:
444
+ features (KeyedJaggedTensor): KJT of form [F X B X L].
445
+
446
+ Returns:
447
+ Dict[str, JaggedTensor]
448
+ """
449
+
450
+ feature_embeddings: Dict[str, JaggedTensor] = {}
451
+ jt_dict: Dict[str, JaggedTensor] = features.to_dict()
452
+ for config, embedding_names, emb_module in zip(
453
+ self._embedding_configs,
454
+ self._embedding_names_by_table,
455
+ self.embeddings,
456
+ ):
457
+ for feature_name, embedding_name in zip(
458
+ config.feature_names, embedding_names
459
+ ):
460
+ f = jt_dict[feature_name]
461
+ values = f.values()
462
+ offsets = f.offsets()
463
+ lookup = emb_module(
464
+ indices=values.int(),
465
+ offsets=offsets.int(),
466
+ )
467
+ feature_embeddings[embedding_name] = JaggedTensor(
468
+ values=lookup,
469
+ lengths=f.lengths(),
470
+ weights=f.values() if self.need_indices else None,
471
+ )
472
+ return feature_embeddings
473
+
474
+ # pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
475
+ def state_dict(
476
+ self,
477
+ destination: Optional[Dict[str, Any]] = None,
478
+ prefix: str = "",
479
+ keep_vars: bool = False,
480
+ ) -> Dict[str, Any]:
481
+ if destination is None:
482
+ destination = OrderedDict()
483
+ # pyre-ignore [16]
484
+ destination._metadata = OrderedDict()
485
+ for emb_config, emb_module in zip(
486
+ self.embedding_configs,
487
+ self.embeddings,
488
+ ):
489
+ (weight, _) = emb_module.split_embedding_weights(split_scale_shifts=False)[
490
+ 0
491
+ ]
492
+ destination[prefix + f"embeddings.{emb_config.name}.weight"] = weight
493
+ return destination
494
+
495
+ @classmethod
496
+ def from_float(cls, module: OriginalEmbeddingCollection) -> "EmbeddingCollection":
497
+ assert hasattr(
498
+ module, "qconfig"
499
+ ), "EmbeddingCollection input float module must have qconfig defined"
500
+
501
+ # pyre-ignore [16]
502
+ data_type = dtype_to_data_type(module.qconfig.weight().dtype)
503
+ tables = copy.deepcopy(module.embedding_configs)
504
+ for config in tables:
505
+ config.data_type = data_type
506
+
507
+ table_name_to_quantized_weights: Dict[str, Tuple[Tensor, Tensor]] = {}
508
+ device = quantize_state_dict(module, table_name_to_quantized_weights, data_type)
509
+
510
+ return cls(
511
+ table_name_to_quantized_weights,
512
+ tables,
513
+ device=device,
514
+ need_indices=module.need_indices,
515
+ )
516
+
517
+ def named_buffers(
518
+ self, prefix: str = "", recurse: bool = True
519
+ ) -> Iterator[Tuple[str, nn.Parameter]]:
520
+ state_dict = self.state_dict(prefix=prefix, keep_vars=True)
521
+ for key, value in state_dict.items():
522
+ yield key, value
523
+
524
+ def _get_name(self) -> str:
525
+ return "QuantizedEmbeddingCollection"
526
+
527
+ @property
528
+ def need_indices(self) -> bool:
529
+ return self._need_indices
530
+
531
+ @property
532
+ def embedding_dim(self) -> int:
533
+ return self._embedding_dim
534
+
535
+ @property
536
+ def embedding_configs(self) -> List[EmbeddingConfig]:
537
+ return self._embedding_configs
538
+
539
+ @property
540
+ def embedding_names_by_table(self) -> List[List[str]]:
541
+ return self._embedding_names_by_table
542
+
543
+ @property
544
+ def output_dtype(self) -> torch.dtype:
545
+ return self._output_dtype
@@ -0,0 +1,33 @@
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 Jagged Tensors
9
+
10
+ It has 3 classes: JaggedTensor, KeyedJaggedTensor, KeyedTensor.
11
+
12
+ JaggedTensor
13
+
14
+ It represents an (optionally weighted) jagged tensor. A JaggedTensor is a
15
+ tensor with a jagged dimension which is dimension whose slices may be of
16
+ different lengths. See KeyedJaggedTensor docstring for full example and further
17
+ information.
18
+
19
+ KeyedJaggedTensor
20
+
21
+ KeyedJaggedTensor has additional "Key" information. Keyed on first dimesion,
22
+ and jagged on last dimension. Please refer to KeyedJaggedTensor docstring for full example and
23
+ further information.
24
+
25
+ KeyedTensor
26
+
27
+ KeyedTensor holds a concatenated list of dense tensors each of which can be accessed by a key.
28
+ Keyed dimension can be variable length (length_per_key). Common use cases uses include storage
29
+ of pooled embeddings of different dimensions. Please refer to KeyedTensor docstring for full
30
+ example and further information.
31
+ """
32
+
33
+ from . import jagged_tensor # noqa