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>
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 size_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 uint2 index [[thread_position_in_grid]],
18 uint2 grid_dim [[threads_per_grid]]) {
19 auto ind_idx = index.x;
20 auto ind_offset = index.y;
21
22 size_t src_idx = 0;
23 for (int i = 0; i < NIDX; ++i) {
24 size_t idx_loc;
25 if (IDX_NDIM == 0) {
26 idx_loc = 0;
27 } else if (IDX_NDIM == 1) {
28 idx_loc = ind_idx * indices.strides[indices.ndim * i];
29 } else {
30 idx_loc = elem_to_loc(
31 ind_idx,
32 &indices.shapes[indices.ndim * i],
33 &indices.strides[indices.ndim * i],
34 indices.ndim);
35 }
36 auto ax = axes[i];
37 auto idx_val = offset_neg_idx(indices.buffers[i][idx_loc], src_shape[ax]);
38 src_idx += idx_val * src_strides[ax];
39 }
40
41 auto src_offset = elem_to_loc(ind_offset, slice_sizes, src_strides, src_ndim);
42
43 size_t out_idx = index.y + static_cast<size_t>(grid_dim.y) * index.x;
44 out[out_idx] = src[src_offset + src_idx];
45}
METAL_FUNC stride_t elem_to_loc(uint elem, device const int *shape, device const stride_t *strides, int ndim)
Definition utils.h:77
METAL_FUNC void gather_impl(const device T *src, device T *out, const constant int *src_shape, const constant size_t *src_strides, const constant size_t &src_ndim, const constant int *slice_sizes, const constant int *axes, const thread Indices< IdxT, NIDX > &indices, uint2 index, uint2 grid_dim)
Definition gather.h:8
METAL_FUNC size_t offset_neg_idx(IdxT idx, size_t size)
Definition indexing.h:16
Definition indexing.h:8