Git Product home page Git Product logo

tree-math's Introduction

tree-math: mathematical operations for JAX pytrees

tree-math makes it easy to implement numerical algorithms that work on JAX pytrees, such as iterative methods for optimization and equation solving. It does so by providing a wrapper class tree_math.Vector that defines array operations such as infix arithmetic and dot-products on pytrees as if they were vectors.

Why tree-math

In a library like SciPy, numerical algorithms are typically written to handle fixed-rank arrays, e.g., scipy.integrate.solve_ivp requires inputs of shape (n,). This is convenient for implementors of numerical methods, but not for users, because 1d arrays are typically not the best way to keep track of state for non-trivial functions (e.g., neural networks or PDE solvers).

tree-math provides an alternative to flattening and unflattening these more complex data structures ("pytrees") for use in numerical algorithms. Instead, the numerical algorithm itself can be written in way to handle arbitrary collections of arrays stored in pytrees. This avoids unnecessary memory copies, and gives the user more control over the memory layouts used in computation. In practice, this can often makes a big difference for computational efficiency as well, which is why support for flexible data structures is so prevalent inside libraries that use JAX.

Installation

tree-math is implemented in pure Python, and only depends upon JAX.

You can install it from PyPI: pip install tree-math.

User guide

tree-math is simple to use. Just pass arbitrary pytree objects into tree_math.Vector to create an a object that arithmetic as if all leaves of the pytree were flattened and concatenated together:

>>> import tree_math as tm
>>> import jax.numpy as jnp
>>> v = tm.Vector({'x': 1, 'y': jnp.arange(2, 4)})
>>> v
tree_math.Vector({'x': 1, 'y': DeviceArray([2, 3], dtype=int32)})
>>> v + 1
tree_math.Vector({'x': 2, 'y': DeviceArray([3, 4], dtype=int32)})
>>> v.sum()
DeviceArray(6, dtype=int32)

You can also find a few functions defined on vectors in tree_math.numpy, which implements a very restricted subset of jax.numpy. If you're interested in more functionality, please open an issue to discuss before sending a pull request. (In the long term, this separate module might disappear if we can support Vector objects directly inside jax.numpy.)

Vector objects are pytrees themselves, which means the are compatible with JAX transformations like jit, vmap and grad, and control flow like while_loop and cond.

When you're done manipulating vectors, you can pull out the underlying pytrees from the .tree property:

>>> v.tree
{'x': 1, 'y': DeviceArray([2, 3], dtype=int32)}

As an alternative to manipulating Vector objects directly, you can also use the functional transformations wrap and unwrap (see the "Writing an algorithm" below). Or you can create your own Vector-like objects from a pytree with VectorMixin or tree_math.struct (see "Custom vector classes" below).

One important difference between tree_math and jax.numpy is that dot products in tree_math default to full precision on all platforms, rather than defaulting to bfloat16 precision on TPUs. This is useful for writing most numerical algorithms, and will likely be JAX's default behavior in the future.

It would be nice to have a Matrix class to make it possible to use tree-math for numerical algorithms such as L-BFGS which use matrices to represent stacks of vectors. If you're interesting in contributing this feature, please comment on this GitHub issue.

Writing an algorithm

Here is how we could write the preconditioned conjugate gradient method. Notice how similar the implementation is to the pseudocode from Wikipedia, unlike the implementation in JAX. Both versions support arbitrary pytrees as input:

import functools
from jax import lax
import tree_math as tm
import tree_math.numpy as tnp

@functools.partial(tm.wrap, vector_argnames=['b', 'x0'])
def cg(A, b, x0, M=lambda x: x, maxiter=5, tol=1e-5, atol=0.0):
  """jax.scipy.sparse.linalg.cg, written with tree_math."""
  A = tm.unwrap(A)
  M = tm.unwrap(M)

  atol2 = tnp.maximum(tol**2 * (b @ b), atol**2)

  def cond_fun(value):
    x, r, gamma, p, k = value
    return (r @ r > atol2) & (k < maxiter)

  def body_fun(value):
    x, r, gamma, p, k = value
    Ap = A(p)
    alpha = gamma / (p.conj() @ Ap)
    x_ = x + alpha * p
    r_ = r - alpha * Ap
    z_ = M(r_)
    gamma_ = r_.conj() @ z_
    beta_ = gamma_ / gamma
    p_ = z_ + beta_ * p
    return x_, r_, gamma_, p_, k + 1

  r0 = b - A(x0)
  p0 = z0 = M(r0)
  gamma0 = r0 @ z0
  initial_value = (x0, r0, gamma0, p0, 0)

  x_final, *_ = lax.while_loop(cond_fun, body_fun, initial_value)
  return x_final

Custom vector classes

You can also make your own classes directly support math like Vector. To do so, either inherit from tree_math.VectorMixin on your pytree class, or use tree_math.struct (similar to flax.struct) to create pytree and tree math supporting dataclass:

import jax
import tree_math

@tree_math.struct
class Point:
  x: float | jax.Array
  y: float | jax.Array

a = Point(0.0, 1.0)
b = Point(2.0, 3.0)

a + 3 * b  # Point(6.0, 10.0)
jax.grad(lambda x, y: x @ y)(a, b)  # Point(2.0, 3.0)

tree-math's People

Contributors

cgarciae avatar pnorgaard avatar shoyer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tree-math's Issues

Rename wrap/unwrap?

These are rather undescriptive names, and I guess most people (including myself!) will have to guess & check to keep them straight. :)

Some other possibilities, in rough order of increasing descriptiveness:

  • tree_wrap/tree_unwrap
  • transform/untransform
  • automath/undomath
  • vectorize/unvectorize
  • tree_vectorize/tree_unvectorize
  • vector_to_tree_func/tree_to_vector_func

Any favorites?

Unexpected input type for array?

I'm not sure if I'm using this right, but here's what I have:

from tree_math import Vector
from typing import Any, Callable, TypeVar
from jax.scipy.optimize import minimize

T = TypeVar('T')


def tree_minimize(fun: Callable[[T], RealNumeric], x0: T,
                  *,
                  method: str,
                  tol: float | None = None,
                  options: None | Mapping[str, Any] = None) -> T:
    wrapped = Vector(x0)
    def wrapped_fun(x: Vector) -> RealNumeric:
        return fun(x.tree)
    optimize_result = minimize(wrapped_fun, wrapped, method=method, tol=tol, options=options)
    return optimize_result.x.tree  # type: ignore[attr-defined]

When I call this, I get:

  File "/home/neil/.cache/pypoetry/virtualenvs/cmm-tspD8tmv-py3.10/lib/python3.10/site-packages/jax/_src/scipy/optimize/minimize.py", line 103, in minimize
    results = minimize_bfgs(fun_with_args, x0, **options)
  File "/home/neil/.cache/pypoetry/virtualenvs/cmm-tspD8tmv-py3.10/lib/python3.10/site-packages/jax/_src/scipy/optimize/bfgs.py", line 102, in minimize_bfgs
    converged=jnp.linalg.norm(g_0, ord=norm) < gtol,
  File "/home/neil/.cache/pypoetry/virtualenvs/cmm-tspD8tmv-py3.10/lib/python3.10/site-packages/jax/_src/numpy/linalg.py", line 438, in norm
    x, = _promote_dtypes_inexact(jnp.asarray(x))
  File "/home/neil/.cache/pypoetry/virtualenvs/cmm-tspD8tmv-py3.10/lib/python3.10/site-packages/jax/_src/numpy/lax_numpy.py", line 1924, in asarray
    return array(a, dtype=dtype, copy=False, order=order)
  File "/home/neil/.cache/pypoetry/virtualenvs/cmm-tspD8tmv-py3.10/lib/python3.10/site-packages/jax/_src/numpy/lax_numpy.py", line 1903, in array
    raise TypeError(f"Unexpected input type for array: {type(object)}")
TypeError: Unexpected input type for array: <class 'tree_math._src.vector.Vector'>

I thought Vector was supposed to pretend to be a jax.Array? Is it impossible to add a __jax_array__ method to tree_math.VectorMixin?

New release?

Is there a roadmap for the next release? Thanks.

Matrix support

I'd like to add a Matrix class to complement Vector.

A key design question is what this needs to support. In particular: do we need to support multiple axes that correspond to flattened pytrees, or is only a single axis enough?

If we only need to support a single "tree axis", then most Matrix operations can be implemented essentially by calling vmap on a Vector, and the implementation only needs to keep track of whether the "tree axis" on the underlying pytree is at the start or the end. This would suffice for use-cases like implementing L-BFGS or GMRES, which keep track of some fixed number of state vectors in the form of a matrix.

In contrast, multiple "tree axes" would be required to fully support use cases where both the inputs and outputs of a linear map correspond to (possible different) pytrees. For example, consider the outputs of jax.jacobian on a pytree -> pytree function. Here the implemention would need to be more complex to keep track of the separate tree definitions for inputs/outputs, similar to my first attempt at implementing a tree vectorizing transformation: google/jax#3263.

My inclination is to only implement the "single tree-axis" version of matrix, which the reasoning being that it suffices to implement most "efficient" numerical algorithms on large-scale inputs, which cannot afford to use O(n^2) memory. On the other hand, it does preclude the interesting use-case of using tree-math to implement jax.jacobian (and variations).

VectorMixin

Hey! Continuing the discussion about VectorMixin for pytree classes, I see two ways to implement this:

  1. VectorMixin inherits from Vector and overrides the tree property to return self. Roughly implemented as:
class VectorMixin(tm.Vector):
    """A mixin class for vector operations that works with any pytree class"""

    @property
    def tree(self):
        return self
  1. VectorMixin does not inherit from Vector, instead of using .tree it assumes self is a pytree and implements all the operators based on this. Vector inherits from VectorMixin and implements the pytree protocol roughly as:
@tree_util.register_pytree_node_class
class Vector(VectorMixin):
  """A wrapper for treating an arbitrary pytree as a 1D vector."""

  def __init__(self, tree):
    self._tree = tree

  def tree_flatten(self):
    return (self._tree,), None

  @classmethod
  def tree_unflatten(cls, _, args):
    return cls(*args)
  
  ...

First option is the easiest, second requires a refactor but its more in the spirit of what a mixin "should be". WDYT?

`tm.unwrap`: Error when `out_vectors` is list [documentation]

import jax.numpy as jnp 
import tree_math as tm

def f(x, y):
  return x, y
  
x = y = tm.Vector(jnp.array(0.))

tm.unwrap(f, out_vectors = (True, False))(x, y)
# (tree_math.Vector(DeviceArray(0., dtype=float32, weak_type=True)), DeviceArray(0., dtype=float32, weak_type=True))
tm.unwrap(f, out_vectors = [True, False])(x, y)
# ValueError: Expected list, got (DeviceArray(0., dtype=float32, weak_type=True), DeviceArray(0., dtype=float32, weak_type=True)).

Operations should allow shape broadcasting

It seems like the current implementation doesn't allow broadcasting arguments. Here's an example for normalizing leafs.

import tree_math as tm
import jax
import jax.numpy as jnp

a = jnp.ones(10)
b = jnp.ones(5)

v = tm.Vector({'a': a, 'b': b})
v / jax.tree_map(jnp.linalg.norm, v)

returns the following error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-19-c2a8ad9c2f8f> in <module>()
----> 1 v / jax.tree_map(jnp.linalg.norm, v)

2 frames
/usr/local/lib/python3.7/dist-packages/tree_math/_src/vector.py in wrapper(self, other)
     72   """Implement a forward binary method, e.g., __add__."""
     73   def wrapper(self, other):
---> 74     return broadcasting_map(func, self, other)
     75   wrapper.__name__ = f"__{name}__"
     76   return wrapper

/usr/local/lib/python3.7/dist-packages/tree_math/_src/vector.py in broadcasting_map(func, *args)
     65   if not vector_args:
     66     return func2()  # result is a scalar
---> 67   _flatten_together(*[arg.tree for arg in vector_args])  # check shapes
     68   return tree_util.tree_map(func2, *vector_args)
     69 

/usr/local/lib/python3.7/dist-packages/tree_math/_src/vector.py in _flatten_together(*args)
     37   if not all(shapes == all_shapes[0] for shapes in all_shapes[1:]):
     38     shapes_str = " vs ".join(map(str, all_shapes))
---> 39     raise ValueError(f"tree leaves have different array shapes: {shapes_str}")
     40 
     41   return all_values, all_treedefs[0]

ValueError: tree leaves have different array shapes: [(10,), (5,)] vs [(), ()]

How well does tree-math support computation on multiple devices?

Wondering how well tree-math supports computation on multiple devices?

Let's say we have a pytree of tensors of different dimensions and want to perform some operations on each of them with tree-math, can we distribute those tasks to multiple devices (GPU, for instance)?

import struct

How should I go about importing struct? Thanks!

My attempt below fails --

import tree_math

@tree_math.struct
class Point: 
    x: float 
    y: float 

AttributeError: module 'tree_math' has no attribute 'struct'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.