Skip to content

Support namedtuple and tuple subclasses in tree_merge - #3703

Merged
angeloskath merged 1 commit into
ml-explore:mainfrom
Pablosinyores:fix/tree-utils-namedtuple
Jun 17, 2026
Merged

angeloskath merged 1 commit into
ml-explore:mainfrom
Pablosinyores:fix/tree-utils-namedtuple

Conversation

@Pablosinyores

Copy link
Copy Markdown
Contributor

Summary

tree_map and tree_map_with_path reconstruct list/tuple containers with

return TreeType(*subtrees) if hasattr(tree, "_fields") else TreeType(subtrees)

so that namedtuples (whose constructor takes one positional argument per field) and tuple subclasses round-trip correctly. tree_merge was still using the plain TreeType(<generator>) form, so merging two namedtuple pytrees binds the whole generator to the first field and raises a misleading TypeError pointing at the merge function:

from mlx.utils import tree_merge
from typing import NamedTuple

class Params(NamedTuple):
    m: int
    b: int

tree_merge(Params(1, 2), Params(10, 20), lambda a, b: a + b)
# TypeError: <lambda>() missing 1 required positional argument: 'b'

This applies the same reconstruction idiom already used by tree_map/tree_map_with_path so namedtuples and tuple subclasses merge correctly, while plain lists and tuples are unchanged.

Changes

  • tree_merge reconstructs _fields-bearing containers with TreeType(*subtrees).
  • Extended test_supported_trees to cover tree_merge over a namedtuple and a tuple subclass.

Result

tree_merge(Params(1, 2), Params(10, 20), lambda a, b: a + b)
# Params(m=11, b=22)

tree_map and tree_map_with_path reconstruct list/tuple containers with
`TreeType(*subtrees) if hasattr(tree, "_fields") else TreeType(subtrees)`
so that namedtuples (which take one positional arg per field) and tuple
subclasses round-trip correctly. tree_merge still used the plain
`TreeType(<generator>)` form, so merging two namedtuple pytrees bound the
whole generator to the first field and raised a misleading TypeError
about the merge function's arguments.

Mirror the same reconstruction idiom in tree_merge and extend
test_supported_trees to cover tree_merge over a namedtuple and a tuple
subclass.

@angeloskath angeloskath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, thanks!

@angeloskath
angeloskath merged commit f27b2cd into ml-explore:main Jun 17, 2026
16 checks passed
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.

2 participants