Repository navigation
Reject nonfinite weights before weighted sampling - #3848
Conversation
|
Performance benchmarks:
|
| "Expected str, Callable, Sequence[float], or None." | ||
| ) | ||
|
|
||
| if any(not np.isfinite(x) for x in w): |
There was a problem hiding this comment.
why use numpy here on each individual number. Might it not be faster (too be tested) to cast the weights to a numpy array and vectorize this check? Or alternatively compare with inf directly using python itself instead of numpy.
There was a problem hiding this comment.
Switched to math.isfinite. Timed all three over 100 runs on a list of 100k floats: numpy called per element 8.2s, vectorized np.isfinite(np.asarray(w)).all() 0.34s, math.isfinite 0.15s. Since w is already a plain list, building the array costs more than the vectorized check saves, so plain Python wins at every size I tried. Pushed in b9ccd50.
quaquel
left a comment
There was a problem hiding this comment.
minor question/change. Looks fine otherwise.
Note
Use this template for bug fixes only. For enhancements or new features, use the feature template and get maintainer approval in an issue or discussion before opening a PR.
Pre PR Checklist
Summary
Reject NaN and infinite weights before weighted sampling chooses an algorithm. Without this validation, sampling without replacement can silently select agents using invalid probability weights.
Bug / Issue
Fixes #3847.
AgentSet.select_random() currently accepts NaN and positive infinity when replace=False, although the replacement path rejects them. This makes the result depend on invalid generated keys instead of a valid probability distribution.
Implementation
Validate that every resolved weight is finite before checking negativity or total weight. The validation applies consistently to both replacement modes.
Testing
Added parameterized regression coverage for NaN and positive infinity. All 41 AgentSet tests pass. Ruff formatting passes. Ruff lint passes apart from two existing UP038 findings in agentset.py that are also present on current main.
Additional Notes
This validation is separate from PR #3845, which addresses zero weight sampling capacity.