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,358 @@
|
|
|
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 logging
|
|
12
|
+
from typing import Any, Dict, List, Optional, Type, Union
|
|
13
|
+
|
|
14
|
+
import torch
|
|
15
|
+
import torch.distributed as dist
|
|
16
|
+
import torch.nn as nn
|
|
17
|
+
from torchrec.metrics.auc import AUCMetric
|
|
18
|
+
from torchrec.metrics.calibration import CalibrationMetric
|
|
19
|
+
from torchrec.metrics.ctr import CTRMetric
|
|
20
|
+
from torchrec.metrics.metrics_config import (
|
|
21
|
+
MetricsConfig,
|
|
22
|
+
RecMetricEnum,
|
|
23
|
+
RecMetricEnumBase,
|
|
24
|
+
RecTaskInfo,
|
|
25
|
+
StateMetricEnum,
|
|
26
|
+
)
|
|
27
|
+
from torchrec.metrics.metrics_namespace import (
|
|
28
|
+
compose_customized_metric_key,
|
|
29
|
+
compose_metric_namespace,
|
|
30
|
+
MetricNamespace,
|
|
31
|
+
)
|
|
32
|
+
from torchrec.metrics.model_utils import parse_task_model_outputs
|
|
33
|
+
from torchrec.metrics.mse import MSEMetric
|
|
34
|
+
from torchrec.metrics.ne import NEMetric
|
|
35
|
+
from torchrec.metrics.rec_metric import RecMetric, RecMetricList
|
|
36
|
+
from torchrec.metrics.throughput import ThroughputMetric
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
logger: logging.Logger = logging.getLogger(__name__)
|
|
40
|
+
|
|
41
|
+
REC_METRICS_MAPPING: Dict[RecMetricEnumBase, Type[RecMetric]] = {
|
|
42
|
+
RecMetricEnum.NE: NEMetric,
|
|
43
|
+
RecMetricEnum.CTR: CTRMetric,
|
|
44
|
+
RecMetricEnum.CALIBRATION: CalibrationMetric,
|
|
45
|
+
RecMetricEnum.AUC: AUCMetric,
|
|
46
|
+
RecMetricEnum.MSE: MSEMetric,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# Label used for emitting model metrics to the coresponding trainer publishers.
|
|
51
|
+
MODEL_METRIC_LABEL: str = "model"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
MEMORY_AVG_WARNING_PERCENTAGE = 20
|
|
55
|
+
MEMORY_AVG_WARNING_WARMUP = 100
|
|
56
|
+
|
|
57
|
+
MetricValue = Union[torch.Tensor, float]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class StateMetric(abc.ABC):
|
|
61
|
+
"""
|
|
62
|
+
The interface of state metrics for a component (e.g., optimizer, qat).
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
@abc.abstractmethod
|
|
66
|
+
def get_metrics(self) -> Dict[str, MetricValue]:
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class RecMetricModule(nn.Module):
|
|
71
|
+
r"""
|
|
72
|
+
For the current recommendation models, we assume there will be three
|
|
73
|
+
types of metrics, 1.) RecMetric, 2.) Throughput, 3.) StateMetric.
|
|
74
|
+
|
|
75
|
+
RecMetric is a metric that is computed from the model outputs (labels,
|
|
76
|
+
predictions, weights).
|
|
77
|
+
|
|
78
|
+
Throughput is being a standalone type as its unique characteristic, time-based.
|
|
79
|
+
|
|
80
|
+
StateMetric is a metric that is computed based on a model componenet
|
|
81
|
+
(e.g., Optimizer) internal logic.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
batch_size (int): batch size used by this trainer.
|
|
85
|
+
world_size (int): the number of trainers.
|
|
86
|
+
rec_tasks (Optional[List[RecTaskInfo]]): the information of the model tasks.
|
|
87
|
+
rec_metrics (Optional[RecMetricList]): the list of the RecMetrics.
|
|
88
|
+
throughput_metric (Optional[ThroughputMetric]): the ThroughputMetric.
|
|
89
|
+
state_metrics (Optional[Dict[str, StateMetric]]): the dict of StateMetrics.
|
|
90
|
+
compute_interval_steps (int): the intervals between two compute calls in the unit of batch number
|
|
91
|
+
memory_usage_limit_mb (float): the memory usage limit for OOM check
|
|
92
|
+
|
|
93
|
+
Call Args:
|
|
94
|
+
Not supported.
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
Not supported.
|
|
98
|
+
|
|
99
|
+
Example:
|
|
100
|
+
>>> config = dataclasses.replace(
|
|
101
|
+
>>> DefaultMetricsConfig, state_metrics=[StateMetricEnum.OPTIMIZERS]
|
|
102
|
+
>>> )
|
|
103
|
+
>>>
|
|
104
|
+
>>> metricModule = generate_metric_module(
|
|
105
|
+
>>> metric_class=RecMetricModule,
|
|
106
|
+
>>> metrics_config=config,
|
|
107
|
+
>>> batch_size=128,
|
|
108
|
+
>>> world_size=64,
|
|
109
|
+
>>> my_rank=0,
|
|
110
|
+
>>> state_metrics_mapping={StateMetricEnum.OPTIMIZERS: mock_optimizer},
|
|
111
|
+
>>> device=torch.device("cpu"),
|
|
112
|
+
>>> pg=dist.new_group([0]),
|
|
113
|
+
>>> )
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
batch_size: int
|
|
117
|
+
world_size: int
|
|
118
|
+
rec_tasks: List[RecTaskInfo]
|
|
119
|
+
rec_metrics: RecMetricList
|
|
120
|
+
throughput_metric: Optional[ThroughputMetric]
|
|
121
|
+
state_metrics: Dict[str, StateMetric]
|
|
122
|
+
memory_usage_limit_mb: float
|
|
123
|
+
memory_usage_mb_avg: float
|
|
124
|
+
oom_count: int
|
|
125
|
+
compute_count: int
|
|
126
|
+
|
|
127
|
+
def __init__(
|
|
128
|
+
self,
|
|
129
|
+
batch_size: int,
|
|
130
|
+
world_size: int,
|
|
131
|
+
rec_tasks: Optional[List[RecTaskInfo]] = None,
|
|
132
|
+
rec_metrics: Optional[RecMetricList] = None,
|
|
133
|
+
throughput_metric: Optional[ThroughputMetric] = None,
|
|
134
|
+
state_metrics: Optional[Dict[str, StateMetric]] = None,
|
|
135
|
+
compute_interval_steps: int = 100,
|
|
136
|
+
memory_usage_limit_mb: float = 512,
|
|
137
|
+
) -> None:
|
|
138
|
+
super().__init__()
|
|
139
|
+
self.rec_tasks = rec_tasks if rec_tasks else []
|
|
140
|
+
self.rec_metrics = rec_metrics if rec_metrics else RecMetricList([])
|
|
141
|
+
self.throughput_metric = throughput_metric
|
|
142
|
+
self.state_metrics = state_metrics if state_metrics else {}
|
|
143
|
+
self.trained_batches: int = 0
|
|
144
|
+
self.batch_size = batch_size
|
|
145
|
+
self.world_size = world_size
|
|
146
|
+
self.memory_usage_limit_mb = memory_usage_limit_mb
|
|
147
|
+
self.memory_usage_mb_avg = 0.0
|
|
148
|
+
self.oom_count = 0
|
|
149
|
+
self.compute_count = 0
|
|
150
|
+
self.compute_interval_steps = compute_interval_steps
|
|
151
|
+
|
|
152
|
+
def get_memory_usage(self) -> int:
|
|
153
|
+
r"""Total memory of unique RecMetric tensors in bytes"""
|
|
154
|
+
total = {}
|
|
155
|
+
for metric in self.rec_metrics.rec_metrics:
|
|
156
|
+
total.update(metric.get_memory_usage())
|
|
157
|
+
return sum(total.values())
|
|
158
|
+
|
|
159
|
+
def check_memory_usage(self, compute_count: int) -> None:
|
|
160
|
+
memory_usage_mb = self.get_memory_usage() / (10**6)
|
|
161
|
+
if memory_usage_mb > self.memory_usage_limit_mb:
|
|
162
|
+
self.oom_count += 1
|
|
163
|
+
logger.warning(
|
|
164
|
+
f"MetricModule is using {memory_usage_mb}MB. "
|
|
165
|
+
f"This is larger than the limit{self.memory_usage_limit_mb}MB. "
|
|
166
|
+
f"This is the f{self.oom_count}th OOM."
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
if (
|
|
170
|
+
compute_count > MEMORY_AVG_WARNING_WARMUP
|
|
171
|
+
and memory_usage_mb
|
|
172
|
+
> self.memory_usage_mb_avg * ((100 + MEMORY_AVG_WARNING_PERCENTAGE) / 100)
|
|
173
|
+
):
|
|
174
|
+
logger.warning(
|
|
175
|
+
f"MetricsModule is using more than {MEMORY_AVG_WARNING_PERCENTAGE}% of "
|
|
176
|
+
f"the average memory usage. Current usage: {memory_usage_mb}MB."
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
self.memory_usage_mb_avg = (
|
|
180
|
+
self.memory_usage_mb_avg * (compute_count - 1) + memory_usage_mb
|
|
181
|
+
) / compute_count
|
|
182
|
+
|
|
183
|
+
def _update_rec_metrics(self, model_out: Dict[str, torch.Tensor]) -> None:
|
|
184
|
+
r"""the internal update function to parse the model output.
|
|
185
|
+
Override this function if the implementation cannot support
|
|
186
|
+
the model output format.
|
|
187
|
+
"""
|
|
188
|
+
if self.rec_metrics and self.rec_tasks:
|
|
189
|
+
labels, predictions, weights = parse_task_model_outputs(
|
|
190
|
+
self.rec_tasks, model_out
|
|
191
|
+
)
|
|
192
|
+
self.rec_metrics.update(
|
|
193
|
+
predictions=predictions, labels=labels, weights=weights
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
def update(self, model_out: Dict[str, torch.Tensor]) -> None:
|
|
197
|
+
r"""update() is called per batch, usually right after forward() to
|
|
198
|
+
update the local states of metrics based on the model_output.
|
|
199
|
+
|
|
200
|
+
Throughput.update() is also called due to the implementation sliding window
|
|
201
|
+
throughput.
|
|
202
|
+
"""
|
|
203
|
+
self._update_rec_metrics(model_out)
|
|
204
|
+
if self.throughput_metric:
|
|
205
|
+
self.throughput_metric.update()
|
|
206
|
+
self.trained_batches += 1
|
|
207
|
+
|
|
208
|
+
def should_compute(self) -> bool:
|
|
209
|
+
return self.trained_batches % self.compute_interval_steps == 0
|
|
210
|
+
|
|
211
|
+
def compute(self) -> Dict[str, MetricValue]:
|
|
212
|
+
r"""compute() is called when the global metrics are required, usually
|
|
213
|
+
right before logging the metrics results to the data sink.
|
|
214
|
+
"""
|
|
215
|
+
self.compute_count += 1
|
|
216
|
+
self.check_memory_usage(self.compute_count)
|
|
217
|
+
|
|
218
|
+
ret: Dict[str, MetricValue] = {}
|
|
219
|
+
if self.rec_metrics:
|
|
220
|
+
ret.update(self.rec_metrics.compute())
|
|
221
|
+
if self.throughput_metric:
|
|
222
|
+
ret.update(self.throughput_metric.compute())
|
|
223
|
+
if self.state_metrics:
|
|
224
|
+
for namespace, component in self.state_metrics.items():
|
|
225
|
+
ret.update(
|
|
226
|
+
{
|
|
227
|
+
f"{compose_customized_metric_key(namespace, metric_name)}": metric_value
|
|
228
|
+
for metric_name, metric_value in component.get_metrics().items()
|
|
229
|
+
}
|
|
230
|
+
)
|
|
231
|
+
return ret
|
|
232
|
+
|
|
233
|
+
def local_compute(self) -> Dict[str, MetricValue]:
|
|
234
|
+
r"""local_compute() is called when per-trainer metrics are required. It's
|
|
235
|
+
can be used for debugging. Currently only rec_metrics is supported.
|
|
236
|
+
"""
|
|
237
|
+
ret: Dict[str, MetricValue] = {}
|
|
238
|
+
if self.rec_metrics:
|
|
239
|
+
ret.update(self.rec_metrics.local_compute())
|
|
240
|
+
return ret
|
|
241
|
+
|
|
242
|
+
def sync(self) -> None:
|
|
243
|
+
self.rec_metrics.sync()
|
|
244
|
+
|
|
245
|
+
def unsync(self) -> None:
|
|
246
|
+
self.rec_metrics.unsync()
|
|
247
|
+
|
|
248
|
+
def reset(self) -> None:
|
|
249
|
+
self.rec_metrics.reset()
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _generate_rec_metrics(
|
|
253
|
+
metrics_config: MetricsConfig,
|
|
254
|
+
world_size: int,
|
|
255
|
+
my_rank: int,
|
|
256
|
+
batch_size: int,
|
|
257
|
+
process_group: Optional[dist.ProcessGroup] = None,
|
|
258
|
+
) -> RecMetricList:
|
|
259
|
+
rec_metrics = []
|
|
260
|
+
for metric_enum, metric_def in metrics_config.rec_metrics.items():
|
|
261
|
+
|
|
262
|
+
kwargs: Dict[str, Any] = {}
|
|
263
|
+
if metric_def and metric_def.arguments is not None:
|
|
264
|
+
kwargs = metric_def.arguments
|
|
265
|
+
|
|
266
|
+
rec_tasks: List[RecTaskInfo] = []
|
|
267
|
+
if metric_def.rec_tasks and metric_def.rec_task_indices:
|
|
268
|
+
raise ValueError(
|
|
269
|
+
"Only one of RecMetricDef.rec_tasks and RecMetricDef.rec_task_indices "
|
|
270
|
+
"should be specified."
|
|
271
|
+
)
|
|
272
|
+
if metric_def.rec_tasks:
|
|
273
|
+
rec_tasks = metric_def.rec_tasks
|
|
274
|
+
elif metric_def.rec_task_indices:
|
|
275
|
+
rec_tasks = [
|
|
276
|
+
metrics_config.rec_tasks[idx] for idx in metric_def.rec_task_indices
|
|
277
|
+
]
|
|
278
|
+
else:
|
|
279
|
+
raise ValueError(
|
|
280
|
+
"One of RecMetricDef.rec_tasks and RecMetricDef.rec_task_indices "
|
|
281
|
+
"should be a non-empty list"
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
rec_metrics.append(
|
|
285
|
+
REC_METRICS_MAPPING[metric_enum](
|
|
286
|
+
world_size=world_size,
|
|
287
|
+
my_rank=my_rank,
|
|
288
|
+
batch_size=batch_size,
|
|
289
|
+
tasks=rec_tasks,
|
|
290
|
+
compute_mode=metrics_config.rec_compute_mode,
|
|
291
|
+
window_size=metric_def.window_size,
|
|
292
|
+
fused_update_limit=metrics_config.fused_update_limit,
|
|
293
|
+
compute_on_all_ranks=metrics_config.compute_on_all_ranks,
|
|
294
|
+
should_validate_update=metrics_config.should_validate_update,
|
|
295
|
+
process_group=process_group,
|
|
296
|
+
**kwargs,
|
|
297
|
+
)
|
|
298
|
+
)
|
|
299
|
+
return RecMetricList(rec_metrics)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
STATE_METRICS_NAMESPACE_MAPPING: Dict[StateMetricEnum, MetricNamespace] = {
|
|
303
|
+
StateMetricEnum.OPTIMIZERS: MetricNamespace.OPTIMIZERS,
|
|
304
|
+
StateMetricEnum.MODEL_CONFIGURATOR: MetricNamespace.MODEL_CONFIGURATOR,
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _generate_state_metrics(
|
|
309
|
+
metrics_config: MetricsConfig,
|
|
310
|
+
state_metrics_mapping: Dict[StateMetricEnum, StateMetric],
|
|
311
|
+
) -> Dict[str, StateMetric]:
|
|
312
|
+
state_metrics: Dict[str, StateMetric] = {}
|
|
313
|
+
for metric_enum in metrics_config.state_metrics:
|
|
314
|
+
metric_namespace: Optional[
|
|
315
|
+
MetricNamespace
|
|
316
|
+
] = STATE_METRICS_NAMESPACE_MAPPING.get(metric_enum, None)
|
|
317
|
+
if metric_namespace is None:
|
|
318
|
+
raise ValueError(f"Unknown StateMetrics {metric_enum}")
|
|
319
|
+
full_namespace = compose_metric_namespace(
|
|
320
|
+
metric_namespace, str(metric_namespace)
|
|
321
|
+
)
|
|
322
|
+
state_metrics[full_namespace] = state_metrics_mapping[metric_enum]
|
|
323
|
+
return state_metrics
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def generate_metric_module(
|
|
327
|
+
metric_class: Type[RecMetricModule],
|
|
328
|
+
metrics_config: MetricsConfig,
|
|
329
|
+
batch_size: int,
|
|
330
|
+
world_size: int,
|
|
331
|
+
my_rank: int,
|
|
332
|
+
state_metrics_mapping: Dict[StateMetricEnum, StateMetric],
|
|
333
|
+
device: torch.device,
|
|
334
|
+
process_group: Optional[dist.ProcessGroup] = None,
|
|
335
|
+
) -> RecMetricModule:
|
|
336
|
+
rec_metrics = _generate_rec_metrics(
|
|
337
|
+
metrics_config, world_size, my_rank, batch_size, process_group
|
|
338
|
+
)
|
|
339
|
+
if metrics_config.throughput_metric:
|
|
340
|
+
throughput_metric = ThroughputMetric(
|
|
341
|
+
batch_size=batch_size,
|
|
342
|
+
world_size=world_size,
|
|
343
|
+
window_seconds=metrics_config.throughput_metric.window_size,
|
|
344
|
+
)
|
|
345
|
+
else:
|
|
346
|
+
throughput_metric = None
|
|
347
|
+
state_metrics = _generate_state_metrics(metrics_config, state_metrics_mapping)
|
|
348
|
+
metrics = metric_class(
|
|
349
|
+
batch_size=batch_size,
|
|
350
|
+
world_size=world_size,
|
|
351
|
+
rec_tasks=metrics_config.rec_tasks,
|
|
352
|
+
rec_metrics=rec_metrics,
|
|
353
|
+
throughput_metric=throughput_metric,
|
|
354
|
+
state_metrics=state_metrics,
|
|
355
|
+
compute_interval_steps=metrics_config.compute_interval_steps,
|
|
356
|
+
)
|
|
357
|
+
metrics.to(device)
|
|
358
|
+
return metrics
|
|
@@ -0,0 +1,152 @@
|
|
|
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
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from enum import Enum
|
|
10
|
+
from typing import Any, Dict, List, Optional
|
|
11
|
+
|
|
12
|
+
from torchrec.metrics.metrics_namespace import StrValueMixin
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class RecMetricEnumBase(StrValueMixin, Enum):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RecMetricEnum(RecMetricEnumBase):
|
|
20
|
+
NE = "ne"
|
|
21
|
+
CTR = "ctr"
|
|
22
|
+
AUC = "auc"
|
|
23
|
+
CALIBRATION = "calibration"
|
|
24
|
+
MSE = "mse"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(unsafe_hash=True, eq=True)
|
|
28
|
+
class RecTaskInfo:
|
|
29
|
+
name: str = "DefaultTask"
|
|
30
|
+
label_name: str = "label"
|
|
31
|
+
prediction_name: str = "prediction"
|
|
32
|
+
weight_name: str = "weight"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class RecComputeMode(Enum):
|
|
36
|
+
"""This Enum lists the supported computation modes for RecMetrics.
|
|
37
|
+
|
|
38
|
+
FUSED_TASKS_COMPUTATION indicates that RecMetrics will fuse the computation
|
|
39
|
+
for multiple tasks of the same metric. This can be used by modules where the
|
|
40
|
+
outputs of all the tasks are vectorized.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
FUSED_TASKS_COMPUTATION = 1
|
|
44
|
+
UNFUSED_TASKS_COMPUTATION = 2
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
_DEFAULT_WINDOW_SIZE = 10_000_000
|
|
48
|
+
_DEFAULT_THROUGHPUT_WINDOW_SECONDS = 100
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class RecMetricDef:
|
|
53
|
+
"""The dataclass that defines a RecMetric.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
rec_tasks (List[RecTaskInfo]): this and next fields specify the RecTask
|
|
57
|
+
information. ``rec_tasks`` specifies the RecTask information while
|
|
58
|
+
``rec_task_indices`` represents the indices that point to the
|
|
59
|
+
RecTask information stored in the parent ``MetricsConfig``. Only one
|
|
60
|
+
of the two fields should be specified.
|
|
61
|
+
rec_task_indices (List[int]): see the doscstring of ``rec_tasks``.
|
|
62
|
+
window_size (int): the window size for this metric.
|
|
63
|
+
arguments (Optional[Dict[str, Any]]): any propritary arguments to be used
|
|
64
|
+
by this Metric.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
rec_tasks: List[RecTaskInfo] = field(default_factory=list)
|
|
68
|
+
rec_task_indices: List[int] = field(default_factory=list)
|
|
69
|
+
window_size: int = _DEFAULT_WINDOW_SIZE
|
|
70
|
+
arguments: Optional[Dict[str, Any]] = None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class StateMetricEnum(StrValueMixin, Enum):
|
|
74
|
+
OPTIMIZERS = "optimizers"
|
|
75
|
+
MODEL_CONFIGURATOR = "model_configurator"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass
|
|
79
|
+
class ThroughputDef:
|
|
80
|
+
window_size: int = _DEFAULT_THROUGHPUT_WINDOW_SECONDS
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass
|
|
84
|
+
class MetricsConfig:
|
|
85
|
+
"""The dataclass that lists all the configurations to be used by the
|
|
86
|
+
MetricModule.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
rec_tasks (List[RecTaskInfo]): the list of RecTasks that will be shared
|
|
90
|
+
by all the metrics.
|
|
91
|
+
rec_metrics (Dict[RecMetricEnum, RecMetricDef]): the confiurations of
|
|
92
|
+
the RecMetric objects.
|
|
93
|
+
throughput_metric: (Optional[ThroughputDef]): the configurations of the ThroughputMetric
|
|
94
|
+
object.
|
|
95
|
+
rec_compute_mode (RecComputeMode): the computation mode for the
|
|
96
|
+
RecMetric objects. This will be applied to all the RecMetric
|
|
97
|
+
objects defined by ``rec_metrics``.
|
|
98
|
+
fused_update_limit (int): the maximum updates that can be fused. The
|
|
99
|
+
default is 0 which means no fusion. Setting this field to 1 is
|
|
100
|
+
logically identical to 0. If this field ii larger than 1,
|
|
101
|
+
RecMetrics will perform the actual update every ``update()`` calls.
|
|
102
|
+
state_metrics (List[StateMetricEnum]): indicates what state_metrics
|
|
103
|
+
will be enabled.
|
|
104
|
+
compute_on_all_ranks (bool): whether to compute rec metrics on all ranks.
|
|
105
|
+
If False, only compute on rank 0.
|
|
106
|
+
should_validate_update (bool): whether to check the inputs of update() and skip
|
|
107
|
+
update if the inputs are invalid. Invalid inputs include the case where all
|
|
108
|
+
examples have 0 weights for a batch.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
rec_tasks: List[RecTaskInfo] = field(default_factory=list)
|
|
112
|
+
rec_metrics: Dict[RecMetricEnum, RecMetricDef] = field(default_factory=dict)
|
|
113
|
+
throughput_metric: Optional[ThroughputDef] = None
|
|
114
|
+
rec_compute_mode: RecComputeMode = RecComputeMode.UNFUSED_TASKS_COMPUTATION
|
|
115
|
+
fused_update_limit: int = 0
|
|
116
|
+
state_metrics: List[StateMetricEnum] = field(default_factory=list)
|
|
117
|
+
# Computing metrics every step can be expsensive. This field is used to
|
|
118
|
+
# specify the computation interval. MetricModule does not use this field but
|
|
119
|
+
# the end users need to use this field to decide whether to call
|
|
120
|
+
# ``compute()``.
|
|
121
|
+
compute_interval_steps: int = 100
|
|
122
|
+
compute_on_all_ranks: bool = False
|
|
123
|
+
should_validate_update: bool = False
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
DefaultTaskInfo = RecTaskInfo(
|
|
127
|
+
name="DefaultTask",
|
|
128
|
+
label_name="label",
|
|
129
|
+
prediction_name="prediction",
|
|
130
|
+
weight_name="weight",
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
DefaultMetricsConfig = MetricsConfig(
|
|
135
|
+
rec_tasks=[DefaultTaskInfo],
|
|
136
|
+
rec_metrics={
|
|
137
|
+
RecMetricEnum.NE: RecMetricDef(
|
|
138
|
+
rec_tasks=[DefaultTaskInfo], window_size=_DEFAULT_WINDOW_SIZE
|
|
139
|
+
),
|
|
140
|
+
},
|
|
141
|
+
throughput_metric=ThroughputDef(),
|
|
142
|
+
state_metrics=[],
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
# Explicitly specifying the empty fields to avoid any mistakes cased by simply
|
|
146
|
+
# relying on the Python default values, e.g., MetricConfig().
|
|
147
|
+
EmptyMetricsConfig = MetricsConfig(
|
|
148
|
+
rec_tasks=[],
|
|
149
|
+
rec_metrics={},
|
|
150
|
+
throughput_metric=None,
|
|
151
|
+
state_metrics=[],
|
|
152
|
+
)
|
|
@@ -0,0 +1,114 @@
|
|
|
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
|
+
"""
|
|
9
|
+
The namespace definition and genration APIs for rec metrics.
|
|
10
|
+
|
|
11
|
+
The key is defined as the following format:
|
|
12
|
+
f"{namespace}-{task_name}|{metric_key}"
|
|
13
|
+
1. namespace should be one of MetricNamespace.
|
|
14
|
+
2. task_name is user-defined value. If there is no task_name, it should be
|
|
15
|
+
the same as namespace.
|
|
16
|
+
3. metric_key can be:
|
|
17
|
+
a.) One of MetricName.
|
|
18
|
+
b.) One of MetricPrefix + One of MetricName.
|
|
19
|
+
c.) Any string. This arbitrary case should happen only for reporting the
|
|
20
|
+
internal state metrics.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from enum import Enum
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class StrValueMixin:
|
|
27
|
+
def __str__(self) -> str:
|
|
28
|
+
# pyre-fixme[16]: `StrValueMixin` has no attribute `value`.
|
|
29
|
+
return self.value
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class MetricNameBase(StrValueMixin, Enum):
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class MetricName(MetricNameBase):
|
|
37
|
+
DEFAULT = ""
|
|
38
|
+
|
|
39
|
+
NE = "ne"
|
|
40
|
+
THROUGHPUT = "throughput"
|
|
41
|
+
TOTAL_EXAMPLES = "total_examples"
|
|
42
|
+
CTR = "ctr"
|
|
43
|
+
CALIBRATION = "calibration"
|
|
44
|
+
MSE = "mse"
|
|
45
|
+
RMSE = "rmse"
|
|
46
|
+
AUC = "auc"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class MetricNamespaceBase(StrValueMixin, Enum):
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class MetricNamespace(MetricNamespaceBase):
|
|
54
|
+
DEFAULT = ""
|
|
55
|
+
|
|
56
|
+
NE = "ne"
|
|
57
|
+
THROUGHPUT = "throughput"
|
|
58
|
+
CTR = "ctr"
|
|
59
|
+
CALIBRATION = "calibration"
|
|
60
|
+
MSE = "mse"
|
|
61
|
+
AUC = "auc"
|
|
62
|
+
|
|
63
|
+
OPTIMIZERS = "optimizers"
|
|
64
|
+
MODEL_CONFIGURATOR = "model_configurator"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class MetricPrefix(StrValueMixin, Enum):
|
|
68
|
+
DEFAULT = ""
|
|
69
|
+
LIFETIME = "lifetime_"
|
|
70
|
+
WINDOW = "window_"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def task_wildcard_metrics_pattern(
|
|
74
|
+
namespace: MetricNamespace,
|
|
75
|
+
metric_name: MetricName,
|
|
76
|
+
metric_prefix: MetricPrefix = MetricPrefix.DEFAULT,
|
|
77
|
+
) -> str:
|
|
78
|
+
r"""Get the re (regular expression) pattern to find a set of metrics
|
|
79
|
+
regardless task names. The motivation to have this API is from the past
|
|
80
|
+
bugs which tools hard-code the patterns but the naming change, causing
|
|
81
|
+
some testing issues.
|
|
82
|
+
"""
|
|
83
|
+
return rf"{namespace}-.+\|{metric_prefix}{metric_name}"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def compose_metric_namespace(
|
|
87
|
+
namespace: MetricNamespaceBase,
|
|
88
|
+
task_name: str,
|
|
89
|
+
) -> str:
|
|
90
|
+
r"""Get the full namespace of a metric based on the input parameters"""
|
|
91
|
+
return f"{namespace}-{task_name}"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def compose_customized_metric_key(
|
|
95
|
+
namespace: str,
|
|
96
|
+
metric_name: str,
|
|
97
|
+
) -> str:
|
|
98
|
+
r"""Get the metric key. The input are unrestricted (string) namespace and
|
|
99
|
+
metric_name. This API should only be used by compose_metric_key() and
|
|
100
|
+
state metrics as the keys of state metrics are unknown.
|
|
101
|
+
"""
|
|
102
|
+
return f"{namespace}|{metric_name}"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def compose_metric_key(
|
|
106
|
+
namespace: MetricNamespaceBase,
|
|
107
|
+
task_name: str,
|
|
108
|
+
metric_name: MetricNameBase,
|
|
109
|
+
metric_prefix: MetricPrefix = MetricPrefix.DEFAULT,
|
|
110
|
+
) -> str:
|
|
111
|
+
r"""Get the metric key based on the input parameters"""
|
|
112
|
+
return compose_customized_metric_key(
|
|
113
|
+
compose_metric_namespace(namespace, task_name), f"{metric_prefix}{metric_name}"
|
|
114
|
+
)
|
|
@@ -0,0 +1,85 @@
|
|
|
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
|
+
from typing import Dict, List, Optional, Tuple
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
from torchrec.metrics.rec_metric import RecTaskInfo
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def is_empty_signals(
|
|
15
|
+
labels: torch.Tensor,
|
|
16
|
+
predictions: torch.Tensor,
|
|
17
|
+
weights: torch.Tensor,
|
|
18
|
+
) -> bool:
|
|
19
|
+
return (
|
|
20
|
+
torch.numel(labels) <= 0
|
|
21
|
+
and torch.numel(predictions) <= 0
|
|
22
|
+
and torch.numel(weights) <= 0
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def parse_model_outputs(
|
|
27
|
+
label_name: str,
|
|
28
|
+
prediction_name: str,
|
|
29
|
+
weight_name: str,
|
|
30
|
+
model_out: Dict[str, torch.Tensor],
|
|
31
|
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]:
|
|
32
|
+
labels = model_out[label_name].squeeze()
|
|
33
|
+
if not prediction_name:
|
|
34
|
+
assert not weight_name, "weight name must be empty if prediction name is empty"
|
|
35
|
+
return (labels, None, None)
|
|
36
|
+
assert isinstance(labels, torch.Tensor)
|
|
37
|
+
predictions = model_out[prediction_name].squeeze()
|
|
38
|
+
assert isinstance(predictions, torch.Tensor)
|
|
39
|
+
weights = model_out[weight_name].squeeze()
|
|
40
|
+
assert isinstance(weights, torch.Tensor)
|
|
41
|
+
# If the model output for the metric is empty, pass it forward
|
|
42
|
+
if not (
|
|
43
|
+
(torch.numel(labels) == torch.numel(predictions))
|
|
44
|
+
and (torch.numel(labels) == torch.numel(weights))
|
|
45
|
+
):
|
|
46
|
+
assert is_empty_signals(labels, predictions, weights)
|
|
47
|
+
|
|
48
|
+
if not is_empty_signals(labels, predictions, weights):
|
|
49
|
+
assert (torch.numel(labels) == torch.numel(predictions)) and (
|
|
50
|
+
torch.numel(labels) == torch.numel(weights)
|
|
51
|
+
), (
|
|
52
|
+
"Expect the same number of elements in labels, predictions, and weights. "
|
|
53
|
+
f"Instead got {torch.numel(labels)}, {torch.numel(predictions)}, "
|
|
54
|
+
f"{torch.numel(weights)}"
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
# non-empty tensors need to have rank 1
|
|
58
|
+
if len(labels.size()) == 0:
|
|
59
|
+
labels = labels.unsqueeze(0)
|
|
60
|
+
predictions = predictions.unsqueeze(0)
|
|
61
|
+
weights = weights.unsqueeze(0)
|
|
62
|
+
|
|
63
|
+
return labels, predictions, weights
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def parse_task_model_outputs(
|
|
67
|
+
tasks: List[RecTaskInfo], model_out: Dict[str, torch.Tensor]
|
|
68
|
+
) -> Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor], Dict[str, torch.Tensor]]:
|
|
69
|
+
all_labels: Dict[str, torch.Tensor] = {}
|
|
70
|
+
all_predictions: Dict[str, torch.Tensor] = {}
|
|
71
|
+
all_weights: Dict[str, torch.Tensor] = {}
|
|
72
|
+
for task in tasks:
|
|
73
|
+
labels, predictions, weights = parse_model_outputs(
|
|
74
|
+
task.label_name, task.prediction_name, task.weight_name, model_out
|
|
75
|
+
)
|
|
76
|
+
if predictions is not None and weights is not None:
|
|
77
|
+
if not is_empty_signals(labels, predictions, weights):
|
|
78
|
+
all_labels[task.name] = labels
|
|
79
|
+
all_predictions[task.name] = predictions
|
|
80
|
+
all_weights[task.name] = weights
|
|
81
|
+
else:
|
|
82
|
+
if torch.numel(labels) > 0:
|
|
83
|
+
all_labels[task.name] = labels
|
|
84
|
+
|
|
85
|
+
return all_labels, all_predictions, all_weights
|