Repository navigation
Add DensityEstimatorBuilder with build() dispatch - #1877
Conversation
|
This is a stacked PR, so opening as a Draft. Once the PR #1872 is merged into a new GSoC specific branch, I will rebase this branch and mark it Ready for review. |
feb2d25 to
0737ed4
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## gsoc-2026 #1877 +/- ##
============================================
Coverage ? 87.97%
============================================
Files ? 144
Lines ? 13448
Branches ? 0
============================================
Hits ? 11831
Misses ? 1617
Partials ? 0
Flags with carried forward coverage won't be shown. Click here to find out more.
|
janfb
left a comment
There was a problem hiding this comment.
Great follow-up @satwiksps 👍
I added a couple of minor comments, and a larger one regarding our general plan. I suggest to drop the context arg for now as we are still relying on the internal z-scoring and don't need the context at all for now.
this also implies that we should make the ZScoreConfig and ZScoreStats and compute_z_score_stats all private for now, to not make any promises in terms of public API. this will be added later.
for the follow-up #1882 , you would need to adapt a bit to the drop of context, let's discuss in our meeting.
great work! 👏
| build_resnet_classifier, | ||
| ) | ||
| from sbi.neural_nets.net_builders.estimator_configs import ( | ||
| DensityEstimatorBuilder, |
There was a problem hiding this comment.
cosmetics: please check whether removing the comma keeps it all in one line.
| _VALID_DENSITY_MODELS = { | ||
| "mdn", | ||
| "made", | ||
| "maf", | ||
| "maf_rqs", | ||
| "nsf", | ||
| "zuko_nice", | ||
| "zuko_maf", | ||
| "zuko_nsf", | ||
| "zuko_ncsf", | ||
| "zuko_sospf", | ||
| "zuko_naf", | ||
| "zuko_unaf", | ||
| "zuko_gf", | ||
| "zuko_bpf", | ||
| } |
There was a problem hiding this comment.
good to have this separate as a set, but we could still re-use the definition from above via frozenset(get_args(DENSITY_MODELS)) (needs to import get_args from typing).
| # --- Shared across most builders --- | ||
| z_score_x: Optional[str] = None | ||
| z_score_y: Optional[str] = None | ||
| hidden_features: Optional[Any] = None |
There was a problem hiding this comment.
this could be more strict, e.g, hidden_features = Optional[Union[int, Sequence[int]]] (because zuko allows sequence.
| z_score_x: Optional[str] = None | ||
| z_score_y: Optional[str] = None |
There was a problem hiding this comment.
could make this literals as well, like in the build_* funs, e.g., Literal["none","independent","structured","transform_to_unconstrained"] or will this be too strict at this level? please check the pyright consequences.
| ) | ||
|
|
||
|
|
||
| def test_density_estimator_builder_defaults(): |
There was a problem hiding this comment.
defaults are hard coded, we don't need to check for them again. can be dropped.
|
|
||
|
|
||
| @pytest.mark.parametrize("model", sorted(_VALID_DENSITY_MODELS)) | ||
| def test_density_estimator_builder_accepts_valid_models(model): |
There was a problem hiding this comment.
mostly covered by test_density_estimator_builder_build except the dataclass default model, so also trivial I think. I suggest to drop, but please double check.
|
I have worked upon the minor comments as per review. For the major change related to |
janfb
left a comment
There was a problem hiding this comment.
looks very good @satwiksps 👍 all my previous comments perfectly addressed. I just found some typing constraints that we should add, that's the last thing before we can merge 🚀
|
|
||
| def build(self, context: BuildContext) -> Any: | ||
| """Build an estimator from a ``BuildContext``. | ||
| def build(self, batch_theta: Tensor, batch_x: Tensor) -> Any: |
There was a problem hiding this comment.
the return type could be more specialized, e.g., ConditionalEstimator?
needs an import from sbi.neural_nets.estimators.base
| f"Must be one of {sorted(_VALID_DENSITY_MODELS)}." | ||
| ) | ||
|
|
||
| def build(self, batch_theta: Tensor, batch_x: Tensor): |
There was a problem hiding this comment.
add return specialized for this subclass method, e.g., ConditionalDensityEstimator. needs an import from from sbi.neural_nets.estimators.base as well.
same for all future specific builders. It's ok to have subclass return types different from the parent class because the type has been defined with covariant=True.
Co-authored-by: Jan Teusen (né Boelts) <[email protected]>
janfb
left a comment
There was a problem hiding this comment.
all good, thanks @satwiksps 🚀
…1877) * export DensityEstimatorBuilder from net_builders * add supported density model definitions * add the DensityEstimatorBuilder class * add tests * add proper docstrings to estimator_configs new class * add some more tests for DensityEstimatorBuilder * cosmetic change to keep import in one line * re-use DENSITY_MODELS definition * make literals strict * drop trivial tests * add necessary asserts to tests * fix comment line too long error * remove BuildContext from base class * remove context from tests * update builder base test * more specialized return type * Apply suggestion from @janfb Co-authored-by: Jan Teusen (né Boelts) <[email protected]> * wrap docstring to fix E501 Line too long --------- Co-authored-by: Jan Teusen (né Boelts) <[email protected]>
What does this PR do?
This is the second PR for for the Neural Network (NN) Builder API refactor project under GSoC 2026. It adds
DensityEstimatorBuilderwhich is the first concrete builder class in the NN builder refactor. It provides a typed, inspectable replacement for theposterior_nn()/likelihood_nn()factory closures, covering all 14 continuous density estimator model types.Builds on PR #1872 which introduced
BuildContext,ZScoreConfig,ZScoreStats, and the_EstimatorBuilderBasecontract.Files Changed
sbi/neural_nets/net_builders/estimator_configs.pyDensityEstimatorBuilder(_EstimatorBuilderBase)dataclass with:model: Literal[...]field selecting the architecture (maf, nsf, mdn, made, maf_rqs, and all Zuko variants)__post_init__validation: unknown model names fail immediately at constructionbuild(context, batch_theta, batch_x): dispatches to the appropriate existingbuild_*function_build_kwargs(): collects non-None fields + extra_kwargs, excludingmodel(used only for dispatch)DENSITY_MODELStype alias and_VALID_DENSITY_MODELSset for validationsbi/neural_nets/net_builders/__init__.pyDensityEstimatorBuildertests/density_estimator_builder_test.py(created new file, or may be we can also add to existing test files ?)AI Usage
Does this close any issues?
N/A
Any relevant code examples, logs, or error messages?
N/A