Skip to content

[Tensor] Support shape-axis layouts for vector and matrix tensors - #991

Open
hughperkins wants to merge 121 commits into
mainfrom
hp/compound-layout
Open

hughperkins wants to merge 121 commits into
mainfrom
hp/compound-layout

Conversation

@hughperkins

@hughperkins hughperkins commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Builds on the helper renames in #994 and test organization in #996, both merged into main. This PR targets main, adds compound layouts, fuses NumPy import helpers, and removes obsolete layout-rejection and factory-hint tests.

Vector and matrix tensors now accept shape-axis layout= permutations through all three factories: qd.tensor, qd.Vector.tensor, and qd.Matrix.tensor. Both FIELD and NDARRAY backends keep component axes innermost and user-facing indexing canonical.

For example, qd.Vector.tensor(3, qd.f32, shape=(4, 5), layout=(1, 0)) uses physical storage order (5, 4, 3) while exporting canonical shape (4, 5, 3).

  • Delegate the vector/matrix convenience factories to the generic factory so layout validation and allocation are shared.
  • Extend ndarray DLPack permutations with unchanged component axes, and use canonical shapes for NumPy/Torch imports and exports.
  • Add _total_canonical_shape() and unify scalar, vector, and matrix NumPy imports in _copy_from_numpy(), sharing validation and synchronization while retaining the existing copy kernels.
  • Preserve layout through vector/matrix pickle reconstruction and deepcopy, retaining compatibility with older pickles.
  • Document the semantics and cover indexing, iteration, copied and zero-copy interop, copying across layouts, serialization, gradients, validation, and kernel specialization.

Validation:

  • Representative cases at 4722e3f3d: 87 CPU/CUDA tests passed across compound layouts and convenience factories. Each general compound-layout test has one parameterization covering all four backend/type pairs. Dtype constants were subsequently inlined into the cases; formatting and lint checks passed.
  • At 5a3479a9b, general compound-layout tests run on all enabled architectures. The available CPU/CUDA environment passed 179 cases with python tests/run_tests.py -v -t 2 test_tensor_compound_layout test_tensor_factory_vec_mat. NumPy zero-copy remains CPU-only; Torch/DLPack excludes Vulkan and skips Metal FIELD sharing on unsupported PyTorch versions. Metal, AMDGPU, and Vulkan were unavailable in this validation environment.
  • After stacking on [Tensor] Move test_tensor_pr560_fixes.py tests into other test files #996, all 16 relocated regressions passed on CPU at abc6cf109, including the updated factory-hint tests. The unchanged 16 tests also passed independently on the [Tensor] Move test_tensor_pr560_fixes.py tests into other test files #996 base.
  • _total_physical_layout() extraction at bfa0e9148: 227 CPU/CUDA compound-layout and interop cases passed, with 2 skips. The subsequent variable rename and merge of main passed formatting, lint, and non-ASCII checks; the merge leaves branch file contents unchanged.
  • Stacked branch at ed7b8ffda: 589 CPU/CUDA cases passed across ndarray, factories, compound layouts, error handling, gradients, wrapper surface, and layouts. The subsequent base-branch ASCII punctuation fix leaves this branch's file contents unchanged.
  • At 22c0cceca: 412 CPU/CUDA ndarray and layout cases passed after unifying NumPy imports. The subsequent _copy_to_torch() rename passed formatting and lint checks.
  • At 3062f762c: 122 compound-layout CPU/CUDA cases passed after adding _total_canonical_shape(), including copied and zero-copy Torch interop.
  • At 9d5be3558: C++ rebuild succeeded; 412 ndarray and layout CPU/CUDA cases passed after the physical-shape rename.
  • At b09c32bd577085dd5ad9249680e3d6083d510b59: 383 CPU/CUDA cases passed after removing the private factory helpers. These cover factories, compound layouts, error messages, gradients, wrappers, and layouts.
  • The earlier run at eeb56dca6282854e2fdef67783b3ba1b897e2be4 also passed 589 existing regression cases, with 2 skips.
  • Pre-commit checks passed. Pyright: 0 errors, 8 warnings.

Reproduce the shape-helper validation with:

python tests/run_tests.py --arch cpu,cuda -v -t 2 test_ndarray test_tensor_compound_layout test_tensor_layout

Reproduce the factory validation with:

python tests/run_tests.py --arch cpu,cuda -v -t 2 \
  test_tensor_factory_vec_mat test_tensor_compound_layout \
  test_tensor_grad test_tensor_wrapper_surface test_tensor_layout

The earlier regression run also exercised:

python tests/run_tests.py --arch cpu,cuda -v -t 2 \
  test_tensor_layout test_tensor_factory_vec_mat test_tensor_factory_layout_ndarray \
  test_tensor_wrapper_surface test_tensor_layout_host_indexing test_tensor_layout_interop \
  test_tensor_layout_grad test_ndarray test_pickle

Fixes #936.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-28T19:05:56.449446Z 881016c Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@hughperkins hughperkins changed the title Support shape-axis layouts for vector and matrix tensors [Tensor] Support shape-axis layouts for vector and matrix tensors Oct 26, 2026
@github-actions

Copy link
Copy Markdown

Comment thread python/quadrants/_tensor.py

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this file seems ok-ish

@github-actions

Copy link
Copy Markdown

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this file okish

Comment thread python/quadrants/_tensor_wrapper.py
return t


def _rebuild_matrix_tensor(

@hughperkins hughperkins Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_rebuild_matrix_tensor function ok

return t # type: ignore[reportReturnType]


def _rebuild_vector_tensor(

@hughperkins hughperkins Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_rebuild_vector_tensor function ok

def element_shape(self) -> typing.Tuple[int, ...]:
return _element_shape_of(self._impl)

def __reduce__(self) -> typing.Tuple[typing.Any, typing.Tuple[typing.Any, ...]]:

@hughperkins hughperkins Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reduce function ok

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this file changs ok

# work on one backend and raise cryptic errors deep in the other. Users who need backend-specific knobs (e.g.
# ``offset=`` for field offset indexing, ``order=`` for SoA layouts) should call ``qd.field`` / ``qd.ndarray`` directly
# — they have explicitly opted out of the unified tensor API.
#

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this change ok

_TENSOR_ACCEPTED_KWARGS = frozenset({"backend", "needs_grad", "layout"})


def _validate_kwargs(kwargs, *, factory_name, accepted):

@hughperkins hughperkins Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changes in _validate_kwargs function ok

Comment thread python/quadrants/_tensor.py Outdated
Comment thread python/quadrants/_tensor.py
return "".join(chr(ord("i") + axis) for axis in layout)


def tensor(dtype, shape, *, backend=Backend.NDARRAY, layout=None, **kwargs):

@hughperkins hughperkins Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tensor function ok

@github-actions

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown

Comment thread python/quadrants/lang/matrix.py

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this file ok

@github-actions

Copy link
Copy Markdown

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this file ok (reviwed earelir, before the rename/mege)

reason="Coverage probes change the kernel AST, preventing offline cache hits after reinit",
)
@test_utils.test()
def test_compound_layout_offline_cache(backend: qd.Backend, dtype: MatrixType, tmp_path: Path) -> None:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test_compound_layout_offline_cache ok 🥵

],
)
@test_utils.test()
def test_compound_layout_fastcache(dtype: MatrixType, tmp_path: Path) -> None:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test_compound_layout_fastcache ok

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this file ok 🙌

@hughperkins

hughperkins commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

Finally, review ok 🙌

Lets wait for CI green-ish, and recheck Mr Codex review.

@hughperkins

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5e13254c79

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread python/quadrants/lang/_ndarray.py
@github-actions

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown

@test_utils.test()
def test_compound_layout_grad(backend: qd.Backend, dtype: MatrixType, request: pytest.FixtureRequest) -> None:
"""Check that gradients retain the layout and compute correct values across different input and output layouts."""
if sys.platform == "darwin" and qd.lang.impl.current_cfg().arch == qd.vulkan and backend == qd.Backend.NDARRAY:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this xfail seems ok-ish

@hughperkins

Copy link
Copy Markdown
Collaborator Author

Ok, so we'll merged once CI green-ish.

@github-actions

Copy link
Copy Markdown

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

@github-actions

Copy link
Copy Markdown

@hughperkins

Copy link
Copy Markdown
Collaborator Author

@codex review

@github-actions

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

qd.tensor rejects layout= with a vector / matrix dtype

1 participant