-
Notifications
You must be signed in to change notification settings - Fork 143
/
categorify.py
1916 lines (1688 loc) · 74.2 KB
/
categorify.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import math
import os
import warnings
from collections import defaultdict
from copy import deepcopy
from dataclasses import dataclass
from operator import getitem
from pathlib import Path
from typing import Optional, Union
import dask.dataframe as dd
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.dataset as pa_ds
from dask import config
from dask.base import tokenize
from dask.blockwise import BlockIndex
from dask.core import flatten
from dask.dataframe.core import DataFrame as DaskDataFrame
from dask.dataframe.core import _concat, new_dd_object
from dask.dataframe.shuffle import shuffle_group
from dask.delayed import Delayed
from dask.highlevelgraph import HighLevelGraph
from dask.utils import parse_bytes
from fsspec.core import get_fs_token_paths
from merlin.core import dispatch
from merlin.core.dispatch import DataFrameType, annotate, is_cpu_object, nullable_series
from merlin.core.utils import device_mem_size, run_on_worker
from merlin.dag.ops.stat_operator import StatOperator
from merlin.io.worker import fetch_table_data, get_worker_cache
from merlin.schema import Schema, Tags
from nvtabular.ops.operator import ColumnSelector, Operator
# Constants
# (NVTabular will reserve `0` for padding and `1` for nulls)
PAD_OFFSET = 0
NULL_OFFSET = 1
OOV_OFFSET = 2
class Categorify(StatOperator):
"""
Most of the data set will contain categorical features,
and these variables are typically stored as text values.
Machine Learning algorithms don't support these text values.
Categorify operation can be added to the workflow to
transform categorical features into unique integer values.
Encoding Convention::
- `0`: Not used by `Categorify` (reserved for padding).
- `1`: Null and NaN values.
- `[2, 2 + num_buckets)`: OOV values (including hash buckets).
- `[2 + num_buckets, max_size)`: Unique vocabulary.
Example usage::
# Define pipeline
cat_features = CATEGORICAL_COLUMNS >> nvt.ops.Categorify(freq_threshold=10)
# Initialize the workflow and execute it
proc = nvt.Workflow(cat_features)
proc.fit(dataset)
proc.transform(dataset).to_parquet('./test/')
Example for frequency hashing::
import cudf
import nvtabular as nvt
# Create toy dataset
df = cudf.DataFrame({
'author': ['User_A', 'User_B', 'User_C', 'User_C', 'User_A', 'User_B', 'User_A'],
'productID': [100, 101, 102, 101, 102, 103, 103],
'label': [0, 0, 1, 1, 1, 0, 0]
})
dataset = nvt.Dataset(df)
# Define pipeline
CATEGORICAL_COLUMNS = ['author', 'productID']
cat_features = CATEGORICAL_COLUMNS >> nvt.ops.Categorify(
freq_threshold={"author": 3, "productID": 2},
num_buckets={"author": 10, "productID": 20})
# Initialize the workflow and execute it
proc = nvt.Workflow(cat_features)
proc.fit(dataset)
ddf = proc.transform(dataset).to_ddf()
# Print results
print(ddf.compute())
Example with multi-hot::
import cudf
import nvtabular as nvt
# Create toy dataset
df = cudf.DataFrame({
'userID': [10001, 10002, 10003],
'productID': [30003, 30005, 40005],
'categories': [['Cat A', 'Cat B'], ['Cat C'], ['Cat A', 'Cat C', 'Cat D']],
'label': [0,0,1]
})
dataset = nvt.Dataset(df)
# Define pipeline
CATEGORICAL_COLUMNS = ['userID', 'productID', 'categories']
cat_features = CATEGORICAL_COLUMNS >> nvt.ops.Categorify()
# Initialize the workflow and execute it
proc = nvt.Workflow(cat_features)
proc.fit(dataset)
ddf = proc.transform(dataset).to_ddf()
# Print results
print(ddf.compute())
Parameters
-----------
freq_threshold : int or dictionary:{column: freq_limit_value}, default 0
Categories with a count/frequency below this threshold will be
omitted from the encoding and corresponding data will be mapped
to the OOV indices. Can be represented as both an integer or
a dictionary with column names as keys and frequency limit as
value. If dictionary is used, all columns targeted must be included
in the dictionary.
encode_type : {"joint", "combo"}, default "joint"
If "joint", the columns within any multi-column group will be
jointly encoded. If "combo", the combination of values will be
encoded as a new column. Note that replacement is not allowed for
"combo", because the same column name can be included in
multiple groups.
split_out : dict or int, optional
Number of files needed to store the unique values of each categorical
column. High-cardinality columns may require `split_out>1`, while
low-cardinality columns should be fine with the `split_out=1` default.
If passing a dict, each key and value should correspond to the column
name and value, respectively. The default value is 1 for all columns.
split_every : dict or int, optional
Number of adjacent partitions to aggregate in each tree-reduction
node. The default value is 8 for all columns.
out_path : str, optional
Root directory where groupby statistics will be written out in
parquet format.
on_host : bool, default True
Whether to convert cudf data to pandas between tasks in the hash-based
groupby reduction. The extra host <-> device data movement can reduce
performance. However, using `on_host=True` typically improves stability
(by avoiding device-level memory pressure).
cat_cache : {"device", "host", "disk"} or dict
Location to cache the list of unique categories for
each categorical column. If passing a dict, each key and value
should correspond to the column name and location, respectively.
Default is "host" for all columns.
dtype :
If specified, categorical labels will be cast to this dtype
after encoding is performed.
name_sep : str, default "_"
String separator to use between concatenated column names
for multi-column groups.
search_sorted : bool, default False.
Set it True to apply searchsorted algorithm in encoding.
num_buckets : int, or dictionary:{column: num_oov_indices}, optional
Number of indices to reserve for out-of-vocabulary (OOV) encoding at
transformation time. By default, all OOV values will be mapped to
the same index (`2`). If `num_buckets` is set to an integer greater
than one, a column-wise hash and modulo will be used to map each OOV
value to an index in the range `[2, 2 + num_buckets)`. A dictionary
may be used if the desired `num_buckets` behavior varies by column.
max_size : int or dictionary:{column: max_size_value}, optional
Set the maximum size of the expected embedding table for each column.
For example, if `max_size` is set to 1000, only the first 997 most-
frequent values will be included in the unique-value vocabulary, and
all remaining non-null values will be mapped to the OOV indices
(indices `0` and `1` will still be reserved for padding and nulls).
To use multiple OOV indices for infrequent values, set the `num_buckets`
parameter accordingly. Note that `max_size` cannot be combined with
`freq_threshold`, and it cannot be less than `num_buckets + 2`. By
default, the total number of encoding indices will be unconstrained.
cardinality_memory_limit: int or str, optional
Upper limit on the "allowed" memory usage of the internal DataFrame and Table objects
used to store unique categories. By default, this limit is 12.5% of the total memory.
Note that this argument is meant as a guide for internal optimizations and UserWarnings
within NVTabular, and does not guarantee that the memory limit will be satisfied.
"""
def __init__(
self,
freq_threshold=0,
out_path=None,
cat_cache="host",
dtype=None,
on_host=True,
encode_type="joint",
name_sep="_",
search_sorted=False,
num_buckets=None,
vocabs=None,
max_size=0,
single_table=False,
cardinality_memory_limit=None,
tree_width=None,
split_out=1,
split_every=8,
**kwargs, # Deprecated/unsupported arguments
):
# Handle deprecations and unsupported kwargs
if "start_index" in kwargs:
raise ValueError(
"start_index is now deprecated. `Categorify` will always "
"reserve index `0` for user-specific purposes, and will "
"use index `1` for null values."
)
if "na_sentinel" in kwargs:
raise ValueError(
"na_sentinel is now deprecated. `Categorify` will always "
"reserve index `1` for null values, and the following "
"`num_buckets` indices for out-of-vocabulary values "
"(or just index `2` if `num_buckets is None`)."
)
if kwargs:
raise ValueError(f"Unrecognized key-word arguments: {kwargs}")
# Warn user if they set num_buckets without setting max_size or
# freq_threshold - This setting used to hash everything, but will
# now just use multiple indices for OOV encodings at transform time
if num_buckets and not (max_size or freq_threshold):
warnings.warn(
"You are setting num_buckets without using max_size or "
"freq_threshold to restrict the number of distinct "
"categories. Are you sure this is what you want?"
)
# We need to handle three types of encoding here:
#
# (1) Conventional encoding. There are no multi-column groups. So,
# each categorical column is separately transformed into a new
# "encoded" column (1-to-1). The unique values are calculated
# separately for each column.
#
# (2) Multi-column "Joint" encoding (there are multi-column groups
# in `columns` and `encode_type="joint"`). Still a
# 1-to-1 transformation of categorical columns. However,
# we concatenate column groups to determine uniques (rather
# than getting uniques of each categorical column separately).
#
# (3) Multi-column "Group" encoding (there are multi-column groups
# in `columns` and `encode_type="combo"`). No longer
# a 1-to-1 transformation of categorical columns. Each column
# group will be transformed to a single "encoded" column. This
# means the unique "values" correspond to unique combinations.
# Since the same column may be included in multiple groups,
# replacement is not allowed for this transform.
# Set workflow_nodes if the user has passed in a list of columns.
# The purpose is to capture multi-column groups. If the user doesn't
# specify `columns`, there are no multi-column groups to worry about.
self.workflow_nodes = None
self.name_sep = name_sep
# For case (2), we need to keep track of the multi-column group name
# that will be used for the joint encoding of each column in that group.
# For case (3), we also use this "storage name" to signify the name of
# the file with the required "combination" groupby statistics.
self.storage_name = {}
# Only support two kinds of multi-column encoding
if encode_type not in ("joint", "combo"):
raise ValueError(f"encode_type={encode_type} not supported.")
if encode_type == "combo" and vocabs is not None:
raise ValueError("Passing in vocabs is not supported with a combo encoding.")
# Other self-explanatory initialization
super().__init__()
self.single_table = single_table
self.freq_threshold = freq_threshold or 0
self.out_path = out_path or "./"
self.dtype = dtype
self.on_host = on_host
self.cat_cache = cat_cache
self.encode_type = encode_type
self.search_sorted = search_sorted
self.cardinality_memory_limit = cardinality_memory_limit
self.split_every = split_every
self.split_out = split_out
_deprecate_tree_width(tree_width)
if self.search_sorted and self.freq_threshold:
raise ValueError(
"cannot use search_sorted=True with anything else than the default freq_threshold"
)
if num_buckets == 0:
raise ValueError(
"For hashing num_buckets should be an int > 1, otherwise set num_buckets=None."
)
elif isinstance(num_buckets, dict):
self.num_buckets = num_buckets
elif isinstance(num_buckets, int) or num_buckets is None:
self.num_buckets = num_buckets
else:
raise ValueError(
"`num_buckets` must be dict or int, got type {}".format(type(num_buckets))
)
if isinstance(max_size, dict):
self.max_size = max_size
elif isinstance(max_size, int) or max_size is None:
self.max_size = max_size
else:
raise ValueError("max_size must be dict or int, got type {}".format(type(max_size)))
if freq_threshold and max_size:
raise ValueError("cannot use freq_threshold param together with max_size param")
if self.num_buckets is not None:
# See: merlin.core.dispatch.hash_series
warnings.warn(
"Performing a hash-based transformation. Do not "
"expect Categorify to be consistent on GPU and CPU "
"with this num_buckets setting!"
)
self.vocabs = {}
if vocabs is not None:
self.vocabs = self.process_vocabs(vocabs)
self.categories = deepcopy(self.vocabs)
@annotate("Categorify_fit", color="darkgreen", domain="nvt_python")
def fit(self, col_selector: ColumnSelector, ddf: dd.DataFrame):
# User passed in a list of column groups. We need to figure out
# if this list contains any multi-column groups, and if there
# are any (obvious) problems with these groups
columns_uniq = list(set(flatten(col_selector.names, container=tuple)))
columns_all = list(flatten(col_selector.names, container=tuple))
if sorted(columns_all) != sorted(columns_uniq) and self.encode_type == "joint":
# If we are doing "joint" encoding, there must be unique mapping
# between input column names and column groups. Otherwise, more
# than one unique-value table could be used to encode the same
# column.
raise ValueError("Same column name included in multiple groups.")
for group in col_selector.subgroups:
if len(group.names) > 1:
# For multi-column groups, we concatenate column names
# to get the "group" name.
name = _make_name(*group.names, sep=self.name_sep)
for col in group.names:
self.storage_name[col] = name
# Check metadata type to reset on_host and cat_cache if the
# underlying ddf is already a pandas-backed collection
_cpu = False
if isinstance(ddf._meta, pd.DataFrame):
_cpu = True
self.on_host = False
# Cannot use "device" caching if the data is pandas-backed
self.cat_cache = "host" if self.cat_cache == "device" else self.cat_cache
if self.search_sorted:
# Pandas' search_sorted only works with Series.
# For now, it is safest to disallow this option.
self.search_sorted = False
warnings.warn("Cannot use `search_sorted=True` for pandas-backed data.")
# convert tuples to lists
cols_with_vocabs = list(self.categories.keys())
columns = [
list(c) if isinstance(c, tuple) else c
for c in col_selector.grouped_names
if (_make_name(*c, sep=self.name_sep) if isinstance(c, tuple) else c)
not in cols_with_vocabs
]
if not columns:
return Delayed("no-op", {"no-op": {}})
# Define a rough row-count at which we are likely to
# start hitting memory-pressure issues that cannot
# be accommodated with smaller partition sizes.
# By default, we estimate a "problematic" cardinality
# to be one that consumes >12.5% of the total memory.
self.cardinality_memory_limit = parse_bytes(
self.cardinality_memory_limit or int(device_mem_size(kind="total", cpu=_cpu) * 0.125)
)
dsk, key = _category_stats(ddf, self._create_fit_options_from_columns(columns))
return Delayed(key, dsk)
def fit_finalize(self, categories):
idx_count = 0
for cat in categories:
# this is a path
self.categories[cat] = categories[cat]
# check the argument
if self.single_table:
cat_file_path = self.categories[cat]
idx_count, new_cat_file_path = run_on_worker(
_reset_df_index, cat, cat_file_path, idx_count
)
self.categories[cat] = new_cat_file_path
def clear(self):
"""Clear the internal state of the operator's stats."""
self.categories = deepcopy(self.vocabs)
def process_vocabs(self, vocabs):
"""Process vocabs passed in by the user."""
categories = {}
if isinstance(vocabs, dict) and all(dispatch.is_series_object(v) for v in vocabs.values()):
fit_options = self._create_fit_options_from_columns(list(vocabs.keys()))
base_path = os.path.join(self.out_path, fit_options.stat_name)
num_buckets = fit_options.num_buckets
os.makedirs(base_path, exist_ok=True)
for col, vocab in vocabs.items():
col_name = _make_name(*col, sep=self.name_sep) if isinstance(col, tuple) else col
vals = {col_name: vocab}
oov_count = 1
if num_buckets:
oov_count = (
num_buckets if isinstance(num_buckets, int) else num_buckets[col_name]
) or 1
col_df = dispatch.make_df(vals).dropna()
col_df.index += NULL_OFFSET + oov_count
save_path = _save_encodings(col_df, base_path, col_name)
categories[col_name] = save_path
elif isinstance(vocabs, dict) and all(isinstance(v, str) for v in vocabs.values()):
# TODO: How to deal with the fact that this file may be missing null and oov rows??
categories = {
(_make_name(*col, sep=self.name_sep) if isinstance(col, tuple) else col): path
for col, path in vocabs.items()
}
else:
error = """Unrecognized vocab type,
please provide either a dictionary with paths to parquet files
or a dictionary with pandas Series objects.
"""
raise ValueError(error)
return categories
def _create_fit_options_from_columns(self, columns) -> "FitOptions":
return FitOptions(
columns,
[],
[],
self.out_path,
self.freq_threshold,
self.split_out,
self.on_host,
concat_groups=self.encode_type == "joint",
name_sep=self.name_sep,
max_size=self.max_size,
num_buckets=self.num_buckets,
cardinality_memory_limit=self.cardinality_memory_limit,
split_every=self.split_every,
)
def set_storage_path(self, new_path, copy=False):
self.categories = _copy_storage(self.categories, self.out_path, new_path, copy=copy)
self.out_path = new_path
@annotate("Categorify_transform", color="darkgreen", domain="nvt_python")
def transform(self, col_selector: ColumnSelector, df: DataFrameType) -> DataFrameType:
new_df = df.copy(deep=False)
if isinstance(self.freq_threshold, dict):
assert all(x in self.freq_threshold for x in col_selector.names)
column_mapping = self.column_mapping(col_selector)
column_names = list(column_mapping.keys())
# Encode each column-group separately
for name in column_names:
try:
# Use the column-group `list` directly (not the string name)
use_name = column_mapping.get(name, name)
# Storage name may be different than group for case (2)
# Only use the "aliased" `storage_name` if we are dealing with
# a multi-column group, or if we are doing joint encoding
if isinstance(use_name, (list, tuple)) and len(use_name) == 1:
use_name = use_name[0]
if isinstance(use_name, (list, tuple)) and len(use_name) == 1:
use_name = use_name[0]
if use_name != name or self.encode_type == "joint":
storage_name = self.storage_name.get(name, name)
else:
storage_name = name
if isinstance(use_name, tuple):
use_name = list(use_name)
path = self.categories[storage_name]
encoded = _encode(
use_name,
storage_name,
path,
df,
self.cat_cache,
freq_threshold=self.freq_threshold[name]
if isinstance(self.freq_threshold, dict)
else self.freq_threshold,
search_sorted=self.search_sorted,
buckets=self.num_buckets,
encode_type=self.encode_type,
cat_names=column_names,
max_size=self.max_size,
dtype=self.output_dtype,
split_out=(
self.split_out.get(storage_name, 1)
if isinstance(self.split_out, dict)
else self.split_out
),
single_table=self.single_table,
)
new_df[name] = encoded
except Exception as e:
raise RuntimeError(f"Failed to categorical encode column {name}") from e
return new_df
def column_mapping(self, col_selector):
column_mapping = {}
if self.encode_type == "combo":
for group in col_selector.grouped_names:
if isinstance(group, (tuple, list)):
name = _make_name(*group, sep=self.name_sep)
group = [*group]
else:
name = group
group = [group]
column_mapping[name] = group
else:
column_mapping = super().column_mapping(col_selector)
return column_mapping
def _compute_properties(self, col_schema, input_schema):
new_schema = super()._compute_properties(col_schema, input_schema)
col_name = col_schema.name
category_name = self.storage_name.get(col_name, col_name)
target_category_path = self.categories.get(category_name, None)
cardinality, dimensions = self.get_embedding_sizes([category_name])[category_name]
to_add = {
"num_buckets": self.num_buckets[col_name]
if isinstance(self.num_buckets, dict)
else self.num_buckets,
"freq_threshold": self.freq_threshold[col_name]
if isinstance(self.freq_threshold, dict)
else self.freq_threshold,
"max_size": self.max_size[col_name]
if isinstance(self.max_size, dict)
else self.max_size,
"cat_path": target_category_path,
"domain": {"min": 0, "max": cardinality - 1, "name": category_name},
"embedding_sizes": {"cardinality": cardinality, "dimension": dimensions},
}
return col_schema.with_properties({**new_schema.properties, **to_add})
@property
def output_tags(self):
return [Tags.CATEGORICAL]
@property
def output_dtype(self):
return self.dtype or np.int64
def compute_selector(
self,
input_schema: Schema,
selector: ColumnSelector,
parents_selector: ColumnSelector,
dependencies_selector: ColumnSelector,
) -> ColumnSelector:
self._validate_matching_cols(input_schema, parents_selector, "computing input selector")
return parents_selector
def get_embedding_sizes(self, columns):
return _get_embeddings_dask(self.categories, columns, self.num_buckets)
def inference_initialize(self, columns, inference_config):
# we don't currently support 'combo'
if self.encode_type == "combo":
warnings.warn("Falling back to unoptimized inference path for encode_type 'combo' ")
return None
import nvtabular_cpp
return nvtabular_cpp.inference.CategorifyTransform(self)
transform.__doc__ = Operator.transform.__doc__
fit.__doc__ = StatOperator.fit.__doc__
fit_finalize.__doc__ = StatOperator.fit_finalize.__doc__
def get_embedding_sizes(source, output_dtypes=None):
"""Returns a dictionary of embedding sizes from a workflow or workflow_node
Parameters
----------
source : Workflow or ColumnSelector
Either a nvtabular Workflow or ColumnSelector object that we should use to find
embedding sizes
output_dtypes : dict, optional
Optional dictionary of column_name:dtype. If passing a workflow object dtypes
will be read from the workflow. This is used to figure out which columns
are multihot-categorical, which are split out by this function. If passed a workflow_node
and this parameter isn't set, you won't have multihot columns returned separately
"""
# TODO: do we need to distinguish multihot columns here? (if so why? )
# have to lazy import Workflow to avoid circular import errors
from nvtabular.workflow import Workflow
output_node = source.output_node if isinstance(source, Workflow) else source
if isinstance(source, Workflow):
output_dtypes = output_dtypes or source.output_dtypes
else:
# passed in a column group
output_dtypes = output_dtypes or {}
output = {}
multihot_columns = set()
cats_schema = output_node.output_schema.select_by_tag(Tags.CATEGORICAL)
for col_name, col_schema in cats_schema.column_schemas.items():
if col_schema.dtype and col_schema.is_list and col_schema.is_ragged:
# multi hot so remove from output and add to multihot
multihot_columns.add(col_name)
embeddings_sizes = col_schema.properties.get("embedding_sizes", {})
cardinality = embeddings_sizes["cardinality"]
dimensions = embeddings_sizes["dimension"]
output[col_name] = (cardinality, dimensions)
# TODO: returning different return types like this (based off the presence
# of multihot features) is pretty janky. fix.
if not multihot_columns:
return output
single_hots = {k: v for k, v in output.items() if k not in multihot_columns}
multi_hots = {k: v for k, v in output.items() if k in multihot_columns}
return single_hots, multi_hots
def _get_embeddings_dask(paths, cat_names, buckets=0):
embeddings = {}
if isinstance(buckets, int):
buckets = {name: buckets for name in cat_names}
for col in cat_names:
path = paths.get(col)
num_rows = OOV_OFFSET
if path:
for file_frag in pa_ds.dataset(path, format="parquet").get_fragments():
num_rows += file_frag.metadata.num_rows
if isinstance(buckets, dict):
bucket_size = buckets.get(col, 0)
elif isinstance(buckets, int):
bucket_size = buckets
else:
bucket_size = 1
num_rows += bucket_size
embeddings[col] = _emb_sz_rule(num_rows)
return embeddings
def _emb_sz_rule(n_cat: int, minimum_size=16, maximum_size=512) -> int:
return n_cat, min(max(minimum_size, round(1.6 * n_cat**0.56)), maximum_size)
def _make_name(*args, sep="_"):
return sep.join(args)
def _to_parquet_dask_lazy(df, path, write_index=False):
# Write DataFrame data to parquet (lazily) with dask
# Check if we already have a dask collection
is_collection = isinstance(df, DaskDataFrame)
# Use `ddf.to_parquet` method
kwargs = {
"overwrite": True,
"compute": False,
"write_index": write_index,
"schema": None,
}
return (
df
if is_collection
else dispatch.convert_data(
df,
cpu=isinstance(df, pd.DataFrame),
to_collection=True,
)
).to_parquet(path, **kwargs)
def _save_encodings(
df,
base_path,
field_name,
preserve_index=False,
first_n=None,
freq_threshold=None,
oov_count=1,
null_size=None,
):
# Write DataFrame data to parquet (eagerly) with dask
# Define paths
unique_path = "/".join([str(base_path), f"unique.{field_name}.parquet"])
meta_path = "/".join([str(base_path), f"meta.{field_name}.parquet"])
# Check if we already have a dask collection
is_collection = isinstance(df, DaskDataFrame)
# Create empty directory if it doesn't already exist
use_directory = is_collection and df.npartitions > 1
fs = get_fs_token_paths(unique_path, mode="wb")[0]
_path = fs._strip_protocol(unique_path)
if fs.isdir(_path) or fs.exists(_path):
fs.rm(_path, recursive=True)
if use_directory:
fs.mkdir(_path, exists_ok=True)
# Start tracking embedding metadata
record_size_meta = True
oov_size = 0
unique_count = 0
unique_size = 0
# Iterate over partitions and write to disk
size = oov_count + OOV_OFFSET # Reserve null and oov buckets
for p, part in enumerate(df.partitions if is_collection else [df]):
local_path = "/".join([unique_path, f"part.{p}.parquet"]) if use_directory else unique_path
_df = _compute_sync(part) if is_collection else part
_len = len(_df)
if _len == 0:
continue
size_col = f"{field_name}_size"
if size_col not in _df.columns:
record_size_meta = False
if record_size_meta:
# Set number of rows allowed from this part
if first_n is not None:
first_n_local = first_n - size
else:
first_n_local = _len
# Update oov size
if first_n or freq_threshold:
removed = None
if freq_threshold:
sizes = _df[size_col]
removed = df[(sizes < freq_threshold) & (sizes > 0)]
_df = _df[(sizes >= freq_threshold) | (sizes == 0)]
if first_n and _len > first_n_local:
removed = _df.iloc[first_n_local:]
_df = _df.iloc[:first_n_local]
if removed is not None:
oov_size += removed[size_col].sum()
_len = len(_df)
# Record unique-value metadata
unique_size += _df[size_col].sum()
if not preserve_index:
# If we are NOT writing the index of df,
# then make sure we are writing a "correct"
# index. Note that we avoid using ddf.to_parquet
# so that we can make sure the index is correct
_df.set_index(
pd.RangeIndex(
start=size,
stop=size + _len,
step=1,
),
drop=True,
inplace=True,
)
size += _len
unique_count += _len
_df.to_parquet(local_path, compression=None)
if first_n and size >= first_n:
break # Ignore any remaining files
# Write encoding metadata
meta = {
"kind": ["pad", "null", "oov", "unique"],
"offset": [PAD_OFFSET, NULL_OFFSET, OOV_OFFSET, OOV_OFFSET + oov_count],
"num_indices": [1, 1, oov_count, unique_count],
}
if record_size_meta:
meta["num_observed"] = [0, null_size, oov_size, unique_size]
type(_df)(meta).to_parquet(meta_path)
# Return path to uniques
return unique_path
@dataclass
class FitOptions:
"""Contains options on how to fit statistics.
Parameters
----------
col_groups: list
Columns to group by
agg_cols: list
For groupby statistics, this is the list of continuous columns to calculate statistics
for
agg_list: list
List of operations (sum/max/...) to perform on the grouped continuous columns
out_path: str
Where to write statistics in parquet format
freq_limit: int or dict
Categories with a count/frequency below this threshold will be
omitted from the encoding and corresponding data will be mapped
to the "null" category.
split_out:
Number of output partitions to use for each category in ``fit``.
on_host:
Whether to convert cudf data to pandas between tasks in the groupby reduction.
stat_name:
Name of statistic to use when writing out statistics
concat_groups:
Whether to use a 'joint' vocabulary between columns
name_sep:
Delimiter to use for concatenating columns into a string
max_size:
The maximum size of an embedding table
num_buckets:
If specified will also do hashing operation for values that would otherwise be mapped
to as unknown (by freq_limit or max_size parameters)
cardinality_memory_limit: int
Suggested upper limit on categorical data containers.
split_every:
Number of adjacent partitions to reduce in each tree node.
"""
col_groups: list
agg_cols: list
agg_list: list
out_path: str
freq_limit: Union[int, dict]
split_out: Union[int, dict]
on_host: bool
stat_name: str = "categories"
concat_groups: bool = False
name_sep: str = "-"
max_size: Optional[Union[int, dict]] = None
num_buckets: Optional[Union[int, dict]] = None
cardinality_memory_limit: Optional[int] = None
split_every: Optional[Union[int, dict]] = 8
def __post_init__(self):
if not isinstance(self.col_groups, ColumnSelector):
self.col_groups = ColumnSelector(self.col_groups)
col_selectors = []
for cat_col_names in self.col_groups.grouped_names:
if isinstance(cat_col_names, tuple):
cat_col_names = list(cat_col_names)
if isinstance(cat_col_names, str):
cat_col_names = [cat_col_names]
if not isinstance(cat_col_names, ColumnSelector):
cat_col_selector = ColumnSelector(cat_col_names)
else:
cat_col_selector = cat_col_names
col_selectors.append(cat_col_selector)
self.col_groups = col_selectors
def _general_concat(
frames,
cardinality_memory_limit=False,
col_selector=None,
**kwargs,
):
# Concatenate DataFrame or pa.Table objects
if isinstance(frames[0], pa.Table):
df = pa.concat_tables(frames, promote=True)
if (
cardinality_memory_limit
and col_selector is not None
and df.nbytes > cardinality_memory_limit
):
# Before fully converting this pyarrow Table
# to a cudf DatFrame, we can reduce the memory
# footprint of `df`. Since the size of `df`
# depends on the cardinality of the features,
# and NOT on the partition size, the remaining
# logic in this function has an OOM-error risk
# (even with tiny partitions).
size_columns = []
for col in col_selector.names:
name = col + "_size"
if name in df.schema.names:
# Convert this column alone to cudf,
# and drop the field from df. Note that
# we are only converting this column to
# cudf to take advantage of fast `max`
# performance.
size_columns.append(dispatch.from_host(df.select([name])))
df = df.drop([name])
# Use numpy to calculate the "minimum"
# dtype needed to capture the "size" column,
# and cast the type
typ = np.min_scalar_type(size_columns[-1][name].max() * 2)
size_columns[-1][name] = size_columns[-1][name].astype(typ)
# Convert the remaining columns in df to cudf,
# and append the type-casted "size" columns
df = dispatch.concat_columns([dispatch.from_host(df)] + size_columns)
else:
# Empty DataFrame - No need for type-casting
df = dispatch.from_host(df)
return df
else:
# For now, if we are not concatenating in host memory,
# we will assume that reducing the memory footprint of
# "size" columns is not a priority. However, the same
# type-casting optimization can also be done for both
# pandas and cudf-backed data here.
return _concat(frames, **kwargs)
@annotate("top_level_groupby", color="green", domain="nvt_python")
def _top_level_groupby(df, options: FitOptions = None, spill=True):
assert options is not None
sum_sq = "std" in options.agg_list or "var" in options.agg_list
calculate_min = "min" in options.agg_list
calculate_max = "max" in options.agg_list
# Top-level operation for category-based groupby aggregations
output = {}
k = 0
for i, cat_col_names in enumerate(options.col_groups):
if not isinstance(cat_col_names, ColumnSelector):
cat_col_selector = ColumnSelector(cat_col_names)
else:
cat_col_selector = cat_col_names
cat_col_selector_str = _make_name(*cat_col_selector.names, sep=options.name_sep)
if options.concat_groups and len(cat_col_selector.names) > 1:
# Concatenate columns and replace cat_col_group
# with the single name
df_gb = type(df)()
ignore_index = True
df_gb[cat_col_selector_str] = _concat(
[_maybe_flatten_list_column(col, df)[col] for col in cat_col_selector.names],
ignore_index,
)
cat_col_selector = ColumnSelector([cat_col_selector_str])
else:
# Compile aggregation dictionary and add "squared-sum"
# column(s) (necessary when `agg_cols` is non-empty)
combined_col_selector = cat_col_selector + options.agg_cols
df_gb = df[combined_col_selector.names].copy(deep=False)
agg_dict = {}
base_aggs = []
if "size" in options.agg_list:
# This is either for a Categorify operation,
# or "size" is in the list of aggregations
base_aggs.append("size")
if set(options.agg_list).difference({"size", "min", "max"}):
# This is a groupby aggregation that may
# require "count" statistics
base_aggs.append("count")
agg_dict[cat_col_selector.names[0]] = base_aggs
if isinstance(options.agg_cols, list):