-
Notifications
You must be signed in to change notification settings - Fork 32
Add final_log_prob return value to AdamOptimization.optimize method #229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
0bc1e93
Fix formatting of dimensions in AdamOptimization class
thomasckng 1cefa88
Fix gradient calculation in AdamOptimization to include data in grad_fn
thomasckng f20998e
Add final_log_prob return value to AdamOptimization.optimize method
thomasckng 99b6fa7
Fix return value unpacking in AdamOptimization.__call__ method
thomasckng 6f15b5e
Formatting
thomasckng f593ed0
Fix unpacking of return values in TestOptimizationStrategies.optimize…
thomasckng 5651d24
Add final_log_prob assertion to AdamOptimization test
thomasckng 0908327
Add docstring for optimize method in AdamOptimization class
thomasckng d0cb0ee
Add bounds argument description to AdamOptimization class docstring
thomasckng 0326733
Update loss_fn signature to include data parameter in optimization st…
thomasckng 332c687
Fix gradient computation in optimize method to prevent data shadowing
thomasckng fbe05fb
Revert some suggestions by coderabbit
thomasckng d768b01
Enhance bounds validation in AdamOptimization class and update docstr…
thomasckng 15e103e
Formatting
thomasckng File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -20,13 +20,18 @@ class AdamOptimization(Strategy): | |
| Learning rate for the optimization. | ||
| noise_level: float = 10 | ||
| Variance of the noise added to the gradients. | ||
| bounds: Float[Array, " n_dim 2"] = jnp.array([[-jnp.inf, jnp.inf]]) | ||
| Bounds for the optimization. The optimization will be projected to these bounds. | ||
| If bounds has shape (1, 2), it will be broadcast to all dimensions. For n_dim > 1, | ||
| passing a (1, 2) array applies the same bound to every dimension. To specify different | ||
| bounds per dimension, provide an array of shape (n_dim, 2). | ||
| """ | ||
|
|
||
| logpdf: Callable[[Float[Array, " n_dim"], dict], Float] | ||
| n_steps: int = 100 | ||
| learning_rate: float = 1e-2 | ||
| noise_level: float = 10 | ||
| bounds: Float[Array, "n_dim 2"] = jnp.array([[-jnp.inf, jnp.inf]]) | ||
| bounds: Float[Array, " n_dim 2"] = jnp.array([[-jnp.inf, jnp.inf]]) | ||
|
|
||
| def __repr__(self): | ||
| return "AdamOptimization" | ||
|
|
@@ -37,14 +42,22 @@ def __init__( | |
| n_steps: int = 100, | ||
| learning_rate: float = 1e-2, | ||
| noise_level: float = 10, | ||
| bounds: Float[Array, "n_dim 2"] = jnp.array([[-jnp.inf, jnp.inf]]), | ||
| bounds: Float[Array, " n_dim 2"] = jnp.array([[-jnp.inf, jnp.inf]]), | ||
| ): | ||
| self.logpdf = logpdf | ||
| self.n_steps = n_steps | ||
| self.learning_rate = learning_rate | ||
| self.noise_level = noise_level | ||
| self.bounds = bounds | ||
|
|
||
| # Validate bounds shape | ||
| if bounds.ndim != 2 or bounds.shape[1] != 2: | ||
| raise ValueError( | ||
| f"bounds must have shape (n_dim, 2) or (1, 2), got {bounds.shape}" | ||
| ) | ||
| # If bounds is (1, 2), it will be broadcast to all dimensions. If not, check compatibility. | ||
| # Try to infer n_dim from logpdf signature or initial_position, but here we can't, so warn in runtime. | ||
|
|
||
| self.solver = optax.chain( | ||
| optax.adam(learning_rate=self.learning_rate), | ||
| ) | ||
|
|
@@ -58,12 +71,12 @@ def __call__( | |
| ) -> tuple[ | ||
| PRNGKeyArray, | ||
| dict[str, Resource], | ||
| Float[Array, "n_chains n_dim"], | ||
| Float[Array, " n_chain n_dim"], | ||
| ]: | ||
| def loss_fn(params: Float[Array, " n_dim"]) -> Float: | ||
| def loss_fn(params: Float[Array, " n_dim"], data: dict) -> Float: | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @kazewong This may affect performance, but removing it will cause an issue when calling below. |
||
| return -self.logpdf(params, data) | ||
|
|
||
| rng_key, optimized_positions = self.optimize( | ||
| rng_key, optimized_positions, _ = self.optimize( | ||
| rng_key, loss_fn, initial_position, data | ||
| ) | ||
|
|
||
|
|
@@ -76,6 +89,14 @@ def optimize( | |
| initial_position: Float[Array, " n_chain n_dim"], | ||
| data: dict, | ||
| ): | ||
| # Validate bounds shape against n_dim | ||
| n_dim = initial_position.shape[-1] | ||
| if not (self.bounds.shape[0] == 1 or self.bounds.shape[0] == n_dim): | ||
| raise ValueError( | ||
| f"bounds shape {self.bounds.shape} is incompatible with n_dim={n_dim}. " | ||
| "Provide bounds of shape (1, 2) for broadcasting or (n_dim, 2) for per-dimension bounds." | ||
| ) | ||
|
|
||
| """Optimization kernel. This can be used independently of the __call__ method. | ||
|
|
||
| Args: | ||
|
|
@@ -85,14 +106,26 @@ def optimize( | |
| Objective function to optimize. | ||
| initial_position: Float[Array, " n_chain n_dim"] | ||
| Initial positions for the optimization. | ||
| data: dict | ||
| Data to pass to the objective function. | ||
|
|
||
| Returns: | ||
| rng_key: PRNGKeyArray | ||
| Updated random key. | ||
| optimized_positions: Float[Array, " n_chain n_dim"] | ||
| Optimized positions. | ||
| final_log_prob: Float[Array, " n_chain"] | ||
| Final log-probabilities of the optimized positions. | ||
| """ | ||
| grad_fn = jax.jit(jax.grad(objective)) | ||
|
|
||
| def _kernel(carry, data): | ||
| def _kernel(carry, _step): | ||
| key, params, opt_state = carry | ||
|
|
||
| key, subkey = jax.random.split(key) | ||
| grad = grad_fn(params) * (1 + jax.random.normal(subkey) * self.noise_level) | ||
| grad = grad_fn(params, data) * ( | ||
| 1 + jax.random.normal(subkey) * self.noise_level | ||
| ) | ||
| updates, opt_state = self.solver.update(grad, opt_state, params) | ||
| params = optax.apply_updates(params, updates) | ||
| params = optax.projections.projection_box( | ||
|
|
@@ -128,4 +161,4 @@ def _single_optimize( | |
| if jnp.isinf(final_log_prob).any() or jnp.isnan(final_log_prob).any(): | ||
| print("Warning: Optimization accessed infinite or NaN log-probabilities.") | ||
|
|
||
| return rng_key, optimized_positions | ||
| return rng_key, optimized_positions, final_log_prob | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.