Creates a context in which `module` has `state`.` This lets you write tests that make calls to a module without needing to call `functional()` yourself. It is similar in spirit to FLAX's `module.bind()` although that works differently due to the fact that FLAX state is only associa
(
module: ConfigOr[M],
*,
is_training: bool = True,
prng_key: Optional[jax.random.PRNGKey] = None,
state: Nested[Tensor],
)
| 774 | |
| 775 | @contextlib.contextmanager |
| 776 | def bind_module( |
| 777 | module: ConfigOr[M], |
| 778 | *, |
| 779 | is_training: bool = True, |
| 780 | prng_key: Optional[jax.random.PRNGKey] = None, |
| 781 | state: Nested[Tensor], |
| 782 | ) -> Iterator[M]: |
| 783 | """Creates a context in which `module` has `state`.` |
| 784 | |
| 785 | This lets you write tests that make calls to a module without needing to call `functional()` |
| 786 | yourself. |
| 787 | |
| 788 | It is similar in spirit to FLAX's `module.bind()` although that works differently due to the |
| 789 | fact that FLAX state is only associated with an instance of a module, whereas AXLearn state is |
| 790 | global. |
| 791 | |
| 792 | Example: |
| 793 | ``` |
| 794 | cfg = MyModule.default_config() |
| 795 | with test_utils.bind_layer(cfg) as module: |
| 796 | result = module.do_something(some_args) |
| 797 | ``` |
| 798 | |
| 799 | Args: |
| 800 | module: The module to create a context for. |
| 801 | is_training: Tell the module it is in training or not. |
| 802 | prng_key: The PRNG key to use. If None, `jax.random.PRNGKey(0)`. |
| 803 | state: The state to use. |
| 804 | |
| 805 | Returns: |
| 806 | The initialized module. |
| 807 | """ |
| 808 | if prng_key is None: |
| 809 | prng_key = jax.random.PRNGKey(0) |
| 810 | |
| 811 | if isinstance(module, InstantiableConfig): |
| 812 | if isinstance(module, Module.Config) and isinstance( |
| 813 | getattr(module, "name", None), RequiredFieldValue |
| 814 | ): |
| 815 | setattr(module, "name", "tmp") |
| 816 | module = module.instantiate(parent=None) |
| 817 | ctx = InvocationContext( |
| 818 | name="root", |
| 819 | parent=None, |
| 820 | module=module, |
| 821 | is_training=is_training, |
| 822 | prng_key=prng_key, |
| 823 | state=state, |
| 824 | output_collection=new_output_collection(), |
| 825 | ) |
| 826 | with set_current_context(ctx): |
| 827 | yield module |
| 828 | |
| 829 | |
| 830 | @contextlib.contextmanager |
no test coverage detected