Skip to content

fix: raise ValueError for empty top_k in HitRate#3722

Open
muhammadrashid4587 wants to merge 1 commit intopytorch:masterfrom
muhammadrashid4587:fix/hitrate-empty-top-k-validation
Open

fix: raise ValueError for empty top_k in HitRate#3722
muhammadrashid4587 wants to merge 1 commit intopytorch:masterfrom
muhammadrashid4587:fix/hitrate-empty-top-k-validation

Conversation

@muhammadrashid4587
Copy link
Copy Markdown

Summary

  • Adds validation for empty top_k list in HitRate.__init__()
  • HitRate(top_k=[]) now raises a clear ValueError at construction time instead of crashing with IndexError during update()

Root cause

The existing check any(k <= 0 for k in top_k) returns False for empty lists, so top_k=[] passed validation. Later, self.top_k[-1] in update() raises IndexError.

Fixes #3718

This PR was created with AI agent assistance.

Test plan

  • HitRate(top_k=[]) now raises ValueError("top_k must not be empty.")
  • Existing validation for negative values still works
  • Normal usage HitRate(top_k=[1, 2, 3]) unaffected

HitRate(top_k=[]) silently passed validation because
`any(k <= 0 for k in [])` returns False for empty lists, then
crashed with an unhelpful IndexError during update().

Add an explicit check for empty top_k at construction time so
users get a clear ValueError immediately.

Fixes pytorch#3718
@github-actions github-actions bot added the module: metrics Metrics module label Apr 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

module: metrics Metrics module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] HitRate metric raises IndexError instead of ValueError when top_k is empty

2 participants