Skip to content

fix(median): handle empty axes in mlx_median_axes - #133

Open
aki-xavier wants to merge 1 commit into
ml-explore:mainfrom
aki-xavier:fix/mlx-median-empty-axes
Open

fix(median): handle empty axes in mlx_median_axes#133
aki-xavier wants to merge 1 commit into
ml-explore:mainfrom
aki-xavier:fix/mlx-median-empty-axes

Conversation

@aki-xavier

Copy link
Copy Markdown

Summary

mlx_median_axes(res, a, NULL, 0, keepdims, s) — the "reduce over all dimensions" spelling — builds an empty axes vector that flows into the axes overload of mlx::core::median. That overload moves all axes to the back and calls flatten(start_axis == ndim), which is rejected by the assertion:

[flatten] start_axis must be less than or equal to end_axis

This makes the all-axes median unusable through the _axes entry point. The dedicated no-axis entry point mlx_median already routes to the full-reduce overload and works; only the _axes path is broken.

Reproduction

mlx_array res = mlx_array_new();
float data[4] = {1, 2, 3, 4};
int shape[2] = {2, 2};
mlx_array a = mlx_array_new_data(data, shape, 2, MLX_FLOAT32);

int rc = mlx_median_axes(&res, a, NULL, 0, false, mlx_default_cpu_stream_new());
// Before: rc == 1, prints "[flatten] start_axis must be less than or equal to end_axis"
// After:  rc == 0, res == 2.5

Fix

When axes_num == 0, route to the full-reduce overload mlx::core::median(a, keepdims, s) directly, mirroring the dedicated mlx_median entry point. The normal axes_num > 0 path is unchanged.

Verification

Built mlxc (CPU backend) and ran a small program against it:

case before after
mlx_median(a, keepdims=false) rc=0, 2.5 rc=0, 2.5
mlx_median_axes(a, NULL, 0, ...) rc=1, flatten assert rc=0, 2.5
mlx_median_axes(a, axis=0, ...) rc=0 rc=0

Fixes #128.

Passing axes=NULL/axes_num=0 to mlx_median_axes builds an empty axes
vector that flows into the axes overload of mlx::core::median. That
overload transposes all axes to the back and calls flatten(start ==
ndim), which is rejected by the assert '[flatten] start_axis must be
less than or equal to end_axis'.

Route the no-axis case (axes_num == 0) to the full-reduce overload,
mirroring the dedicated mlx_median entry point, so reducing over all
dimensions works. Fixes ml-explore#128.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

mlx_median with no axis (axes=NULL, axes_num=0) fails: [flatten] start_axis must be less than or equal to end_axis

1 participant