Skip to content

Register collections.OrderedDict with flax.serialization - #5672

Open
sohailshk wants to merge 1 commit into
google:mainfrom
sohailshk:fix/serialization-ordered-dict
Open

sohailshk wants to merge 1 commit into
google:mainfrom
sohailshk:fix/serialization-ordered-dict

Conversation

@sohailshk

Copy link
Copy Markdown

What does this PR do?

optax.named_chain keeps its state in a collections.OrderedDict (google-deepmind/optax#1397, released in optax 0.2.6, changed it from a dict). flax.serialization only registers the exact type dict, so to_state_dict returns an OrderedDict unchanged, to_bytes fails with TypeError: can not serialize 'collections.OrderedDict' object, and from_state_dict returns the given state dict instead of rebuilding the target.

Repro:

import jax.numpy as jnp, optax, flax.serialization as fs
tx = optax.named_chain(('clip', optax.clip(1.0)), ('adam', optax.adam(0.1)))
state = tx.init({'w': jnp.ones(2)})
fs.to_bytes(state)  # TypeError on main

Fix: register collections.OrderedDict in flax/serialization.py with the dict state-dict function; restoring rebuilds an OrderedDict in the target's key order.

Tests: new test_ordered_dict_serialization in tests/serialization_test.py (named_chain state -> to_bytes -> from_bytes, type, key order, leaves and tree structure). On main it fails with the msgpack TypeError; with the change it passes. pytest tests/serialization_test.py: 88 passed, 4 skipped. ruff check on the two files is clean. Not run: the rest of the test suite, pre-commit hooks.

Behaviour change: states containing an OrderedDict that previously could not be written with to_bytes now can. from_state_dict on an OrderedDict target now rebuilds an OrderedDict in the target's key order instead of returning the given state dict. Plain dict handling is unchanged.

Fixes #5671

Checklist

  • This PR fixes a minor issue (e.g.: typo or small bug) or improves the docs (you can dismiss the other checks if that's the case).
  • This change is discussed in a Github issue/discussion (please add a link).
  • The documentation and docstrings adhere to the documentation guidelines.
  • This change includes necessary high-coverage tests.

The implementation and tests were written with AI assistance.

optax.named_chain keeps its state in an OrderedDict. Only the exact type dict
was registered, so to_state_dict returned the OrderedDict unchanged,
to_bytes failed in msgpack, and from_state_dict returned the given state
dict instead of rebuilding the target.

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.

flax.serialization cannot serialize collections.OrderedDict (breaks to_bytes for optax.named_chain state)

1 participant