Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build_and_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ jobs:

build_documentation:
name: Build Documentation
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
needs: check_lint
steps:
- uses: actions/checkout@v7.0.1
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jobs:
build_documentation:
name: Build documentation
if: github.repository == 'ml-explore/mlx'
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7.0.1
- uses: $/.github/actions/build-docs
Expand Down
1 change: 1 addition & 0 deletions docs/src/python/ops.rst
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ Operations
searchsorted
sigmoid
sign
signbit
sin
sinh
slice
Expand Down
9 changes: 9 additions & 0 deletions mlx/backend/cpu/simd/base_simd.h
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,15 @@ Simd<T, 1> recip(Simd<T, 1> in) {
return T(1.0) / in;
}

template <typename T>
Simd<bool, 1> signbit(Simd<T, 1> in) {
if constexpr (std::is_same_v<T, float16_t> || std::is_same_v<T, bfloat16_t>) {
return std::signbit(static_cast<float>(in.value));
} else {
return std::signbit(in.value);
}
}

#define DEFAULT_UNARY(name, op) \
template <typename T> \
Simd<T, 1> name(Simd<T, 1> in) { \
Expand Down
6 changes: 6 additions & 0 deletions mlx/backend/cpu/unary.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,12 @@ void Sign::eval_cpu(const std::vector<array>& inputs, array& out) {
}
}

void SignBit::eval_cpu(const std::vector<array>& inputs, array& out) {
assert(inputs.size() == 1);
const auto& in = inputs[0];
unary_real_to_bool(in, out, detail::SignBit(), stream());
}

void Sin::eval_cpu(const std::vector<array>& inputs, array& out) {
assert(inputs.size() == 1);
const auto& in = inputs[0];
Expand Down
17 changes: 17 additions & 0 deletions mlx/backend/cpu/unary.h
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,23 @@ void unary_real_fp(const array& a, array& out, Op op, Stream stream) {
}
});
}

template <typename Op>
void unary_real_to_bool(const array& a, array& out, Op op, Stream stream) {
set_unary_output_data(a, out);
auto& encoder = cpu::get_command_encoder(stream);
encoder.set_input_array(a);
encoder.set_output_array(out);
encoder.dispatch([a = array::unsafe_weak_copy(a),
out = array::unsafe_weak_copy(out),
op = op]() mutable {
dispatch_float_types(a.dtype(), "[unary_real_to_bool]", [&](auto type_tag) {
using T = MLX_GET_TYPE(type_tag);
unary_op<T, bool>(a, out, op);
});
});
}

template <typename Op>
void unary_fp(const array& a, array& out, Op op, Stream stream) {
set_unary_output_data(a, out);
Expand Down
12 changes: 12 additions & 0 deletions mlx/backend/cpu/unary_ops.h
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,18 @@ struct Sign {
SINGLE()
};

struct SignBit {
template <typename T>
bool operator()(T x) {
return simd::signbit(Simd<T, 1>(x)).value;
}

template <typename T, int N>
Simd<bool, N> operator()(Simd<T, N> x) {
return simd::signbit(x);
}
};

struct Square {
template <int N, typename T>
Simd<T, N> operator()(Simd<T, N> x) {
Expand Down
7 changes: 7 additions & 0 deletions mlx/backend/cuda/device/unary_ops.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,13 @@ struct Sign {
}
};

struct SignBit {
template <typename T>
__device__ bool operator()(T x) {
return cuda::std::signbit(x);
}
};

struct Sin {
template <typename T>
__device__ T operator()(T x) {
Expand Down
1 change: 1 addition & 0 deletions mlx/backend/cuda/unary/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ target_sources(
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/round.cu
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/sigmoid.cu
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/sign.cu
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/signbit.cu
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/sin.cu
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/sinh.cu
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/sqrt.cu
Expand Down
7 changes: 7 additions & 0 deletions mlx/backend/cuda/unary/signbit.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Copyright © 2026 Apple Inc.

#include "mlx/backend/cuda/unary/unary.cuh"

namespace mlx::core {
UNARY_GPU(SignBit)
} // namespace mlx::core
3 changes: 3 additions & 0 deletions mlx/backend/cuda/unary/unary.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ constexpr bool supports_unary_op() {
std::is_same_v<Op, Sign> || std::is_same_v<Op, Square>) {
return std::is_same_v<In, Out>;
}
if (std::is_same_v<Op, SignBit>) {
return std::is_same_v<Out, bool> && is_floating_v<In>;
}
if (std::is_same_v<Op, ArcCosh> || std::is_same_v<Op, ArcSinh> ||
std::is_same_v<Op, ArcTanh> || std::is_same_v<Op, Erf> ||
std::is_same_v<Op, ErfInv> || std::is_same_v<Op, Expm1> ||
Expand Down
3 changes: 3 additions & 0 deletions mlx/backend/metal/kernels/unary.metal
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ instantiate_unary_float(Sigmoid)
instantiate_unary_float(Erf)
instantiate_unary_float(ErfInv)
instantiate_unary_types(Sign)
instantiate_unary_all(SignBit, float16, bool_, half, bool)
instantiate_unary_all(SignBit, float32, bool_, float, bool)
instantiate_unary_all(SignBit, bfloat16, bool_, bfloat16_t, bool)
instantiate_unary_float(Sin)
instantiate_unary_float(Sinh)
instantiate_unary_types(Square)
Expand Down
7 changes: 7 additions & 0 deletions mlx/backend/metal/kernels/unary_ops.h
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,13 @@ struct Sign {
};
};

struct SignBit {
template <typename T>
bool operator()(T x) thread {
return metal::signbit(x);
}
};

struct Sin {
template <typename T>
T operator()(T x) thread {
Expand Down
1 change: 1 addition & 0 deletions mlx/backend/metal/unary.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ UNARY_GPU(Negative)
UNARY_GPU(Real)
UNARY_GPU(Sigmoid)
UNARY_GPU(Sign)
UNARY_GPU(SignBit)
UNARY_GPU(Sin)
UNARY_GPU(Sinh)
UNARY_GPU(Square)
Expand Down
1 change: 1 addition & 0 deletions mlx/backend/no_cpu/primitives.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ NO_CPU(Select)
NO_CPU(SegmentedMM)
NO_CPU(Sigmoid)
NO_CPU(Sign)
NO_CPU(SignBit)
NO_CPU(Sin)
NO_CPU(Sinh)
NO_CPU(Slice)
Expand Down
1 change: 1 addition & 0 deletions mlx/backend/no_gpu/primitives.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ NO_GPU(Select)
NO_GPU(SegmentedMM)
NO_GPU(Sigmoid)
NO_GPU(Sign)
NO_GPU(SignBit)
NO_GPU(Sin)
NO_GPU(Sinh)
NO_GPU(Slice)
Expand Down
11 changes: 6 additions & 5 deletions mlx/compile/fuse.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,12 @@ bool is_unary(const Primitive& p) {
typeid(p) == typeid(Log1p) || typeid(p) == typeid(LogicalNot) ||
typeid(p) == typeid(Negative) || typeid(p) == typeid(Round) ||
typeid(p) == typeid(Sigmoid) || typeid(p) == typeid(Sign) ||
typeid(p) == typeid(Sin) || typeid(p) == typeid(Sinh) ||
typeid(p) == typeid(Square) || typeid(p) == typeid(Sqrt) ||
typeid(p) == typeid(Tan) || typeid(p) == typeid(Tanh) ||
typeid(p) == typeid(Expm1) || typeid(p) == typeid(Real) ||
typeid(p) == typeid(Imag) || typeid(p) == typeid(BitwiseInvert));
typeid(p) == typeid(SignBit) || typeid(p) == typeid(Sin) ||
typeid(p) == typeid(Sinh) || typeid(p) == typeid(Square) ||
typeid(p) == typeid(Sqrt) || typeid(p) == typeid(Tan) ||
typeid(p) == typeid(Tanh) || typeid(p) == typeid(Expm1) ||
typeid(p) == typeid(Real) || typeid(p) == typeid(Imag) ||
typeid(p) == typeid(BitwiseInvert));
}

bool is_binary(const Primitive& p) {
Expand Down
1 change: 1 addition & 0 deletions mlx/export.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@ struct PrimitiveFactory {
SERIALIZE_PRIMITIVE(Select),
SERIALIZE_PRIMITIVE(Sigmoid),
SERIALIZE_PRIMITIVE(Sign),
SERIALIZE_PRIMITIVE(SignBit),
SERIALIZE_PRIMITIVE(Sin),
SERIALIZE_PRIMITIVE(Sinh),
SERIALIZE_PRIMITIVE(Slice),
Expand Down
13 changes: 13 additions & 0 deletions mlx/ops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3218,6 +3218,19 @@ array sign(const array& a, StreamOrDevice s /* = {} */) {
return array(a.shape(), a.dtype(), std::make_shared<Sign>(to_stream(s)), {a});
}

array signbit(const array& a, StreamOrDevice s /* = {} */) {
if (issubdtype(a.dtype(), complexfloating)) {
throw std::invalid_argument("[signbit] Not supported for complex types.");
}
if (a.dtype() == bool_ || issubdtype(a.dtype(), unsignedinteger)) {
return full(a.shape(), false, bool_, s);
}
if (issubdtype(a.dtype(), signedinteger)) {
return less(a, array(0, a.dtype()), s);
}
return array(a.shape(), bool_, std::make_shared<SignBit>(to_stream(s)), {a});
}

array logical_not(const array& a, StreamOrDevice s /* = {} */) {
return array(
a.shape(),
Expand Down
3 changes: 3 additions & 0 deletions mlx/ops.h
Original file line number Diff line number Diff line change
Expand Up @@ -967,6 +967,9 @@ MLX_API array operator-(const array& a);
/** The sign of the elements in an array. */
MLX_API array sign(const array& a, StreamOrDevice s = {});

/** Test whether the sign bit is set for each element of a non-complex array. */
MLX_API array signbit(const array& a, StreamOrDevice s = {});

/** Logical not of an array */
MLX_API array logical_not(const array& a, StreamOrDevice s = {});

Expand Down
27 changes: 27 additions & 0 deletions mlx/primitives.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5124,6 +5124,33 @@ std::pair<std::vector<array>, std::vector<int>> Sign::vmap(
return {{sign(inputs[0], stream())}, axes};
}

std::vector<array> SignBit::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
const std::vector<int>& argnums,
const std::vector<array>&) {
assert(primals.size() == 1);
assert(argnums.size() == 1);
return {zeros_like(primals[0], stream())};
}

std::vector<array> SignBit::jvp(
const std::vector<array>& primals,
const std::vector<array>& tangents,
const std::vector<int>& argnums) {
assert(primals.size() == 1);
assert(argnums.size() == 1);
return {zeros_like(tangents[0], stream())};
}

std::pair<std::vector<array>, std::vector<int>> SignBit::vmap(
const std::vector<array>& inputs,
const std::vector<int>& axes) {
assert(inputs.size() == 1);
assert(axes.size() == 1);
return {{signbit(inputs[0], stream())}, axes};
}

std::vector<array> Sin::vjp(
const std::vector<array>& primals,
const std::vector<array>& cotangents,
Expand Down
14 changes: 14 additions & 0 deletions mlx/primitives.h
Original file line number Diff line number Diff line change
Expand Up @@ -2071,6 +2071,20 @@ class Sign : public UnaryPrimitive {
DEFINE_INPUT_OUTPUT_SHAPE()
};

class SignBit : public UnaryPrimitive {
public:
explicit SignBit(Stream stream) : UnaryPrimitive(stream) {}

void eval_cpu(const std::vector<array>& inputs, array& out) override;
void eval_gpu(const std::vector<array>& inputs, array& out) override;

DEFINE_VMAP()
DEFINE_GRADS()
DEFINE_NAME(SignBit)
DEFINE_DEFAULT_IS_EQUIVALENT()
DEFINE_INPUT_OUTPUT_SHAPE()
};

class Sin : public UnaryPrimitive {
public:
explicit Sin(Stream stream) : UnaryPrimitive(stream) {}
Expand Down
24 changes: 24 additions & 0 deletions python/src/ops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,30 @@ void init_ops(nb::module_& m) {
Returns:
array: The sign of ``a``.
)pbdoc");
m.def(
"signbit",
[](const ScalarOrArray& a, mx::StreamOrDevice s) {
return mx::signbit(to_array(a), s);
},
nb::arg(),
nb::kw_only(),
"stream"_a = nb::none(),
nb::sig(
"def signbit(a: array | bool | int | float, /, *, stream: StreamOrDevice = None) -> array"),
R"pbdoc(
Test whether the sign bit is set for each element.

Negative zero and NaNs with a set sign bit return ``True``.
Unsigned integers and booleans return ``False``.

Args:
a (array or bool or int or float): Input array or scalar with a non-complex dtype.

Returns:
array: A boolean array with the same shape as ``a``,
containing ``True`` where the sign bit is set and ``False``
otherwise.
)pbdoc");
m.def(
"positive",
&mx::positive,
Expand Down
9 changes: 9 additions & 0 deletions python/tests/test_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -1202,6 +1202,15 @@ def test_sign(self):
expected = c / np.abs(c)
self.assertTrue(np.allclose(result, expected))

def test_signbit(self):
a = mx.array([0.0, -0.0, 1.0, -1.0, np.inf, -np.inf, np.nan, -np.nan])
result = mx.signbit(a)
self.assertEqual(result.dtype, mx.bool_)
self.assertTrue(np.array_equal(result, np.signbit(a)))

with self.assertRaisesRegex(ValueError, "complex"):
mx.signbit(mx.array(1, dtype=mx.complex64))

def test_logical_not(self):
a = mx.array([-1.0, 1.0, 0.0, 1.0, -2.0, 3.0])
result = mx.logical_not(a)
Expand Down
7 changes: 7 additions & 0 deletions python/tests/test_vmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ def test_unary(self):
"rsqrt",
"sigmoid",
"sign",
"signbit",
"sin",
"sqrt",
"square",
Expand All @@ -66,6 +67,12 @@ def test_unary(self):
y = mx.vmap(op, in_axes=1, out_axes=1)(x)
self.assertTrue(mx.array_equal(y, op(x), equal_nan=True))

def test_signbit(self):
# `signbit` implementation shortcuts to `less` on integer input.
# This tests the normal path with float explicitly.
x = mx.array([[-2.0, -0.0, 0.0], [1.0, -3.0, 4.0]])
self.assertTrue(mx.array_equal(mx.vmap(mx.signbit)(x), mx.signbit(x)))

def test_binary(self):
ops = [
"add",
Expand Down
Loading
Loading