statedict2pytree 1.0.1__tar.gz → 1.0.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- Metadata-Version: 2.3
1
+ Metadata-Version: 2.4
2
2
  Name: statedict2pytree
3
- Version: 1.0.1
3
+ Version: 1.0.2
4
4
  Summary: Converts torch models into PyTrees for Equinox
5
5
  Author-email: "Artur A. Galstyan" <mail@arturgalstyan.dev>
6
6
  Requires-Python: >=3.11
7
7
  Requires-Dist: beartype
8
- Requires-Dist: equinox
8
+ Requires-Dist: equinox>=0.13.0
9
9
  Requires-Dist: jax
10
10
  Requires-Dist: jaxlib
11
11
  Requires-Dist: jaxtyping
@@ -0,0 +1,33 @@
1
+ import torch
2
+ from flax import nnx
3
+ from statedict2pytree import autoconvert, pytree_to_fields
4
+
5
+
6
+ class TorchModel(torch.nn.Module):
7
+ def __init__(self, din, dout):
8
+ super(TorchModel, self).__init__()
9
+ self.linear = torch.nn.Linear(din, dout, bias=False)
10
+ self.linear.weight.data = torch.ones_like(self.linear.weight)
11
+
12
+ def forward(self, x):
13
+ return self.linear(x)
14
+
15
+
16
+ class Model(nnx.Module):
17
+ def __init__(self, din, dout, rngs: nnx.Rngs):
18
+ self.linear = nnx.Linear(din, dout, rngs=rngs, use_bias=False)
19
+
20
+ def __call__(self, x):
21
+ return self.linear(x)
22
+
23
+
24
+ flax_model = Model(2, 64, rngs=nnx.Rngs(0))
25
+ torch_model = TorchModel(2, 64)
26
+
27
+ pt_fields = pytree_to_fields(flax_model)
28
+ print(pt_fields)
29
+
30
+ flax_model = autoconvert(flax_model, torch_model.state_dict())
31
+
32
+ print(flax_model)
33
+ print(flax_model.linear.kernel.value)
@@ -1,13 +1,13 @@
1
1
  [project]
2
2
  name = "statedict2pytree"
3
- version = "1.0.1"
3
+ version = "1.0.2"
4
4
  description = "Converts torch models into PyTrees for Equinox"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
7
7
  authors = [{ name = "Artur A. Galstyan", email = "mail@arturgalstyan.dev" }]
8
8
  dependencies = [
9
9
  "jax",
10
- "equinox",
10
+ "equinox>=0.13.0",
11
11
  "jaxlib",
12
12
  "beartype",
13
13
  "jaxtyping",
@@ -94,7 +94,7 @@ def _get_node(
94
94
  if len(path) == 0:
95
95
  return tree, state_indices
96
96
  f, *_ = path
97
- if hasattr(tree, "is_stateful"):
97
+ if hasattr(tree, "is_stateful") and tree.is_stateful():
98
98
  if state_indices is None:
99
99
  state_indices = {}
100
100
  indices = _get_stateindex_fields(tree)
@@ -109,7 +109,10 @@ def _get_node(
109
109
  elif isinstance(f, FlattenedIndexKey):
110
110
  if isinstance(tree, eqx.nn.State):
111
111
  assert state_indices is not None
112
- index = state_indices[f.key]
112
+
113
+ markers = list(tree._state.keys())
114
+ marker = markers[f.key]
115
+ index = state_indices[marker]
113
116
  subtree = tree.get(index)
114
117
  else:
115
118
  subtree = None