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,686 @@
|
|
|
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
|
+
#!/usr/bin/env python3
|
|
9
|
+
|
|
10
|
+
import abc
|
|
11
|
+
import itertools
|
|
12
|
+
import math
|
|
13
|
+
from collections import defaultdict, deque
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from enum import Enum
|
|
16
|
+
from typing import (
|
|
17
|
+
Any,
|
|
18
|
+
Callable,
|
|
19
|
+
cast,
|
|
20
|
+
Deque,
|
|
21
|
+
Dict,
|
|
22
|
+
Iterator,
|
|
23
|
+
List,
|
|
24
|
+
Mapping,
|
|
25
|
+
Optional,
|
|
26
|
+
Sequence,
|
|
27
|
+
Tuple,
|
|
28
|
+
Type,
|
|
29
|
+
TypeVar,
|
|
30
|
+
Union,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
import torch
|
|
34
|
+
import torch.distributed as dist
|
|
35
|
+
import torch.nn as nn
|
|
36
|
+
from torchmetrics import Metric
|
|
37
|
+
from torchrec.metrics.metrics_config import RecComputeMode, RecTaskInfo
|
|
38
|
+
from torchrec.metrics.metrics_namespace import (
|
|
39
|
+
compose_metric_key,
|
|
40
|
+
MetricNameBase,
|
|
41
|
+
MetricNamespaceBase,
|
|
42
|
+
MetricPrefix,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
RecModelOutput = Union[torch.Tensor, Dict[str, torch.Tensor]]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class MetricComputationReport:
|
|
51
|
+
name: MetricNameBase
|
|
52
|
+
metric_prefix: MetricPrefix
|
|
53
|
+
value: torch.Tensor
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
DefaultValueT = TypeVar("DefaultValueT")
|
|
57
|
+
ComputeIterType = Iterator[
|
|
58
|
+
Tuple[RecTaskInfo, MetricNameBase, torch.Tensor, MetricPrefix]
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
MAX_BUFFER_COUNT = 1000
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class RecMetricException(Exception):
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class WindowBuffer:
|
|
69
|
+
def __init__(self, max_size: int, max_buffer_count: int) -> None:
|
|
70
|
+
self._max_size: int = max_size
|
|
71
|
+
self._max_buffer_count: int = max_buffer_count
|
|
72
|
+
|
|
73
|
+
self._buffers: Deque[torch.Tensor] = deque(maxlen=max_buffer_count)
|
|
74
|
+
self._used_sizes: Deque[int] = deque(maxlen=max_buffer_count)
|
|
75
|
+
self._window_used_size = 0
|
|
76
|
+
|
|
77
|
+
def aggregate_state(
|
|
78
|
+
self, window_state: torch.Tensor, curr_state: torch.Tensor, size: int
|
|
79
|
+
) -> None:
|
|
80
|
+
def remove(window_state: torch.Tensor) -> None:
|
|
81
|
+
window_state -= self._buffers.popleft()
|
|
82
|
+
self._window_used_size -= self._used_sizes.popleft()
|
|
83
|
+
|
|
84
|
+
if len(self._buffers) == self._buffers.maxlen:
|
|
85
|
+
remove(window_state)
|
|
86
|
+
|
|
87
|
+
self._buffers.append(curr_state)
|
|
88
|
+
self._used_sizes.append(size)
|
|
89
|
+
window_state += curr_state
|
|
90
|
+
self._window_used_size += size
|
|
91
|
+
|
|
92
|
+
while self._window_used_size > self._max_size:
|
|
93
|
+
remove(window_state)
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def buffers(self) -> Deque[torch.Tensor]:
|
|
97
|
+
return self._buffers
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class RecMetricComputation(Metric, abc.ABC):
|
|
101
|
+
r"""The internal computation class template.
|
|
102
|
+
A metric implementation should overwrite update() and compute(). These two
|
|
103
|
+
APIs focuses the actual mathematical meaning of the metric, without the
|
|
104
|
+
detail knowledge of model output and task information.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
my_rank (int): the rank of this trainer.
|
|
108
|
+
batch_size (int): batch size used by this trainer.
|
|
109
|
+
n_tasks (int): the number tasks this communication obj
|
|
110
|
+
will have to compute.
|
|
111
|
+
window_size (int): the window size for the window metric.
|
|
112
|
+
compute_on_all_ranks (bool): whether to compute metrics on all ranks. This
|
|
113
|
+
is necessary if non-leader rank want to consum metrics result.
|
|
114
|
+
should_validate_update (bool): whether to check the inputs of update() and skip
|
|
115
|
+
update if the inputs are invalid. Invalid inputs include the case where all
|
|
116
|
+
examples have 0 weights for a batch
|
|
117
|
+
process_group (Optional[ProcessGroup]): the process group used for the
|
|
118
|
+
communication. Will use the default process group if not specified.
|
|
119
|
+
"""
|
|
120
|
+
_batch_window_buffers: Optional[Dict[str, WindowBuffer]]
|
|
121
|
+
|
|
122
|
+
def __init__(
|
|
123
|
+
self,
|
|
124
|
+
my_rank: int,
|
|
125
|
+
batch_size: int,
|
|
126
|
+
n_tasks: int,
|
|
127
|
+
window_size: int,
|
|
128
|
+
compute_on_all_ranks: bool = False,
|
|
129
|
+
should_validate_update: bool = False,
|
|
130
|
+
process_group: Optional[dist.ProcessGroup] = None,
|
|
131
|
+
*args: Any,
|
|
132
|
+
**kwargs: Any,
|
|
133
|
+
) -> None:
|
|
134
|
+
super().__init__(process_group=process_group, *args, **kwargs)
|
|
135
|
+
|
|
136
|
+
self._my_rank = my_rank
|
|
137
|
+
self._n_tasks = n_tasks
|
|
138
|
+
self._batch_size = batch_size
|
|
139
|
+
self._window_size = window_size
|
|
140
|
+
self._compute_on_all_ranks = compute_on_all_ranks
|
|
141
|
+
self._should_validate_update = should_validate_update
|
|
142
|
+
if self._window_size > 0:
|
|
143
|
+
self._batch_window_buffers = {}
|
|
144
|
+
else:
|
|
145
|
+
self._batch_window_buffers = None
|
|
146
|
+
if self._should_validate_update:
|
|
147
|
+
self._add_state(
|
|
148
|
+
"has_valid_update",
|
|
149
|
+
torch.zeros(self._n_tasks, dtype=torch.uint8),
|
|
150
|
+
add_window_state=False,
|
|
151
|
+
dist_reduce_fx=lambda x: torch.any(x, dim=0).byte(),
|
|
152
|
+
persistent=True,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
@staticmethod
|
|
156
|
+
def get_window_state_name(state_name: str) -> str:
|
|
157
|
+
return f"window_{state_name}"
|
|
158
|
+
|
|
159
|
+
def get_window_state(self, state_name: str) -> torch.Tensor:
|
|
160
|
+
return getattr(self, self.get_window_state_name(state_name))
|
|
161
|
+
|
|
162
|
+
def _add_state(
|
|
163
|
+
self, name: str, default: DefaultValueT, add_window_state: bool, **kwargs: Any
|
|
164
|
+
) -> None:
|
|
165
|
+
# pyre-fixme[6]: Expected `Union[List[typing.Any], torch.Tensor]` for 2nd
|
|
166
|
+
# param but got `DefaultValueT`.
|
|
167
|
+
super().add_state(name, default, **kwargs)
|
|
168
|
+
if add_window_state:
|
|
169
|
+
if self._batch_window_buffers is None:
|
|
170
|
+
raise RuntimeError(
|
|
171
|
+
"Users is adding a window state while window metric is disabled."
|
|
172
|
+
)
|
|
173
|
+
kwargs["persistent"] = False
|
|
174
|
+
window_state_name = self.get_window_state_name(name)
|
|
175
|
+
# Avoid pyre error
|
|
176
|
+
assert isinstance(default, torch.Tensor)
|
|
177
|
+
super().add_state(window_state_name, default.detach().clone(), **kwargs)
|
|
178
|
+
self._batch_window_buffers[window_state_name] = WindowBuffer(
|
|
179
|
+
max_size=self._window_size,
|
|
180
|
+
max_buffer_count=MAX_BUFFER_COUNT,
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
def _aggregate_window_state(
|
|
184
|
+
self, state_name: str, state: torch.Tensor, num_samples: int
|
|
185
|
+
) -> None:
|
|
186
|
+
if self._batch_window_buffers is None:
|
|
187
|
+
raise RuntimeError(
|
|
188
|
+
"Users is adding a window state while window metric is disabled."
|
|
189
|
+
)
|
|
190
|
+
window_state_name = self.get_window_state_name(state_name)
|
|
191
|
+
assert self._batch_window_buffers is not None
|
|
192
|
+
self._batch_window_buffers[window_state_name].aggregate_state(
|
|
193
|
+
getattr(self, window_state_name), curr_state=state, size=num_samples
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
@abc.abstractmethod
|
|
197
|
+
# pyre-fixme[14]: `update` overrides method defined in `Metric` inconsistently.
|
|
198
|
+
def update(
|
|
199
|
+
self,
|
|
200
|
+
*,
|
|
201
|
+
predictions: Optional[torch.Tensor],
|
|
202
|
+
labels: torch.Tensor,
|
|
203
|
+
weights: Optional[torch.Tensor],
|
|
204
|
+
) -> None: # pragma: no cover
|
|
205
|
+
pass
|
|
206
|
+
|
|
207
|
+
@abc.abstractmethod
|
|
208
|
+
def _compute(self) -> List[MetricComputationReport]: # pragma: no cover
|
|
209
|
+
pass
|
|
210
|
+
|
|
211
|
+
def pre_compute(self) -> None:
|
|
212
|
+
r"""If a metric need to do some work before `compute()`, the metric
|
|
213
|
+
has to override this `pre_compute()`. One possible usage is to do
|
|
214
|
+
some pre-processing of the local state before `compute()` as TorchMetric
|
|
215
|
+
wraps `RecMetricComputation.compute()` and will do the global aggregation
|
|
216
|
+
before `RecMetricComputation.compute()` is called.
|
|
217
|
+
"""
|
|
218
|
+
return
|
|
219
|
+
|
|
220
|
+
def compute(self) -> List[MetricComputationReport]:
|
|
221
|
+
if self._my_rank == 0 or self._compute_on_all_ranks:
|
|
222
|
+
return self._compute()
|
|
223
|
+
else:
|
|
224
|
+
return []
|
|
225
|
+
|
|
226
|
+
def local_compute(self) -> List[MetricComputationReport]:
|
|
227
|
+
return self._compute()
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class RecMetric(nn.Module, abc.ABC):
|
|
231
|
+
r"""The main class template to implement a recommendation metric.
|
|
232
|
+
This class contains the recommendation tasks information (RecTaskInfo) and
|
|
233
|
+
the actual computation object (RecMetricComputation). RecMetric processes
|
|
234
|
+
all the information related to RecTaskInfo and models and pass the required
|
|
235
|
+
signals to the computation object, allowing the implementation of
|
|
236
|
+
RecMetricComputation to focus on the mathemetical meaning.
|
|
237
|
+
|
|
238
|
+
A new metric that inherit RecMetric must override the following attributes
|
|
239
|
+
in its own __init__(): `_namespace` and `_metrics_computations`. No other
|
|
240
|
+
methods should be overridden.
|
|
241
|
+
|
|
242
|
+
Args:
|
|
243
|
+
world_size (int): the number of trainers.
|
|
244
|
+
my_rank (int): the rank of this trainer.
|
|
245
|
+
batch_size (int): batch size used by this trainer.
|
|
246
|
+
tasks (List[RecTaskInfo]): the information of the model tasks.
|
|
247
|
+
compute_mode (RecComputeMode): the computation mode. See RecComputeMode.
|
|
248
|
+
window_size (int): the window size for the window metric.
|
|
249
|
+
fused_update_limit (int): the maximum number of updates to be fused.
|
|
250
|
+
compute_on_all_ranks (bool): whether to compute metrics on all ranks. This
|
|
251
|
+
is necessary if non-leader rank want to consume global metrics result.
|
|
252
|
+
should_validate_update (bool): whether to check the inputs of update() and skip
|
|
253
|
+
update if the inputs are invalid. Invalid inputs include the case where all
|
|
254
|
+
examples have 0 weights for a batch
|
|
255
|
+
process_group (Optional[ProcessGroup]): the process group used for the
|
|
256
|
+
communication. Will use the default process group if not specified.
|
|
257
|
+
|
|
258
|
+
Call Args:
|
|
259
|
+
Not supported.
|
|
260
|
+
|
|
261
|
+
Returns:
|
|
262
|
+
Not supported.
|
|
263
|
+
|
|
264
|
+
Example::
|
|
265
|
+
|
|
266
|
+
ne = NEMetric(
|
|
267
|
+
world_size=4,
|
|
268
|
+
my_rank=0,
|
|
269
|
+
batch_size=128,
|
|
270
|
+
tasks=DefaultTaskInfo,
|
|
271
|
+
)
|
|
272
|
+
"""
|
|
273
|
+
_computation_class: Type[RecMetricComputation]
|
|
274
|
+
_namespace: MetricNamespaceBase
|
|
275
|
+
_metrics_computations: nn.ModuleList
|
|
276
|
+
|
|
277
|
+
_tasks: List[RecTaskInfo]
|
|
278
|
+
_window_size: int
|
|
279
|
+
_tasks_iter: Callable[[str], ComputeIterType]
|
|
280
|
+
_update_buffers: Dict[str, List[RecModelOutput]]
|
|
281
|
+
_default_weights: Dict[Tuple[int, ...], torch.Tensor]
|
|
282
|
+
|
|
283
|
+
PREDICTIONS: str = "predictions"
|
|
284
|
+
LABELS: str = "labels"
|
|
285
|
+
WEIGHTS: str = "weights"
|
|
286
|
+
|
|
287
|
+
def __init__(
|
|
288
|
+
self,
|
|
289
|
+
world_size: int,
|
|
290
|
+
my_rank: int,
|
|
291
|
+
batch_size: int,
|
|
292
|
+
tasks: List[RecTaskInfo],
|
|
293
|
+
compute_mode: RecComputeMode = RecComputeMode.UNFUSED_TASKS_COMPUTATION,
|
|
294
|
+
window_size: int = 100,
|
|
295
|
+
fused_update_limit: int = 0,
|
|
296
|
+
compute_on_all_ranks: bool = False,
|
|
297
|
+
should_validate_update: bool = False,
|
|
298
|
+
process_group: Optional[dist.ProcessGroup] = None,
|
|
299
|
+
**kwargs: Any,
|
|
300
|
+
) -> None:
|
|
301
|
+
# TODO(stellaya): consider to inherit from TorchMetrics.Metric or
|
|
302
|
+
# TorchMetrics.MetricCollection.
|
|
303
|
+
if (
|
|
304
|
+
compute_mode == RecComputeMode.FUSED_TASKS_COMPUTATION
|
|
305
|
+
and fused_update_limit > 0
|
|
306
|
+
):
|
|
307
|
+
raise ValueError(
|
|
308
|
+
"The fused tasks computation and the fused update cannot be set at the same time"
|
|
309
|
+
)
|
|
310
|
+
super().__init__()
|
|
311
|
+
self._world_size = world_size
|
|
312
|
+
self._my_rank = my_rank
|
|
313
|
+
self._window_size = math.ceil(window_size / world_size)
|
|
314
|
+
self._batch_size = batch_size
|
|
315
|
+
self._tasks = tasks
|
|
316
|
+
self._compute_mode = compute_mode
|
|
317
|
+
self._fused_update_limit = fused_update_limit
|
|
318
|
+
self._should_validate_update = should_validate_update
|
|
319
|
+
self._default_weights = {}
|
|
320
|
+
self._update_buffers = {
|
|
321
|
+
self.PREDICTIONS: [],
|
|
322
|
+
self.LABELS: [],
|
|
323
|
+
self.WEIGHTS: [],
|
|
324
|
+
}
|
|
325
|
+
if compute_mode == RecComputeMode.FUSED_TASKS_COMPUTATION:
|
|
326
|
+
n_metrics = 1
|
|
327
|
+
task_per_metric = len(self._tasks)
|
|
328
|
+
self._tasks_iter = self._fused_tasks_iter
|
|
329
|
+
else:
|
|
330
|
+
n_metrics = len(self._tasks)
|
|
331
|
+
task_per_metric = 1
|
|
332
|
+
self._tasks_iter = self._unfused_tasks_iter
|
|
333
|
+
|
|
334
|
+
self._metrics_computations: nn.ModuleList = nn.ModuleList(
|
|
335
|
+
[
|
|
336
|
+
# This Pyre error seems to be Pyre's bug as it can be inferred by mypy
|
|
337
|
+
# according to https://github.com/python/mypy/issues/3048.
|
|
338
|
+
# pyre-fixme[45]: Cannot instantiate abstract class `RecMetricCoputation`.
|
|
339
|
+
self._computation_class(
|
|
340
|
+
my_rank,
|
|
341
|
+
batch_size,
|
|
342
|
+
task_per_metric,
|
|
343
|
+
self._window_size,
|
|
344
|
+
compute_on_all_ranks,
|
|
345
|
+
self._should_validate_update,
|
|
346
|
+
process_group,
|
|
347
|
+
**kwargs,
|
|
348
|
+
)
|
|
349
|
+
for _ in range(n_metrics)
|
|
350
|
+
]
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
# TODO(stellaya): Refactor the _[fused, unfused]_tasks_iter methods and replace the
|
|
354
|
+
# compute_scope str input with an enum
|
|
355
|
+
def _fused_tasks_iter(self, compute_scope: str) -> ComputeIterType:
|
|
356
|
+
assert len(self._metrics_computations) == 1
|
|
357
|
+
self._metrics_computations[0].pre_compute()
|
|
358
|
+
for metric_report in getattr(
|
|
359
|
+
self._metrics_computations[0], compute_scope + "compute"
|
|
360
|
+
)():
|
|
361
|
+
for task, metric_value, has_valid_update in zip(
|
|
362
|
+
self._tasks,
|
|
363
|
+
metric_report.value,
|
|
364
|
+
self._metrics_computations[0].has_valid_update
|
|
365
|
+
if self._should_validate_update
|
|
366
|
+
else itertools.repeat(
|
|
367
|
+
1
|
|
368
|
+
), # has_valid_update > 0 means the update is valid
|
|
369
|
+
):
|
|
370
|
+
# The attribute has_valid_update is a tensor whose length equals to the
|
|
371
|
+
# number of tasks. Each value in it is corresponding to whether a task
|
|
372
|
+
# has valid updates or not.
|
|
373
|
+
# If for a task there's no valid updates, the calculated metric_value
|
|
374
|
+
# will be meaningless, so we mask it with the default value, i.e. 0.
|
|
375
|
+
valid_metric_value = (
|
|
376
|
+
metric_value
|
|
377
|
+
if has_valid_update > 0
|
|
378
|
+
else torch.zeros_like(metric_value)
|
|
379
|
+
)
|
|
380
|
+
yield task, metric_report.name, valid_metric_value, compute_scope + metric_report.metric_prefix.value
|
|
381
|
+
|
|
382
|
+
def _unfused_tasks_iter(self, compute_scope: str) -> ComputeIterType:
|
|
383
|
+
for task, metric_computation in zip(self._tasks, self._metrics_computations):
|
|
384
|
+
metric_computation.pre_compute()
|
|
385
|
+
for metric_report in getattr(
|
|
386
|
+
metric_computation, compute_scope + "compute"
|
|
387
|
+
)():
|
|
388
|
+
# The attribute has_valid_update is a tensor with only 1 value
|
|
389
|
+
# corresponding to whether the task has valid updates or not.
|
|
390
|
+
# If there's no valid update, the calculated metric_report.value
|
|
391
|
+
# will be meaningless, so we mask it with the default value, i.e. 0.
|
|
392
|
+
valid_metric_value = (
|
|
393
|
+
metric_report.value
|
|
394
|
+
if not self._should_validate_update
|
|
395
|
+
or metric_computation.has_valid_update[0] > 0
|
|
396
|
+
else torch.zeros_like(metric_report.value)
|
|
397
|
+
)
|
|
398
|
+
yield task, metric_report.name, valid_metric_value, compute_scope + metric_report.metric_prefix.value
|
|
399
|
+
|
|
400
|
+
def _fuse_update_buffers(self) -> Dict[str, RecModelOutput]:
|
|
401
|
+
def fuse(outputs: List[RecModelOutput]) -> RecModelOutput:
|
|
402
|
+
assert len(outputs) > 0
|
|
403
|
+
if isinstance(outputs[0], torch.Tensor):
|
|
404
|
+
return torch.cat(cast(List[torch.Tensor], outputs))
|
|
405
|
+
else:
|
|
406
|
+
task_outputs: Dict[str, List[torch.Tensor]] = defaultdict(list)
|
|
407
|
+
for output in outputs:
|
|
408
|
+
assert isinstance(output, dict)
|
|
409
|
+
for task_name, tensor in output.items():
|
|
410
|
+
task_outputs[task_name].append(tensor)
|
|
411
|
+
return {
|
|
412
|
+
name: torch.cat(tensors) for name, tensors in task_outputs.items()
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
ret: Dict[str, RecModelOutput] = {}
|
|
416
|
+
for key, output_list in self._update_buffers.items():
|
|
417
|
+
if len(output_list) > 0:
|
|
418
|
+
ret[key] = fuse(output_list)
|
|
419
|
+
else:
|
|
420
|
+
assert key == self.WEIGHTS
|
|
421
|
+
output_list.clear()
|
|
422
|
+
return ret
|
|
423
|
+
|
|
424
|
+
def _check_fused_update(self, force: bool) -> None:
|
|
425
|
+
if self._fused_update_limit <= 0:
|
|
426
|
+
return
|
|
427
|
+
if len(self._update_buffers[self.PREDICTIONS]) == 0:
|
|
428
|
+
return
|
|
429
|
+
if (
|
|
430
|
+
not force
|
|
431
|
+
and len(self._update_buffers[self.PREDICTIONS]) < self._fused_update_limit
|
|
432
|
+
):
|
|
433
|
+
return
|
|
434
|
+
fused_arguments = self._fuse_update_buffers()
|
|
435
|
+
self._update(
|
|
436
|
+
predictions=fused_arguments[self.PREDICTIONS],
|
|
437
|
+
labels=fused_arguments[self.LABELS],
|
|
438
|
+
weights=fused_arguments.get(self.WEIGHTS, None),
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
def _create_default_weights(self, predictions: torch.Tensor) -> torch.Tensor:
|
|
442
|
+
# pyre-fixme[6]: For 1st param expected `Tuple[int, ...]` but got `Size`.
|
|
443
|
+
weights = self._default_weights.get(predictions.size(), None)
|
|
444
|
+
if weights is None:
|
|
445
|
+
weights = torch.ones_like(predictions)
|
|
446
|
+
# pyre-fixme[6]: For 1st param expected `Tuple[int, ...]` but got `Size`.
|
|
447
|
+
self._default_weights[predictions.size()] = weights
|
|
448
|
+
return weights
|
|
449
|
+
|
|
450
|
+
def _check_nonempty_weights(self, weights: torch.Tensor) -> torch.Tensor:
|
|
451
|
+
return torch.gt(torch.count_nonzero(weights, dim=-1), 0)
|
|
452
|
+
|
|
453
|
+
def _update(
|
|
454
|
+
self,
|
|
455
|
+
*,
|
|
456
|
+
predictions: RecModelOutput,
|
|
457
|
+
labels: RecModelOutput,
|
|
458
|
+
weights: Optional[RecModelOutput],
|
|
459
|
+
) -> None:
|
|
460
|
+
with torch.no_grad():
|
|
461
|
+
if self._compute_mode == RecComputeMode.FUSED_TASKS_COMPUTATION:
|
|
462
|
+
assert isinstance(predictions, torch.Tensor)
|
|
463
|
+
# Reshape the predictions to size([len(self._tasks), self._batch_size])
|
|
464
|
+
predictions = predictions.view(-1, self._batch_size)
|
|
465
|
+
assert isinstance(labels, torch.Tensor)
|
|
466
|
+
labels = labels.view(-1, self._batch_size)
|
|
467
|
+
if weights is None:
|
|
468
|
+
weights = self._create_default_weights(predictions)
|
|
469
|
+
else:
|
|
470
|
+
assert isinstance(weights, torch.Tensor)
|
|
471
|
+
weights = weights.view(-1, self._batch_size)
|
|
472
|
+
if self._should_validate_update:
|
|
473
|
+
# has_valid_weights is a tensor of bool whose length equals to the number
|
|
474
|
+
# of tasks. Each value in it is corresponding to whether the weights
|
|
475
|
+
# are valid, i.e. are set to non-zero values for that task in this update.
|
|
476
|
+
# If has_valid_weights are Falses for all the tasks, we just ignore this
|
|
477
|
+
# update.
|
|
478
|
+
has_valid_weights = self._check_nonempty_weights(weights)
|
|
479
|
+
if torch.any(has_valid_weights):
|
|
480
|
+
self._metrics_computations[0].update(
|
|
481
|
+
predictions=predictions, labels=labels, weights=weights
|
|
482
|
+
)
|
|
483
|
+
self._metrics_computations[0].has_valid_update.logical_or_(
|
|
484
|
+
has_valid_weights
|
|
485
|
+
)
|
|
486
|
+
else:
|
|
487
|
+
self._metrics_computations[0].update(
|
|
488
|
+
predictions=predictions, labels=labels, weights=weights
|
|
489
|
+
)
|
|
490
|
+
else:
|
|
491
|
+
for task, metric_ in zip(self._tasks, self._metrics_computations):
|
|
492
|
+
if task.name not in predictions:
|
|
493
|
+
continue
|
|
494
|
+
if torch.numel(predictions[task.name]) == 0:
|
|
495
|
+
assert torch.numel(labels[task.name]) == 0
|
|
496
|
+
assert weights is None or torch.numel(weights[task.name]) == 0
|
|
497
|
+
continue
|
|
498
|
+
# Reshape the predictions to size([1, self._batch_size])
|
|
499
|
+
task_predictions = predictions[task.name].view(1, -1)
|
|
500
|
+
task_labels = labels[task.name].view(1, -1)
|
|
501
|
+
if weights is None:
|
|
502
|
+
task_weights = self._create_default_weights(task_predictions)
|
|
503
|
+
else:
|
|
504
|
+
task_weights = weights[task.name].view(1, -1)
|
|
505
|
+
if self._should_validate_update:
|
|
506
|
+
# has_valid_weights is a tensor with only 1 value corresponding to
|
|
507
|
+
# whether the weights are valid, i.e. are set to non-zero values for
|
|
508
|
+
# the task in this update.
|
|
509
|
+
# If has_valid_update[0] is False, we just ignore this update.
|
|
510
|
+
has_valid_weights = self._check_nonempty_weights(task_weights)
|
|
511
|
+
if has_valid_weights[0]:
|
|
512
|
+
metric_.has_valid_update.logical_or_(has_valid_weights)
|
|
513
|
+
else:
|
|
514
|
+
continue
|
|
515
|
+
metric_.update(
|
|
516
|
+
predictions=task_predictions,
|
|
517
|
+
labels=task_labels,
|
|
518
|
+
weights=task_weights,
|
|
519
|
+
)
|
|
520
|
+
|
|
521
|
+
def update(
|
|
522
|
+
self,
|
|
523
|
+
*,
|
|
524
|
+
predictions: RecModelOutput,
|
|
525
|
+
labels: RecModelOutput,
|
|
526
|
+
weights: Optional[RecModelOutput],
|
|
527
|
+
) -> None:
|
|
528
|
+
if self._fused_update_limit > 0:
|
|
529
|
+
self._update_buffers[self.PREDICTIONS].append(predictions)
|
|
530
|
+
self._update_buffers[self.LABELS].append(labels)
|
|
531
|
+
if weights is not None:
|
|
532
|
+
self._update_buffers[self.WEIGHTS].append(weights)
|
|
533
|
+
self._check_fused_update(force=False)
|
|
534
|
+
else:
|
|
535
|
+
self._update(predictions=predictions, labels=labels, weights=weights)
|
|
536
|
+
|
|
537
|
+
# The implementation of compute is very similar to local_compute, but compute overwrites
|
|
538
|
+
# the abstract method compute in torchmetrics.Metric, which is wrapped by _wrap_compute
|
|
539
|
+
def compute(self) -> Dict[str, torch.Tensor]:
|
|
540
|
+
self._check_fused_update(force=True)
|
|
541
|
+
ret = {}
|
|
542
|
+
for task, metric_name, metric_value, prefix in self._tasks_iter(""):
|
|
543
|
+
metric_key = compose_metric_key(
|
|
544
|
+
self._namespace, task.name, metric_name, prefix
|
|
545
|
+
)
|
|
546
|
+
ret[metric_key] = metric_value
|
|
547
|
+
return ret
|
|
548
|
+
|
|
549
|
+
def local_compute(self) -> Dict[str, torch.Tensor]:
|
|
550
|
+
self._check_fused_update(force=True)
|
|
551
|
+
ret = {}
|
|
552
|
+
for task, metric_name, metric_value, prefix in self._tasks_iter("local_"):
|
|
553
|
+
metric_key = compose_metric_key(
|
|
554
|
+
self._namespace, task.name, metric_name, prefix
|
|
555
|
+
)
|
|
556
|
+
ret[metric_key] = metric_value
|
|
557
|
+
return ret
|
|
558
|
+
|
|
559
|
+
def sync(self) -> None:
|
|
560
|
+
for computation in self._metrics_computations:
|
|
561
|
+
computation.sync()
|
|
562
|
+
|
|
563
|
+
def unsync(self) -> None:
|
|
564
|
+
for computation in self._metrics_computations:
|
|
565
|
+
if computation._is_synced:
|
|
566
|
+
computation.unsync()
|
|
567
|
+
|
|
568
|
+
def reset(self) -> None:
|
|
569
|
+
for computation in self._metrics_computations:
|
|
570
|
+
computation.reset()
|
|
571
|
+
|
|
572
|
+
def get_memory_usage(self) -> Dict[torch.Tensor, int]:
|
|
573
|
+
r"""Estimates the memory of the rec metric instance's
|
|
574
|
+
underlying tensors; returns the map of tensor to size
|
|
575
|
+
"""
|
|
576
|
+
tensor_map = {}
|
|
577
|
+
attributes_q = deque(self.__dict__.values())
|
|
578
|
+
while attributes_q:
|
|
579
|
+
attribute = attributes_q.popleft()
|
|
580
|
+
if isinstance(attribute, torch.Tensor):
|
|
581
|
+
tensor_map[attribute] = (
|
|
582
|
+
attribute.size().numel() * attribute.element_size()
|
|
583
|
+
)
|
|
584
|
+
elif isinstance(attribute, WindowBuffer):
|
|
585
|
+
attributes_q.extend(attribute.buffers)
|
|
586
|
+
elif isinstance(attribute, Mapping):
|
|
587
|
+
attributes_q.extend(attribute.values())
|
|
588
|
+
elif isinstance(attribute, Sequence) and not isinstance(attribute, str):
|
|
589
|
+
attributes_q.extend(attribute)
|
|
590
|
+
elif hasattr(attribute, "__dict__") and not isinstance(attribute, Enum):
|
|
591
|
+
attributes_q.extend(attribute.__dict__.values())
|
|
592
|
+
return tensor_map
|
|
593
|
+
|
|
594
|
+
# pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
|
|
595
|
+
def state_dict(
|
|
596
|
+
self,
|
|
597
|
+
destination: Optional[Dict[str, torch.Tensor]] = None,
|
|
598
|
+
prefix: str = "",
|
|
599
|
+
keep_vars: bool = False,
|
|
600
|
+
) -> Dict[str, torch.Tensor]:
|
|
601
|
+
# We need to flush the cached output to ensure checkpointing correctness.
|
|
602
|
+
self._check_fused_update(force=True)
|
|
603
|
+
destination = super().state_dict(
|
|
604
|
+
destination=destination, prefix=prefix, keep_vars=keep_vars
|
|
605
|
+
)
|
|
606
|
+
return self._metrics_computations.state_dict(
|
|
607
|
+
destination=destination,
|
|
608
|
+
prefix=f"{prefix}_metrics_computations.",
|
|
609
|
+
keep_vars=keep_vars,
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
class RecMetricList(nn.Module):
|
|
614
|
+
"""
|
|
615
|
+
A list module to encapulate multiple RecMetric instances and provide the
|
|
616
|
+
same interfaces as RecMetric.
|
|
617
|
+
|
|
618
|
+
Args:
|
|
619
|
+
rec_metrics (List[RecMetric]: the list of the input RecMetrics.
|
|
620
|
+
|
|
621
|
+
Call Args:
|
|
622
|
+
Not supported.
|
|
623
|
+
|
|
624
|
+
Returns:
|
|
625
|
+
Not supported.
|
|
626
|
+
|
|
627
|
+
Example::
|
|
628
|
+
|
|
629
|
+
ne = NEMetric(
|
|
630
|
+
world_size=4,
|
|
631
|
+
my_rank=0,
|
|
632
|
+
batch_size=128,
|
|
633
|
+
tasks=DefaultTaskInfo
|
|
634
|
+
)
|
|
635
|
+
metrics = RecMetricList([ne])
|
|
636
|
+
"""
|
|
637
|
+
|
|
638
|
+
rec_metrics: nn.ModuleList
|
|
639
|
+
|
|
640
|
+
def __init__(self, rec_metrics: List[RecMetric]) -> None:
|
|
641
|
+
# TODO(stellaya): consider to inherit from TorchMetrics.MetricCollection.
|
|
642
|
+
# The prequsite to use MetricCollection is that RecMetric inherits from
|
|
643
|
+
# TorchMetrics.Metric or TorchMetrics.MetricCollection
|
|
644
|
+
|
|
645
|
+
super().__init__()
|
|
646
|
+
self.rec_metrics = nn.ModuleList(rec_metrics)
|
|
647
|
+
|
|
648
|
+
def __len__(self) -> int:
|
|
649
|
+
return len(self.rec_metrics)
|
|
650
|
+
|
|
651
|
+
def __getitem__(self, idx: int) -> nn.Module:
|
|
652
|
+
return self.rec_metrics[idx]
|
|
653
|
+
|
|
654
|
+
def update(
|
|
655
|
+
self,
|
|
656
|
+
*,
|
|
657
|
+
predictions: RecModelOutput,
|
|
658
|
+
labels: RecModelOutput,
|
|
659
|
+
weights: RecModelOutput,
|
|
660
|
+
) -> None:
|
|
661
|
+
for metric in self.rec_metrics:
|
|
662
|
+
metric.update(predictions=predictions, labels=labels, weights=weights)
|
|
663
|
+
|
|
664
|
+
def compute(self) -> Dict[str, torch.Tensor]:
|
|
665
|
+
ret = {}
|
|
666
|
+
for metric in self.rec_metrics:
|
|
667
|
+
ret.update(metric.compute())
|
|
668
|
+
return ret
|
|
669
|
+
|
|
670
|
+
def local_compute(self) -> Dict[str, torch.Tensor]:
|
|
671
|
+
ret = {}
|
|
672
|
+
for metric in self.rec_metrics:
|
|
673
|
+
ret.update(metric.local_compute())
|
|
674
|
+
return ret
|
|
675
|
+
|
|
676
|
+
def sync(self) -> None:
|
|
677
|
+
for metric in self.rec_metrics:
|
|
678
|
+
metric.sync()
|
|
679
|
+
|
|
680
|
+
def unsync(self) -> None:
|
|
681
|
+
for metric in self.rec_metrics:
|
|
682
|
+
metric.unsync()
|
|
683
|
+
|
|
684
|
+
def reset(self) -> None:
|
|
685
|
+
for metric in self.rec_metrics:
|
|
686
|
+
metric.reset()
|