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,174 @@
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
+ import math
11
+ import time
12
+ from collections import deque
13
+ from typing import Deque, Dict
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ from torchrec.metrics.metrics_namespace import (
18
+ compose_metric_key,
19
+ MetricName,
20
+ MetricNamespace,
21
+ MetricPrefix,
22
+ )
23
+
24
+ MAX_WINDOW_TS = 1_000_000
25
+
26
+
27
+ class ThroughputMetric(nn.Module):
28
+ """
29
+ The module to calculate throughput. Throughput is defined as the trained examples
30
+ across all ranks per second. For example, if the batch size on each rank is 512
31
+ and there are 32 ranks, throughput is 512 * 32 / time_to_train_one_step.
32
+
33
+ Args:
34
+ batch_size (int): batch size for the trainer
35
+ world_size (int): the number of trainers
36
+ window_seconds (int): Throughput use time-based window for window_throughput. This
37
+ argument specify the window size in seconds.
38
+ warmup_steps (int): the number of warmup batches. No Throughput will be calculated
39
+ before the warmup batches count reached.
40
+
41
+ Call Args:
42
+ Not supported.
43
+
44
+ Returns:
45
+ Not supported.
46
+
47
+ Example::
48
+
49
+ throughput = ThroughputMetric(
50
+ batch_size=128,
51
+ world_size=4,
52
+ window_seconds=100,
53
+ warmup_steps=100
54
+ )
55
+ """
56
+
57
+ _namespace: MetricNamespace
58
+ _metric_name: MetricName
59
+ _batch_examples: int
60
+ _window_seconds: int
61
+ _warmup_steps: int
62
+ _window_time_lapse_buffer: Deque[float]
63
+ _window_time_lapse: float
64
+ _previous_ts: float
65
+ _lifetime_throughput_key: str
66
+ _window_throughput_key: str
67
+ _total_examples_key: str
68
+ _steps: int
69
+
70
+ def __init__(
71
+ self,
72
+ *,
73
+ batch_size: int,
74
+ world_size: int,
75
+ window_seconds: int,
76
+ warmup_steps: int = 100,
77
+ ) -> None:
78
+ super().__init__()
79
+ self._namespace = MetricNamespace.THROUGHPUT
80
+ self._metric_name = MetricName.THROUGHPUT
81
+ if window_seconds < 1:
82
+ raise ValueError(
83
+ "window_seconds must be at least 1 to give window throughput "
84
+ "the minimum time window"
85
+ )
86
+ if warmup_steps < 1:
87
+ raise ValueError(
88
+ "warmup_steps must be at least 1 to give throughput a "
89
+ "reasonable begin time."
90
+ )
91
+
92
+ self._batch_examples = batch_size * world_size
93
+ self._window_seconds = window_seconds
94
+ self._warmup_steps = warmup_steps
95
+
96
+ self.register_buffer("total_examples", torch.tensor(0, dtype=torch.long))
97
+ self.register_buffer("warmup_examples", torch.tensor(0, dtype=torch.long))
98
+ self.register_buffer(
99
+ "time_lapse_after_warmup", torch.tensor(0, dtype=torch.double)
100
+ )
101
+
102
+ self._window_time_lapse_buffer = deque(maxlen=MAX_WINDOW_TS)
103
+ self._window_time_lapse = 0
104
+ self._previous_ts = 0
105
+
106
+ self._lifetime_throughput_key = compose_metric_key(
107
+ self._namespace,
108
+ str(self._namespace),
109
+ self._metric_name,
110
+ MetricPrefix.LIFETIME,
111
+ )
112
+ self._window_throughput_key = compose_metric_key(
113
+ self._namespace,
114
+ str(self._namespace),
115
+ self._metric_name,
116
+ MetricPrefix.WINDOW,
117
+ )
118
+ self._total_examples_key = compose_metric_key(
119
+ self._namespace,
120
+ str(self._namespace),
121
+ MetricName.TOTAL_EXAMPLES,
122
+ )
123
+
124
+ self._steps = 0
125
+
126
+ def _check_window(self) -> None:
127
+ while self._window_time_lapse > self._window_seconds:
128
+ self._window_time_lapse -= self._window_time_lapse_buffer.popleft()
129
+
130
+ def update(self) -> None:
131
+ ts = time.monotonic()
132
+ self._steps += 1
133
+ self.total_examples += self._batch_examples
134
+
135
+ if self._steps <= self._warmup_steps:
136
+ self.warmup_examples += self._batch_examples
137
+ if self._steps == self._warmup_steps:
138
+ self._previous_ts = ts
139
+ else:
140
+ time_lapse = ts - self._previous_ts
141
+ self.time_lapse_after_warmup += time_lapse
142
+ self._window_time_lapse += time_lapse
143
+ self._window_time_lapse_buffer.append(time_lapse)
144
+ self._check_window()
145
+ self._previous_ts = ts
146
+
147
+ def compute(self) -> Dict[str, torch.Tensor]:
148
+ ret = {self._total_examples_key: self.total_examples}
149
+ if self._steps > self._warmup_steps and (
150
+ not math.isclose(self.time_lapse_after_warmup.item(), 0)
151
+ ):
152
+ lifetime_throughput = (
153
+ self.total_examples - self.warmup_examples
154
+ ) / self.time_lapse_after_warmup
155
+ if not math.isclose(self._window_time_lapse, 0):
156
+ window_throughput = (
157
+ len(self._window_time_lapse_buffer)
158
+ * self._batch_examples
159
+ / self._window_time_lapse
160
+ )
161
+ else:
162
+ window_throughput = 0.0
163
+ if not math.isclose(lifetime_throughput.item(), 0):
164
+ ret.update(
165
+ {
166
+ self._lifetime_throughput_key: torch.tensor(
167
+ lifetime_throughput, dtype=torch.double
168
+ ),
169
+ self._window_throughput_key: torch.tensor(
170
+ window_throughput, dtype=torch.double
171
+ ),
172
+ }
173
+ )
174
+ return ret
@@ -0,0 +1,27 @@
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 Models
9
+
10
+ Torchrec provides the architecture for two popular recsys models;
11
+ `DeepFM <https://arxiv.org/pdf/1703.04247.pdf>`_ and `DLRM (Deep Learning Recommendation Model)
12
+ <https://arxiv.org/abs/1906.00091>`_.
13
+
14
+ Along with the overall model, the individual architectures of each layer are also
15
+ provided (e.g. `SparseArch`, `DenseArch`, `InteractionArch`, and `OverArch`).
16
+
17
+ Examples can be found within each model.
18
+
19
+ The following notation is used throughout the documentation for the models:
20
+
21
+ * F: number of sparse features
22
+ * D: embedding_dimension of sparse features
23
+ * B: batch size
24
+ * num_features: number of dense features
25
+ """
26
+
27
+ from . import deepfm, dlrm # noqa # noqa
@@ -0,0 +1,346 @@
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 List
9
+
10
+ import torch
11
+ from torch import nn
12
+ from torchrec import EmbeddingBagCollection, KeyedJaggedTensor
13
+ from torchrec.modules.deepfm import DeepFM, FactorizationMachine
14
+ from torchrec.sparse.jagged_tensor import KeyedTensor
15
+
16
+
17
+ class SparseArch(nn.Module):
18
+ """
19
+ Processes the sparse features of the DeepFMNN model. Does embedding lookups for all
20
+ EmbeddingBag and embedding features of each collection.
21
+
22
+ Args:
23
+ embedding_bag_collection (EmbeddingBagCollection): represents a collection of
24
+ pooled embeddings.
25
+
26
+ Example::
27
+
28
+ eb1_config = EmbeddingBagConfig(
29
+ name="t1", embedding_dim=3, num_embeddings=10, feature_names=["f1"]
30
+ )
31
+ eb2_config = EmbeddingBagConfig(
32
+ name="t2", embedding_dim=4, num_embeddings=10, feature_names=["f2"]
33
+ )
34
+
35
+ ebc = EmbeddingBagCollection(tables=[eb1_config, eb2_config])
36
+
37
+ # 0 1 2 <-- batch
38
+ # 0 [0,1] None [2]
39
+ # 1 [3] [4] [5,6,7]
40
+ # ^
41
+ # feature
42
+ features = KeyedJaggedTensor.from_offsets_sync(
43
+ keys=["f1", "f2"],
44
+ values=torch.tensor([0, 1, 2, 3, 4, 5, 6, 7]),
45
+ offsets=torch.tensor([0, 2, 2, 3, 4, 5, 8]),
46
+ )
47
+
48
+ sparse_arch(features)
49
+ """
50
+
51
+ def __init__(self, embedding_bag_collection: EmbeddingBagCollection) -> None:
52
+ super().__init__()
53
+ self.embedding_bag_collection: EmbeddingBagCollection = embedding_bag_collection
54
+
55
+ def forward(
56
+ self,
57
+ features: KeyedJaggedTensor,
58
+ ) -> KeyedTensor:
59
+ """
60
+ Args:
61
+ features (KeyedJaggedTensor):
62
+
63
+ Returns:
64
+ KeyedJaggedTensor: an output KJT of size F * D X B.
65
+ """
66
+ return self.embedding_bag_collection(features)
67
+
68
+
69
+ class DenseArch(nn.Module):
70
+ """
71
+ Processes the dense features of DeepFMNN model. Output layer is sized to
72
+ the embedding_dimension of the EmbeddingBagCollection embeddings.
73
+
74
+ Args:
75
+ in_features (int): dimensionality of the dense input features.
76
+ hidden_layer_size (int): sizes of the hidden layers in the DenseArch.
77
+ embedding_dim (int): the same size of the embedding_dimension of sparseArch.
78
+ device (torch.device): default compute device.
79
+
80
+ Example::
81
+
82
+ B = 20
83
+ D = 3
84
+ in_features = 10
85
+ dense_arch = DenseArch(in_features=10, hidden_layer_size=10, embedding_dim=D)
86
+ dense_embedded = dense_arch(torch.rand((B, 10)))
87
+ """
88
+
89
+ def __init__(
90
+ self,
91
+ in_features: int,
92
+ hidden_layer_size: int,
93
+ embedding_dim: int,
94
+ ) -> None:
95
+ super().__init__()
96
+ self.model: nn.Module = nn.Sequential(
97
+ nn.Linear(in_features, hidden_layer_size),
98
+ nn.ReLU(),
99
+ nn.Linear(hidden_layer_size, embedding_dim),
100
+ nn.ReLU(),
101
+ )
102
+
103
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
104
+ """
105
+ Args:
106
+ features (torch.Tensor): size B X `num_features`.
107
+
108
+ Returns:
109
+ torch.Tensor: an output tensor of size B X D.
110
+ """
111
+ return self.model(features)
112
+
113
+
114
+ class FMInteractionArch(nn.Module):
115
+ """
116
+ Processes the output of both `SparseArch` (sparse_features) and `DenseArch`
117
+ (dense_features) and apply the general DeepFM interaction according to the
118
+ external source of DeepFM paper: https://arxiv.org/pdf/1703.04247.pdf
119
+
120
+ The output dimension is expected to be a cat of `dense_features`, D.
121
+
122
+ Args:
123
+ fm_in_features (int): the input dimension of `dense_module` in DeepFM. For
124
+ example, if the input embeddings is [randn(3, 2, 3), randn(3, 4, 5)], then
125
+ the `fm_in_features` should be: 2 * 3 + 4 * 5.
126
+ sparse_feature_names (List[str]): length of F.
127
+ deep_fm_dimension (int): output of the deep interaction (DI) in the DeepFM arch.
128
+
129
+ Example::
130
+
131
+ D = 3
132
+ B = 10
133
+ keys = ["f1", "f2"]
134
+ F = len(keys)
135
+ fm_inter_arch = FMInteractionArch(sparse_feature_names=keys)
136
+ dense_features = torch.rand((B, D))
137
+ sparse_features = KeyedTensor(
138
+ keys=keys,
139
+ length_per_key=[D, D],
140
+ values=torch.rand((B, D * F)),
141
+ )
142
+ cat_fm_output = fm_inter_arch(dense_features, sparse_features)
143
+ """
144
+
145
+ def __init__(
146
+ self,
147
+ fm_in_features: int,
148
+ sparse_feature_names: List[str],
149
+ deep_fm_dimension: int,
150
+ ) -> None:
151
+ super().__init__()
152
+ self.sparse_feature_names: List[str] = sparse_feature_names
153
+ self.deep_fm = DeepFM(
154
+ dense_module=nn.Sequential(
155
+ nn.Linear(fm_in_features, deep_fm_dimension),
156
+ nn.ReLU(),
157
+ )
158
+ )
159
+ self.fm = FactorizationMachine()
160
+
161
+ def forward(
162
+ self, dense_features: torch.Tensor, sparse_features: KeyedTensor
163
+ ) -> torch.Tensor:
164
+ """
165
+ Args:
166
+ dense_features (torch.Tensor): tensor of size B X D.
167
+ sparse_features (KeyedJaggedTensor): KJT of size F * D X B.
168
+
169
+ Returns:
170
+ torch.Tensor: an output tensor of size B X (D + DI + 1).
171
+ """
172
+ if len(self.sparse_feature_names) == 0:
173
+ return dense_features
174
+
175
+ tensor_list: List[torch.Tensor] = [dense_features]
176
+ # dense/sparse interaction
177
+ # size B X F
178
+ for feature_name in self.sparse_feature_names:
179
+ tensor_list.append(sparse_features[feature_name])
180
+
181
+ deep_interaction = self.deep_fm(tensor_list)
182
+ fm_interaction = self.fm(tensor_list)
183
+
184
+ return torch.cat([dense_features, deep_interaction, fm_interaction], dim=1)
185
+
186
+
187
+ class OverArch(nn.Module):
188
+ """
189
+ Final Arch - simple MLP. The output is just one target.
190
+
191
+ Args:
192
+ in_features (int): the output dimension of the interaction arch.
193
+
194
+ Example::
195
+
196
+ B = 20
197
+ over_arch = OverArch()
198
+ logits = over_arch(torch.rand((B, 10)))
199
+ """
200
+
201
+ def __init__(self, in_features: int) -> None:
202
+ super().__init__()
203
+ self.model: nn.Module = nn.Sequential(
204
+ nn.Linear(in_features, 1),
205
+ nn.Sigmoid(),
206
+ )
207
+
208
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
209
+ """
210
+ Args:
211
+ features (torch.Tensor):
212
+
213
+ Returns:
214
+ torch.Tensor: an output tensor of size B X 1.
215
+ """
216
+ return self.model(features)
217
+
218
+
219
+ class SimpleDeepFMNN(nn.Module):
220
+ """
221
+ Basic recsys module with DeepFM arch. Processes sparse features by
222
+ learning pooled embeddings for each feature. Learns the relationship between
223
+ dense features and sparse features by projecting dense features into the same
224
+ embedding space. Learns the interaction among those dense and sparse features
225
+ by deep_fm proposed in this paper: https://arxiv.org/pdf/1703.04247.pdf
226
+
227
+ The module assumes all sparse features have the same embedding dimension
228
+ (i.e, each `EmbeddingBagConfig` uses the same embedding_dim)
229
+
230
+ The following notation is used throughout the documentation for the models:
231
+
232
+ * F: number of sparse features
233
+ * D: embedding_dimension of sparse features
234
+ * B: batch size
235
+ * num_features: number of dense features
236
+
237
+ Args:
238
+ num_dense_features (int): the number of input dense features.
239
+ embedding_bag_collection (EmbeddingBagCollection): collection of embedding bags
240
+ used to define `SparseArch`.
241
+ hidden_layer_size (int): the hidden layer size used in dense module.
242
+ deep_fm_dimension (int): the output layer size used in `deep_fm`'s deep
243
+ interaction module.
244
+
245
+ Example::
246
+
247
+ B = 2
248
+ D = 8
249
+
250
+ eb1_config = EmbeddingBagConfig(
251
+ name="t1", embedding_dim=D, num_embeddings=100, feature_names=["f1", "f3"]
252
+ )
253
+ eb2_config = EmbeddingBagConfig(
254
+ name="t2",
255
+ embedding_dim=D,
256
+ num_embeddings=100,
257
+ feature_names=["f2"],
258
+ )
259
+
260
+ ebc = EmbeddingBagCollection(tables=[eb1_config, eb2_config])
261
+ sparse_nn = SimpleDeepFMNN(
262
+ embedding_bag_collection=ebc, hidden_layer_size=20, over_embedding_dim=5
263
+ )
264
+
265
+ features = torch.rand((B, 100))
266
+
267
+ # 0 1
268
+ # 0 [1,2] [4,5]
269
+ # 1 [4,3] [2,9]
270
+ # ^
271
+ # feature
272
+ sparse_features = KeyedJaggedTensor.from_offsets_sync(
273
+ keys=["f1", "f3"],
274
+ values=torch.tensor([1, 2, 4, 5, 4, 3, 2, 9]),
275
+ offsets=torch.tensor([0, 2, 4, 6, 8]),
276
+ )
277
+
278
+ logits = sparse_nn(
279
+ dense_features=features,
280
+ sparse_features=sparse_features,
281
+ )
282
+ """
283
+
284
+ def __init__(
285
+ self,
286
+ num_dense_features: int,
287
+ embedding_bag_collection: EmbeddingBagCollection,
288
+ hidden_layer_size: int,
289
+ deep_fm_dimension: int,
290
+ ) -> None:
291
+ super().__init__()
292
+ assert (
293
+ len(embedding_bag_collection.embedding_bag_configs) > 0
294
+ ), "At least one embedding bag is required"
295
+ for i in range(1, len(embedding_bag_collection.embedding_bag_configs)):
296
+ conf_prev = embedding_bag_collection.embedding_bag_configs[i - 1]
297
+ conf = embedding_bag_collection.embedding_bag_configs[i]
298
+ assert (
299
+ conf_prev.embedding_dim == conf.embedding_dim
300
+ ), "All EmbeddingBagConfigs must have the same dimension"
301
+ embedding_dim: int = embedding_bag_collection.embedding_bag_configs[
302
+ 0
303
+ ].embedding_dim
304
+
305
+ feature_names = []
306
+
307
+ fm_in_features = embedding_dim
308
+ for conf in embedding_bag_collection.embedding_bag_configs:
309
+ for feat in conf.feature_names:
310
+ feature_names.append(feat)
311
+ fm_in_features += conf.embedding_dim
312
+
313
+ self.sparse_arch = SparseArch(embedding_bag_collection)
314
+ self.dense_arch = DenseArch(
315
+ in_features=num_dense_features,
316
+ hidden_layer_size=hidden_layer_size,
317
+ embedding_dim=embedding_dim,
318
+ )
319
+ self.inter_arch = FMInteractionArch(
320
+ fm_in_features=fm_in_features,
321
+ sparse_feature_names=feature_names,
322
+ deep_fm_dimension=deep_fm_dimension,
323
+ )
324
+ over_in_features = embedding_dim + deep_fm_dimension + 1
325
+ self.over_arch = OverArch(over_in_features)
326
+
327
+ def forward(
328
+ self,
329
+ dense_features: torch.Tensor,
330
+ sparse_features: KeyedJaggedTensor,
331
+ ) -> torch.Tensor:
332
+ """
333
+ Args:
334
+ dense_features (torch.Tensor): the dense features.
335
+ sparse_features (KeyedJaggedTensor): the sparse features.
336
+
337
+ Returns:
338
+ torch.Tensor: logits with size B X 1.
339
+ """
340
+ embedded_dense = self.dense_arch(dense_features)
341
+ embedded_sparse = self.sparse_arch(sparse_features)
342
+ concatenated_dense = self.inter_arch(
343
+ dense_features=embedded_dense, sparse_features=embedded_sparse
344
+ )
345
+ logits = self.over_arch(concatenated_dense)
346
+ return logits