[Feature] Implement TopK wrapper class for metrics
🚀 Feature
(Follow up to #3530 and #2631)
After getting in the HitRate@top_k metric for recommendation systems, it makes sense to have Recall@top_k as well. To implement this metric, as discussed we can add a top_k argument to existing Recall metric instead of creating a new class:
The idea is to use the _prepare_output method of _BasePrecision_Recall to convert our data to the required format that can then be used directly with same logic of if self._average == "samples": of Recall class:
for the true_positives, fetch the top-k indices of y_pred and gather those elements from y.
y can then also be directly be passed as actual_positives.
https://github.com/pytorch/ignite/blob/24535a0bb078398d1374657ce6f8c1f583cd467a/ignite/metrics/precision.py#L60
_, top_indices = torch.topk(y_pred, k=self._top_k, dim=1) true_positives = torch.gather(y, 1, top_k_indices)
then in https://github.com/pytorch/ignite/blob/24535a0bb078398d1374657ce6f8c1f583cd467a/ignite/metrics/recall.py#L229 we can use this same logic for final metric calculation
@rwtarpit thanks for checking this topic! Adding top_k argument can be OK, however we have to add such arg to all classification metrics where it makes sense. I wonder if it could be possible and interesting to have the API like this:
classification_metric = ...
top_k_metric = TopK(classification_metric, k=5)
top_k_metric.attach(engine)
TopK internally would override _prepare_output method and fail if the metric does not have it. We may need to make a pass and unify the internal implementations of the classification metrics where top_k can be computed and these metrics for some reason do not have _prepare_output method. What do you think?
yes this looks much better, and we can cover broader than just RecSys, basically any situation that might require top-k classification.
both Recall and Precision have _prepare_output method.
Accuracy metric don't have the _prepare_output method, but has a different class TopKCategoricalAccuracy implemented.
We can add _prepare_output to Accuracy with a pass, or port update's logic to it to unify the API.
then the wrapper can be implemented uniformly, and we can also deprecate TopKCategoricalAccuracy in future.
Sounds good to me
i am thinking of something like this:
class TopK(Metric):
def __init__(self, base_metric : Metric, k : int, **kwargs):
self.base_metric = base_metric
self.top_k = k
self._base_prepare_output = base_metric._prepare_output
self.base_metric._prepare_output = self._wrap_prepare_output
super(TopK, self).__init__(**kwargs)
def _wrap_prepare_output(self, output):
_y_pred, _y = output[0], output[1]
...
y_pred, y = ...
return self._base_prepare_output(y_pred, y)
def update(self, output):
self.base_metric.update(output)
in this way we only need to transform the input just before prepare_output of base metric.
or do you think top_k should be list[int] similar to HitRate?
i prefer it to be int only and user can define multiple like:
top1 = TopK(Recall(), k=1)
top5 = TopK(Recall(), k=5)
From implementing MRR with list[int], I think int with the TopK wrapper is cleaner. Happy to update MRR to align with whatever is decided here.
In case of top k list with 3+ values (top_k=[1, 2, 3, 4, 5]) like in HitRate, it can be bulky to code:
recall = Recall()
metrics = [TopK(recall, k=k) for k in range(1, 6)]
# + attach metrics to an engine, maybe using MetricGroup.
and also the metric input will preprocessed 5 times potentially containing redundant ops. If we can support the list of int in TopK wrapper it would be really great from user UX. What do you think?
performing same ops for everytime does seem redundant. if we go with list[int], simple logic like used in HitRate might not work for every classification metric. I am thinking of something where we can maintain state for every k in list without repeating any common operation. I'll try to come up with a bare minimum prototype to explain in much better way
the redundant ops that are common in all metrics mainly are: https://github.com/pytorch/ignite/blob/5901ed499451cfd90de1d2923c52efdd17360732/ignite/metrics/precision.py#L412
self._check_shape(output)
self._check_type(output)
y_pred, y, correct = self._prepare_output(output)
what if we port _check_shape and _check_type in _prepare_ouput itself of such metrics(Recall,Precision), and in TopK's _wrap_prepare_output we would call these checks only once per batch before using the actual prepare_output logic. This also maintains backward compatibility.
Another concern here is how we can handle states of metrics for different k. we may either have to make deepcopy of metrics or use dict. Really haven't thought about this as of now. If we go with deepcopy then creating as many copies as k doesn't seem to be any good. with dict we would need to maintain states of each k with all the attributes(numerator,denom,flags,etc) and then create a single instance of metric and swap the states to calculate final results.
Also, i think recall and precision would share similar logic for TopK's _prepare_output, but Accuracy will need a seperate logic due to different denominator requirements. similarly, if we are considering to extend/generalise this wrapper to other metrics in future, i assume we would have branched logics
what do you guys think @vfdev-5 @steaphenai ?
what if we port _check_shape and _check_type in _prepare_ouput itself of such metrics(Recall,Precision), and in TopK's _wrap_prepare_output we would call these checks only once per batch before using the actual prepare_output logic. This also maintains backward compatibility.
What do you mean by porting the methods?
Another concern here is how we can handle states of metrics for different k. we may either have to make deepcopy of metrics or use dict. Really haven't thought about this as of now. If we go with deepcopy then creating as many copies as k doesn't seem to be any good. with dict we would need to maintain states of each k with all the attributes(numerator,denom,flags,etc) and then create a single instance of metric and swap the states to calculate final results.
Using dict for that is ok to me. I do not think we'll have that much attributes to store: numerator, denom What flags you meant in your sentence:
(numerator,denom,flags,etc)
Also, i think recall and precision would share similar logic for TopK's _prepare_output, but Accuracy will need a seperate logic due to different denominator requirements. similarly, if we are considering to extend/generalise this wrapper to other metrics in future, i assume we would have branched logics
Yes, we need a bit more careful design of that.
Thanks for working on this feature @rwtarpit !
https://github.com/pytorch/ignite/blob/ca3371f30cf3f2105f46492898188147dfccb50b/ignite/metrics/precision.py#L412-L416
currently we call _check_shape and _check_type in update method of metrics before the _prepare_output method. the idea is to bypass these redundant calls. for the same batch we wouldn't want these to be called for each k seperately.
though i rechecked my previous idea of porting these checks into _prepare_output but it really doesn't fix anything. i'll try to look for something to skip these checks.
let me know if you could find a way for this!!
by flags i meant the meta data for the metric, but i think _state_dict_all_req_keys will handle it :
https://github.com/pytorch/ignite/blob/ca3371f30cf3f2105f46492898188147dfccb50b/ignite/metrics/precision.py#L16
ignite/ignite/metrics/precision.py
Lines 412 to 416 in ca3371f
self._check_shape(output) self._check_type(output) y_pred, y, correct = self._prepare_output(output)
if self._average == "samples": currently we call
_check_shapeand_check_typeinupdatemethod of metrics before the_prepare_outputmethod. the idea is to bypass these redundant calls. for the same batch we wouldn't want these to be called for eachkseperately. though i rechecked my previous idea of porting these checks into _prepare_output but it really doesn't fix anything. i'll try to look for something to skip these checks. let me know if you could find a way for this!!by flags i meant the meta data for the metric, but i think
_state_dict_all_req_keyswill handle it :ignite/ignite/metrics/precision.py
Line 16 in ca3371f
_state_dict_all_req_keys = ("_numerator", "_denominator", "_weight", "_updated")
Maybe we can centralize _check_shape, _check_type, and the top k computation inside TopK.update , run them once per batch, and then reuse preprocessed tensors for each k. We could maintain per-k states via a dict to avoid redundant ops, which would keep preprocessing efficient. What do you think?
yes, maybe we can add a flag that makes sure that the checks run only once the batch. this flag will only be raised from TopK, so metrics work as normal when called without the wrapper:
# in Base metric's update
def update(self, output):
if not getattr(self, '_skip_checks', False):
self._check_shape(output)
self._check_type(output)
y_pred, y, correct = self._prepare_output(output)
...
and then TopK update can be modelled like this maybe:
class TopK(Metric):
...
def update(self, output):
self._base_metric._check_shape(output)
self._base_metric._check_type(output)
self._base_metric._skip_checks = True
output = self._wrap_prepare_output(output)
# then dispatch processed input to base metric's update for each k
...
self._base_metric._skip_checks = False
# removes the flag for next batch
this seems much more feasible if we incorporate the other ideas discussed above?