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,130 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
4
|
+
# All rights reserved.
|
|
5
|
+
# This source code is licensed under the BSD-style license found in the
|
|
6
|
+
# LICENSE file in the root directory of this source tree.
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
from .lookup_args import *
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
#import os
|
|
14
|
+
#torch.ops.load_library(os.path.join(os.path.join(os.path.dirname(os.path.dirname(__file__)), "fbgemm_gpu_py.so")))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def invoke(
|
|
19
|
+
common_args: CommonArgs,
|
|
20
|
+
optimizer_args: OptimizerArgs,
|
|
21
|
+
|
|
22
|
+
momentum1: Momentum,
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
iter: int,
|
|
27
|
+
|
|
28
|
+
) -> torch.Tensor:
|
|
29
|
+
if (common_args.host_weights.numel() > 0):
|
|
30
|
+
return torch.ops.fbgemm.split_embedding_codegen_lookup_rowwise_weighted_adagrad_function_cpu(
|
|
31
|
+
# common_args
|
|
32
|
+
host_weights=common_args.host_weights,
|
|
33
|
+
weights_placements=common_args.weights_placements,
|
|
34
|
+
weights_offsets=common_args.weights_offsets,
|
|
35
|
+
D_offsets=common_args.D_offsets,
|
|
36
|
+
total_D=common_args.total_D,
|
|
37
|
+
max_D=common_args.max_D,
|
|
38
|
+
hash_size_cumsum=common_args.hash_size_cumsum,
|
|
39
|
+
total_hash_size_bits=common_args.total_hash_size_bits,
|
|
40
|
+
indices=common_args.indices,
|
|
41
|
+
offsets=common_args.offsets,
|
|
42
|
+
pooling_mode=common_args.pooling_mode,
|
|
43
|
+
indice_weights=common_args.indice_weights,
|
|
44
|
+
feature_requires_grad=common_args.feature_requires_grad,
|
|
45
|
+
# optimizer_args
|
|
46
|
+
gradient_clipping = optimizer_args.gradient_clipping,
|
|
47
|
+
max_gradient=optimizer_args.max_gradient,
|
|
48
|
+
stochastic_rounding=optimizer_args.stochastic_rounding,
|
|
49
|
+
|
|
50
|
+
learning_rate=optimizer_args.learning_rate,
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
eps=optimizer_args.eps,
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
weight_decay=optimizer_args.weight_decay,
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# momentum1
|
|
64
|
+
|
|
65
|
+
momentum1_host=momentum1.host,
|
|
66
|
+
momentum1_offsets=momentum1.offsets,
|
|
67
|
+
momentum1_placements=momentum1.placements,
|
|
68
|
+
|
|
69
|
+
# momentum2
|
|
70
|
+
|
|
71
|
+
# iter
|
|
72
|
+
|
|
73
|
+
iter=iter,
|
|
74
|
+
|
|
75
|
+
)
|
|
76
|
+
else:
|
|
77
|
+
return torch.ops.fbgemm.split_embedding_codegen_lookup_rowwise_weighted_adagrad_function(
|
|
78
|
+
# common_args
|
|
79
|
+
|
|
80
|
+
placeholder_autograd_tensor=common_args.placeholder_autograd_tensor,
|
|
81
|
+
|
|
82
|
+
dev_weights=common_args.dev_weights,
|
|
83
|
+
uvm_weights=common_args.uvm_weights,
|
|
84
|
+
lxu_cache_weights=common_args.lxu_cache_weights,
|
|
85
|
+
weights_placements=common_args.weights_placements,
|
|
86
|
+
weights_offsets=common_args.weights_offsets,
|
|
87
|
+
D_offsets=common_args.D_offsets,
|
|
88
|
+
total_D=common_args.total_D,
|
|
89
|
+
max_D=common_args.max_D,
|
|
90
|
+
hash_size_cumsum=common_args.hash_size_cumsum,
|
|
91
|
+
total_hash_size_bits=common_args.total_hash_size_bits,
|
|
92
|
+
indices=common_args.indices,
|
|
93
|
+
offsets=common_args.offsets,
|
|
94
|
+
pooling_mode=common_args.pooling_mode,
|
|
95
|
+
indice_weights=common_args.indice_weights,
|
|
96
|
+
feature_requires_grad=common_args.feature_requires_grad,
|
|
97
|
+
lxu_cache_locations=common_args.lxu_cache_locations,
|
|
98
|
+
# optimizer_args
|
|
99
|
+
gradient_clipping = optimizer_args.gradient_clipping,
|
|
100
|
+
max_gradient=optimizer_args.max_gradient,
|
|
101
|
+
stochastic_rounding=optimizer_args.stochastic_rounding,
|
|
102
|
+
|
|
103
|
+
learning_rate=optimizer_args.learning_rate,
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
eps=optimizer_args.eps,
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
weight_decay=optimizer_args.weight_decay,
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# momentum1
|
|
117
|
+
|
|
118
|
+
momentum1_dev=momentum1.dev,
|
|
119
|
+
momentum1_uvm=momentum1.uvm,
|
|
120
|
+
momentum1_offsets=momentum1.offsets,
|
|
121
|
+
momentum1_placements=momentum1.placements,
|
|
122
|
+
|
|
123
|
+
# momentum2
|
|
124
|
+
|
|
125
|
+
# iter
|
|
126
|
+
|
|
127
|
+
iter=iter,
|
|
128
|
+
|
|
129
|
+
output_dtype=common_args.output_dtype,
|
|
130
|
+
)
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
4
|
+
# All rights reserved.
|
|
5
|
+
# This source code is licensed under the BSD-style license found in the
|
|
6
|
+
# LICENSE file in the root directory of this source tree.
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
from .lookup_args import *
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
#import os
|
|
14
|
+
#torch.ops.load_library(os.path.join(os.path.join(os.path.dirname(os.path.dirname(__file__)), "fbgemm_gpu_py.so")))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def invoke(
|
|
19
|
+
common_args: CommonArgs,
|
|
20
|
+
optimizer_args: OptimizerArgs,
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
) -> torch.Tensor:
|
|
25
|
+
if (common_args.host_weights.numel() > 0):
|
|
26
|
+
return torch.ops.fbgemm.split_embedding_codegen_lookup_sgd_function_cpu(
|
|
27
|
+
# common_args
|
|
28
|
+
host_weights=common_args.host_weights,
|
|
29
|
+
weights_placements=common_args.weights_placements,
|
|
30
|
+
weights_offsets=common_args.weights_offsets,
|
|
31
|
+
D_offsets=common_args.D_offsets,
|
|
32
|
+
total_D=common_args.total_D,
|
|
33
|
+
max_D=common_args.max_D,
|
|
34
|
+
hash_size_cumsum=common_args.hash_size_cumsum,
|
|
35
|
+
total_hash_size_bits=common_args.total_hash_size_bits,
|
|
36
|
+
indices=common_args.indices,
|
|
37
|
+
offsets=common_args.offsets,
|
|
38
|
+
pooling_mode=common_args.pooling_mode,
|
|
39
|
+
indice_weights=common_args.indice_weights,
|
|
40
|
+
feature_requires_grad=common_args.feature_requires_grad,
|
|
41
|
+
# optimizer_args
|
|
42
|
+
gradient_clipping = optimizer_args.gradient_clipping,
|
|
43
|
+
max_gradient=optimizer_args.max_gradient,
|
|
44
|
+
stochastic_rounding=optimizer_args.stochastic_rounding,
|
|
45
|
+
|
|
46
|
+
learning_rate=optimizer_args.learning_rate,
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# momentum1
|
|
56
|
+
|
|
57
|
+
# momentum2
|
|
58
|
+
|
|
59
|
+
# iter
|
|
60
|
+
|
|
61
|
+
)
|
|
62
|
+
else:
|
|
63
|
+
return torch.ops.fbgemm.split_embedding_codegen_lookup_sgd_function(
|
|
64
|
+
# common_args
|
|
65
|
+
|
|
66
|
+
placeholder_autograd_tensor=common_args.placeholder_autograd_tensor,
|
|
67
|
+
|
|
68
|
+
dev_weights=common_args.dev_weights,
|
|
69
|
+
uvm_weights=common_args.uvm_weights,
|
|
70
|
+
lxu_cache_weights=common_args.lxu_cache_weights,
|
|
71
|
+
weights_placements=common_args.weights_placements,
|
|
72
|
+
weights_offsets=common_args.weights_offsets,
|
|
73
|
+
D_offsets=common_args.D_offsets,
|
|
74
|
+
total_D=common_args.total_D,
|
|
75
|
+
max_D=common_args.max_D,
|
|
76
|
+
hash_size_cumsum=common_args.hash_size_cumsum,
|
|
77
|
+
total_hash_size_bits=common_args.total_hash_size_bits,
|
|
78
|
+
indices=common_args.indices,
|
|
79
|
+
offsets=common_args.offsets,
|
|
80
|
+
pooling_mode=common_args.pooling_mode,
|
|
81
|
+
indice_weights=common_args.indice_weights,
|
|
82
|
+
feature_requires_grad=common_args.feature_requires_grad,
|
|
83
|
+
lxu_cache_locations=common_args.lxu_cache_locations,
|
|
84
|
+
# optimizer_args
|
|
85
|
+
gradient_clipping = optimizer_args.gradient_clipping,
|
|
86
|
+
max_gradient=optimizer_args.max_gradient,
|
|
87
|
+
stochastic_rounding=optimizer_args.stochastic_rounding,
|
|
88
|
+
|
|
89
|
+
learning_rate=optimizer_args.learning_rate,
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# momentum1
|
|
99
|
+
|
|
100
|
+
# momentum2
|
|
101
|
+
|
|
102
|
+
# iter
|
|
103
|
+
|
|
104
|
+
output_dtype=common_args.output_dtype,
|
|
105
|
+
)
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
4
|
+
# All rights reserved.
|
|
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 enum
|
|
9
|
+
from typing import Dict, Any
|
|
10
|
+
|
|
11
|
+
import torch
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@enum.unique
|
|
15
|
+
class EmbOptimType(enum.Enum):
|
|
16
|
+
SGD = "sgd" # uses non-deterministic updates (atomicAdd(..)) with duplicate ids
|
|
17
|
+
EXACT_SGD = (
|
|
18
|
+
"exact_sgd" # uses deterministic updates (via sorting + segment reduction)
|
|
19
|
+
)
|
|
20
|
+
LAMB = "lamb"
|
|
21
|
+
ADAM = "adam"
|
|
22
|
+
# exact/dedup: gradients to the same row are applied with coalesce then apply
|
|
23
|
+
# together, instead of applied in sequence (approx).
|
|
24
|
+
EXACT_ADAGRAD = "exact_adagrad"
|
|
25
|
+
EXACT_ROWWISE_ADAGRAD = "exact_row_wise_adagrad"
|
|
26
|
+
LARS_SGD = "lars_sgd"
|
|
27
|
+
PARTIAL_ROWWISE_ADAM = "partial_row_wise_adam"
|
|
28
|
+
PARTIAL_ROWWISE_LAMB = "partial_row_wise_lamb"
|
|
29
|
+
ROWWISE_ADAGRAD = "row_wise_adagrad"
|
|
30
|
+
MADGRAD = "madgrad"
|
|
31
|
+
EXACT_ROWWISE_WEIGHTED_ADAGRAD = "exact_row_wise_weighted_adagrad"
|
|
32
|
+
|
|
33
|
+
def __str__(self) -> str:
|
|
34
|
+
return self.value
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# Base class for quantization configuration (in case other numeric types have
|
|
38
|
+
# configs)
|
|
39
|
+
class QuantizationConfig:
|
|
40
|
+
def __init__(self) -> None:
|
|
41
|
+
self.config = {} # type: Dict[str, Any]
|
|
42
|
+
|
|
43
|
+
def get(self, name: str) -> int:
|
|
44
|
+
return -1
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# FP8 quantization configuration
|
|
48
|
+
# Compute necessary parameters in the constructor
|
|
49
|
+
class FP8QuantizationConfig(QuantizationConfig):
|
|
50
|
+
def __init__(self, exponent_bits: int, exponent_bias: int) -> None:
|
|
51
|
+
super(FP8QuantizationConfig, self).__init__()
|
|
52
|
+
self.config = {
|
|
53
|
+
"exponent_bits": exponent_bits,
|
|
54
|
+
"exponent_bias": exponent_bias,
|
|
55
|
+
"max_position": (1 << ((1 << exponent_bits) - 2 - exponent_bias))
|
|
56
|
+
* (2 - 2 ** (exponent_bits - 7)),
|
|
57
|
+
} # type: Dict[str, Any]
|
|
58
|
+
|
|
59
|
+
def get(self, name: str) -> int:
|
|
60
|
+
if name not in self.config:
|
|
61
|
+
raise RuntimeError("{} must be set in config".format(name))
|
|
62
|
+
return self.config[name]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@enum.unique
|
|
66
|
+
class SparseType(enum.Enum):
|
|
67
|
+
FP32 = "fp32"
|
|
68
|
+
FP16 = "fp16"
|
|
69
|
+
FP8 = "fp8"
|
|
70
|
+
INT8 = "int8"
|
|
71
|
+
INT4 = "int4"
|
|
72
|
+
INT2 = "int2"
|
|
73
|
+
BF16 = "bf16"
|
|
74
|
+
|
|
75
|
+
def __str__(self) -> str:
|
|
76
|
+
return self.value
|
|
77
|
+
|
|
78
|
+
@staticmethod
|
|
79
|
+
def from_int(ty: int) -> "SparseType":
|
|
80
|
+
if ty == 0:
|
|
81
|
+
return SparseType("fp32")
|
|
82
|
+
elif ty == 1:
|
|
83
|
+
return SparseType("fp16")
|
|
84
|
+
elif ty == 2:
|
|
85
|
+
return SparseType("int8")
|
|
86
|
+
elif ty == 3:
|
|
87
|
+
return SparseType("int4")
|
|
88
|
+
elif ty == 4:
|
|
89
|
+
return SparseType("int2")
|
|
90
|
+
elif ty == 5:
|
|
91
|
+
return SparseType("bf16")
|
|
92
|
+
elif ty == 6:
|
|
93
|
+
return SparseType("fp8")
|
|
94
|
+
else:
|
|
95
|
+
raise ValueError(f"Unsupported sparse type: {ty}")
|
|
96
|
+
|
|
97
|
+
def as_int(self) -> int:
|
|
98
|
+
return {
|
|
99
|
+
SparseType.FP32.value: 0,
|
|
100
|
+
SparseType.FP16.value: 1,
|
|
101
|
+
SparseType.INT8.value: 2,
|
|
102
|
+
SparseType.INT4.value: 3,
|
|
103
|
+
SparseType.INT2.value: 4,
|
|
104
|
+
SparseType.BF16.value: 5,
|
|
105
|
+
SparseType.FP8.value: 6,
|
|
106
|
+
}[self.value]
|
|
107
|
+
|
|
108
|
+
@staticmethod
|
|
109
|
+
def from_dtype(dtype: torch.dtype) -> "SparseType":
|
|
110
|
+
if dtype == torch.float32:
|
|
111
|
+
return SparseType("fp32")
|
|
112
|
+
elif dtype == torch.float16:
|
|
113
|
+
return SparseType("fp16")
|
|
114
|
+
elif dtype == torch.int8 or dtype == torch.uint8:
|
|
115
|
+
return SparseType("int8")
|
|
116
|
+
elif dtype == torch.quint4x2:
|
|
117
|
+
return SparseType("int4")
|
|
118
|
+
elif dtype == torch.quint2x4:
|
|
119
|
+
return SparseType("int2")
|
|
120
|
+
elif dtype == torch.bfloat16:
|
|
121
|
+
return SparseType("bf16")
|
|
122
|
+
else:
|
|
123
|
+
raise ValueError(f"Unsupported sparse dtype: {dtype}")
|
|
124
|
+
|
|
125
|
+
def as_dtype(self) -> torch.dtype:
|
|
126
|
+
return {
|
|
127
|
+
SparseType.FP32.value: torch.float32,
|
|
128
|
+
SparseType.FP16.value: torch.float16,
|
|
129
|
+
SparseType.INT8.value: torch.uint8,
|
|
130
|
+
SparseType.INT4.value: torch.quint4x2,
|
|
131
|
+
SparseType.INT2.value: torch.quint2x4,
|
|
132
|
+
SparseType.BF16.value: torch.bfloat16,
|
|
133
|
+
}[self.value]
|
|
134
|
+
|
|
135
|
+
def bit_rate(self) -> int:
|
|
136
|
+
return {
|
|
137
|
+
SparseType.FP32.value: 32,
|
|
138
|
+
SparseType.FP16.value: 16,
|
|
139
|
+
SparseType.FP8.value: 8,
|
|
140
|
+
SparseType.INT8.value: 8,
|
|
141
|
+
SparseType.INT4.value: 4,
|
|
142
|
+
SparseType.INT2.value: 2,
|
|
143
|
+
SparseType.BF16.value: 16,
|
|
144
|
+
}[self.value]
|
|
145
|
+
|
|
146
|
+
def align_size(self) -> int:
|
|
147
|
+
return {
|
|
148
|
+
SparseType.FP32.value: 1,
|
|
149
|
+
SparseType.FP16.value: 2,
|
|
150
|
+
SparseType.FP8.value: 4,
|
|
151
|
+
SparseType.INT8.value: 4,
|
|
152
|
+
SparseType.INT4.value: 8,
|
|
153
|
+
SparseType.INT2.value: 16,
|
|
154
|
+
SparseType.BF16.value: 2,
|
|
155
|
+
}[self.value]
|
|
156
|
+
|
|
157
|
+
def is_float(self) -> bool:
|
|
158
|
+
if (
|
|
159
|
+
self.value == SparseType.FP32.value
|
|
160
|
+
or self.value == SparseType.FP16.value
|
|
161
|
+
or self.value == SparseType.FP8.value
|
|
162
|
+
or self.value == SparseType.BF16.value
|
|
163
|
+
):
|
|
164
|
+
return True
|
|
165
|
+
else:
|
|
166
|
+
return False
|
|
167
|
+
|
|
168
|
+
def default_config(self) -> QuantizationConfig:
|
|
169
|
+
if self.value == SparseType.FP8.value:
|
|
170
|
+
return FP8QuantizationConfig(4, 7)
|
|
171
|
+
else:
|
|
172
|
+
return QuantizationConfig()
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
ELEMENT_SIZE: Dict[SparseType, int] = {
|
|
176
|
+
SparseType.FP32: 4,
|
|
177
|
+
SparseType.FP16: 2,
|
|
178
|
+
SparseType.FP8: 1,
|
|
179
|
+
SparseType.INT8: 1,
|
|
180
|
+
SparseType.BF16: 2,
|
|
181
|
+
# SparseType.INT4: 0.5,
|
|
182
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
# pyre-unsafe
|
|
4
|
+
|
|
5
|
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
6
|
+
# All rights reserved.
|
|
7
|
+
# This source code is licensed under the BSD-style license found in the
|
|
8
|
+
# LICENSE file in the root directory of this source tree.
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
import math
|
|
12
|
+
from typing import Optional, Tuple
|
|
13
|
+
|
|
14
|
+
import fbgemm_gpu.split_table_batched_embeddings_ops as split_table_batched_embeddings_ops
|
|
15
|
+
import numpy as np
|
|
16
|
+
import torch
|
|
17
|
+
from fbgemm_gpu.split_embedding_configs import (
|
|
18
|
+
SparseType,
|
|
19
|
+
QuantizationConfig,
|
|
20
|
+
)
|
|
21
|
+
from torch import Tensor, nn
|
|
22
|
+
|
|
23
|
+
# TODO: add per-feature based converter option (based on embedding_specs during inference)
|
|
24
|
+
# TODO: optimize embedding pruning and quantization latency.
|
|
25
|
+
class SplitEmbInferenceConverter:
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
quantize_type: SparseType,
|
|
29
|
+
pruning_ratio: Optional[float],
|
|
30
|
+
use_array_for_index_remapping: bool = True,
|
|
31
|
+
quantization_config: Optional[QuantizationConfig] = None,
|
|
32
|
+
):
|
|
33
|
+
self.quantize_type = quantize_type
|
|
34
|
+
# TODO(yingz): Change the pruning ratio to per-table settings.
|
|
35
|
+
self.pruning_ratio = pruning_ratio
|
|
36
|
+
self.use_array_for_index_remapping = use_array_for_index_remapping
|
|
37
|
+
self.quantization_config = quantization_config
|
|
38
|
+
|
|
39
|
+
def convert_model(self, model: torch.nn.Module) -> nn.Module:
|
|
40
|
+
self._process_split_embs(model)
|
|
41
|
+
return model
|
|
42
|
+
|
|
43
|
+
def _prune_by_weights_l2_norm(self, new_num_rows, weights) -> Tuple[Tensor, float]:
|
|
44
|
+
assert new_num_rows > 0
|
|
45
|
+
from numpy.linalg import norm
|
|
46
|
+
|
|
47
|
+
indicators = []
|
|
48
|
+
for row in weights:
|
|
49
|
+
indicators.append(norm(row.cpu().numpy(), ord=2))
|
|
50
|
+
sorted_indicators = sorted(indicators, reverse=True)
|
|
51
|
+
threshold = None
|
|
52
|
+
for i in range(new_num_rows, len(sorted_indicators)):
|
|
53
|
+
if sorted_indicators[i] < sorted_indicators[new_num_rows - 1]:
|
|
54
|
+
threshold = sorted_indicators[i]
|
|
55
|
+
break
|
|
56
|
+
if threshold is None:
|
|
57
|
+
threshold = sorted_indicators[-1] - 1
|
|
58
|
+
return (torch.tensor(indicators), threshold)
|
|
59
|
+
|
|
60
|
+
def _prune_embs(
|
|
61
|
+
self,
|
|
62
|
+
idx: int,
|
|
63
|
+
num_rows: int,
|
|
64
|
+
module: split_table_batched_embeddings_ops.SplitTableBatchedEmbeddingBagsCodegen,
|
|
65
|
+
) -> Tuple[Tensor, Optional[Tensor]]:
|
|
66
|
+
# TODO(yingz): Avoid DtoH / HtoD overhead.
|
|
67
|
+
weights = module.split_embedding_weights()[idx].cpu()
|
|
68
|
+
if self.pruning_ratio is None:
|
|
69
|
+
return (weights, None)
|
|
70
|
+
new_num_rows = int(math.ceil(num_rows * (1.0 - self.pruning_ratio))) # type: ignore
|
|
71
|
+
if new_num_rows == num_rows:
|
|
72
|
+
return (weights, None)
|
|
73
|
+
|
|
74
|
+
(indicators, threshold) = self._prune_by_weights_l2_norm(new_num_rows, weights)
|
|
75
|
+
|
|
76
|
+
return torch.ops.fbgemm.embedding_bag_rowwise_prune(
|
|
77
|
+
weights, indicators, threshold, torch.int32
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
def _get_quantization_config(self, name):
|
|
81
|
+
quantization_config = self.quantization_config
|
|
82
|
+
if quantization_config is None:
|
|
83
|
+
raise RuntimeError("quantization_config must be set for FP8 weight")
|
|
84
|
+
return quantization_config.get(name)
|
|
85
|
+
|
|
86
|
+
def _quantize_embs(
|
|
87
|
+
self, weight: Tensor, weight_ty: SparseType
|
|
88
|
+
) -> Tuple[Tensor, Optional[Tensor]]:
|
|
89
|
+
if weight_ty == SparseType.FP32:
|
|
90
|
+
q_weight = weight.float()
|
|
91
|
+
# FIXME: How to view the PyTorch Tensor as a different type (e.g., uint8)
|
|
92
|
+
# Here it uses numpy and it will introduce DtoH/HtoD overhead.
|
|
93
|
+
res_weight = torch.tensor(
|
|
94
|
+
q_weight.cpu().numpy().view(np.uint8)
|
|
95
|
+
).contiguous()
|
|
96
|
+
return (res_weight, None)
|
|
97
|
+
|
|
98
|
+
elif weight_ty == SparseType.FP16:
|
|
99
|
+
q_weight = weight.half()
|
|
100
|
+
res_weight = torch.tensor(
|
|
101
|
+
q_weight.cpu().numpy().view(np.uint8)
|
|
102
|
+
).contiguous()
|
|
103
|
+
return (res_weight, None)
|
|
104
|
+
|
|
105
|
+
elif weight_ty == SparseType.FP8:
|
|
106
|
+
# Output tensor is already in uint8
|
|
107
|
+
q_weight = torch.ops.fbgemm.FloatToHFP8Quantized(
|
|
108
|
+
weight.float(),
|
|
109
|
+
self._get_quantization_config("exponent_bits"),
|
|
110
|
+
self._get_quantization_config("exponent_bias"),
|
|
111
|
+
self._get_quantization_config("max_position"),
|
|
112
|
+
)
|
|
113
|
+
return (q_weight, None)
|
|
114
|
+
|
|
115
|
+
elif weight_ty == SparseType.INT8:
|
|
116
|
+
q_weight = torch.ops.fbgemm.FloatToFused8BitRowwiseQuantized(weight)
|
|
117
|
+
res_weight = torch.tensor(q_weight[:, :-8].cpu().numpy().view(np.uint8))
|
|
118
|
+
res_scale_shift = torch.tensor(
|
|
119
|
+
q_weight[:, -8:]
|
|
120
|
+
.contiguous()
|
|
121
|
+
.cpu()
|
|
122
|
+
.numpy()
|
|
123
|
+
.view(np.float32)
|
|
124
|
+
.astype(np.float16)
|
|
125
|
+
.view(np.uint8)
|
|
126
|
+
) # [-4, -2]: scale; [-2:]: bias
|
|
127
|
+
return (res_weight, res_scale_shift)
|
|
128
|
+
|
|
129
|
+
elif weight_ty == SparseType.INT4 or weight_ty == SparseType.INT2:
|
|
130
|
+
q_weight = torch.ops.fbgemm.FloatToFusedNBitRowwiseQuantizedSBHalf(
|
|
131
|
+
weight,
|
|
132
|
+
bit_rate=weight_ty.bit_rate(),
|
|
133
|
+
)
|
|
134
|
+
res_weight = torch.tensor(q_weight[:, :-4].cpu().numpy().view(np.uint8))
|
|
135
|
+
res_scale_shift = torch.tensor(
|
|
136
|
+
q_weight[:, -4:].contiguous().cpu().numpy().view(np.uint8)
|
|
137
|
+
) # [-4, -2]: scale; [-2:]: bias
|
|
138
|
+
return (res_weight, res_scale_shift)
|
|
139
|
+
|
|
140
|
+
else:
|
|
141
|
+
raise RuntimeError("Unsupported SparseType: {}".format(weight_ty))
|
|
142
|
+
|
|
143
|
+
def _process_split_embs(self, model: nn.Module) -> None:
|
|
144
|
+
for name, child in model.named_children():
|
|
145
|
+
if isinstance(
|
|
146
|
+
child,
|
|
147
|
+
split_table_batched_embeddings_ops.SplitTableBatchedEmbeddingBagsCodegen,
|
|
148
|
+
):
|
|
149
|
+
embedding_specs = []
|
|
150
|
+
use_cpu = (
|
|
151
|
+
child.embedding_specs[0][3]
|
|
152
|
+
== split_table_batched_embeddings_ops.ComputeDevice.CPU
|
|
153
|
+
)
|
|
154
|
+
for (E, D, _, _) in child.embedding_specs:
|
|
155
|
+
weights_ty = self.quantize_type
|
|
156
|
+
if D % weights_ty.align_size() != 0:
|
|
157
|
+
logging.warning(
|
|
158
|
+
f"Embedding dim {D} couldn't be divided by align size {weights_ty.align_size()}!"
|
|
159
|
+
)
|
|
160
|
+
assert D % 4 == 0
|
|
161
|
+
weights_ty = (
|
|
162
|
+
SparseType.FP16
|
|
163
|
+
) # fall back to FP16 if dimension couldn't be aligned with the required size
|
|
164
|
+
embedding_specs.append(("", E, D, weights_ty))
|
|
165
|
+
|
|
166
|
+
weight_lists = []
|
|
167
|
+
new_embedding_specs = []
|
|
168
|
+
index_remapping_list = []
|
|
169
|
+
for t, (_, E, D, weight_ty) in enumerate(embedding_specs):
|
|
170
|
+
# Try to prune embeddings.
|
|
171
|
+
(pruned_weight, index_remapping) = self._prune_embs(t, E, child)
|
|
172
|
+
new_embedding_specs.append(
|
|
173
|
+
(
|
|
174
|
+
"",
|
|
175
|
+
pruned_weight.size()[0],
|
|
176
|
+
D,
|
|
177
|
+
weight_ty,
|
|
178
|
+
split_table_batched_embeddings_ops.EmbeddingLocation.HOST
|
|
179
|
+
if use_cpu
|
|
180
|
+
else split_table_batched_embeddings_ops.EmbeddingLocation.DEVICE,
|
|
181
|
+
)
|
|
182
|
+
)
|
|
183
|
+
index_remapping_list.append(index_remapping)
|
|
184
|
+
|
|
185
|
+
# Try to quantize embeddings.
|
|
186
|
+
weight_lists.append(self._quantize_embs(pruned_weight, weight_ty))
|
|
187
|
+
|
|
188
|
+
is_fp8_weight = self.quantize_type == SparseType.FP8
|
|
189
|
+
|
|
190
|
+
q_child = split_table_batched_embeddings_ops.IntNBitTableBatchedEmbeddingBagsCodegen(
|
|
191
|
+
embedding_specs=new_embedding_specs,
|
|
192
|
+
index_remapping=index_remapping_list
|
|
193
|
+
if self.pruning_ratio is not None
|
|
194
|
+
else None,
|
|
195
|
+
pooling_mode=child.pooling_mode,
|
|
196
|
+
device="cpu" if use_cpu else torch.cuda.current_device(),
|
|
197
|
+
weight_lists=weight_lists,
|
|
198
|
+
use_array_for_index_remapping=self.use_array_for_index_remapping,
|
|
199
|
+
fp8_exponent_bits=self._get_quantization_config("exponent_bits")
|
|
200
|
+
if is_fp8_weight
|
|
201
|
+
else None,
|
|
202
|
+
fp8_exponent_bias=self._get_quantization_config("exponent_bias")
|
|
203
|
+
if is_fp8_weight
|
|
204
|
+
else None,
|
|
205
|
+
)
|
|
206
|
+
setattr(model, name, q_child)
|
|
207
|
+
else:
|
|
208
|
+
self._process_split_embs(child)
|