Skip to content

fix(nnx): ensure ToLinen args and kwargs are hashable - #5598

Open
reginaldalfret wants to merge 1 commit into
google:mainfrom
reginaldalfret:fix/4156-tolinen-hashable
Open

reginaldalfret wants to merge 1 commit into
google:mainfrom
reginaldalfret:fix/4156-tolinen-hashable

Conversation

@reginaldalfret

Copy link
Copy Markdown

Fixes #4156

Description

ToLinen modules should be hashable like standard Linen modules, allowing them to be passed as static arguments to jax.jit and stored in sets/dicts.

Previously, if kwargs was supplied as a standard Python dictionary (or if args was supplied as a sequence like a list), hash(model) failed with TypeError: unhashable type: 'dict' because Linen dataclasses calculate __hash__ across all module attributes.

Changes

  • Added __post_init__ to ToLinen in flax/nnx/bridge/wrappers.py to:
    • Coerce args to a tuple if it is not already one.
    • Coerce kwargs to a FrozenDict (which recursively freezes nested dicts) if it is not already one.
  • Added regression test test_to_linen_hashable in tests/nnx/bridge/wrappers_test.py verifying:
    • Default ToLinen is hashable.
    • ToLinen with a mutable dict for kwargs is automatically converted to FrozenDict and hashable.
    • ToLinen with a list for args is automatically converted to tuple and hashable.
    • ToLinen can be safely passed as a static argument (static_argnums=(0,)) to jax.jit.

Coerce args to a tuple and kwargs to a FrozenDict during ToLinen
initialization so that wrapped Linen modules can be hashed and
passed as static arguments to jax.jit.

Fixes google#4156

Signed-off-by: Reginald Alfret <reginaldalfret@gmail.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ToLinen is not hashable (Linen modules are)

1 participant