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,192 @@
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, Optional
9
+
10
+ import click
11
+ import faiss # @manual=//faiss/python:pyfaiss_gpu
12
+ import faiss.contrib.torch_utils # @manual=//faiss/contrib:faiss_contrib_gpu
13
+ import torch
14
+ from torchrec import inference as trec_infer
15
+
16
+ from torchrec.datasets.movielens import DEFAULT_RATINGS_COLUMN_NAMES
17
+ from torchrec.distributed.embedding_types import EmbeddingComputeKernel
18
+ from torchrec.distributed.model_parallel import DistributedModelParallel
19
+ from torchrec.distributed.planner.types import ParameterConstraints
20
+ from torchrec.distributed.types import ShardingEnv, ShardingType
21
+ from torchrec.modules.embedding_configs import EmbeddingBagConfig
22
+ from torchrec.modules.embedding_modules import EmbeddingBagCollection
23
+ from torchrec.sparse.jagged_tensor import KeyedJaggedTensor
24
+
25
+
26
+ # OSS import
27
+ try:
28
+ # pyre-ignore[21]
29
+ # @manual=//torchrec/github/examples/retrieval/data:dataloader
30
+ from data.dataloader import get_dataloader
31
+
32
+ # pyre-ignore[21]
33
+ # @manual=//torchrec/github/examples/retrieval:knn_index
34
+ from knn_index import get_index
35
+
36
+ # pyre-ignore[21]
37
+ # @manual=//torchrec/github/examples/retrieval/modules:two_tower
38
+ from modules.two_tower import ( # noqa F811
39
+ convert_TwoTower_to_TwoTowerRetrieval,
40
+ TwoTowerRetrieval,
41
+ )
42
+ except ImportError:
43
+ pass
44
+
45
+ # internal import
46
+ try:
47
+ from .data.dataloader import get_dataloader # noqa F811
48
+ from .knn_index import get_index # noqa F811
49
+ from .modules.two_tower import ( # noqa F811
50
+ convert_TwoTower_to_TwoTowerRetrieval,
51
+ TwoTowerRetrieval,
52
+ )
53
+ except ImportError:
54
+ pass
55
+
56
+
57
+ @click.command()
58
+ @click.option(
59
+ "--load_dir",
60
+ type=click.STRING,
61
+ default=None,
62
+ help="Directory to load model and faiss index from. If None, uses random data",
63
+ )
64
+ def main(load_dir: Optional[str]) -> None:
65
+ infer(load_dir=load_dir)
66
+
67
+
68
+ def infer(
69
+ num_embeddings: int = 1024 * 1024,
70
+ embedding_dim: int = 64,
71
+ layer_sizes: Optional[List[int]] = None,
72
+ num_centroids: int = 100,
73
+ k: int = 100,
74
+ num_subquantizers: int = 8,
75
+ bits_per_code: int = 8,
76
+ num_probe: int = 8,
77
+ model_device_idx: int = 0,
78
+ faiss_device_idx: int = 0,
79
+ batch_size: int = 32,
80
+ load_dir: Optional[str] = None,
81
+ ) -> None:
82
+ """
83
+ Loads the serialized model and FAISS index from `two_tower_train.py`.
84
+ A `TwoTowerRetrieval` model is instantiated, which wraps the `KNNIndex`, the query (user) tower and the candidate item (movie) tower inside an `nn.Module`.
85
+ The retreival model is quantized using [`torchrec.quant`](https://pytorch.org/torchrec/torchrec.quant.html).
86
+ The serialized `TwoTower` model weights trained before are converted into `TwoTowerRetrieval` which are loaded into the retrieval model.
87
+ The seralized trained FAISS index is also loaded.
88
+ The entire retreival model can be queried with a batch of candidate (user) ids and returns logits which can be used in ranking.
89
+
90
+ Args:
91
+ num_embeddings (int): The number of embeddings the embedding table
92
+ embedding_dim (int): embedding dimension of both embedding tables
93
+ layer_sizes (str): Comma separated list representing layer sizes of the MLP. Last size is the final embedding size
94
+ num_centroids (int): The number of centroids (Voronoi cells)
95
+ k (int): The number of nearest neighbors to retrieve
96
+ num_subquantizers (int): The number of subquanitizers in Product Quantization (PQ) compression of subvectors
97
+ bits_per_code (int): The number of bits for each subvector in Product Quantization (PQ)
98
+ num_probe (int): The number of centroids (Voronoi cells) to probe. Must be <= num_centroids. Sweeping powers of 2 for nprobe and picking one of those based on recall statistics (e.g., 1, 2, 4, 8, ..,) is typically done.
99
+ model_device_idx (int): device index to place model on
100
+ faiss_device_idx (int): device index to place FAISS index on
101
+ batch_size (int): batch_size of the random batch used to query Retrieval model at the end of the script
102
+ load_dir (Optional[str]): Directory to load model and faiss index from. If None, uses random data
103
+ """
104
+ if layer_sizes is None:
105
+ layer_sizes = [128, 64]
106
+ assert torch.cuda.is_available(), "This example requires a GPU"
107
+
108
+ device: torch.device = torch.device(f"cuda:{model_device_idx}")
109
+ torch.cuda.set_device(device)
110
+
111
+ two_tower_column_names = DEFAULT_RATINGS_COLUMN_NAMES[:2]
112
+ ebcs = []
113
+ for feature_name in two_tower_column_names:
114
+ config = EmbeddingBagConfig(
115
+ name=f"t_{feature_name}",
116
+ embedding_dim=embedding_dim,
117
+ num_embeddings=num_embeddings,
118
+ feature_names=[feature_name],
119
+ )
120
+ ebcs.append(
121
+ EmbeddingBagCollection(
122
+ tables=[config],
123
+ device=torch.device("meta"),
124
+ )
125
+ )
126
+
127
+ retrieval_sd = None
128
+ if load_dir is not None:
129
+ load_dir = load_dir.rstrip("/")
130
+ # pyre-ignore[16]
131
+ index = faiss.index_cpu_to_gpu(
132
+ # pyre-ignore[16]
133
+ faiss.StandardGpuResources(),
134
+ faiss_device_idx,
135
+ # pyre-ignore[16]
136
+ faiss.read_index(f"{load_dir}/faiss.index"),
137
+ )
138
+ two_tower_sd = torch.load(f"{load_dir}/model.pt")
139
+ retrieval_sd = convert_TwoTower_to_TwoTowerRetrieval(
140
+ two_tower_sd,
141
+ [f"t_{two_tower_column_names[0]}"],
142
+ [f"t_{two_tower_column_names[1]}"],
143
+ )
144
+ else:
145
+ embeddings = torch.rand((num_embeddings, embedding_dim)).to(
146
+ torch.device(f"cuda:{faiss_device_idx}")
147
+ )
148
+ index = get_index(
149
+ embedding_dim=embedding_dim,
150
+ num_centroids=num_centroids,
151
+ num_probe=num_probe,
152
+ num_subquantizers=num_subquantizers,
153
+ bits_per_code=bits_per_code,
154
+ device=torch.device(f"cuda:{faiss_device_idx}"),
155
+ )
156
+ index.train(embeddings)
157
+ index.add(embeddings)
158
+
159
+ retrieval_model = TwoTowerRetrieval(index, ebcs[0], ebcs[1], layer_sizes, k, device)
160
+
161
+ constraints = {}
162
+ for feature_name in two_tower_column_names:
163
+ constraints[f"t_{feature_name}"] = ParameterConstraints(
164
+ sharding_types=[ShardingType.TABLE_WISE.value],
165
+ compute_kernels=[EmbeddingComputeKernel.QUANT.value],
166
+ )
167
+
168
+ quant_model = trec_infer.modules.quantize_embeddings(
169
+ retrieval_model, dtype=torch.qint8, inplace=True
170
+ )
171
+
172
+ dmp = DistributedModelParallel(
173
+ module=quant_model,
174
+ device=device,
175
+ env=ShardingEnv.from_local(world_size=2, rank=model_device_idx),
176
+ init_data_parallel=False,
177
+ )
178
+ if retrieval_sd is not None:
179
+ dmp.load_state_dict(retrieval_sd)
180
+
181
+ # query with random batch
182
+ values = torch.randint(0, num_embeddings, (batch_size,), device=device)
183
+ batch = KeyedJaggedTensor(
184
+ keys=[two_tower_column_names[0]],
185
+ values=values,
186
+ lengths=torch.tensor([1] * batch_size, device=device),
187
+ )
188
+ dmp(batch)
189
+
190
+
191
+ if __name__ == "__main__":
192
+ main()
@@ -0,0 +1,253 @@
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 os
11
+ from typing import cast, List, Optional
12
+
13
+ import click
14
+
15
+ import faiss # @manual=//faiss/python:pyfaiss_gpu
16
+ import faiss.contrib.torch_utils # @manual=//faiss/contrib:faiss_contrib_gpu
17
+ import torch
18
+ from fbgemm_gpu.split_embedding_configs import EmbOptimType
19
+ from torch import distributed as dist, nn
20
+ from torchrec import inference as trec_infer
21
+ from torchrec.datasets.movielens import DEFAULT_RATINGS_COLUMN_NAMES
22
+ from torchrec.distributed import TrainPipelineSparseDist
23
+ from torchrec.distributed.embeddingbag import EmbeddingBagCollectionSharder
24
+ from torchrec.distributed.model_parallel import DistributedModelParallel
25
+ from torchrec.distributed.planner import EmbeddingShardingPlanner, Topology
26
+ from torchrec.distributed.types import ModuleSharder
27
+ from torchrec.inference.state_dict_transform import (
28
+ state_dict_gather,
29
+ state_dict_to_device,
30
+ )
31
+ from torchrec.modules.embedding_configs import EmbeddingBagConfig
32
+ from torchrec.modules.embedding_modules import EmbeddingBagCollection
33
+ from torchrec.optim.keyed import KeyedOptimizerWrapper
34
+ from torchrec.sparse.jagged_tensor import KeyedJaggedTensor
35
+
36
+
37
+ # OSS import
38
+ try:
39
+ # pyre-ignore[21]
40
+ # @manual=//torchrec/github/examples/retrieval/data:dataloader
41
+ from data.dataloader import get_dataloader
42
+
43
+ # pyre-ignore[21]
44
+ # @manual=//torchrec/github/examples/retrieval:knn_index
45
+ from knn_index import get_index
46
+
47
+ # pyre-ignore[21]
48
+ # @manual=//torchrec/github/examples/retrieval/modules:two_tower
49
+ from modules.two_tower import TwoTower, TwoTowerTrainTask
50
+ except ImportError:
51
+ pass
52
+
53
+ # internal import
54
+ try:
55
+ from .data.dataloader import get_dataloader # noqa F811
56
+ from .knn_index import get_index # noqa F811
57
+ from .modules.two_tower import TwoTower, TwoTowerTrainTask # noqa F811
58
+ except ImportError:
59
+ pass
60
+
61
+
62
+ @click.command()
63
+ @click.option(
64
+ "--save_dir",
65
+ type=click.STRING,
66
+ default=None,
67
+ help="Directory to save model and faiss index. If None, nothing is saved",
68
+ )
69
+ def main(save_dir: Optional[str]) -> None:
70
+ train(save_dir=save_dir)
71
+
72
+
73
+ def train(
74
+ num_embeddings: int = 1024**2,
75
+ embedding_dim: int = 64,
76
+ layer_sizes: Optional[List[int]] = None,
77
+ learning_rate: float = 0.01,
78
+ batch_size: int = 32,
79
+ num_iterations: int = 100,
80
+ num_centroids: int = 100,
81
+ num_subquantizers: int = 8,
82
+ bits_per_code: int = 8,
83
+ num_probe: int = 8,
84
+ save_dir: Optional[str] = None,
85
+ ) -> None:
86
+ """
87
+ Trains a simple Two Tower (UV) model, which is a simplified version of [A Dual Augmented Two-tower Model for Online Large-scale Recommendation](https://dlp-kdd.github.io/assets/pdf/DLP-KDD_2021_paper_4.pdf).
88
+ Torchrec is used to shard the model, and is pipelined so that dataloading, data-parallel to model-parallel comms, and forward/backward are overlapped.
89
+ It is trained on random data in the format of [MovieLens 20M](https://grouplens.org/datasets/movielens/20m/) dataset in SPMD fashion.
90
+ The distributed model is gathered to CPU.
91
+ The item (movie) towers embeddings are used to train a FAISS [IVFPQ](https://github.com/facebookresearch/faiss/wiki/Lower-memory-footprint) index, which is serialized.
92
+ The resulting `KNNIndex` can be queried with batched `torch.Tensor`, and will return the distances and indices for the approximate K nearest neighbors of the query embeddings. The model itself is also serialized.
93
+
94
+ Args:
95
+ num_embeddings (int): The number of embeddings the embedding table
96
+ embedding_dim (int): embedding dimension of both embedding tables
97
+ layer_sizes (List[int]): list representing layer sizes of the MLP. Last size is the final embedding size
98
+ learning_rate (float): learning_rate
99
+ batch_size (int): batch size to use for training
100
+ num_iterations (int): number of train batches
101
+ num_centroids (int): The number of centroids (Voronoi cells)
102
+ num_subquantizers (int): The number of subquanitizers in Product Quantization (PQ) compression of subvectors
103
+ bits_per_code (int): The number of bits for each subvector in Product Quantization (PQ)
104
+ num_probe (int): The number of centroids (Voronoi cells) to probe. Must be <= num_centroids. Sweeping powers of 2 for nprobe and picking one of those based on recall statistics (e.g., 1, 2, 4, 8, ..,) is typically done.
105
+ save_dir (Optional[str]): Directory to save model and faiss index. If None, nothing is saved
106
+ """
107
+ if layer_sizes is None:
108
+ layer_sizes = [128, 64]
109
+
110
+ rank = int(os.environ["LOCAL_RANK"])
111
+ world_size = int(os.environ["WORLD_SIZE"])
112
+ if torch.cuda.is_available():
113
+ device: torch.device = torch.device(f"cuda:{rank}")
114
+ backend = "nccl"
115
+ torch.cuda.set_device(device)
116
+ else:
117
+ device: torch.device = torch.device("cpu")
118
+ backend = "gloo"
119
+ dist.init_process_group(backend=backend)
120
+
121
+ two_tower_column_names = DEFAULT_RATINGS_COLUMN_NAMES[:2]
122
+ eb_configs = [
123
+ EmbeddingBagConfig(
124
+ name=f"t_{feature_name}",
125
+ embedding_dim=embedding_dim,
126
+ num_embeddings=num_embeddings,
127
+ feature_names=[feature_name],
128
+ )
129
+ for feature_name in two_tower_column_names
130
+ ]
131
+ embedding_bag_collection = EmbeddingBagCollection(
132
+ tables=eb_configs,
133
+ device=torch.device("meta"),
134
+ )
135
+ two_tower_model = TwoTower(
136
+ embedding_bag_collection=embedding_bag_collection,
137
+ layer_sizes=layer_sizes,
138
+ device=device,
139
+ )
140
+ two_tower_train_task = TwoTowerTrainTask(two_tower_model)
141
+
142
+ fused_params = {
143
+ "learning_rate": learning_rate,
144
+ "optimizer": EmbOptimType.ROWWISE_ADAGRAD,
145
+ }
146
+ sharders = cast(
147
+ List[ModuleSharder[nn.Module]],
148
+ [EmbeddingBagCollectionSharder(fused_params=fused_params)],
149
+ )
150
+
151
+ # TODO: move pg to the EmbeddingShardingPlanner (out of collective_plan) and make optional
152
+ # TODO: make Topology optional argument to EmbeddingShardingPlanner
153
+ # TODO: give collective_plan a default sharders
154
+ # TODO: once this is done, move defaults out of DMP and just get from ShardingPlan (eg _sharding_map should not exist - just use the plan)
155
+ plan = EmbeddingShardingPlanner(
156
+ topology=Topology(
157
+ world_size=world_size,
158
+ compute_device=device.type,
159
+ ),
160
+ ).collective_plan(
161
+ module=two_tower_model, sharders=sharders, pg=dist.GroupMember.WORLD
162
+ )
163
+ model = DistributedModelParallel(
164
+ module=two_tower_train_task,
165
+ device=device,
166
+ plan=plan,
167
+ )
168
+
169
+ optimizer = KeyedOptimizerWrapper(
170
+ dict(model.named_parameters()),
171
+ lambda params: torch.optim.Adam(params, lr=learning_rate),
172
+ )
173
+
174
+ # pyre-fixme[16]: Module `data` has no attribute `dataloader`.
175
+ dataloader = get_dataloader(
176
+ batch_size=batch_size,
177
+ num_embeddings=num_embeddings,
178
+ pin_memory=(backend == "nccl"),
179
+ )
180
+ dl_iterator = iter(dataloader)
181
+ train_pipeline = TrainPipelineSparseDist(
182
+ model,
183
+ optimizer,
184
+ device,
185
+ )
186
+
187
+ # Train model
188
+ for _ in range(num_iterations):
189
+ try:
190
+ train_pipeline.progress(dl_iterator)
191
+ except StopIteration:
192
+ break
193
+
194
+ checkpoint_pg = dist.new_group(backend="gloo")
195
+ # Copy sharded state_dict to CPU.
196
+ cpu_state_dict = state_dict_to_device(
197
+ model.state_dict(), pg=checkpoint_pg, device=torch.device("cpu")
198
+ )
199
+
200
+ ebc_cpu = EmbeddingBagCollection(
201
+ tables=eb_configs,
202
+ device=torch.device("meta"),
203
+ )
204
+ two_tower_cpu = TwoTower(
205
+ embedding_bag_collection=ebc_cpu,
206
+ layer_sizes=layer_sizes,
207
+ )
208
+ two_tower_train_cpu = TwoTowerTrainTask(two_tower_cpu)
209
+ if rank == 0:
210
+ two_tower_train_cpu = two_tower_train_cpu.to_empty(device="cpu")
211
+ state_dict_gather(cpu_state_dict, two_tower_train_cpu.state_dict())
212
+ dist.barrier()
213
+
214
+ # Create and train FAISS index for the item (movie) tower on CPU
215
+ if rank == 0:
216
+ index = get_index(
217
+ embedding_dim=embedding_dim,
218
+ num_centroids=num_centroids,
219
+ num_probe=num_probe,
220
+ num_subquantizers=num_subquantizers,
221
+ bits_per_code=bits_per_code,
222
+ device=torch.device("cpu"),
223
+ )
224
+
225
+ values = torch.tensor(list(range(num_embeddings)), device=torch.device("cpu"))
226
+ kjt = KeyedJaggedTensor(
227
+ keys=two_tower_column_names,
228
+ values=values,
229
+ lengths=torch.tensor(
230
+ [0] * num_embeddings + [1] * num_embeddings,
231
+ device=torch.device("cpu"),
232
+ ),
233
+ )
234
+
235
+ # Get the embeddings of the item(movie) tower by querying model
236
+ with torch.no_grad():
237
+ lookups = two_tower_cpu.ebc(kjt)[two_tower_column_names[1]]
238
+ item_embeddings = two_tower_cpu.candidate_proj(lookups)
239
+ index.train(item_embeddings)
240
+ index.add(item_embeddings)
241
+
242
+ if save_dir is not None:
243
+ save_dir = save_dir.rstrip("/")
244
+ quant_model = trec_infer.modules.quantize_embeddings(
245
+ model, dtype=torch.qint8, inplace=True
246
+ )
247
+ torch.save(quant_model.state_dict(), f"{save_dir}/model.pt")
248
+ # pyre-ignore[16]
249
+ faiss.write_index(index, f"{save_dir}/faiss.index")
250
+
251
+
252
+ if __name__ == "__main__":
253
+ main()
@@ -0,0 +1,8 @@
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 . import dataloader # noqa
@@ -0,0 +1,116 @@
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 torch
9
+ import torcharrow as ta
10
+ import torcharrow.dtypes as dt
11
+ import torcharrow.pytorch as tap
12
+ from torch.utils.data import DataLoader
13
+ from torcharrow import functional
14
+ from torchdata.datapipes.iter import FileLister
15
+ from torchrec.datasets.criteo import (
16
+ DEFAULT_CAT_NAMES,
17
+ DEFAULT_INT_NAMES,
18
+ DEFAULT_LABEL_NAME,
19
+ )
20
+
21
+ from torchrec.sparse.jagged_tensor import KeyedJaggedTensor
22
+
23
+
24
+ class _JaggedTensorConversion(tap.TensorConversion):
25
+ # pyre-fixme[14]: `to_tensor` overrides method defined in `TensorConversion`
26
+ # inconsistently.
27
+ def to_tensor(self, df: ta.DataFrame):
28
+
29
+ kjt_keys = df.columns
30
+ kjt_values = []
31
+ kjt_lengths = []
32
+ for row in df:
33
+ for idx, _column in enumerate(df.columns):
34
+ value = row[idx]
35
+ kjt_values.extend(value)
36
+ kjt_lengths.append(len(value))
37
+ kjt = KeyedJaggedTensor.from_lengths_sync(
38
+ keys=kjt_keys,
39
+ values=torch.tensor(kjt_values),
40
+ lengths=torch.tensor(kjt_lengths),
41
+ )
42
+ return kjt
43
+
44
+
45
+ class _Scalar(tap.TensorConversion):
46
+ def to_tensor(self, df: ta.DataFrame):
47
+ labels = torch.tensor(df)
48
+ return labels
49
+
50
+
51
+ def get_dataloader(
52
+ parquet_directory, world_size, rank, num_embeddings=4096, salt=0, batch_size=16
53
+ ):
54
+ source_dp = FileLister(parquet_directory, masks="*.parquet")
55
+ # TODO support batch_size for load_parquet_as_df.
56
+ # TODO use OSSArrowDataPipe once it is ready
57
+ parquet_df_dp = source_dp.load_parquet_as_df()
58
+
59
+ def preproc(df, max_idx=num_embeddings, salt=salt):
60
+
61
+ for feature_name in DEFAULT_INT_NAMES:
62
+ df[feature_name] = df[feature_name].fill_null(0)
63
+ for feature_name in DEFAULT_CAT_NAMES:
64
+ df[feature_name] = df[feature_name].fill_null(0)
65
+ df[feature_name] = df[feature_name].cast(dt.int64)
66
+
67
+ # construct a sprase index from a dense one
68
+ df["bucketize_int_0"] = functional.bucketize(df["int_0"], [0.5, 1.0, 1.5]).cast(
69
+ dt.int64
70
+ )
71
+
72
+ # flatten several columns into one
73
+ df["dense_features"] = ta.dataframe(
74
+ {int_name: df[int_name] for int_name in DEFAULT_INT_NAMES}
75
+ )
76
+
77
+ df["dense_features"] = (df["dense_features"] + 3).log()
78
+
79
+ for cat_name in DEFAULT_CAT_NAMES + ["bucketize_int_0"]:
80
+ # hash our embedding index into our embedding tables
81
+ df[cat_name] = functional.sigrid_hash(df[cat_name], salt, max_idx)
82
+ df[cat_name] = functional.array_constructor(df[cat_name])
83
+ df[cat_name] = functional.firstx(df[cat_name], 1)
84
+
85
+ df["sparse_features"] = ta.dataframe(
86
+ {
87
+ cat_name: df[cat_name]
88
+ for cat_name in DEFAULT_CAT_NAMES + ["bucketize_int_0"]
89
+ }
90
+ )
91
+
92
+ df = df[["dense_features", "sparse_features", DEFAULT_LABEL_NAME]]
93
+
94
+ return df
95
+
96
+ parquet_df_dp = parquet_df_dp.map(preproc).sharding_filter()
97
+ parquet_df_dp.apply_sharding(world_size, rank)
98
+
99
+ def criteo_collate(df):
100
+ dense_features, kjt, labels = df.to_tensor(
101
+ {
102
+ "dense_features": tap.rec.Dense(batch_first=True),
103
+ "sparse_features": _JaggedTensorConversion(),
104
+ "label": _Scalar(),
105
+ }
106
+ )
107
+
108
+ return dense_features, kjt, labels
109
+
110
+ return DataLoader(
111
+ parquet_df_dp,
112
+ batch_size=None,
113
+ collate_fn=criteo_collate,
114
+ drop_last=False,
115
+ pin_memory=True,
116
+ )
@@ -0,0 +1,126 @@
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 os
9
+
10
+ import click
11
+ import dataloader as torcharrow_dataloader
12
+ import torch
13
+ import torch.distributed as dist
14
+ from fbgemm_gpu.split_embedding_configs import EmbOptimType
15
+ from torch.distributed.elastic.multiprocessing.errors import record
16
+ from torchrec import EmbeddingBagCollection
17
+ from torchrec.datasets.criteo import DEFAULT_CAT_NAMES, INT_FEATURE_COUNT
18
+ from torchrec.distributed.embeddingbag import EmbeddingBagCollectionSharder
19
+ from torchrec.distributed.model_parallel import DistributedModelParallel
20
+ from torchrec.models.dlrm import DLRM
21
+ from torchrec.modules.embedding_configs import EmbeddingBagConfig
22
+ from torchrec.optim.keyed import KeyedOptimizerWrapper
23
+
24
+
25
+ @record
26
+ @click.command()
27
+ @click.option("--batch_size", default=256)
28
+ @click.option("--num_embeddings", default=2048)
29
+ @click.option("--sigrid_hash_salt", default=0)
30
+ @click.option("--parquet_directory", default="/data/criteo_preproc")
31
+ def main(
32
+ batch_size,
33
+ num_embeddings,
34
+ sigrid_hash_salt,
35
+ parquet_directory,
36
+ ) -> None:
37
+ rank = int(os.environ["LOCAL_RANK"])
38
+ if torch.cuda.is_available():
39
+ device = torch.device(f"cuda:{rank}")
40
+ backend = "nccl"
41
+ torch.cuda.set_device(device)
42
+ else:
43
+ device = torch.device("cpu")
44
+ backend = "gloo"
45
+ print(
46
+ "\033[92m"
47
+ + f"WARNING: Running in CPU mode. cuda availablility {torch.cuda.is_available()}."
48
+ )
49
+
50
+ dist.init_process_group(backend=backend)
51
+
52
+ world_size = dist.get_world_size()
53
+
54
+ dataloader = torcharrow_dataloader.get_dataloader(
55
+ parquet_directory,
56
+ world_size,
57
+ rank,
58
+ batch_size=batch_size,
59
+ num_embeddings=num_embeddings,
60
+ salt=sigrid_hash_salt,
61
+ )
62
+ it = iter(dataloader)
63
+
64
+ model = DLRM(
65
+ embedding_bag_collection=EmbeddingBagCollection(
66
+ tables=[
67
+ EmbeddingBagConfig(
68
+ name=f"table_{cat_name}",
69
+ embedding_dim=64,
70
+ num_embeddings=num_embeddings,
71
+ feature_names=[cat_name],
72
+ )
73
+ for cat_name in DEFAULT_CAT_NAMES + ["bucketize_int_0"]
74
+ ],
75
+ device=torch.device("meta"),
76
+ ),
77
+ dense_in_features=INT_FEATURE_COUNT,
78
+ dense_arch_layer_sizes=[64],
79
+ over_arch_layer_sizes=[32, 1],
80
+ dense_device=device,
81
+ )
82
+
83
+ fused_params = {
84
+ "learning_rate": 0.02,
85
+ "optimizer": EmbOptimType.EXACT_ROWWISE_ADAGRAD,
86
+ }
87
+
88
+ sharded_model = DistributedModelParallel(
89
+ module=model,
90
+ device=device,
91
+ sharders=[
92
+ EmbeddingBagCollectionSharder(fused_params=fused_params),
93
+ ],
94
+ )
95
+
96
+ optimizer = KeyedOptimizerWrapper(
97
+ dict(model.named_parameters()),
98
+ lambda params: torch.optim.SGD(params, lr=0.01),
99
+ )
100
+
101
+ loss_fn = torch.nn.BCEWithLogitsLoss()
102
+
103
+ print_example = dist.get_rank() == 0
104
+ for (dense_features, kjt, labels) in it:
105
+ if print_example:
106
+ print("Example dense_features", dense_features)
107
+ print("Example KJT input", kjt)
108
+ print_example = False
109
+
110
+ dense_features = dense_features.to(device)
111
+ kjt = kjt.to(device)
112
+ labels = labels.to(device)
113
+
114
+ optimizer.zero_grad()
115
+
116
+ preds = sharded_model(dense_features, kjt)
117
+ loss = loss_fn(preds.squeeze(), labels.squeeze())
118
+ loss.sum().backward()
119
+
120
+ optimizer.step()
121
+
122
+ print("\033[92m" + "DLRM run with torcharrow last-mile preprocessing finished!")
123
+
124
+
125
+ if __name__ == "__main__":
126
+ main()