fix: element-wise operations on transposed/swap-axes views return wrong data - #31
Merged
Merged
Conversation
with non-C-contiguous strides
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR fixes a bug where element-wise operations (clamp, log, exp, add, multiply, sqrt, etc.) on transposed or swap-axes views returned data in raw buffer order instead of the view's logical order.
Motivation and Context
When an NDArray view had strides matching an F-contiguous layout (e.g., strides
[1, 3]for a transposed[3, 3]matrix), ndarray'smap()fast path interpreted the raw C-ordered buffer as F-ordered data, producing wrong results. This affected all operations using element-wise mapping — clamp, log, exp, add_scalar, multiply_scalar, and 30+ math functions. The bug was discovered in production in the TransformersPHP test suite and confirmed with direct PHP-side element-by-element verification.What's Changed
extract_view_*toextract_array_*and changed return type fromArrayViewDtoArrayDwith internal correctness logic — C-contiguous strides use memcpy, custom strides use stride-based iterationextract_array_mut_*toextract_view_mut_*to accurately reflect the mutable view return typeextract_array_*results to accept&ArrayD<T>instead ofArrayViewD<T>define_extract_view_asinternal.to_owned()call, now handled bydefine_extract_arrayShapeOpsTestcovering transpose→clamp, swapaxes→clamp, and slice→transpose→clampBreaking Changes
None. All public PHP APIs remain unchanged. This is purely an internal Rust-layer fix