mlx_rs/ops/indexing/mod.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
//! Indexing Arrays
//!
//! # Overview
//!
//! Due to limitations in the `std::ops::Index` and `std::ops::IndexMut` traits (only references can
//! be returned), the indexing is achieved with the [`IndexOp`] and [`IndexMutOp`] traits where
//! arrays can be indexed with [`IndexOp::index()`] and [`IndexMutOp::index_mut()`] respectively.
//!
//! The following types can be used as indices:
//!
//! | Type | Description |
//! |------|-------------|
//! | [`i32`] | An integer index |
//! | [`Array`] | Use an array to index another array |
//! | `&Array` | Use a reference to an array to index another array |
//! | [`std::ops::Range<i32>`] | A range index |
//! | [`std::ops::RangeFrom<i32>`] | A range index |
//! | [`std::ops::RangeFull`] | A range index |
//! | [`std::ops::RangeInclusive<i32>`] | A range index |
//! | [`std::ops::RangeTo<i32>`] | A range index |
//! | [`std::ops::RangeToInclusive<i32>`] | A range index |
//! | [`StrideBy`] | A range index with stride |
//! | [`NewAxis`] | Add a new axis |
//! | [`Ellipsis`] | Consume all axes |
//!
//! # Single axis indexing
//!
//! | Indexing Operation | `mlx` (python) | `mlx-swift` | `mlx-rs` |
//! |--------------------|--------|-------|------|
//! | integer | `arr[1]` | `arr[1]` | `arr.index(1)` |
//! | range expression | `arr[1:3]` | `arr[1..<3]` | `arr.index(1..3)` |
//! | full range | `arr[:]` | `arr[0...]` | `arr.index(..)` |
//! | range with stride | `arr[::2]` | `arr[.stride(by: 2)]` | `arr.index((..).stride_by(2))` |
//! | ellipsis (consuming all axes) | `arr[...]` | `arr[.ellipsis]` | `arr.index(Ellipsis)` |
//! | newaxis | `arr[None]` | `arr[.newAxis]` | `arr.index(NewAxis)` |
//! | mlx array `i` | `arr[i]` | `arr[i]` | `arr.index(i)` |
//!
//! # Multi-axes indexing
//!
//! Multi-axes indexing with combinations of the above operations is also supported by combining the
//! operations in a tuple with the restriction that `Ellipsis` can only be used once.
//!
//! ## Examples
//!
//! ```rust
//! // See the multi-dimensional example code for mlx python https://ml-explore.github.io/mlx/build/html/usage/indexing.html
//!
//! use mlx_rs::{Array, ops::indexing::*};
//!
//! let a = Array::from_iter(0..8, &[2, 2, 2]);
//!
//! // a[:, :, 0]
//! let mut s1 = a.index((.., .., 0));
//!
//! let expected = Array::from_slice(&[0, 2, 4, 6], &[2, 2]);
//! assert_eq!(s1, expected);
//!
//! // a[..., 0]
//! let mut s2 = a.index((Ellipsis, 0));
//!
//! let expected = Array::from_slice(&[0, 2, 4, 6], &[2, 2]);
//! assert_eq!(s1, expected);
//! ```
//!
//! # Set values with indexing
//!
//! The same indexing operations (single or multiple) can be used to set values in an array using
//! the [`IndexMutOp`] trait.
//!
//! ## Example
//!
//! ```rust
//! use mlx_rs::{Array, ops::indexing::*};
//!
//! let mut a = Array::from_slice(&[1, 2, 3], &[3]);
//! a.index_mut(2, Array::from_int(0));
//!
//! let expected = Array::from_slice(&[1, 2, 0], &[3]);
//! assert_eq!(a, expected);
//! ```
//!
//! ```rust
//! use mlx_rs::{Array, ops::indexing::*};
//!
//! let mut a = Array::from_iter(0i32..20, &[2, 2, 5]);
//!
//! // writing using slices -- this ends up covering two elements
//! a.index_mut((0..1, 1..2, 2..4), Array::from_int(88));
//!
//! let expected = Array::from_slice(
//! &[
//! 0, 1, 2, 3, 4, 5, 6, 88, 88, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
//! ],
//! &[2, 2, 5],
//! );
//! assert_eq!(a, expected);
//! ```
use std::{borrow::Cow, ops::Bound, rc::Rc};
use mlx_internal_macros::default_device;
use crate::{error::Result, utils::guard::Guarded, Array, Stream, StreamOrDevice};
pub(crate) mod index_impl;
pub(crate) mod indexmut_impl;
/* -------------------------------------------------------------------------- */
/* Custom types */
/* -------------------------------------------------------------------------- */
/// New axis indexing operation.
///
/// See the module level documentation for more information.
#[derive(Debug, Clone, Copy)]
pub struct NewAxis;
/// Ellipsis indexing operation.
///
/// See the module level documentation for more information.
#[derive(Debug, Clone, Copy)]
pub struct Ellipsis;
/// Stride indexing operation.
///
/// See the module level documentation for more information.
#[derive(Debug, Clone, Copy)]
pub struct StrideBy<I> {
/// The inner iterator
pub inner: I,
/// The stride
pub stride: i32,
}
/// Helper trait for creating a stride indexing operation.
pub trait IntoStrideBy: Sized {
/// Create a stride indexing operation.
fn stride_by(self, stride: i32) -> StrideBy<Self>;
}
impl<T> IntoStrideBy for T {
fn stride_by(self, stride: i32) -> StrideBy<Self> {
StrideBy {
inner: self,
stride,
}
}
}
/// Range indexing operation.
#[derive(Debug, Clone)]
pub struct RangeIndex {
start: Bound<i32>,
stop: Bound<i32>,
stride: i32,
}
impl RangeIndex {
pub(crate) fn new(start: Bound<i32>, stop: Bound<i32>, stride: Option<i32>) -> Self {
let stride = stride.unwrap_or(1);
Self {
start,
stop,
stride,
}
}
pub(crate) fn is_full(&self) -> bool {
matches!(self.start, Bound::Unbounded)
&& matches!(self.stop, Bound::Unbounded)
&& self.stride == 1
}
pub(crate) fn stride(&self) -> i32 {
self.stride
}
pub(crate) fn start(&self, size: i32) -> i32 {
match self.start {
Bound::Included(start) => start,
Bound::Excluded(start) => start + 1,
Bound::Unbounded => {
// ref swift binding
// _start ?? (stride < 0 ? size - 1 : 0)
if self.stride.is_negative() {
size - 1
} else {
0
}
}
}
}
pub(crate) fn absolute_start(&self, size: i32) -> i32 {
// ref swift binding
// return start < 0 ? start + size : start
let start = self.start(size);
if start.is_negative() {
start + size
} else {
start
}
}
pub(crate) fn end(&self, size: i32) -> i32 {
match self.stop {
Bound::Included(stop) => stop + 1,
Bound::Excluded(stop) => stop,
Bound::Unbounded => {
// ref swift binding
// _end ?? (stride < 0 ? -size - 1 : size)
if self.stride.is_negative() {
-size - 1
} else {
size
}
}
}
}
pub(crate) fn absolute_end(&self, size: i32) -> i32 {
// ref swift binding
// return end < 0 ? end + size : end
let end = self.end(size);
if end.is_negative() {
end + size
} else {
end
}
}
}
/// Indexing operation for arrays.
#[derive(Debug, Clone)]
pub enum ArrayIndexOp<'a> {
/// An `Ellipsis` is used to consume all axes
///
/// This is equivalent to `...` in python
Ellipsis,
/// A single index operation
///
/// This is equivalent to `arr[1]` in python
TakeIndex {
/// The index to take
index: i32,
},
/// Indexing with an array
TakeArray {
/// The indices to take
indices: Rc<Array>, // TODO: remove `Rc` because `Array` is `Clone`
},
/// Indexing with an array reference
TakeArrayRef {
/// The indices to take
indices: &'a Array,
},
/// Indexing with a range
///
/// This is equivalent to `arr[1:3]` in python
Slice(RangeIndex),
/// New axis operation
///
/// This is equivalent to `arr[None]` in python
ExpandDims,
}
impl ArrayIndexOp<'_> {
fn is_array_or_index(&self) -> bool {
// Using the full match syntax to avoid forgetting to add new variants
match self {
ArrayIndexOp::TakeIndex { .. }
| ArrayIndexOp::TakeArrayRef { .. }
| ArrayIndexOp::TakeArray { .. } => true,
ArrayIndexOp::Ellipsis | ArrayIndexOp::Slice(_) | ArrayIndexOp::ExpandDims => false,
}
}
fn is_array(&self) -> bool {
// Using the full match syntax to avoid forgetting to add new variants
match self {
ArrayIndexOp::TakeArray { .. } | ArrayIndexOp::TakeArrayRef { .. } => true,
ArrayIndexOp::TakeIndex { .. }
| ArrayIndexOp::Ellipsis
| ArrayIndexOp::Slice(_)
| ArrayIndexOp::ExpandDims => false,
}
}
}
/* -------------------------------------------------------------------------- */
/* Custom traits */
/* -------------------------------------------------------------------------- */
/// Trait for custom indexing operations.
///
/// Out of bounds indexing is allowed and wouldn't return an error.
pub trait TryIndexOp<Idx> {
/// Try to index the array with the given index.
fn try_index_device(&self, i: Idx, stream: impl AsRef<Stream>) -> Result<Array>;
/// Try to index the array with the given index.
fn try_index(&self, i: Idx) -> Result<Array> {
self.try_index_device(i, StreamOrDevice::default())
}
}
/// Trait for custom indexing operations.
///
/// This is implemented for all types that implement `TryIndexOp`.
pub trait IndexOp<Idx>: TryIndexOp<Idx> {
/// Index the array with the given index.
fn index_device(&self, i: Idx, stream: impl AsRef<Stream>) -> Array {
self.try_index_device(i, stream).unwrap()
}
/// Index the array with the given index.
fn index(&self, i: Idx) -> Array {
self.try_index(i).unwrap()
}
}
impl<T, Idx> IndexOp<Idx> for T where T: TryIndexOp<Idx> {}
/// Trait for custom mutable indexing operations.
pub trait TryIndexMutOp<Idx, Val> {
/// Try to index the array with the given index and set the value.
fn try_index_mut_device(&mut self, i: Idx, val: Val, stream: impl AsRef<Stream>) -> Result<()>;
/// Try to index the array with the given index and set the value.
fn try_index_mut(&mut self, i: Idx, val: Val) -> Result<()> {
self.try_index_mut_device(i, val, StreamOrDevice::default())
}
}
// TODO: should `Val` impl `AsRef<Array>` or `Into<Array>`?
/// Trait for custom mutable indexing operations.
pub trait IndexMutOp<Idx, Val>: TryIndexMutOp<Idx, Val> {
/// Index the array with the given index and set the value.
fn index_mut_device(&mut self, i: Idx, val: Val, stream: impl AsRef<Stream>) {
self.try_index_mut_device(i, val, stream).unwrap()
}
/// Index the array with the given index and set the value.
fn index_mut(&mut self, i: Idx, val: Val) {
self.try_index_mut(i, val).unwrap()
}
}
impl<T, Idx, Val> IndexMutOp<Idx, Val> for T where T: TryIndexMutOp<Idx, Val> {}
/// Trait for custom indexing operations.
pub trait ArrayIndex<'a> {
/// `mlx` allows out of bounds indexing.
fn index_op(self) -> ArrayIndexOp<'a>;
}
/* -------------------------------------------------------------------------- */
/* Implementation */
/* -------------------------------------------------------------------------- */
// Implement public bindings
impl Array {
/// Take elements along an axis.
///
/// The elements are taken from `indices` along the specified axis. If the axis is not specified
/// the array is treated as a flattened 1-D array prior to performing the take.
///
/// See [`Array::take_all`] for the flattened array.
///
/// # Params
///
/// - `indices`: The indices to take from the array.
/// - `axis`: The axis along which to take the elements.
#[default_device]
pub fn take_device(
&self,
indices: impl AsRef<Array>,
axis: i32,
stream: impl AsRef<Stream>,
) -> Result<Array> {
Array::try_from_op(|res| unsafe {
mlx_sys::mlx_take(
res,
self.as_ptr(),
indices.as_ref().as_ptr(),
axis,
stream.as_ref().as_ptr(),
)
})
}
/// Take elements from flattened 1-D array.
///
/// # Params
///
/// - `indices`: The indices to take from the array.
#[default_device]
pub fn take_all_device(
&self,
indices: impl AsRef<Array>,
stream: impl AsRef<Stream>,
) -> Result<Array> {
Array::try_from_op(|res| unsafe {
mlx_sys::mlx_take_all(
res,
self.as_ptr(),
indices.as_ref().as_ptr(),
stream.as_ref().as_ptr(),
)
})
}
/// Take values along an axis at the specified indices.
///
/// If no axis is specified, the array is flattened to 1D prior to the indexing operation.
///
/// # Params
///
/// - `indices`: The indices to take from the array.
/// - `axis`: Axis in the input to take the values from.
#[default_device]
pub fn take_along_axis_device(
&self,
indices: impl AsRef<Array>,
axis: impl Into<Option<i32>>,
stream: impl AsRef<Stream>,
) -> Result<Array> {
let (input, axis) = match axis.into() {
None => (Cow::Owned(self.reshape_device(&[-1], &stream)?), 0),
Some(ax) => (Cow::Borrowed(self), ax),
};
Array::try_from_op(|res| unsafe {
mlx_sys::mlx_take_along_axis(
res,
input.as_ptr(),
indices.as_ref().as_ptr(),
axis,
stream.as_ref().as_ptr(),
)
})
}
/// Put values along an axis at the specified indices.
///
/// If no axis is specified, the array is flattened to 1D prior to the indexing operation.
///
/// # Params
/// - indices: Indices array. These should be broadcastable with the input array excluding the `axis` dimension.
/// - values: Values array. These should be broadcastable with the indices.
/// - axis: Axis in the destination to put the values to.
/// - stream: stream or device to evaluate on.
#[default_device]
pub fn put_along_axis_device(
&self,
indices: impl AsRef<Array>,
values: impl AsRef<Array>,
axis: impl Into<Option<i32>>,
stream: impl AsRef<Stream>,
) -> Result<Array> {
match axis.into() {
None => {
let input = self.reshape_device(&[-1], &stream)?;
let array = Array::try_from_op(|res| unsafe {
mlx_sys::mlx_put_along_axis(
res,
input.as_ptr(),
indices.as_ref().as_ptr(),
values.as_ref().as_ptr(),
0,
stream.as_ref().as_ptr(),
)
})?;
let array = array.reshape_device(self.shape(), &stream)?;
Ok(array)
}
Some(ax) => Array::try_from_op(|res| unsafe {
mlx_sys::mlx_put_along_axis(
res,
self.as_ptr(),
indices.as_ref().as_ptr(),
values.as_ref().as_ptr(),
ax,
stream.as_ref().as_ptr(),
)
}),
}
}
}
/// Indices of the maximum values along the axis.
///
/// See [`argmax_all`] for the flattened array.
///
/// # Params
///
/// - `a`: The input array.
/// - `axis`: Axis to reduce over
/// - `keep_dims`: Keep reduced axes as singleton dimensions, defaults to False.
#[default_device]
pub fn argmax_device(
a: impl AsRef<Array>,
axis: i32,
keep_dims: impl Into<Option<bool>>,
stream: impl AsRef<Stream>,
) -> Result<Array> {
let keep_dims = keep_dims.into().unwrap_or(false);
Array::try_from_op(|res| unsafe {
mlx_sys::mlx_argmax(
res,
a.as_ref().as_ptr(),
axis,
keep_dims,
stream.as_ref().as_ptr(),
)
})
}
/// Indices of the maximum value over the entire array.
///
/// # Params
///
/// - `a`: The input array.
/// - `keep_dims`: Keep reduced axes as singleton dimensions, defaults to False.
#[default_device]
pub fn argmax_all_device(
a: impl AsRef<Array>,
keep_dims: impl Into<Option<bool>>,
stream: impl AsRef<Stream>,
) -> Result<Array> {
let keep_dims = keep_dims.into().unwrap_or(false);
Array::try_from_op(|res| unsafe {
mlx_sys::mlx_argmax_all(
res,
a.as_ref().as_ptr(),
keep_dims,
stream.as_ref().as_ptr(),
)
})
}
/// Indices of the minimum values along the axis.
///
/// See [`argmin_all`] for the flattened array.
///
/// # Params
///
/// - `a`: The input array.
/// - `axis`: Axis to reduce over.
/// - `keep_dims`: Keep reduced axes as singleton dimensions, defaults to False.
#[default_device]
pub fn argmin_device(
a: impl AsRef<Array>,
axis: i32,
keep_dims: impl Into<Option<bool>>,
stream: impl AsRef<Stream>,
) -> Result<Array> {
let keep_dims = keep_dims.into().unwrap_or(false);
Array::try_from_op(|res| unsafe {
mlx_sys::mlx_argmin(
res,
a.as_ref().as_ptr(),
axis,
keep_dims,
stream.as_ref().as_ptr(),
)
})
}
/// Indices of the minimum value over the entire array.
///
/// # Params
///
/// - `a`: The input array.
/// - `keep_dims`: Keep reduced axes as singleton dimensions, defaults to False.
#[default_device]
pub fn argmin_all_device(
a: impl AsRef<Array>,
keep_dims: impl Into<Option<bool>>,
stream: impl AsRef<Stream>,
) -> Result<Array> {
let keep_dims = keep_dims.into().unwrap_or(false);
Array::try_from_op(|res| unsafe {
mlx_sys::mlx_argmin_all(
res,
a.as_ref().as_ptr(),
keep_dims,
stream.as_ref().as_ptr(),
)
})
}
/// Returns the indices that partition the array.
///
/// The ordering of the elements within a partition in given by the indices is undefined.
///
/// See [`argpartition_all`] for the flattened array.
///
/// # Params
///
/// - `a`: The input array.
/// - `kth`: Element index at the `kth` position in the output will give the sorted position. All
/// indices before the `kth` position will be of elements less or equal to the element at the
/// `kth` index and all indices after will be of elements greater or equal to the element at the
/// `kth` index.
/// - `axis`: Axis to partition over
#[default_device]
pub fn argpartition_device(
a: impl AsRef<Array>,
kth: i32,
axis: i32,
stream: impl AsRef<Stream>,
) -> Result<Array> {
Array::try_from_op(|res| unsafe {
mlx_sys::mlx_argpartition(
res,
a.as_ref().as_ptr(),
kth,
axis,
stream.as_ref().as_ptr(),
)
})
}
/// Returns the indices that partition the flattened array.
///
/// The ordering of the elements within a partition in given by the indices is undefined.
///
/// # Params
///
/// - `a`: The input array.
/// - `kth`: Element index at the `kth` position in the output will give the sorted position. All
/// indices before the`kth` position will be of elements less than or equal to the element at the
/// `kth` index and all indices after will be elemenents greater than or equal to the element at
/// the `kth` position.
#[default_device]
pub fn argpartition_all_device(
a: impl AsRef<Array>,
kth: i32,
stream: impl AsRef<Stream>,
) -> Result<Array> {
Array::try_from_op(|res| unsafe {
mlx_sys::mlx_argpartition_all(res, a.as_ref().as_ptr(), kth, stream.as_ref().as_ptr())
})
}
/// Returns the indices that sort the array.
///
/// See [`argsort_all`] for the flattened array.
///
/// # Params
///
/// - `a`: The input array.
/// - `axis`: Axis to sort over.
#[default_device]
pub fn argsort_device(
a: impl AsRef<Array>,
axis: i32,
stream: impl AsRef<Stream>,
) -> Result<Array> {
Array::try_from_op(|res| unsafe {
mlx_sys::mlx_argsort(res, a.as_ref().as_ptr(), axis, stream.as_ref().as_ptr())
})
}
/// Returns the indices that sort the flattened array.
#[default_device]
pub fn argsort_all_device(a: impl AsRef<Array>, stream: impl AsRef<Stream>) -> Result<Array> {
Array::try_from_op(|res| unsafe {
mlx_sys::mlx_argsort_all(res, a.as_ref().as_ptr(), stream.as_ref().as_ptr())
})
}
/// See [`Array::take_along_axis`]
#[default_device]
pub fn take_along_axis_device(
a: impl AsRef<Array>,
indices: impl AsRef<Array>,
axis: impl Into<Option<i32>>,
stream: impl AsRef<Stream>,
) -> Result<Array> {
a.as_ref().take_along_axis_device(indices, axis, stream)
}
/// See [`Array::put_along_axis`]
#[default_device]
pub fn put_along_axis_device(
a: impl AsRef<Array>,
indices: impl AsRef<Array>,
values: impl AsRef<Array>,
axis: impl Into<Option<i32>>,
stream: impl AsRef<Stream>,
) -> Result<Array> {
a.as_ref()
.put_along_axis_device(indices, values, axis, stream)
}
/// See [`Array::take`]
#[default_device]
pub fn take_device(
a: impl AsRef<Array>,
indices: impl AsRef<Array>,
axis: i32,
stream: impl AsRef<Stream>,
) -> Result<Array> {
a.as_ref().take_device(indices, axis, stream)
}
/// See [`Array::take_all`]
#[default_device]
pub fn take_all_device(
a: impl AsRef<Array>,
indices: impl AsRef<Array>,
stream: impl AsRef<Stream>,
) -> Result<Array> {
a.as_ref().take_all_device(indices, stream)
}
/// Returns the `k` largest elements from the input along a given axis.
///
/// The elements will not necessarily be in sorted order.
///
/// See [`topk_all`] for the flattened array.
///
/// # Params
///
/// - `a`: The input array.
/// - `k`: The number of elements to return.
/// - `axis`: Axis to sort over. Default to `-1` if not specified.
#[default_device]
pub fn topk_device(
a: impl AsRef<Array>,
k: i32,
axis: impl Into<Option<i32>>,
stream: impl AsRef<Stream>,
) -> Result<Array> {
let axis = axis.into().unwrap_or(-1);
Array::try_from_op(|res| unsafe {
mlx_sys::mlx_topk(res, a.as_ref().as_ptr(), k, axis, stream.as_ref().as_ptr())
})
}
/// Returns the `k` largest elements from the flattened input array.
#[default_device]
pub fn topk_all_device(a: impl AsRef<Array>, k: i32, stream: impl AsRef<Stream>) -> Result<Array> {
Array::try_from_op(|res| unsafe {
mlx_sys::mlx_topk_all(res, a.as_ref().as_ptr(), k, stream.as_ref().as_ptr())
})
}
/* -------------------------------------------------------------------------- */
/* Helper functions */
/* -------------------------------------------------------------------------- */
fn count_non_new_axis_operations(operations: &[ArrayIndexOp]) -> usize {
operations
.iter()
.filter(|op| !matches!(op, ArrayIndexOp::ExpandDims))
.count()
}
fn expand_ellipsis_operations<'a>(
ndim: usize,
operations: &'a [ArrayIndexOp<'a>],
) -> Cow<'a, [ArrayIndexOp<'a>]> {
let ellipsis_count = operations
.iter()
.filter(|op| matches!(op, ArrayIndexOp::Ellipsis))
.count();
if ellipsis_count == 0 {
return Cow::Borrowed(operations);
}
if ellipsis_count > 1 {
panic!("Indexing with multiple ellipsis is not supported");
}
let ellipsis_pos = operations
.iter()
.position(|op| matches!(op, ArrayIndexOp::Ellipsis))
.unwrap();
let prefix = &operations[..ellipsis_pos];
let suffix = &operations[(ellipsis_pos + 1)..];
let expand_range =
count_non_new_axis_operations(prefix)..(ndim - count_non_new_axis_operations(suffix));
let expand = expand_range.map(|_| (..).index_op());
let mut expanded = Vec::with_capacity(ndim);
expanded.extend_from_slice(prefix);
expanded.extend(expand);
expanded.extend_from_slice(suffix);
Cow::Owned(expanded)
}