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
examples/__init__.py ADDED
File without changes
@@ -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 criteo_dataframes # noqa
@@ -0,0 +1,101 @@
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 Iterable, List, Tuple, Union
9
+
10
+ import numpy as np
11
+ import torch.utils.data.datapipes as dp
12
+ import torcharrow as ta
13
+ import torcharrow.dtypes as dt
14
+ from torch.utils.data import IterDataPipe
15
+ from torchrec.datasets.criteo import (
16
+ CAT_FEATURE_COUNT,
17
+ CriteoIterDataPipe,
18
+ DEFAULT_CAT_NAMES,
19
+ DEFAULT_INT_NAMES,
20
+ INT_FEATURE_COUNT,
21
+ )
22
+ from torchrec.datasets.utils import safe_cast
23
+
24
+ DTYPE = dt.Struct(
25
+ [
26
+ dt.Field("labels", dt.int8),
27
+ dt.Field(
28
+ "dense_features",
29
+ dt.Struct(
30
+ [
31
+ dt.Field(int_name, dt.Int32(nullable=True))
32
+ for int_name in DEFAULT_INT_NAMES
33
+ ]
34
+ ),
35
+ ),
36
+ dt.Field(
37
+ "sparse_features",
38
+ dt.Struct(
39
+ [
40
+ dt.Field(cat_name, dt.Int32(nullable=True))
41
+ for cat_name in DEFAULT_CAT_NAMES
42
+ ]
43
+ ),
44
+ ),
45
+ ]
46
+ )
47
+
48
+
49
+ def _torcharrow_row_mapper(
50
+ row: List[str],
51
+ ) -> Tuple[int, Tuple[int, ...], Tuple[int, ...]]:
52
+ # TODO: Fix safe_cast type annotation
53
+ label = int(safe_cast(row[0], int, 0))
54
+ dense = tuple(
55
+ (int(safe_cast(row[i], int, 0)) for i in range(1, 1 + INT_FEATURE_COUNT))
56
+ )
57
+ sparse = tuple(
58
+ (
59
+ int(safe_cast(row[i], str, "0") or "0", 16)
60
+ for i in range(
61
+ 1 + INT_FEATURE_COUNT, 1 + INT_FEATURE_COUNT + CAT_FEATURE_COUNT
62
+ )
63
+ )
64
+ )
65
+ # TorchArrow doesn't support uint32, but we can save memory
66
+ # by not using int64. Numpy will automatically handle sparse values >= 2 ** 31.
67
+ sparse = tuple(np.array(sparse, dtype=np.int32).tolist())
68
+
69
+ return (label, dense, sparse)
70
+
71
+
72
+ def criteo_dataframes_from_tsv(
73
+ paths: Union[str, Iterable[str]],
74
+ *,
75
+ batch_size: int = 128,
76
+ ) -> IterDataPipe:
77
+ """
78
+ Load Criteo dataset (Kaggle or Terabyte) as TorchArrow DataFrame streams from TSV file(s)
79
+
80
+ This implementaiton is inefficient and is used for prototype and test only.
81
+
82
+ Args:
83
+ paths (str or Iterable[str]): local paths to TSV files that constitute
84
+ the Kaggle or Criteo 1TB dataset.
85
+
86
+ Example::
87
+
88
+ datapipe = criteo_dataframes_from_tsv(
89
+ ["/home/datasets/criteo/day_0.tsv", "/home/datasets/criteo/day_1.tsv"]
90
+ )
91
+ for df in datapipe:
92
+ print(df)
93
+ """
94
+ if isinstance(paths, str):
95
+ paths = [paths]
96
+
97
+ datapipe = CriteoIterDataPipe(paths, row_mapper=_torcharrow_row_mapper)
98
+ datapipe = dp.iter.Batcher(datapipe, batch_size)
99
+ datapipe = dp.iter.Mapper(datapipe, lambda batch: ta.dataframe(batch, dtype=DTYPE))
100
+
101
+ return datapipe
File without changes
@@ -0,0 +1,51 @@
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
+
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from torch.distributed import all_reduce, get_rank, get_world_size, init_process_group
15
+
16
+
17
+ def compute_world_size() -> int:
18
+ "Dummy script to compute world_size. Meant to test if can run Ray + Pytorch DDP"
19
+ rank = int(os.getenv("RANK")) # pyre-ignore[6]
20
+ world_size = int(os.getenv("WORLD_SIZE")) # pyre-ignore[6]
21
+ master_port = int(os.getenv("MASTER_PORT")) # pyre-ignore[6]
22
+ master_addr = os.getenv("MASTER_ADDR")
23
+ backend = "gloo"
24
+
25
+ print(f"initializing `{backend}` process group")
26
+ init_process_group( # pyre-ignore[16]
27
+ backend=backend,
28
+ init_method=f"tcp://{master_addr}:{master_port}",
29
+ rank=rank,
30
+ world_size=world_size,
31
+ )
32
+ print("successfully initialized process group")
33
+
34
+ rank = get_rank() # pyre-ignore[16]
35
+ world_size = get_world_size() # pyre-ignore[16]
36
+
37
+ t = F.one_hot(torch.tensor(rank), num_classes=world_size)
38
+ all_reduce(t) # pyre-ignore[16]
39
+ computed_world_size = int(torch.sum(t).item())
40
+ print(
41
+ f"rank: {rank}, actual world_size: {world_size}, computed world_size: {computed_world_size}"
42
+ )
43
+ return computed_world_size
44
+
45
+
46
+ def main() -> None:
47
+ compute_world_size()
48
+
49
+
50
+ if __name__ == "__main__":
51
+ main()
@@ -0,0 +1,133 @@
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 torch
14
+ from fbgemm_gpu.split_embedding_configs import EmbOptimType as OptimType
15
+ from torch import distributed as dist, nn
16
+ from torch.utils.data import DataLoader
17
+ from torchrec.datasets.criteo import DEFAULT_CAT_NAMES, DEFAULT_INT_NAMES
18
+ from torchrec.datasets.random import RandomRecDataset
19
+ from torchrec.distributed import TrainPipelineSparseDist
20
+ from torchrec.distributed.embeddingbag import EmbeddingBagCollectionSharder
21
+ from torchrec.distributed.model_parallel import DistributedModelParallel
22
+ from torchrec.distributed.types import ModuleSharder
23
+ from torchrec.models.dlrm import DLRM, DLRMTrain
24
+ from torchrec.modules.embedding_configs import EmbeddingBagConfig
25
+ from torchrec.modules.embedding_modules import EmbeddingBagCollection
26
+ from torchrec.optim.keyed import KeyedOptimizerWrapper
27
+ from tqdm import tqdm
28
+
29
+
30
+ def _get_random_dataloader(
31
+ num_embeddings: int, batch_size: int = 32, pin_memory: bool = False
32
+ ) -> DataLoader:
33
+ return DataLoader(
34
+ RandomRecDataset(
35
+ keys=DEFAULT_CAT_NAMES,
36
+ batch_size=batch_size,
37
+ hash_size=num_embeddings,
38
+ ids_per_feature=1,
39
+ num_dense=len(DEFAULT_INT_NAMES),
40
+ ),
41
+ batch_size=None,
42
+ batch_sampler=None,
43
+ pin_memory=pin_memory,
44
+ num_workers=0,
45
+ )
46
+
47
+
48
+ def train(
49
+ num_embeddings: int = 1024**2,
50
+ embedding_dim: int = 128,
51
+ dense_arch_layer_sizes: Optional[List[int]] = None,
52
+ over_arch_layer_sizes: Optional[List[int]] = None,
53
+ learning_rate: float = 0.1,
54
+ ) -> None:
55
+ """
56
+ Constructs and trains a DLRM model (using random dummy data). Each script is run on each process (rank) in SPMD fashion.
57
+ The embedding layers will be sharded across available ranks
58
+ """
59
+ if dense_arch_layer_sizes is None:
60
+ dense_arch_layer_sizes = [64, 128]
61
+ if over_arch_layer_sizes is None:
62
+ over_arch_layer_sizes = [64, 1]
63
+
64
+ # Init process_group , device, rank, backend
65
+ rank = int(os.environ["LOCAL_RANK"])
66
+ if torch.cuda.is_available():
67
+ device: torch.device = torch.device(f"cuda:{rank}")
68
+ backend = "nccl"
69
+ torch.cuda.set_device(device)
70
+ else:
71
+ device: torch.device = torch.device("cpu")
72
+ backend = "gloo"
73
+ dist.init_process_group(backend=backend)
74
+
75
+ # Construct DLRM module
76
+ eb_configs = [
77
+ EmbeddingBagConfig(
78
+ name=f"t_{feature_name}",
79
+ embedding_dim=embedding_dim,
80
+ num_embeddings=num_embeddings,
81
+ feature_names=[feature_name],
82
+ )
83
+ for feature_idx, feature_name in enumerate(DEFAULT_CAT_NAMES)
84
+ ]
85
+ dlrm_model = DLRM(
86
+ embedding_bag_collection=EmbeddingBagCollection(
87
+ tables=eb_configs, device=torch.device("meta")
88
+ ),
89
+ dense_in_features=len(DEFAULT_INT_NAMES),
90
+ dense_arch_layer_sizes=dense_arch_layer_sizes,
91
+ over_arch_layer_sizes=over_arch_layer_sizes,
92
+ dense_device=device,
93
+ )
94
+ train_model = DLRMTrain(dlrm_model)
95
+
96
+ # Enable optimizer fusion
97
+ fused_params = {
98
+ "learning_rate": learning_rate,
99
+ "optimizer": OptimType.EXACT_ROWWISE_ADAGRAD,
100
+ }
101
+ sharders = [
102
+ EmbeddingBagCollectionSharder(fused_params=fused_params),
103
+ ]
104
+ # Distribute model across devices
105
+ model = DistributedModelParallel(
106
+ module=train_model,
107
+ device=device,
108
+ sharders=cast(List[ModuleSharder[nn.Module]], sharders),
109
+ )
110
+
111
+ # Overlap comm/compute/device transfer during training through train_pipeline
112
+ non_fused_optimizer = KeyedOptimizerWrapper(
113
+ dict(model.named_parameters()),
114
+ lambda params: torch.optim.Adagrad(params, lr=learning_rate),
115
+ )
116
+ train_pipeline = TrainPipelineSparseDist(
117
+ model,
118
+ non_fused_optimizer,
119
+ device,
120
+ )
121
+
122
+ # train model
123
+ train_iterator = iter(
124
+ _get_random_dataloader(
125
+ num_embeddings=num_embeddings, pin_memory=backend == "nccl"
126
+ )
127
+ )
128
+ for _ in tqdm(range(int(1e4)), mininterval=5.0):
129
+ train_pipeline.progress(train_iterator)
130
+
131
+
132
+ if __name__ == "__main__":
133
+ train()
@@ -0,0 +1,6 @@
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.
@@ -0,0 +1,6 @@
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.
@@ -0,0 +1,44 @@
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 torch.utils.data import DataLoader
9
+ from torchrec.datasets.movielens import DEFAULT_RATINGS_COLUMN_NAMES
10
+ from torchrec.datasets.random import RandomRecDataset
11
+
12
+
13
+ def get_dataloader(
14
+ batch_size: int, num_embeddings: int, pin_memory: bool = False, num_workers: int = 0
15
+ ) -> DataLoader:
16
+ """
17
+ Gets a Random dataloader for the two tower model, containing a two_feature KJT as sparse_features, empty dense_features
18
+ and binary labels
19
+
20
+ Args:
21
+ batch_size (int): batch_size
22
+ num_embeddings (int): hash_size of the two embedding tables
23
+ pin_memory (bool): Whether to pin_memory on the GPU
24
+ num_workers (int) Number of dataloader workers
25
+
26
+ Returns:
27
+ dataloader (DataLoader): PyTorch dataloader for the specified options.
28
+
29
+ """
30
+ two_tower_column_names = DEFAULT_RATINGS_COLUMN_NAMES[:2]
31
+
32
+ return DataLoader(
33
+ RandomRecDataset(
34
+ keys=two_tower_column_names,
35
+ batch_size=batch_size,
36
+ hash_size=num_embeddings,
37
+ ids_per_feature=1,
38
+ num_dense=0,
39
+ ),
40
+ batch_size=None,
41
+ batch_sampler=None,
42
+ pin_memory=pin_memory,
43
+ num_workers=num_workers,
44
+ )
@@ -0,0 +1,67 @@
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 Optional, Union
9
+
10
+ import faiss # @manual=//faiss/python:pyfaiss_gpu
11
+ import faiss.contrib.torch_utils # @manual=//faiss/contrib:faiss_contrib_gpu
12
+ import torch
13
+
14
+
15
+ def get_index(
16
+ embedding_dim: int,
17
+ num_centroids: int,
18
+ num_probe: int,
19
+ num_subquantizers: int,
20
+ bits_per_code: int,
21
+ device: Optional[torch.device] = None,
22
+ # pyre-ignore[11]
23
+ ) -> Union[faiss.GpuIndexIVFPQ, faiss.IndexIVFPQ]:
24
+ """
25
+ returns a FAISS IVFPQ index, placed on the device passed in
26
+
27
+ Args:
28
+ embedding_dim (int): indexed embedding dimension,
29
+ num_centroids (int): the number of centroids (Voronoi cells),
30
+ 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.,
31
+ num_subquantizers (int): the number of subquanitizers in Product Quantization (PQ) compression of subvectors,
32
+ bits_per_code (int): The number of bits for each subvector in Product Quantization (PQ),
33
+
34
+ Example::
35
+
36
+ get_index()
37
+
38
+ """
39
+ if device is not None and device.type == "cuda":
40
+ # pyre-fixme[16]
41
+ res = faiss.StandardGpuResources()
42
+ # pyre-fixme[16]
43
+ config = faiss.GpuIndexIVFPQConfig()
44
+ # pyre-ignore[16]
45
+ index = faiss.GpuIndexIVFPQ(
46
+ res,
47
+ embedding_dim,
48
+ num_centroids,
49
+ num_subquantizers,
50
+ bits_per_code,
51
+ # pyre-fixme[16]
52
+ faiss.METRIC_L2,
53
+ config,
54
+ )
55
+ else:
56
+ # pyre-fixme[16]
57
+ quantizer = faiss.IndexFlatL2(embedding_dim)
58
+ # pyre-fixme[16]
59
+ index = faiss.IndexIVFPQ(
60
+ quantizer,
61
+ embedding_dim,
62
+ num_centroids,
63
+ num_subquantizers,
64
+ bits_per_code,
65
+ )
66
+ index.nprobe = num_probe
67
+ return index
@@ -0,0 +1,6 @@
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.
@@ -0,0 +1,229 @@
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, List, Mapping, Optional, OrderedDict, Tuple, Union
9
+
10
+ import faiss # @manual=//faiss/python:pyfaiss_gpu
11
+ import faiss.contrib.torch_utils # @manual=//faiss/contrib:faiss_contrib_gpu
12
+ import torch
13
+ from torch import nn
14
+ from torchrec.datasets.utils import Batch
15
+ from torchrec.modules.embedding_modules import EmbeddingBagCollection
16
+ from torchrec.modules.mlp import MLP
17
+ from torchrec.sparse.jagged_tensor import KeyedJaggedTensor
18
+
19
+
20
+ def convert_TwoTower_to_TwoTowerRetrieval(
21
+ sd: OrderedDict[str, torch.Tensor],
22
+ query_tables: List[str],
23
+ candidate_tables: List[str],
24
+ ) -> OrderedDict[str, torch.Tensor]:
25
+ for query_table in query_tables:
26
+ sd[f"query_ebc.embedding_bags.{query_table}.weight"] = sd.pop(
27
+ f"two_tower.ebc.embedding_bags.{query_table}.weight"
28
+ )
29
+ for candidate_table in candidate_tables:
30
+ sd[f"candidate_ebc.embedding_bags.{candidate_table}.weight"] = sd.pop(
31
+ f"two_tower.ebc.embedding_bags.{candidate_table}.weight"
32
+ )
33
+ return sd
34
+
35
+
36
+ class TwoTower(nn.Module):
37
+ """
38
+ Simple TwoTower (UV) Model. Embeds two different entities into the same space.
39
+ A simplified version of the `A Dual Augmented Two-tower Model for Online Large-scale Recommendation
40
+ <https://dlp-kdd.github.io/assets/pdf/DLP-KDD_2021_paper_4.pdf>`_ model.
41
+ Used to train the retrieval model
42
+
43
+ Embeddings trained with this model will be indexed and queried in the retrieval example.
44
+
45
+ Args:
46
+ embedding_bag_collection (EmbeddingBagCollection): embedding_bag_collection with two EmbeddingBags
47
+ layer_sizes (List[int]): list of the layer_sizes for the MLP
48
+ device (Optional[torch.device])
49
+
50
+ Example::
51
+
52
+ m = TwoTower(ebc, [16, 8], device)
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ embedding_bag_collection: EmbeddingBagCollection,
58
+ layer_sizes: List[int],
59
+ device: Optional[torch.device] = None,
60
+ ) -> None:
61
+ super().__init__()
62
+ assert (
63
+ len(embedding_bag_collection.embedding_bag_configs) == 2
64
+ ), "Expected two EmbeddingBags in the two tower model"
65
+ assert (
66
+ embedding_bag_collection.embedding_bag_configs[0].embedding_dim
67
+ == embedding_bag_collection.embedding_bag_configs[1].embedding_dim
68
+ ), "Both EmbeddingBagConfigs must have the same dimension"
69
+ embedding_dim: int = embedding_bag_collection.embedding_bag_configs[
70
+ 0
71
+ ].embedding_dim
72
+ self._feature_names_query: List[
73
+ str
74
+ ] = embedding_bag_collection.embedding_bag_configs[0].feature_names
75
+ self._candidate_feature_names: List[
76
+ str
77
+ ] = embedding_bag_collection.embedding_bag_configs[1].feature_names
78
+ self.ebc = embedding_bag_collection
79
+ self.query_proj = MLP(
80
+ in_size=embedding_dim, layer_sizes=layer_sizes, device=device
81
+ )
82
+ self.candidate_proj = MLP(
83
+ in_size=embedding_dim, layer_sizes=layer_sizes, device=device
84
+ )
85
+
86
+ def forward(self, kjt: KeyedJaggedTensor) -> Tuple[torch.Tensor, torch.Tensor]:
87
+ """
88
+ Args:
89
+ kjt (KeyedJaggedTensor): KJT containing query_ids and candidate_ids to query
90
+
91
+ Returns:
92
+ Tuple[torch.Tensor, torch.Tensor]: Tuple containing embeddings for each tower
93
+ """
94
+ pooled_embeddings = self.ebc(kjt)
95
+ query_embedding: torch.Tensor = self.query_proj(
96
+ torch.cat(
97
+ [pooled_embeddings[feature] for feature in self._feature_names_query],
98
+ dim=1,
99
+ )
100
+ )
101
+ candidate_embedding: torch.Tensor = self.candidate_proj(
102
+ torch.cat(
103
+ [
104
+ pooled_embeddings[feature]
105
+ for feature in self._candidate_feature_names
106
+ ],
107
+ dim=1,
108
+ )
109
+ )
110
+ return query_embedding, candidate_embedding
111
+
112
+
113
+ class TwoTowerTrainTask(nn.Module):
114
+ """
115
+ Train Task for the TwoTower model. Adds BinaryCrossEntropy Loss. to use with train_pipeline
116
+
117
+ Args:
118
+ two_tower (TwoTower): two tower model
119
+
120
+ Example::
121
+
122
+ m = TwoTowerTrainTask(two_tower_model)
123
+ """
124
+
125
+ def __init__(self, two_tower: TwoTower) -> None:
126
+ super().__init__()
127
+ self.two_tower = two_tower
128
+ self.loss_fn: nn.Module = nn.BCEWithLogitsLoss()
129
+
130
+ def forward(
131
+ self, batch: Batch
132
+ ) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
133
+ """
134
+ Args:
135
+ batch (Batch): batch from torchrec.datasets
136
+
137
+ Returns:
138
+ Tuple[loss, Tuple[loss, logits, labels]]: each of shape B x 1
139
+ """
140
+ query_embedding, candidate_embedding = self.two_tower(batch.sparse_features)
141
+ logits = (query_embedding * candidate_embedding).sum(dim=1).squeeze()
142
+ loss = self.loss_fn(logits, batch.labels.float())
143
+ return loss, (loss.detach(), logits.detach(), batch.labels.detach())
144
+
145
+
146
+ class TwoTowerRetrieval(nn.Module):
147
+ """
148
+ Simple TwoTower (UV) Model. Embeds two different entities (query and candidate) into the same space.
149
+ Similar to the TwoTower model above, but is meant for retrieval. Specifically, this module
150
+ also contiains a FAISS index, used to KNN search the K closest entities of tower 2. It separates query
151
+ and candidate into separate EmbeddingBagCollections
152
+
153
+ Args:
154
+ faiss_index (Union[faiss.GpuIndexIVFPQ, faiss.IndexIVFPQ]): faiss index to search candidate
155
+ query_ebc (EmbeddingBagCollection): embedding_bag_collection with one EmbeddingBag
156
+ candidate_ebc (EmbeddingBagCollection): embedding_bag_collection with one EmbeddingBag
157
+ layer_sizes (List[int]): list of the layer_sizes for the MLP
158
+ k (int): number of tower 2 nearest neighbors to score
159
+ device (Optional[torch.device])
160
+
161
+ Example::
162
+
163
+ m = TwoTowerRetrieval(index, query_ebc, candidate_ebc, [16, 8], 100, device)
164
+ """
165
+
166
+ def __init__(
167
+ self,
168
+ # pyre-ignore[11]
169
+ faiss_index: Union[faiss.GpuIndexIVFPQ, faiss.IndexIVFPQ],
170
+ query_ebc: EmbeddingBagCollection,
171
+ candidate_ebc: EmbeddingBagCollection,
172
+ layer_sizes: List[int],
173
+ k: int,
174
+ device: Optional[torch.device] = None,
175
+ ) -> None:
176
+ super().__init__()
177
+ self.embedding_dim: int = query_ebc.embedding_bag_configs[0].embedding_dim
178
+ assert (
179
+ candidate_ebc.embedding_bag_configs[0].embedding_dim == self.embedding_dim
180
+ ), "Both EmbeddingBagCollections must have the same dimension"
181
+ self.candidate_feature_names: List[str] = candidate_ebc.embedding_bag_configs[
182
+ 0
183
+ ].feature_names
184
+ self.query_ebc = query_ebc
185
+ self.candidate_ebc = candidate_ebc
186
+ self.query_proj = MLP(
187
+ in_size=self.embedding_dim, layer_sizes=layer_sizes, device=device
188
+ )
189
+ self.candidate_proj = MLP(
190
+ in_size=self.embedding_dim, layer_sizes=layer_sizes, device=device
191
+ )
192
+ self.faiss_index: Union[faiss.GpuIndexIVFPQ, faiss.IndexIVFPQ] = faiss_index
193
+ self.k = k
194
+ self.device = device
195
+
196
+ def forward(self, query_kjt: KeyedJaggedTensor) -> torch.Tensor:
197
+ """
198
+ Args:
199
+ query_kjt (KeyedJaggedTensor): KJT containing query_ids to query
200
+
201
+ Returns:
202
+ torch.Tensor: logits
203
+ """
204
+ batch_size = query_kjt.stride()
205
+ # tower 1 lookup
206
+ query_embedding = self.query_proj(self.query_ebc(query_kjt).values())
207
+
208
+ # KNN lookup
209
+ distances = torch.empty((batch_size, self.k), device=self.device)
210
+ candidates = torch.empty(
211
+ (batch_size, self.k), device=self.device, dtype=torch.int64
212
+ )
213
+ self.faiss_index.search(query_embedding, self.k, distances, candidates)
214
+
215
+ # candidate lookup
216
+ candidate_kjt = KeyedJaggedTensor(
217
+ keys=self.candidate_feature_names,
218
+ values=candidates.reshape(-1),
219
+ lengths=torch.tensor([self.k] * batch_size),
220
+ )
221
+ candidate_embedding = self.candidate_proj(
222
+ self.candidate_ebc(candidate_kjt).values()
223
+ )
224
+
225
+ # return logit (dot product)
226
+ return (query_embedding * candidate_embedding).sum(dim=1).squeeze()
227
+
228
+ def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool) -> None:
229
+ super().load_state_dict(state_dict, strict)