PennyLaneAI / PennyLaneAI/catalyst

[Bug] Dynamic shape arrays and reshaping

Open
#908 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug upstream
Dominant language
Python
Stars
234
Forks
84
Avg merge
2d 15h
Merged PRs (30d)
66

Description

It turns out that there are several bugs involved in attempting to reshape dynamic shaped arrays. In particular:

  • jnp.reshape of a dynamically-shaped array with new compile-time shape results in the array being returned without any change in shape:

    @qjit(abstracted_axes={0: 'm', 1: 'n'}, keep_intermediate=True)
    def g(a):
         return jnp.reshape(a, (3, 5))
    
    a = jnp.ones([1, 3], dtype=float)
    g(a)
    

    I would expect the output to be of shape (3, 5) but with junk values for the out of bound elements.

  • jnp.reshape of a dynamically-shaped array with new dynamic shape results in a segfault during compilation. Lowering to MLIR seems to happen correctly, but we suspect that mhlo.dynamic_reshape doesn't have a lowering rule.

    @qjit(abstracted_axes={0: 'm', 1: 'n'}, keep_intermediate=True)
    def g(a):
         return jnp.reshape(a, (a.shape[1], a.shape[0]))
    
    a = jnp.ones([1, 3], dtype=float)
    g(a)
    
    • Separately, we should consider adding a proper exception to catch this, rather than the segfault killing the kernel.
  • jnp.reshape of a dynamically-shaped array within a loop iteration leads to a cryptic error even before compilation:

    >>> @qjit(abstracted_axes={0: 'm', 1: 'n'})
    ... def g(x):
    ...     @catalyst.for_loop(0, 10, 1, experimental_preserve_dimensions=False)
    ...     def loop(_, a):
    ...         return jnp.reshape(a, (3, 1))
    ...     return loop(x)
    >>> a = jnp.ones([1, 3], dtype=float)
    >>> g(a)
    ValueError: Too few leaves for PyTreeDef; expected 1, got 0
    

Originally posted by @josh146 in https://github.com/PennyLaneAI/catalyst/pull/904#discussion_r1667077464

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 reproducing the three jnp.reshape cases using qjit, dynamic abstracted_axes, and catalyst.for_loop. Trace the MLIR lowering and the suspected mhlo.dynamic_reshape path, then verify that compile-time and dynamic reshapes behave as specified, loop reshaping no longer raises the PyTree error, and invalid cases produce a proper exception instead of a segfault.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.