patrick-kidger / patrick-kidger/jaxtyping

Jaxtyping a class with mutable shapes

Open
#303 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

question
Dominant language
Python
Stars
1.9k
Forks
96
PR merge metrics
No merged PRs in 30d

Description

I want to typecheck a class (typedict in the below example) with the contract that at any instant, all shape variables (eg. B, T, H, W) are the same for all tensors in the class but transforms such as crop_sample can modify the class. Is there a way to rebind H, W after such shape altering operations?

from typing import TypedDict

import torch
from jaxtyping import Float32, jaxtyped
from typeguard import typechecked



@jaxtyped(typechecker=typechecked)
class MyDict (TypedDict, total=False):
    foo1: Float32[torch.Tensor, "B T 3 H W"]
    foo2: Float32[torch.Tensor, "B T 3 H W"]
    baz: Float32[torch.Tensor, "B 1 4 4"]


@jaxtyped(typechecker=typechecked)
def crop_sample(dict: MyDict) -> MyDict:
    # Ensure we modify all tensors with the same crop
    h_start, w_start = 50, 50
    foo1 = dict["foo1"][:, :, :, h_start:, w_start:]
    foo2 = dict["foo2"][:, :, :, h_start:, w_start:]
    dict["foo1"] = foo1
    dict["foo2"] = foo2
    return dict


if __name__ == "__main__":
    my_dict = MyDict(foo1=torch.randn(1, 1, 3, 100, 100), foo2=torch.randn(1, 1, 3, 100, 100))
    print(my_dict["foo1"].shape)
    my_dict = crop_sample(my_dict)
    print(my_dict["foo1"].shape)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the supplied Python example with the TypedDict, @jaxtyped, and crop_sample definitions to reproduce the mutable-shape case. Trace how jaxtyping handles symbolic shape bindings across decorated function calls. Done should be a documented, supported answer or design for preserving the shared-shape contract after shape-changing operations.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.