Skip to content

Support for streaming metrics #655

Open

Description

@Dref360

Is your feature request related to a problem? Please describe.

I am using fairlearn to evaluate deep learning models. In this context, we often compute metrics per batch due to the large size of the dataset. In addition, some tasks such as semantic segmentation are so expensive that we can't hold all the predictions in memory.

Describe the solution you'd like

I would like if MetricFrame would accept an update method where we can add more data. For the first version, we can simply add more data to the internal representation of ytrue, ypred, sensitive_attribute. But then I would like it if we could keep a confusion matrix and the update method would update this confusion matrix.

Describe alternatives you've considered, if relevant

I made a wrapper around Fairlearn metrics that keep tracks of ytrue, ypred, sensitive_attribute and then call the underlying metric when needed.

Additional context

Example of a metric in Pytorch Lightning, a fairly popular DL framework.
https://pytorch-lightning.readthedocs.io/en/stable/metrics.html#implementing-a-metric

Keras has a similar API

https://keras.io/api/metrics/#as-subclasses-of-metric-stateful

Activity

  1. riedgar-ms commented on Dec 11, 2020

    @riedgar-ms
    Member

    As discussed in our call, this certainly sounds like something Fairlearn should support. However, MetricFrame doesn't keep track of anything - in fact, it doesn't really care what the contents of y_true and y_pred really are, and certainly doesn't require that the incoming data can be formed into a confusion matrix. That would be something for the individual metrics themselves to support.

    The way I see this working is that each metric would be responsible for its own accumulations, and we'd make a copy of the relevant object for each detected sensitive feature combination. The update(...) method on the MetricFrame would in turn call the update method on each of those underlying metric objects.

  2. MiroDudik commented on Dec 11, 2020

    @MiroDudik
    Member

    (1) Re. "wrapper" implementation where all the incoming data is kept around:

    • This should not be default, but only enabled by setting a Boolean flag in the constructor.

    (2) To incorporate some initial efficient implementations (say for the metrics based on keeping track of the contingency table), we could allow strings as metrics, similarly to pd.SeriesGroupBy.aggregate, e.g.,

    mf = flm.MetricFrame('accuracy_score', y_true, y_pred, sensitive_features=sf)
    mf.add_data(y_true_new, y_pred_new, sensitive_features=sf_new)
    
    mf = flm.MetricFrame(['accuracy_score', 'false_positive_rate', 'false_negative_rate'],
                         y_true, y_pred, sensitive_features=sf)

    We could even support some "standard" lists that we have found useful?

    mf = flm.MetricFrame('binary_classification_metrics',
                         y_true, y_pred, sensitive_features=sf)

    (3) For streaming setting, it would be much nicer to support a constructor / add_data pattern of the following form:

    mf = flm.MetricFrame('accuracy_score')
    mf.add_data(y_true_next, y_pred_next, sensitive_features=sf_next)

    Whereas the current alternative is:

    mf = flm.MetricFrame('accuracy_score', [], [], sensitive_features=[])
    mf.add_data(y_true_next, y_pred_next, sensitive_features=sf_next)

    I'm not completely sure how to do this right (without making the consructor work with generic *args which would hide the meaning). There might be some alternative via @classmethod? Something like:

    mf = flm.MetricFrame.for_streaming('accuracy_score')      # or
    mf = flm.MetricFrame.without_data('accuracy_score')       # or?

    Does that feel right or too fancy? This style is mostly used with from_... as in DataFrame.from_dict(...)

  3. Dref360 commented on Dec 14, 2020

    @Dref360
    ContributorAuthor

    In 1) you talk about a flag-enabled feature. This would fix 3) I think.

    # This work
    mf = flm.MetricFrame('accuracy_score', [], [], sensitive_features=[], streaming=True)
    
    # This should raise
    mf = flm.MetricFrame('accuracy_score', [], [], sensitive_features=[])
    # ValueError("y_true, y_pred can't be empty if `streaming=False`.")
  4. changed the title [-]Support fort streaming metrics[/-] [+]Support for streaming metrics[/+] on Dec 14, 2020
  5. riedgar-ms commented on Dec 15, 2020

    @riedgar-ms
    Member

    Going through @MiroDudik 's points....

    (1) I don't think MetricFrame should be in the business of keeping any data around. That would be the responsibility of the metrics objects themselves. MetricFrame should simply slice up the incoming data according to the sensitive (and control!) features, and make one copy of each metric object to keep track of that slice. Then, feed each metric object its own slice of the data (repeat as necessary when the user supplies more data). When the user requests some of the results (via .overall or .by_group etc.), the MetricFrame should go through its collection of metric objects, and get the current value from each.

    (2) Is something we've discussed before (apart from the set binary_classification_metrics but that does seem like a reasonable extra). There would simply be a different default implementation based on whether some other streaming flag was set.

    (3) That classmethod would be a factory :-)

  6. MiroDudik commented on Dec 18, 2020

    @MiroDudik
    Member

    I really like @Dref360's suggestion above. I am just wondering whether we should allow the user to somehow select the naive "wrapper" option, where y_pred, y_true, sensitive_features etc. are memorized.

    We could still use streaming flag, with the allowed values:

    • None or False (default) -- disable streaming
    • True -- streaming is delegated to the base metric (if base metric does not support it, we raise)
    • 'memorize_data'

    Thoughts?

  7. adrinjalali commented on Dec 20, 2020

    @adrinjalali
    Member

    (1) I don't think MetricFrame should be in the business of keeping any data around. That would be the responsibility of the metrics objects themselves. MetricFrame should simply slice up the incoming data according to the sensitive (and control!) features, and make one copy of each metric object to keep track of that slice. Then, feed each metric object its own slice of the data (repeat as necessary when the user supplies more data). When the user requests some of the results (via .overall or .by_group etc.), the MetricFrame should go through its collection of metric objects, and get the current value from each.

    metrics are pretty much functions, they don't have the concept of storing stuff, at least most of the ones we have right now don't. So it'd be the MetricFrame which would store data.

    We could even support some "standard" lists that we have found useful?

    I don't think standard lists would be required, it adds quite a bit of complexity to the API I think, and it's outside the scope of this issue anyway.

    (3) That classmethod would be a factory :-)

    We probably don't need a factory, it's just the constructor which takes an extra parameter and makes the MetricFrame to store stuff or not.

    For the parameter, I'd go with:

    streaming: bool, default=False
        False: the object does not support streaming and `add_data` would raise.
        True: the object supports streaming.
    

    It wouldn't be the users' responsibility to know which metrics support streaming and which ones don't. To begin with, we store the data fed to the MetricFrame and pass it each time to the underlying metric. It's not the most efficient implementation, but it does the job. In later iterations, we can start by adding support for certain commonly used metrics by implementing them ourselves in a update-able efficient way and enhance the MetricFrame implementation, w/o any change on the user/API side.

  8. riedgar-ms commented on Dec 20, 2020

    @riedgar-ms
    Member

    For (1) I suppose it depends on how much we're concerned with efficiency (and I will confess ignorance as to how streamable metrics such as those mentioned above do this right now) vs making the new user experience as smooth as possible. Storing all the data as it comes in is certainly inefficient, since we would have to just store it, and reprocess everything for each update call. Specialised streaming metrics could be more efficient - for example by building a confusion matrix, and updating the counts for new data (we can't do this within MetricFrame because it's much more general than CM-based classification metrics).

    I can certainly see the sense in @adrinjalali 's suggestion.

  9. MiroDudik commented on Dec 21, 2020

    @MiroDudik
    Member

    I am fine with @adrinjalali 's suggestion (i think that might be exactly also what @Dref360 had in mind).

    My only concern is whether we should try to be more transparent with the user when we are using the inefficient implementation. Do we issue a warning or is that too annoying? I'm also okay just stating in the documentation which metrics have efficient streaming and that all other metrics just use a non-efficient fallback.

  10. adrinjalali commented on Dec 22, 2020

    @adrinjalali
    Member

    I wouldn't raise a warning, but I'm happy to have that implementation detail explained in the docs with the performance issues related to it.

  11. MiroDudik commented on Dec 22, 2020

    @MiroDudik
    Member

    Ok--let's then just have a boolean flag along the lines of Frederic's comment and Adrin's comment and with the initial inefficient implementation.

    @Dref360 -- do you want to get started with that?

    The next step is going to be to enable some efficient implementations. I see several options:

    Option 1. We allow pytorch_lightning.metrics.Metric objects in the constructor, e.g.,

    import pytorch_lightning.metrics as plm
    import fairlearn.metrics as flm
    
    mf = flm.MetricFrame({'accuracy': plm.Accuracy, 'f1': plm.F1},
                         [], [], sensitive_features=[], streaming=True)

    This sets up a pattern where we could continue adding support for other metric styles, e.g., we might add tf.keras.metrics.Metric etc.

    • the upside is that this will immediately provide access to many metrics beyond sklearn.metrics
    • the downside is that we're now creating a dependency on other packages

    Option 2. We create our own streaming metric interface. The implication is that we would then need to build wrappers for pytorch_lightning.metrics.Metric, tf.keras.metrics.Metric, etc. The downside is that we are creating another new API for users to deal with.

    Option 3. We create our own efficient streaming implementation that could be accessed via string, e.g.,

    mf = flm.MetricFrame(['accuracy_score', 'f1_score'],
                         [], [], sensitive_features=[], streaming=True)

    In this case, we would create our own internal API for streaming metrics, but we wouldn't need to obsess about it too much (since we wouldn't be exporting it, so we could easily change it later). This is compatible with Option 1 above (we would be able to build our internal wrappers for this internal API).

    Thoughts?

  12. Dref360 commented on Dec 23, 2020

    @Dref360
    ContributorAuthor

    Yes let's start with an unefficient v1. I'll try to get a PR opened before the next meeting in January

  13. TamaraAtanasoska commented on Mar 31, 2025

    @TamaraAtanasoska
    Contributor

    hi @Dref360 and folks involved in reviewing the PRs following this issue, is this still something of interest? @Dref360 it seems #942 was close to merge, is it something we could still make available for someone else to pick up if time to complete the idea is an issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions