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,155 @@
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
+ import json
10
+ from dataclasses import asdict, dataclass
11
+ from typing import Any, Dict, List, Optional, Type
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.quantization as quant
16
+ import torchrec as trec
17
+ import torchrec.quant as trec_quant
18
+
19
+
20
+ def quantize_embeddings(
21
+ module: nn.Module,
22
+ dtype: torch.dtype,
23
+ inplace: bool,
24
+ additional_qconfig_spec_keys: Optional[List[Type[nn.Module]]] = None,
25
+ additional_mapping: Optional[Dict[Type[nn.Module], Type[nn.Module]]] = None,
26
+ ) -> nn.Module:
27
+ qconfig = quant.QConfig(
28
+ activation=quant.PlaceholderObserver,
29
+ weight=quant.PlaceholderObserver.with_args(dtype=dtype),
30
+ )
31
+ qconfig_spec: Dict[Type[nn.Module], quant.QConfig] = {
32
+ trec.EmbeddingBagCollection: qconfig,
33
+ }
34
+ mapping: Dict[Type[nn.Module], Type[nn.Module]] = {
35
+ trec.EmbeddingBagCollection: trec_quant.EmbeddingBagCollection,
36
+ }
37
+ if additional_qconfig_spec_keys is not None:
38
+ for t in additional_qconfig_spec_keys:
39
+ qconfig_spec[t] = qconfig
40
+ if additional_mapping is not None:
41
+ mapping.update(additional_mapping)
42
+ return quant.quantize_dynamic(
43
+ module,
44
+ qconfig_spec=qconfig_spec,
45
+ mapping=mapping,
46
+ inplace=inplace,
47
+ )
48
+
49
+
50
+ @dataclass
51
+ class BatchingMetadata:
52
+ """
53
+ Metadata class for batching, this should be kept in sync with the C++ definition.
54
+ """
55
+
56
+ type: str
57
+ # cpu or cuda
58
+ device: str
59
+
60
+
61
+ class PredictFactory(abc.ABC):
62
+ """
63
+ Creates a model (with already learned weights) to be used inference time.
64
+ """
65
+
66
+ @abc.abstractmethod
67
+ def create_predict_module(self) -> nn.Module:
68
+ """
69
+ Returns already sharded model with allocated weights.
70
+ state_dict() must match TransformModule.transform_state_dict().
71
+ It assumes that torch.distributed.init_process_group was already called
72
+ and will shard model according to torch.distributed.get_world_size().
73
+ """
74
+ pass
75
+
76
+ @abc.abstractmethod
77
+ def batching_metadata(self) -> Dict[str, BatchingMetadata]:
78
+ """
79
+ Returns a dict from input name to BatchingMetadata. This infomation is used for batching for input requests.
80
+ """
81
+ pass
82
+
83
+ def batching_metadata_json(self) -> str:
84
+ """
85
+ Serialize the batching metadata to JSON, for ease of parsing with torch::deploy environments.
86
+ """
87
+ return json.dumps(
88
+ {key: asdict(value) for key, value in self.batching_metadata().items()}
89
+ )
90
+
91
+ @abc.abstractmethod
92
+ def result_metadata(self) -> str:
93
+ """
94
+ Returns a string which represents the result type. This information is used for result split.
95
+ """
96
+ pass
97
+
98
+
99
+ class PredictModule(nn.Module):
100
+ """
101
+ Interface for modules to work in a torch.deploy based backend. Users should
102
+ override predict_forward to convert batch input format to module input format.
103
+
104
+ Call Args:
105
+ batch: a dict of input tensors
106
+
107
+ Returns:
108
+ output: a dict of output tensors
109
+
110
+ Args:
111
+ module: the actual predict module
112
+ device: the primary device for this module that will be used in forward calls.
113
+
114
+ Example::
115
+
116
+ module = PredictModule(torch.device("cuda", torch.cuda.current_device()))
117
+ """
118
+
119
+ def __init__(
120
+ self,
121
+ module: nn.Module,
122
+ ) -> None:
123
+ super().__init__()
124
+ self._module: nn.Module = module
125
+ # lazy init device from thread inited device guard
126
+ self._device: Optional[torch.device] = None
127
+ self._module.eval()
128
+
129
+ @property
130
+ def predict_module(
131
+ self,
132
+ ) -> nn.Module:
133
+ return self._module
134
+
135
+ @abc.abstractmethod
136
+ # pyre-fixme[3]
137
+ def predict_forward(self, batch: Dict[str, torch.Tensor]) -> Any:
138
+ pass
139
+
140
+ # pyre-fixme[3]
141
+ def forward(self, batch: Dict[str, torch.Tensor]) -> Any:
142
+ if self._device is None:
143
+ self._device = torch.device("cuda", torch.cuda.current_device())
144
+ with torch.cuda.device(self._device), torch.inference_mode():
145
+ return self.predict_forward(batch)
146
+
147
+ # pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently.
148
+ def state_dict(
149
+ self,
150
+ destination: Optional[Dict[str, Any]] = None,
151
+ prefix: str = "",
152
+ keep_vars: bool = False,
153
+ ) -> Dict[str, Any]:
154
+ # pyre-fixme[19]: Expected 0 positional arguments.
155
+ return self._module.state_dict(destination, prefix, keep_vars)
@@ -0,0 +1,103 @@
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, Union
9
+
10
+ import torch
11
+ from torch import distributed as dist
12
+ from torch.distributed import ProcessGroup
13
+ from torch.distributed._shard.sharded_tensor import Shard, ShardedTensor
14
+
15
+
16
+ def state_dict_gather(
17
+ src: Dict[str, Union[torch.Tensor, ShardedTensor]],
18
+ dst: Dict[str, torch.Tensor],
19
+ ) -> None:
20
+ """
21
+ Gathers the values of the src state_dict of the keys present in the dst state_dict. Can handle ShardedTensors in the src state_dict.
22
+
23
+ Args:
24
+ src (Dict[str, Union[torch.Tensor, ShardedTensor]]): source's state_dict for this rank
25
+ dst (Dict[str, torch.Tensor]): destination's state_dict
26
+ """
27
+ for key, dst_tensor in dst.items():
28
+ src_tensor = src[key]
29
+ if isinstance(src_tensor, ShardedTensor):
30
+ src_tensor.gather(out=dst_tensor if (dist.get_rank() == 0) else None)
31
+ elif isinstance(src_tensor, torch.Tensor):
32
+ dst_tensor.copy_(src_tensor)
33
+ else:
34
+ raise ValueError(f"Unsupported tensor {key} type {type(src_tensor)}")
35
+
36
+
37
+ def state_dict_all_gather_keys(
38
+ state_dict: Dict[str, Union[torch.Tensor, ShardedTensor]],
39
+ pg: ProcessGroup,
40
+ ) -> List[str]:
41
+ """
42
+ Gathers all the keys of the state_dict from all ranks. Can handle ShardedTensors in the state_dict.
43
+
44
+ Args:
45
+ state_dict (Dict[str, Union[torch.Tensor, ShardedTensor]]): keys of this state_dict will be gathered
46
+ pg (ProcessGroup): Process Group used for comms
47
+ """
48
+ names = list(state_dict.keys())
49
+ all_names = [None] * dist.get_world_size(pg)
50
+ dist.all_gather_object(all_names, names, pg)
51
+ deduped_names = set()
52
+ for local_names in all_names:
53
+ # pyre-ignore[16]
54
+ for name in local_names:
55
+ deduped_names.add(name)
56
+ return sorted(deduped_names)
57
+
58
+
59
+ def state_dict_to_device(
60
+ state_dict: Dict[str, Union[torch.Tensor, ShardedTensor]],
61
+ pg: ProcessGroup,
62
+ device: torch.device,
63
+ ) -> Dict[str, Union[torch.Tensor, ShardedTensor]]:
64
+ """
65
+ Moves a state_dict to a device with a process group. Can handle ShardedTensors in the state_dict.
66
+
67
+ Args:
68
+ state_dict (Dict[str, Union[torch.Tensor, ShardedTensor]]): state_dict to move
69
+ pg (ProcessGroup): Process Group used for comms
70
+ device (torch.device): device to put state_dict on
71
+ """
72
+ ret = {}
73
+ all_keys = state_dict_all_gather_keys(state_dict, pg)
74
+ for key in all_keys:
75
+ if key in state_dict:
76
+ tensor = state_dict[key]
77
+ if isinstance(tensor, ShardedTensor):
78
+ copied_shards = [
79
+ Shard.from_tensor_and_offsets(
80
+ tensor=shard.tensor.to(device),
81
+ shard_offsets=shard.metadata.shard_offsets,
82
+ rank=dist.get_rank(pg),
83
+ )
84
+ for shard in tensor.local_shards()
85
+ ]
86
+ ret[key] = ShardedTensor._init_from_local_shards(
87
+ copied_shards,
88
+ tensor.metadata().size,
89
+ process_group=pg,
90
+ )
91
+ elif isinstance(tensor, torch.Tensor):
92
+ ret[key] = tensor.to(device)
93
+ else:
94
+ raise ValueError(f"Unsupported tensor {key} type {type(tensor)}")
95
+ else:
96
+ # No state_dict entries for table-wise sharding,
97
+ # but need to follow full-sync.
98
+ ret[key] = ShardedTensor._init_from_local_shards(
99
+ [],
100
+ [],
101
+ process_group=pg,
102
+ )
103
+ return ret
File without changes
@@ -0,0 +1,159 @@
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 Any, cast, List, Optional, Type
9
+
10
+ import torch
11
+ from torchrec.metrics.metrics_namespace import MetricName, MetricNamespace, MetricPrefix
12
+ from torchrec.metrics.rec_metric import (
13
+ MetricComputationReport,
14
+ RecMetric,
15
+ RecMetricComputation,
16
+ RecMetricException,
17
+ )
18
+
19
+ PREDICTIONS = "predictions"
20
+ LABELS = "labels"
21
+ WEIGHTS = "weights"
22
+
23
+
24
+ def compute_auc(
25
+ n_tasks: int, predictions: torch.Tensor, labels: torch.Tensor, weights: torch.Tensor
26
+ ) -> torch.Tensor:
27
+ # The return values are sorted_predictions, sorted_index but only
28
+ # sorted_predictions is needed.
29
+ _, sorted_indices = torch.sort(predictions, descending=True, dim=-1)
30
+ aucs = []
31
+ for sorted_indices_i, labels_i, weights_i in zip(sorted_indices, labels, weights):
32
+ sorted_labels = torch.index_select(labels_i, dim=0, index=sorted_indices_i)
33
+ sorted_weights = torch.index_select(weights_i, dim=0, index=sorted_indices_i)
34
+ cum_fp = torch.cumsum(sorted_weights * (1.0 - sorted_labels), dim=0)
35
+ cum_tp = torch.cumsum(sorted_weights * sorted_labels, dim=0)
36
+ auc = torch.where(
37
+ cum_fp[-1] * cum_tp[-1] == 0,
38
+ 0.5, # 0.5 is the no-signal default value for auc.
39
+ torch.trapz(cum_tp, cum_fp) / cum_fp[-1] / cum_tp[-1],
40
+ )
41
+ aucs.append(auc.view(1))
42
+ return torch.cat(aucs)
43
+
44
+
45
+ def _state_reduction(state: List[torch.Tensor]) -> List[torch.Tensor]:
46
+ return [torch.cat(state, dim=1)]
47
+
48
+
49
+ class AUCMetricComputation(RecMetricComputation):
50
+ r"""
51
+ This class implementation the RecMetricComputation for AUC, i.e. Area Under the Curve.
52
+
53
+ The constructer arguments are defined in RecMetricComputation.
54
+ See the docstring of RecMetricComputation for more detail.
55
+ """
56
+
57
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
58
+ super().__init__(*args, **kwargs)
59
+ self._add_state(
60
+ PREDICTIONS,
61
+ [],
62
+ add_window_state=False,
63
+ dist_reduce_fx=_state_reduction,
64
+ persistent=False,
65
+ )
66
+ self._add_state(
67
+ LABELS,
68
+ [],
69
+ add_window_state=False,
70
+ dist_reduce_fx=_state_reduction,
71
+ persistent=False,
72
+ )
73
+ self._add_state(
74
+ WEIGHTS,
75
+ [],
76
+ add_window_state=False,
77
+ dist_reduce_fx=_state_reduction,
78
+ persistent=False,
79
+ )
80
+ self._init_states()
81
+
82
+ # The states values are set to empty lists in __init__() and reset(), and then we
83
+ # add a size (self._n_tasks, 1) tensor to each of the list as the initial values
84
+ # This is to bypass the limitation of state aggregation in TorchMetrics sync() when
85
+ # we try to checkpoint the states before update()
86
+ # The reason for using lists here is to avoid automatically stacking the tensors from
87
+ # all the trainers into one tensor in sync()
88
+ # The reason for using non-empty tensors as the first elements is to avoid the
89
+ # floating point exception thrown in sync() for aggregating empty tensors
90
+ def _init_states(self) -> None:
91
+ if len(getattr(self, PREDICTIONS)) > 0:
92
+ return
93
+
94
+ getattr(self, PREDICTIONS).append(
95
+ torch.zeros((self._n_tasks, 1), dtype=torch.double, device=self.device)
96
+ )
97
+ getattr(self, LABELS).append(
98
+ torch.zeros((self._n_tasks, 1), dtype=torch.double, device=self.device)
99
+ )
100
+ getattr(self, WEIGHTS).append(
101
+ torch.zeros((self._n_tasks, 1), dtype=torch.double, device=self.device)
102
+ )
103
+
104
+ def update(
105
+ self,
106
+ *,
107
+ predictions: Optional[torch.Tensor],
108
+ labels: torch.Tensor,
109
+ weights: Optional[torch.Tensor],
110
+ ) -> None:
111
+ if predictions is None or weights is None:
112
+ raise RecMetricException(
113
+ "Inputs 'predictions' and 'weights' should not be None for AUCMetricComputation update"
114
+ )
115
+ predictions = predictions.double()
116
+ labels = labels.double()
117
+ weights = weights.double()
118
+ num_samples = getattr(self, PREDICTIONS)[0].size(-1)
119
+ batch_size = predictions.size(-1)
120
+ start_index = max(num_samples + batch_size - self._window_size, 0)
121
+ # Using `self.predictions =` will cause Pyre errors.
122
+ getattr(self, PREDICTIONS)[0] = torch.cat(
123
+ [
124
+ cast(torch.Tensor, getattr(self, PREDICTIONS)[0])[:, start_index:],
125
+ predictions,
126
+ ],
127
+ dim=-1,
128
+ )
129
+ getattr(self, LABELS)[0] = torch.cat(
130
+ [cast(torch.Tensor, getattr(self, LABELS)[0])[:, start_index:], labels],
131
+ dim=-1,
132
+ )
133
+ getattr(self, WEIGHTS)[0] = torch.cat(
134
+ [cast(torch.Tensor, getattr(self, WEIGHTS)[0])[:, start_index:], weights],
135
+ dim=-1,
136
+ )
137
+
138
+ def _compute(self) -> List[MetricComputationReport]:
139
+ return [
140
+ MetricComputationReport(
141
+ name=MetricName.AUC,
142
+ metric_prefix=MetricPrefix.WINDOW,
143
+ value=compute_auc(
144
+ self._n_tasks,
145
+ cast(torch.Tensor, getattr(self, PREDICTIONS)[0]),
146
+ cast(torch.Tensor, getattr(self, LABELS)[0]),
147
+ cast(torch.Tensor, getattr(self, WEIGHTS)[0]),
148
+ ),
149
+ )
150
+ ]
151
+
152
+ def reset(self) -> None:
153
+ super().reset()
154
+ self._init_states()
155
+
156
+
157
+ class AUCMetric(RecMetric):
158
+ _namespace: MetricNamespace = MetricNamespace.AUC
159
+ _computation_class: Type[RecMetricComputation] = AUCMetricComputation
@@ -0,0 +1,108 @@
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 Any, cast, Dict, List, Optional, Type
9
+
10
+ import torch
11
+ from torchrec.metrics.metrics_namespace import MetricName, MetricNamespace, MetricPrefix
12
+ from torchrec.metrics.rec_metric import (
13
+ MetricComputationReport,
14
+ RecMetric,
15
+ RecMetricComputation,
16
+ RecMetricException,
17
+ )
18
+
19
+ CALIBRATION_NUM = "calibration_num"
20
+ CALIBRATION_DENOM = "calibration_denom"
21
+
22
+
23
+ def compute_calibration(
24
+ calibration_num: torch.Tensor, calibration_denom: torch.Tensor
25
+ ) -> torch.Tensor:
26
+ return torch.where(
27
+ calibration_denom <= 0.0, 0.0, calibration_num / calibration_denom
28
+ ).double()
29
+
30
+
31
+ def get_calibration_states(
32
+ labels: torch.Tensor, predictions: torch.Tensor, weights: torch.Tensor
33
+ ) -> Dict[str, torch.Tensor]:
34
+ return {
35
+ CALIBRATION_NUM: torch.sum(predictions * weights, dim=-1),
36
+ CALIBRATION_DENOM: torch.sum(labels * weights, dim=-1),
37
+ }
38
+
39
+
40
+ class CalibrationMetricComputation(RecMetricComputation):
41
+ r"""
42
+ This class implementation the RecMetricComputation for Calibration, which is the
43
+ ratio between the prediction and the labels (conversions).
44
+
45
+ The constructer arguments are defined in RecMetricComputation.
46
+ See the docstring of RecMetricComputation for more detail.
47
+ """
48
+
49
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
50
+ super().__init__(*args, **kwargs)
51
+ self._add_state(
52
+ CALIBRATION_NUM,
53
+ torch.zeros(self._n_tasks, dtype=torch.double),
54
+ add_window_state=True,
55
+ dist_reduce_fx="sum",
56
+ persistent=True,
57
+ )
58
+ self._add_state(
59
+ CALIBRATION_DENOM,
60
+ torch.zeros(self._n_tasks, dtype=torch.double),
61
+ add_window_state=True,
62
+ dist_reduce_fx="sum",
63
+ persistent=True,
64
+ )
65
+
66
+ def update(
67
+ self,
68
+ *,
69
+ predictions: Optional[torch.Tensor],
70
+ labels: torch.Tensor,
71
+ weights: Optional[torch.Tensor],
72
+ ) -> None:
73
+ if predictions is None or weights is None:
74
+ raise RecMetricException(
75
+ "Inputs 'predictions' and 'weights' should not be None for CalibrationMetricComputation update"
76
+ )
77
+ num_samples = predictions.shape[-1]
78
+ for state_name, state_value in get_calibration_states(
79
+ labels, predictions, weights
80
+ ).items():
81
+ state = getattr(self, state_name)
82
+ state += state_value
83
+ self._aggregate_window_state(state_name, state_value, num_samples)
84
+
85
+ def _compute(self) -> List[MetricComputationReport]:
86
+ return [
87
+ MetricComputationReport(
88
+ name=MetricName.CALIBRATION,
89
+ metric_prefix=MetricPrefix.LIFETIME,
90
+ value=compute_calibration(
91
+ cast(torch.Tensor, self.calibration_num),
92
+ cast(torch.Tensor, self.calibration_denom),
93
+ ),
94
+ ),
95
+ MetricComputationReport(
96
+ name=MetricName.CALIBRATION,
97
+ metric_prefix=MetricPrefix.WINDOW,
98
+ value=compute_calibration(
99
+ self.get_window_state(CALIBRATION_NUM),
100
+ self.get_window_state(CALIBRATION_DENOM),
101
+ ),
102
+ ),
103
+ ]
104
+
105
+
106
+ class CalibrationMetric(RecMetric):
107
+ _namespace: MetricNamespace = MetricNamespace.CALIBRATION
108
+ _computation_class: Type[RecMetricComputation] = CalibrationMetricComputation
@@ -0,0 +1,104 @@
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 Any, cast, Dict, List, Optional, Type
9
+
10
+ import torch
11
+ from torchrec.metrics.metrics_namespace import MetricName, MetricNamespace, MetricPrefix
12
+ from torchrec.metrics.rec_metric import (
13
+ MetricComputationReport,
14
+ RecMetric,
15
+ RecMetricComputation,
16
+ RecMetricException,
17
+ )
18
+
19
+ CTR_NUM = "ctr_num"
20
+ CTR_DENOM = "ctr_denom"
21
+
22
+
23
+ def compute_ctr(ctr_num: torch.Tensor, ctr_denom: torch.Tensor) -> torch.Tensor:
24
+ return torch.where(ctr_denom == 0.0, 0.0, ctr_num / ctr_denom).double()
25
+
26
+
27
+ def get_ctr_states(
28
+ labels: torch.Tensor, predictions: torch.Tensor, weights: torch.Tensor
29
+ ) -> Dict[str, torch.Tensor]:
30
+ return {
31
+ CTR_NUM: torch.sum(labels * weights, dim=-1),
32
+ CTR_DENOM: torch.sum(weights, dim=-1),
33
+ }
34
+
35
+
36
+ class CTRMetricComputation(RecMetricComputation):
37
+ r"""
38
+ This class implementation the RecMetricComputation for CTR, i.e. Click Through Rate,
39
+ which is the ratio between the predicted positive examples and the total examples.
40
+
41
+ The constructer arguments are defined in RecMetricComputation.
42
+ See the docstring of RecMetricComputation for more detail.
43
+ """
44
+
45
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
46
+ super().__init__(*args, **kwargs)
47
+ self._add_state(
48
+ CTR_NUM,
49
+ torch.zeros(self._n_tasks, dtype=torch.double),
50
+ add_window_state=True,
51
+ dist_reduce_fx="sum",
52
+ persistent=True,
53
+ )
54
+ self._add_state(
55
+ CTR_DENOM,
56
+ torch.zeros(self._n_tasks, dtype=torch.double),
57
+ add_window_state=True,
58
+ dist_reduce_fx="sum",
59
+ persistent=True,
60
+ )
61
+
62
+ def update(
63
+ self,
64
+ *,
65
+ predictions: Optional[torch.Tensor],
66
+ labels: torch.Tensor,
67
+ weights: Optional[torch.Tensor],
68
+ ) -> None:
69
+ if predictions is None or weights is None:
70
+ raise RecMetricException(
71
+ "Inputs 'predictions' and 'weights' should not be None for CTRMetricComputation update"
72
+ )
73
+ num_samples = predictions.shape[-1]
74
+ for state_name, state_value in get_ctr_states(
75
+ labels, predictions, weights
76
+ ).items():
77
+ state = getattr(self, state_name)
78
+ state += state_value
79
+ self._aggregate_window_state(state_name, state_value, num_samples)
80
+
81
+ def _compute(self) -> List[MetricComputationReport]:
82
+ return [
83
+ MetricComputationReport(
84
+ name=MetricName.CTR,
85
+ metric_prefix=MetricPrefix.LIFETIME,
86
+ value=compute_ctr(
87
+ cast(torch.Tensor, self.ctr_num),
88
+ cast(torch.Tensor, self.ctr_denom),
89
+ ),
90
+ ),
91
+ MetricComputationReport(
92
+ name=MetricName.CTR,
93
+ metric_prefix=MetricPrefix.WINDOW,
94
+ value=compute_ctr(
95
+ self.get_window_state(CTR_NUM),
96
+ self.get_window_state(CTR_DENOM),
97
+ ),
98
+ ),
99
+ ]
100
+
101
+
102
+ class CTRMetric(RecMetric):
103
+ _namespace: MetricNamespace = MetricNamespace.CTR
104
+ _computation_class: Type[RecMetricComputation] = CTRMetricComputation