{"id":13869738,"url":"https://github.com/cgarciae/treex","last_synced_at":"2025-07-15T18:31:53.562Z","repository":{"id":37846589,"uuid":"394865540","full_name":"cgarciae/treex","owner":"cgarciae","description":"A Pytree Module system for Deep Learning in JAX","archived":true,"fork":false,"pushed_at":"2023-02-26T16:55:36.000Z","size":4558,"stargazers_count":215,"open_issues_count":16,"forks_count":17,"subscribers_count":8,"default_branch":"master","last_synced_at":"2024-05-02T01:24:40.241Z","etag":null,"topics":["deep-learning","jax"],"latest_commit_sha":null,"homepage":"https://cgarciae.github.io/treex/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cgarciae.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-08-11T04:49:22.000Z","updated_at":"2024-06-20T23:26:09.413Z","dependencies_parsed_at":"2024-06-20T23:26:05.338Z","dependency_job_id":"edb87912-8244-47d8-8d5a-faee1c93cd90","html_url":"https://github.com/cgarciae/treex","commit_stats":null,"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"purl":"pkg:github/cgarciae/treex","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cgarciae%2Ftreex","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cgarciae%2Ftreex/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cgarciae%2Ftreex/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cgarciae%2Ftreex/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cgarciae","download_url":"https://codeload.github.com/cgarciae/treex/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cgarciae%2Ftreex/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265451443,"owners_count":23767768,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["deep-learning","jax"],"created_at":"2024-08-05T20:01:14.648Z","updated_at":"2025-07-15T18:31:53.140Z","avatar_url":"https://github.com/cgarciae.png","language":"Python","funding_links":[],"categories":["Python"],"sub_categories":[],"readme":"_Deprecation Notice_: This library was an experiment trying to get pytree Modules working with Flax-like colletions. I'd currently recommend the following alternatives:\n* Just custom pytrees: [simple_pytree](https://github.com/cgarciae/simple-pytree)\n* Pytree module system: [equinox](https://github.com/patrick-kidger/equinox)\n* Production ready module system: [flax](https://github.com/google/flax)\n\n# Treex\n\n_A Pytree Module system for Deep Learning in JAX_\n\n#### Main Features\n\n* 💡 **Intuitive**: Modules contain their own parameters and respect Object Oriented semantics like in PyTorch and Keras.\n* 🌳 **Pytree-based**:  Modules are Pytrees whose leaves are its parameters, meaning they are fully compatible with `jit`, `grad`, `vmap`, etc.\n\nTreex is implemented on top of [Treeo](https://github.com/cgarciae/treeo) and reexports all of its API for convenience.\n\n[Getting Started](#getting-started) | [User Guide](https://cgarciae.github.io/treex/user-guide/intro) | [Examples](#examples) |  [Documentation](https://cgarciae.github.io/treex)\n\n## What is included?\n* A base `Module` class.\n* A `nn` module for with common layers implemented as wrappers over Flax layers.\n* A `losses` module with common loss functions.\n* A `metrics` module with common metrics.\n* An `Optimizer` class that can wrap any optax optimizer.\n## Why Treex?\n\u003cdetails\u003e\n\u003csummary\u003eShow\u003c/summary\u003e\u003cbr\u003e\n\nDespite all JAX benefits, current Module systems are not intuitive to new users and add additional complexity not present in frameworks like PyTorch or Keras. Treex takes inspiration from S4TF and delivers an intuitive experience using JAX Pytree infrastructure.\n\n\u003cdetails\u003e\n\u003csummary\u003eCurrent Alternative's Drawbacks and Solutions\u003c/summary\u003e\n\nCurrently we have many alternatives like Flax, Haiku, Objax, that have one or more of the following drawbacks:\n\n* Module structure and parameter structure are separate, and parameters have to be manipulated around by the end-user, which is not intuitive. In Treex, parameters are stored in the modules themselves and can be accessed directly.\n* Monadic architecture adds complexity. Flax and Haiku use an `apply` method to call modules that set a context with parameters, rng, and different metadata, which adds additional overhead to the API and creates an asymmetry in how Modules are being used inside and outside a context. In Treex, modules can be called directly.\n* Among different frameworks, parameter surgery requires special consideration and is challenging to implement. Consider a standard workflow such as transfer learning, transferring parameters and state from a  pre-trained module or submodule as part of a new module; in different frameworks, we have to know precisely how to extract their parameters and how to insert them into the new parameter structure/dictionaries such that it is in agreement with the new module structure. In Treex, just as in PyTorch / Keras, we enable to pass the (sub)module to the new module, and parameters are automatically added to the new structure.\n* Multiple frameworks deviate from JAX semantics and require particular versions of `jit`, `grad`, `vmap`, etc., which makes it harder to integrate with other JAX libraries. Treex's Modules are plain old JAX PyTrees and are compatible with any JAX library that supports them.\n* Other Pytree-based approaches like Parallax and Equinox do not have a total state management solution to handle complex states as encountered in Flax. Treex has the Filter and Update API, which is very expressive and can effectively handle systems with a complex state.\n\n\u003c/details\u003e\n\u003c/details\u003e\n\n## Installation\nInstall using pip:\n```bash\npip install treex\n```\n\n\n## Getting Started\n\u003c!-- Remake Getting Started now that most content is in the User Guide --\u003e\n\nThis is a small appetizer to give you a feel for how using Treex looks like, be sure to checkout the [User Guide](https://cgarciae.github.io/treex/user-guide/intro) for a more in-depth explanation.\n```python\nimport treex as tx\nimport numpy as np\nimport jax, optax\n\n\n# create some data\nx = np.random.uniform(size=(50, 1))\ny = 1.3 * x ** 2 - 0.3 + np.random.normal(size=x.shape)\n\n\n\n# initialize a Module, its simple\nmodel = tx.MLP([64, 1]).init(key=42, inputs=x)\n# define an optimizer, init with model params\noptimizer = tx.Optimizer(optax.adam(4e-3)).init(model)\n\n\n\n# define loss function, notice\n# Modules are jit-abel and differentiable 🤯\n@jax.jit\n@jax.grad\ndef loss_fn(model: tx.MLP, x, y):\n    # forward is a simple call\n    preds = model(x)\n    # MSE\n    return ((preds - y) ** 2).mean()\n\n\n\n# basic training loop\nfor step in range(500):\n\n    # grads have the same type as model\n    grads: tx.MLP = loss_fn(model, x, y)\n    # apply the gradient updates\n    model = optimizer.update(grads, model)\n\n\n\n# Pytorch-like eval mode\nmodel = model.eval()\npreds = model(x)\n```\n#### Custom Modules\n\u003cdetails\u003e\n\u003csummary\u003eShow\u003c/summary\u003e\u003cbr\u003e\n\nModules are Treeo `Tree`s, which are Pytrees. When creating core layers you often mark fields that will contain state that JAX should be aware as `nodes` by assigning class variables to the output of functions like `tx.Parameter.node()`:\n\n```python\nimport treex as tx\n\nclass Linear(tx.Module):\n    # use Treeo's API to define Parameter nodes\n    w: jnp.ndarray = tx.Parameter.node()\n    b: jnp.ndarray = tx.Parameter.node()\n\n    def __init__(self, features_out: int):\n        self.features_out = features_out\n\n    def __call__(self, x: jnp.ndarray) -\u003e jnp.ndarray:\n        # init will call forward, we can know if we are inside it\n        if self.initializing():\n            # `next_key` only available during `init`\n            key = tx.next_key() \n            # leverage shape inference\n            self.w = jax.random.uniform(\n                key, shape=[x.shape[-1], self.features_out]\n            )\n            self.b = jnp.zeros(shape=[self.features_out])\n\n        # linear forward\n        return jnp.dot(x, self.w) + self.b\n\nmodel = Linear(10).init(key=42, inputs=x)\n```\nNode field types (e.g. `tx.Parameter`) are called Kinds and Treex exports a whole family of Kinds which serve for differente purposes such as holding non-differentiable state (`tx.BatchStats`), metric's state (`tx.MetricState`), logging, etc. Checkout the [kinds](https://cgarciae.github.io/treex/user-guide/kinds) section for more information.\n\u003c/details\u003e\n\n#### Composite Modules\n\u003cdetails\u003e\n\u003csummary\u003eShow\u003c/summary\u003e\u003cbr\u003e\n\nComposite Modules usually hold and call other Modules within them, while they would be instantiate inside `__init__` and used later in `__call__` like in Pytorch / Keras, in Treex you usually leverage the `@tx.compact` decorator over the `__call__` method to define the submodules inline.\n```python\nclass MLP(tx.Module):\n    def __init__(self, features: Sequence[int]):\n        self.features = features\n\n    # compact lets you define submodules on the fly\n    @tx.compact\n    def __call__(self, x: jnp.ndarray) -\u003e jnp.ndarray:\n        for units in self.features[:-1]:\n            x = Linear(units)(x)\n            x = jax.nn.relu(x)\n\n        return Linear(self.features[-1])(x)\n\nmodel = MLP([32, 10]).init(key=42, inputs=x)\n```\nUnder the hood all calls to submodule constructors (e.g. `Linear(...)`) inside `compact` are assigned to fields in the parent Module (`MLP`) so they are part of the same Pytree, their field names are available under the `._subtrees` attribute. `compact` must always define submodules in the same order.\n\n\u003c/details\u003e\n\n## Status\nTreex is in an early stage, things might break between versions but we will respect semanting versioning. Since Treex layers are numerically equivalent to Flax, it borrows some maturity and yields more confidence over its results. Feedback is much appreciated.\n\n**Roadmap**:\n\n- Wrap all Flax Linen Modules\n- Implement more layers, losses, and metrics.\n- Create applications and pretrained Modules.\n\nContributions are welcomed!\n\n## Sponsors 💚\n* [Quansight](https://www.quansight.com) - paid development time\n\n## Examples\nCheckout the [/examples](examples) directory for more detailed examples. Here are a few additional toy examples:\n\n\n#### Linear Regression\nThis is a simple but realistic example of how Treex is used.\n\n```python\nfrom functools import partial\nfrom typing import Union\nimport jax\nimport jax.numpy as jnp\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport optax\nimport treex as tx\n\nx = np.random.uniform(size=(500, 1))\ny = 1.4 * x - 0.3 + np.random.normal(scale=0.1, size=(500, 1))\n\n\n# differentiate only w.r.t. parameters\ndef loss_fn(params, model, x, y):\n    # merge params into model\n    model = model.merge(params)\n\n    preds = model(x)\n    loss = jnp.mean((preds - y) ** 2)\n\n    # the model may contain state updates\n    # so it should be returned\n    return loss, model\n\n\ngrad_fn = jax.value_and_grad(loss_fn, has_aux=True)\n\n# both model and optimizer are jit-able\n@jax.jit\ndef train_step(model, x, y, optimizer):\n    # select only the parameters\n    params = model.parameters()\n\n    (loss, model), grads = grad_fn(params, model, x, y)\n\n    # update params and model\n    params = optimizer.update(grads, params)\n    model = model.merge(params)\n\n    # return new model and optimizer\n    return loss, model, optimizer\n\n\nmodel = tx.Linear(1).init(42, x)\noptimizer = tx.Optimizer(optax.adam(0.01)).init(model)\n\nfor step in range(300):\n    loss, model, optimizer = train_step(model, x, y, optimizer)\n    if step % 50 == 0:\n        print(f\"loss: {loss:.4f}\")\n\n# eval mode \"turns off\" layers like Dropout / BatchNorm\nmodel = model.eval()\n\nX_test = np.linspace(x.min(), x.max(), 100)[:, None]\npreds = model(X_test)\n\nplt.scatter(x, y, c=\"k\", label=\"data\")\nplt.plot(X_test, preds, c=\"b\", linewidth=2, label=\"prediction\")\nplt.legend()\nplt.show()\n```\n\n#### A Stateful Module\nHere is an example of creating a stateful module of a `RollingMean` metric and using them with `jax.jit`. For a real use cases use the metrics inside `treex.metrics`.\n\n```python\nclass RollingMean(tx.Module):\n    count: jnp.ndarray = tx.State.node()\n    total: jnp.ndarray = tx.State.node()\n\n    def __init__(self):\n        self.count = jnp.array(0, dtype=jnp.int32)\n        self.total = jnp.array(0.0, dtype=jnp.float32)\n\n    def __call__(self, x: jnp.ndarray) -\u003e jnp.ndarray:\n        self.count += np.prod(x.shape)\n        self.total += x.sum()\n\n        return self.total / self.count\n\n@jax.jit\ndef update(x: jnp.ndarray, metric: RollingMean) -\u003e Tuple[jnp.ndarray, RollingMean]:\n    mean = metric(x)\n    return mean, metric # return mean value and updated metric\n\n\nmetric = RollingMean()\n\nfor i in range(10):\n    x = np.random.uniform(-1, 1, size=(100, 1))\n    mean, metric = update(x, metric)\n\nprint(mean)\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcgarciae%2Ftreex","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcgarciae%2Ftreex","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcgarciae%2Ftreex/lists"}