patrick-kidger / patrick-kidger/jaxtyping
Stateful Equinox Module: how to annotate?
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 1.9k
- Forks
- 96
- PR merge metrics
- No merged PRs in 30d
Description
I recently come up with the following code:
from typing import Self
import equinox as eqx
from beartype import beartype
from jax import numpy as jnp
from jaxtyping import Array, Float, jaxtyped
@jaxtyped(typechecker=beartype) # to typecheck __init__
@beartype
class Accumulator(eqx.Module):
x: Float[Array, " n"]
@jaxtyped
def add(self, y: Float[Array, " n"]) -> Self:
return self.__class__(self.x + y)
Now, when running this code, jaxtyped complained in a UserWarning saying that it prefers the @jaxtyped(typechecker=beartype) syntax. (This warning was added before beartype's __instancecheck_str__ pseudostandard was implemented.) However, in this context, such syntax will lead to an error by beartype, because it lacks the context to figure out what typing.Self refers to. Therefore the code above is the only way to get it running.
However, this Accumulator faces an issue: If you write
@jaxtyped(typechecker=beartype)
def test_accumulator():
x = jnp.ones(3)
y = jnp.ones(4)
acc1 = Accumulator(x)
acc1 = acc1.add(x)
acc2 = Accumulator(y)
acc2 = acc2.add(y)
return acc1, acc2
In calling acc2.add(y), it seems that n=3 is still in the memo from the previous acc1.add(x) call, and a type check error BeartypeCallHintParamViolation will be raised.
So, my question is: how do one properly type-annotate this kind of class?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the Accumulator example and the test_accumulator entry point with arrays of lengths 3 and 4. Inspect how @jaxtyped, @beartype, typing.Self, and shape-variable memoization interact; done means establishing a supported annotation pattern or a clearly documented limitation without the stale n binding causing the second call to fail.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 32/100