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,2503 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
# pyre-ignore-all-errors[56]
|
|
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 enum
|
|
11
|
+
import logging
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from itertools import accumulate
|
|
14
|
+
from math import log2
|
|
15
|
+
from typing import Dict, List, NamedTuple, Optional, Tuple, Type, Union
|
|
16
|
+
|
|
17
|
+
import fbgemm_gpu.split_embedding_codegen_lookup_invokers as invokers
|
|
18
|
+
import torch
|
|
19
|
+
from fbgemm_gpu.split_embedding_configs import EmbOptimType as OptimType
|
|
20
|
+
from fbgemm_gpu.split_embedding_configs import SparseType
|
|
21
|
+
from torch import Tensor, nn
|
|
22
|
+
|
|
23
|
+
ASSOC = 32
|
|
24
|
+
# Maximum number of times prefetch() can be called without
|
|
25
|
+
# a corresponding forward() call
|
|
26
|
+
MAX_PREFETCH_DEPTH = 100
|
|
27
|
+
INT8_EMB_ROW_DIM_OFFSET = 8
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class DoesNotHavePrefix(Exception):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class EmbeddingLocation(enum.IntEnum):
|
|
35
|
+
DEVICE = 0
|
|
36
|
+
MANAGED = 1
|
|
37
|
+
MANAGED_CACHING = 2
|
|
38
|
+
HOST = 3
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ComputeDevice(enum.IntEnum):
|
|
42
|
+
CPU = 0
|
|
43
|
+
CUDA = 1
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class CacheAlgorithm(enum.Enum):
|
|
47
|
+
LRU = 0
|
|
48
|
+
LFU = 1
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class PoolingMode(enum.IntEnum):
|
|
52
|
+
SUM = 0
|
|
53
|
+
MEAN = 1
|
|
54
|
+
NONE = 2
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class BoundsCheckMode(enum.IntEnum):
|
|
58
|
+
# Raise an exception (CPU) or device-side assert (CUDA)
|
|
59
|
+
FATAL = 0
|
|
60
|
+
# Log the first out-of-bounds instance per kernel, and set to zero.
|
|
61
|
+
WARNING = 1
|
|
62
|
+
# Set to zero.
|
|
63
|
+
IGNORE = 2
|
|
64
|
+
# No bounds checks.
|
|
65
|
+
NONE = 3
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class WeightDecayMode(enum.IntEnum):
|
|
69
|
+
L2 = 1
|
|
70
|
+
DECOUPLE = 2
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
RecordCacheMetrics: NamedTuple = NamedTuple(
|
|
74
|
+
"RecordCacheMetrics",
|
|
75
|
+
[("record_cache_miss_counter", bool), ("record_tablewise_cache_miss", bool)],
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class SplitState:
|
|
81
|
+
dev_size: int
|
|
82
|
+
host_size: int
|
|
83
|
+
uvm_size: int
|
|
84
|
+
placements: List[EmbeddingLocation]
|
|
85
|
+
offsets: List[int]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def construct_split_state(
|
|
89
|
+
embedding_specs: List[Tuple[int, int, EmbeddingLocation, ComputeDevice]],
|
|
90
|
+
rowwise: bool,
|
|
91
|
+
cacheable: bool,
|
|
92
|
+
precision: SparseType = SparseType.FP32,
|
|
93
|
+
int8_emb_row_dim_offset: int = INT8_EMB_ROW_DIM_OFFSET,
|
|
94
|
+
) -> SplitState:
|
|
95
|
+
placements = []
|
|
96
|
+
offsets = []
|
|
97
|
+
dev_size = 0
|
|
98
|
+
host_size = 0
|
|
99
|
+
uvm_size = 0
|
|
100
|
+
for (num_embeddings, embedding_dim, location, _) in embedding_specs:
|
|
101
|
+
assert embedding_dim % 4 == 0, f"{embedding_dim}"
|
|
102
|
+
if precision == SparseType.INT8:
|
|
103
|
+
embedding_dim += int8_emb_row_dim_offset
|
|
104
|
+
state_size = num_embeddings * embedding_dim if not rowwise else num_embeddings
|
|
105
|
+
if location == EmbeddingLocation.HOST:
|
|
106
|
+
placements.append(EmbeddingLocation.HOST)
|
|
107
|
+
offsets.append(host_size)
|
|
108
|
+
host_size += state_size
|
|
109
|
+
# If table is on device, then opimtizer is on device.
|
|
110
|
+
# If table is managed, then if optimizer state is rowwise, optimizer is on device, otherwise optimizer is managed.
|
|
111
|
+
elif location == EmbeddingLocation.DEVICE or rowwise:
|
|
112
|
+
placements.append(EmbeddingLocation.DEVICE)
|
|
113
|
+
offsets.append(dev_size)
|
|
114
|
+
dev_size += state_size
|
|
115
|
+
else:
|
|
116
|
+
if cacheable and location == EmbeddingLocation.MANAGED_CACHING:
|
|
117
|
+
placements.append(EmbeddingLocation.MANAGED_CACHING)
|
|
118
|
+
else:
|
|
119
|
+
placements.append(EmbeddingLocation.MANAGED)
|
|
120
|
+
offsets.append(uvm_size)
|
|
121
|
+
uvm_size += state_size
|
|
122
|
+
assert len(placements) == len(offsets)
|
|
123
|
+
return SplitState(
|
|
124
|
+
dev_size=dev_size,
|
|
125
|
+
host_size=host_size,
|
|
126
|
+
uvm_size=uvm_size,
|
|
127
|
+
placements=placements,
|
|
128
|
+
offsets=offsets,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass
|
|
133
|
+
class CacheState:
|
|
134
|
+
# T + 1 elements and cache_hash_size_cumsum[-1] == total_cache_hash_size
|
|
135
|
+
cache_hash_size_cumsum: List[int]
|
|
136
|
+
cache_index_table_map: List[int]
|
|
137
|
+
total_cache_hash_size: int
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def construct_cache_state(
|
|
141
|
+
row_list: List[int],
|
|
142
|
+
location_list: List[EmbeddingLocation],
|
|
143
|
+
feature_table_map: List[int],
|
|
144
|
+
) -> CacheState:
|
|
145
|
+
_cache_hash_size_cumsum = [0]
|
|
146
|
+
total_cache_hash_size = 0
|
|
147
|
+
for (num_embeddings, location) in zip(row_list, location_list):
|
|
148
|
+
if location == EmbeddingLocation.MANAGED_CACHING:
|
|
149
|
+
total_cache_hash_size += num_embeddings
|
|
150
|
+
_cache_hash_size_cumsum.append(total_cache_hash_size)
|
|
151
|
+
# [T], -1: non-cached table
|
|
152
|
+
cache_hash_size_cumsum = []
|
|
153
|
+
# [total_cache_hash_size], linear cache index -> table index
|
|
154
|
+
cache_index_table_map = [-1] * total_cache_hash_size
|
|
155
|
+
for t, t_ in enumerate(feature_table_map):
|
|
156
|
+
for i in range(_cache_hash_size_cumsum[t_], _cache_hash_size_cumsum[t_ + 1]):
|
|
157
|
+
cache_index_table_map[i] = t
|
|
158
|
+
location = location_list[t_]
|
|
159
|
+
if location == EmbeddingLocation.MANAGED_CACHING:
|
|
160
|
+
cache_hash_size_cumsum.append(_cache_hash_size_cumsum[t_])
|
|
161
|
+
else:
|
|
162
|
+
cache_hash_size_cumsum.append(-1)
|
|
163
|
+
cache_hash_size_cumsum.append(total_cache_hash_size)
|
|
164
|
+
s = CacheState(
|
|
165
|
+
cache_hash_size_cumsum=cache_hash_size_cumsum,
|
|
166
|
+
cache_index_table_map=cache_index_table_map,
|
|
167
|
+
total_cache_hash_size=total_cache_hash_size,
|
|
168
|
+
)
|
|
169
|
+
return s
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class SplitTableBatchedEmbeddingBagsCodegen(nn.Module):
|
|
173
|
+
"""
|
|
174
|
+
Multiple sparse features can share one embedding table.
|
|
175
|
+
'feature_table_map' specifies the feature-table mapping.
|
|
176
|
+
T: number of logical tables
|
|
177
|
+
T_: number of physical tables
|
|
178
|
+
T >= T_
|
|
179
|
+
"""
|
|
180
|
+
|
|
181
|
+
embedding_specs: List[Tuple[int, int, EmbeddingLocation, ComputeDevice]]
|
|
182
|
+
optimizer_args: invokers.lookup_args.OptimizerArgs
|
|
183
|
+
lxu_cache_locations_list: List[Tensor]
|
|
184
|
+
lxu_cache_locations_empty: Tensor
|
|
185
|
+
timesteps_prefetched: List[int]
|
|
186
|
+
record_cache_metrics: RecordCacheMetrics
|
|
187
|
+
|
|
188
|
+
def __init__( # noqa C901
|
|
189
|
+
self,
|
|
190
|
+
embedding_specs: List[
|
|
191
|
+
Tuple[int, int, EmbeddingLocation, ComputeDevice]
|
|
192
|
+
], # tuple of (rows, dims, placements, compute_devices)
|
|
193
|
+
feature_table_map: Optional[List[int]] = None, # [T]
|
|
194
|
+
cache_algorithm: CacheAlgorithm = CacheAlgorithm.LRU,
|
|
195
|
+
cache_load_factor: float = 0.2,
|
|
196
|
+
cache_sets: int = 0,
|
|
197
|
+
cache_reserved_memory: float = 0.0,
|
|
198
|
+
cache_precision: SparseType = SparseType.FP32,
|
|
199
|
+
weights_precision: SparseType = SparseType.FP32,
|
|
200
|
+
output_dtype: SparseType = SparseType.FP32,
|
|
201
|
+
enforce_hbm: bool = False, # place all weights/momentums in HBM when using cache
|
|
202
|
+
optimizer: OptimType = OptimType.EXACT_SGD,
|
|
203
|
+
record_cache_metrics: Optional[RecordCacheMetrics] = None,
|
|
204
|
+
# General Optimizer args
|
|
205
|
+
stochastic_rounding: bool = True,
|
|
206
|
+
gradient_clipping: bool = False,
|
|
207
|
+
max_gradient: float = 1.0,
|
|
208
|
+
learning_rate: float = 0.01,
|
|
209
|
+
eps: float = 1.0e-8, # used by Adagrad, LAMB, and Adam
|
|
210
|
+
momentum: float = 0.9, # used by LARS-SGD
|
|
211
|
+
weight_decay: float = 0.0, # used by LARS-SGD, LAMB, ADAM, and Rowwise Adagrad
|
|
212
|
+
# used by Rowwise Adagrad. LARS-SGD, LAMB and ADAM only supports decoupled weight decay
|
|
213
|
+
weight_decay_mode: WeightDecayMode = WeightDecayMode.L2,
|
|
214
|
+
eta: float = 0.001, # used by LARS-SGD,
|
|
215
|
+
beta1: float = 0.9, # used by LAMB and ADAM
|
|
216
|
+
beta2: float = 0.999, # used by LAMB and ADAM
|
|
217
|
+
pooling_mode: PoolingMode = PoolingMode.SUM,
|
|
218
|
+
device: Optional[torch.device] = None,
|
|
219
|
+
bounds_check_mode: BoundsCheckMode = BoundsCheckMode.WARNING,
|
|
220
|
+
) -> None:
|
|
221
|
+
super(SplitTableBatchedEmbeddingBagsCodegen, self).__init__()
|
|
222
|
+
|
|
223
|
+
self.pooling_mode = pooling_mode
|
|
224
|
+
self.bounds_check_mode_int: int = bounds_check_mode.value
|
|
225
|
+
self.weights_precision = weights_precision
|
|
226
|
+
self.output_dtype: int = output_dtype.as_int()
|
|
227
|
+
|
|
228
|
+
if record_cache_metrics is not None:
|
|
229
|
+
self.record_cache_metrics = record_cache_metrics
|
|
230
|
+
else:
|
|
231
|
+
self.record_cache_metrics = RecordCacheMetrics(False, False)
|
|
232
|
+
# NOTE: a placeholder to avoid multi-construction and make TorchScript work!
|
|
233
|
+
self.dummy_tensor: Tensor = torch.zeros(0, device=device)
|
|
234
|
+
|
|
235
|
+
self.embedding_specs = embedding_specs
|
|
236
|
+
(rows, dims, locations, compute_devices) = zip(*embedding_specs)
|
|
237
|
+
T_ = len(self.embedding_specs)
|
|
238
|
+
self.dims: List[int] = dims
|
|
239
|
+
assert T_ > 0
|
|
240
|
+
# mixed D is not supported by no bag kernels
|
|
241
|
+
mixed_D = False
|
|
242
|
+
D = self.dims[0]
|
|
243
|
+
for d in self.dims:
|
|
244
|
+
if d != D:
|
|
245
|
+
mixed_D = False
|
|
246
|
+
if mixed_D:
|
|
247
|
+
assert (
|
|
248
|
+
self.pooling_mode != PoolingMode.NONE
|
|
249
|
+
), "Mixed dimension tables only supported for pooling tables."
|
|
250
|
+
|
|
251
|
+
assert all(
|
|
252
|
+
cd == compute_devices[0] for cd in compute_devices
|
|
253
|
+
), "Heterogenous compute_devices are NOT supported!"
|
|
254
|
+
self.use_cpu: bool = all(cd == ComputeDevice.CPU for cd in compute_devices)
|
|
255
|
+
assert not self.use_cpu or all(
|
|
256
|
+
loc == EmbeddingLocation.HOST for loc in locations
|
|
257
|
+
), "ComputeDevice.CPU is only for EmbeddingLocation.HOST!"
|
|
258
|
+
assert self.use_cpu or all(
|
|
259
|
+
loc != EmbeddingLocation.HOST for loc in locations
|
|
260
|
+
), "EmbeddingLocation.HOST doesn't work for CUDA device!"
|
|
261
|
+
if self.use_cpu or self.pooling_mode == PoolingMode.NONE:
|
|
262
|
+
assert (
|
|
263
|
+
output_dtype == SparseType.FP32
|
|
264
|
+
or output_dtype == SparseType.FP16
|
|
265
|
+
or output_dtype == SparseType.BF16
|
|
266
|
+
), "Fused pooled embedding quantization only supported for cuda."
|
|
267
|
+
|
|
268
|
+
if device is not None:
|
|
269
|
+
self.current_device: torch.device = device
|
|
270
|
+
else:
|
|
271
|
+
self.current_device: torch.device = (
|
|
272
|
+
torch.device("cpu") if self.use_cpu else torch.cuda.current_device()
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
# add placeholder require_grad param tensor to enable autograd with int8 weights
|
|
276
|
+
self.placeholder_autograd_tensor = nn.Parameter(
|
|
277
|
+
torch.zeros(0, device=self.current_device, dtype=torch.float)
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
self.int8_emb_row_dim_offset: int = INT8_EMB_ROW_DIM_OFFSET
|
|
281
|
+
|
|
282
|
+
self.feature_table_map: List[int] = (
|
|
283
|
+
feature_table_map if feature_table_map is not None else list(range(T_))
|
|
284
|
+
)
|
|
285
|
+
T = len(self.feature_table_map)
|
|
286
|
+
assert T_ <= T
|
|
287
|
+
table_has_feature = [False] * T_
|
|
288
|
+
for t in self.feature_table_map:
|
|
289
|
+
table_has_feature[t] = True
|
|
290
|
+
assert all(table_has_feature), "Each table must have at least one feature!"
|
|
291
|
+
|
|
292
|
+
D_offsets = [dims[t] for t in self.feature_table_map]
|
|
293
|
+
D_offsets = [0] + list(accumulate(D_offsets))
|
|
294
|
+
self.total_D: int = D_offsets[-1]
|
|
295
|
+
self.max_D: int = max(dims)
|
|
296
|
+
cached_dims = [
|
|
297
|
+
embedding_spec[1]
|
|
298
|
+
for embedding_spec in embedding_specs
|
|
299
|
+
if embedding_spec[2] == EmbeddingLocation.MANAGED_CACHING
|
|
300
|
+
]
|
|
301
|
+
self.max_D_cache: int = max(cached_dims) if len(cached_dims) > 0 else 0
|
|
302
|
+
|
|
303
|
+
self.register_buffer(
|
|
304
|
+
"D_offsets",
|
|
305
|
+
torch.tensor(D_offsets, device=self.current_device, dtype=torch.int32),
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
hash_size_cumsum = [0] + list(accumulate(rows))
|
|
309
|
+
if hash_size_cumsum[-1] == 0:
|
|
310
|
+
self.total_hash_size_bits: int = 0
|
|
311
|
+
else:
|
|
312
|
+
self.total_hash_size_bits: int = int(log2(float(hash_size_cumsum[-1])) + 1)
|
|
313
|
+
# The last element is to easily access # of rows of each table by
|
|
314
|
+
# hash_size_cumsum[t + 1] - hash_size_cumsum[t]
|
|
315
|
+
hash_size_cumsum = [hash_size_cumsum[t] for t in self.feature_table_map] + [
|
|
316
|
+
hash_size_cumsum[-1]
|
|
317
|
+
]
|
|
318
|
+
self.register_buffer(
|
|
319
|
+
"hash_size_cumsum",
|
|
320
|
+
torch.tensor(
|
|
321
|
+
hash_size_cumsum, device=self.current_device, dtype=torch.int64
|
|
322
|
+
),
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
self.register_buffer(
|
|
326
|
+
"rows_per_table",
|
|
327
|
+
torch.tensor(
|
|
328
|
+
[rows[t] for t in self.feature_table_map],
|
|
329
|
+
device=self.current_device,
|
|
330
|
+
dtype=torch.int64,
|
|
331
|
+
),
|
|
332
|
+
)
|
|
333
|
+
self.register_buffer(
|
|
334
|
+
"bounds_check_warning",
|
|
335
|
+
torch.tensor([0], device=self.current_device, dtype=torch.int64),
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
weight_split = construct_split_state(
|
|
339
|
+
embedding_specs,
|
|
340
|
+
rowwise=False,
|
|
341
|
+
cacheable=True,
|
|
342
|
+
precision=weights_precision,
|
|
343
|
+
)
|
|
344
|
+
table_embedding_dtype = weights_precision.as_dtype()
|
|
345
|
+
|
|
346
|
+
self._apply_split(
|
|
347
|
+
weight_split,
|
|
348
|
+
prefix="weights",
|
|
349
|
+
# pyre-fixme[6]: For 3rd param expected `Type[Type[_dtype]]` but got
|
|
350
|
+
# `Type[_dtype]`.
|
|
351
|
+
dtype=table_embedding_dtype,
|
|
352
|
+
enforce_hbm=enforce_hbm,
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
if self.use_cpu:
|
|
356
|
+
# Construct optimizer states
|
|
357
|
+
assert optimizer in (
|
|
358
|
+
OptimType.EXACT_ADAGRAD,
|
|
359
|
+
OptimType.EXACT_ROWWISE_ADAGRAD,
|
|
360
|
+
OptimType.EXACT_ROWWISE_WEIGHTED_ADAGRAD,
|
|
361
|
+
OptimType.EXACT_SGD,
|
|
362
|
+
OptimType.ROWWISE_ADAGRAD,
|
|
363
|
+
OptimType.SGD,
|
|
364
|
+
), f"Optimizer {optimizer} is not supported in cpu mode."
|
|
365
|
+
else:
|
|
366
|
+
assert optimizer in (
|
|
367
|
+
OptimType.ADAM,
|
|
368
|
+
OptimType.EXACT_ADAGRAD,
|
|
369
|
+
OptimType.EXACT_ROWWISE_ADAGRAD,
|
|
370
|
+
OptimType.EXACT_ROWWISE_WEIGHTED_ADAGRAD,
|
|
371
|
+
OptimType.EXACT_SGD,
|
|
372
|
+
OptimType.LAMB,
|
|
373
|
+
OptimType.LARS_SGD,
|
|
374
|
+
OptimType.PARTIAL_ROWWISE_ADAM,
|
|
375
|
+
OptimType.PARTIAL_ROWWISE_LAMB,
|
|
376
|
+
OptimType.SGD,
|
|
377
|
+
), f"Optimizer {optimizer} is not supported."
|
|
378
|
+
|
|
379
|
+
self.stochastic_rounding = stochastic_rounding
|
|
380
|
+
self.optimizer = optimizer
|
|
381
|
+
|
|
382
|
+
self.optimizer_args = invokers.lookup_args.OptimizerArgs(
|
|
383
|
+
stochastic_rounding=stochastic_rounding,
|
|
384
|
+
gradient_clipping=gradient_clipping,
|
|
385
|
+
max_gradient=max_gradient,
|
|
386
|
+
learning_rate=learning_rate,
|
|
387
|
+
eps=eps,
|
|
388
|
+
beta1=beta1,
|
|
389
|
+
beta2=beta2,
|
|
390
|
+
weight_decay=weight_decay,
|
|
391
|
+
weight_decay_mode=weight_decay_mode.value,
|
|
392
|
+
eta=eta,
|
|
393
|
+
momentum=momentum,
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
if optimizer in (
|
|
397
|
+
OptimType.SGD,
|
|
398
|
+
OptimType.EXACT_SGD,
|
|
399
|
+
):
|
|
400
|
+
# NOTE: make TorchScript work!
|
|
401
|
+
self.register_buffer(
|
|
402
|
+
"momentum1_dev", torch.tensor([0], dtype=torch.int64), persistent=False
|
|
403
|
+
)
|
|
404
|
+
self.register_buffer(
|
|
405
|
+
"momentum1_host", torch.tensor([0], dtype=torch.int64), persistent=False
|
|
406
|
+
)
|
|
407
|
+
self.register_buffer(
|
|
408
|
+
"momentum1_uvm", torch.tensor([0], dtype=torch.int64), persistent=False
|
|
409
|
+
)
|
|
410
|
+
self.register_buffer(
|
|
411
|
+
"momentum1_placements",
|
|
412
|
+
torch.tensor([0], dtype=torch.int64),
|
|
413
|
+
persistent=False,
|
|
414
|
+
)
|
|
415
|
+
self.register_buffer(
|
|
416
|
+
"momentum1_offsets",
|
|
417
|
+
torch.tensor([0], dtype=torch.int64),
|
|
418
|
+
persistent=False,
|
|
419
|
+
)
|
|
420
|
+
else:
|
|
421
|
+
self._apply_split(
|
|
422
|
+
construct_split_state(
|
|
423
|
+
embedding_specs,
|
|
424
|
+
rowwise=optimizer
|
|
425
|
+
in [
|
|
426
|
+
OptimType.EXACT_ROWWISE_ADAGRAD,
|
|
427
|
+
OptimType.ROWWISE_ADAGRAD,
|
|
428
|
+
OptimType.EXACT_ROWWISE_WEIGHTED_ADAGRAD,
|
|
429
|
+
],
|
|
430
|
+
cacheable=False,
|
|
431
|
+
),
|
|
432
|
+
prefix="momentum1",
|
|
433
|
+
# pyre-fixme[6]: Expected `Type[Type[torch._dtype]]` for 3rd param
|
|
434
|
+
# but got `Type[torch.float32]`.
|
|
435
|
+
dtype=torch.float32,
|
|
436
|
+
enforce_hbm=enforce_hbm,
|
|
437
|
+
)
|
|
438
|
+
if optimizer in (
|
|
439
|
+
OptimType.ADAM,
|
|
440
|
+
OptimType.PARTIAL_ROWWISE_ADAM,
|
|
441
|
+
OptimType.LAMB,
|
|
442
|
+
OptimType.PARTIAL_ROWWISE_LAMB,
|
|
443
|
+
):
|
|
444
|
+
self._apply_split(
|
|
445
|
+
construct_split_state(
|
|
446
|
+
embedding_specs,
|
|
447
|
+
rowwise=optimizer
|
|
448
|
+
in (OptimType.PARTIAL_ROWWISE_ADAM, OptimType.PARTIAL_ROWWISE_LAMB),
|
|
449
|
+
cacheable=False,
|
|
450
|
+
),
|
|
451
|
+
prefix="momentum2",
|
|
452
|
+
# pyre-fixme[6]: Expected `Type[Type[torch._dtype]]` for 3rd param
|
|
453
|
+
# but got `Type[torch.float32]`.
|
|
454
|
+
dtype=torch.float32,
|
|
455
|
+
)
|
|
456
|
+
else:
|
|
457
|
+
# NOTE: make TorchScript work!
|
|
458
|
+
self.register_buffer(
|
|
459
|
+
"momentum2_dev",
|
|
460
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
461
|
+
persistent=False,
|
|
462
|
+
)
|
|
463
|
+
self.register_buffer(
|
|
464
|
+
"momentum2_host",
|
|
465
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
466
|
+
persistent=False,
|
|
467
|
+
)
|
|
468
|
+
self.register_buffer(
|
|
469
|
+
"momentum2_uvm",
|
|
470
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
471
|
+
persistent=False,
|
|
472
|
+
)
|
|
473
|
+
self.register_buffer(
|
|
474
|
+
"momentum2_placements",
|
|
475
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
476
|
+
persistent=False,
|
|
477
|
+
)
|
|
478
|
+
self.register_buffer(
|
|
479
|
+
"momentum2_offsets",
|
|
480
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
481
|
+
persistent=False,
|
|
482
|
+
)
|
|
483
|
+
if optimizer in (
|
|
484
|
+
OptimType.ADAM,
|
|
485
|
+
OptimType.EXACT_ROWWISE_WEIGHTED_ADAGRAD,
|
|
486
|
+
OptimType.LAMB,
|
|
487
|
+
OptimType.PARTIAL_ROWWISE_ADAM,
|
|
488
|
+
OptimType.PARTIAL_ROWWISE_LAMB,
|
|
489
|
+
):
|
|
490
|
+
self.register_buffer(
|
|
491
|
+
"iter", torch.zeros(1, dtype=torch.int64, device=self.current_device)
|
|
492
|
+
)
|
|
493
|
+
else:
|
|
494
|
+
self.register_buffer(
|
|
495
|
+
"iter",
|
|
496
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
497
|
+
persistent=False,
|
|
498
|
+
)
|
|
499
|
+
|
|
500
|
+
cache_state = construct_cache_state(rows, locations, self.feature_table_map)
|
|
501
|
+
|
|
502
|
+
# Add table-wise cache miss counter
|
|
503
|
+
if self.record_cache_metrics.record_tablewise_cache_miss:
|
|
504
|
+
num_tables = len(cache_state.cache_hash_size_cumsum) - 1
|
|
505
|
+
self.register_buffer(
|
|
506
|
+
"table_wise_cache_miss",
|
|
507
|
+
torch.zeros(
|
|
508
|
+
num_tables,
|
|
509
|
+
device=self.current_device,
|
|
510
|
+
dtype=torch.int64,
|
|
511
|
+
),
|
|
512
|
+
)
|
|
513
|
+
# NOTE: make TorchScript work!
|
|
514
|
+
else:
|
|
515
|
+
self.register_buffer(
|
|
516
|
+
"table_wise_cache_miss",
|
|
517
|
+
torch.zeros(
|
|
518
|
+
0,
|
|
519
|
+
device=self.current_device,
|
|
520
|
+
dtype=torch.int64,
|
|
521
|
+
),
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
if cache_precision == SparseType.FP32:
|
|
525
|
+
cache_embedding_dtype = torch.float32
|
|
526
|
+
elif cache_precision == SparseType.FP16:
|
|
527
|
+
cache_embedding_dtype = torch.float16
|
|
528
|
+
else:
|
|
529
|
+
raise AssertionError(f"cache_precision {cache_precision} not supported!")
|
|
530
|
+
|
|
531
|
+
self._apply_cache_state(
|
|
532
|
+
cache_state,
|
|
533
|
+
cache_algorithm,
|
|
534
|
+
cache_load_factor,
|
|
535
|
+
cache_sets,
|
|
536
|
+
cache_reserved_memory,
|
|
537
|
+
dtype=cache_embedding_dtype,
|
|
538
|
+
)
|
|
539
|
+
|
|
540
|
+
logging.info(
|
|
541
|
+
f"Using fused {optimizer} with optimizer_args={self.optimizer_args}"
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
self.step = 0
|
|
545
|
+
|
|
546
|
+
def get_states(self, prefix: str) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
|
|
547
|
+
if not hasattr(self, f"{prefix}_physical_placements"):
|
|
548
|
+
raise DoesNotHavePrefix()
|
|
549
|
+
dev_param = getattr(self, f"{prefix}_dev")
|
|
550
|
+
host_param = getattr(self, f"{prefix}_host")
|
|
551
|
+
uvm_param = getattr(self, f"{prefix}_uvm")
|
|
552
|
+
placements = getattr(self, f"{prefix}_physical_placements")
|
|
553
|
+
offsets = getattr(self, f"{prefix}_physical_offsets")
|
|
554
|
+
return (
|
|
555
|
+
dev_param,
|
|
556
|
+
host_param,
|
|
557
|
+
uvm_param,
|
|
558
|
+
torch.tensor(placements, dtype=torch.int32),
|
|
559
|
+
torch.tensor(offsets, dtype=torch.int64),
|
|
560
|
+
)
|
|
561
|
+
|
|
562
|
+
def get_all_states(self) -> List[Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]]:
|
|
563
|
+
all_states = []
|
|
564
|
+
for prefix in ["weights", "momentum1", "momentum2"]:
|
|
565
|
+
try:
|
|
566
|
+
all_states.append(self.get_states(prefix))
|
|
567
|
+
except DoesNotHavePrefix:
|
|
568
|
+
pass
|
|
569
|
+
return all_states
|
|
570
|
+
|
|
571
|
+
@torch.jit.export
|
|
572
|
+
def get_cache_miss_counter(self) -> Tensor:
|
|
573
|
+
# cache_miss_counter contains two items:
|
|
574
|
+
# The first one is cache_miss_forward_count which records the total number of forwards which has at least one cache miss
|
|
575
|
+
# The second one is the unique_cache_miss_count which records to total number of unique (dedup) cache misses
|
|
576
|
+
|
|
577
|
+
# pyre-fixme[7]: Expected `Tensor` but got `typing.Union[Tensor,
|
|
578
|
+
# nn.Module]`.
|
|
579
|
+
return self.cache_miss_counter
|
|
580
|
+
|
|
581
|
+
@torch.jit.export
|
|
582
|
+
def get_table_wise_cache_miss(self) -> Tensor:
|
|
583
|
+
# table_wise_cache_miss contains all the cache miss count for each table in this embedding table object:
|
|
584
|
+
|
|
585
|
+
return self.table_wise_cache_miss
|
|
586
|
+
|
|
587
|
+
def forward(
|
|
588
|
+
self,
|
|
589
|
+
indices: Tensor,
|
|
590
|
+
offsets: Tensor,
|
|
591
|
+
per_sample_weights: Optional[Tensor] = None,
|
|
592
|
+
feature_requires_grad: Optional[Tensor] = None,
|
|
593
|
+
) -> Tensor:
|
|
594
|
+
(indices, offsets) = indices.long(), offsets.long()
|
|
595
|
+
if self.bounds_check_mode_int != BoundsCheckMode.NONE.value:
|
|
596
|
+
torch.ops.fbgemm.bounds_check_indices(
|
|
597
|
+
self.rows_per_table,
|
|
598
|
+
indices,
|
|
599
|
+
offsets,
|
|
600
|
+
self.bounds_check_mode_int,
|
|
601
|
+
self.bounds_check_warning,
|
|
602
|
+
per_sample_weights,
|
|
603
|
+
)
|
|
604
|
+
self.step += 1
|
|
605
|
+
if len(self.timesteps_prefetched) == 0:
|
|
606
|
+
self.prefetch(indices, offsets)
|
|
607
|
+
|
|
608
|
+
self.timesteps_prefetched.pop(0)
|
|
609
|
+
lxu_cache_locations = (
|
|
610
|
+
self.lxu_cache_locations_empty
|
|
611
|
+
if len(self.lxu_cache_locations_list) == 0
|
|
612
|
+
else self.lxu_cache_locations_list.pop(0)
|
|
613
|
+
)
|
|
614
|
+
common_args = invokers.lookup_args.CommonArgs(
|
|
615
|
+
placeholder_autograd_tensor=self.placeholder_autograd_tensor,
|
|
616
|
+
# pyre-fixme[6]: Expected `Tensor` for 2nd param but got `Union[Tensor,
|
|
617
|
+
# nn.Module]`.
|
|
618
|
+
dev_weights=self.weights_dev,
|
|
619
|
+
# pyre-fixme[6]: Expected `Tensor` for 3rd param but got `Union[Tensor,
|
|
620
|
+
# nn.Module]`.
|
|
621
|
+
host_weights=self.weights_host,
|
|
622
|
+
# pyre-fixme[6]: Expected `Tensor` for 4th param but got `Union[Tensor,
|
|
623
|
+
# nn.Module]`.
|
|
624
|
+
uvm_weights=self.weights_uvm,
|
|
625
|
+
# pyre-fixme[6]: Expected `Tensor` for 5th param but got `Union[Tensor,
|
|
626
|
+
# nn.Module]`.
|
|
627
|
+
lxu_cache_weights=self.lxu_cache_weights,
|
|
628
|
+
# pyre-fixme[6]: Expected `Tensor` for 6th param but got `Union[Tensor,
|
|
629
|
+
# nn.Module]`.
|
|
630
|
+
weights_placements=self.weights_placements,
|
|
631
|
+
# pyre-fixme[6]: Expected `Tensor` for 7th param but got `Union[Tensor,
|
|
632
|
+
# nn.Module]`.
|
|
633
|
+
weights_offsets=self.weights_offsets,
|
|
634
|
+
D_offsets=self.D_offsets,
|
|
635
|
+
total_D=self.total_D,
|
|
636
|
+
max_D=self.max_D,
|
|
637
|
+
hash_size_cumsum=self.hash_size_cumsum,
|
|
638
|
+
total_hash_size_bits=self.total_hash_size_bits,
|
|
639
|
+
indices=indices,
|
|
640
|
+
offsets=offsets,
|
|
641
|
+
pooling_mode=self.pooling_mode,
|
|
642
|
+
indice_weights=per_sample_weights,
|
|
643
|
+
feature_requires_grad=feature_requires_grad,
|
|
644
|
+
lxu_cache_locations=lxu_cache_locations,
|
|
645
|
+
output_dtype=self.output_dtype,
|
|
646
|
+
)
|
|
647
|
+
|
|
648
|
+
if self.optimizer == OptimType.EXACT_SGD:
|
|
649
|
+
return invokers.lookup_sgd.invoke(common_args, self.optimizer_args)
|
|
650
|
+
elif self.optimizer == OptimType.SGD:
|
|
651
|
+
assert self.use_cpu, "Approx SGD is only supported in CPU mode"
|
|
652
|
+
return invokers.lookup_approx_sgd.invoke(common_args, self.optimizer_args)
|
|
653
|
+
|
|
654
|
+
momentum1 = invokers.lookup_args.Momentum(
|
|
655
|
+
dev=self.momentum1_dev,
|
|
656
|
+
host=self.momentum1_host,
|
|
657
|
+
uvm=self.momentum1_uvm,
|
|
658
|
+
offsets=self.momentum1_offsets,
|
|
659
|
+
placements=self.momentum1_placements,
|
|
660
|
+
)
|
|
661
|
+
|
|
662
|
+
if self.optimizer == OptimType.LARS_SGD:
|
|
663
|
+
return invokers.lookup_lars_sgd.invoke(
|
|
664
|
+
common_args, self.optimizer_args, momentum1
|
|
665
|
+
)
|
|
666
|
+
if self.optimizer == OptimType.EXACT_ADAGRAD:
|
|
667
|
+
return invokers.lookup_adagrad.invoke(
|
|
668
|
+
common_args, self.optimizer_args, momentum1
|
|
669
|
+
)
|
|
670
|
+
if self.optimizer == OptimType.EXACT_ROWWISE_ADAGRAD:
|
|
671
|
+
return invokers.lookup_rowwise_adagrad.invoke(
|
|
672
|
+
common_args, self.optimizer_args, momentum1
|
|
673
|
+
)
|
|
674
|
+
if self.optimizer == OptimType.ROWWISE_ADAGRAD:
|
|
675
|
+
assert self.use_cpu, "Approx rowwise AdaGrad is only supported in CPU mode"
|
|
676
|
+
return invokers.lookup_approx_rowwise_adagrad.invoke(
|
|
677
|
+
common_args, self.optimizer_args, momentum1
|
|
678
|
+
)
|
|
679
|
+
|
|
680
|
+
momentum2 = invokers.lookup_args.Momentum(
|
|
681
|
+
dev=self.momentum2_dev,
|
|
682
|
+
host=self.momentum2_host,
|
|
683
|
+
uvm=self.momentum2_uvm,
|
|
684
|
+
offsets=self.momentum2_offsets,
|
|
685
|
+
placements=self.momentum2_placements,
|
|
686
|
+
)
|
|
687
|
+
# Ensure iter is always on CPU so the increment doesn't synchronize.
|
|
688
|
+
if self.iter.is_cuda:
|
|
689
|
+
self.iter = self.iter.cpu()
|
|
690
|
+
self.iter[0] += 1
|
|
691
|
+
|
|
692
|
+
if self.optimizer == OptimType.EXACT_ROWWISE_WEIGHTED_ADAGRAD:
|
|
693
|
+
return invokers.lookup_rowwise_weighted_adagrad.invoke(
|
|
694
|
+
common_args,
|
|
695
|
+
self.optimizer_args,
|
|
696
|
+
momentum1,
|
|
697
|
+
# pyre-fixme[6]: Expected `int` for 4th param but got `Union[float,
|
|
698
|
+
# int]`.
|
|
699
|
+
self.iter.item(),
|
|
700
|
+
)
|
|
701
|
+
if self.optimizer == OptimType.ADAM:
|
|
702
|
+
return invokers.lookup_adam.invoke(
|
|
703
|
+
common_args,
|
|
704
|
+
self.optimizer_args,
|
|
705
|
+
momentum1,
|
|
706
|
+
momentum2,
|
|
707
|
+
# pyre-fixme[6]: Expected `int` for 5th param but got `Union[float,
|
|
708
|
+
# int]`.
|
|
709
|
+
self.iter.item(),
|
|
710
|
+
)
|
|
711
|
+
if self.optimizer == OptimType.PARTIAL_ROWWISE_ADAM:
|
|
712
|
+
return invokers.lookup_partial_rowwise_adam.invoke(
|
|
713
|
+
common_args,
|
|
714
|
+
self.optimizer_args,
|
|
715
|
+
momentum1,
|
|
716
|
+
momentum2,
|
|
717
|
+
# pyre-fixme[6]: Expected `int` for 5th param but got `Union[float,
|
|
718
|
+
# int]`.
|
|
719
|
+
self.iter.item(),
|
|
720
|
+
)
|
|
721
|
+
if self.optimizer == OptimType.LAMB:
|
|
722
|
+
return invokers.lookup_lamb.invoke(
|
|
723
|
+
common_args,
|
|
724
|
+
self.optimizer_args,
|
|
725
|
+
momentum1,
|
|
726
|
+
momentum2,
|
|
727
|
+
# pyre-fixme[6]: Expected `int` for 5th param but got `Union[float,
|
|
728
|
+
# int]`.
|
|
729
|
+
self.iter.item(),
|
|
730
|
+
)
|
|
731
|
+
if self.optimizer == OptimType.PARTIAL_ROWWISE_LAMB:
|
|
732
|
+
return invokers.lookup_partial_rowwise_lamb.invoke(
|
|
733
|
+
common_args,
|
|
734
|
+
self.optimizer_args,
|
|
735
|
+
momentum1,
|
|
736
|
+
momentum2,
|
|
737
|
+
# pyre-fixme[6]: Expected `int` for 5th param but got `Union[float,
|
|
738
|
+
# int]`.
|
|
739
|
+
self.iter.item(),
|
|
740
|
+
)
|
|
741
|
+
|
|
742
|
+
raise ValueError(f"Invalid OptimType: {self.optimizer}")
|
|
743
|
+
|
|
744
|
+
def prefetch(self, indices: Tensor, offsets: Tensor) -> None:
|
|
745
|
+
self.timestep += 1
|
|
746
|
+
self.timesteps_prefetched.append(self.timestep)
|
|
747
|
+
# pyre-fixme[29]:
|
|
748
|
+
# `Union[BoundMethod[typing.Callable(Tensor.numel)[[Named(self, Tensor)],
|
|
749
|
+
# int], Tensor], Tensor, nn.Module]` is not a function.
|
|
750
|
+
if not self.lxu_cache_weights.numel():
|
|
751
|
+
return
|
|
752
|
+
|
|
753
|
+
(indices, offsets) = indices.long(), offsets.long()
|
|
754
|
+
linear_cache_indices = torch.ops.fbgemm.linearize_cache_indices(
|
|
755
|
+
self.cache_hash_size_cumsum,
|
|
756
|
+
indices,
|
|
757
|
+
offsets,
|
|
758
|
+
)
|
|
759
|
+
|
|
760
|
+
if (
|
|
761
|
+
self.record_cache_metrics.record_cache_miss_counter
|
|
762
|
+
or self.record_cache_metrics.record_tablewise_cache_miss
|
|
763
|
+
):
|
|
764
|
+
lxu_cache_locations = torch.ops.fbgemm.lxu_cache_lookup(
|
|
765
|
+
linear_cache_indices,
|
|
766
|
+
self.lxu_cache_state,
|
|
767
|
+
self.total_cache_hash_size,
|
|
768
|
+
)
|
|
769
|
+
if self.record_cache_metrics.record_cache_miss_counter:
|
|
770
|
+
self._update_cache_miss_counter(
|
|
771
|
+
lxu_cache_locations, linear_cache_indices
|
|
772
|
+
)
|
|
773
|
+
if self.record_cache_metrics.record_tablewise_cache_miss:
|
|
774
|
+
self._update_tablewise_cache_miss(
|
|
775
|
+
lxu_cache_locations, linear_cache_indices, offsets
|
|
776
|
+
)
|
|
777
|
+
|
|
778
|
+
if self.cache_algorithm == CacheAlgorithm.LRU:
|
|
779
|
+
torch.ops.fbgemm.lru_cache_populate(
|
|
780
|
+
self.weights_uvm,
|
|
781
|
+
self.cache_hash_size_cumsum,
|
|
782
|
+
self.total_cache_hash_size,
|
|
783
|
+
self.cache_index_table_map,
|
|
784
|
+
self.weights_offsets,
|
|
785
|
+
self.D_offsets,
|
|
786
|
+
linear_cache_indices,
|
|
787
|
+
self.lxu_cache_state,
|
|
788
|
+
self.lxu_cache_weights,
|
|
789
|
+
self.timestep,
|
|
790
|
+
self.lxu_state,
|
|
791
|
+
self.stochastic_rounding,
|
|
792
|
+
)
|
|
793
|
+
elif self.cache_algorithm == CacheAlgorithm.LFU:
|
|
794
|
+
torch.ops.fbgemm.lfu_cache_populate(
|
|
795
|
+
self.weights_uvm,
|
|
796
|
+
self.cache_hash_size_cumsum,
|
|
797
|
+
self.total_cache_hash_size,
|
|
798
|
+
self.cache_index_table_map,
|
|
799
|
+
self.weights_offsets,
|
|
800
|
+
self.D_offsets,
|
|
801
|
+
linear_cache_indices,
|
|
802
|
+
self.lxu_cache_state,
|
|
803
|
+
self.lxu_cache_weights,
|
|
804
|
+
self.lxu_state,
|
|
805
|
+
self.stochastic_rounding,
|
|
806
|
+
)
|
|
807
|
+
|
|
808
|
+
assert (
|
|
809
|
+
len(self.lxu_cache_locations_list) < self.max_prefetch_depth
|
|
810
|
+
), f"self.lxu_cache_locations_list has grown to size: {len(self.lxu_cache_locations_list)}, this exceeds the maximum: {self.max_prefetch_depth}. This probably indicates an error in logic where prefetch() is being called more frequently than forward()"
|
|
811
|
+
self.lxu_cache_locations_list.append(
|
|
812
|
+
torch.ops.fbgemm.lxu_cache_lookup(
|
|
813
|
+
linear_cache_indices,
|
|
814
|
+
self.lxu_cache_state,
|
|
815
|
+
self.total_cache_hash_size,
|
|
816
|
+
)
|
|
817
|
+
)
|
|
818
|
+
|
|
819
|
+
def _update_cache_miss_counter(
|
|
820
|
+
self,
|
|
821
|
+
lxu_cache_locations: Tensor,
|
|
822
|
+
linear_cache_indices: Tensor,
|
|
823
|
+
) -> None:
|
|
824
|
+
CACHE_MISS = -1
|
|
825
|
+
CACHE_HIT = -2
|
|
826
|
+
|
|
827
|
+
cache_missed_locations = torch.where(
|
|
828
|
+
lxu_cache_locations == CACHE_MISS, linear_cache_indices, CACHE_HIT
|
|
829
|
+
)
|
|
830
|
+
unique_ids_list = torch.unique(cache_missed_locations)
|
|
831
|
+
unique_ids_count_list = torch.where(unique_ids_list == CACHE_HIT, 0, 1)
|
|
832
|
+
|
|
833
|
+
miss_count = torch.sum(unique_ids_count_list)
|
|
834
|
+
|
|
835
|
+
# pyre-fixme[29]:
|
|
836
|
+
# `Union[BoundMethod[typing.Callable(Tensor.__getitem__)[[Named(self,
|
|
837
|
+
# Tensor), Named(item, typing.Any)], typing.Any], Tensor], Tensor,
|
|
838
|
+
# nn.Module]` is not a function.
|
|
839
|
+
self.cache_miss_counter[0] += (miss_count > 0).to(torch.int64)
|
|
840
|
+
|
|
841
|
+
# pyre-fixme[29]:
|
|
842
|
+
# `Union[BoundMethod[typing.Callable(Tensor.__getitem__)[[Named(self,
|
|
843
|
+
# Tensor), Named(item, typing.Any)], typing.Any], Tensor], Tensor,
|
|
844
|
+
# nn.Module]` is not a function.
|
|
845
|
+
self.cache_miss_counter[1] += miss_count
|
|
846
|
+
|
|
847
|
+
def _update_tablewise_cache_miss(
|
|
848
|
+
self,
|
|
849
|
+
lxu_cache_locations: Tensor,
|
|
850
|
+
linear_cache_indices: Tensor,
|
|
851
|
+
offsets: Tensor,
|
|
852
|
+
) -> None:
|
|
853
|
+
CACHE_MISS = -1
|
|
854
|
+
CACHE_HIT = -2
|
|
855
|
+
|
|
856
|
+
# pyre-ignore[6]:
|
|
857
|
+
# Incompatible parameter type [6]: Expected `typing.Sized` for 1st
|
|
858
|
+
# positional only parameter to call `len` but got `typing.Union[Tensor, nn.Module]`.
|
|
859
|
+
num_tables = len(self.cache_hash_size_cumsum) - 1
|
|
860
|
+
num_offsets_per_table = (len(offsets) - 1) // num_tables
|
|
861
|
+
cache_missed_locations = torch.where(
|
|
862
|
+
lxu_cache_locations == CACHE_MISS, linear_cache_indices, CACHE_HIT
|
|
863
|
+
)
|
|
864
|
+
|
|
865
|
+
for i in range(num_tables):
|
|
866
|
+
start = offsets[i * num_offsets_per_table]
|
|
867
|
+
end = offsets[(i + 1) * num_offsets_per_table]
|
|
868
|
+
|
|
869
|
+
current_cache_missed_locations = cache_missed_locations[start:end]
|
|
870
|
+
unique_ids_list = torch.unique(current_cache_missed_locations)
|
|
871
|
+
unique_ids_count_list = torch.where(unique_ids_list == CACHE_HIT, 0, 1)
|
|
872
|
+
|
|
873
|
+
miss_count = torch.sum(unique_ids_count_list)
|
|
874
|
+
|
|
875
|
+
self.table_wise_cache_miss[i] += miss_count
|
|
876
|
+
|
|
877
|
+
def init_embedding_weights_uniform(self, min_val: float, max_val: float) -> None:
|
|
878
|
+
splits = self.split_embedding_weights()
|
|
879
|
+
if self.weights_precision == SparseType.INT8:
|
|
880
|
+
# TODO: add in-place FloatToFused8BitRowwiseQuantized conversion
|
|
881
|
+
for emb in splits:
|
|
882
|
+
assert (
|
|
883
|
+
len(emb.shape) == 2
|
|
884
|
+
), "Int8 embedding only supported for 2D weight tensors."
|
|
885
|
+
shape = [emb.shape[0], emb.shape[1] - self.int8_emb_row_dim_offset]
|
|
886
|
+
tmp_emb = torch.zeros(shape, device=self.current_device)
|
|
887
|
+
tmp_emb.uniform_(min_val, max_val)
|
|
888
|
+
tmp_emb_i8 = torch.ops.fbgemm.FloatToFused8BitRowwiseQuantized(tmp_emb)
|
|
889
|
+
emb.data.copy_(tmp_emb_i8)
|
|
890
|
+
else:
|
|
891
|
+
for param in splits:
|
|
892
|
+
param.uniform_(min_val, max_val)
|
|
893
|
+
|
|
894
|
+
@torch.jit.ignore
|
|
895
|
+
def split_embedding_weights(self) -> List[Tensor]:
|
|
896
|
+
"""
|
|
897
|
+
Returns a list of weights, split by table
|
|
898
|
+
"""
|
|
899
|
+
splits = []
|
|
900
|
+
for t, (rows, dim, _, _) in enumerate(self.embedding_specs):
|
|
901
|
+
if self.weights_precision == SparseType.INT8:
|
|
902
|
+
dim += self.int8_emb_row_dim_offset
|
|
903
|
+
# pyre-fixme[29]:
|
|
904
|
+
# `Union[BoundMethod[typing.Callable(Tensor.__getitem__)[[Named(self,
|
|
905
|
+
# Tensor), Named(item, typing.Any)], typing.Any], Tensor], Tensor,
|
|
906
|
+
# nn.Module]` is not a function.
|
|
907
|
+
placement = self.weights_physical_placements[t]
|
|
908
|
+
# pyre-fixme[29]:
|
|
909
|
+
# `Union[BoundMethod[typing.Callable(Tensor.__getitem__)[[Named(self,
|
|
910
|
+
# Tensor), Named(item, typing.Any)], typing.Any], Tensor], Tensor,
|
|
911
|
+
# nn.Module]` is not a function.
|
|
912
|
+
offset = self.weights_physical_offsets[t]
|
|
913
|
+
if placement == EmbeddingLocation.DEVICE.value:
|
|
914
|
+
weights = self.weights_dev
|
|
915
|
+
elif placement == EmbeddingLocation.HOST.value:
|
|
916
|
+
weights = self.weights_host
|
|
917
|
+
else:
|
|
918
|
+
weights = self.weights_uvm
|
|
919
|
+
splits.append(
|
|
920
|
+
# pyre-fixme[29]:
|
|
921
|
+
# `Union[BoundMethod[typing.Callable(Tensor.detach)[[Named(self,
|
|
922
|
+
# Tensor)], Tensor], Tensor], Tensor, nn.Module]` is not a function.
|
|
923
|
+
weights.detach()[offset : offset + rows * dim].view(rows, dim)
|
|
924
|
+
)
|
|
925
|
+
return splits
|
|
926
|
+
|
|
927
|
+
@torch.jit.ignore
|
|
928
|
+
def get_optimizer_buffer(self, state: str) -> torch.Tensor:
|
|
929
|
+
for name, buffer in self.named_buffers():
|
|
930
|
+
if name == state:
|
|
931
|
+
return buffer
|
|
932
|
+
return torch.tensor(0)
|
|
933
|
+
|
|
934
|
+
@torch.jit.export
|
|
935
|
+
def get_optimizer_state(self) -> List[Dict[str, torch.Tensor]]:
|
|
936
|
+
r"""
|
|
937
|
+
Get the optimizer state dict that matches the OSS Pytorch optims
|
|
938
|
+
TODO: populate the supported list of optimizers
|
|
939
|
+
"""
|
|
940
|
+
if (
|
|
941
|
+
self.optimizer == OptimType.EXACT_ROWWISE_ADAGRAD
|
|
942
|
+
or self.optimizer == OptimType.ROWWISE_ADAGRAD
|
|
943
|
+
or self.optimizer == OptimType.EXACT_ROWWISE_WEIGHTED_ADAGRAD
|
|
944
|
+
):
|
|
945
|
+
list_of_state_dict = [
|
|
946
|
+
{"sum": _sum[0]} for _sum in self.split_optimizer_states()
|
|
947
|
+
]
|
|
948
|
+
else:
|
|
949
|
+
raise NotImplementedError(
|
|
950
|
+
f"Getting optimizer state {self.optimizer} is not implmeneted"
|
|
951
|
+
)
|
|
952
|
+
|
|
953
|
+
return list_of_state_dict
|
|
954
|
+
|
|
955
|
+
@torch.jit.ignore
|
|
956
|
+
def split_optimizer_states(self) -> List[Tuple[torch.Tensor]]:
|
|
957
|
+
"""
|
|
958
|
+
Returns a list of states, split by table
|
|
959
|
+
"""
|
|
960
|
+
|
|
961
|
+
def get_optimizer_states(
|
|
962
|
+
state_dev: Tensor,
|
|
963
|
+
state_host: Tensor,
|
|
964
|
+
state_uvm: Tensor,
|
|
965
|
+
state_offsets: Tensor,
|
|
966
|
+
state_placements: Tensor,
|
|
967
|
+
rowwise: bool,
|
|
968
|
+
) -> List[torch.Tensor]:
|
|
969
|
+
splits = []
|
|
970
|
+
for t, (rows, dim, _, _) in enumerate(self.embedding_specs):
|
|
971
|
+
offset = state_offsets[t]
|
|
972
|
+
placement = state_placements[t]
|
|
973
|
+
if placement == EmbeddingLocation.DEVICE:
|
|
974
|
+
state = state_dev
|
|
975
|
+
elif placement == EmbeddingLocation.HOST:
|
|
976
|
+
state = state_host
|
|
977
|
+
else:
|
|
978
|
+
state = state_uvm
|
|
979
|
+
if not rowwise:
|
|
980
|
+
splits.append(
|
|
981
|
+
state.detach()[offset : offset + rows * dim].view(rows, dim)
|
|
982
|
+
)
|
|
983
|
+
else:
|
|
984
|
+
splits.append(state.detach()[offset : offset + rows].view(rows))
|
|
985
|
+
return splits
|
|
986
|
+
|
|
987
|
+
states: List[List[torch.Tensor]] = []
|
|
988
|
+
if self.optimizer not in (
|
|
989
|
+
OptimType.SGD,
|
|
990
|
+
OptimType.EXACT_SGD,
|
|
991
|
+
):
|
|
992
|
+
states.append(
|
|
993
|
+
get_optimizer_states(
|
|
994
|
+
self.momentum1_dev,
|
|
995
|
+
self.momentum1_host,
|
|
996
|
+
self.momentum1_uvm,
|
|
997
|
+
# pyre-fixme[6]: Expected `Tensor` for 4th param but got
|
|
998
|
+
# `Union[Tensor, nn.Module]`.
|
|
999
|
+
self.momentum1_physical_offsets,
|
|
1000
|
+
# pyre-fixme[6]: Expected `Tensor` for 5th param but got
|
|
1001
|
+
# `Union[Tensor, nn.Module]`.
|
|
1002
|
+
self.momentum1_physical_placements,
|
|
1003
|
+
rowwise=self.optimizer
|
|
1004
|
+
in [
|
|
1005
|
+
OptimType.EXACT_ROWWISE_ADAGRAD,
|
|
1006
|
+
OptimType.ROWWISE_ADAGRAD,
|
|
1007
|
+
OptimType.EXACT_ROWWISE_WEIGHTED_ADAGRAD,
|
|
1008
|
+
],
|
|
1009
|
+
)
|
|
1010
|
+
)
|
|
1011
|
+
if self.optimizer in (
|
|
1012
|
+
OptimType.ADAM,
|
|
1013
|
+
OptimType.PARTIAL_ROWWISE_ADAM,
|
|
1014
|
+
OptimType.LAMB,
|
|
1015
|
+
OptimType.PARTIAL_ROWWISE_LAMB,
|
|
1016
|
+
):
|
|
1017
|
+
states.append(
|
|
1018
|
+
get_optimizer_states(
|
|
1019
|
+
self.momentum2_dev,
|
|
1020
|
+
self.momentum2_host,
|
|
1021
|
+
self.momentum2_uvm,
|
|
1022
|
+
# pyre-fixme[6]: Expected `Tensor` for 4th param but got
|
|
1023
|
+
# `Union[Tensor, nn.Module]`.
|
|
1024
|
+
self.momentum2_physical_offsets,
|
|
1025
|
+
# pyre-fixme[6]: Expected `Tensor` for 5th param but got
|
|
1026
|
+
# `Union[Tensor, nn.Module]`.
|
|
1027
|
+
self.momentum2_physical_placements,
|
|
1028
|
+
rowwise=self.optimizer
|
|
1029
|
+
in (OptimType.PARTIAL_ROWWISE_ADAM, OptimType.PARTIAL_ROWWISE_LAMB),
|
|
1030
|
+
)
|
|
1031
|
+
)
|
|
1032
|
+
return list(zip(*states))
|
|
1033
|
+
|
|
1034
|
+
@torch.jit.export
|
|
1035
|
+
def set_learning_rate(self, lr: float) -> None:
|
|
1036
|
+
"""
|
|
1037
|
+
Sets the learning rate.
|
|
1038
|
+
"""
|
|
1039
|
+
self._set_learning_rate(lr)
|
|
1040
|
+
|
|
1041
|
+
@torch.jit.ignore
|
|
1042
|
+
def _set_learning_rate(self, lr: float) -> float:
|
|
1043
|
+
"""
|
|
1044
|
+
Helper function to script `set_learning_rate`.
|
|
1045
|
+
Note that returning None does not work.
|
|
1046
|
+
"""
|
|
1047
|
+
self.optimizer_args = self.optimizer_args._replace(learning_rate=lr)
|
|
1048
|
+
return 0.0
|
|
1049
|
+
|
|
1050
|
+
@torch.jit.export
|
|
1051
|
+
def set_optimizer_step(self, step: int) -> None:
|
|
1052
|
+
"""
|
|
1053
|
+
Sets the optimizer step.
|
|
1054
|
+
"""
|
|
1055
|
+
self.iter[0] = step
|
|
1056
|
+
|
|
1057
|
+
@torch.jit.export
|
|
1058
|
+
def flush(self) -> None:
|
|
1059
|
+
# pyre-fixme[29]:
|
|
1060
|
+
# `Union[BoundMethod[typing.Callable(Tensor.numel)[[Named(self, Tensor)],
|
|
1061
|
+
# int], Tensor], Tensor, nn.Module]` is not a function.
|
|
1062
|
+
if not self.lxu_cache_weights.numel():
|
|
1063
|
+
return
|
|
1064
|
+
torch.ops.fbgemm.lxu_cache_flush(
|
|
1065
|
+
self.weights_uvm,
|
|
1066
|
+
self.cache_hash_size_cumsum,
|
|
1067
|
+
self.cache_index_table_map,
|
|
1068
|
+
self.weights_offsets,
|
|
1069
|
+
self.D_offsets,
|
|
1070
|
+
self.total_D,
|
|
1071
|
+
self.lxu_cache_state,
|
|
1072
|
+
self.lxu_cache_weights,
|
|
1073
|
+
self.stochastic_rounding,
|
|
1074
|
+
)
|
|
1075
|
+
|
|
1076
|
+
def _apply_split(
|
|
1077
|
+
self,
|
|
1078
|
+
split: SplitState,
|
|
1079
|
+
prefix: str,
|
|
1080
|
+
dtype: Type[torch.dtype],
|
|
1081
|
+
enforce_hbm: bool = False,
|
|
1082
|
+
) -> None:
|
|
1083
|
+
setattr(self, f"{prefix}_physical_placements", split.placements)
|
|
1084
|
+
setattr(self, f"{prefix}_physical_offsets", split.offsets)
|
|
1085
|
+
|
|
1086
|
+
offsets = [split.offsets[t] for t in self.feature_table_map]
|
|
1087
|
+
placements = [split.placements[t] for t in self.feature_table_map]
|
|
1088
|
+
self.register_buffer(
|
|
1089
|
+
f"{prefix}_offsets",
|
|
1090
|
+
torch.tensor(offsets, device=self.current_device, dtype=torch.int64),
|
|
1091
|
+
)
|
|
1092
|
+
self.register_buffer(
|
|
1093
|
+
f"{prefix}_placements",
|
|
1094
|
+
torch.tensor(placements, device=self.current_device, dtype=torch.int32),
|
|
1095
|
+
)
|
|
1096
|
+
if split.dev_size > 0:
|
|
1097
|
+
self.register_buffer(
|
|
1098
|
+
f"{prefix}_dev",
|
|
1099
|
+
# pyre-fixme[6]: Expected `Optional[Type[torch._dtype]]` for 3rd
|
|
1100
|
+
# param but got `Type[Type[torch._dtype]]`.
|
|
1101
|
+
torch.zeros(split.dev_size, device=self.current_device, dtype=dtype),
|
|
1102
|
+
)
|
|
1103
|
+
else:
|
|
1104
|
+
self.register_buffer(
|
|
1105
|
+
f"{prefix}_dev",
|
|
1106
|
+
torch.empty(0, device=self.current_device, dtype=dtype),
|
|
1107
|
+
)
|
|
1108
|
+
if split.host_size > 0:
|
|
1109
|
+
if dtype == torch.uint8:
|
|
1110
|
+
self.register_buffer(
|
|
1111
|
+
f"{prefix}_host",
|
|
1112
|
+
torch.zeros(
|
|
1113
|
+
split.host_size,
|
|
1114
|
+
device=self.current_device,
|
|
1115
|
+
# pyre-fixme[6]: Expected `Optional[Type[torch._dtype]]` for
|
|
1116
|
+
# 3rd param but got `Type[Type[torch._dtype]]`.
|
|
1117
|
+
dtype=dtype,
|
|
1118
|
+
),
|
|
1119
|
+
)
|
|
1120
|
+
else:
|
|
1121
|
+
setattr(
|
|
1122
|
+
self,
|
|
1123
|
+
f"{prefix}_host",
|
|
1124
|
+
nn.Parameter(
|
|
1125
|
+
torch.zeros(
|
|
1126
|
+
split.host_size,
|
|
1127
|
+
device=self.current_device,
|
|
1128
|
+
# pyre-fixme[6]: Expected `Optional[Type[torch._dtype]]`
|
|
1129
|
+
# for 3rd param but got `Type[Type[torch._dtype]]`.
|
|
1130
|
+
dtype=dtype,
|
|
1131
|
+
)
|
|
1132
|
+
),
|
|
1133
|
+
)
|
|
1134
|
+
else:
|
|
1135
|
+
self.register_buffer(
|
|
1136
|
+
f"{prefix}_host",
|
|
1137
|
+
torch.empty(0, device=self.current_device, dtype=dtype),
|
|
1138
|
+
)
|
|
1139
|
+
if split.uvm_size > 0:
|
|
1140
|
+
assert not self.use_cpu
|
|
1141
|
+
if enforce_hbm:
|
|
1142
|
+
logging.info("Enforce hbm for the cache location")
|
|
1143
|
+
self.register_buffer(
|
|
1144
|
+
f"{prefix}_uvm",
|
|
1145
|
+
torch.zeros(
|
|
1146
|
+
split.uvm_size,
|
|
1147
|
+
device=self.current_device,
|
|
1148
|
+
# pyre-fixme[6]: Expected `Optional[Type[torch._dtype]]` for
|
|
1149
|
+
# 3rd param but got `Type[Type[torch._dtype]]`.
|
|
1150
|
+
dtype=dtype,
|
|
1151
|
+
),
|
|
1152
|
+
)
|
|
1153
|
+
else:
|
|
1154
|
+
self.register_buffer(
|
|
1155
|
+
f"{prefix}_uvm",
|
|
1156
|
+
torch.zeros(
|
|
1157
|
+
split.uvm_size,
|
|
1158
|
+
out=torch.ops.fbgemm.new_managed_tensor(
|
|
1159
|
+
# pyre-fixme[6]: Expected `Optional[Type[torch._dtype]]`
|
|
1160
|
+
# for 3rd param but got `Type[Type[torch._dtype]]`.
|
|
1161
|
+
torch.zeros(1, device=self.current_device, dtype=dtype),
|
|
1162
|
+
[split.uvm_size],
|
|
1163
|
+
),
|
|
1164
|
+
),
|
|
1165
|
+
)
|
|
1166
|
+
else:
|
|
1167
|
+
self.register_buffer(
|
|
1168
|
+
f"{prefix}_uvm",
|
|
1169
|
+
torch.empty(0, device=self.current_device, dtype=dtype),
|
|
1170
|
+
)
|
|
1171
|
+
|
|
1172
|
+
def _apply_cache_state(
|
|
1173
|
+
self,
|
|
1174
|
+
cache_state: CacheState,
|
|
1175
|
+
cache_algorithm: CacheAlgorithm,
|
|
1176
|
+
cache_load_factor: float,
|
|
1177
|
+
cache_sets: int,
|
|
1178
|
+
cache_reserved_memory: float,
|
|
1179
|
+
dtype: torch.dtype,
|
|
1180
|
+
) -> None:
|
|
1181
|
+
self.cache_algorithm = cache_algorithm
|
|
1182
|
+
self.timestep = 1
|
|
1183
|
+
self.timesteps_prefetched = []
|
|
1184
|
+
|
|
1185
|
+
self.max_prefetch_depth = MAX_PREFETCH_DEPTH
|
|
1186
|
+
self.lxu_cache_locations_list = []
|
|
1187
|
+
self.lxu_cache_locations_empty = torch.empty(
|
|
1188
|
+
0, device=self.current_device, dtype=torch.int32
|
|
1189
|
+
).fill_(-1)
|
|
1190
|
+
|
|
1191
|
+
# NOTE: no cache for CPU mode!
|
|
1192
|
+
if cache_state.total_cache_hash_size == 0 or self.use_cpu:
|
|
1193
|
+
self.register_buffer(
|
|
1194
|
+
"lxu_cache_weights",
|
|
1195
|
+
torch.zeros(0, 0, device=self.current_device, dtype=dtype),
|
|
1196
|
+
)
|
|
1197
|
+
# NOTE: make TorchScript work!
|
|
1198
|
+
self.register_buffer(
|
|
1199
|
+
"cache_hash_size_cumsum",
|
|
1200
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
1201
|
+
persistent=False,
|
|
1202
|
+
)
|
|
1203
|
+
self.register_buffer(
|
|
1204
|
+
"total_cache_hash_size",
|
|
1205
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
1206
|
+
persistent=False,
|
|
1207
|
+
)
|
|
1208
|
+
self.register_buffer(
|
|
1209
|
+
"cache_index_table_map",
|
|
1210
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
1211
|
+
persistent=False,
|
|
1212
|
+
)
|
|
1213
|
+
self.register_buffer(
|
|
1214
|
+
"lxu_cache_state",
|
|
1215
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
1216
|
+
persistent=False,
|
|
1217
|
+
)
|
|
1218
|
+
self.register_buffer(
|
|
1219
|
+
"lxu_state",
|
|
1220
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
1221
|
+
persistent=False,
|
|
1222
|
+
)
|
|
1223
|
+
self.register_buffer(
|
|
1224
|
+
"cache_miss_counter",
|
|
1225
|
+
torch.tensor([0, 0], dtype=torch.int64),
|
|
1226
|
+
persistent=False,
|
|
1227
|
+
)
|
|
1228
|
+
return
|
|
1229
|
+
|
|
1230
|
+
assert cache_load_factor > 0
|
|
1231
|
+
element_size = 2 if dtype == torch.float16 else 4
|
|
1232
|
+
if cache_sets <= 0:
|
|
1233
|
+
total_memory = torch.cuda.get_device_properties(
|
|
1234
|
+
self.current_device
|
|
1235
|
+
).total_memory
|
|
1236
|
+
free_memory = (
|
|
1237
|
+
total_memory
|
|
1238
|
+
- torch.cuda.memory_reserved(self.current_device)
|
|
1239
|
+
- int(cache_reserved_memory)
|
|
1240
|
+
)
|
|
1241
|
+
assert free_memory > 0
|
|
1242
|
+
cache_sets = (
|
|
1243
|
+
int(cache_state.total_cache_hash_size * cache_load_factor) + ASSOC - 1
|
|
1244
|
+
) // ASSOC
|
|
1245
|
+
cache_sets = 1 if cache_sets == 0 else cache_sets
|
|
1246
|
+
cache_size = cache_sets * ASSOC * element_size * self.max_D_cache
|
|
1247
|
+
if cache_size > free_memory:
|
|
1248
|
+
cache_sets = (
|
|
1249
|
+
int(1.0 * free_memory / self.max_D_cache / element_size) + ASSOC - 1
|
|
1250
|
+
) // ASSOC
|
|
1251
|
+
cache_load_factor = (
|
|
1252
|
+
1.0 * cache_sets * ASSOC / int(cache_state.total_cache_hash_size)
|
|
1253
|
+
)
|
|
1254
|
+
assert cache_sets > 0
|
|
1255
|
+
if cache_algorithm == CacheAlgorithm.LFU:
|
|
1256
|
+
assert cache_sets < 2**24 - 1
|
|
1257
|
+
cache_size = cache_sets * ASSOC * element_size * self.max_D_cache
|
|
1258
|
+
logging.info(
|
|
1259
|
+
f"Using on-device cache with admission algorithm "
|
|
1260
|
+
f"{cache_algorithm}, {cache_sets} sets, "
|
|
1261
|
+
f"load_factor: {cache_load_factor : .3f}, "
|
|
1262
|
+
f"{cache_size / 1024.0 / 1024.0 / 1024.0 : .2f}GB"
|
|
1263
|
+
)
|
|
1264
|
+
|
|
1265
|
+
self.total_cache_hash_size = cache_state.total_cache_hash_size
|
|
1266
|
+
self.register_buffer(
|
|
1267
|
+
"cache_hash_size_cumsum",
|
|
1268
|
+
torch.tensor(
|
|
1269
|
+
cache_state.cache_hash_size_cumsum,
|
|
1270
|
+
device=self.current_device,
|
|
1271
|
+
dtype=torch.int64,
|
|
1272
|
+
),
|
|
1273
|
+
)
|
|
1274
|
+
self.register_buffer(
|
|
1275
|
+
"cache_index_table_map",
|
|
1276
|
+
torch.tensor(
|
|
1277
|
+
cache_state.cache_index_table_map,
|
|
1278
|
+
device=self.current_device,
|
|
1279
|
+
dtype=torch.int32,
|
|
1280
|
+
),
|
|
1281
|
+
)
|
|
1282
|
+
self.register_buffer(
|
|
1283
|
+
"lxu_cache_state",
|
|
1284
|
+
torch.zeros(
|
|
1285
|
+
cache_sets, ASSOC, device=self.current_device, dtype=torch.int64
|
|
1286
|
+
).fill_(-1),
|
|
1287
|
+
)
|
|
1288
|
+
self.register_buffer(
|
|
1289
|
+
"lxu_cache_weights",
|
|
1290
|
+
torch.zeros(
|
|
1291
|
+
cache_sets * ASSOC,
|
|
1292
|
+
self.max_D_cache,
|
|
1293
|
+
device=self.current_device,
|
|
1294
|
+
dtype=dtype,
|
|
1295
|
+
),
|
|
1296
|
+
)
|
|
1297
|
+
self.register_buffer(
|
|
1298
|
+
"lxu_state",
|
|
1299
|
+
# pyre-fixme[28]: Unexpected keyword argument `size`.
|
|
1300
|
+
torch.zeros(
|
|
1301
|
+
size=(self.total_cache_hash_size + 1,)
|
|
1302
|
+
if cache_algorithm == CacheAlgorithm.LFU
|
|
1303
|
+
else (cache_sets, ASSOC),
|
|
1304
|
+
device=self.current_device,
|
|
1305
|
+
dtype=torch.int64,
|
|
1306
|
+
),
|
|
1307
|
+
)
|
|
1308
|
+
self.register_buffer(
|
|
1309
|
+
"cache_miss_counter",
|
|
1310
|
+
torch.tensor([0, 0], device=self.current_device, dtype=torch.int64),
|
|
1311
|
+
)
|
|
1312
|
+
if cache_algorithm not in (CacheAlgorithm.LFU, CacheAlgorithm.LRU):
|
|
1313
|
+
raise ValueError(
|
|
1314
|
+
f"cache_algorithm must be {CacheAlgorithm.LRU} "
|
|
1315
|
+
f"or {CacheAlgorithm.LFU}"
|
|
1316
|
+
)
|
|
1317
|
+
|
|
1318
|
+
def reset_cache_states(self) -> None:
|
|
1319
|
+
# pyre-fixme[29]:
|
|
1320
|
+
# `Union[BoundMethod[typing.Callable(Tensor.numel)[[Named(self, Tensor)],
|
|
1321
|
+
# int], Tensor], Tensor, nn.Module]` is not a function.
|
|
1322
|
+
if not self.lxu_cache_weights.numel():
|
|
1323
|
+
return
|
|
1324
|
+
self.lxu_cache_state.fill_(-1)
|
|
1325
|
+
self.lxu_state.fill_(0)
|
|
1326
|
+
self.timestep = 1
|
|
1327
|
+
|
|
1328
|
+
|
|
1329
|
+
class DenseTableBatchedEmbeddingBagsCodegen(nn.Module):
|
|
1330
|
+
"""
|
|
1331
|
+
Table-batched version of nn.EmbeddingBag(sparse=False)
|
|
1332
|
+
"""
|
|
1333
|
+
|
|
1334
|
+
weights: Tensor
|
|
1335
|
+
weights_offsets: Tensor
|
|
1336
|
+
D_offsets: Tensor
|
|
1337
|
+
total_D: int
|
|
1338
|
+
max_D: int
|
|
1339
|
+
hash_size_cumsum: Tensor
|
|
1340
|
+
total_hash_size_bits: int
|
|
1341
|
+
embedding_specs: List[Tuple[int, int]]
|
|
1342
|
+
|
|
1343
|
+
def __init__(
|
|
1344
|
+
self,
|
|
1345
|
+
embedding_specs: List[Tuple[int, int]], # tuple of (rows, dims)
|
|
1346
|
+
feature_table_map: Optional[List[int]] = None, # [T]
|
|
1347
|
+
pooling_mode: PoolingMode = PoolingMode.SUM,
|
|
1348
|
+
use_cpu: bool = False,
|
|
1349
|
+
) -> None: # noqa C901 # tuple of (rows, dims,)
|
|
1350
|
+
super(DenseTableBatchedEmbeddingBagsCodegen, self).__init__()
|
|
1351
|
+
|
|
1352
|
+
self.pooling_mode = pooling_mode
|
|
1353
|
+
|
|
1354
|
+
self.use_cpu = use_cpu
|
|
1355
|
+
self.current_device: torch.device = (
|
|
1356
|
+
torch.device("cpu") if self.use_cpu else torch.cuda.current_device()
|
|
1357
|
+
)
|
|
1358
|
+
|
|
1359
|
+
self.embedding_specs = embedding_specs
|
|
1360
|
+
(rows, dims) = zip(*embedding_specs)
|
|
1361
|
+
T_ = len(self.embedding_specs)
|
|
1362
|
+
assert T_ > 0
|
|
1363
|
+
|
|
1364
|
+
feature_table_map = (
|
|
1365
|
+
feature_table_map if feature_table_map is not None else list(range(T_))
|
|
1366
|
+
)
|
|
1367
|
+
T = len(feature_table_map)
|
|
1368
|
+
assert T_ <= T
|
|
1369
|
+
D_offsets = [dims[t] for t in feature_table_map]
|
|
1370
|
+
D_offsets = [0] + list(accumulate(D_offsets))
|
|
1371
|
+
self.total_D = D_offsets[-1]
|
|
1372
|
+
self.max_D = max(dims)
|
|
1373
|
+
self.register_buffer(
|
|
1374
|
+
"D_offsets",
|
|
1375
|
+
torch.tensor(D_offsets, device=self.current_device, dtype=torch.int32),
|
|
1376
|
+
)
|
|
1377
|
+
assert self.D_offsets.numel() == T + 1
|
|
1378
|
+
|
|
1379
|
+
hash_size_cumsum = [0] + list(accumulate(rows))
|
|
1380
|
+
if hash_size_cumsum[-1] == 0:
|
|
1381
|
+
self.total_hash_size_bits: int = 0
|
|
1382
|
+
else:
|
|
1383
|
+
self.total_hash_size_bits: int = int(log2(float(hash_size_cumsum[-1])) + 1)
|
|
1384
|
+
# The last element is to easily access # of rows of each table by
|
|
1385
|
+
# hash_size_cumsum[t + 1] - hash_size_cumsum[t]
|
|
1386
|
+
hash_size_cumsum = [hash_size_cumsum[t] for t in feature_table_map] + [
|
|
1387
|
+
hash_size_cumsum[-1]
|
|
1388
|
+
]
|
|
1389
|
+
self.register_buffer(
|
|
1390
|
+
"hash_size_cumsum",
|
|
1391
|
+
torch.tensor(
|
|
1392
|
+
hash_size_cumsum, device=self.current_device, dtype=torch.int64
|
|
1393
|
+
),
|
|
1394
|
+
)
|
|
1395
|
+
weights_offsets = [0] + list(
|
|
1396
|
+
accumulate([row * dim for (row, dim) in embedding_specs])
|
|
1397
|
+
)
|
|
1398
|
+
self.weights = nn.Parameter(
|
|
1399
|
+
torch.randn(
|
|
1400
|
+
weights_offsets[-1],
|
|
1401
|
+
device=self.current_device,
|
|
1402
|
+
)
|
|
1403
|
+
)
|
|
1404
|
+
for feature in range(T):
|
|
1405
|
+
t = feature_table_map[feature]
|
|
1406
|
+
row, dim = embedding_specs[t]
|
|
1407
|
+
if (
|
|
1408
|
+
self.weights[weights_offsets[t] : weights_offsets[t + 1]].numel()
|
|
1409
|
+
!= row * dim
|
|
1410
|
+
):
|
|
1411
|
+
logging.info(
|
|
1412
|
+
f"row {row} dim {dim} feature {feature} t {t} {self.weights[weights_offsets[t] : weights_offsets[t + 1]].numel()}"
|
|
1413
|
+
)
|
|
1414
|
+
assert (
|
|
1415
|
+
self.weights[weights_offsets[t] : weights_offsets[t + 1]].numel()
|
|
1416
|
+
== row * dim
|
|
1417
|
+
)
|
|
1418
|
+
assert self.hash_size_cumsum[feature] == sum(
|
|
1419
|
+
row for (row, _) in embedding_specs[:t]
|
|
1420
|
+
)
|
|
1421
|
+
|
|
1422
|
+
self.weights_physical_offsets: List[int] = weights_offsets
|
|
1423
|
+
weights_offsets = [weights_offsets[t] for t in feature_table_map]
|
|
1424
|
+
self.register_buffer(
|
|
1425
|
+
"weights_offsets",
|
|
1426
|
+
torch.tensor(
|
|
1427
|
+
weights_offsets, device=self.current_device, dtype=torch.int64
|
|
1428
|
+
),
|
|
1429
|
+
)
|
|
1430
|
+
|
|
1431
|
+
def forward(
|
|
1432
|
+
self,
|
|
1433
|
+
indices: Tensor,
|
|
1434
|
+
offsets: Tensor,
|
|
1435
|
+
per_sample_weights: Optional[Tensor] = None,
|
|
1436
|
+
feature_requires_grad: Optional[Tensor] = None,
|
|
1437
|
+
) -> Tensor:
|
|
1438
|
+
(indices, offsets) = indices.long(), offsets.long()
|
|
1439
|
+
return torch.ops.fbgemm.dense_embedding_codegen_lookup_function(
|
|
1440
|
+
dev_weights=self.weights,
|
|
1441
|
+
weights_offsets=self.weights_offsets,
|
|
1442
|
+
D_offsets=self.D_offsets,
|
|
1443
|
+
total_D=self.total_D,
|
|
1444
|
+
max_D=self.max_D,
|
|
1445
|
+
hash_size_cumsum=self.hash_size_cumsum,
|
|
1446
|
+
total_hash_size_bits=self.total_hash_size_bits,
|
|
1447
|
+
indices=indices,
|
|
1448
|
+
offsets=offsets,
|
|
1449
|
+
pooling_mode=self.pooling_mode,
|
|
1450
|
+
indice_weights=per_sample_weights,
|
|
1451
|
+
feature_requires_grad=feature_requires_grad,
|
|
1452
|
+
)
|
|
1453
|
+
|
|
1454
|
+
@torch.jit.export
|
|
1455
|
+
def split_embedding_weights(self) -> List[Tensor]:
|
|
1456
|
+
"""
|
|
1457
|
+
Returns a list of weights, split by table
|
|
1458
|
+
"""
|
|
1459
|
+
splits = []
|
|
1460
|
+
for t, (rows, dim) in enumerate(self.embedding_specs):
|
|
1461
|
+
offset = self.weights_physical_offsets[t]
|
|
1462
|
+
splits.append(
|
|
1463
|
+
self.weights.detach()[offset : offset + rows * dim].view(rows, dim)
|
|
1464
|
+
)
|
|
1465
|
+
return splits
|
|
1466
|
+
|
|
1467
|
+
def init_embedding_weights_uniform(self, min_val: float, max_val: float) -> None:
|
|
1468
|
+
splits = self.split_embedding_weights()
|
|
1469
|
+
for param in splits:
|
|
1470
|
+
param.uniform_(min_val, max_val)
|
|
1471
|
+
|
|
1472
|
+
|
|
1473
|
+
def round_up(a: int, b: int) -> int:
|
|
1474
|
+
return int((a + b - 1) // b) * b
|
|
1475
|
+
|
|
1476
|
+
|
|
1477
|
+
def rounded_row_size_in_bytes(
|
|
1478
|
+
dim: int, weight_ty: SparseType, row_alignment: int
|
|
1479
|
+
) -> int:
|
|
1480
|
+
r = unpadded_row_size_in_bytes(dim, weight_ty)
|
|
1481
|
+
# align each row to 16-byte boundaries.
|
|
1482
|
+
return round_up(r, row_alignment)
|
|
1483
|
+
|
|
1484
|
+
|
|
1485
|
+
def unpadded_row_size_in_bytes(dim: int, weight_ty: SparseType) -> int:
|
|
1486
|
+
r = {
|
|
1487
|
+
SparseType.FP32.value: dim * 4,
|
|
1488
|
+
SparseType.FP16.value: dim * 2,
|
|
1489
|
+
SparseType.FP8.value: dim,
|
|
1490
|
+
SparseType.INT8.value: dim + 4,
|
|
1491
|
+
SparseType.INT4.value: dim // 2 + 4,
|
|
1492
|
+
SparseType.INT2.value: dim // 4 + 4,
|
|
1493
|
+
}[weight_ty.value]
|
|
1494
|
+
return r
|
|
1495
|
+
|
|
1496
|
+
|
|
1497
|
+
def align_to_cacheline(a: int) -> int:
|
|
1498
|
+
# align each table to 128b cache line boundary.
|
|
1499
|
+
return round_up(a, 128)
|
|
1500
|
+
|
|
1501
|
+
|
|
1502
|
+
def nbit_construct_split_state(
|
|
1503
|
+
embedding_specs: List[Tuple[str, int, int, SparseType, EmbeddingLocation]],
|
|
1504
|
+
cacheable: bool,
|
|
1505
|
+
row_alignment: int,
|
|
1506
|
+
) -> SplitState:
|
|
1507
|
+
placements = []
|
|
1508
|
+
offsets = []
|
|
1509
|
+
dev_size = 0
|
|
1510
|
+
host_size = 0
|
|
1511
|
+
uvm_size = 0
|
|
1512
|
+
for (_, num_embeddings, embedding_dim, weight_ty, location) in embedding_specs:
|
|
1513
|
+
embedding_dim = rounded_row_size_in_bytes(
|
|
1514
|
+
embedding_dim, weight_ty, row_alignment
|
|
1515
|
+
)
|
|
1516
|
+
state_size = align_to_cacheline(num_embeddings * embedding_dim)
|
|
1517
|
+
if location == EmbeddingLocation.HOST:
|
|
1518
|
+
placements.append(EmbeddingLocation.HOST)
|
|
1519
|
+
offsets.append(host_size)
|
|
1520
|
+
host_size += state_size
|
|
1521
|
+
elif location == EmbeddingLocation.DEVICE:
|
|
1522
|
+
placements.append(EmbeddingLocation.DEVICE)
|
|
1523
|
+
offsets.append(dev_size)
|
|
1524
|
+
dev_size += state_size
|
|
1525
|
+
else:
|
|
1526
|
+
if cacheable and location == EmbeddingLocation.MANAGED_CACHING:
|
|
1527
|
+
placements.append(EmbeddingLocation.MANAGED_CACHING)
|
|
1528
|
+
else:
|
|
1529
|
+
placements.append(EmbeddingLocation.MANAGED)
|
|
1530
|
+
offsets.append(uvm_size)
|
|
1531
|
+
uvm_size += state_size
|
|
1532
|
+
assert len(placements) == len(offsets)
|
|
1533
|
+
return SplitState(
|
|
1534
|
+
dev_size=dev_size,
|
|
1535
|
+
host_size=host_size,
|
|
1536
|
+
uvm_size=uvm_size,
|
|
1537
|
+
placements=placements,
|
|
1538
|
+
offsets=offsets,
|
|
1539
|
+
)
|
|
1540
|
+
|
|
1541
|
+
|
|
1542
|
+
class IntNBitTableBatchedEmbeddingBagsCodegen(nn.Module):
|
|
1543
|
+
"""
|
|
1544
|
+
Table-batched version of nn.EmbeddingBag(sparse=False)
|
|
1545
|
+
Inference version, with FP16/INT8/INT4/INT2 supports
|
|
1546
|
+
"""
|
|
1547
|
+
|
|
1548
|
+
embedding_specs: List[Tuple[str, int, int, SparseType, EmbeddingLocation]]
|
|
1549
|
+
record_cache_metrics: RecordCacheMetrics
|
|
1550
|
+
|
|
1551
|
+
def __init__(
|
|
1552
|
+
self,
|
|
1553
|
+
embedding_specs: List[
|
|
1554
|
+
Tuple[str, int, int, SparseType, EmbeddingLocation]
|
|
1555
|
+
], # tuple of (feature_names, rows, dims, SparseType, EmbeddingLocation/placement)
|
|
1556
|
+
feature_table_map: Optional[List[int]] = None, # [T]
|
|
1557
|
+
index_remapping: Optional[List[Tensor]] = None,
|
|
1558
|
+
pooling_mode: PoolingMode = PoolingMode.SUM,
|
|
1559
|
+
device: Optional[Union[str, int, torch.device]] = None,
|
|
1560
|
+
bounds_check_mode: BoundsCheckMode = BoundsCheckMode.WARNING,
|
|
1561
|
+
weight_lists: Optional[List[Tuple[Tensor, Tensor]]] = None,
|
|
1562
|
+
load_factor: float = 0.5,
|
|
1563
|
+
use_array_for_index_remapping: bool = True,
|
|
1564
|
+
output_dtype: SparseType = SparseType.FP16,
|
|
1565
|
+
cache_algorithm: CacheAlgorithm = CacheAlgorithm.LRU,
|
|
1566
|
+
cache_load_factor: float = 0.2,
|
|
1567
|
+
cache_sets: int = 0,
|
|
1568
|
+
cache_reserved_memory: float = 0.0,
|
|
1569
|
+
enforce_hbm: bool = False, # place all weights/momentums in HBM when using cache
|
|
1570
|
+
record_cache_metrics: Optional[RecordCacheMetrics] = None,
|
|
1571
|
+
row_alignment: Optional[int] = None,
|
|
1572
|
+
fp8_exponent_bits: Optional[int] = None,
|
|
1573
|
+
fp8_exponent_bias: Optional[int] = None,
|
|
1574
|
+
) -> None: # noqa C901 # tuple of (rows, dims,)
|
|
1575
|
+
super(IntNBitTableBatchedEmbeddingBagsCodegen, self).__init__()
|
|
1576
|
+
|
|
1577
|
+
if device is None:
|
|
1578
|
+
self.current_device: torch.device = torch.device(
|
|
1579
|
+
torch.cuda.current_device()
|
|
1580
|
+
)
|
|
1581
|
+
elif isinstance(device, torch.device):
|
|
1582
|
+
self.current_device = device
|
|
1583
|
+
else:
|
|
1584
|
+
# pyre-ignore [6]
|
|
1585
|
+
self.current_device = torch.device(device)
|
|
1586
|
+
self.use_cpu: bool = self.current_device.type == "cpu"
|
|
1587
|
+
|
|
1588
|
+
self.pooling_mode = pooling_mode
|
|
1589
|
+
self.bounds_check_mode_int: int = bounds_check_mode.value
|
|
1590
|
+
self.embedding_specs = embedding_specs
|
|
1591
|
+
self.output_dtype: int = output_dtype.as_int()
|
|
1592
|
+
# (feature_names, rows, dims, weights_tys, locations) = zip(*embedding_specs)
|
|
1593
|
+
# Pyre workaround
|
|
1594
|
+
self.feature_names: List[str] = [e[0] for e in embedding_specs]
|
|
1595
|
+
rows: List[int] = [e[1] for e in embedding_specs]
|
|
1596
|
+
dims: List[int] = [e[2] for e in embedding_specs]
|
|
1597
|
+
weights_tys: List[SparseType] = [e[3] for e in embedding_specs]
|
|
1598
|
+
locations: List[EmbeddingLocation] = [e[4] for e in embedding_specs]
|
|
1599
|
+
|
|
1600
|
+
if row_alignment is None:
|
|
1601
|
+
self.row_alignment: int = 1 if self.use_cpu else 16
|
|
1602
|
+
else:
|
|
1603
|
+
self.row_alignment = row_alignment
|
|
1604
|
+
|
|
1605
|
+
if record_cache_metrics is not None:
|
|
1606
|
+
self.record_cache_metrics = record_cache_metrics
|
|
1607
|
+
else:
|
|
1608
|
+
self.record_cache_metrics = RecordCacheMetrics(False, False)
|
|
1609
|
+
|
|
1610
|
+
# mixed D is not supported by no bag kernels
|
|
1611
|
+
mixed_D = not all(d == dims[0] for d in dims)
|
|
1612
|
+
if mixed_D:
|
|
1613
|
+
assert (
|
|
1614
|
+
self.pooling_mode != PoolingMode.NONE
|
|
1615
|
+
), "Mixed dimension tables are only supported for pooling tables."
|
|
1616
|
+
|
|
1617
|
+
assert not self.use_cpu or all(
|
|
1618
|
+
loc == EmbeddingLocation.HOST for loc in locations
|
|
1619
|
+
), "CPU device requires EmbeddingLocation.HOST for location!"
|
|
1620
|
+
assert self.use_cpu or all(
|
|
1621
|
+
loc != EmbeddingLocation.HOST for loc in locations
|
|
1622
|
+
), "EmbeddingLocation.HOST doesn't work for CUDA device!"
|
|
1623
|
+
|
|
1624
|
+
T_ = len(self.embedding_specs)
|
|
1625
|
+
assert T_ > 0
|
|
1626
|
+
|
|
1627
|
+
self.feature_table_map: List[int] = (
|
|
1628
|
+
feature_table_map if feature_table_map is not None else list(range(T_))
|
|
1629
|
+
)
|
|
1630
|
+
T = len(self.feature_table_map)
|
|
1631
|
+
assert T_ <= T
|
|
1632
|
+
|
|
1633
|
+
table_has_feature = [False] * T_
|
|
1634
|
+
for t in self.feature_table_map:
|
|
1635
|
+
table_has_feature[t] = True
|
|
1636
|
+
assert all(table_has_feature), "Each table must have at least one feature!"
|
|
1637
|
+
D_offsets = [dims[t] for t in self.feature_table_map]
|
|
1638
|
+
D_offsets = [0] + list(accumulate(D_offsets))
|
|
1639
|
+
self.total_D: int = D_offsets[-1]
|
|
1640
|
+
for dim, weight_ty in zip(dims, weights_tys):
|
|
1641
|
+
if not weight_ty.is_float():
|
|
1642
|
+
assert (
|
|
1643
|
+
dim % (8 / weight_ty.bit_rate()) == 0
|
|
1644
|
+
), "For quantized types we need to at least pack at byte granularity"
|
|
1645
|
+
|
|
1646
|
+
def max_ty_D(ty: SparseType) -> int:
|
|
1647
|
+
return max(
|
|
1648
|
+
[dim for dim, weight_ty in zip(dims, weights_tys) if weight_ty == ty],
|
|
1649
|
+
default=0,
|
|
1650
|
+
)
|
|
1651
|
+
|
|
1652
|
+
self.max_int2_D: int = max_ty_D(SparseType.INT2)
|
|
1653
|
+
self.max_int4_D: int = max_ty_D(SparseType.INT4)
|
|
1654
|
+
self.max_int8_D: int = max_ty_D(SparseType.INT8)
|
|
1655
|
+
self.max_float8_D: int = max_ty_D(SparseType.FP8)
|
|
1656
|
+
self.max_float16_D: int = max_ty_D(SparseType.FP16)
|
|
1657
|
+
self.max_float32_D: int = max_ty_D(SparseType.FP32)
|
|
1658
|
+
|
|
1659
|
+
self.register_buffer(
|
|
1660
|
+
"D_offsets",
|
|
1661
|
+
torch.tensor(D_offsets, device=self.current_device, dtype=torch.int32),
|
|
1662
|
+
)
|
|
1663
|
+
assert self.D_offsets.numel() == T + 1
|
|
1664
|
+
|
|
1665
|
+
self.register_buffer(
|
|
1666
|
+
"rows_per_table",
|
|
1667
|
+
torch.tensor(
|
|
1668
|
+
[rows[t] for t in self.feature_table_map],
|
|
1669
|
+
device=self.current_device,
|
|
1670
|
+
dtype=torch.int64,
|
|
1671
|
+
),
|
|
1672
|
+
)
|
|
1673
|
+
self.register_buffer(
|
|
1674
|
+
"bounds_check_warning",
|
|
1675
|
+
torch.tensor([0], device=self.current_device, dtype=torch.int64),
|
|
1676
|
+
)
|
|
1677
|
+
|
|
1678
|
+
weights_tys_int = [weights_tys[t].as_int() for t in self.feature_table_map]
|
|
1679
|
+
self.register_buffer(
|
|
1680
|
+
"weights_tys",
|
|
1681
|
+
torch.tensor(
|
|
1682
|
+
weights_tys_int, device=self.current_device, dtype=torch.uint8
|
|
1683
|
+
),
|
|
1684
|
+
)
|
|
1685
|
+
self.weight_initialized: bool = False
|
|
1686
|
+
|
|
1687
|
+
self.weights_dev: torch.Tensor = torch.zeros(
|
|
1688
|
+
0,
|
|
1689
|
+
device=self.current_device,
|
|
1690
|
+
dtype=torch.uint8,
|
|
1691
|
+
)
|
|
1692
|
+
|
|
1693
|
+
self.weights_host: torch.Tensor = torch.zeros(
|
|
1694
|
+
0, device=self.current_device, dtype=torch.uint8
|
|
1695
|
+
)
|
|
1696
|
+
|
|
1697
|
+
self.weights_uvm: torch.Tensor = torch.empty(
|
|
1698
|
+
0, device=self.current_device, dtype=torch.uint8
|
|
1699
|
+
)
|
|
1700
|
+
|
|
1701
|
+
cached_dims = [
|
|
1702
|
+
rounded_row_size_in_bytes(embedding_spec[2], embedding_spec[3], 16)
|
|
1703
|
+
for embedding_spec in self.embedding_specs
|
|
1704
|
+
if embedding_spec[4] == EmbeddingLocation.MANAGED_CACHING
|
|
1705
|
+
]
|
|
1706
|
+
self.max_D_cache: int = max(cached_dims) if len(cached_dims) > 0 else 0
|
|
1707
|
+
|
|
1708
|
+
weight_split: SplitState = nbit_construct_split_state(
|
|
1709
|
+
self.embedding_specs, cacheable=True, row_alignment=self.row_alignment
|
|
1710
|
+
)
|
|
1711
|
+
|
|
1712
|
+
self.weights_physical_placements: List[int] = [
|
|
1713
|
+
t.value for t in weight_split.placements
|
|
1714
|
+
]
|
|
1715
|
+
self.weights_physical_offsets: List[int] = weight_split.offsets
|
|
1716
|
+
self.host_size: int = weight_split.host_size
|
|
1717
|
+
self.dev_size: int = weight_split.dev_size
|
|
1718
|
+
self.uvm_size: int = weight_split.uvm_size
|
|
1719
|
+
self.enforce_hbm: bool = enforce_hbm
|
|
1720
|
+
|
|
1721
|
+
# Assign weights after weights and weights_offsets are initialized.
|
|
1722
|
+
if weight_lists:
|
|
1723
|
+
self._apply_split(
|
|
1724
|
+
self.dev_size,
|
|
1725
|
+
self.host_size,
|
|
1726
|
+
self.uvm_size,
|
|
1727
|
+
self.weights_physical_placements,
|
|
1728
|
+
self.weights_physical_offsets,
|
|
1729
|
+
self.enforce_hbm,
|
|
1730
|
+
)
|
|
1731
|
+
self.assign_embedding_weights(weight_lists) # type: ignore
|
|
1732
|
+
|
|
1733
|
+
# Handle index remapping for embedding pruning.
|
|
1734
|
+
self.register_buffer(
|
|
1735
|
+
"index_remappings_array_offsets",
|
|
1736
|
+
torch.empty(0, device=self.current_device, dtype=torch.int64),
|
|
1737
|
+
)
|
|
1738
|
+
self.register_buffer(
|
|
1739
|
+
"index_remappings_array",
|
|
1740
|
+
torch.empty(0, device=self.current_device, dtype=torch.int32),
|
|
1741
|
+
)
|
|
1742
|
+
self.register_buffer(
|
|
1743
|
+
"index_remapping_hash_table_offsets",
|
|
1744
|
+
torch.empty(0, device=self.current_device, dtype=torch.int64),
|
|
1745
|
+
)
|
|
1746
|
+
self.register_buffer(
|
|
1747
|
+
"index_remapping_hash_table",
|
|
1748
|
+
torch.empty(0, device=self.current_device, dtype=torch.int32),
|
|
1749
|
+
)
|
|
1750
|
+
# pyre-fixme[4]: Attribute must be annotated.
|
|
1751
|
+
self.index_remapping_hash_table_cpu = None
|
|
1752
|
+
|
|
1753
|
+
if index_remapping:
|
|
1754
|
+
self.set_index_remappings(
|
|
1755
|
+
index_remapping, load_factor, use_array_for_index_remapping
|
|
1756
|
+
)
|
|
1757
|
+
|
|
1758
|
+
# Currently only support cache_precision == embedding_precision.
|
|
1759
|
+
# Both are represented as uint8_t
|
|
1760
|
+
cache_state = construct_cache_state(rows, locations, self.feature_table_map)
|
|
1761
|
+
|
|
1762
|
+
if self.record_cache_metrics.record_tablewise_cache_miss:
|
|
1763
|
+
num_tables = len(cache_state.cache_hash_size_cumsum) - 1
|
|
1764
|
+
self.register_buffer(
|
|
1765
|
+
"table_wise_cache_miss",
|
|
1766
|
+
torch.zeros(
|
|
1767
|
+
num_tables,
|
|
1768
|
+
device=self.current_device,
|
|
1769
|
+
dtype=torch.int64,
|
|
1770
|
+
),
|
|
1771
|
+
)
|
|
1772
|
+
# NOTE: make TorchScript work!
|
|
1773
|
+
else:
|
|
1774
|
+
self.register_buffer(
|
|
1775
|
+
"table_wise_cache_miss",
|
|
1776
|
+
torch.zeros(
|
|
1777
|
+
0,
|
|
1778
|
+
device=self.current_device,
|
|
1779
|
+
dtype=torch.int64,
|
|
1780
|
+
),
|
|
1781
|
+
)
|
|
1782
|
+
|
|
1783
|
+
self._apply_cache_state(
|
|
1784
|
+
cache_state,
|
|
1785
|
+
cache_algorithm,
|
|
1786
|
+
cache_load_factor,
|
|
1787
|
+
cache_sets,
|
|
1788
|
+
cache_reserved_memory,
|
|
1789
|
+
)
|
|
1790
|
+
|
|
1791
|
+
if self.max_float8_D > 0:
|
|
1792
|
+
default_config = SparseType.FP8.default_config()
|
|
1793
|
+
self.fp8_exponent_bits: int = (
|
|
1794
|
+
default_config.get("exponent_bits")
|
|
1795
|
+
if fp8_exponent_bits is None
|
|
1796
|
+
else fp8_exponent_bits
|
|
1797
|
+
)
|
|
1798
|
+
self.fp8_exponent_bias: int = (
|
|
1799
|
+
default_config.get("exponent_bias")
|
|
1800
|
+
if fp8_exponent_bias is None
|
|
1801
|
+
else fp8_exponent_bias
|
|
1802
|
+
)
|
|
1803
|
+
else:
|
|
1804
|
+
self.fp8_exponent_bits = -1
|
|
1805
|
+
self.fp8_exponent_bias = -1
|
|
1806
|
+
|
|
1807
|
+
@torch.jit.export
|
|
1808
|
+
def get_cache_miss_counter(self) -> Tensor:
|
|
1809
|
+
# cache_miss_counter[0]: cache_miss_forward_count which records the total number of forwards which has at least one cache miss
|
|
1810
|
+
# cache_miss_counter[1]: unique_cache_miss_count which records to total number of unique (dedup) cache misses
|
|
1811
|
+
|
|
1812
|
+
# pyre-fixme[7]: Expected `Tensor` but got `typing.Union[Tensor,
|
|
1813
|
+
# nn.Module]`.
|
|
1814
|
+
return self.cache_miss_counter
|
|
1815
|
+
|
|
1816
|
+
@torch.jit.export
|
|
1817
|
+
def get_table_wise_cache_miss(self) -> Tensor:
|
|
1818
|
+
# table_wise_cache_miss contains all the cache miss count for each table in this embedding table object:
|
|
1819
|
+
|
|
1820
|
+
return self.table_wise_cache_miss
|
|
1821
|
+
|
|
1822
|
+
@torch.jit.export
|
|
1823
|
+
def prefetch(self, indices: Tensor, offsets: Tensor) -> None:
|
|
1824
|
+
self.timestep_counter.increment()
|
|
1825
|
+
self.timestep_prefetch_size.increment()
|
|
1826
|
+
# pyre-fixme[29]:
|
|
1827
|
+
# `Union[BoundMethod[typing.Callable(Tensor.numel)[[Named(self, Tensor)],
|
|
1828
|
+
# int], Tensor], Tensor, nn.Module]` is not a function.
|
|
1829
|
+
if not self.lxu_cache_weights.numel():
|
|
1830
|
+
return
|
|
1831
|
+
|
|
1832
|
+
linear_cache_indices = torch.ops.fbgemm.linearize_cache_indices(
|
|
1833
|
+
self.cache_hash_size_cumsum,
|
|
1834
|
+
indices,
|
|
1835
|
+
offsets,
|
|
1836
|
+
)
|
|
1837
|
+
|
|
1838
|
+
if (
|
|
1839
|
+
self.record_cache_metrics.record_cache_miss_counter
|
|
1840
|
+
or self.record_cache_metrics.record_tablewise_cache_miss
|
|
1841
|
+
):
|
|
1842
|
+
lxu_cache_locations = torch.ops.fbgemm.lxu_cache_lookup(
|
|
1843
|
+
linear_cache_indices,
|
|
1844
|
+
self.lxu_cache_state,
|
|
1845
|
+
self.total_cache_hash_size,
|
|
1846
|
+
)
|
|
1847
|
+
if self.record_cache_metrics.record_cache_miss_counter:
|
|
1848
|
+
self._update_cache_miss_counter(
|
|
1849
|
+
lxu_cache_locations, linear_cache_indices
|
|
1850
|
+
)
|
|
1851
|
+
if self.record_cache_metrics.record_tablewise_cache_miss:
|
|
1852
|
+
self._update_tablewise_cache_miss(
|
|
1853
|
+
lxu_cache_locations, linear_cache_indices, offsets
|
|
1854
|
+
)
|
|
1855
|
+
|
|
1856
|
+
if self.cache_algorithm == CacheAlgorithm.LRU:
|
|
1857
|
+
torch.ops.fbgemm.lru_cache_populate_byte(
|
|
1858
|
+
self.weights_uvm,
|
|
1859
|
+
self.cache_hash_size_cumsum,
|
|
1860
|
+
self.total_cache_hash_size,
|
|
1861
|
+
self.cache_index_table_map,
|
|
1862
|
+
self.weights_offsets,
|
|
1863
|
+
self.weights_tys,
|
|
1864
|
+
self.D_offsets,
|
|
1865
|
+
linear_cache_indices,
|
|
1866
|
+
self.lxu_cache_state,
|
|
1867
|
+
self.lxu_cache_weights,
|
|
1868
|
+
self.timestep_counter.get(),
|
|
1869
|
+
self.lxu_state,
|
|
1870
|
+
)
|
|
1871
|
+
elif self.cache_algorithm == CacheAlgorithm.LFU:
|
|
1872
|
+
torch.ops.fbgemm.lfu_cache_populate_byte(
|
|
1873
|
+
self.weights_uvm,
|
|
1874
|
+
self.cache_hash_size_cumsum,
|
|
1875
|
+
self.total_cache_hash_size,
|
|
1876
|
+
self.cache_index_table_map,
|
|
1877
|
+
self.weights_offsets,
|
|
1878
|
+
self.weights_tys,
|
|
1879
|
+
self.D_offsets,
|
|
1880
|
+
linear_cache_indices,
|
|
1881
|
+
self.lxu_cache_state,
|
|
1882
|
+
self.lxu_cache_weights,
|
|
1883
|
+
self.lxu_state,
|
|
1884
|
+
)
|
|
1885
|
+
|
|
1886
|
+
assert (
|
|
1887
|
+
self.lxu_cache_locations_list.size() < self.max_prefetch_depth
|
|
1888
|
+
), f"self.lxu_cache_locations_list has grown to size: {self.lxu_cache_locations_list.size()}, this exceeds the maximum: {self.max_prefetch_depth}. This probably indicates an error in logic where prefetch() is being called more frequently than forward()"
|
|
1889
|
+
self.lxu_cache_locations_list.push(
|
|
1890
|
+
torch.ops.fbgemm.lxu_cache_lookup(
|
|
1891
|
+
linear_cache_indices,
|
|
1892
|
+
self.lxu_cache_state,
|
|
1893
|
+
self.total_cache_hash_size,
|
|
1894
|
+
)
|
|
1895
|
+
)
|
|
1896
|
+
|
|
1897
|
+
def _update_cache_miss_counter(
|
|
1898
|
+
self,
|
|
1899
|
+
lxu_cache_locations: Tensor,
|
|
1900
|
+
linear_cache_indices: Tensor,
|
|
1901
|
+
) -> None:
|
|
1902
|
+
CACHE_MISS = torch.tensor([-1], device=self.current_device, dtype=torch.int32)
|
|
1903
|
+
CACHE_HIT = torch.tensor([-2], device=self.current_device, dtype=torch.int32)
|
|
1904
|
+
|
|
1905
|
+
cache_missed_locations = torch.where(
|
|
1906
|
+
lxu_cache_locations == CACHE_MISS, linear_cache_indices, CACHE_HIT
|
|
1907
|
+
)
|
|
1908
|
+
unique_ids_list = torch.unique(cache_missed_locations)
|
|
1909
|
+
unique_ids_count_list = torch.where(unique_ids_list == CACHE_HIT, 0, 1)
|
|
1910
|
+
|
|
1911
|
+
miss_count = torch.sum(unique_ids_count_list)
|
|
1912
|
+
|
|
1913
|
+
# pyre-fixme[29]:
|
|
1914
|
+
# `Union[BoundMethod[typing.Callable(Tensor.__getitem__)[[Named(self,
|
|
1915
|
+
# Tensor), Named(item, typing.Any)], typing.Any], Tensor], Tensor,
|
|
1916
|
+
# nn.Module]` is not a function.
|
|
1917
|
+
self.cache_miss_counter[0] += (miss_count > 0).to(torch.int64)
|
|
1918
|
+
|
|
1919
|
+
# pyre-fixme[29]:
|
|
1920
|
+
# `Union[BoundMethod[typing.Callable(Tensor.__getitem__)[[Named(self,
|
|
1921
|
+
# Tensor), Named(item, typing.Any)], typing.Any], Tensor], Tensor,
|
|
1922
|
+
# nn.Module]` is not a function.
|
|
1923
|
+
self.cache_miss_counter[1] += miss_count
|
|
1924
|
+
|
|
1925
|
+
def _update_tablewise_cache_miss(
|
|
1926
|
+
self,
|
|
1927
|
+
lxu_cache_locations: Tensor,
|
|
1928
|
+
linear_cache_indices: Tensor,
|
|
1929
|
+
offsets: Tensor,
|
|
1930
|
+
) -> None:
|
|
1931
|
+
CACHE_MISS = torch.tensor([-1], device=self.current_device, dtype=torch.int32)
|
|
1932
|
+
CACHE_HIT = torch.tensor([-2], device=self.current_device, dtype=torch.int32)
|
|
1933
|
+
|
|
1934
|
+
# pyre-ignore[6]:
|
|
1935
|
+
# Incompatible parameter type [6]: Expected `typing.Sized` for 1st
|
|
1936
|
+
# positional only parameter to call `len` but got `typing.Union[Tensor, nn.Module]`.
|
|
1937
|
+
num_tables = len(self.cache_hash_size_cumsum) - 1
|
|
1938
|
+
num_offsets_per_table = (len(offsets) - 1) // num_tables
|
|
1939
|
+
cache_missed_locations = torch.where(
|
|
1940
|
+
lxu_cache_locations == CACHE_MISS, linear_cache_indices, CACHE_HIT
|
|
1941
|
+
)
|
|
1942
|
+
|
|
1943
|
+
for i in range(num_tables):
|
|
1944
|
+
start = offsets[i * num_offsets_per_table]
|
|
1945
|
+
end = offsets[(i + 1) * num_offsets_per_table]
|
|
1946
|
+
|
|
1947
|
+
current_cache_missed_locations = cache_missed_locations[start:end]
|
|
1948
|
+
unique_ids_list = torch.unique(current_cache_missed_locations)
|
|
1949
|
+
unique_ids_count_list = torch.where(unique_ids_list == CACHE_HIT, 0, 1)
|
|
1950
|
+
|
|
1951
|
+
miss_count = torch.sum(unique_ids_count_list)
|
|
1952
|
+
|
|
1953
|
+
self.table_wise_cache_miss[i] += miss_count
|
|
1954
|
+
|
|
1955
|
+
def forward(
|
|
1956
|
+
self,
|
|
1957
|
+
indices: Tensor,
|
|
1958
|
+
offsets: Tensor,
|
|
1959
|
+
per_sample_weights: Optional[Tensor] = None,
|
|
1960
|
+
) -> Tensor:
|
|
1961
|
+
if self.timestep_prefetch_size.get() <= 0:
|
|
1962
|
+
self.prefetch(indices, offsets)
|
|
1963
|
+
self.timestep_prefetch_size.decrement()
|
|
1964
|
+
|
|
1965
|
+
lxu_cache_locations = self.lxu_cache_locations_list.pop()
|
|
1966
|
+
|
|
1967
|
+
assert (
|
|
1968
|
+
self.weight_initialized
|
|
1969
|
+
), "weight needs to be initialized before forward function"
|
|
1970
|
+
if self.index_remapping_hash_table_cpu is not None:
|
|
1971
|
+
indices = self.index_remapping_hash_table_cpu.lookup(indices, offsets)
|
|
1972
|
+
elif self.index_remapping_hash_table.numel() > 0:
|
|
1973
|
+
# Convert from raw indices to pruned indices
|
|
1974
|
+
indices = torch.ops.fbgemm.pruned_hashmap_lookup(
|
|
1975
|
+
indices,
|
|
1976
|
+
offsets,
|
|
1977
|
+
self.index_remapping_hash_table,
|
|
1978
|
+
self.index_remapping_hash_table_offsets,
|
|
1979
|
+
)
|
|
1980
|
+
elif self.index_remappings_array.numel() > 0:
|
|
1981
|
+
indices = torch.ops.fbgemm.pruned_array_lookup(
|
|
1982
|
+
indices,
|
|
1983
|
+
offsets,
|
|
1984
|
+
self.index_remappings_array,
|
|
1985
|
+
self.index_remappings_array_offsets,
|
|
1986
|
+
)
|
|
1987
|
+
|
|
1988
|
+
# We cast to int as a TorchScript workaround.
|
|
1989
|
+
if self.bounds_check_mode_int != BoundsCheckMode.NONE.value:
|
|
1990
|
+
torch.ops.fbgemm.bounds_check_indices(
|
|
1991
|
+
self.rows_per_table,
|
|
1992
|
+
indices,
|
|
1993
|
+
offsets,
|
|
1994
|
+
self.bounds_check_mode_int,
|
|
1995
|
+
self.bounds_check_warning,
|
|
1996
|
+
per_sample_weights,
|
|
1997
|
+
)
|
|
1998
|
+
# Note: CPU and CUDA ops use the same interface to facilitate JIT IR
|
|
1999
|
+
# generation for CUDA/CPU. For CPU op, we don't need weights_uvm and
|
|
2000
|
+
# weights_placements
|
|
2001
|
+
return torch.ops.fbgemm.int_nbit_split_embedding_codegen_lookup_function(
|
|
2002
|
+
dev_weights=self.weights_host if self.host_size > 0 else self.weights_dev,
|
|
2003
|
+
uvm_weights=self.weights_uvm,
|
|
2004
|
+
weights_placements=self.weights_placements,
|
|
2005
|
+
weights_offsets=self.weights_offsets,
|
|
2006
|
+
weights_tys=self.weights_tys,
|
|
2007
|
+
D_offsets=self.D_offsets,
|
|
2008
|
+
total_D=self.total_D,
|
|
2009
|
+
max_int2_D=self.max_int2_D,
|
|
2010
|
+
max_int4_D=self.max_int4_D,
|
|
2011
|
+
max_int8_D=self.max_int8_D,
|
|
2012
|
+
max_float16_D=self.max_float16_D,
|
|
2013
|
+
max_float32_D=self.max_float32_D,
|
|
2014
|
+
indices=indices,
|
|
2015
|
+
offsets=offsets,
|
|
2016
|
+
pooling_mode=self.pooling_mode,
|
|
2017
|
+
indice_weights=per_sample_weights,
|
|
2018
|
+
output_dtype=self.output_dtype,
|
|
2019
|
+
lxu_cache_weights=self.lxu_cache_weights,
|
|
2020
|
+
lxu_cache_locations=lxu_cache_locations,
|
|
2021
|
+
row_alignment=self.row_alignment,
|
|
2022
|
+
max_float8_D=self.max_float8_D,
|
|
2023
|
+
fp8_exponent_bits=self.fp8_exponent_bits,
|
|
2024
|
+
fp8_exponent_bias=self.fp8_exponent_bias,
|
|
2025
|
+
)
|
|
2026
|
+
|
|
2027
|
+
def _apply_split(
|
|
2028
|
+
self,
|
|
2029
|
+
dev_size: int,
|
|
2030
|
+
host_size: int,
|
|
2031
|
+
uvm_size: int,
|
|
2032
|
+
placements: List[int],
|
|
2033
|
+
offsets: List[int],
|
|
2034
|
+
enforce_hbm: bool,
|
|
2035
|
+
) -> None:
|
|
2036
|
+
assert not self.weight_initialized, "Weights have already been initialized."
|
|
2037
|
+
self.weight_initialized = True
|
|
2038
|
+
self.weights_physical_placements = placements
|
|
2039
|
+
self.weights_physical_offsets = offsets
|
|
2040
|
+
|
|
2041
|
+
self.host_size = host_size
|
|
2042
|
+
self.dev_size = dev_size
|
|
2043
|
+
self.uvm_size = uvm_size
|
|
2044
|
+
|
|
2045
|
+
offsets = [offsets[t] for t in self.feature_table_map]
|
|
2046
|
+
placements = [placements[t] for t in self.feature_table_map]
|
|
2047
|
+
self.weights_offsets = torch.tensor(
|
|
2048
|
+
offsets, device=self.current_device, dtype=torch.int64
|
|
2049
|
+
)
|
|
2050
|
+
self.weights_placements = torch.tensor(
|
|
2051
|
+
placements, device=self.current_device, dtype=torch.int32
|
|
2052
|
+
)
|
|
2053
|
+
|
|
2054
|
+
if dev_size > 0:
|
|
2055
|
+
self.weights_dev = torch.zeros(
|
|
2056
|
+
dev_size,
|
|
2057
|
+
device=self.current_device,
|
|
2058
|
+
dtype=torch.uint8,
|
|
2059
|
+
)
|
|
2060
|
+
|
|
2061
|
+
if host_size > 0:
|
|
2062
|
+
self.weights_host = torch.zeros(
|
|
2063
|
+
host_size, device=self.current_device, dtype=torch.uint8
|
|
2064
|
+
)
|
|
2065
|
+
|
|
2066
|
+
if uvm_size > 0:
|
|
2067
|
+
assert not self.use_cpu
|
|
2068
|
+
if enforce_hbm:
|
|
2069
|
+
logging.info("Enforce hbm for the cache location")
|
|
2070
|
+
self.weights_uvm = torch.zeros(
|
|
2071
|
+
uvm_size,
|
|
2072
|
+
device=self.current_device,
|
|
2073
|
+
dtype=torch.uint8,
|
|
2074
|
+
)
|
|
2075
|
+
else:
|
|
2076
|
+
self.weights_uvm = torch.zeros(
|
|
2077
|
+
uvm_size,
|
|
2078
|
+
out=torch.ops.fbgemm.new_managed_tensor(
|
|
2079
|
+
torch.zeros(1, device=self.D_offsets.device, dtype=torch.uint8),
|
|
2080
|
+
[uvm_size],
|
|
2081
|
+
),
|
|
2082
|
+
)
|
|
2083
|
+
|
|
2084
|
+
def _apply_cache_state(
|
|
2085
|
+
self,
|
|
2086
|
+
cache_state: CacheState,
|
|
2087
|
+
cache_algorithm: CacheAlgorithm,
|
|
2088
|
+
cache_load_factor: float,
|
|
2089
|
+
cache_sets: int,
|
|
2090
|
+
cache_reserved_memory: float,
|
|
2091
|
+
) -> None:
|
|
2092
|
+
self.cache_algorithm = cache_algorithm
|
|
2093
|
+
self.timestep_counter = torch.classes.fbgemm.AtomicCounter()
|
|
2094
|
+
self.timestep_prefetch_size = torch.classes.fbgemm.AtomicCounter()
|
|
2095
|
+
|
|
2096
|
+
self.max_prefetch_depth = MAX_PREFETCH_DEPTH
|
|
2097
|
+
|
|
2098
|
+
if self.current_device.type == "meta":
|
|
2099
|
+
# To reslove "Cannot copy out of meta tensor; no data!" error
|
|
2100
|
+
lxu_cache_locations_empty = torch.empty(0, dtype=torch.int32).fill_(-1)
|
|
2101
|
+
else:
|
|
2102
|
+
lxu_cache_locations_empty = torch.empty(
|
|
2103
|
+
0, device=self.current_device, dtype=torch.int32
|
|
2104
|
+
).fill_(-1)
|
|
2105
|
+
self.lxu_cache_locations_list = torch.classes.fbgemm.TensorQueue(
|
|
2106
|
+
lxu_cache_locations_empty
|
|
2107
|
+
)
|
|
2108
|
+
|
|
2109
|
+
# NOTE: no cache for CPU mode!
|
|
2110
|
+
if cache_state.total_cache_hash_size == 0 or self.use_cpu:
|
|
2111
|
+
self.register_buffer(
|
|
2112
|
+
"lxu_cache_weights",
|
|
2113
|
+
torch.zeros(0, 0, device=self.current_device, dtype=torch.uint8),
|
|
2114
|
+
)
|
|
2115
|
+
# NOTE: make TorchScript work!
|
|
2116
|
+
self.register_buffer(
|
|
2117
|
+
"cache_hash_size_cumsum",
|
|
2118
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
2119
|
+
persistent=False,
|
|
2120
|
+
)
|
|
2121
|
+
self.register_buffer(
|
|
2122
|
+
"total_cache_hash_size",
|
|
2123
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
2124
|
+
persistent=False,
|
|
2125
|
+
)
|
|
2126
|
+
self.register_buffer(
|
|
2127
|
+
"cache_index_table_map",
|
|
2128
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
2129
|
+
persistent=False,
|
|
2130
|
+
)
|
|
2131
|
+
self.register_buffer(
|
|
2132
|
+
"lxu_cache_state",
|
|
2133
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
2134
|
+
persistent=False,
|
|
2135
|
+
)
|
|
2136
|
+
self.register_buffer(
|
|
2137
|
+
"lxu_state",
|
|
2138
|
+
torch.zeros(1, dtype=torch.int64, device=self.current_device),
|
|
2139
|
+
persistent=False,
|
|
2140
|
+
)
|
|
2141
|
+
self.register_buffer(
|
|
2142
|
+
"cache_miss_counter",
|
|
2143
|
+
torch.tensor([0, 0], dtype=torch.int64),
|
|
2144
|
+
persistent=False,
|
|
2145
|
+
)
|
|
2146
|
+
return
|
|
2147
|
+
|
|
2148
|
+
assert cache_load_factor > 0
|
|
2149
|
+
if cache_sets <= 0:
|
|
2150
|
+
total_memory = torch.cuda.get_device_properties(
|
|
2151
|
+
self.current_device
|
|
2152
|
+
).total_memory
|
|
2153
|
+
free_memory = (
|
|
2154
|
+
total_memory
|
|
2155
|
+
- torch.cuda.memory_reserved(self.current_device)
|
|
2156
|
+
- int(cache_reserved_memory)
|
|
2157
|
+
)
|
|
2158
|
+
assert free_memory > 0
|
|
2159
|
+
cache_sets = (
|
|
2160
|
+
int(cache_state.total_cache_hash_size * cache_load_factor) + ASSOC - 1
|
|
2161
|
+
) // ASSOC
|
|
2162
|
+
# Note that element_size has been included in max_D_cache (in Bytes)
|
|
2163
|
+
cache_size = cache_sets * ASSOC * self.max_D_cache
|
|
2164
|
+
if cache_size > free_memory:
|
|
2165
|
+
cache_sets = (
|
|
2166
|
+
int(1.0 * free_memory / self.max_D_cache) + ASSOC - 1
|
|
2167
|
+
) // ASSOC
|
|
2168
|
+
cache_sets = 1 if cache_sets == 0 else cache_sets
|
|
2169
|
+
cache_load_factor = (
|
|
2170
|
+
1.0 * cache_sets * ASSOC / int(cache_state.total_cache_hash_size)
|
|
2171
|
+
)
|
|
2172
|
+
assert cache_sets > 0
|
|
2173
|
+
if cache_algorithm == CacheAlgorithm.LFU:
|
|
2174
|
+
assert cache_sets < 2**24 - 1
|
|
2175
|
+
cache_size = cache_sets * ASSOC * self.max_D_cache
|
|
2176
|
+
logging.info(
|
|
2177
|
+
f"Using on-device cache with admission algorithm "
|
|
2178
|
+
f"{cache_algorithm}, {cache_sets} sets, "
|
|
2179
|
+
f"load_factor: {cache_load_factor : .3f}, "
|
|
2180
|
+
f"{cache_size / 1024.0 / 1024.0 / 1024.0 : .2f}GB"
|
|
2181
|
+
)
|
|
2182
|
+
|
|
2183
|
+
self.total_cache_hash_size = cache_state.total_cache_hash_size
|
|
2184
|
+
self.register_buffer(
|
|
2185
|
+
"cache_hash_size_cumsum",
|
|
2186
|
+
torch.tensor(
|
|
2187
|
+
cache_state.cache_hash_size_cumsum,
|
|
2188
|
+
device=self.current_device,
|
|
2189
|
+
dtype=torch.int64,
|
|
2190
|
+
),
|
|
2191
|
+
)
|
|
2192
|
+
self.register_buffer(
|
|
2193
|
+
"cache_index_table_map",
|
|
2194
|
+
torch.tensor(
|
|
2195
|
+
cache_state.cache_index_table_map,
|
|
2196
|
+
device=self.current_device,
|
|
2197
|
+
dtype=torch.int32,
|
|
2198
|
+
),
|
|
2199
|
+
)
|
|
2200
|
+
self.register_buffer(
|
|
2201
|
+
"lxu_cache_state",
|
|
2202
|
+
torch.zeros(
|
|
2203
|
+
cache_sets, ASSOC, device=self.current_device, dtype=torch.int64
|
|
2204
|
+
).fill_(-1),
|
|
2205
|
+
)
|
|
2206
|
+
self.register_buffer(
|
|
2207
|
+
"lxu_cache_weights",
|
|
2208
|
+
torch.zeros(
|
|
2209
|
+
cache_sets * ASSOC,
|
|
2210
|
+
self.max_D_cache,
|
|
2211
|
+
device=self.current_device,
|
|
2212
|
+
dtype=torch.uint8,
|
|
2213
|
+
),
|
|
2214
|
+
)
|
|
2215
|
+
self.register_buffer(
|
|
2216
|
+
"lxu_state",
|
|
2217
|
+
# pyre-fixme[28]: Unexpected keyword argument `size`.
|
|
2218
|
+
torch.zeros(
|
|
2219
|
+
size=(self.total_cache_hash_size + 1,)
|
|
2220
|
+
if cache_algorithm == CacheAlgorithm.LFU
|
|
2221
|
+
else (cache_sets, ASSOC),
|
|
2222
|
+
device=self.current_device,
|
|
2223
|
+
dtype=torch.int64,
|
|
2224
|
+
),
|
|
2225
|
+
)
|
|
2226
|
+
self.register_buffer(
|
|
2227
|
+
"cache_miss_counter",
|
|
2228
|
+
torch.tensor([0, 0], device=self.current_device, dtype=torch.int64),
|
|
2229
|
+
)
|
|
2230
|
+
if cache_algorithm not in (CacheAlgorithm.LFU, CacheAlgorithm.LRU):
|
|
2231
|
+
raise ValueError(
|
|
2232
|
+
f"cache_algorithm must be {CacheAlgorithm.LRU} "
|
|
2233
|
+
f"or {CacheAlgorithm.LFU}"
|
|
2234
|
+
)
|
|
2235
|
+
|
|
2236
|
+
def reset_cache_states(self) -> None:
|
|
2237
|
+
# pyre-fixme[29]:
|
|
2238
|
+
# `Union[BoundMethod[typing.Callable(Tensor.numel)[[Named(self, Tensor)],
|
|
2239
|
+
# int], Tensor], Tensor, nn.Module]` is not a function.
|
|
2240
|
+
if not self.lxu_cache_weights.numel():
|
|
2241
|
+
return
|
|
2242
|
+
self.lxu_cache_state.fill_(-1)
|
|
2243
|
+
self.lxu_state.fill_(0)
|
|
2244
|
+
self.timestep_counter.reset()
|
|
2245
|
+
|
|
2246
|
+
@torch.jit.export
|
|
2247
|
+
def split_embedding_weights(
|
|
2248
|
+
self, split_scale_shifts: bool = True
|
|
2249
|
+
) -> List[Tuple[Tensor, Optional[Tensor]]]:
|
|
2250
|
+
"""
|
|
2251
|
+
Returns a list of weights, split by table
|
|
2252
|
+
"""
|
|
2253
|
+
assert self.weight_initialized
|
|
2254
|
+
splits: List[Tuple[Tensor, Optional[Tensor]]] = []
|
|
2255
|
+
for t, (_, rows, dim, weight_ty, _) in enumerate(self.embedding_specs):
|
|
2256
|
+
placement = self.weights_physical_placements[t]
|
|
2257
|
+
if placement == EmbeddingLocation.DEVICE.value:
|
|
2258
|
+
weights = self.weights_dev
|
|
2259
|
+
elif placement == EmbeddingLocation.HOST.value:
|
|
2260
|
+
weights = self.weights_host
|
|
2261
|
+
else:
|
|
2262
|
+
weights = self.weights_uvm
|
|
2263
|
+
offset = self.weights_physical_offsets[t]
|
|
2264
|
+
weights_shifts = weights.detach()[
|
|
2265
|
+
offset : offset
|
|
2266
|
+
+ rows * rounded_row_size_in_bytes(dim, weight_ty, self.row_alignment)
|
|
2267
|
+
].view(rows, rounded_row_size_in_bytes(dim, weight_ty, self.row_alignment))
|
|
2268
|
+
|
|
2269
|
+
if split_scale_shifts:
|
|
2270
|
+
# remove the padding at the end of each row.
|
|
2271
|
+
weights_shifts = weights_shifts[
|
|
2272
|
+
:, : unpadded_row_size_in_bytes(dim, weight_ty)
|
|
2273
|
+
]
|
|
2274
|
+
if (
|
|
2275
|
+
weight_ty == SparseType.INT8
|
|
2276
|
+
or weight_ty == SparseType.INT4
|
|
2277
|
+
or weight_ty == SparseType.INT2
|
|
2278
|
+
):
|
|
2279
|
+
splits.append(
|
|
2280
|
+
(
|
|
2281
|
+
weights_shifts[:, 4:],
|
|
2282
|
+
weights_shifts[:, :4],
|
|
2283
|
+
)
|
|
2284
|
+
)
|
|
2285
|
+
else:
|
|
2286
|
+
assert (
|
|
2287
|
+
weight_ty == SparseType.FP8
|
|
2288
|
+
or weight_ty == SparseType.FP16
|
|
2289
|
+
or weight_ty == SparseType.FP32
|
|
2290
|
+
)
|
|
2291
|
+
splits.append(
|
|
2292
|
+
(
|
|
2293
|
+
weights_shifts,
|
|
2294
|
+
None,
|
|
2295
|
+
)
|
|
2296
|
+
)
|
|
2297
|
+
else:
|
|
2298
|
+
splits.append((weights_shifts, None))
|
|
2299
|
+
|
|
2300
|
+
return splits
|
|
2301
|
+
|
|
2302
|
+
def initialize_weights(self) -> None:
|
|
2303
|
+
if not self.weight_initialized:
|
|
2304
|
+
self._apply_split(
|
|
2305
|
+
self.dev_size,
|
|
2306
|
+
self.host_size,
|
|
2307
|
+
self.uvm_size,
|
|
2308
|
+
self.weights_physical_placements,
|
|
2309
|
+
self.weights_physical_offsets,
|
|
2310
|
+
self.enforce_hbm,
|
|
2311
|
+
)
|
|
2312
|
+
self.weight_initialized: bool = True
|
|
2313
|
+
|
|
2314
|
+
def fill_random_weights(self) -> None:
|
|
2315
|
+
"""
|
|
2316
|
+
Fill the buffer with random weights, table by table
|
|
2317
|
+
FIXME: make it in-place fill.
|
|
2318
|
+
"""
|
|
2319
|
+
self.initialize_weights()
|
|
2320
|
+
weights = self.split_embedding_weights()
|
|
2321
|
+
for dest_weight in weights:
|
|
2322
|
+
dest_weight[0].copy_(
|
|
2323
|
+
torch.randint(
|
|
2324
|
+
0,
|
|
2325
|
+
255,
|
|
2326
|
+
size=dest_weight[0].shape,
|
|
2327
|
+
dtype=torch.uint8,
|
|
2328
|
+
device=self.current_device,
|
|
2329
|
+
)
|
|
2330
|
+
)
|
|
2331
|
+
|
|
2332
|
+
def assign_embedding_weights(
|
|
2333
|
+
self, q_weight_list: List[Tuple[Tensor, Optional[Tensor]]]
|
|
2334
|
+
) -> None:
|
|
2335
|
+
"""
|
|
2336
|
+
Assigns self.split_embedding_weights() with values from the input list of weights and scale_shifts.
|
|
2337
|
+
"""
|
|
2338
|
+
weights = self.split_embedding_weights()
|
|
2339
|
+
assert len(q_weight_list) == len(weights)
|
|
2340
|
+
|
|
2341
|
+
for (dest_weight, input_weight) in zip(weights, q_weight_list):
|
|
2342
|
+
dest_weight[0].copy_(input_weight[0])
|
|
2343
|
+
if input_weight[1] is not None:
|
|
2344
|
+
assert dest_weight[1] is not None
|
|
2345
|
+
dest_weight[1].copy_(input_weight[1])
|
|
2346
|
+
else:
|
|
2347
|
+
assert dest_weight[1] is None
|
|
2348
|
+
|
|
2349
|
+
def set_index_remappings(
|
|
2350
|
+
self,
|
|
2351
|
+
index_remapping: List[Tensor],
|
|
2352
|
+
load_factor: float = 0.5,
|
|
2353
|
+
use_array_for_index_remapping: bool = True,
|
|
2354
|
+
) -> None:
|
|
2355
|
+
rows: List[int] = [e[1] for e in self.embedding_specs]
|
|
2356
|
+
T = len(self.embedding_specs)
|
|
2357
|
+
if not use_array_for_index_remapping:
|
|
2358
|
+
capacities = [
|
|
2359
|
+
round_up(int(row * 1.0 / load_factor), 32)
|
|
2360
|
+
if index_remap is not None
|
|
2361
|
+
else 0
|
|
2362
|
+
for (index_remap, row) in zip(index_remapping, rows)
|
|
2363
|
+
]
|
|
2364
|
+
hash_table = torch.empty(
|
|
2365
|
+
(sum(capacities), 2),
|
|
2366
|
+
dtype=torch.int32,
|
|
2367
|
+
)
|
|
2368
|
+
hash_table[:, :] = -1
|
|
2369
|
+
hash_table_offsets = torch.tensor([0] + list(accumulate(capacities))).long()
|
|
2370
|
+
|
|
2371
|
+
merged_index_remappings = [
|
|
2372
|
+
mapping if mapping is not None else Tensor(list(range(spec[1])))
|
|
2373
|
+
for (mapping, spec) in zip(index_remapping, self.embedding_specs)
|
|
2374
|
+
]
|
|
2375
|
+
original_feature_rows = [
|
|
2376
|
+
mapping.numel() for mapping in merged_index_remappings
|
|
2377
|
+
]
|
|
2378
|
+
dense_indices = torch.cat(merged_index_remappings, dim=0).int()
|
|
2379
|
+
indices = torch.cat(
|
|
2380
|
+
[torch.arange(row) for row in original_feature_rows], dim=0
|
|
2381
|
+
).int()
|
|
2382
|
+
offsets = torch.tensor([0] + list(accumulate(original_feature_rows))).int()
|
|
2383
|
+
|
|
2384
|
+
if self.use_cpu:
|
|
2385
|
+
self.index_remapping_hash_table_cpu = torch.classes.fb.PrunedMapCPU()
|
|
2386
|
+
self.index_remapping_hash_table_cpu.insert(
|
|
2387
|
+
indices, dense_indices, offsets, T
|
|
2388
|
+
)
|
|
2389
|
+
else:
|
|
2390
|
+
torch.ops.fbgemm.pruned_hashmap_insert(
|
|
2391
|
+
indices, dense_indices, offsets, hash_table, hash_table_offsets
|
|
2392
|
+
)
|
|
2393
|
+
self.index_remapping_hash_table = hash_table.to(self.current_device)
|
|
2394
|
+
self.index_remapping_hash_table_offsets = hash_table_offsets.to(
|
|
2395
|
+
self.current_device
|
|
2396
|
+
)
|
|
2397
|
+
self.index_remapping_hash_table_cpu = None
|
|
2398
|
+
else:
|
|
2399
|
+
index_remappings_array_offsets = [0]
|
|
2400
|
+
last_offset = 0
|
|
2401
|
+
for mapping in index_remapping:
|
|
2402
|
+
if mapping is not None:
|
|
2403
|
+
last_offset += mapping.numel()
|
|
2404
|
+
index_remappings_array_offsets.append(last_offset)
|
|
2405
|
+
|
|
2406
|
+
self.index_remappings_array_offsets = torch.tensor(
|
|
2407
|
+
index_remappings_array_offsets,
|
|
2408
|
+
device=self.current_device,
|
|
2409
|
+
dtype=torch.int64,
|
|
2410
|
+
)
|
|
2411
|
+
self.index_remappings_array = (
|
|
2412
|
+
torch.empty(0, dtype=torch.int32, device=self.current_device)
|
|
2413
|
+
if self.index_remappings_array_offsets[-1] == 0
|
|
2414
|
+
else torch.cat(
|
|
2415
|
+
[mapping for mapping in index_remapping if mapping is not None]
|
|
2416
|
+
).to(self.current_device)
|
|
2417
|
+
)
|
|
2418
|
+
|
|
2419
|
+
def _embedding_inplace_update_per_table(
|
|
2420
|
+
self,
|
|
2421
|
+
update_table_idx: int,
|
|
2422
|
+
update_row_indices: List[int],
|
|
2423
|
+
update_weights: Tensor,
|
|
2424
|
+
) -> None:
|
|
2425
|
+
row_size = len(update_row_indices)
|
|
2426
|
+
if row_size == 0:
|
|
2427
|
+
return
|
|
2428
|
+
update_row_indices = torch.tensor(
|
|
2429
|
+
update_row_indices,
|
|
2430
|
+
device=self.current_device,
|
|
2431
|
+
dtype=torch.int64,
|
|
2432
|
+
)
|
|
2433
|
+
table_values = self.split_embedding_weights(split_scale_shifts=False)[
|
|
2434
|
+
update_table_idx
|
|
2435
|
+
]
|
|
2436
|
+
table_values[0].scatter_(
|
|
2437
|
+
dim=0,
|
|
2438
|
+
index=update_row_indices.view(row_size, 1).expand_as(update_weights),
|
|
2439
|
+
src=update_weights,
|
|
2440
|
+
)
|
|
2441
|
+
|
|
2442
|
+
@torch.jit.export
|
|
2443
|
+
def embedding_inplace_update(
|
|
2444
|
+
self,
|
|
2445
|
+
update_table_indices: List[int],
|
|
2446
|
+
update_row_indices: List[List[int]],
|
|
2447
|
+
update_weights: List[Tensor],
|
|
2448
|
+
) -> None:
|
|
2449
|
+
for i in range(len(update_table_indices)):
|
|
2450
|
+
self._embedding_inplace_update_per_table(
|
|
2451
|
+
update_table_indices[i],
|
|
2452
|
+
update_row_indices[i],
|
|
2453
|
+
update_weights[i],
|
|
2454
|
+
)
|
|
2455
|
+
|
|
2456
|
+
def embedding_inplace_update_internal(
|
|
2457
|
+
self,
|
|
2458
|
+
update_table_indices: List[int],
|
|
2459
|
+
update_row_indices: List[int],
|
|
2460
|
+
update_weights: Tensor,
|
|
2461
|
+
) -> None:
|
|
2462
|
+
assert len(update_table_indices) == len(update_row_indices)
|
|
2463
|
+
update_offsets = []
|
|
2464
|
+
update_offset = 0
|
|
2465
|
+
for table_idx in update_table_indices:
|
|
2466
|
+
D_bytes = rounded_row_size_in_bytes(
|
|
2467
|
+
self.embedding_specs[table_idx][2],
|
|
2468
|
+
self.embedding_specs[table_idx][3],
|
|
2469
|
+
self.row_alignment,
|
|
2470
|
+
)
|
|
2471
|
+
update_offsets.append(update_offset)
|
|
2472
|
+
update_offset += D_bytes
|
|
2473
|
+
update_offsets.append(update_offset)
|
|
2474
|
+
|
|
2475
|
+
update_table_indices = torch.tensor(
|
|
2476
|
+
update_table_indices,
|
|
2477
|
+
device=self.current_device,
|
|
2478
|
+
dtype=torch.int32,
|
|
2479
|
+
)
|
|
2480
|
+
update_row_indices = torch.tensor(
|
|
2481
|
+
update_row_indices,
|
|
2482
|
+
device=self.current_device,
|
|
2483
|
+
dtype=torch.int32,
|
|
2484
|
+
)
|
|
2485
|
+
update_offsets = torch.tensor(
|
|
2486
|
+
update_offsets,
|
|
2487
|
+
device=self.current_device,
|
|
2488
|
+
dtype=torch.int64,
|
|
2489
|
+
)
|
|
2490
|
+
# Internal function for now
|
|
2491
|
+
torch.ops.fbgemm.emb_inplace_update(
|
|
2492
|
+
dev_weights=self.weights_host if self.host_size > 0 else self.weights_dev,
|
|
2493
|
+
uvm_weights=self.weights_uvm,
|
|
2494
|
+
weights_placements=self.weights_placements,
|
|
2495
|
+
weights_offsets=self.weights_offsets,
|
|
2496
|
+
weights_tys=self.weights_tys,
|
|
2497
|
+
D_offsets=self.D_offsets,
|
|
2498
|
+
update_weights=update_weights,
|
|
2499
|
+
update_table_indices=update_table_indices,
|
|
2500
|
+
update_row_indices=update_row_indices,
|
|
2501
|
+
update_offsets=update_offsets,
|
|
2502
|
+
row_alignment=self.row_alignment,
|
|
2503
|
+
)
|