MLX
 
Loading...
Searching...
No Matches
gather.h
Go to the documentation of this file.
1// Copyright © 2024 Apple Inc.
2
3#pragma once
4
6
7template <typename T, typename IdxT, int NIDX, int IDX_NDIM, typename LocT>
8METAL_FUNC void gather_impl(
9 const device T* src [[buffer(0)]],
10 device T* out [[buffer(1)]],
11 const constant int* src_shape [[buffer(2)]],
12 const constant int64_t* src_strides [[buffer(3)]],
13 const constant size_t& src_ndim [[buffer(4)]],
14 const constant int* slice_sizes [[buffer(5)]],
15 const constant int* axes [[buffer(6)]],
16 const thread Indices<IdxT, NIDX>& indices,
17 uint3 index [[thread_position_in_grid]],
18 uint3 grid_dim [[threads_per_grid]]) {
19 LocT src_idx = 0;
20 for (int i = 0; i < NIDX; ++i) {
21 LocT idx_loc;
22 if (IDX_NDIM == 0) {
23 idx_loc = 0;
24 } else if (IDX_NDIM == 1) {
25 idx_loc = index.x * static_cast<LocT>(indices.strides[indices.ndim * i]);
26 } else {
27 idx_loc = index.x * static_cast<LocT>(indices.strides[indices.ndim * i]);
28 idx_loc += indices.row_contiguous[i]
29 ? index.y
31 index.y,
32 &indices.shapes[indices.ndim * i + 1],
33 &indices.strides[indices.ndim * i + 1],
34 indices.ndim - 1);
35 }
36 auto ax = axes[i];
37 auto idx_val = offset_neg_idx(indices.buffers[i][idx_loc], src_shape[ax]);
38 src_idx += static_cast<LocT>(idx_val) * static_cast<LocT>(src_strides[ax]);
39 }
40
41 auto src_offset =
42 elem_to_loc<LocT>(index.z, slice_sizes, src_strides, src_ndim);
43
44 LocT out_idx = index.z;
45 if (IDX_NDIM == 1) {
46 out_idx += static_cast<LocT>(grid_dim.z) * index.x;
47 } else if (IDX_NDIM >= 2) {
48 out_idx += grid_dim.z * (index.x * static_cast<LocT>(grid_dim.y) + index.y);
49 }
50 out[out_idx] = src[src_offset + src_idx];
51}
METAL_FUNC IdxT elem_to_loc(IdxT elem, constant const int *shape, constant const int64_t *strides, int ndim)
Definition utils.h:93
METAL_FUNC void gather_impl(const device T *src, device T *out, const constant int *src_shape, const constant int64_t *src_strides, const constant size_t &src_ndim, const constant int *slice_sizes, const constant int *axes, const thread Indices< IdxT, NIDX > &indices, uint3 index, uint3 grid_dim)
Definition gather.h:8
METAL_FUNC size_t offset_neg_idx(IdxT idx, int size)
Definition indexing.h:17
Definition indexing.h:8