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,140 @@
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
+ from typing import Any, Callable, Dict, List, Optional, Union
10
+
11
+ from torch.utils.data import IterDataPipe
12
+ from torchrec.datasets.utils import LoadFiles, ReadLinesFromCSV, safe_cast
13
+
14
+ RATINGS_FILENAME = "ratings.csv"
15
+ MOVIES_FILENAME = "movies.csv"
16
+
17
+ DEFAULT_RATINGS_COLUMN_NAMES: List[str] = ["userId", "movieId", "rating", "timestamp"]
18
+ DEFAULT_MOVIES_COLUMN_NAMES: List[str] = ["movieId", "title", "genres"]
19
+ DEFAULT_COLUMN_NAMES: List[str] = (
20
+ DEFAULT_RATINGS_COLUMN_NAMES + DEFAULT_MOVIES_COLUMN_NAMES[1:]
21
+ )
22
+
23
+ COLUMN_TYPE_CASTERS: List[
24
+ Callable[[Union[float, int, str]], Union[float, int, str]]
25
+ ] = [
26
+ lambda val: safe_cast(val, int, 0),
27
+ lambda val: safe_cast(val, int, 0),
28
+ lambda val: safe_cast(val, float, 0.0),
29
+ lambda val: safe_cast(val, int, 0),
30
+ lambda val: safe_cast(val, str, ""),
31
+ lambda val: safe_cast(val, str, ""),
32
+ ]
33
+
34
+
35
+ def _default_row_mapper(example: List[str]) -> Dict[str, Union[float, int, str]]:
36
+ return {
37
+ DEFAULT_COLUMN_NAMES[idx]: COLUMN_TYPE_CASTERS[idx](val)
38
+ for idx, val in enumerate(example)
39
+ }
40
+
41
+
42
+ def _join_with_movies(datapipe: IterDataPipe, root: str) -> IterDataPipe:
43
+ movies_path = os.path.join(root, MOVIES_FILENAME)
44
+ movies_datapipe = LoadFiles((movies_path,), mode="r")
45
+ movies_datapipe = ReadLinesFromCSV(
46
+ movies_datapipe,
47
+ skip_first_line=True,
48
+ delimiter=",",
49
+ )
50
+ movie_id_to_movie: Dict[str, List[str]] = {
51
+ row[0]: row[1:] for row in movies_datapipe
52
+ }
53
+
54
+ def join_rating_movie(val: List[str]) -> List[str]:
55
+ return val + movie_id_to_movie[val[1]]
56
+
57
+ return datapipe.map(join_rating_movie)
58
+
59
+
60
+ def _movielens(
61
+ root: str,
62
+ *,
63
+ include_movies_data: bool = False,
64
+ # pyre-ignore[2]
65
+ row_mapper: Optional[Callable[[List[str]], Any]] = _default_row_mapper,
66
+ # pyre-ignore[2]
67
+ **open_kw,
68
+ ) -> IterDataPipe:
69
+ ratings_path = os.path.join(root, RATINGS_FILENAME)
70
+ datapipe = LoadFiles((ratings_path,), mode="r", **open_kw)
71
+ datapipe = ReadLinesFromCSV(datapipe, skip_first_line=True, delimiter=",")
72
+
73
+ if include_movies_data:
74
+ datapipe = _join_with_movies(datapipe, root)
75
+ if row_mapper:
76
+ datapipe = datapipe.map(row_mapper)
77
+
78
+ return datapipe
79
+
80
+
81
+ def movielens_20m(
82
+ root: str,
83
+ *,
84
+ include_movies_data: bool = False,
85
+ # pyre-ignore[2]
86
+ row_mapper: Optional[Callable[[List[str]], Any]] = _default_row_mapper,
87
+ # pyre-ignore[2]
88
+ **open_kw,
89
+ ) -> IterDataPipe:
90
+ """`MovieLens 20M <https://grouplens.org/datasets/movielens/20m/>`_ Dataset
91
+ Args:
92
+ root (str): local path to root directory containing MovieLens 20M dataset files.
93
+ include_movies_data (bool): if True, adds movies data to each line.
94
+ row_mapper (Optional[Callable[[List[str]], Any]]): function to apply to each split line.
95
+ open_kw: options to pass to underlying invocation of iopath.common.file_io.PathManager.open.
96
+
97
+ Example::
98
+
99
+ datapipe = movielens_20m("/home/datasets/ml-20")
100
+ datapipe = dp.iter.Batch(datapipe, 100)
101
+ datapipe = dp.iter.Collate(datapipe)
102
+ batch = next(iter(datapipe))
103
+ """
104
+ return _movielens(
105
+ root,
106
+ include_movies_data=include_movies_data,
107
+ row_mapper=row_mapper,
108
+ **open_kw,
109
+ )
110
+
111
+
112
+ def movielens_25m(
113
+ root: str,
114
+ *,
115
+ include_movies_data: bool = False,
116
+ # pyre-ignore[2]
117
+ row_mapper: Optional[Callable[[List[str]], Any]] = _default_row_mapper,
118
+ # pyre-ignore[2]
119
+ **open_kw,
120
+ ) -> IterDataPipe:
121
+ """`MovieLens 25M <https://grouplens.org/datasets/movielens/25m/>`_ Dataset
122
+ Args:
123
+ root (str): local path to root directory containing MovieLens 25M dataset files.
124
+ include_movies_data (bool): if True, adds movies data to each line.
125
+ row_mapper (Optional[Callable[[List[str]], Any]]): function to apply to each split line.
126
+ open_kw: options to pass to underlying invocation of iopath.common.file_io.PathManager.open.
127
+
128
+ Example::
129
+
130
+ datapipe = movielens_25m("/home/datasets/ml-25")
131
+ datapipe = dp.iter.Batch(datapipe, 100)
132
+ datapipe = dp.iter.Collate(datapipe)
133
+ batch = next(iter(datapipe))
134
+ """
135
+ return _movielens(
136
+ root,
137
+ include_movies_data=include_movies_data,
138
+ row_mapper=row_mapper,
139
+ **open_kw,
140
+ )
@@ -0,0 +1,188 @@
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 Iterator, List, Optional
9
+
10
+ import torch
11
+ from torch.utils.data.dataset import IterableDataset
12
+ from torchrec.datasets.utils import Batch
13
+ from torchrec.sparse.jagged_tensor import KeyedJaggedTensor
14
+
15
+
16
+ class _RandomRecBatch:
17
+ generator: Optional[torch.Generator]
18
+
19
+ def __init__(
20
+ self,
21
+ keys: List[str],
22
+ batch_size: int,
23
+ hash_sizes: List[int],
24
+ ids_per_features: List[int],
25
+ num_dense: int,
26
+ manual_seed: Optional[int] = None,
27
+ num_generated_batches: int = 10,
28
+ num_batches: Optional[int] = None,
29
+ ) -> None:
30
+
31
+ self.keys = keys
32
+ self.keys_length: int = len(keys)
33
+ self.batch_size = batch_size
34
+ self.hash_sizes = hash_sizes
35
+ self.ids_per_features = ids_per_features
36
+ self.num_dense = num_dense
37
+ self.num_batches = num_batches
38
+ self.num_generated_batches = num_generated_batches
39
+
40
+ if manual_seed is not None:
41
+ self.generator = torch.Generator()
42
+ self.generator.manual_seed(manual_seed)
43
+ else:
44
+ self.generator = None
45
+
46
+ self._generated_batches: List[Batch] = [
47
+ self._generate_batch()
48
+ ] * num_generated_batches
49
+ self.batch_index = 0
50
+
51
+ def __iter__(self) -> "_RandomRecBatch":
52
+ self.batch_index = 0
53
+ return self
54
+
55
+ def __next__(self) -> Batch:
56
+ if self.batch_index == self.num_batches:
57
+ raise StopIteration
58
+ if self.num_generated_batches >= 0:
59
+ batch = self._generated_batches[
60
+ self.batch_index % len(self._generated_batches)
61
+ ]
62
+ else:
63
+ batch = self._generate_batch()
64
+ self.batch_index += 1
65
+ return batch
66
+
67
+ def _generate_batch(self) -> Batch:
68
+
69
+ values = []
70
+ lengths = []
71
+ for key_idx, _ in enumerate(self.keys):
72
+ hash_size = self.hash_sizes[key_idx]
73
+ num_ids_in_batch = self.ids_per_features[key_idx]
74
+
75
+ values.append(
76
+ torch.randint(
77
+ high=hash_size,
78
+ size=(num_ids_in_batch * self.batch_size,),
79
+ generator=self.generator,
80
+ )
81
+ )
82
+ lengths.extend([num_ids_in_batch] * self.batch_size)
83
+
84
+ sparse_features = KeyedJaggedTensor.from_lengths_sync(
85
+ keys=self.keys,
86
+ values=torch.cat(values),
87
+ lengths=torch.tensor(lengths, dtype=torch.int32),
88
+ )
89
+
90
+ dense_features = torch.randn(
91
+ self.batch_size,
92
+ self.num_dense,
93
+ generator=self.generator,
94
+ )
95
+ labels = torch.randint(
96
+ low=0,
97
+ high=2,
98
+ size=(self.batch_size,),
99
+ generator=self.generator,
100
+ )
101
+
102
+ batch = Batch(
103
+ dense_features=dense_features,
104
+ sparse_features=sparse_features,
105
+ labels=labels,
106
+ )
107
+ return batch
108
+
109
+
110
+ class RandomRecDataset(IterableDataset[Batch]):
111
+ """
112
+ Random iterable dataset used to generate batches for recommender systems
113
+ (RecSys). Currently produces unweighted sparse features only. TODO: Add
114
+ weighted sparse features.
115
+
116
+ Args:
117
+ keys (List[str]): List of feature names for sparse features.
118
+ batch_size (int): batch size.
119
+ hash_size (Optional[int]): Max sparse id value. All sparse IDs will be taken
120
+ modulo this value.
121
+ hash_sizes (Optional[List[int]]): Max sparse id value per feature in keys. Each
122
+ sparse ID will be taken modulo the corresponding value from this argument. Note, if this is used, hash_size will be ignored.
123
+ ids_per_feature (int): Number of IDs per sparse feature.
124
+ ids_per_features (int): Number of IDs per sparse feature in each key. Note, if this is used, ids_per_feature will be ignored.
125
+ num_dense (int): Number of dense features.
126
+ manual_seed (int): Seed for deterministic behavior.
127
+ num_batches: (Optional[int]): Num batches to generate before raising StopIteration
128
+ num_generated_batches int: Num batches to cache. If num_batches > num_generated batches, then we will cycle to the first generated batch.
129
+ If this value is negative, batches will be generated on the fly.
130
+
131
+ Example::
132
+
133
+ dataset = RandomRecDataset(
134
+ keys=["feat1", "feat2"],
135
+ batch_size=16,
136
+ hash_size=100_000,
137
+ ids_per_feature=1,
138
+ num_dense=13,
139
+ ),
140
+ example = next(iter(dataset))
141
+ """
142
+
143
+ def __init__(
144
+ self,
145
+ keys: List[str],
146
+ batch_size: int,
147
+ hash_size: Optional[int] = 100,
148
+ hash_sizes: Optional[List[int]] = None,
149
+ ids_per_feature: Optional[int] = 2,
150
+ ids_per_features: Optional[List[int]] = None,
151
+ num_dense: int = 50,
152
+ manual_seed: Optional[int] = None,
153
+ num_batches: Optional[int] = None,
154
+ num_generated_batches: int = 10,
155
+ ) -> None:
156
+ super().__init__()
157
+
158
+ if hash_sizes is None:
159
+ hash_size = hash_size or 100
160
+ hash_sizes = [hash_size] * len(keys)
161
+
162
+ assert hash_sizes is not None
163
+ assert len(hash_sizes) == len(
164
+ keys
165
+ ), "length of hash_sizes must be equal to the number of keys"
166
+
167
+ if ids_per_features is None:
168
+ ids_per_feature = ids_per_feature or 2
169
+ ids_per_features = [ids_per_feature] * len(keys)
170
+
171
+ assert ids_per_features is not None
172
+ assert len(ids_per_features) == len(
173
+ keys
174
+ ), "length of ids_per_features must be equal to the number of keys"
175
+
176
+ self.batch_generator = _RandomRecBatch(
177
+ keys=keys,
178
+ batch_size=batch_size,
179
+ hash_sizes=hash_sizes,
180
+ ids_per_features=ids_per_features,
181
+ num_dense=num_dense,
182
+ manual_seed=manual_seed,
183
+ num_batches=num_batches,
184
+ num_generated_batches=num_generated_batches,
185
+ )
186
+
187
+ def __iter__(self) -> Iterator[Batch]:
188
+ return iter(self.batch_generator)
File without changes
@@ -0,0 +1,75 @@
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
+ # This script preprocesses the sparse feature files (binary npy) to such that
9
+ # the IDs become contiguous (with frequency thresholding applied).
10
+ # The results are saved in new binary (npy) files.
11
+
12
+ import argparse
13
+ import os
14
+ import sys
15
+ from typing import List
16
+
17
+ from torchrec.datasets.criteo import BinaryCriteoUtils
18
+
19
+
20
+ def parse_args(argv: List[str]) -> argparse.Namespace:
21
+ parser = argparse.ArgumentParser(
22
+ description="Criteo sparse -> contiguous preprocessing script. "
23
+ )
24
+ parser.add_argument(
25
+ "--input_dir",
26
+ type=str,
27
+ required=True,
28
+ help="Input directory containing the sparse features in numpy format (.npy). Files in the directory "
29
+ "should be named day_{0-23}_sparse.npy.",
30
+ )
31
+ parser.add_argument(
32
+ "--output_dir",
33
+ type=str,
34
+ required=True,
35
+ help="Output directory to store npy files.",
36
+ )
37
+ return parser.parse_args(argv)
38
+
39
+
40
+ def main(argv: List[str]) -> None:
41
+ """
42
+ This function processes the sparse features (.npy) to be contiguous
43
+ and saves the result in a separate (.npy) file.
44
+
45
+ Args:
46
+ argv (List[str]): Command line args.
47
+
48
+ Returns:
49
+ None.
50
+ """
51
+
52
+ args = parse_args(argv)
53
+ input_dir = args.input_dir
54
+ output_dir = args.output_dir
55
+
56
+ # Look for files that end in "_sparse.npy" since this processing is
57
+ # only applied to sparse data.
58
+ input_files = list(
59
+ map(
60
+ lambda f: os.path.join(input_dir, f),
61
+ list(filter(lambda f: f.endswith("_sparse.npy"), os.listdir(input_dir))),
62
+ )
63
+ )
64
+ if not input_files:
65
+ raise ValueError(
66
+ f"There are no files that end with '_sparse.npy' in this directory: {input_dir}"
67
+ )
68
+
69
+ print(f"Processing files in: {input_files}. Outputs will be saved to {output_dir}.")
70
+ BinaryCriteoUtils.sparse_to_contiguous(input_files, output_dir)
71
+ print("Done processing.")
72
+
73
+
74
+ if __name__ == "__main__":
75
+ main(sys.argv[1:])
@@ -0,0 +1,73 @@
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
+ # This script preprocesses Criteo dataset tsv files to binary (npy) files.
9
+
10
+ import argparse
11
+ import os
12
+ import sys
13
+ from typing import List
14
+
15
+ from torchrec.datasets.criteo import BinaryCriteoUtils
16
+
17
+
18
+ def parse_args(argv: List[str]) -> argparse.Namespace:
19
+ parser = argparse.ArgumentParser(
20
+ description="Criteo tsv -> npy preprocessing script."
21
+ )
22
+ parser.add_argument(
23
+ "--input_dir",
24
+ type=str,
25
+ required=True,
26
+ help="Input directory containing Criteo tsv files. Files in the directory "
27
+ "should be named day_{0-23}.",
28
+ )
29
+ parser.add_argument(
30
+ "--output_dir",
31
+ type=str,
32
+ required=True,
33
+ help="Output directory to store npy files.",
34
+ )
35
+ return parser.parse_args(argv)
36
+
37
+
38
+ def main(argv: List[str]) -> None:
39
+ """
40
+ This function preprocesses the raw Criteo tsvs into the format (npy binary)
41
+ expected by InMemoryBinaryCriteoIterDataPipe.
42
+
43
+ Args:
44
+ argv (List[str]): Command line args.
45
+
46
+ Returns:
47
+ None.
48
+ """
49
+
50
+ args = parse_args(argv)
51
+ input_dir = args.input_dir
52
+ output_dir = args.output_dir
53
+
54
+ for f in os.listdir(input_dir):
55
+ in_file_path = os.path.join(input_dir, f)
56
+ dense_out_file_path = os.path.join(output_dir, f + "_dense.npy")
57
+ sparse_out_file_path = os.path.join(output_dir, f + "_sparse.npy")
58
+ labels_out_file_path = os.path.join(output_dir, f + "_labels.npy")
59
+ print(
60
+ f"Processing {in_file_path}. Outputs will be saved to {dense_out_file_path}"
61
+ f", {sparse_out_file_path}, and {labels_out_file_path}..."
62
+ )
63
+ BinaryCriteoUtils.tsv_to_npys(
64
+ in_file_path,
65
+ dense_out_file_path,
66
+ sparse_out_file_path,
67
+ labels_out_file_path,
68
+ )
69
+ print(f"Done processing {in_file_path}.")
70
+
71
+
72
+ if __name__ == "__main__":
73
+ main(sys.argv[1:])
File without changes
@@ -0,0 +1,139 @@
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 contextlib
9
+ import csv
10
+ import os
11
+ import random
12
+ import tempfile
13
+ import unittest
14
+ from typing import Any, Dict, Generator, List, Optional, Tuple
15
+
16
+ import numpy as np
17
+ from pyre_extensions import none_throws
18
+ from torchrec.datasets.criteo import CAT_FEATURE_COUNT, INT_FEATURE_COUNT
19
+
20
+
21
+ class CriteoTest(unittest.TestCase):
22
+ """
23
+ Superclass with helper functions for tests related to Criteo dataset. Helper
24
+ functions include those that create mini mock/random datasets and some functions
25
+ that validate samples returned by the dataset.
26
+ """
27
+
28
+ INT_FEATURE_COUNT = 13
29
+ CAT_FEATURE_COUNT = 26
30
+
31
+ LABEL_VAL_RANGE = (0, 1)
32
+ INT_VAL_RANGE = (0, 100)
33
+ CAT_VAL_RANGE = (0, 1000)
34
+
35
+ @classmethod
36
+ @contextlib.contextmanager
37
+ def _create_dataset_tsv(
38
+ cls,
39
+ num_rows: int = 10,
40
+ train: bool = True,
41
+ filename: str = "criteo",
42
+ ) -> Generator[str, None, None]:
43
+ with tempfile.TemporaryDirectory() as tmpdir:
44
+ path = os.path.join(tmpdir, filename)
45
+ with open(path, "w") as f:
46
+ rows = []
47
+ for _ in range(num_rows):
48
+ row = []
49
+ if train:
50
+ row.append(str(random.randint(*cls.LABEL_VAL_RANGE)))
51
+ row += [
52
+ *(
53
+ str(random.randint(*cls.INT_VAL_RANGE))
54
+ for _ in range(cls.INT_FEATURE_COUNT)
55
+ ),
56
+ *(
57
+ (
58
+ "%x"
59
+ % abs(hash(str(random.randint(*cls.CAT_VAL_RANGE))))
60
+ ).zfill(8)[:8]
61
+ for _ in range(cls.CAT_FEATURE_COUNT)
62
+ ),
63
+ ]
64
+ rows.append(row)
65
+ cf = csv.writer(f, delimiter="\t")
66
+ cf.writerows(rows)
67
+ yield path
68
+
69
+ def _validate_sample(self, sample: Dict[str, Any], train: bool = True) -> None:
70
+ if train:
71
+ self.assertEqual(
72
+ len(sample), self.INT_FEATURE_COUNT + self.CAT_FEATURE_COUNT + 1
73
+ )
74
+ label_val = sample["label"]
75
+ self.assertTrue(
76
+ self.LABEL_VAL_RANGE[0] <= label_val <= self.LABEL_VAL_RANGE[1]
77
+ )
78
+ else:
79
+ self.assertEqual(
80
+ len(sample), self.INT_FEATURE_COUNT + self.CAT_FEATURE_COUNT
81
+ )
82
+ for idx in range(self.INT_FEATURE_COUNT):
83
+ int_val = sample[f"int_{idx}"]
84
+ self.assertTrue(self.INT_VAL_RANGE[0] <= int_val <= self.INT_VAL_RANGE[1])
85
+ for idx in range(self.CAT_FEATURE_COUNT):
86
+ cat_val = int(sample[f"cat_{idx}"], 16)
87
+ self.assertTrue(0 <= cat_val <= 16**8 - 1)
88
+
89
+ @classmethod
90
+ @contextlib.contextmanager
91
+ def _create_dataset_npys(
92
+ cls,
93
+ num_rows: int = 10,
94
+ filename: Optional[str] = "criteo",
95
+ filenames: Optional[List[str]] = None,
96
+ generate_dense: bool = True,
97
+ generate_sparse: bool = True,
98
+ generate_labels: bool = True,
99
+ ) -> Generator[Tuple[str, ...], None, None]:
100
+ with tempfile.TemporaryDirectory() as tmpdir:
101
+
102
+ if filenames is None:
103
+ filenames = [filename]
104
+
105
+ paths = []
106
+ for filename in filenames:
107
+ filename = none_throws(filename)
108
+
109
+ if generate_dense:
110
+ dense_path = os.path.join(tmpdir, filename + "_dense.npy")
111
+ dense = np.random.random((num_rows, INT_FEATURE_COUNT)).astype(
112
+ np.float32
113
+ )
114
+ np.save(dense_path, dense)
115
+ paths.append(dense_path)
116
+
117
+ if generate_sparse:
118
+ sparse_path = os.path.join(tmpdir, filename + "_sparse.npy")
119
+ sparse = np.random.randint(
120
+ cls.CAT_VAL_RANGE[0],
121
+ cls.CAT_VAL_RANGE[1] + 1,
122
+ size=(num_rows, CAT_FEATURE_COUNT),
123
+ dtype=np.int32,
124
+ )
125
+ np.save(sparse_path, sparse)
126
+ paths.append(sparse_path)
127
+
128
+ if generate_labels:
129
+ labels_path = os.path.join(tmpdir, filename + "_labels.npy")
130
+ labels = np.random.randint(
131
+ cls.LABEL_VAL_RANGE[0],
132
+ cls.LABEL_VAL_RANGE[1] + 1,
133
+ size=(num_rows, 1),
134
+ dtype=np.int32,
135
+ )
136
+ np.save(labels_path, labels)
137
+ paths.append(labels_path)
138
+
139
+ yield tuple(paths)