Skip to content
Merged
5 changes: 3 additions & 2 deletions mlx/backend/cpu/binary.h
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ void binary_op_dispatch_dims(
const T* b,
U* out,
int dim,
int size,
size_t size,
const Shape& shape,
const Strides& a_strides,
const Strides& b_strides,
Expand All @@ -135,7 +135,7 @@ void binary_op_dispatch_dims(
ContiguousIterator a_it(shape, a_strides, dim - 3);
ContiguousIterator b_it(shape, b_strides, dim - 3);
auto stride = out_strides[dim - 4];
for (int64_t elem = 0; elem < size; elem += stride) {
for (size_t elem = 0; elem < size; elem += stride) {
binary_op_dims<T, U, Op, 3, Strided>(
a + a_it.loc,
b + b_it.loc,
Expand Down Expand Up @@ -387,6 +387,7 @@ void binary_int_op_cpu(
switch (out.dtype()) {
case bool_:
binary_op<bool, Op>(a, b, out, bopt);
break;
case uint8:
binary_op<uint8_t, Op>(a, b, out, bopt);
break;
Expand Down
27 changes: 23 additions & 4 deletions mlx/backend/cpu/compiled.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <fstream>
#include <list>
#include <mutex>
#include <random>
#include <shared_mutex>

#include <fmt/format.h>
Expand Down Expand Up @@ -116,9 +117,14 @@ void* compile(
}

if (!lib_exists) {
// Open source file and write source code to it
std::string source_file_name = kernel_file_name + ".cpp";
auto source_file_path = (output_dir / source_file_name).string();
// Build under a unique name, then move the files into place. Other
// processes then never load a partly written library.
auto tmp_name = fmt::format("tmp_{:08x}", std::random_device{}());
std::string source_file_name = tmp_name + ".cpp";
std::string tmp_lib_name =
tmp_name + std::filesystem::path(shared_lib_name).extension().string();
auto source_file_path = output_dir / source_file_name;
auto tmp_lib_path = output_dir / tmp_lib_name;

std::ofstream source_file(source_file_path);
source_file << source_code;
Expand All @@ -127,14 +133,27 @@ void* compile(
try {
JitCompiler::exec(
JitCompiler::build_command(
output_dir, source_file_name, shared_lib_name));
output_dir, source_file_name, tmp_lib_name));
} catch (const std::exception& error) {
throw std::runtime_error(
fmt::format(
"[Compile::eval_cpu] Failed to compile function {0}: {1}",
kernel_name,
error.what()));
}

std::error_code error;
std::filesystem::rename(
source_file_path, output_dir / (kernel_file_name + ".cpp"), error);
std::filesystem::rename(tmp_lib_path, shared_lib_path, error);
if (error) {
// On Windows the rename can fail while another process uses the file.
if (std::filesystem::exists(shared_lib_path, error)) {
std::filesystem::remove(tmp_lib_path, error);
} else {
shared_lib_path = tmp_lib_path.string();
}
}
}

// load library
Expand Down
35 changes: 20 additions & 15 deletions mlx/backend/cpu/conv.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -299,18 +299,20 @@ void slow_conv_2D(
int oH_border_1 = is_idil_one
? ((padding_lo[0] + wt_strides[0] - 1) / wt_strides[0])
: oH;
int oH_border_2 = std::max(
oH_border_1,
(iH + padding_lo[0] - wH * wt_dilation[0]) / wt_strides[0]);
oH_border_1 = std::min(std::max(oH_border_0, oH_border_1), oH);
int oH_border_2 =
(iH + padding_lo[0] - wH * wt_dilation[0]) / wt_strides[0];
oH_border_2 = std::min(std::max(oH_border_1, oH_border_2), oH);
int oH_border_3 = oH;

int oW_border_0 = 0;
int oW_border_1 = is_idil_one
? ((padding_lo[1] + wt_strides[1] - 1) / wt_strides[1])
: oW;
int oW_border_2 = std::max(
oW_border_1,
(iW + padding_lo[1] - wW * wt_dilation[1]) / wt_strides[1]);
oW_border_1 = std::min(std::max(oW_border_0, oW_border_1), oW);
int oW_border_2 =
(iW + padding_lo[1] - wW * wt_dilation[1]) / wt_strides[1];
oW_border_2 = std::min(std::max(oW_border_1, oW_border_2), oW);
int oW_border_3 = oW;

for (int n = 0; n < N; ++n) {
Expand Down Expand Up @@ -586,27 +588,30 @@ void slow_conv_3D(
int oD_border_1 = is_idil_one
? ((padding_lo[0] + wt_strides[0] - 1) / wt_strides[0])
: oD;
int oD_border_2 = std::max(
oD_border_1,
(iD + padding_lo[0] - wD * wt_dilation[0]) / wt_strides[0]);
oD_border_1 = std::min(std::max(oD_border_0, oD_border_1), oD);
int oD_border_2 =
(iD + padding_lo[0] - wD * wt_dilation[0]) / wt_strides[0];
oD_border_2 = std::min(std::max(oD_border_1, oD_border_2), oD);
int oD_border_3 = oD;

int oH_border_0 = 0;
int oH_border_1 = is_idil_one
? ((padding_lo[1] + wt_strides[1] - 1) / wt_strides[1])
: oH;
int oH_border_2 = std::max(
oH_border_1,
(iH + padding_lo[1] - wH * wt_dilation[1]) / wt_strides[1]);
oH_border_1 = std::min(std::max(oH_border_0, oH_border_1), oH);
int oH_border_2 =
(iH + padding_lo[1] - wH * wt_dilation[1]) / wt_strides[1];
oH_border_2 = std::min(std::max(oH_border_1, oH_border_2), oH);
int oH_border_3 = oH;

int oW_border_0 = 0;
int oW_border_1 = is_idil_one
? ((padding_lo[2] + wt_strides[2] - 1) / wt_strides[2])
: oW;
int oW_border_2 = std::max(
oW_border_1,
(iW + padding_lo[2] - wW * wt_dilation[2]) / wt_strides[2]);
oW_border_1 = std::min(std::max(oW_border_0, oW_border_1), oW);
int oW_border_2 =
(iW + padding_lo[2] - wW * wt_dilation[2]) / wt_strides[2];
oW_border_2 = std::min(std::max(oW_border_1, oW_border_2), oW);
int oW_border_3 = oW;

for (int n = 0; n < N; ++n) {
Expand Down
8 changes: 7 additions & 1 deletion mlx/backend/cpu/copy.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,13 @@ void copy_vector(const array& src, array& dst) {
auto src_ptr = src.data<SrcT>();
auto dst_ptr = dst.data<DstT>();
auto size = src.data_size();
std::copy(src_ptr, src_ptr + size, dst_ptr);
if constexpr (std::is_same_v<SrcT, DstT>) {
std::copy(src_ptr, src_ptr + size, dst_ptr);
} else {
std::transform(src_ptr, src_ptr + size, dst_ptr, [](SrcT x) {
return static_cast<DstT>(x);
});
}
}

template <typename SrcT, typename DstT, int D>
Expand Down
9 changes: 8 additions & 1 deletion mlx/backend/cpu/primitives.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ static std::pair<array, bool> compute_dynamic_offset(
const Strides& strides,
const std::vector<int>& axes,
Stream stream) {
auto& encoder = cpu::get_command_encoder(stream);
// The kernel reads the indices contiguously
if (!indices.flags().row_contiguous) {
auto copy = contiguous_copy_cpu(indices, stream);
encoder.add_temporary(copy);
return compute_dynamic_offset(copy, strides, axes, stream);
}

array offset({1}, int64, nullptr, {});
bool donate = indices.is_donatable() &&
(indices.data_size() * indices.itemsize()) >= offset.itemsize();
Expand All @@ -44,7 +52,6 @@ static std::pair<array, bool> compute_dynamic_offset(
offset.set_data(allocator::malloc(offset.itemsize()));
}

auto& encoder = cpu::get_command_encoder(stream);
encoder.set_input_array(indices);
encoder.set_output_array(offset);
auto compute_offset =
Expand Down
3 changes: 2 additions & 1 deletion mlx/backend/cpu/quantized.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ static inline T dequantize_scale(uint8_t s) {
uint16_t i;
};
FOrI out;
out.i = (s == 0 ? 0x40 : (static_cast<uint16_t>(s) << 7));
out.i = (s == 0) ? 0x40
: (s == 0xFF ? 0x7FC0 : (static_cast<uint16_t>(s) << 7));
return static_cast<T>(out.f);
}
}
Expand Down
40 changes: 22 additions & 18 deletions mlx/backend/cpu/reduce.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,12 @@ void strided_reduce(
};

template <typename T, typename U, typename Op>
void contiguous_reduce(const T* x, U* accumulator, int size, Op op, U init) {
void contiguous_reduce(
const T* x,
U* accumulator,
int64_t size,
Op op,
U init) {
constexpr int N = std::min(simd::max_size<T>, simd::max_size<U>);
simd::Simd<U, N> accumulator_v(init);
while (size >= N) {
Expand All @@ -125,11 +130,11 @@ void contiguous_reduce(const T* x, U* accumulator, int size, Op op, U init) {

// Helper for the ndimensional strided loop
void nd_loop(
std::function<void(int)> callback,
std::function<void(int64_t)> callback,
const Shape& shape,
const Strides& strides) {
std::function<void(int, int)> loop_inner;
loop_inner = [&](int dim, int offset) {
std::function<void(int, int64_t)> loop_inner;
loop_inner = [&](int dim, int64_t offset) {
if (dim < shape.size() - 1) {
auto size = shape[dim];
auto stride = strides[dim];
Expand Down Expand Up @@ -181,16 +186,16 @@ void reduction_op(
auto [shape, strides] = shapes_without_reduction_axes(x, axes);
if (plan.shape.size() == 0) {
for (int i = 0; i < out.size(); i++, out_ptr++) {
int offset = elem_to_loc(i, shape, strides);
int64_t offset = elem_to_loc(i, shape, strides);
*out_ptr = init;
contiguous_reduce(in_ptr + offset, out_ptr, reduction_size, Op{}, init);
}
} else {
for (int i = 0; i < out.size(); i++, out_ptr++) {
int offset = elem_to_loc(i, shape, strides);
int64_t offset = elem_to_loc(i, shape, strides);
*out_ptr = init;
nd_loop(
[&](int extra_offset) {
[&](int64_t extra_offset) {
contiguous_reduce(
in_ptr + offset + extra_offset,
out_ptr,
Expand Down Expand Up @@ -229,18 +234,18 @@ void reduction_op(

if (plan.shape.size() == 0) {
for (int i = 0; i < out.size(); i += reduction_stride) {
int offset = elem_to_loc(i, shape, strides);
int64_t offset = elem_to_loc(i, shape, strides);
std::fill_n(out_ptr, reduction_stride, init);
strided_reduce(
in_ptr + offset, out_ptr, reduction_size, reduction_stride, Op{});
out_ptr += reduction_stride;
}
} else {
for (int i = 0; i < out.size(); i += reduction_stride) {
int offset = elem_to_loc(i, shape, strides);
int64_t offset = elem_to_loc(i, shape, strides);
std::fill_n(out_ptr, reduction_stride, init);
nd_loop(
[&](int extra_offset) {
[&](int64_t extra_offset) {
strided_reduce(
in_ptr + offset + extra_offset,
out_ptr,
Expand All @@ -260,10 +265,10 @@ void reduction_op(
auto [shape, strides] = shapes_without_reduction_axes(x, axes);

for (int i = 0; i < out.size(); i++, out_ptr++) {
int offset = elem_to_loc(i, shape, strides);
int64_t offset = elem_to_loc(i, shape, strides);
U val = init;
nd_loop(
[&](int extra_offset) {
[&](int64_t extra_offset) {
val = Op{}(val, *(in_ptr + offset + extra_offset));
},
plan.shape,
Expand Down Expand Up @@ -293,7 +298,7 @@ void float_reduction(
struct AndReduce {
template <typename T>
bool operator()(bool x, T y) {
return x & (y != 0);
return x & static_cast<bool>(y);
}

bool operator()(bool x, bool y) {
Expand All @@ -319,7 +324,7 @@ struct AndReduce {
struct OrReduce {
template <typename T>
bool operator()(bool x, T y) {
return x | (y != 0);
return x | static_cast<bool>(y);
}

bool operator()(bool x, bool y) {
Expand Down Expand Up @@ -517,12 +522,11 @@ void Reduce::eval_cpu(const std::vector<array>& inputs, array& out) {
break;
case uint64:
case int64:
// complex64 stays on the integer path. Testing it as a complex
// would go through complex64_t's conversion to float and only look
// at the real part, which would miss 1j.
case complex64:
reduce_dispatch_and_or<int64_t>(in, out, reduce_type_, axes_);
break;
case complex64:
reduce_dispatch_and_or<complex64_t>(in, out, reduce_type_, axes_);
break;
case float64:
reduce_dispatch_and_or<double>(in, out, reduce_type_, axes_);
break;
Expand Down
23 changes: 23 additions & 0 deletions mlx/backend/cpu/simd/math.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ template <typename T, int N>
Simd<T, N> exp(Simd<T, N> in) {
if constexpr (is_complex<T>) {
return Simd<T, 1>{std::exp(in.value)};
} else if constexpr (std::is_same_v<T, double>) {
// The path below computes in float32.
Simd<T, N> out;
for (int i = 0; i < N; ++i) {
out[i] = std::exp(in[i]);
}
return out;
} else {
Simd<float, N> x_init = in;
auto x = x_init * 1.442695f; // multiply with log_2(e)
Expand Down Expand Up @@ -121,6 +128,14 @@ Simd<T, N> sincos(Simd<T, N> in) {
// to libm instead. 2^23 keeps x * 4/pi under 2^24 with room to spare.
template <bool Sine, typename T, int N>
Simd<T, N> sincos_checked(Simd<T, N> x) {
if constexpr (std::is_same_v<T, double>) {
// The path below computes in float32.
Simd<T, N> out;
for (int i = 0; i < N; ++i) {
out[i] = Sine ? std::sin(x[i]) : std::cos(x[i]);
}
return out;
}
Simd<float, N> xf = x;
if (any(abs(xf) > Simd<float, N>(8388608.0f))) {
Simd<T, N> out;
Expand Down Expand Up @@ -153,6 +168,14 @@ Simd<T, N> cos(Simd<T, N> x) {

template <typename T, int N>
Simd<T, N> erf(Simd<T, N> x) {
if constexpr (std::is_same_v<T, double>) {
// The path below computes in float32.
Simd<T, N> out;
for (int i = 0; i < N; ++i) {
out[i] = std::erf(x[i]);
}
return out;
}
// https://github.com/pytorch/pytorch/blob/abf28982a8cb43342e7669d859de9543fd804cc9/aten/src/ATen/cpu/vec/vec256/vec256_float.h#L175
Simd<float, N> v = x;
auto t = recip(fma(Simd<float, N>(0.3275911f), abs(v), 1.0f));
Expand Down
Loading