MCPcopy Create free account
hub / github.com/ml-explore/mlx / mlx_expand_ellipsis

Function mlx_expand_ellipsis

python/src/indexing.cpp:210–269  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

208}
209
210auto mlx_expand_ellipsis(const mx::Shape& shape, const nb::tuple& entries) {
211 std::vector<nb::object> indices;
212
213 // Go over all entries and note the position of ellipsis
214 int non_none_indices_before = 0;
215 int non_none_indices_after = 0;
216 std::vector<nb::object> r_indices;
217 int i = 0;
218 bool has_ellipsis = false;
219
220 // Start from dimension 0 till we hit an ellipsis
221 for (; i < entries.size(); i++) {
222 auto idx = entries[i];
223 if (!is_valid_index_type(idx)) {
224 throw std::invalid_argument(
225 "Cannot index mlx array using the given type yet");
226 }
227 if (!nb::ellipsis().is(idx)) {
228 indices.push_back(idx);
229 non_none_indices_before += !idx.is_none();
230 } else {
231 has_ellipsis = true;
232 break;
233 }
234 }
235
236 // If we do hit an ellipsis, collect indices from the back
237 for (int j = entries.size() - 1; j > i; j--) {
238 auto idx = entries[j];
239 if (!is_valid_index_type(idx)) {
240 throw std::invalid_argument(
241 "Cannot index mlx array using the given type yet");
242 }
243 if (nb::ellipsis().is(idx)) {
244 throw std::invalid_argument(
245 "An index can only have a single ellipsis (...)");
246 }
247 r_indices.push_back(idx);
248 non_none_indices_after += !idx.is_none();
249 }
250
251 // Count up the number of non none indices
252 int non_none_indices = non_none_indices_before + non_none_indices_after;
253
254 // Expand ellipsis
255 if (has_ellipsis) {
256 for (int axis = non_none_indices_before;
257 axis < shape.size() - non_none_indices_after;
258 axis++) {
259 indices.push_back(
260 nb::slice(mx::ShapeElem{0}, shape[axis], mx::ShapeElem{1}));
261 non_none_indices++;
262 }
263 }
264
265 // Insert indices collected after the ellipsis
266 indices.insert(indices.end(), r_indices.rbegin(), r_indices.rend());
267

Callers 3

mlx_get_item_ndFunction · 0.85
mlx_scatter_args_ndFunction · 0.85

Calls 8

is_valid_index_typeFunction · 0.85
push_backMethod · 0.80
rbeginMethod · 0.80
rendMethod · 0.80
sliceFunction · 0.50
sizeMethod · 0.45
insertMethod · 0.45
endMethod · 0.45

Tested by

no test coverage detected