-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1efee84
commit 8a4f8d6
Showing
2 changed files
with
25 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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
This file contains 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 |
---|---|---|
@@ -1,13 +1,35 @@ | ||
from __future__ import annotations | ||
|
||
from collections.abc import Generator | ||
from contextlib import contextmanager | ||
from typing import Any | ||
|
||
import jax | ||
import jax.numpy as jnp | ||
from jax import tree | ||
|
||
from .annotations import JaxBooleanArray | ||
|
||
|
||
def dynamic_tree_all(tree: Any) -> JaxBooleanArray: | ||
"""Like `jax.tree.all`, but can be used in dynamic code like jitted functions and loops.""" | ||
return jax.tree.reduce(jnp.logical_and, tree, jnp.asarray(True)) | ||
|
||
|
||
class NotEditableError(RuntimeError): | ||
pass | ||
|
||
|
||
@contextmanager | ||
def edit_tree[T](model: T, /, editable_types: tuple[type[Any], ...]) -> Generator[T, None, None]: | ||
flattened, pytree = tree.flatten(model) | ||
model_copy = tree.unflatten(pytree, flattened) | ||
yield model_copy | ||
|
||
def verify(x: Any, y: Any) -> None: | ||
if isinstance(x, editable_types): | ||
return | ||
if id(x) != id(y): | ||
raise NotEditableError("Non-editable value changed.") # noqa: TRY003 | ||
|
||
tree.map(verify, model, model_copy, is_leaf=lambda x: isinstance(x, editable_types)) |