torchrec 0.2.0.dev0__37-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. examples/__init__.py +0 -0
  2. examples/datasets/__init__.py +8 -0
  3. examples/datasets/criteo_dataframes.py +101 -0
  4. examples/ray/__init__.py +0 -0
  5. examples/ray/compute_world_size.py +51 -0
  6. examples/ray/train_torchrec.py +133 -0
  7. examples/retrieval/__init__.py +6 -0
  8. examples/retrieval/data/__init__.py +6 -0
  9. examples/retrieval/data/dataloader.py +44 -0
  10. examples/retrieval/knn_index.py +67 -0
  11. examples/retrieval/modules/__init__.py +6 -0
  12. examples/retrieval/modules/two_tower.py +229 -0
  13. examples/retrieval/two_tower_retrieval.py +192 -0
  14. examples/retrieval/two_tower_train.py +253 -0
  15. examples/torcharrow/__init__.py +8 -0
  16. examples/torcharrow/dataloader.py +116 -0
  17. examples/torcharrow/run.py +126 -0
  18. fbgemm_gpu/__init__.py +16 -0
  19. fbgemm_gpu/batched_unary_embeddings_ops.py +82 -0
  20. fbgemm_gpu/enums.py +21 -0
  21. fbgemm_gpu/fbgemm_gpu_py.so +0 -0
  22. fbgemm_gpu/permute_pooled_embedding_modules.py +73 -0
  23. fbgemm_gpu/permute_pooled_embedding_modules_split.py +76 -0
  24. fbgemm_gpu/split_embedding_codegen_lookup_invokers/__init__.py +19 -0
  25. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adagrad.py +120 -0
  26. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adam.py +149 -0
  27. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad.py +128 -0
  28. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_counter.py +134 -0
  29. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_weight_decay.py +128 -0
  30. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_sgd.py +105 -0
  31. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_args.py +54 -0
  32. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lamb.py +149 -0
  33. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lars_sgd.py +128 -0
  34. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_adam.py +149 -0
  35. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_lamb.py +149 -0
  36. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad.py +128 -0
  37. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_counter.py +134 -0
  38. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_weight_decay.py +128 -0
  39. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_weighted_adagrad.py +130 -0
  40. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_sgd.py +105 -0
  41. fbgemm_gpu/split_embedding_configs.py +182 -0
  42. fbgemm_gpu/split_embedding_inference_converter.py +208 -0
  43. fbgemm_gpu/split_table_batched_embeddings_ops.py +2503 -0
  44. fbgemm_gpu/uvm.py +35 -0
  45. torchrec/__init__.py +27 -0
  46. torchrec/datasets/__init__.py +31 -0
  47. torchrec/datasets/criteo.py +831 -0
  48. torchrec/datasets/movielens.py +140 -0
  49. torchrec/datasets/random.py +188 -0
  50. torchrec/datasets/scripts/__init__.py +0 -0
  51. torchrec/datasets/scripts/contiguous_preproc_criteo.py +75 -0
  52. torchrec/datasets/scripts/npy_preproc_criteo.py +73 -0
  53. torchrec/datasets/test_utils/__init__.py +0 -0
  54. torchrec/datasets/test_utils/criteo_test_utils.py +139 -0
  55. torchrec/datasets/utils.py +341 -0
  56. torchrec/distributed/__init__.py +55 -0
  57. torchrec/distributed/batched_embedding_kernel.py +697 -0
  58. torchrec/distributed/collective_utils.py +71 -0
  59. torchrec/distributed/comm.py +149 -0
  60. torchrec/distributed/comm_ops.py +930 -0
  61. torchrec/distributed/dist_data.py +949 -0
  62. torchrec/distributed/embedding.py +638 -0
  63. torchrec/distributed/embedding_kernel.py +326 -0
  64. torchrec/distributed/embedding_lookup.py +760 -0
  65. torchrec/distributed/embedding_sharding.py +660 -0
  66. torchrec/distributed/embedding_tower_sharding.py +992 -0
  67. torchrec/distributed/embedding_types.py +369 -0
  68. torchrec/distributed/embeddingbag.py +731 -0
  69. torchrec/distributed/fused_embeddingbag.py +148 -0
  70. torchrec/distributed/grouped_position_weighted.py +103 -0
  71. torchrec/distributed/model_parallel.py +555 -0
  72. torchrec/distributed/planner/__init__.py +24 -0
  73. torchrec/distributed/planner/constants.py +77 -0
  74. torchrec/distributed/planner/enumerators.py +353 -0
  75. torchrec/distributed/planner/parallelized_planners.py +307 -0
  76. torchrec/distributed/planner/partitioners.py +280 -0
  77. torchrec/distributed/planner/perf_models.py +24 -0
  78. torchrec/distributed/planner/planners.py +290 -0
  79. torchrec/distributed/planner/proposers.py +270 -0
  80. torchrec/distributed/planner/shard_estimators.py +971 -0
  81. torchrec/distributed/planner/stats.py +477 -0
  82. torchrec/distributed/planner/storage_reservations.py +168 -0
  83. torchrec/distributed/planner/types.py +423 -0
  84. torchrec/distributed/planner/utils.py +30 -0
  85. torchrec/distributed/quant_embedding.py +307 -0
  86. torchrec/distributed/quant_embedding_kernel.py +295 -0
  87. torchrec/distributed/quant_embeddingbag.py +288 -0
  88. torchrec/distributed/sharding/__init__.py +0 -0
  89. torchrec/distributed/sharding/cw_sequence_sharding.py +71 -0
  90. torchrec/distributed/sharding/cw_sharding.py +242 -0
  91. torchrec/distributed/sharding/dp_sequence_sharding.py +87 -0
  92. torchrec/distributed/sharding/dp_sharding.py +217 -0
  93. torchrec/distributed/sharding/rw_sequence_sharding.py +130 -0
  94. torchrec/distributed/sharding/rw_sharding.py +393 -0
  95. torchrec/distributed/sharding/sequence_sharding.py +69 -0
  96. torchrec/distributed/sharding/tw_sequence_sharding.py +211 -0
  97. torchrec/distributed/sharding/tw_sharding.py +469 -0
  98. torchrec/distributed/sharding/twcw_sharding.py +32 -0
  99. torchrec/distributed/sharding/twrw_sharding.py +543 -0
  100. torchrec/distributed/sharding/vb_cw_sharding.py +91 -0
  101. torchrec/distributed/sharding/vb_rw_sharding.py +250 -0
  102. torchrec/distributed/sharding/vb_sharding.py +54 -0
  103. torchrec/distributed/sharding/vb_tw_sharding.py +148 -0
  104. torchrec/distributed/sharding/vb_twrw_sharding.py +388 -0
  105. torchrec/distributed/test_utils/__init__.py +0 -0
  106. torchrec/distributed/test_utils/multi_process.py +132 -0
  107. torchrec/distributed/test_utils/test_model.py +818 -0
  108. torchrec/distributed/test_utils/test_model_parallel.py +74 -0
  109. torchrec/distributed/test_utils/test_model_parallel_base.py +117 -0
  110. torchrec/distributed/test_utils/test_sharding.py +280 -0
  111. torchrec/distributed/train_pipeline.py +531 -0
  112. torchrec/distributed/types.py +594 -0
  113. torchrec/distributed/utils.py +186 -0
  114. torchrec/fused_planner.py +57 -0
  115. torchrec/fx/__init__.py +15 -0
  116. torchrec/fx/tracer.py +78 -0
  117. torchrec/inference/__init__.py +25 -0
  118. torchrec/inference/client.py +127 -0
  119. torchrec/inference/model_packager.py +102 -0
  120. torchrec/inference/modules.py +155 -0
  121. torchrec/inference/state_dict_transform.py +103 -0
  122. torchrec/metrics/__init__.py +0 -0
  123. torchrec/metrics/auc.py +159 -0
  124. torchrec/metrics/calibration.py +108 -0
  125. torchrec/metrics/ctr.py +104 -0
  126. torchrec/metrics/metric_module.py +358 -0
  127. torchrec/metrics/metrics_config.py +152 -0
  128. torchrec/metrics/metrics_namespace.py +114 -0
  129. torchrec/metrics/model_utils.py +85 -0
  130. torchrec/metrics/mse.py +134 -0
  131. torchrec/metrics/ne.py +164 -0
  132. torchrec/metrics/rec_metric.py +686 -0
  133. torchrec/metrics/throughput.py +174 -0
  134. torchrec/models/__init__.py +27 -0
  135. torchrec/models/deepfm.py +346 -0
  136. torchrec/models/dlrm.py +708 -0
  137. torchrec/modules/__init__.py +34 -0
  138. torchrec/modules/activation.py +55 -0
  139. torchrec/modules/crossnet.py +446 -0
  140. torchrec/modules/deepfm.py +213 -0
  141. torchrec/modules/embedding_configs.py +148 -0
  142. torchrec/modules/embedding_modules.py +381 -0
  143. torchrec/modules/embedding_tower.py +150 -0
  144. torchrec/modules/feature_processor.py +74 -0
  145. torchrec/modules/fused_embedding_modules.py +625 -0
  146. torchrec/modules/lazy_extension.py +258 -0
  147. torchrec/modules/mlp.py +172 -0
  148. torchrec/modules/utils.py +117 -0
  149. torchrec/optim/__init__.py +35 -0
  150. torchrec/optim/clipping.py +53 -0
  151. torchrec/optim/fused.py +42 -0
  152. torchrec/optim/keyed.py +399 -0
  153. torchrec/optim/rowwise_adagrad.py +222 -0
  154. torchrec/optim/test_utils/__init__.py +19 -0
  155. torchrec/optim/warmup.py +147 -0
  156. torchrec/quant/__init__.py +34 -0
  157. torchrec/quant/embedding_modules.py +545 -0
  158. torchrec/sparse/__init__.py +33 -0
  159. torchrec/sparse/jagged_tensor.py +1281 -0
  160. torchrec/sparse/test_utils/__init__.py +45 -0
  161. torchrec/streamable.py +46 -0
  162. torchrec/test_utils/__init__.py +111 -0
  163. torchrec-0.2.dev0.dist-info/LICENSE +29 -0
  164. torchrec-0.2.dev0.dist-info/METADATA +175 -0
  165. torchrec-0.2.dev0.dist-info/RECORD +167 -0
  166. torchrec-0.2.dev0.dist-info/WHEEL +5 -0
  167. torchrec-0.2.dev0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,1281 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import abc
9
+ from typing import Dict, List, Optional, Tuple
10
+
11
+ import torch
12
+ import torch.fx
13
+ from torchrec.streamable import Pipelineable
14
+
15
+ try:
16
+ torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops")
17
+ torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops_cpu")
18
+ except OSError:
19
+ pass
20
+
21
+ # OSS
22
+ try:
23
+ import fbgemm_gpu # @manual # noqa
24
+ except ImportError:
25
+ pass
26
+
27
+
28
+ def _cumsum(o: List[int]) -> List[int]:
29
+ ret = [0] * (len(o) + 1)
30
+ for i in range(len(o)):
31
+ ret[i + 1] = ret[i] + o[i]
32
+ return ret
33
+
34
+
35
+ def _to_offsets(lengths: torch.Tensor) -> torch.Tensor:
36
+ return torch.ops.fbgemm.asynchronous_complete_cumsum(lengths)
37
+
38
+
39
+ def _to_lengths(offsets: torch.Tensor) -> torch.Tensor:
40
+ return offsets[1:] - offsets[:-1]
41
+
42
+
43
+ def _batched_lengths_to_offsets(lengths: torch.Tensor) -> torch.Tensor:
44
+ (f, b) = lengths.shape
45
+ offsets_0 = lengths.new_zeros((f, 1))
46
+ offsets_1 = torch.cumsum(lengths, dim=-1).to(lengths.dtype)
47
+ offsets = torch.cat([offsets_0, offsets_1], dim=-1)
48
+ return offsets
49
+
50
+
51
+ def _maybe_compute_lengths(
52
+ lengths: Optional[torch.Tensor], offsets: Optional[torch.Tensor]
53
+ ) -> torch.Tensor:
54
+ if lengths is None:
55
+ assert offsets is not None
56
+ lengths = _to_lengths(offsets)
57
+ return lengths
58
+
59
+
60
+ def _maybe_compute_offsets(
61
+ lengths: Optional[torch.Tensor], offsets: Optional[torch.Tensor]
62
+ ) -> torch.Tensor:
63
+ if offsets is None:
64
+ assert lengths is not None
65
+ offsets = _to_offsets(lengths)
66
+ return offsets
67
+
68
+
69
+ def _get_weights_or_throw(weights: Optional[torch.Tensor]) -> torch.Tensor:
70
+ assert weights is not None, "This (Keyed)JaggedTensor doesn't have weights."
71
+ return weights
72
+
73
+
74
+ def _assert_offsets_or_lengths_is_provided(
75
+ offsets: Optional[torch.Tensor], lengths: Optional[torch.Tensor]
76
+ ) -> None:
77
+ assert offsets is not None or lengths is not None, "Must provide lengths or offsets"
78
+
79
+
80
+ def _regroup_keyed_tensors(
81
+ keyed_tensors: List["KeyedTensor"], groups: List[List[str]]
82
+ ) -> List[torch.Tensor]:
83
+ # Shortcut for no re-grouping
84
+ if len(keyed_tensors) == len(groups):
85
+ match = True
86
+ for kt, group in zip(keyed_tensors, groups):
87
+ if kt.keys() != group:
88
+ match = False
89
+ break
90
+ if match:
91
+ return [kt.values() for kt in keyed_tensors]
92
+
93
+ embedding_dicts = [keyed_tensor.to_dict() for keyed_tensor in keyed_tensors]
94
+ lengths = [keyed_tensor.length_per_key() for keyed_tensor in keyed_tensors]
95
+ indices = [keyed_tensor._key_indices() for keyed_tensor in keyed_tensors]
96
+ key_dim = keyed_tensors[0].key_dim()
97
+
98
+ key_to_idx: dict[str, int] = {}
99
+ for (i, keyed_tensor) in enumerate(keyed_tensors):
100
+ for key in keyed_tensor.keys():
101
+ key_to_idx[key] = i
102
+
103
+ # Rearrange values based on groups with a single torch.cat operation.
104
+ cat_input: List[torch.Tensor] = []
105
+ for group in groups:
106
+ for name in group:
107
+ cat_input.append(embedding_dicts[key_to_idx[name]][name])
108
+ rearranged_values = torch.cat(cat_input, key_dim)
109
+
110
+ # Provide views over the rearranged values with a single torch.split operation.
111
+ split_lengths: List[int] = []
112
+ for group in groups:
113
+ group_length = 0
114
+ for name in group:
115
+ group_length += lengths[key_to_idx[name]][indices[key_to_idx[name]][name]]
116
+ split_lengths.append(group_length)
117
+
118
+ return list(rearranged_values.split(split_lengths, dim=key_dim))
119
+
120
+
121
+ torch.fx.wrap("_regroup_keyed_tensors")
122
+
123
+
124
+ def _values_string(values: torch.Tensor, start: int, end: int) -> str:
125
+ size = values.size()
126
+ if len(size) == 1:
127
+ return "[" + ", ".join([str(value.item()) for value in values[start:end]]) + "]"
128
+ elif len(size) == 2:
129
+ values_list: List[str] = []
130
+ for value in values[start:end]:
131
+ values_list.append("[" + ", ".join([str(s.item()) for s in value]) + "]")
132
+ return "[" + ", ".join(values_list) + "]"
133
+ else:
134
+ raise ValueError(
135
+ "the values dimension is larger than 2, we don't support printing"
136
+ )
137
+
138
+
139
+ def _jagged_values_string(
140
+ values: torch.Tensor,
141
+ offsets: torch.Tensor,
142
+ offset_start: int,
143
+ offset_end: int,
144
+ ) -> str:
145
+ return (
146
+ "["
147
+ + ", ".join(
148
+ [
149
+ # pyre-fixme[6]: For 2nd param expected `int` but got `Tensor`.
150
+ # pyre-fixme[6]: For 3rd param expected `int` but got `Tensor`.
151
+ _values_string(values, offsets[index], offsets[index + 1])
152
+ for index in range(offset_start, offset_end)
153
+ ]
154
+ )
155
+ + "]"
156
+ )
157
+
158
+
159
+ # pyre-fixme[11]: Annotation `ProxyableClassMeta` is not defined as a type.
160
+ class JaggedTensorMeta(abc.ABCMeta, torch.fx.ProxyableClassMeta):
161
+ pass
162
+
163
+
164
+ class JaggedTensor(Pipelineable, metaclass=JaggedTensorMeta):
165
+ """
166
+ Represents an (optionally weighted) jagged tensor.
167
+
168
+ A `JaggedTensor` is a tensor with a *jagged dimension* which is dimension whose
169
+ slices may be of different lengths. See `KeyedJaggedTensor` for full example.
170
+
171
+ Implementation is torch.jit.script-able.
172
+
173
+ NOTE:
174
+ We will NOT do input validation as it's expensive, you should always pass in the
175
+ valid lengths, offsets, etc.
176
+
177
+ Args:
178
+ values (torch.Tensor): values tensor in dense representation.
179
+ weights (Optional[torch.Tensor]): if values have weights. Tensor with same shape
180
+ as values.
181
+ lengths (Optional[torch.Tensor]): jagged slices, represented as lengths.
182
+ offsets (Optional[torch.Tensor]): jagged slices, represented as cumulative
183
+ offsets.
184
+ """
185
+
186
+ def __init__(
187
+ self,
188
+ values: torch.Tensor,
189
+ weights: Optional[torch.Tensor] = None,
190
+ lengths: Optional[torch.Tensor] = None,
191
+ offsets: Optional[torch.Tensor] = None,
192
+ ) -> None:
193
+ self._values: torch.Tensor = values
194
+ self._weights: Optional[torch.Tensor] = weights
195
+ _assert_offsets_or_lengths_is_provided(offsets, lengths)
196
+ if offsets is not None:
197
+ _assert_tensor_has_no_elements_or_has_integers(offsets, "offsets")
198
+ if lengths is not None:
199
+ _assert_tensor_has_no_elements_or_has_integers(lengths, "lengths")
200
+ self._lengths: Optional[torch.Tensor] = lengths
201
+ self._offsets: Optional[torch.Tensor] = offsets
202
+
203
+ @staticmethod
204
+ def empty(is_weighted: bool = False) -> "JaggedTensor":
205
+ weights = torch.tensor([]) if is_weighted else None
206
+ return JaggedTensor(
207
+ values=torch.tensor([]),
208
+ offsets=torch.tensor([]),
209
+ lengths=torch.tensor([]),
210
+ weights=weights,
211
+ )
212
+
213
+ @staticmethod
214
+ def from_dense_lengths(
215
+ values: torch.Tensor,
216
+ lengths: torch.Tensor,
217
+ weights: Optional[torch.Tensor] = None,
218
+ ) -> "JaggedTensor":
219
+ """
220
+ Constructs `JaggedTensor` from dense values/weights of shape (B, N,).
221
+
222
+ Note that `lengths` is still of shape (B,).
223
+ """
224
+ mask2d = torch.arange(values.size(1), device=values.device).expand(
225
+ values.size(0), -1
226
+ ) < lengths.unsqueeze(-1)
227
+ return JaggedTensor(
228
+ values=values[mask2d],
229
+ weights=weights[mask2d] if weights is not None else None,
230
+ lengths=lengths,
231
+ )
232
+
233
+ @staticmethod
234
+ def from_dense(
235
+ values: List[torch.Tensor],
236
+ weights: Optional[List[torch.Tensor]] = None,
237
+ ) -> "JaggedTensor":
238
+ """
239
+ Constructs `JaggedTensor` from dense values/weights of shape (B, N,).
240
+
241
+ Note that `lengths` and `offsets` are still of shape (B,).
242
+
243
+ Args:
244
+ values (List[torch.Tensor]): a list of tensors for dense representation
245
+ weights (Optional[List[torch.Tensor]]): if values have weights, tensor with
246
+ the same shape as values.
247
+
248
+ Returns:
249
+ JaggedTensor: JaggedTensor created from 2D dense tensor.
250
+
251
+ Example::
252
+
253
+ values = [
254
+ torch.Tensor([1.0]),
255
+ torch.Tensor(),
256
+ torch.Tensor([7.0, 8.0]),
257
+ torch.Tensor([10.0, 11.0, 12.0]),
258
+ ]
259
+ weights = [
260
+ torch.Tensor([1.0]),
261
+ torch.Tensor(),
262
+ torch.Tensor([7.0, 8.0]),
263
+ torch.Tensor([10.0, 11.0, 12.0]),
264
+ ]
265
+ j1 = JaggedTensor.from_dense(
266
+ values=values,
267
+ weights=weights,
268
+ )
269
+
270
+ # j1 = [[1.0], [], [7.0], [8.0], [10.0, 11.0, 12.0]]
271
+ """
272
+ lengths = torch.IntTensor([value.size(0) for value in values])
273
+ # pyre-ignore [9]: values is declared to have type `List[Tensor]` but is used as type `Tensor`.
274
+ values = torch.cat(values, dim=0)
275
+ # pyre-ignore [9]: weights is declared to have type `Optional[List[Tensor]]` but is used as type `Optional[Tensor]`.
276
+ weights = torch.cat(weights, dim=0) if weights is not None else None
277
+
278
+ return JaggedTensor(
279
+ # pyre-fixme[6]: For 1st param expected `Tensor` but got `List[Tensor]`.
280
+ values=values,
281
+ # pyre-fixme[6]: For 2nd param expected `Optional[Tensor]` but got
282
+ # `Optional[List[Tensor]]`.
283
+ weights=weights,
284
+ lengths=lengths,
285
+ )
286
+
287
+ def to_dense(self) -> List[torch.Tensor]:
288
+ """
289
+ Constructs dense-reprensentation tensor from JT.
290
+
291
+ Returns:
292
+ List[torch.Tensor]: list of tensors.
293
+
294
+ Example::
295
+
296
+ values = torch.Tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
297
+ offsets = torch.IntTensor([0, 2, 2, 3, 4, 5, 8])
298
+ jt = JaggedTensor(values=values, offsets=offsets)
299
+
300
+ torch_list = jt.to_dense()
301
+
302
+ # torch_list = [
303
+ # torch.tensor([1.0, 2.0]),
304
+ # torch.tensor([]),
305
+ # torch.tensor([3.0]),
306
+ # torch.tensor([4.0]),
307
+ # torch.tensor([5.0]),
308
+ # torch.tensor([6.0, 7.0, 8.0]),
309
+ # ]
310
+ """
311
+ tensor_list = []
312
+ for index in range(self.offsets().size(0) - 1):
313
+ offset = self.offsets()[index].item()
314
+ next_offset = self.offsets()[index + 1].item()
315
+ tensor_list.append(self.values()[offset:next_offset])
316
+ return tensor_list
317
+
318
+ def to_padded_dense(
319
+ self,
320
+ desired_length: Optional[int] = None,
321
+ padding_value: float = 0.0,
322
+ ) -> torch.Tensor:
323
+ """
324
+ Constructs 2D dense Tensor from JT to shape (B, N,).
325
+
326
+ Note that `B` is the length of self.lengths() and `N` is the longest feature
327
+ length or `desired_length`.
328
+
329
+ If `desired_length` > `length` we will pad with `padding_value`, otherwise we
330
+ will select the last value at `desired_length`.
331
+
332
+ Args:
333
+ desired_length (int): the length of the tensor.
334
+ padding_value (float): padding value if we need to pad.
335
+
336
+ Returns:
337
+ torch.Tensor: 2d dense tensor.
338
+
339
+ Example::
340
+
341
+ values = torch.Tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
342
+ offsets = torch.IntTensor([0, 2, 2, 3, 4, 5, 8])
343
+ jt = JaggedTensor(values=values, offsets=offsets)
344
+
345
+ dt = jt.to_padded_dense(
346
+ desired_length=2,
347
+ padding_value=10.0,
348
+ )
349
+
350
+ # dt = [
351
+ # [1.0, 2.0],
352
+ # [10.0, 10.0],
353
+ # [3.0, 10.0],
354
+ # [4.0, 10.0],
355
+ # [5.0, 10.0],
356
+ # [7.0, 8.0],
357
+ # ]
358
+ """
359
+ lengths_list: List[int] = self.lengths().tolist()
360
+ N = max(lengths_list) if desired_length is None else desired_length
361
+ return torch.ops.fbgemm.jagged_to_padded_dense(
362
+ self.values(), [self.offsets()], [N], padding_value
363
+ )
364
+
365
+ def lengths(self) -> torch.Tensor:
366
+ _lengths = _maybe_compute_lengths(self._lengths, self._offsets)
367
+ self._lengths = _lengths
368
+ return _lengths
369
+
370
+ def offsets(self) -> torch.Tensor:
371
+ _offsets = _maybe_compute_offsets(self._lengths, self._offsets)
372
+ self._offsets = _offsets
373
+ return _offsets
374
+
375
+ def values(self) -> torch.Tensor:
376
+ return self._values
377
+
378
+ def weights(self) -> torch.Tensor:
379
+ return _get_weights_or_throw(self._weights)
380
+
381
+ def weights_or_none(self) -> Optional[torch.Tensor]:
382
+ return self._weights
383
+
384
+ def to(self, device: torch.device, non_blocking: bool = False) -> "JaggedTensor":
385
+ weights = self._weights
386
+ lengths = self._lengths
387
+ offsets = self._offsets
388
+ return JaggedTensor(
389
+ values=self._values.to(device, non_blocking=non_blocking),
390
+ weights=weights.to(device, non_blocking=non_blocking)
391
+ if weights is not None
392
+ else None,
393
+ lengths=lengths.to(device, non_blocking=non_blocking)
394
+ if lengths is not None
395
+ else None,
396
+ offsets=offsets.to(device, non_blocking=non_blocking)
397
+ if offsets is not None
398
+ else None,
399
+ )
400
+
401
+ @torch.jit.unused
402
+ def record_stream(self, stream: torch.cuda.streams.Stream) -> None:
403
+ # pyre-fixme[6]: For 1st param expected `Stream` but got `Stream`.
404
+ self._values.record_stream(stream)
405
+ weights = self._weights
406
+ lengths = self._lengths
407
+ offsets = self._offsets
408
+ if weights is not None:
409
+ # pyre-fixme[6]: For 1st param expected `Stream` but got `Stream`.
410
+ weights.record_stream(stream)
411
+ if lengths is not None:
412
+ # pyre-fixme[6]: For 1st param expected `Stream` but got `Stream`.
413
+ lengths.record_stream(stream)
414
+ if offsets is not None:
415
+ # pyre-fixme[6]: For 1st param expected `Stream` but got `Stream`.
416
+ offsets.record_stream(stream)
417
+
418
+ def __str__(self) -> str:
419
+ offsets = self.offsets()
420
+
421
+ if self._weights is None:
422
+ return (
423
+ "JaggedTensor({\n "
424
+ + _jagged_values_string(self._values, offsets, 0, len(offsets) - 1)
425
+ + "\n})\n"
426
+ )
427
+
428
+ return (
429
+ "JaggedTensor({\n"
430
+ + ' "values": '
431
+ + _jagged_values_string(self._values, offsets, 0, len(offsets) - 1)
432
+ + ',\n "weights": '
433
+ + _jagged_values_string(
434
+ _get_weights_or_throw(self._weights), offsets, 0, len(offsets) - 1
435
+ )
436
+ + "\n})\n"
437
+ )
438
+
439
+
440
+ def _assert_tensor_has_no_elements_or_has_integers(
441
+ tensor: torch.Tensor, tensor_name: str
442
+ ) -> None:
443
+ assert tensor.numel() == 0 or tensor.dtype in [
444
+ torch.long,
445
+ torch.int,
446
+ torch.short,
447
+ torch.int8,
448
+ torch.uint8,
449
+ ], "{} must be of integer type, but got {}".format(tensor_name, tensor.dtype)
450
+
451
+
452
+ def _maybe_compute_index_per_key(
453
+ keys: List[str],
454
+ index_per_key: Optional[Dict[str, int]],
455
+ ) -> Dict[str, int]:
456
+ if index_per_key is None:
457
+ index_per_key = {key: i for i, key in enumerate(keys)}
458
+ return index_per_key
459
+
460
+
461
+ def _maybe_compute_stride_kjt(
462
+ keys: List[str],
463
+ stride: Optional[int],
464
+ lengths: Optional[torch.Tensor],
465
+ offsets: Optional[torch.Tensor],
466
+ ) -> int:
467
+ if stride is None:
468
+ if len(keys) == 0:
469
+ stride = 0
470
+ elif offsets is not None:
471
+ stride = (offsets.numel() - 1) // len(keys)
472
+ elif lengths is not None:
473
+ stride = lengths.numel() // len(keys)
474
+ else:
475
+ stride = 1
476
+ return stride
477
+
478
+
479
+ # Specialization of _maybe_compute_stride_kjt that is scripted, so it will produce
480
+ # correct results in case of usage with jit.tracing.
481
+ # This module is returning torch.Tensor instead of int, because ji.trace doesn't
482
+ # support int type at the current moment.
483
+ @torch.jit.script
484
+ def _maybe_compute_stride_kjt_scripted(
485
+ keys: List[str],
486
+ stride: Optional[int],
487
+ lengths: Optional[torch.Tensor],
488
+ offsets: Optional[torch.Tensor],
489
+ ) -> torch.Tensor:
490
+ return torch.tensor([_maybe_compute_stride_kjt(keys, stride, lengths, offsets)])
491
+
492
+
493
+ def _maybe_compute_length_per_key(
494
+ keys: List[str],
495
+ stride: int,
496
+ length_per_key: Optional[List[int]],
497
+ lengths: Optional[torch.Tensor],
498
+ offsets: Optional[torch.Tensor],
499
+ ) -> List[int]:
500
+ if length_per_key is None:
501
+ if len(keys) and offsets is not None:
502
+ _length: List[int] = (
503
+ torch.sum((offsets[1:] - offsets[:-1]).view(-1, stride), dim=1)
504
+ .cpu()
505
+ .tolist()
506
+ )
507
+ elif len(keys) and lengths is not None:
508
+ _length: List[int] = (
509
+ torch.sum(lengths.view(-1, stride), dim=1).cpu().tolist()
510
+ )
511
+ else:
512
+ _length: List[int] = []
513
+ length_per_key = _length
514
+ return length_per_key
515
+
516
+
517
+ def _maybe_compute_offset_per_key(
518
+ keys: List[str],
519
+ stride: int,
520
+ length_per_key: Optional[List[int]],
521
+ offset_per_key: Optional[List[int]],
522
+ lengths: Optional[torch.Tensor],
523
+ offsets: Optional[torch.Tensor],
524
+ ) -> Tuple[List[int], List[int]]:
525
+ if length_per_key is None:
526
+ _length_per_key: List[int] = _maybe_compute_length_per_key(
527
+ keys, stride, length_per_key, lengths, offsets
528
+ )
529
+ return _length_per_key, _cumsum(_length_per_key)
530
+ elif offset_per_key is None:
531
+ return length_per_key, _cumsum(length_per_key)
532
+ else:
533
+ return length_per_key, offset_per_key
534
+
535
+
536
+ def _jagged_tensor_string(
537
+ key: str,
538
+ values: torch.Tensor,
539
+ weights: Optional[torch.Tensor],
540
+ offsets: torch.Tensor,
541
+ offset_start: int,
542
+ offset_end: int,
543
+ ) -> str:
544
+ if weights is None:
545
+ return '"{}": '.format(key) + _jagged_values_string(
546
+ values, offsets, offset_start, offset_end
547
+ )
548
+
549
+ return (
550
+ '"{}"'.format(key)
551
+ + ': {\n "values": '
552
+ + _jagged_values_string(values, offsets, offset_start, offset_end)
553
+ + ',\n "weights": '
554
+ + _jagged_values_string(
555
+ _get_weights_or_throw(weights), offsets, offset_start, offset_end
556
+ )
557
+ + "\n }"
558
+ )
559
+
560
+
561
+ def _maybe_compute_kjt_to_jt_dict(
562
+ stride: int,
563
+ keys: List[str],
564
+ length_per_key: List[int],
565
+ values: torch.Tensor,
566
+ lengths: torch.Tensor,
567
+ weights: Optional[torch.Tensor],
568
+ jt_dict: Optional[Dict[str, JaggedTensor]],
569
+ ) -> Dict[str, JaggedTensor]:
570
+ if jt_dict is None:
571
+ _jt_dict: Dict[str, JaggedTensor] = {}
572
+ values_list = torch.split(values, length_per_key)
573
+ lengths_tuple = torch.unbind(lengths.view(-1, stride), dim=0)
574
+ offsets_tuple = torch.unbind(
575
+ _batched_lengths_to_offsets(lengths.view(-1, stride)), dim=0
576
+ )
577
+
578
+ if weights is not None:
579
+ weights_list = torch.split(weights, length_per_key)
580
+ for idx, key in enumerate(keys):
581
+ length = lengths_tuple[idx]
582
+ offset = offsets_tuple[idx]
583
+ _jt_dict[key] = JaggedTensor(
584
+ lengths=length,
585
+ offsets=offset,
586
+ values=values_list[idx],
587
+ weights=weights_list[idx],
588
+ )
589
+ else:
590
+ for idx, key in enumerate(keys):
591
+ length = lengths_tuple[idx]
592
+ offset = offsets_tuple[idx]
593
+ _jt_dict[key] = JaggedTensor(
594
+ lengths=length,
595
+ offsets=offset,
596
+ values=values_list[idx],
597
+ )
598
+ jt_dict = _jt_dict
599
+ return jt_dict
600
+
601
+
602
+ def _merge_weights_or_none(
603
+ a_weights: Optional[torch.Tensor],
604
+ b_weights: Optional[torch.Tensor],
605
+ ) -> Optional[torch.Tensor]:
606
+ assert not (
607
+ (a_weights is None) ^ (b_weights is None)
608
+ ), "Can only merge weighted or unweighted KJTs."
609
+ if a_weights is None:
610
+ return None
611
+ # pyre-ignore[6]
612
+ return torch.cat([a_weights, b_weights], dim=0)
613
+
614
+
615
+ torch.fx.wrap("_merge_weights_or_none")
616
+
617
+
618
+ class KeyedJaggedTensor(Pipelineable, metaclass=JaggedTensorMeta):
619
+ """Represents an (optionally weighted) keyed jagged tensor.
620
+
621
+ A `JaggedTensor` is a tensor with a *jagged dimension* which is dimension whose
622
+ slices may be of different lengths. Keyed on first dimension and jagged on the last
623
+ dimension.
624
+
625
+ Implementation is torch.jit.script-able.
626
+
627
+ Args:
628
+ keys (List[str]): keys to the jagged Tensor.
629
+ values (torch.Tensor): values tensor in dense representation.
630
+ weights (Optional[torch.Tensor]): if the values have weights. Tensor with the
631
+ same shape as values.
632
+ lengths (Optional[torch.Tensor]): jagged slices, represented as lengths.
633
+ offsets (Optional[torch.Tensor]): jagged slices, represented as cumulative
634
+ offsets.
635
+ stride (Optional[int]): number of examples per batch.
636
+ length_per_key (Optional[List[int]]): start length for each key.
637
+ offset_per_key (Optional[List[int]]): start offset for each key and final
638
+ offset.
639
+ index_per_key (Optional[Dict[str, int]]): index for each key.
640
+ jt_dict (Optional[Dict[str, JaggedTensor]]):
641
+
642
+ Example::
643
+
644
+ # 0 1 2 <-- dim_1
645
+ # "Feature0" [V0,V1] None [V2]
646
+ # "Feature1" [V3] [V4] [V5,V6,V7]
647
+ # ^
648
+ # dim_0
649
+
650
+ dim_0: keyed dimension (ie. `Feature0`, `Feature1`)
651
+ dim_1: optional second dimension (ie. batch size)
652
+ dim_2: The jagged dimension which has slice lengths between 0-3 in the above example
653
+
654
+ # We represent this data with following inputs:
655
+
656
+ values: torch.Tensor = [V0, V1, V2, V3, V4, V5, V6, V7] # V == any tensor datatype
657
+ weights: torch.Tensor = [W0, W1, W2, W3, W4, W5, W6, W7] # W == any tensor datatype
658
+ lengths: torch.Tensor = [2, 0, 1, 1, 1, 3] # representing the jagged slice
659
+ offsets: torch.Tensor = [0, 2, 2, 3, 4, 5, 8] # offsets from 0 for each jagged slice
660
+ keys: List[int] = ["Feature0", "Feature1"] # correspond to each value of dim_0
661
+ index_per_key: Dict[str, int] = {"Feature0": 0, "Feature1": 1} # index for each key
662
+ offset_per_key: List[int] = [0, 3, 8] # start offset for each key and final offset
663
+ """
664
+
665
+ def __init__(
666
+ self,
667
+ keys: List[str],
668
+ values: torch.Tensor,
669
+ weights: Optional[torch.Tensor] = None,
670
+ lengths: Optional[torch.Tensor] = None,
671
+ offsets: Optional[torch.Tensor] = None,
672
+ stride: Optional[int] = None,
673
+ # Below exposed to ensure torch.script-able
674
+ length_per_key: Optional[List[int]] = None,
675
+ offset_per_key: Optional[List[int]] = None,
676
+ index_per_key: Optional[Dict[str, int]] = None,
677
+ jt_dict: Optional[Dict[str, JaggedTensor]] = None,
678
+ ) -> None:
679
+ self._keys: List[str] = keys
680
+ self._values: torch.Tensor = values
681
+ self._weights: Optional[torch.Tensor] = weights
682
+ if offsets is not None:
683
+ _assert_tensor_has_no_elements_or_has_integers(offsets, "offsets")
684
+ if lengths is not None:
685
+ _assert_tensor_has_no_elements_or_has_integers(lengths, "lengths")
686
+ self._lengths: Optional[torch.Tensor] = lengths
687
+ self._offsets: Optional[torch.Tensor] = offsets
688
+ if torch.jit.is_tracing():
689
+ stride = _maybe_compute_stride_kjt_scripted(keys, stride, lengths, offsets)[
690
+ 0
691
+ ]
692
+ else:
693
+ stride = _maybe_compute_stride_kjt(keys, stride, lengths, offsets)
694
+
695
+ self._stride: int = stride
696
+
697
+ # lazy fields
698
+ self._length_per_key: Optional[List[int]] = length_per_key
699
+ self._offset_per_key: Optional[List[int]] = offset_per_key
700
+ self._index_per_key: Optional[Dict[str, int]] = index_per_key
701
+ self._jt_dict: Optional[Dict[str, JaggedTensor]] = jt_dict
702
+
703
+ @staticmethod
704
+ def from_offsets_sync(
705
+ keys: List[str],
706
+ values: torch.Tensor,
707
+ offsets: torch.Tensor,
708
+ weights: Optional[torch.Tensor] = None,
709
+ stride: Optional[int] = None,
710
+ ) -> "KeyedJaggedTensor":
711
+ kjt = KeyedJaggedTensor(
712
+ keys=keys,
713
+ values=values,
714
+ weights=weights,
715
+ offsets=offsets,
716
+ stride=stride,
717
+ )
718
+ return kjt.sync()
719
+
720
+ @staticmethod
721
+ def from_lengths_sync(
722
+ keys: List[str],
723
+ values: torch.Tensor,
724
+ lengths: torch.Tensor,
725
+ weights: Optional[torch.Tensor] = None,
726
+ stride: Optional[int] = None,
727
+ ) -> "KeyedJaggedTensor":
728
+ kjt = KeyedJaggedTensor(
729
+ keys=keys,
730
+ values=values,
731
+ weights=weights,
732
+ lengths=lengths,
733
+ stride=stride,
734
+ )
735
+ return kjt.sync()
736
+
737
+ @staticmethod
738
+ def concat(
739
+ kjt_list: List["KeyedJaggedTensor"],
740
+ ) -> "KeyedJaggedTensor":
741
+ if len(kjt_list) == 0:
742
+ raise ValueError("Can't concat empty KJT list")
743
+ stride: int = kjt_list[0].stride()
744
+ is_weighted: bool = kjt_list[0].weights_or_none() is not None
745
+ has_length_per_key: bool = True
746
+
747
+ length_per_key: List[int] = []
748
+ keys: List[str] = []
749
+ value_list: List[torch.Tensor] = []
750
+ weight_list: List[torch.Tensor] = []
751
+ length_list: List[torch.Tensor] = []
752
+
753
+ for kjt in kjt_list:
754
+ if kjt.stride() != stride:
755
+ raise ValueError(
756
+ f"Can only merge KJTs of the same stride ({stride} != kjt.stride())"
757
+ )
758
+ curr_is_weighted: bool = kjt.weights_or_none() is not None
759
+ if is_weighted != curr_is_weighted:
760
+ raise ValueError("Can't merge weighted KJT with unweighted KJT")
761
+
762
+ if kjt._length_per_key is None:
763
+ has_length_per_key = False
764
+
765
+ if has_length_per_key:
766
+ # pyre-ignore[6]
767
+ length_per_key += kjt._length_per_key
768
+ keys += kjt.keys()
769
+ value_list.append(kjt.values())
770
+ if is_weighted:
771
+ weight_list.append(kjt.weights())
772
+ length_list.append(kjt.lengths())
773
+
774
+ return KeyedJaggedTensor(
775
+ keys=keys,
776
+ values=torch.cat(value_list, dim=0),
777
+ weights=torch.cat(weight_list, dim=0) if is_weighted else None,
778
+ lengths=torch.cat(length_list, dim=0),
779
+ stride=stride,
780
+ length_per_key=length_per_key if has_length_per_key else None,
781
+ )
782
+
783
+ @staticmethod
784
+ def empty(
785
+ is_weighted: bool = False, device: Optional[torch.device] = None
786
+ ) -> "KeyedJaggedTensor":
787
+ weights = None
788
+ if is_weighted is True:
789
+ weights = torch.tensor([], device=device) if device else torch.tensor([])
790
+
791
+ return KeyedJaggedTensor(
792
+ keys=[],
793
+ values=torch.tensor([], device=device) if device else torch.tensor([]),
794
+ weights=weights,
795
+ stride=0,
796
+ )
797
+
798
+ @staticmethod
799
+ def empty_like(kjt: "KeyedJaggedTensor") -> "KeyedJaggedTensor":
800
+ return KeyedJaggedTensor(
801
+ keys=[],
802
+ values=torch.tensor([], device=kjt.device(), dtype=kjt.values().dtype),
803
+ weights=None
804
+ if kjt.weights_or_none() is None
805
+ else torch.tensor([], device=kjt.device(), dtype=kjt.weights().dtype),
806
+ lengths=None,
807
+ offsets=None,
808
+ stride=kjt.stride(),
809
+ )
810
+
811
+ def sync(self) -> "KeyedJaggedTensor":
812
+ self.length_per_key()
813
+ self.offset_per_key()
814
+ return self
815
+
816
+ def device(self) -> torch.device:
817
+ return self._values.device
818
+
819
+ def lengths(self) -> torch.Tensor:
820
+ _lengths = _maybe_compute_lengths(self._lengths, self._offsets)
821
+ self._lengths = _lengths
822
+ return _lengths
823
+
824
+ def offsets(self) -> torch.Tensor:
825
+ _offsets = _maybe_compute_offsets(self._lengths, self._offsets)
826
+ self._offsets = _offsets
827
+ return _offsets
828
+
829
+ def keys(self) -> List[str]:
830
+ return self._keys
831
+
832
+ def values(self) -> torch.Tensor:
833
+ return self._values
834
+
835
+ def weights(self) -> torch.Tensor:
836
+ return _get_weights_or_throw(self._weights)
837
+
838
+ def weights_or_none(self) -> Optional[torch.Tensor]:
839
+ return self._weights
840
+
841
+ def stride(self) -> int:
842
+ return self._stride
843
+
844
+ def _key_indices(self) -> Dict[str, int]:
845
+ _index_per_key: Dict[str, int] = _maybe_compute_index_per_key(
846
+ self._keys,
847
+ self._index_per_key,
848
+ )
849
+ self._index_per_key = _index_per_key
850
+ return _index_per_key
851
+
852
+ def length_per_key(self) -> List[int]:
853
+ _length_per_key = _maybe_compute_length_per_key(
854
+ self._keys,
855
+ self.stride(),
856
+ self._length_per_key,
857
+ self._lengths,
858
+ self._offsets,
859
+ )
860
+ self._length_per_key = _length_per_key
861
+ return _length_per_key
862
+
863
+ def offset_per_key(self) -> List[int]:
864
+ _length_per_key, _offset_per_key = _maybe_compute_offset_per_key(
865
+ self._keys,
866
+ self.stride(),
867
+ self._length_per_key,
868
+ self._offset_per_key,
869
+ self._lengths,
870
+ self._offsets,
871
+ )
872
+ self._length_per_key = _length_per_key
873
+ self._offset_per_key = _offset_per_key
874
+ return _offset_per_key
875
+
876
+ def split(self, segments: List[int]) -> List["KeyedJaggedTensor"]:
877
+ split_list: List[KeyedJaggedTensor] = []
878
+ start = 0
879
+ start_offset = 0
880
+ _length_per_key = self.length_per_key()
881
+ _offset_per_key = self.offset_per_key()
882
+ for segment in segments:
883
+ end = start + segment
884
+ end_offset = _offset_per_key[end]
885
+ keys: List[str] = self._keys[start:end]
886
+ if segment == len(self._keys):
887
+ # no torch slicing required
888
+ split_list.append(
889
+ KeyedJaggedTensor(
890
+ keys=self._keys,
891
+ values=self._values,
892
+ weights=self.weights_or_none(),
893
+ lengths=self._lengths,
894
+ offsets=self._offsets,
895
+ stride=self._stride,
896
+ length_per_key=self._length_per_key,
897
+ offset_per_key=self._offset_per_key,
898
+ index_per_key=self._index_per_key,
899
+ jt_dict=self._jt_dict,
900
+ )
901
+ )
902
+ elif segment == 0:
903
+ split_list.append(
904
+ KeyedJaggedTensor(
905
+ keys=keys,
906
+ values=torch.tensor(
907
+ [], device=self.device(), dtype=self._values.dtype
908
+ ),
909
+ weights=None
910
+ if self.weights_or_none() is None
911
+ else torch.tensor(
912
+ [],
913
+ device=self.device(),
914
+ dtype=self.weights().dtype,
915
+ ),
916
+ lengths=torch.tensor([], device=self.device(), dtype=torch.int),
917
+ offsets=torch.tensor([], device=self.device(), dtype=torch.int),
918
+ stride=self._stride,
919
+ length_per_key=None,
920
+ offset_per_key=None,
921
+ index_per_key=None,
922
+ jt_dict=None,
923
+ )
924
+ )
925
+ else:
926
+ split_length_per_key = _length_per_key[start:end]
927
+ split_list.append(
928
+ KeyedJaggedTensor(
929
+ keys=keys,
930
+ values=self._values[start_offset:end_offset],
931
+ weights=None
932
+ if self.weights_or_none() is None
933
+ else self.weights()[start_offset:end_offset],
934
+ lengths=self.lengths()[
935
+ start * self._stride : end * self._stride
936
+ ],
937
+ offsets=None,
938
+ stride=self._stride,
939
+ length_per_key=split_length_per_key,
940
+ offset_per_key=None,
941
+ index_per_key=None,
942
+ jt_dict=None,
943
+ )
944
+ )
945
+ start = end
946
+ start_offset = end_offset
947
+ return split_list
948
+
949
+ def permute(
950
+ self, indices: List[int], indices_tensor: Optional[torch.Tensor] = None
951
+ ) -> "KeyedJaggedTensor":
952
+
953
+ if indices_tensor is None:
954
+ indices_tensor = torch.tensor(
955
+ indices, dtype=torch.int, device=self.device()
956
+ )
957
+
958
+ length_per_key = self.length_per_key()
959
+ permuted_keys: List[str] = []
960
+ permuted_length_per_key: List[int] = []
961
+ permuted_lengths_sum = 0
962
+ for index in indices:
963
+ key = self._keys[index]
964
+ permuted_keys.append(key)
965
+ permuted_lengths_sum += length_per_key[index]
966
+ permuted_length_per_key.append(length_per_key[index])
967
+ (
968
+ permuted_lengths,
969
+ permuted_values,
970
+ permuted_weights,
971
+ ) = torch.ops.fbgemm.permute_2D_sparse_data(
972
+ indices_tensor,
973
+ self.lengths().view(len(self._keys), -1),
974
+ self.values(),
975
+ self.weights_or_none(),
976
+ permuted_lengths_sum,
977
+ )
978
+
979
+ kjt = KeyedJaggedTensor(
980
+ keys=permuted_keys,
981
+ values=permuted_values,
982
+ weights=permuted_weights,
983
+ lengths=permuted_lengths.view(-1),
984
+ offsets=None,
985
+ stride=self._stride,
986
+ length_per_key=permuted_length_per_key if len(permuted_keys) > 0 else None,
987
+ offset_per_key=None,
988
+ index_per_key=None,
989
+ jt_dict=None,
990
+ )
991
+ return kjt
992
+
993
+ def __getitem__(self, key: str) -> JaggedTensor:
994
+ offset_per_key = self.offset_per_key()
995
+ index = self._key_indices()[key]
996
+ start_offset = offset_per_key[index]
997
+ end_offset = offset_per_key[index + 1]
998
+ return JaggedTensor(
999
+ values=self._values[start_offset:end_offset],
1000
+ weights=None
1001
+ if self.weights_or_none() is None
1002
+ else self.weights()[start_offset:end_offset],
1003
+ lengths=self.lengths()[index * self._stride : (index + 1) * self._stride],
1004
+ offsets=None,
1005
+ )
1006
+
1007
+ def to_dict(self) -> Dict[str, JaggedTensor]:
1008
+ _jt_dict = _maybe_compute_kjt_to_jt_dict(
1009
+ self.stride(),
1010
+ self.keys(),
1011
+ self.length_per_key(),
1012
+ self.values(),
1013
+ self.lengths(),
1014
+ self.weights_or_none(),
1015
+ self._jt_dict,
1016
+ )
1017
+ self._jt_dict = _jt_dict
1018
+ return _jt_dict
1019
+
1020
+ @torch.jit.unused
1021
+ def record_stream(self, stream: torch.cuda.streams.Stream) -> None:
1022
+ # pyre-fixme[6]: For 1st param expected `Stream` but got `Stream`.
1023
+ self._values.record_stream(stream)
1024
+ weights = self._weights
1025
+ lengths = self._lengths
1026
+ offsets = self._offsets
1027
+ if weights is not None:
1028
+ # pyre-fixme[6]: For 1st param expected `Stream` but got `Stream`.
1029
+ weights.record_stream(stream)
1030
+ if lengths is not None:
1031
+ # pyre-fixme[6]: For 1st param expected `Stream` but got `Stream`.
1032
+ lengths.record_stream(stream)
1033
+ if offsets is not None:
1034
+ # pyre-fixme[6]: For 1st param expected `Stream` but got `Stream`.
1035
+ offsets.record_stream(stream)
1036
+
1037
+ def to(
1038
+ self, device: torch.device, non_blocking: bool = False
1039
+ ) -> "KeyedJaggedTensor":
1040
+ weights = self._weights
1041
+ lengths = self._lengths
1042
+ offsets = self._offsets
1043
+ length_per_key = self._length_per_key
1044
+ offset_per_key = self._offset_per_key
1045
+ index_per_key = self._index_per_key
1046
+ jt_dict = self._jt_dict
1047
+
1048
+ return KeyedJaggedTensor(
1049
+ keys=self._keys,
1050
+ values=self._values.to(device, non_blocking=non_blocking),
1051
+ weights=weights.to(device, non_blocking=non_blocking)
1052
+ if weights is not None
1053
+ else None,
1054
+ lengths=lengths.to(device, non_blocking=non_blocking)
1055
+ if lengths is not None
1056
+ else None,
1057
+ offsets=offsets.to(device, non_blocking=non_blocking)
1058
+ if offsets is not None
1059
+ else None,
1060
+ stride=self._stride,
1061
+ length_per_key=length_per_key,
1062
+ offset_per_key=offset_per_key,
1063
+ index_per_key=index_per_key,
1064
+ jt_dict=jt_dict,
1065
+ )
1066
+
1067
+ def __str__(self) -> str:
1068
+ if self._offsets is None and self._lengths is None:
1069
+ return "KeyedJaggedTensor()\n"
1070
+ offsets = self.offsets()
1071
+
1072
+ step = (len(offsets) - 1) // len(self._keys)
1073
+ return (
1074
+ "KeyedJaggedTensor({\n"
1075
+ + ",\n".join(
1076
+ [
1077
+ " "
1078
+ + _jagged_tensor_string(
1079
+ self._keys[index],
1080
+ self._values,
1081
+ self._weights,
1082
+ offsets,
1083
+ index * step,
1084
+ (index + 1) * step,
1085
+ )
1086
+ for index in range(len(self._keys))
1087
+ ]
1088
+ )
1089
+ + "\n})\n"
1090
+ )
1091
+
1092
+ def pin_memory(self) -> "KeyedJaggedTensor":
1093
+ weights = self._weights
1094
+ lengths = self._lengths
1095
+ offsets = self._offsets
1096
+
1097
+ return KeyedJaggedTensor(
1098
+ keys=self._keys,
1099
+ values=self._values.pin_memory(),
1100
+ weights=weights.pin_memory() if weights is not None else None,
1101
+ lengths=lengths.pin_memory() if lengths is not None else None,
1102
+ offsets=offsets.pin_memory() if offsets is not None else None,
1103
+ stride=self._stride,
1104
+ length_per_key=self._length_per_key,
1105
+ offset_per_key=self._offset_per_key,
1106
+ index_per_key=self._index_per_key,
1107
+ jt_dict=None,
1108
+ )
1109
+
1110
+
1111
+ def _maybe_compute_offset_per_key_kt(
1112
+ length_per_key: List[int],
1113
+ offset_per_key: Optional[List[int]],
1114
+ ) -> List[int]:
1115
+ if offset_per_key is None:
1116
+ offset_per_key = _cumsum(length_per_key)
1117
+ return offset_per_key
1118
+
1119
+
1120
+ def _keyed_values_string(values: torch.Tensor) -> str:
1121
+ return (
1122
+ "["
1123
+ + ", ".join([_values_string(value, 0, len(value)) for value in values])
1124
+ + "]"
1125
+ )
1126
+
1127
+
1128
+ class KeyedTensor(Pipelineable, metaclass=JaggedTensorMeta):
1129
+ """
1130
+ KeyedTensor holds a concatenated list of dense tensors, each of which can be
1131
+ accessed by a key.
1132
+
1133
+ The keyed dimension can be of variable length (length_per_key).
1134
+ Common use cases uses include storage of pooled embeddings of different dimensions.
1135
+
1136
+ Implementation is torch.jit.script-able.
1137
+
1138
+ Args:
1139
+ keys (List[str]): list of keys.
1140
+ length_per_key (List[int]): length of each key along key dimension.
1141
+ values (torch.Tensor): dense tensor, concatenated typically along key dimension.
1142
+ key_dim (int): key dimension, zero indexed - defaults to 1
1143
+ (typically B is 0-dimension).
1144
+
1145
+ Example::
1146
+
1147
+ # kt is KeyedTensor holding
1148
+
1149
+ # 0 1 2
1150
+ # "Embedding A" [1,1] [1,1] [1,1]
1151
+ # "Embedding B" [2,1,2] [2,1,2] [2,1,2]
1152
+ # "Embedding C" [3,1,2,3] [3,1,2,3] [3,1,2,3]
1153
+
1154
+ tensor_list = [
1155
+ torch.tensor([[1,1]] * 3),
1156
+ torch.tensor([[2,1,2]] * 3),
1157
+ torch.tensor([[3,1,2,3]] * 3),
1158
+ ]
1159
+
1160
+ keys = ["Embedding A", "Embedding B", "Embedding C"]
1161
+
1162
+ kt = KeyedTensor.from_tensor_list(keys, tensor_list)
1163
+
1164
+ kt.values()
1165
+ # tensor(
1166
+ # [
1167
+ # [1, 1, 2, 1, 2, 3, 1, 2, 3],
1168
+ # [1, 1, 2, 1, 2, 3, 1, 2, 3],
1169
+ # [1, 1, 2, 1, 2, 3, 1, 2, 3],
1170
+ # ]
1171
+ # )
1172
+
1173
+ kt["Embedding B"]
1174
+ # tensor([[2, 1, 2], [2, 1, 2], [2, 1, 2]])
1175
+ """
1176
+
1177
+ def __init__(
1178
+ self,
1179
+ keys: List[str],
1180
+ length_per_key: List[int],
1181
+ values: torch.Tensor,
1182
+ key_dim: int = 1,
1183
+ # Below exposed to ensure torch.script-able
1184
+ offset_per_key: Optional[List[int]] = None,
1185
+ index_per_key: Optional[Dict[str, int]] = None,
1186
+ ) -> None:
1187
+ self._keys = keys
1188
+ self._length_per_key = length_per_key
1189
+ self._values = values
1190
+ self._key_dim = key_dim
1191
+
1192
+ self._offset_per_key: Optional[List[int]] = offset_per_key
1193
+ self._index_per_key: Optional[Dict[str, int]] = index_per_key
1194
+
1195
+ @staticmethod
1196
+ def from_tensor_list(
1197
+ keys: List[str], tensors: List[torch.Tensor], key_dim: int = 1, cat_dim: int = 1
1198
+ ) -> "KeyedTensor":
1199
+ length_per_key = [tensor.shape[key_dim] for tensor in tensors]
1200
+ return KeyedTensor(
1201
+ keys=keys,
1202
+ length_per_key=length_per_key,
1203
+ values=torch.cat(tensors, dim=cat_dim),
1204
+ key_dim=key_dim,
1205
+ )
1206
+
1207
+ def keys(self) -> List[str]:
1208
+ return self._keys
1209
+
1210
+ def values(self) -> torch.Tensor:
1211
+ return self._values
1212
+
1213
+ def key_dim(self) -> int:
1214
+ return self._key_dim
1215
+
1216
+ def offset_per_key(self) -> List[int]:
1217
+ _offset_per_key = _maybe_compute_offset_per_key_kt(
1218
+ self._length_per_key,
1219
+ self._offset_per_key,
1220
+ )
1221
+ self._offset_per_key = _offset_per_key
1222
+ return _offset_per_key
1223
+
1224
+ def length_per_key(self) -> List[int]:
1225
+ return self._length_per_key
1226
+
1227
+ def _key_indices(self) -> Dict[str, int]:
1228
+ _index_per_key = _maybe_compute_index_per_key(
1229
+ self._keys,
1230
+ self._index_per_key,
1231
+ )
1232
+ self._index_per_key = _index_per_key
1233
+ return _index_per_key
1234
+
1235
+ def __getitem__(self, key: str) -> torch.Tensor:
1236
+ index = self._key_indices()[key]
1237
+ start = self.offset_per_key()[index]
1238
+ length = self._length_per_key[index]
1239
+ return self._values.narrow(dim=self._key_dim, start=start, length=length)
1240
+
1241
+ def to_dict(self) -> Dict[str, torch.Tensor]:
1242
+ indices = self._key_indices()
1243
+ lengths = self._length_per_key
1244
+ split_values = self._values.split(lengths, dim=self._key_dim)
1245
+ return {key: split_values[index] for (key, index) in indices.items()}
1246
+
1247
+ @staticmethod
1248
+ def regroup(
1249
+ keyed_tensors: List["KeyedTensor"], groups: List[List[str]]
1250
+ ) -> List[torch.Tensor]:
1251
+ return _regroup_keyed_tensors(keyed_tensors, groups)
1252
+
1253
+ @torch.jit.unused
1254
+ def record_stream(self, stream: torch.cuda.streams.Stream) -> None:
1255
+ # pyre-fixme[6]: For 1st param expected `Stream` but got `Stream`.
1256
+ self._values.record_stream(stream)
1257
+
1258
+ def to(self, device: torch.device, non_blocking: bool = False) -> "KeyedTensor":
1259
+ return KeyedTensor(
1260
+ keys=self._keys,
1261
+ length_per_key=self._length_per_key,
1262
+ values=self._values.to(device, non_blocking=non_blocking),
1263
+ key_dim=self._key_dim,
1264
+ offset_per_key=self._offset_per_key,
1265
+ index_per_key=self._index_per_key,
1266
+ )
1267
+
1268
+ def __str__(self) -> str:
1269
+ if len(self._keys) == 0:
1270
+ return "KeyedTensor()\n"
1271
+
1272
+ return (
1273
+ "KeyedTensor({\n"
1274
+ + ",\n".join(
1275
+ [
1276
+ ' "{}": '.format(key) + _keyed_values_string(self[key])
1277
+ for key in self._keys
1278
+ ]
1279
+ )
1280
+ + "\n})\n"
1281
+ )