Skip to content

[BTY-62] Add MEDFAIR imaging fairness metrics, model selection, and debiasing baselines - #1761

Open
irvifa wants to merge 1 commit into
sunlabuiuc:masterfrom
irvifa:bty-62-medfair
Open

irvifa wants to merge 1 commit into
sunlabuiuc:masterfrom
irvifa:bty-62-medfair

Conversation

@irvifa

@irvifa irvifa commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements [BTY-62] MEDFAIR Imaging Fairness Benchmark (ICLR 2023) (Zong, Yang, and Hospedales, ICLR 2023, https://arxiv.org/abs/2210.01725; official code: https://github.com/ys-zong/MEDFAIR) for PyHealth's medical imaging tasks.

What this adds

  • Group fairness metrics & model-selection criteria (pyhealth/metrics/medfair.py):
    • medfair_metrics_fn: computes overall & per-group ROC-AUC, worst_auc, worst_group, auc_gap, subgroup FPR/FNR and gaps, equalized_odds, sensitivity at fixed specificity (group_tpr_at_specificity, worst_tpr_at_specificity), and subgroup Expected Calibration Error (overall_ece, group_eces) for binary and multi-group sensitive attributes.
    • medfair_model_selection_score and select_best_checkpoint: MEDFAIR checkpoint selection supporting "worst_auc", "overall_auc", "equalized_odds", and "loss".
  • Debiasing baselines (pyhealth/models/medfair.py):
    • GroupDROLoss: exponentiated-gradient GroupDRO loss (Sagawa et al., ICLR 2020) as benchmarked in MEDFAIR, supporting optional group-size adjustment (adj / sqrt(n_g)) and loss normalization.
    • MEDFAIRModel(BaseModel): PyHealth 2.0 image classifier supporting method="erm", method="group_dro", and method="domain_ind" (Domain Independent Training with per-group heads and inference_sum_prob logit summation) with resnet18, densenet121, or simple_cnn backbones, compatible with Trainer.
    • make_group_balanced_sampler: MEDFAIR inverse-frequency resampling (WeightedRandomSampler) over (group, label) strata or groups alone.
  • ChestX-ray14 fairness task (pyhealth/tasks/medfair_chestxray14.py):
    • ChestXray14FairnessClassification(BaseTask): emits {"patient_id", "image", "sensitive_attr", "label"} from ChestXray14Dataset for sensitive_attribute="sex", "age_binary", or "age_multi" (MEDFAIR's 5 age bins).
  • Example (examples/fairness/medfair_chestxray14.py): end-to-end ERM / GroupDRO / DomainInd + resampling training and worst_auc checkpoint selection on ChestXray14Dataset.
  • Unit tests (tests/core/test_medfair.py): comprehensive tests for all metrics, model-selection criteria, GroupDROLoss, MEDFAIRModel (erm, group_dro, domain_ind, all backbones, Trainer integration), make_group_balanced_sampler, and ChestXray14FairnessClassification (including end-to-end on test-resources/core/chestxray14).

How it interacts with existing code

  • Purely self-contained new modules (pyhealth/metrics/medfair.py, pyhealth/models/medfair.py, pyhealth/tasks/medfair_chestxray14.py) with standard export registrations in pyhealth/{metrics,models,tasks}/__init__.py. No base classes, Trainer, or existing tasks/datasets are modified.

Verification

  • python3 tools/check_pr_rules.py — all PR contribution rules passed (0 issues).
  • pytest tests/core/test_medfair.py — all tests passed.
  • pytest --doctest-modules pyhealth/metrics/medfair.py pyhealth/models/medfair.py pyhealth/tasks/medfair_chestxray14.py — all doctests passed.

@github-actions github-actions Bot mentioned this pull request Nov 30, 2026
@github-actions

Copy link
Copy Markdown

Test Coverage

Total: 88.59% (60289 / 68057 lines)

Modified file Coverage Lines
pyhealth/metrics/__init__.py 100.00% 20 / 20
pyhealth/metrics/medfair.py 98.96% 95 / 96
pyhealth/models/__init__.py 100.00% 128 / 128
pyhealth/models/medfair.py 97.32% 145 / 149
pyhealth/tasks/__init__.py 98.62% 143 / 145
pyhealth/tasks/medfair_chestxray14.py 98.18% 54 / 55

Workflow run · e65b36f

@solarsys solarsys added the status: manual Pending maintainer's review label Nov 30, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

Why this PR has status: manual: overlap. #1560 (opened about a week earlier, also tagged [BTY-62]) adds MEDFAIR's group-fairness metrics, fairness-aware model selection and debiasing on HAM10000, and the AI review suggests approve there. This PR adds the same pieces under different names (metrics/medfair.py, models/medfair.py), on ChestX-ray14. A maintainer has to pick one set of fairness metrics and selection criteria, and decide the BTY-62 credit. This is tracked in #1668.

To help: please comment here on what this PR does that #1560 doesn't. Your ChestX-ray14 task medfair_chestxray14.py looks new, and so may some of the debiasing baselines. Whichever metrics land first, the other PR can contribute its unique parts on top.

@irvifa

irvifa commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for flagging the overlap with #1560! I missed #1560 when checking open PRs. Comparing with #1560, the parts unique to this PR are:

Copy link
Copy Markdown
Collaborator

/review


Generated by Claude Code

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit e65b36f

num_groups=self.num_groups,
step_size=dro_step_size,
group_counts=group_counts,
adj=dro_adj,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] dro_adj is silently ignored unless group_counts is passed

MEDFAIRModel forwards dro_adj into GroupDROLoss as adj (adj=dro_adj). GroupDROLoss applies the adj / sqrt(n_g) term only when group_counts is also provided. So MEDFAIRModel(..., method="group_dro", dro_adj=1.0) with no group_counts runs with no group-size adjustment and emits no warning, while the MEDFAIRModel docstring (line 272) describes dro_adj as the group-size adjustment. Fix: raise ValueError in MEDFAIRModel.init when dro_adj > 0 and group_counts is None, or state the dependency in the docstring. Add a test for the chosen behavior.

if raw_age is None:
return None
try:
age = float(raw_age)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] NaN age is mapped to the oldest group instead of being skipped

float(raw_age) accepts NaN without raising, so a NaN patient_age passes the try/except and falls through every comparison. age_binary then returns 1 and age_multi returns 4, silently putting unknown-age images in the 60+ or 80+ group. Skip non-finite ages, for example with math.isfinite(age) returning None, and add a case with a NaN age to the existing encoding test.

return WeightedRandomSampler(weights=weights, num_samples=n_draw, replacement=True)


class MEDFAIRModel(BaseModel):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] ERM path overlaps TorchvisionModel; the description does not explain why

With method="erm" and backbone resnet18 or densenet121, MEDFAIRModel does what pyhealth/models/torchvision_model.py TorchvisionModel already does: an ImageNet-style backbone with a linear head and BCE loss. The GroupDRO and DomainInd methods are a real extension, so the component is not redundant, but the description should say why these methods are a new class and not an extension of TorchvisionModel, or whether the backbone code can be reused.

return 4


class ChestXray14FairnessClassification(BaseTask):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] No docs/api pages for the new metric, model and task

Existing PyHealth components have a page under docs/api/ (for example docs/api/tasks/pyhealth.tasks.ChestXray14BinaryClassification.rst and docs/api/metrics/pyhealth.metrics.fairness.rst). The new medfair metric functions, MEDFAIRModel with GroupDROLoss and make_group_balanced_sampler, and ChestXray14FairnessClassification have none. Add matching rst pages and list them in the section indexes.

train_ds,
batch_size=args.batch_size,
sampler=sampler,
collate_fn=collate_fn_dict,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Example batches with collate_fn_dict, which leaves tensors unstacked

collate_fn_dict returns plain lists, so the binary label reaches MEDFAIRModel.forward as a list of per-sample tensors and is converted with torch.as_tensor. The unit tests use get_dataloader, which is the path the rest of the library uses. Use get_dataloader for the training, validation and test loaders, or confirm the example runs on real ChestX-ray14 batches.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: need change
decision: human review

Thank you for this contribution. The MEDFAIR fairness metrics, checkpoint selection, ERM/GroupDRO/DomainInd baselines, group-balanced sampler and ChestX-ray14 fairness task fill a real gap, and the tests are thorough. Coverage is well above the bar: 88.59% for the repository, and about 97–99% for each added file.

To get this merged:

  • In MEDFAIRModel (pyhealth/models/medfair.py), dro_adj is silently ignored unless group_counts is also passed. A user who sets dro_adj > 0 alone gets plain GroupDRO with no warning. Please do one of these:
    • Raise a ValueError when dro_adj > 0 and group_counts is None.
    • Compute group_counts automatically.
    • State the requirement clearly in the MEDFAIRModel docstring.

Optional suggestions:

  • In _encode_sensitive_attribute, a NaN patient_age parses as a float and falls through to group 4 (80+) for age_multi, and to group 1 for age_binary. Returning None for NaN values would skip those samples instead.
  • Add docs/api/ pages for the new metric, model and task.
  • The ERM path overlaps with TorchvisionModel. A sentence in the description on why a separate model is needed would help.
  • Add a numeric check of the domain_ind logit summation at inference.
  • The example batches with collate_fn_dict, while the tests use get_dataloader. Make sure the example has been run once end to end.

Reviewed commit e65b36f

@sanniheruwala

Copy link
Copy Markdown
Contributor

@solarsys Can we have #1560 reviewed and approved , so @irvifa can have additive commits on top of it ?

@solarsys

solarsys commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

#1560 (MEDFAIR subgroup fairness metrics, fairness-aware model selection and subgroup resampling) is now merged into master. Please rebase this PR on master and keep only what it adds on top of #1560. That includes the parts you listed, such as the in-processing debiasing baselines. Reuse the merged metrics and selection rules where they overlap, instead of adding a second implementation. Once rebased, comment /review on its own line. Bounty credit for BTY-62 is a maintainer decision and will be settled once both parts land.

This branch has not been deployed

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

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants