Repository navigation
feat: add element-wise left_shift and right_shift ops - #345
dschulmeist wants to merge 1 commit into
Conversation
Adds Array methods, free functions, and macros for element-wise left_shift and right_shift, mirroring the pattern of the existing arithmetic ops. Both inputs must be of integer dtype; right shift on signed integers is arithmetic (sign-preserving), matching the upstream MLX behaviour. Includes tests for broadcast, signed shift, and incompatible-shape error paths.
|
Sorry for the long silence here. We looked at this and hit a snag: MLX itself doesn't validate shift counts, so negative or >= bit-width counts are C++ UB and the results are inconsistent across dtypes (int32 wraps the count, uint8 truncates). We don't want to freeze that into the API, so we're holding shift wrappers until upstream defines the behavior — leaving this open to track it. |
|
Quick update: upstream fixed this in ml-explore/mlx#4694 (merged 10-29). Out-of-range counts now give 0, or -1 for a negative value shifted right, like numpy and jax. It isn't in an MLX release yet, so we'll pick this up once our pinned MLX includes it. Main has moved a fair bit since April (new ops don't get |
Closes #129.
Changes
Adds element-wise
left_shiftandright_shifttomlx-rs/src/ops/arithmetic.rs:Array::left_shift/Array::left_shift_deviceand the matching free functions inops::, plus theleft_shift!macro generated by#[generate_macro].right_shift.Both operands must be of integer dtype. Right shift on signed integers is arithmetic (sign-preserving), matching upstream MLX, mlx-swift, and numpy semantics.
Naming
The issue title is
shift_left/shift_right, but I went withleft_shift/right_shift:mlx_left_shift/mlx_right_shift.mx.left_shift/mx.right_shift.leftShift/rightShift.Happy to rename if the maintainers prefer the issue's wording.
Testing
Six new unit tests cover the public surface (
cargo test -p mlx-rs --lib left_shift right_shift):test_left_shift—[1,2,4,8] << [1,1,2,3] == [2,4,16,64]and inputs unchanged.test_left_shift_broadcast— scalar broadcast (free function form).test_left_shift_invalid_broadcast— shape mismatch returnsErr.test_right_shift—[16,32,64,128] >> [1,2,3,4] == [8,8,8,8].test_right_shift_arithmetic_for_signed—[-8,-16,-32] >> 1 == [-4,-8,-16].test_right_shift_invalid_broadcast.Doc examples for both methods compile and run via
cargo test -p mlx-rs --doc.