#4579·mlx

[BUG] Negative template int breaks kernel compilation.

Author: alford-auldCreated Sep 28, 2026Updated Sep 29, 2026

☑️ I understand it is strictly prohibited to use AI to write issues.

Describe the bug Passing a negative integer template value to kernel args fires the "Unable to build" error as it produces an invalid C++ function name.

To Reproduce The code snippet

python
import mlx.core as mx

kernel = mx.fast.metal_kernel(
    name="negtmpl",
    input_names=["inp"],
    output_names=["out"],
    source="out[thread_position_in_grid.x] = T(V);",
)

(out,) = kernel(
    inputs=[mx.zeros((4,), dtype=mx.int32)],
    template=[("T", mx.int32), ("V", -1)],
    grid=(4, 1, 1), threadgroup=(4, 1, 1),
    output_shapes=[(4,)], output_dtypes=[mx.int32],
)
mx.eval(out)
print("compiled, out =", out.tolist())

Expected behavior the kernel compiles and returns all '-1'

Desktop (please complete the following information):

  • OS Version: macOS 26.3 (build 25D125)
  • Version 0.32.2
  • Apple M4 (applegpu_g16g), arm64, Python 3.12.13.

Additional context make_template_hash in mlx/backend/common/metal_kernel.cpp only rewrites <, > and , . A negative value yields "-1" inside the name. Reproducer is written by Claude Code and verified by me.

Traceback

bash
Traceback (most recent call last):
  File "/private/tmp/mlx-repros/a_negative_template_int.py", line 16, in <module>
    mx.eval(out)
RuntimeError: [metal::Device] Unable to build metal library from source
mlx/backend/metal/kernels/utils.h:470:3: error: 'kernel' attribute only applies to functions
[[kernel]] void custom_kernel_negtmpl__int32_t_-1_int32_tc_int32_t(
  ^
mlx/backend/metal/kernels/utils.h:470:17: error: program scope variable must reside in constant address space
[[kernel]] void custom_kernel_negtmpl__int32_t_-1_int32_tc_int32_t(
                ^
mlx/backend/metal/kernels/utils.h:470:48: error: expected ';' at end of declaration
[[kernel]] void custom_kernel_negtmpl__int32_t_-1_int32_tc_int32_t(
                                               ^
                                               ;
mlx/backend/metal/kernels/utils.h:470:48: error: expected external declaration
mlx/backend/metal/kernels/utils.h:470:49: error: expected unqualified-id
[[kernel]] void custom_kernel_negtmpl__int32_t_-1_int32_tc_int32_t(