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.
- examples/__init__.py +0 -0
- examples/datasets/__init__.py +8 -0
- examples/datasets/criteo_dataframes.py +101 -0
- examples/ray/__init__.py +0 -0
- examples/ray/compute_world_size.py +51 -0
- examples/ray/train_torchrec.py +133 -0
- examples/retrieval/__init__.py +6 -0
- examples/retrieval/data/__init__.py +6 -0
- examples/retrieval/data/dataloader.py +44 -0
- examples/retrieval/knn_index.py +67 -0
- examples/retrieval/modules/__init__.py +6 -0
- examples/retrieval/modules/two_tower.py +229 -0
- examples/retrieval/two_tower_retrieval.py +192 -0
- examples/retrieval/two_tower_train.py +253 -0
- examples/torcharrow/__init__.py +8 -0
- examples/torcharrow/dataloader.py +116 -0
- examples/torcharrow/run.py +126 -0
- fbgemm_gpu/__init__.py +16 -0
- fbgemm_gpu/batched_unary_embeddings_ops.py +82 -0
- fbgemm_gpu/enums.py +21 -0
- fbgemm_gpu/fbgemm_gpu_py.so +0 -0
- fbgemm_gpu/permute_pooled_embedding_modules.py +73 -0
- fbgemm_gpu/permute_pooled_embedding_modules_split.py +76 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/__init__.py +19 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adagrad.py +120 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adam.py +149 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad.py +128 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_counter.py +134 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_weight_decay.py +128 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_sgd.py +105 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_args.py +54 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lamb.py +149 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lars_sgd.py +128 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_adam.py +149 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_lamb.py +149 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad.py +128 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_counter.py +134 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_weight_decay.py +128 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_weighted_adagrad.py +130 -0
- fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_sgd.py +105 -0
- fbgemm_gpu/split_embedding_configs.py +182 -0
- fbgemm_gpu/split_embedding_inference_converter.py +208 -0
- fbgemm_gpu/split_table_batched_embeddings_ops.py +2503 -0
- fbgemm_gpu/uvm.py +35 -0
- torchrec/__init__.py +27 -0
- torchrec/datasets/__init__.py +31 -0
- torchrec/datasets/criteo.py +831 -0
- torchrec/datasets/movielens.py +140 -0
- torchrec/datasets/random.py +188 -0
- torchrec/datasets/scripts/__init__.py +0 -0
- torchrec/datasets/scripts/contiguous_preproc_criteo.py +75 -0
- torchrec/datasets/scripts/npy_preproc_criteo.py +73 -0
- torchrec/datasets/test_utils/__init__.py +0 -0
- torchrec/datasets/test_utils/criteo_test_utils.py +139 -0
- torchrec/datasets/utils.py +341 -0
- torchrec/distributed/__init__.py +55 -0
- torchrec/distributed/batched_embedding_kernel.py +697 -0
- torchrec/distributed/collective_utils.py +71 -0
- torchrec/distributed/comm.py +149 -0
- torchrec/distributed/comm_ops.py +930 -0
- torchrec/distributed/dist_data.py +949 -0
- torchrec/distributed/embedding.py +638 -0
- torchrec/distributed/embedding_kernel.py +326 -0
- torchrec/distributed/embedding_lookup.py +760 -0
- torchrec/distributed/embedding_sharding.py +660 -0
- torchrec/distributed/embedding_tower_sharding.py +992 -0
- torchrec/distributed/embedding_types.py +369 -0
- torchrec/distributed/embeddingbag.py +731 -0
- torchrec/distributed/fused_embeddingbag.py +148 -0
- torchrec/distributed/grouped_position_weighted.py +103 -0
- torchrec/distributed/model_parallel.py +555 -0
- torchrec/distributed/planner/__init__.py +24 -0
- torchrec/distributed/planner/constants.py +77 -0
- torchrec/distributed/planner/enumerators.py +353 -0
- torchrec/distributed/planner/parallelized_planners.py +307 -0
- torchrec/distributed/planner/partitioners.py +280 -0
- torchrec/distributed/planner/perf_models.py +24 -0
- torchrec/distributed/planner/planners.py +290 -0
- torchrec/distributed/planner/proposers.py +270 -0
- torchrec/distributed/planner/shard_estimators.py +971 -0
- torchrec/distributed/planner/stats.py +477 -0
- torchrec/distributed/planner/storage_reservations.py +168 -0
- torchrec/distributed/planner/types.py +423 -0
- torchrec/distributed/planner/utils.py +30 -0
- torchrec/distributed/quant_embedding.py +307 -0
- torchrec/distributed/quant_embedding_kernel.py +295 -0
- torchrec/distributed/quant_embeddingbag.py +288 -0
- torchrec/distributed/sharding/__init__.py +0 -0
- torchrec/distributed/sharding/cw_sequence_sharding.py +71 -0
- torchrec/distributed/sharding/cw_sharding.py +242 -0
- torchrec/distributed/sharding/dp_sequence_sharding.py +87 -0
- torchrec/distributed/sharding/dp_sharding.py +217 -0
- torchrec/distributed/sharding/rw_sequence_sharding.py +130 -0
- torchrec/distributed/sharding/rw_sharding.py +393 -0
- torchrec/distributed/sharding/sequence_sharding.py +69 -0
- torchrec/distributed/sharding/tw_sequence_sharding.py +211 -0
- torchrec/distributed/sharding/tw_sharding.py +469 -0
- torchrec/distributed/sharding/twcw_sharding.py +32 -0
- torchrec/distributed/sharding/twrw_sharding.py +543 -0
- torchrec/distributed/sharding/vb_cw_sharding.py +91 -0
- torchrec/distributed/sharding/vb_rw_sharding.py +250 -0
- torchrec/distributed/sharding/vb_sharding.py +54 -0
- torchrec/distributed/sharding/vb_tw_sharding.py +148 -0
- torchrec/distributed/sharding/vb_twrw_sharding.py +388 -0
- torchrec/distributed/test_utils/__init__.py +0 -0
- torchrec/distributed/test_utils/multi_process.py +132 -0
- torchrec/distributed/test_utils/test_model.py +818 -0
- torchrec/distributed/test_utils/test_model_parallel.py +74 -0
- torchrec/distributed/test_utils/test_model_parallel_base.py +117 -0
- torchrec/distributed/test_utils/test_sharding.py +280 -0
- torchrec/distributed/train_pipeline.py +531 -0
- torchrec/distributed/types.py +594 -0
- torchrec/distributed/utils.py +186 -0
- torchrec/fused_planner.py +57 -0
- torchrec/fx/__init__.py +15 -0
- torchrec/fx/tracer.py +78 -0
- torchrec/inference/__init__.py +25 -0
- torchrec/inference/client.py +127 -0
- torchrec/inference/model_packager.py +102 -0
- torchrec/inference/modules.py +155 -0
- torchrec/inference/state_dict_transform.py +103 -0
- torchrec/metrics/__init__.py +0 -0
- torchrec/metrics/auc.py +159 -0
- torchrec/metrics/calibration.py +108 -0
- torchrec/metrics/ctr.py +104 -0
- torchrec/metrics/metric_module.py +358 -0
- torchrec/metrics/metrics_config.py +152 -0
- torchrec/metrics/metrics_namespace.py +114 -0
- torchrec/metrics/model_utils.py +85 -0
- torchrec/metrics/mse.py +134 -0
- torchrec/metrics/ne.py +164 -0
- torchrec/metrics/rec_metric.py +686 -0
- torchrec/metrics/throughput.py +174 -0
- torchrec/models/__init__.py +27 -0
- torchrec/models/deepfm.py +346 -0
- torchrec/models/dlrm.py +708 -0
- torchrec/modules/__init__.py +34 -0
- torchrec/modules/activation.py +55 -0
- torchrec/modules/crossnet.py +446 -0
- torchrec/modules/deepfm.py +213 -0
- torchrec/modules/embedding_configs.py +148 -0
- torchrec/modules/embedding_modules.py +381 -0
- torchrec/modules/embedding_tower.py +150 -0
- torchrec/modules/feature_processor.py +74 -0
- torchrec/modules/fused_embedding_modules.py +625 -0
- torchrec/modules/lazy_extension.py +258 -0
- torchrec/modules/mlp.py +172 -0
- torchrec/modules/utils.py +117 -0
- torchrec/optim/__init__.py +35 -0
- torchrec/optim/clipping.py +53 -0
- torchrec/optim/fused.py +42 -0
- torchrec/optim/keyed.py +399 -0
- torchrec/optim/rowwise_adagrad.py +222 -0
- torchrec/optim/test_utils/__init__.py +19 -0
- torchrec/optim/warmup.py +147 -0
- torchrec/quant/__init__.py +34 -0
- torchrec/quant/embedding_modules.py +545 -0
- torchrec/sparse/__init__.py +33 -0
- torchrec/sparse/jagged_tensor.py +1281 -0
- torchrec/sparse/test_utils/__init__.py +45 -0
- torchrec/streamable.py +46 -0
- torchrec/test_utils/__init__.py +111 -0
- torchrec-0.2.dev0.dist-info/LICENSE +29 -0
- torchrec-0.2.dev0.dist-info/METADATA +175 -0
- torchrec-0.2.dev0.dist-info/RECORD +167 -0
- torchrec-0.2.dev0.dist-info/WHEEL +5 -0
- torchrec-0.2.dev0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,831 @@
|
|
|
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
|
+
import time
|
|
10
|
+
from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
import torch
|
|
14
|
+
import torch.utils.data.datapipes as dp
|
|
15
|
+
from iopath.common.file_io import PathManager, PathManagerFactory
|
|
16
|
+
from pyre_extensions import none_throws
|
|
17
|
+
from torch.utils.data import IterableDataset, IterDataPipe
|
|
18
|
+
from torchrec.datasets.utils import (
|
|
19
|
+
Batch,
|
|
20
|
+
LoadFiles,
|
|
21
|
+
PATH_MANAGER_KEY,
|
|
22
|
+
ReadLinesFromCSV,
|
|
23
|
+
safe_cast,
|
|
24
|
+
)
|
|
25
|
+
from torchrec.sparse.jagged_tensor import KeyedJaggedTensor
|
|
26
|
+
|
|
27
|
+
FREQUENCY_THRESHOLD = 3
|
|
28
|
+
INT_FEATURE_COUNT = 13
|
|
29
|
+
CAT_FEATURE_COUNT = 26
|
|
30
|
+
DAYS = 24
|
|
31
|
+
DEFAULT_LABEL_NAME = "label"
|
|
32
|
+
DEFAULT_INT_NAMES: List[str] = [f"int_{idx}" for idx in range(INT_FEATURE_COUNT)]
|
|
33
|
+
DEFAULT_CAT_NAMES: List[str] = [f"cat_{idx}" for idx in range(CAT_FEATURE_COUNT)]
|
|
34
|
+
DEFAULT_COLUMN_NAMES: List[str] = [
|
|
35
|
+
DEFAULT_LABEL_NAME,
|
|
36
|
+
*DEFAULT_INT_NAMES,
|
|
37
|
+
*DEFAULT_CAT_NAMES,
|
|
38
|
+
]
|
|
39
|
+
TOTAL_TRAINING_SAMPLES = 4195197692 # Number of rows across days 0-22 (day 23 is used for validation and testing)
|
|
40
|
+
|
|
41
|
+
COLUMN_TYPE_CASTERS: List[Callable[[Union[int, str]], Union[int, str]]] = [
|
|
42
|
+
lambda val: safe_cast(val, int, 0),
|
|
43
|
+
*(lambda val: safe_cast(val, int, 0) for _ in range(INT_FEATURE_COUNT)),
|
|
44
|
+
*(lambda val: safe_cast(val, str, "") for _ in range(CAT_FEATURE_COUNT)),
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _default_row_mapper(example: List[str]) -> Dict[str, Union[int, str]]:
|
|
49
|
+
column_names = reversed(DEFAULT_COLUMN_NAMES)
|
|
50
|
+
column_type_casters = reversed(COLUMN_TYPE_CASTERS)
|
|
51
|
+
return {
|
|
52
|
+
next(column_names): next(column_type_casters)(val) for val in reversed(example)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class CriteoIterDataPipe(IterDataPipe):
|
|
57
|
+
"""
|
|
58
|
+
IterDataPipe that can be used to stream either the Criteo 1TB Click Logs Dataset
|
|
59
|
+
(https://ailab.criteo.com/download-criteo-1tb-click-logs-dataset/) or the
|
|
60
|
+
Kaggle/Criteo Display Advertising Dataset
|
|
61
|
+
(https://www.kaggle.com/c/criteo-display-ad-challenge/) from the source TSV
|
|
62
|
+
files.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
paths (Iterable[str]): local paths to TSV files that constitute the Criteo
|
|
66
|
+
dataset.
|
|
67
|
+
row_mapper (Optional[Callable[[List[str]], Any]]): function to apply to each
|
|
68
|
+
split TSV line.
|
|
69
|
+
open_kw: options to pass to underlying invocation of
|
|
70
|
+
iopath.common.file_io.PathManager.open.
|
|
71
|
+
|
|
72
|
+
Example::
|
|
73
|
+
|
|
74
|
+
datapipe = CriteoIterDataPipe(
|
|
75
|
+
("/home/datasets/criteo/day_0.tsv", "/home/datasets/criteo/day_1.tsv")
|
|
76
|
+
)
|
|
77
|
+
datapipe = dp.iter.Batcher(datapipe, 100)
|
|
78
|
+
datapipe = dp.iter.Collator(datapipe)
|
|
79
|
+
batch = next(iter(datapipe))
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
paths: Iterable[str],
|
|
85
|
+
*,
|
|
86
|
+
# pyre-ignore[2]
|
|
87
|
+
row_mapper: Optional[Callable[[List[str]], Any]] = _default_row_mapper,
|
|
88
|
+
# pyre-ignore[2]
|
|
89
|
+
**open_kw,
|
|
90
|
+
) -> None:
|
|
91
|
+
self.paths = paths
|
|
92
|
+
self.row_mapper = row_mapper
|
|
93
|
+
self.open_kw: Any = open_kw # pyre-ignore[4]
|
|
94
|
+
|
|
95
|
+
# pyre-ignore[3]
|
|
96
|
+
def __iter__(self) -> Iterator[Any]:
|
|
97
|
+
worker_info = torch.utils.data.get_worker_info()
|
|
98
|
+
paths = self.paths
|
|
99
|
+
if worker_info is not None:
|
|
100
|
+
paths = (
|
|
101
|
+
path
|
|
102
|
+
for (idx, path) in enumerate(paths)
|
|
103
|
+
if idx % worker_info.num_workers == worker_info.id
|
|
104
|
+
)
|
|
105
|
+
datapipe = LoadFiles(paths, mode="r", **self.open_kw)
|
|
106
|
+
datapipe = ReadLinesFromCSV(datapipe, delimiter="\t")
|
|
107
|
+
if self.row_mapper:
|
|
108
|
+
datapipe = dp.iter.Mapper(datapipe, self.row_mapper)
|
|
109
|
+
yield from datapipe
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def criteo_terabyte(
|
|
113
|
+
paths: Iterable[str],
|
|
114
|
+
*,
|
|
115
|
+
# pyre-ignore[2]
|
|
116
|
+
row_mapper: Optional[Callable[[List[str]], Any]] = _default_row_mapper,
|
|
117
|
+
# pyre-ignore[2]
|
|
118
|
+
**open_kw,
|
|
119
|
+
) -> IterDataPipe:
|
|
120
|
+
"""`Criteo 1TB Click Logs <https://ailab.criteo.com/download-criteo-1tb-click-logs-dataset/>`_ Dataset
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
paths (Iterable[str]): local paths to TSV files that constitute the Criteo 1TB
|
|
124
|
+
dataset.
|
|
125
|
+
row_mapper (Optional[Callable[[List[str]], Any]]): function to apply to each
|
|
126
|
+
split TSV line.
|
|
127
|
+
open_kw: options to pass to underlying invocation of
|
|
128
|
+
iopath.common.file_io.PathManager.open.
|
|
129
|
+
|
|
130
|
+
Example::
|
|
131
|
+
|
|
132
|
+
datapipe = criteo_terabyte(
|
|
133
|
+
("/home/datasets/criteo/day_0.tsv", "/home/datasets/criteo/day_1.tsv")
|
|
134
|
+
)
|
|
135
|
+
datapipe = dp.iter.Batcher(datapipe, 100)
|
|
136
|
+
datapipe = dp.iter.Collator(datapipe)
|
|
137
|
+
batch = next(iter(datapipe))
|
|
138
|
+
"""
|
|
139
|
+
return CriteoIterDataPipe(paths, row_mapper=row_mapper, **open_kw)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def criteo_kaggle(
|
|
143
|
+
path: str,
|
|
144
|
+
*,
|
|
145
|
+
# pyre-ignore[2]
|
|
146
|
+
row_mapper: Optional[Callable[[List[str]], Any]] = _default_row_mapper,
|
|
147
|
+
# pyre-ignore[2]
|
|
148
|
+
**open_kw,
|
|
149
|
+
) -> IterDataPipe:
|
|
150
|
+
"""`Kaggle/Criteo Display Advertising <https://www.kaggle.com/c/criteo-display-ad-challenge/>`_ Dataset
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
root (str): local path to train or test dataset file.
|
|
154
|
+
row_mapper (Optional[Callable[[List[str]], Any]]): function to apply to each split TSV line.
|
|
155
|
+
open_kw: options to pass to underlying invocation of iopath.common.file_io.PathManager.open.
|
|
156
|
+
|
|
157
|
+
Example::
|
|
158
|
+
|
|
159
|
+
train_datapipe = criteo_kaggle(
|
|
160
|
+
"/home/datasets/criteo_kaggle/train.txt",
|
|
161
|
+
)
|
|
162
|
+
example = next(iter(train_datapipe))
|
|
163
|
+
test_datapipe = criteo_kaggle(
|
|
164
|
+
"/home/datasets/criteo_kaggle/test.txt",
|
|
165
|
+
)
|
|
166
|
+
example = next(iter(test_datapipe))
|
|
167
|
+
"""
|
|
168
|
+
return CriteoIterDataPipe((path,), row_mapper=row_mapper, **open_kw)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class BinaryCriteoUtils:
|
|
172
|
+
"""
|
|
173
|
+
Utility functions used to preprocess, save, load, partition, etc. the Criteo
|
|
174
|
+
dataset in a binary (numpy) format.
|
|
175
|
+
"""
|
|
176
|
+
|
|
177
|
+
@staticmethod
|
|
178
|
+
def tsv_to_npys(
|
|
179
|
+
in_file: str,
|
|
180
|
+
out_dense_file: str,
|
|
181
|
+
out_sparse_file: str,
|
|
182
|
+
out_labels_file: str,
|
|
183
|
+
path_manager_key: str = PATH_MANAGER_KEY,
|
|
184
|
+
) -> None:
|
|
185
|
+
"""
|
|
186
|
+
Convert one Criteo tsv file to three npy files: one for dense (np.float32), one
|
|
187
|
+
for sparse (np.int32), and one for labels (np.int32).
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
in_file (str): Input tsv file path.
|
|
191
|
+
out_dense_file (str): Output dense npy file path.
|
|
192
|
+
out_sparse_file (str): Output sparse npy file path.
|
|
193
|
+
out_labels_file (str): Output labels npy file path.
|
|
194
|
+
path_manager_key (str): Path manager key used to load from different
|
|
195
|
+
filesystems.
|
|
196
|
+
|
|
197
|
+
Returns:
|
|
198
|
+
None.
|
|
199
|
+
"""
|
|
200
|
+
|
|
201
|
+
def row_mapper(row: List[str]) -> Tuple[List[int], List[int], int]:
|
|
202
|
+
# Missing values are mapped to zero for both dense and sparse features
|
|
203
|
+
label = int(row[0] or "0")
|
|
204
|
+
dense = [int(row[i] or "0") for i in range(1, 1 + INT_FEATURE_COUNT)]
|
|
205
|
+
sparse = [
|
|
206
|
+
int(row[i] or "0", 16)
|
|
207
|
+
for i in range(
|
|
208
|
+
1 + INT_FEATURE_COUNT, 1 + INT_FEATURE_COUNT + CAT_FEATURE_COUNT
|
|
209
|
+
)
|
|
210
|
+
]
|
|
211
|
+
return dense, sparse, label
|
|
212
|
+
|
|
213
|
+
dense, sparse, labels = [], [], []
|
|
214
|
+
for (row_dense, row_sparse, row_label) in CriteoIterDataPipe(
|
|
215
|
+
[in_file], row_mapper=row_mapper
|
|
216
|
+
):
|
|
217
|
+
dense.append(row_dense)
|
|
218
|
+
sparse.append(row_sparse)
|
|
219
|
+
labels.append(row_label)
|
|
220
|
+
|
|
221
|
+
# PyTorch tensors can't handle uint32, but we can save space by not
|
|
222
|
+
# using int64. Numpy will automatically handle dense values >= 2 ** 31.
|
|
223
|
+
dense_np = np.array(dense, dtype=np.int32)
|
|
224
|
+
del dense
|
|
225
|
+
sparse_np = np.array(sparse, dtype=np.int32)
|
|
226
|
+
del sparse
|
|
227
|
+
labels_np = np.array(labels, dtype=np.int32)
|
|
228
|
+
del labels
|
|
229
|
+
|
|
230
|
+
# Log is expensive to compute at runtime.
|
|
231
|
+
dense_np += 3
|
|
232
|
+
dense_np = np.log(dense_np, dtype=np.float32)
|
|
233
|
+
|
|
234
|
+
# To be consistent with dense and sparse.
|
|
235
|
+
labels_np = labels_np.reshape((-1, 1))
|
|
236
|
+
|
|
237
|
+
path_manager = PathManagerFactory().get(path_manager_key)
|
|
238
|
+
for (fname, arr) in [
|
|
239
|
+
(out_dense_file, dense_np),
|
|
240
|
+
(out_sparse_file, sparse_np),
|
|
241
|
+
(out_labels_file, labels_np),
|
|
242
|
+
]:
|
|
243
|
+
with path_manager.open(fname, "wb") as fout:
|
|
244
|
+
np.save(fout, arr)
|
|
245
|
+
|
|
246
|
+
@staticmethod
|
|
247
|
+
def get_shape_from_npy(
|
|
248
|
+
path: str, path_manager_key: str = PATH_MANAGER_KEY
|
|
249
|
+
) -> Tuple[int, ...]:
|
|
250
|
+
"""
|
|
251
|
+
Returns the shape of an npy file using only its header.
|
|
252
|
+
|
|
253
|
+
Args:
|
|
254
|
+
path (str): Input npy file path.
|
|
255
|
+
path_manager_key (str): Path manager key used to load from different
|
|
256
|
+
filesystems.
|
|
257
|
+
|
|
258
|
+
Returns:
|
|
259
|
+
shape (Tuple[int, ...]): Shape tuple.
|
|
260
|
+
"""
|
|
261
|
+
path_manager = PathManagerFactory().get(path_manager_key)
|
|
262
|
+
with path_manager.open(path, "rb") as fin:
|
|
263
|
+
np.lib.format.read_magic(fin)
|
|
264
|
+
shape, _order, _dtype = np.lib.format.read_array_header_1_0(fin)
|
|
265
|
+
return shape
|
|
266
|
+
|
|
267
|
+
@staticmethod
|
|
268
|
+
def get_file_idx_to_row_range(
|
|
269
|
+
lengths: List[int],
|
|
270
|
+
rank: int,
|
|
271
|
+
world_size: int,
|
|
272
|
+
) -> Dict[int, Tuple[int, int]]:
|
|
273
|
+
"""
|
|
274
|
+
Given a rank, world_size, and the lengths (number of rows) for a list of files,
|
|
275
|
+
return which files and which portions of those files (represented as row ranges
|
|
276
|
+
- all range indices are inclusive) should be handled by the rank. Each rank
|
|
277
|
+
will be assigned the same number of rows.
|
|
278
|
+
|
|
279
|
+
The ranges are determined in such a way that each rank deals with large
|
|
280
|
+
continuous ranges of files. This enables each rank to reduce the amount of data
|
|
281
|
+
it needs to read while avoiding seeks.
|
|
282
|
+
|
|
283
|
+
Args:
|
|
284
|
+
lengths (List[int]): A list of row counts for each file.
|
|
285
|
+
rank (int): rank.
|
|
286
|
+
world_size (int): world size.
|
|
287
|
+
|
|
288
|
+
Returns:
|
|
289
|
+
output (Dict[int, Tuple[int, int]]): Mapping of which files to the range in
|
|
290
|
+
those files to be handled by the rank. The keys of this dict are indices
|
|
291
|
+
of lengths.
|
|
292
|
+
"""
|
|
293
|
+
|
|
294
|
+
# All ..._g variables are globals indices (meaning they range from 0 to
|
|
295
|
+
# total_length - 1). All ..._l variables are local indices (meaning they range
|
|
296
|
+
# from 0 to lengths[i] - 1 for the ith file).
|
|
297
|
+
|
|
298
|
+
total_length = sum(lengths)
|
|
299
|
+
rows_per_rank = total_length // world_size
|
|
300
|
+
|
|
301
|
+
# Global indices that rank is responsible for. All ranges (left, right) are
|
|
302
|
+
# inclusive.
|
|
303
|
+
rank_left_g = rank * rows_per_rank
|
|
304
|
+
rank_right_g = (rank + 1) * rows_per_rank - 1
|
|
305
|
+
|
|
306
|
+
output = {}
|
|
307
|
+
|
|
308
|
+
# Find where range (rank_left_g, rank_right_g) intersects each file's range.
|
|
309
|
+
file_left_g, file_right_g = -1, -1
|
|
310
|
+
for idx, length in enumerate(lengths):
|
|
311
|
+
file_left_g = file_right_g + 1
|
|
312
|
+
file_right_g = file_left_g + length - 1
|
|
313
|
+
|
|
314
|
+
# If the ranges overlap.
|
|
315
|
+
if rank_left_g <= file_right_g and rank_right_g >= file_left_g:
|
|
316
|
+
overlap_left_g, overlap_right_g = max(rank_left_g, file_left_g), min(
|
|
317
|
+
rank_right_g, file_right_g
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
# Convert overlap in global numbers to (local) numbers specific to the
|
|
321
|
+
# file.
|
|
322
|
+
overlap_left_l = overlap_left_g - file_left_g
|
|
323
|
+
overlap_right_l = overlap_right_g - file_left_g
|
|
324
|
+
output[idx] = (overlap_left_l, overlap_right_l)
|
|
325
|
+
|
|
326
|
+
return output
|
|
327
|
+
|
|
328
|
+
@staticmethod
|
|
329
|
+
def load_npy_range(
|
|
330
|
+
fname: str,
|
|
331
|
+
start_row: int,
|
|
332
|
+
num_rows: int,
|
|
333
|
+
path_manager_key: str = PATH_MANAGER_KEY,
|
|
334
|
+
mmap_mode: bool = False,
|
|
335
|
+
) -> np.ndarray:
|
|
336
|
+
"""
|
|
337
|
+
Load part of an npy file.
|
|
338
|
+
|
|
339
|
+
NOTE: Assumes npy represents a numpy array of ndim 2.
|
|
340
|
+
|
|
341
|
+
Args:
|
|
342
|
+
fname (str): path string to npy file.
|
|
343
|
+
start_row (int): starting row from the npy file.
|
|
344
|
+
num_rows (int): number of rows to get from the npy file.
|
|
345
|
+
path_manager_key (str): Path manager key used to load from different
|
|
346
|
+
filesystems.
|
|
347
|
+
|
|
348
|
+
Returns:
|
|
349
|
+
output (np.ndarray): numpy array with the desired range of data from the
|
|
350
|
+
supplied npy file.
|
|
351
|
+
"""
|
|
352
|
+
path_manager = PathManagerFactory().get(path_manager_key)
|
|
353
|
+
with path_manager.open(fname, "rb") as fin:
|
|
354
|
+
np.lib.format.read_magic(fin)
|
|
355
|
+
shape, _order, dtype = np.lib.format.read_array_header_1_0(fin)
|
|
356
|
+
if len(shape) == 2:
|
|
357
|
+
total_rows, row_size = shape
|
|
358
|
+
else:
|
|
359
|
+
raise ValueError("Cannot load range for npy with ndim == 2.")
|
|
360
|
+
|
|
361
|
+
if not (0 <= start_row < total_rows):
|
|
362
|
+
raise ValueError(
|
|
363
|
+
f"start_row ({start_row}) is out of bounds. It must be between 0 "
|
|
364
|
+
f"and {total_rows - 1}, inclusive."
|
|
365
|
+
)
|
|
366
|
+
if not (start_row + num_rows <= total_rows):
|
|
367
|
+
raise ValueError(
|
|
368
|
+
f"num_rows ({num_rows}) exceeds number of available rows "
|
|
369
|
+
f"({total_rows}) for the given start_row ({start_row})."
|
|
370
|
+
)
|
|
371
|
+
if mmap_mode:
|
|
372
|
+
data = np.load(fname, mmap_mode="r")
|
|
373
|
+
data = data[start_row : start_row + num_rows]
|
|
374
|
+
else:
|
|
375
|
+
offset = start_row * row_size * dtype.itemsize
|
|
376
|
+
fin.seek(offset, os.SEEK_CUR)
|
|
377
|
+
num_entries = num_rows * row_size
|
|
378
|
+
data = np.fromfile(fin, dtype=dtype, count=num_entries)
|
|
379
|
+
return data.reshape((num_rows, row_size))
|
|
380
|
+
|
|
381
|
+
@staticmethod
|
|
382
|
+
def sparse_to_contiguous(
|
|
383
|
+
in_files: List[str],
|
|
384
|
+
output_dir: str,
|
|
385
|
+
frequency_threshold: int = FREQUENCY_THRESHOLD,
|
|
386
|
+
columns: int = CAT_FEATURE_COUNT,
|
|
387
|
+
path_manager_key: str = PATH_MANAGER_KEY,
|
|
388
|
+
output_file_suffix: str = "_contig_freq.npy",
|
|
389
|
+
) -> None:
|
|
390
|
+
"""
|
|
391
|
+
Convert all sparse .npy files to have contiguous integers. Store in a separate
|
|
392
|
+
.npy file. All input files must be processed together because columns
|
|
393
|
+
can have matching IDs between files. Hence, they must be transformed
|
|
394
|
+
together. Also, the transformed IDs are not unique between columns. IDs
|
|
395
|
+
that appear less than frequency_threshold amount of times will be remapped
|
|
396
|
+
to have a value of 1.
|
|
397
|
+
|
|
398
|
+
Example transformation, frequenchy_threshold of 2:
|
|
399
|
+
day_0_sparse.npy
|
|
400
|
+
| col_0 | col_1 |
|
|
401
|
+
-----------------
|
|
402
|
+
| abc | xyz |
|
|
403
|
+
| iop | xyz |
|
|
404
|
+
|
|
405
|
+
day_1_sparse.npy
|
|
406
|
+
| col_0 | col_1 |
|
|
407
|
+
-----------------
|
|
408
|
+
| iop | tuv |
|
|
409
|
+
| lkj | xyz |
|
|
410
|
+
|
|
411
|
+
day_0_sparse_contig.npy
|
|
412
|
+
| col_0 | col_1 |
|
|
413
|
+
-----------------
|
|
414
|
+
| 1 | 2 |
|
|
415
|
+
| 2 | 2 |
|
|
416
|
+
|
|
417
|
+
day_1_sparse_contig.npy
|
|
418
|
+
| col_0 | col_1 |
|
|
419
|
+
-----------------
|
|
420
|
+
| 2 | 1 |
|
|
421
|
+
| 1 | 2 |
|
|
422
|
+
|
|
423
|
+
Args:
|
|
424
|
+
in_files List[str]: Input directory of npy files.
|
|
425
|
+
out_dir (str): Output directory of processed npy files.
|
|
426
|
+
frequency_threshold: IDs occuring less than this frequency will be remapped to a value of 1.
|
|
427
|
+
path_manager_key (str): Path manager key used to load from different filesystems.
|
|
428
|
+
|
|
429
|
+
Returns:
|
|
430
|
+
None.
|
|
431
|
+
"""
|
|
432
|
+
|
|
433
|
+
# Load each .npy file of sparse features. Transformations are made along the columns.
|
|
434
|
+
# Thereby, transpose the input to ease operations.
|
|
435
|
+
# E.g. file_to_features = {"day_0_sparse": [array([[3,6,7],[7,9,3]]}
|
|
436
|
+
file_to_features: Dict[str, np.ndarray] = {}
|
|
437
|
+
for f in in_files:
|
|
438
|
+
name = os.path.basename(f).split(".")[0]
|
|
439
|
+
file_to_features[name] = np.load(f).transpose()
|
|
440
|
+
print(f"Successfully loaded file: {f}")
|
|
441
|
+
|
|
442
|
+
# Iterate through each column in each file and map the sparse ids to contiguous ids.
|
|
443
|
+
for col in range(columns):
|
|
444
|
+
print(f"Processing column: {col}")
|
|
445
|
+
|
|
446
|
+
# Iterate through each row in each file for the current column and determine the
|
|
447
|
+
# frequency of each sparse id.
|
|
448
|
+
sparse_to_frequency: Dict[int, int] = {}
|
|
449
|
+
if frequency_threshold > 1:
|
|
450
|
+
for f in file_to_features:
|
|
451
|
+
for _, sparse in enumerate(file_to_features[f][col]):
|
|
452
|
+
if sparse in sparse_to_frequency:
|
|
453
|
+
sparse_to_frequency[sparse] += 1
|
|
454
|
+
else:
|
|
455
|
+
sparse_to_frequency[sparse] = 1
|
|
456
|
+
|
|
457
|
+
# Iterate through each row in each file for the current column and remap each
|
|
458
|
+
# sparse id to a contiguous id. The contiguous ints start at a value of 2 so that
|
|
459
|
+
# infrequenct IDs (determined by the frequency_threshold) can be remapped to 1.
|
|
460
|
+
running_sum = 2
|
|
461
|
+
sparse_to_contiguous_int: Dict[int, int] = {}
|
|
462
|
+
|
|
463
|
+
for f in file_to_features:
|
|
464
|
+
print(f"Processing file: {f}")
|
|
465
|
+
|
|
466
|
+
for i, sparse in enumerate(file_to_features[f][col]):
|
|
467
|
+
if sparse not in sparse_to_contiguous_int:
|
|
468
|
+
# If the ID appears less than frequency_threshold amount of times
|
|
469
|
+
# remap the value to 1.
|
|
470
|
+
if (
|
|
471
|
+
frequency_threshold > 1
|
|
472
|
+
and sparse_to_frequency[sparse] < frequency_threshold
|
|
473
|
+
):
|
|
474
|
+
sparse_to_contiguous_int[sparse] = 1
|
|
475
|
+
else:
|
|
476
|
+
sparse_to_contiguous_int[sparse] = running_sum
|
|
477
|
+
running_sum += 1
|
|
478
|
+
|
|
479
|
+
# Re-map sparse value to contiguous in place.
|
|
480
|
+
file_to_features[f][col][i] = sparse_to_contiguous_int[sparse]
|
|
481
|
+
|
|
482
|
+
path_manager = PathManagerFactory().get(path_manager_key)
|
|
483
|
+
for f, features in file_to_features.items():
|
|
484
|
+
output_file = os.path.join(output_dir, f + output_file_suffix)
|
|
485
|
+
with path_manager.open(output_file, "wb") as fout:
|
|
486
|
+
print(f"Writing file: {output_file}")
|
|
487
|
+
# Transpose back the features when saving, as they were transposed when loading.
|
|
488
|
+
np.save(fout, features.transpose())
|
|
489
|
+
|
|
490
|
+
@staticmethod
|
|
491
|
+
def shuffle(
|
|
492
|
+
input_dir_labels_and_dense: str,
|
|
493
|
+
input_dir_sparse: str,
|
|
494
|
+
output_dir_shuffled: str,
|
|
495
|
+
rows_per_day: Dict[int, int],
|
|
496
|
+
output_dir_full_set: Optional[str] = None,
|
|
497
|
+
days: int = DAYS,
|
|
498
|
+
int_columns: int = INT_FEATURE_COUNT,
|
|
499
|
+
sparse_columns: int = CAT_FEATURE_COUNT,
|
|
500
|
+
path_manager_key: str = PATH_MANAGER_KEY,
|
|
501
|
+
) -> None:
|
|
502
|
+
"""
|
|
503
|
+
Shuffle the dataset. Expects the files to be in .npy format and the data
|
|
504
|
+
to be split by day and by dense, sparse and label data.
|
|
505
|
+
Dense data must be in: day_x_dense.npy
|
|
506
|
+
Sparse data must be in: day_x_sparse.npy
|
|
507
|
+
Labels data must be in: day_x_labels.npy
|
|
508
|
+
|
|
509
|
+
The dataset will be reconstructed, shuffled and then split back into
|
|
510
|
+
separate dense, sparse and labels files.
|
|
511
|
+
|
|
512
|
+
Args:
|
|
513
|
+
input_dir_labels_and_dense (str): Input directory of labels and dense npy files.
|
|
514
|
+
input_dir_sparse (str): Input directory of sparse npy files.
|
|
515
|
+
output_dir_shuffled (str): Output directory for shuffled labels, dense and sparse npy files.
|
|
516
|
+
rows_per_day Dict[int, int]: Number of rows in each file.
|
|
517
|
+
output_dir_full_set (str): Output directory of the full dataset, if desired.
|
|
518
|
+
days (int): Number of day files.
|
|
519
|
+
int_columns (int): Number of columns with dense features.
|
|
520
|
+
columns (int): Total number of columns.
|
|
521
|
+
path_manager_key (str): Path manager key used to load from different filesystems.
|
|
522
|
+
"""
|
|
523
|
+
|
|
524
|
+
total_rows = sum(rows_per_day.values())
|
|
525
|
+
columns = int_columns + sparse_columns + 1 # add 1 for label column
|
|
526
|
+
full_dataset = np.zeros((total_rows, columns), dtype=np.float32)
|
|
527
|
+
curr_first_row = 0
|
|
528
|
+
curr_last_row = 0
|
|
529
|
+
for d in range(0, days):
|
|
530
|
+
curr_last_row += rows_per_day[d]
|
|
531
|
+
|
|
532
|
+
# dense
|
|
533
|
+
path_to_file = os.path.join(
|
|
534
|
+
input_dir_labels_and_dense, f"day_{d}_dense.npy"
|
|
535
|
+
)
|
|
536
|
+
data = np.load(path_to_file)
|
|
537
|
+
print(
|
|
538
|
+
f"Day {d} dense- {curr_first_row}-{curr_last_row} loaded files - {time.time()} - {path_to_file}"
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
full_dataset[curr_first_row:curr_last_row, 0:int_columns] = data
|
|
542
|
+
del data
|
|
543
|
+
|
|
544
|
+
# sparse
|
|
545
|
+
path_to_file = os.path.join(input_dir_sparse, f"day_{d}_sparse.npy")
|
|
546
|
+
data = np.load(path_to_file)
|
|
547
|
+
print(
|
|
548
|
+
f"Day {d} sparse- {curr_first_row}-{curr_last_row} loaded files - {time.time()} - {path_to_file}"
|
|
549
|
+
)
|
|
550
|
+
|
|
551
|
+
full_dataset[curr_first_row:curr_last_row, int_columns : columns - 1] = data
|
|
552
|
+
del data
|
|
553
|
+
|
|
554
|
+
# labels
|
|
555
|
+
path_to_file = os.path.join(
|
|
556
|
+
input_dir_labels_and_dense, f"day_{d}_labels.npy"
|
|
557
|
+
)
|
|
558
|
+
data = np.load(path_to_file)
|
|
559
|
+
print(
|
|
560
|
+
f"Day {d} labels- {curr_first_row}-{curr_last_row} loaded files - {time.time()} - {path_to_file}"
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
full_dataset[curr_first_row:curr_last_row, columns - 1 :] = data
|
|
564
|
+
del data
|
|
565
|
+
|
|
566
|
+
curr_first_row = curr_last_row
|
|
567
|
+
|
|
568
|
+
path_manager = PathManagerFactory().get(path_manager_key)
|
|
569
|
+
|
|
570
|
+
# Save the full dataset
|
|
571
|
+
if output_dir_full_set is not None:
|
|
572
|
+
full_output_file = os.path.join(output_dir_full_set, "full.npy")
|
|
573
|
+
with path_manager.open(full_output_file, "wb") as fout:
|
|
574
|
+
print(f"Writing full set file: {full_output_file}")
|
|
575
|
+
np.save(fout, full_dataset)
|
|
576
|
+
|
|
577
|
+
print("Shuffling dataset")
|
|
578
|
+
np.random.shuffle(full_dataset)
|
|
579
|
+
|
|
580
|
+
# Slice and save each portion into dense, sparse and labels
|
|
581
|
+
curr_first_row = 0
|
|
582
|
+
curr_last_row = 0
|
|
583
|
+
for d in range(0, days):
|
|
584
|
+
curr_last_row += rows_per_day[d]
|
|
585
|
+
|
|
586
|
+
# write dense columns
|
|
587
|
+
shuffled_dense_file = os.path.join(
|
|
588
|
+
output_dir_shuffled, f"day_{d}_dense.npy"
|
|
589
|
+
)
|
|
590
|
+
with path_manager.open(shuffled_dense_file, "wb") as fout:
|
|
591
|
+
print(
|
|
592
|
+
f"Writing rows {curr_first_row}-{curr_last_row-1} dense file: {shuffled_dense_file}"
|
|
593
|
+
)
|
|
594
|
+
np.save(fout, full_dataset[curr_first_row:curr_last_row, 0:int_columns])
|
|
595
|
+
|
|
596
|
+
# write sparse columns
|
|
597
|
+
shuffled_sparse_file = os.path.join(
|
|
598
|
+
output_dir_shuffled, f"day_{d}_sparse.npy"
|
|
599
|
+
)
|
|
600
|
+
with path_manager.open(shuffled_sparse_file, "wb") as fout:
|
|
601
|
+
print(
|
|
602
|
+
f"Writing rows {curr_first_row}-{curr_last_row-1} sparse file: {shuffled_sparse_file}"
|
|
603
|
+
)
|
|
604
|
+
np.save(
|
|
605
|
+
fout,
|
|
606
|
+
full_dataset[
|
|
607
|
+
curr_first_row:curr_last_row, int_columns : columns - 1
|
|
608
|
+
].astype(np.int32),
|
|
609
|
+
)
|
|
610
|
+
|
|
611
|
+
# write labels columns
|
|
612
|
+
shuffled_labels_file = os.path.join(
|
|
613
|
+
output_dir_shuffled, f"day_{d}_labels.npy"
|
|
614
|
+
)
|
|
615
|
+
with path_manager.open(shuffled_labels_file, "wb") as fout:
|
|
616
|
+
print(
|
|
617
|
+
f"Writing rows {curr_first_row}-{curr_last_row-1} labels file: {shuffled_labels_file}"
|
|
618
|
+
)
|
|
619
|
+
np.save(
|
|
620
|
+
fout,
|
|
621
|
+
full_dataset[curr_first_row:curr_last_row, columns - 1 :].astype(
|
|
622
|
+
np.int32
|
|
623
|
+
),
|
|
624
|
+
)
|
|
625
|
+
|
|
626
|
+
curr_first_row = curr_last_row
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
class InMemoryBinaryCriteoIterDataPipe(IterableDataset):
|
|
630
|
+
"""
|
|
631
|
+
Datapipe designed to operate over binary (npy) versions of Criteo datasets. Loads
|
|
632
|
+
the entire dataset into memory to prevent disk speed from affecting throughout. Each
|
|
633
|
+
rank reads only the data for the portion of the dataset it is responsible for.
|
|
634
|
+
|
|
635
|
+
The torchrec/datasets/scripts/npy_preproc_criteo.py script can be used to convert
|
|
636
|
+
the Criteo tsv files to the npy files expected by this dataset.
|
|
637
|
+
|
|
638
|
+
Args:
|
|
639
|
+
dense_paths (List[str]): List of path strings to dense npy files.
|
|
640
|
+
sparse_paths (List[str]): List of path strings to sparse npy files.
|
|
641
|
+
labels_paths (List[str]): List of path strings to labels npy files.
|
|
642
|
+
batch_size (int): batch size.
|
|
643
|
+
rank (int): rank.
|
|
644
|
+
world_size (int): world size.
|
|
645
|
+
shuffle_batches (bool): Whether to shuffle batches
|
|
646
|
+
hashes (Optional[int]): List of max categorical feature value for each feature.
|
|
647
|
+
Length of this list should be CAT_FEATURE_COUNT.
|
|
648
|
+
path_manager_key (str): Path manager key used to load from different
|
|
649
|
+
filesystems.
|
|
650
|
+
|
|
651
|
+
Example::
|
|
652
|
+
|
|
653
|
+
template = "/home/datasets/criteo/1tb_binary/day_{}_{}.npy"
|
|
654
|
+
datapipe = InMemoryBinaryCriteoIterDataPipe(
|
|
655
|
+
dense_paths=[template.format(0, "dense"), template.format(1, "dense")],
|
|
656
|
+
sparse_paths=[template.format(0, "sparse"), template.format(1, "sparse")],
|
|
657
|
+
labels_paths=[template.format(0, "labels"), template.format(1, "labels")],
|
|
658
|
+
batch_size=1024,
|
|
659
|
+
rank=torch.distributed.get_rank(),
|
|
660
|
+
world_size=torch.distributed.get_world_size(),
|
|
661
|
+
)
|
|
662
|
+
batch = next(iter(datapipe))
|
|
663
|
+
"""
|
|
664
|
+
|
|
665
|
+
def __init__(
|
|
666
|
+
self,
|
|
667
|
+
dense_paths: List[str],
|
|
668
|
+
sparse_paths: List[str],
|
|
669
|
+
labels_paths: List[str],
|
|
670
|
+
batch_size: int,
|
|
671
|
+
rank: int,
|
|
672
|
+
world_size: int,
|
|
673
|
+
shuffle_batches: bool = False,
|
|
674
|
+
mmap_mode: bool = False,
|
|
675
|
+
hashes: Optional[List[int]] = None,
|
|
676
|
+
path_manager_key: str = PATH_MANAGER_KEY,
|
|
677
|
+
) -> None:
|
|
678
|
+
self.dense_paths = dense_paths
|
|
679
|
+
self.sparse_paths = sparse_paths
|
|
680
|
+
self.labels_paths = labels_paths
|
|
681
|
+
self.batch_size = batch_size
|
|
682
|
+
self.rank = rank
|
|
683
|
+
self.world_size = world_size
|
|
684
|
+
self.shuffle_batches = shuffle_batches
|
|
685
|
+
self.mmap_mode = mmap_mode
|
|
686
|
+
self.hashes = hashes
|
|
687
|
+
self.path_manager_key = path_manager_key
|
|
688
|
+
self.path_manager: PathManager = PathManagerFactory().get(path_manager_key)
|
|
689
|
+
|
|
690
|
+
self._load_data_for_rank()
|
|
691
|
+
self.num_rows_per_file: List[int] = [a.shape[0] for a in self.dense_arrs]
|
|
692
|
+
self.num_batches: int = sum(self.num_rows_per_file) // batch_size
|
|
693
|
+
|
|
694
|
+
# These values are the same for the KeyedJaggedTensors in all batches, so they
|
|
695
|
+
# are computed once here. This avoids extra work from the KeyedJaggedTensor sync
|
|
696
|
+
# functions.
|
|
697
|
+
self._num_ids_in_batch: int = CAT_FEATURE_COUNT * batch_size
|
|
698
|
+
self.keys: List[str] = DEFAULT_CAT_NAMES
|
|
699
|
+
self.lengths: torch.Tensor = torch.ones(
|
|
700
|
+
(self._num_ids_in_batch,), dtype=torch.int32
|
|
701
|
+
)
|
|
702
|
+
self.offsets: torch.Tensor = torch.arange(
|
|
703
|
+
0, self._num_ids_in_batch + 1, dtype=torch.int32
|
|
704
|
+
)
|
|
705
|
+
self.stride = batch_size
|
|
706
|
+
self.length_per_key: List[int] = CAT_FEATURE_COUNT * [batch_size]
|
|
707
|
+
self.offset_per_key: List[int] = [
|
|
708
|
+
batch_size * i for i in range(CAT_FEATURE_COUNT + 1)
|
|
709
|
+
]
|
|
710
|
+
self.index_per_key: Dict[str, int] = {
|
|
711
|
+
key: i for (i, key) in enumerate(self.keys)
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
def _load_data_for_rank(self) -> None:
|
|
715
|
+
file_idx_to_row_range = BinaryCriteoUtils.get_file_idx_to_row_range(
|
|
716
|
+
lengths=[
|
|
717
|
+
BinaryCriteoUtils.get_shape_from_npy(
|
|
718
|
+
path, path_manager_key=self.path_manager_key
|
|
719
|
+
)[0]
|
|
720
|
+
for path in self.dense_paths
|
|
721
|
+
],
|
|
722
|
+
rank=self.rank,
|
|
723
|
+
world_size=self.world_size,
|
|
724
|
+
)
|
|
725
|
+
|
|
726
|
+
self.dense_arrs, self.sparse_arrs, self.labels_arrs = [], [], []
|
|
727
|
+
for arrs, paths in zip(
|
|
728
|
+
[self.dense_arrs, self.sparse_arrs, self.labels_arrs],
|
|
729
|
+
[self.dense_paths, self.sparse_paths, self.labels_paths],
|
|
730
|
+
):
|
|
731
|
+
for idx, (range_left, range_right) in file_idx_to_row_range.items():
|
|
732
|
+
arrs.append(
|
|
733
|
+
BinaryCriteoUtils.load_npy_range(
|
|
734
|
+
paths[idx],
|
|
735
|
+
range_left,
|
|
736
|
+
range_right - range_left + 1,
|
|
737
|
+
path_manager_key=self.path_manager_key,
|
|
738
|
+
mmap_mode=self.mmap_mode,
|
|
739
|
+
)
|
|
740
|
+
)
|
|
741
|
+
|
|
742
|
+
# When mmap_mode is enabled, the hash is applied in def __iter__, which is
|
|
743
|
+
# where samples are batched during training.
|
|
744
|
+
# Otherwise, the ML dataset is preloaded, and the hash is applied here in
|
|
745
|
+
# the preload stage, as shown:
|
|
746
|
+
if not self.mmap_mode and self.hashes is not None:
|
|
747
|
+
hashes_np = np.array(self.hashes).reshape((1, CAT_FEATURE_COUNT))
|
|
748
|
+
for sparse_arr in self.sparse_arrs:
|
|
749
|
+
sparse_arr %= hashes_np
|
|
750
|
+
|
|
751
|
+
def _np_arrays_to_batch(
|
|
752
|
+
self, dense: np.ndarray, sparse: np.ndarray, labels: np.ndarray
|
|
753
|
+
) -> Batch:
|
|
754
|
+
if self.shuffle_batches:
|
|
755
|
+
# Shuffle all 3 in unison
|
|
756
|
+
shuffler = np.random.permutation(len(dense))
|
|
757
|
+
dense = dense[shuffler]
|
|
758
|
+
sparse = sparse[shuffler]
|
|
759
|
+
labels = labels[shuffler]
|
|
760
|
+
|
|
761
|
+
return Batch(
|
|
762
|
+
dense_features=torch.from_numpy(dense),
|
|
763
|
+
sparse_features=KeyedJaggedTensor(
|
|
764
|
+
keys=self.keys,
|
|
765
|
+
# transpose + reshape(-1) incurs an additional copy.
|
|
766
|
+
values=torch.from_numpy(sparse.transpose(1, 0).reshape(-1)),
|
|
767
|
+
lengths=self.lengths,
|
|
768
|
+
offsets=self.offsets,
|
|
769
|
+
stride=self.stride,
|
|
770
|
+
length_per_key=self.length_per_key,
|
|
771
|
+
offset_per_key=self.offset_per_key,
|
|
772
|
+
index_per_key=self.index_per_key,
|
|
773
|
+
),
|
|
774
|
+
labels=torch.from_numpy(labels.reshape(-1)),
|
|
775
|
+
)
|
|
776
|
+
|
|
777
|
+
def __iter__(self) -> Iterator[Batch]:
|
|
778
|
+
# Invariant: buffer never contains more than batch_size rows.
|
|
779
|
+
buffer: Optional[List[np.ndarray]] = None
|
|
780
|
+
|
|
781
|
+
def append_to_buffer(
|
|
782
|
+
dense: np.ndarray, sparse: np.ndarray, labels: np.ndarray
|
|
783
|
+
) -> None:
|
|
784
|
+
nonlocal buffer
|
|
785
|
+
if buffer is None:
|
|
786
|
+
buffer = [dense, sparse, labels]
|
|
787
|
+
else:
|
|
788
|
+
for idx, arr in enumerate([dense, sparse, labels]):
|
|
789
|
+
buffer[idx] = np.concatenate((buffer[idx], arr))
|
|
790
|
+
|
|
791
|
+
# Maintain a buffer that can contain up to batch_size rows. Fill buffer as
|
|
792
|
+
# much as possible on each iteration. Only return a new batch when batch_size
|
|
793
|
+
# rows are filled.
|
|
794
|
+
file_idx = 0
|
|
795
|
+
row_idx = 0
|
|
796
|
+
batch_idx = 0
|
|
797
|
+
while batch_idx < self.num_batches:
|
|
798
|
+
buffer_row_count = 0 if buffer is None else none_throws(buffer)[0].shape[0]
|
|
799
|
+
if buffer_row_count == self.batch_size:
|
|
800
|
+
yield self._np_arrays_to_batch(*none_throws(buffer))
|
|
801
|
+
batch_idx += 1
|
|
802
|
+
buffer = None
|
|
803
|
+
else:
|
|
804
|
+
rows_to_get = min(
|
|
805
|
+
self.batch_size - buffer_row_count,
|
|
806
|
+
self.num_rows_per_file[file_idx] - row_idx,
|
|
807
|
+
)
|
|
808
|
+
slice_ = slice(row_idx, row_idx + rows_to_get)
|
|
809
|
+
|
|
810
|
+
dense_inputs = self.dense_arrs[file_idx][slice_, :]
|
|
811
|
+
sparse_inputs = self.sparse_arrs[file_idx][slice_, :]
|
|
812
|
+
target_labels = self.labels_arrs[file_idx][slice_, :]
|
|
813
|
+
|
|
814
|
+
if self.mmap_mode and self.hashes is not None:
|
|
815
|
+
sparse_inputs = sparse_inputs % np.array(self.hashes).reshape(
|
|
816
|
+
(1, CAT_FEATURE_COUNT)
|
|
817
|
+
)
|
|
818
|
+
|
|
819
|
+
append_to_buffer(
|
|
820
|
+
dense_inputs,
|
|
821
|
+
sparse_inputs,
|
|
822
|
+
target_labels,
|
|
823
|
+
)
|
|
824
|
+
row_idx += rows_to_get
|
|
825
|
+
|
|
826
|
+
if row_idx >= self.num_rows_per_file[file_idx]:
|
|
827
|
+
file_idx += 1
|
|
828
|
+
row_idx = 0
|
|
829
|
+
|
|
830
|
+
def __len__(self) -> int:
|
|
831
|
+
return self.num_batches
|