Skip to content

fix(optimizer): prevent Shape/Gather from folding to constants when shape has negative (unknown) dims#2964

Draft
justinchuby with Copilot wants to merge 2 commits into
mainfrom
copilot/fix-invalid-reshape-error
Draft

fix(optimizer): prevent Shape/Gather from folding to constants when shape has negative (unknown) dims#2964
justinchuby with Copilot wants to merge 2 commits into
mainfrom
copilot/fix-invalid-reshape-error

Conversation

Copilot AI commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

FoldConstantsPass incorrectly folds Shape→Gather→Concat→Reshape patterns when the input tensor has unknown dimensions stored as integer -1 in the IR (as opposed to ir.SymbolicDim). Since -1 is an int, the all-integer check passes, causing Shape to fold into Constant(value_ints=[-1, 512, 1, ...]). Gather then returns a constant -1, which propagates into the Reshape shape — producing an invalid shape like [-1, -1] (ONNX allows at most one -1 in a Reshape shape).

Changes

  • Shape handler: add non-negativity guard — only fold to a constant when all shape dims are known positive integers:
    # before
    if all(isinstance(d, int) for d in shape_slice):
    # after
    if all(isinstance(d, int) and d >= 0 for d in shape_slice):
  • Gather handler: same guard on the symbolic-shape gather path, preventing folding when any gathered dimension value is negative.
  • Regression test: test_shape_gather_concat_reshape_with_neg1_dim — verifies that Shape is preserved and Reshape never receives multiple -1 values when the input shape contains -1 integer dims.

The root cause: ONNX IR deserializes unknown dims (dim_value=-1 in the proto) as integer -1, not ir.SymbolicDim. The existing SymbolicDim path was safe; the -1-as-int path was not.

…re negative (-1)

When a tensor shape has `-1` as an integer (representing an unknown/dynamic
dimension), the `Shape` and `Gather` handlers were incorrectly folding to
constants containing `-1`. This caused downstream `Reshape` ops to receive
multiple `-1` values (e.g., `[-1, -1]`), which is invalid in ONNX (at most
one `-1` is allowed in a Reshape shape).

The fix adds a non-negativity check: only fold `Shape`/`Gather` to a constant
when all dimension values are non-negative integers (i.e., all are known static
positive values).

Fixes #2963
Copilot AI changed the title [WIP] Fix invalid reshape issue after FoldConstantsPass fix(optimizer): prevent Shape/Gather from folding to constants when shape has negative (unknown) dims Jul 14, 2026
Copilot AI requested a review from justinchuby July 14, 2026 05:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

Invalid reshape after FoldConstantsPass in specific {Shape->Gather->Concat->Reshape} pattern

2 participants