// Copyright © 2023-2024 Apple Inc. #include #include #include #include #include #include #include "mlx/ops.h" #include "mlx/primitives.h" #include "mlx/transforms.h" #include "mlx/utils.h" namespace mlx::core { namespace { std::pair, std::vector> compute_reduce_shape( const std::vector& axes, const std::vector& shape) { std::set axes_set; auto ndim = shape.size(); for (auto ax : axes) { int ax_ = (ax < 0) ? ax + ndim : ax; if (ax_ < 0 || ax_ >= ndim) { std::ostringstream msg; msg << "Invalid axis " << ax << " for array with " << ndim << " dimensions."; throw std::out_of_range(msg.str()); } axes_set.insert(ax_); } if (axes_set.size() != axes.size()) { throw std::invalid_argument("Duplicate axes detected in reduction."); } std::vector out_shape; for (int i = 0; i < ndim; ++i) { if (axes_set.count(i) == 0) { out_shape.push_back(shape[i]); } else { out_shape.push_back(1); } } std::vector sorted_axes(axes_set.begin(), axes_set.end()); return {out_shape, sorted_axes}; } Dtype at_least_float(const Dtype& d) { return is_floating_point(d) ? d : promote_types(d, float32); } } // namespace array arange( double start, double stop, double step, Dtype dtype, StreamOrDevice s /* = {} */) { if (dtype == bool_) { std::ostringstream msg; msg << bool_ << " not supported for arange."; throw std::invalid_argument(msg.str()); } if (std::isnan(start) || std::isnan(step) || std::isnan(stop)) { throw std::invalid_argument("[arange] Cannot compute length."); } if (std::isinf(start) || std::isinf(stop)) { throw std::invalid_argument("[arange] Cannot compute length."); } // Check if start and stop specify a valid range because if not, we have to // return an empty array if (std::isinf(step) && (step > 0 && start < stop || step < 0 && start > stop)) { return array({start}, dtype); } double real_size = std::ceil((stop - start) / step); if (real_size > INT_MAX) { throw std::invalid_argument("[arange] Maximum size exceeded."); } int size = std::max(static_cast(real_size), 0); return array( {size}, dtype, std::make_unique(to_stream(s), start, stop, step), {}); } array arange( double start, double stop, double step, StreamOrDevice s /* = {} */) { return arange(start, stop, step, float32, to_stream(s)); } array arange( double start, double stop, Dtype dtype, StreamOrDevice s /* = {} */) { return arange(start, stop, 1.0, dtype, to_stream(s)); } array arange(double start, double stop, StreamOrDevice s /* = {} */) { return arange(start, stop, 1.0, float32, to_stream(s)); } array arange(double stop, Dtype dtype, StreamOrDevice s /* = {} */) { return arange(0.0, stop, 1.0, dtype, to_stream(s)); } array arange(double stop, StreamOrDevice s /* = {} */) { return arange(0.0, stop, 1.0, float32, to_stream(s)); } array arange(int start, int stop, int step, StreamOrDevice s /* = {} */) { return arange( static_cast(start), static_cast(stop), static_cast(step), int32, to_stream(s)); } array arange(int start, int stop, StreamOrDevice s /* = {} */) { return arange( static_cast(start), static_cast(stop), 1.0, int32, to_stream(s)); } array arange(int stop, StreamOrDevice s /* = {} */) { return arange(0.0, static_cast(stop), 1.0, int32, to_stream(s)); } array linspace( double start, double stop, int num /* = 50 */, Dtype dtype /* = float32 */, StreamOrDevice s /* = {} */) { if (num < 0) { std::ostringstream msg; msg << "[linspace] number of samples, " << num << ", must be non-negative."; throw std::invalid_argument(msg.str()); } if (num == 1) { return astype(array({start}), dtype, to_stream(s)); } array sequence = arange(0, num, float32, to_stream(s)); float step = (stop - start) / (num - 1); return astype( add(multiply(sequence, array(step), to_stream(s)), array(start), to_stream(s)), dtype, to_stream(s)); } array astype(const array& a, Dtype dtype, StreamOrDevice s /* = {} */) { if (dtype == a.dtype()) { return a; } return array( a.shape(), dtype, std::make_unique(to_stream(s), dtype), {a}); } array as_strided( const array& a, std::vector shape, std::vector strides, size_t offset, StreamOrDevice s /* = {} */) { // Force the input array to be contiguous auto x = reshape(a, {-1}, s); return array( shape, a.dtype(), std::make_unique(to_stream(s), shape, strides, offset), {x}); } array copy(const array& a, StreamOrDevice s /* = {} */) { return array(a.shape(), a.dtype(), std::make_unique(to_stream(s)), {a}); } array full( const std::vector& shape, const array& vals, Dtype dtype, StreamOrDevice s /* = {} */) { if (std::any_of(shape.begin(), shape.end(), [](auto i) { return i < 0; })) { throw std::invalid_argument("[full] Negative dimensions not allowed."); } auto in = broadcast_to(astype(vals, dtype, s), shape, s); return array(shape, dtype, std::make_unique(to_stream(s)), {in}); } array full( const std::vector& shape, const array& vals, StreamOrDevice s /* = {} */) { return full(shape, vals, vals.dtype(), to_stream(s)); } array zeros( const std::vector& shape, Dtype dtype, StreamOrDevice s /* = {} */) { return full(shape, array(0, dtype), to_stream(s)); } array zeros_like(const array& a, StreamOrDevice s /* = {} */) { return zeros(a.shape(), a.dtype(), to_stream(s)); } array ones( const std::vector& shape, Dtype dtype, StreamOrDevice s /* = {} */) { return full(shape, array(1, dtype), to_stream(s)); } array ones_like(const array& a, StreamOrDevice s /* = {} */) { return ones(a.shape(), a.dtype(), to_stream(s)); } array eye(int n, int m, int k, Dtype dtype, StreamOrDevice s /* = {} */) { if (n <= 0 || m <= 0) { throw std::invalid_argument("[eye] N and M must be positive integers."); } array result = zeros({n, m}, dtype, s); if (k >= m || -k >= n) { return result; } int diagonal_length = k >= 0 ? std::min(n, m - k) : std::min(n + k, m); std::vector indices; auto s1 = std::max(0, -k); auto s2 = std::max(0, k); indices.push_back(arange(s1, diagonal_length + s1, int32, s)); indices.push_back(arange(s2, diagonal_length + s2, int32, s)); array ones_array = ones({diagonal_length, 1, 1}, dtype, s); return scatter(result, indices, ones_array, {0, 1}, s); } array identity(int n, Dtype dtype, StreamOrDevice s /* = {} */) { return eye(n, n, 0, dtype, s); } array tri(int n, int m, int k, Dtype type, StreamOrDevice s /* = {} */) { auto l = expand_dims(arange(n, s), 1, s); auto r = expand_dims(arange(-k, m - k, s), 0, s); return astype(greater_equal(l, r, s), type, s); } array tril(array x, int k /* = 0 */, StreamOrDevice s /* = {} */) { if (x.ndim() < 2) { throw std::invalid_argument("[tril] array must be at least 2-D"); } auto mask = tri(x.shape(-2), x.shape(-1), k, x.dtype(), s); return where(mask, x, zeros_like(x, s), s); } array triu(array x, int k /* = 0 */, StreamOrDevice s /* = {} */) { if (x.ndim() < 2) { throw std::invalid_argument("[triu] array must be at least 2-D"); } auto mask = tri(x.shape(-2), x.shape(-1), k - 1, x.dtype(), s); return where(mask, zeros_like(x, s), x, s); } array reshape( const array& a, std::vector shape, StreamOrDevice s /* = {} */) { if (a.shape() == shape) { return a; } size_t size = 1; int infer_idx = -1; for (int i = 0; i < shape.size(); ++i) { if (shape[i] == -1) { if (infer_idx >= 0) { throw std::invalid_argument( "[reshape] Reshape can only infer one dimension."); } infer_idx = i; } else { size *= shape[i]; } } // Infer the shape if (size > 0) { auto q_and_r = std::ldiv(a.size(), size); if (infer_idx >= 0) { shape[infer_idx] = q_and_r.quot; size *= q_and_r.quot; } } else if (infer_idx >= 0) { throw std::invalid_argument( "[reshape] Cannot infer the shape of an empty array"); } // Check the the reshaping is valid if (a.size() != size) { std::ostringstream msg; msg << "[reshape] Cannot reshape array of size " << a.size() << " into shape " << shape << "."; throw std::invalid_argument(msg.str()); } return array( shape, a.dtype(), std::make_unique(to_stream(s), shape), {a}); } array flatten( const array& a, int start_axis, int end_axis /* = -1 */, StreamOrDevice s /* = {} */) { auto ndim = static_cast(a.ndim()); auto start_ax = start_axis + (start_axis < 0 ? ndim : 0); auto end_ax = end_axis + (end_axis < 0 ? ndim : 0); start_ax = std::max(0, start_ax); end_ax = std::min(ndim - 1, end_ax); if (a.ndim() == 0) { return reshape(a, {1}, s); } if (end_ax < start_ax) { throw std::invalid_argument( "[flatten] start_axis must be less than or equal to end_axis"); } if (start_ax >= ndim) { std::ostringstream msg; msg << "[flatten] Invalid start_axis " << start_axis << " for array with " << ndim << " dimensions."; throw std::invalid_argument(msg.str()); } if (end_ax < 0) { std::ostringstream msg; msg << "[flatten] Invalid end_axis " << end_axis << " for array with " << ndim << " dimensions."; throw std::invalid_argument(msg.str()); } if (start_ax == end_ax) { return a; } std::vector new_shape(a.shape().begin(), a.shape().begin() + start_ax); new_shape.push_back(-1); new_shape.insert( new_shape.end(), a.shape().begin() + end_ax + 1, a.shape().end()); return reshape(a, new_shape, s); } array flatten(const array& a, StreamOrDevice s /* = {} */) { return flatten(a, 0, a.ndim() - 1, s); } array squeeze( const array& a, const std::vector& axes, StreamOrDevice s /* = {} */) { std::set unique_axes; for (auto ax : axes) { ax = ax < 0 ? ax + a.ndim() : ax; if (ax < 0 || ax >= a.ndim()) { std::ostringstream msg; msg << "[squeeze] Invalid axes " << ax << " for array with " << a.ndim() << " dimensions."; throw std::invalid_argument(msg.str()); } if (a.shape(ax) != 1) { std::ostringstream msg; msg << "[squeeze] Cannot squeeze axis " << ax << " with size " << a.shape(ax) << " which is not equal to 1."; throw std::invalid_argument(msg.str()); } unique_axes.insert(ax); } if (unique_axes.size() != axes.size()) { throw std::invalid_argument("[squeeze] Received duplicate axes."); } std::vector sorted_axes(unique_axes.begin(), unique_axes.end()); std::vector shape; for (int i = 0, j = 0; i < a.ndim(); ++i) { if (j < sorted_axes.size() && i == sorted_axes[j]) { j++; } else { shape.push_back(a.shape(i)); } } return reshape(a, shape, s); } array squeeze(const array& a, StreamOrDevice s /* = {} */) { std::vector axes; for (int i = 0; i < a.ndim(); ++i) { if (a.shape(i) == 1) { axes.push_back(i); } } return squeeze(a, axes, s); } array expand_dims( const array& a, const std::vector& axes, StreamOrDevice s /* = {} */) { { // Check for repeats std::set unique_axes(axes.begin(), axes.end()); if (unique_axes.size() != axes.size()) { throw std::invalid_argument("[expand_dims] Received duplicate axes."); } } int out_ndim = axes.size() + a.ndim(); std::vector canonical_axes = axes; for (auto& ax : canonical_axes) { ax = ax < 0 ? ax + out_ndim : ax; if (ax < 0 || ax >= out_ndim) { std::ostringstream msg; msg << "[squeeze] Invalid axes " << ax << " for output array with " << a.ndim() << " dimensions."; throw std::invalid_argument(msg.str()); } } // Check for repeats again std::set unique_axes(canonical_axes.begin(), canonical_axes.end()); if (unique_axes.size() != axes.size()) { throw std::invalid_argument("[expand_dims] Received duplicate axes."); } std::vector sorted_axes(unique_axes.begin(), unique_axes.end()); auto out_shape = a.shape(); for (int i = 0; i < sorted_axes.size(); ++i) { out_shape.insert(out_shape.begin() + sorted_axes[i], 1); } return reshape(a, out_shape, s); } array slice( const array& a, std::vector start, std::vector stop, std::vector strides, StreamOrDevice s /* = {} */) { if (start.size() != a.ndim() || stop.size() != a.ndim() || strides.size() != a.ndim()) { std::ostringstream msg; msg << "[slice] Invalid number of indices or strides for " << "array with dimension " << a.ndim() << "."; throw std::invalid_argument(msg.str()); } std::vector negatively_strided_axes; std::vector> negatively_strided_slices; std::vector out_shape(a.ndim()); for (int i = 0; i < a.ndim(); ++i) { // Following numpy docs // Negative i and j are interpreted as n + i and n + j where n is // the number of elements in the corresponding dimension. Negative // k makes stepping go towards smaller indices auto n = a.shape(i); auto s = start[i]; s = s < 0 ? s + n : s; auto e = stop[i]; e = e < 0 ? e + n : e; // Note: We pass positive strides to the primitive and then flip // the axes later as needed if (strides[i] < 0) { negatively_strided_axes.push_back(i); auto st = std::min(s, n - 1); auto ed = std::max(e, -1); negatively_strided_slices.push_back({st, ed, strides[i]}); start[i] = 0; stop[i] = n; strides[i] = 1; } else { start[i] = s; stop[i] = e < s ? s : e; } // Clamp to bounds start[i] = std::max(0, std::min(start[i], n)); stop[i] = std::max(0, std::min(stop[i], n)); out_shape[i] = (stop[i] - start[i] + strides[i] - 1) / strides[i]; } // If strides are negative, slice and then make a copy with axes flipped if (negatively_strided_axes.size() > 0) { // First, take the slice of the positively strided axes auto out = array( out_shape, a.dtype(), std::make_unique( to_stream(s), std::move(start), std::move(stop), std::move(strides)), {a}); std::vector indices; std::vector slice_sizes = out.shape(); std::vector t_axes(out.ndim(), -1); std::vector out_reshape(out.ndim(), -1); int n_axes = negatively_strided_axes.size(); for (int i = 0; i < n_axes; i++) { // Get axis and corresponding slice auto ax = negatively_strided_axes[i]; auto sl = negatively_strided_slices[i]; // Get indices for the slice auto ax_idx = arange(sl[0], sl[1], sl[2], s); // Reshape indices for broadcast as needed std::vector ax_idx_shape(n_axes, 1); ax_idx_shape[i] = ax_idx.size(); ax_idx = reshape(ax_idx, ax_idx_shape, s); // Add indices to list indices.push_back(ax_idx); // Set slice size for axis slice_sizes[ax] = 1; // Gather moves the axis up, remainder needs to be squeezed out_reshape[i] = indices[i].size(); // Gather moves the axis up, needs to be transposed t_axes[ax] = i; } // Prepare out_reshape to squeeze gathered dims // Prepare to transpose dims as needed int j = n_axes; for (int i = 0; j < out.ndim() && i < out.ndim(); i++) { if (t_axes[i] < 0) { t_axes[i] = j; out_reshape[j] = out_shape[i]; j++; } } // Gather out = gather(out, indices, negatively_strided_axes, slice_sizes, s); // Squeeze dims out = reshape(out, out_reshape, s); // Transpose dims out = transpose(out, t_axes, s); return out; } if (out_shape == a.shape()) { return a; } return array( out_shape, a.dtype(), std::make_unique( to_stream(s), std::move(start), std::move(stop), std::move(strides)), {a}); } array slice( const array& a, const std::vector& start, const std::vector& stop, StreamOrDevice s /* = {} */) { return slice(a, start, stop, std::vector(a.ndim(), 1), to_stream(s)); } std::vector split( const array& a, const std::vector& indices, int axis, StreamOrDevice s /* = {} */) { auto ax = axis < 0 ? axis + a.ndim() : axis; if (ax < 0 || ax >= a.ndim()) { std::ostringstream msg; msg << "Invalid axis (" << axis << ") passed to split" << " for array with shape " << a.shape() << "."; throw std::invalid_argument(msg.str()); } if (indices.empty()) { return {a}; } if (indices.size() < 10 && std::is_sorted(indices.begin(), indices.end(), std::less<>{}) && indices[0] > 0 && indices.back() < a.shape(ax)) { std::vector dtypes(indices.size() + 1, a.dtype()); std::vector> shapes(indices.size() + 1, a.shape()); shapes[0][ax] = indices[0]; for (int i = 1; i < indices.size(); i++) { shapes[i][ax] = indices[i] - indices[i - 1]; } shapes.back()[ax] = a.shape(ax) - indices.back(); return array::make_arrays( shapes, dtypes, std::make_shared(to_stream(s), indices, ax), {a}); } std::vector res; auto out_shape = a.shape(); auto start_indices = std::vector(a.ndim(), 0); auto stop_indices = a.shape(); for (int i = 0; i < indices.size() + 1; ++i) { stop_indices[ax] = i < indices.size() ? indices[i] : a.shape(ax); res.push_back(slice(a, start_indices, stop_indices, to_stream(s))); start_indices[ax] = stop_indices[ax]; } return res; } std::vector split( const array& a, const std::vector& indices, StreamOrDevice s /* = {} */) { return split(a, indices, 0, s); } std::vector split(const array& a, int num_splits, int axis, StreamOrDevice s /* = {} */) { auto ax = axis < 0 ? axis + a.ndim() : axis; if (ax < 0 || ax >= a.ndim()) { std::ostringstream msg; msg << "Invalid axis " << axis << " passed to split" << " for array with shape " << a.shape() << "."; throw std::invalid_argument(msg.str()); } auto q_and_r = std::ldiv(a.shape(axis), num_splits); if (q_and_r.rem) { std::ostringstream msg; msg << "Array split does not result in sub arrays with equal size:" << " attempting " << num_splits << " splits along axis " << axis << " for shape " << a.shape() << "."; throw std::invalid_argument(msg.str()); } auto split_size = q_and_r.quot; std::vector indices(num_splits - 1); for (int i = 0; i < indices.size(); ++i) { indices[i] = (i + 1) * split_size; } return split(a, indices, axis, s); } std::vector split(const array& a, int num_splits, StreamOrDevice s /* = {} */) { return split(a, num_splits, 0, to_stream(s)); } array clip( const array& a, const std::optional& a_min, const std::optional& a_max, StreamOrDevice s /* = {} */) { if (!a_min.has_value() && !a_max.has_value()) { throw std::invalid_argument("At most one of a_min and a_max may be None"); } array result = astype(a, a.dtype(), s); if (a_min.has_value()) { result = maximum(result, a_min.value(), s); } if (a_max.has_value()) { result = minimum(result, a_max.value(), s); } return result; } array concatenate( const std::vector& arrays, int axis, StreamOrDevice s /* = {} */) { if (arrays.size() == 0) { throw std::invalid_argument( "[concatenate] No arrays provided for concatenation"); } // Normalize the given axis auto ax = axis < 0 ? axis + arrays[0].ndim() : axis; if (ax < 0 || ax >= arrays[0].ndim()) { std::ostringstream msg; msg << "[concatenate] Invalid axis (" << axis << ") passed to concatenate" << " for array with shape " << arrays[0].shape() << "."; throw std::invalid_argument(msg.str()); } auto throw_invalid_shapes = [&]() { std::ostringstream msg; msg << "[concatenate] All the input array dimensions must match exactly " << "except for the concatenation axis. However, the provided shapes are "; for (auto& a : arrays) { msg << a.shape() << ", "; } msg << "and the concatenation axis is " << axis << "."; throw std::invalid_argument(msg.str()); }; std::vector shape = arrays[0].shape(); shape[ax] = 0; // Make the output shape and validate that all arrays have the same shape // except for the concatenation axis. for (auto& a : arrays) { if (a.ndim() != shape.size()) { std::ostringstream msg; msg << "[concatenate] All the input arrays must have the same number of " << "dimensions. However, got arrays with dimensions " << shape.size() << " and " << a.ndim() << "."; throw std::invalid_argument(msg.str()); } for (int i = 0; i < a.ndim(); i++) { if (i == ax) { continue; } if (a.shape(i) != shape[i]) { throw_invalid_shapes(); } } shape[ax] += a.shape(ax); } // Promote all the arrays to the same type auto dtype = result_type(arrays); return array( shape, dtype, std::make_unique(to_stream(s), ax), arrays); } array concatenate( const std::vector& arrays, StreamOrDevice s /* = {} */) { std::vector flat_inputs; for (auto& a : arrays) { flat_inputs.push_back(reshape(a, {-1}, s)); } return concatenate(flat_inputs, 0, s); } /** Stack arrays along a new axis */ array stack( const std::vector& arrays, int axis, StreamOrDevice s /* = {} */) { if (arrays.empty()) { throw std::invalid_argument("No arrays provided for stacking"); } if (!is_same_shape(arrays)) { throw std::invalid_argument("All arrays must have the same shape"); } int normalized_axis = normalize_axis(axis, arrays[0].ndim() + 1); std::vector new_arrays; new_arrays.reserve(arrays.size()); for (auto& a : arrays) { new_arrays.emplace_back(expand_dims(a, normalized_axis, s)); } return concatenate(new_arrays, axis, s); } array stack(const std::vector& arrays, StreamOrDevice s /* = {} */) { return stack(arrays, 0, s); } /** array repeat with axis */ array repeat(const array& arr, int repeats, int axis, StreamOrDevice s) { axis = normalize_axis(axis, arr.ndim()); if (repeats < 0) { throw std::invalid_argument( "[repeat] Number of repeats cannot be negative"); } if (repeats == 0) { return array({}, arr.dtype()); } if (repeats == 1) { return arr; } // Broadcast to (S_1, S_2, ..., S_axis, repeats, S_axis+1, ...) std::vector shape(arr.shape()); shape.insert(shape.begin() + axis + 1, repeats); array out = expand_dims(arr, axis + 1, s); out = broadcast_to(out, shape, s); // Reshape back into a contiguous array where S_axis is now S_axis * repeats shape.erase(shape.begin() + axis + 1); shape[axis] *= repeats; out = reshape(out, shape, s); return out; } array repeat(const array& arr, int repeats, StreamOrDevice s) { return repeat(flatten(arr, s), repeats, 0, s); } array tile( const array& arr, std::vector reps, StreamOrDevice s /* = {} */) { auto shape = arr.shape(); if (reps.size() < shape.size()) { reps.insert(reps.begin(), shape.size() - reps.size(), 1); } if (reps.size() > shape.size()) { shape.insert(shape.begin(), reps.size() - shape.size(), 1); } std::vector expand_shape; std::vector broad_shape; std::vector final_shape; for (int i = 0; i < shape.size(); i++) { if (reps[i] != 1) { expand_shape.push_back(1); broad_shape.push_back(reps[i]); } expand_shape.push_back(shape[i]); broad_shape.push_back(shape[i]); final_shape.push_back(reps[i] * shape[i]); } auto x = reshape(arr, expand_shape, s); x = broadcast_to(x, broad_shape, s); return reshape(x, final_shape, s); } /** Pad an array with a constant value */ array pad( const array& a, const std::vector& axes, const std::vector& low_pad_size, const std::vector& high_pad_size, const array& pad_value /*= array(0)*/, StreamOrDevice s /* = {}*/) { if (axes.size() != low_pad_size.size() || axes.size() != high_pad_size.size()) { std::ostringstream msg; msg << "Invalid number of padding sizes passed to pad " << "with axes of size " << axes.size(); throw std::invalid_argument(msg.str()); } std::vector out_shape = a.shape(); for (int i = 0; i < axes.size(); i++) { if (low_pad_size[i] < 0) { std::ostringstream msg; msg << "Invalid low padding size (" << low_pad_size[i] << ") passed to pad" << " for axis " << i << ". Padding sizes must be non-negative"; throw std::invalid_argument(msg.str()); } if (high_pad_size[i] < 0) { std::ostringstream msg; msg << "Invalid high padding size (" << high_pad_size[i] << ") passed to pad" << " for axis " << i << ". Padding sizes must be non-negative"; throw std::invalid_argument(msg.str()); } auto ax = axes[i] < 0 ? a.ndim() + axes[i] : axes[i]; out_shape[ax] += low_pad_size[i] + high_pad_size[i]; } return array( out_shape, a.dtype(), std::make_unique(to_stream(s), axes, low_pad_size, high_pad_size), {a, astype(pad_value, a.dtype(), s)}); } /** Pad an array with a constant value along all axes */ array pad( const array& a, const std::vector>& pad_width, const array& pad_value /*= array(0)*/, StreamOrDevice s /*= {}*/) { std::vector axes(a.ndim(), 0); std::iota(axes.begin(), axes.end(), 0); std::vector lows; std::vector highs; for (auto& pads : pad_width) { lows.push_back(pads.first); highs.push_back(pads.second); } return pad(a, axes, lows, highs, pad_value, s); } array pad( const array& a, const std::pair& pad_width, const array& pad_value /*= array(0)*/, StreamOrDevice s /*= {}*/) { return pad( a, std::vector>(a.ndim(), pad_width), pad_value, s); } array pad( const array& a, int pad_width, const array& pad_value /*= array(0)*/, StreamOrDevice s /*= {}*/) { return pad( a, std::vector>(a.ndim(), {pad_width, pad_width}), pad_value, s); } array moveaxis( const array& a, int source, int destination, StreamOrDevice s /* = {} */) { auto check_ax = [&a](int ax) { auto ndim = static_cast(a.ndim()); if (ax < -ndim || ax >= ndim) { std::ostringstream msg; msg << "[moveaxis] Invalid axis " << ax << " for array with " << ndim << " dimensions."; throw std::out_of_range(msg.str()); } return ax < 0 ? ax + ndim : ax; }; source = check_ax(source); destination = check_ax(destination); std::vector reorder(a.ndim()); std::iota(reorder.begin(), reorder.end(), 0); reorder.erase(reorder.begin() + source); reorder.insert(reorder.begin() + destination, source); return transpose(a, reorder, s); } array swapaxes( const array& a, int axis1, int axis2, StreamOrDevice s /* = {} */) { auto check_ax = [&a](int ax) { auto ndim = static_cast(a.ndim()); if (ax < -ndim || ax >= ndim) { std::ostringstream msg; msg << "[swapaxes] Invalid axis " << ax << " for array with " << ndim << " dimensions."; throw std::out_of_range(msg.str()); } return ax < 0 ? ax + ndim : ax; }; axis1 = check_ax(axis1); axis2 = check_ax(axis2); std::vector reorder(a.ndim()); std::iota(reorder.begin(), reorder.end(), 0); std::swap(reorder[axis1], reorder[axis2]); return transpose(a, reorder, s); } array transpose( const array& a, std::vector axes, StreamOrDevice s /* = {} */) { for (auto& ax : axes) { ax = ax < 0 ? ax + a.ndim() : ax; } std::set dims(axes.begin(), axes.end()); if (dims.size() != axes.size()) { throw std::invalid_argument("Repeat axes not allowed in transpose."); } if (dims.size() != a.ndim() || a.ndim() > 0 && (*dims.begin() != 0 || *dims.rbegin() != (a.ndim() - 1))) { throw std::invalid_argument("Transpose axes don't match array dimensions."); } std::vector shape; shape.reserve(axes.size()); for (auto ax : axes) { shape.push_back(a.shape()[ax]); } return array( shape, a.dtype(), std::make_unique(to_stream(s), std::move(axes)), {a}); } array transpose(const array& a, StreamOrDevice s /* = {} */) { std::vector axes(a.ndim()); std::iota(axes.rbegin(), axes.rend(), 0); return transpose(a, std::move(axes), to_stream(s)); } array broadcast_to( const array& a, const std::vector& shape, StreamOrDevice s /* = {} */) { if (a.shape() == shape) { return a; } // Make sure the shapes are broadcastable auto bxshape = broadcast_shapes(a.shape(), shape); if (bxshape != shape) { std::ostringstream msg; msg << "Cannot broadcast array of shape " << a.shape() << " into shape " << shape << "."; throw std::invalid_argument(msg.str()); } return array( shape, a.dtype(), std::make_unique(to_stream(s), shape), {a}); } std::vector broadcast_arrays( const std::vector& inputs, StreamOrDevice s /* = {} */) { std::vector shape{}; for (const auto& in : inputs) { shape = broadcast_shapes(shape, in.shape()); } std::vector outputs; for (const auto& in : inputs) { outputs.push_back(broadcast_to(in, shape, s)); } return outputs; } array equal(const array& a, const array& b, StreamOrDevice s /* = {} */) { auto dtype = promote_types(a.dtype(), b.dtype()); std::vector inputs = {astype(a, dtype, s), astype(b, dtype, s)}; if (a.shape() != b.shape()) { inputs = broadcast_arrays(inputs, s); } return array( inputs[0].shape(), bool_, std::make_unique(to_stream(s)), inputs); } array not_equal(const array& a, const array& b, StreamOrDevice s /* = {} */) { auto dtype = promote_types(a.dtype(), b.dtype()); std::vector inputs = {astype(a, dtype, s), astype(b, dtype, s)}; if (a.shape() != b.shape()) { inputs = broadcast_arrays(inputs, s); } return array( inputs[0].shape(), bool_, std::make_unique(to_stream(s)), inputs); } array greater(const array& a, const array& b, StreamOrDevice s /* = {} */) { auto dtype = promote_types(a.dtype(), b.dtype()); std::vector inputs = {astype(a, dtype, s), astype(b, dtype, s)}; if (a.shape() != b.shape()) { inputs = broadcast_arrays(inputs, s); } return array( inputs[0].shape(), bool_, std::make_unique(to_stream(s)), inputs); } array greater_equal( const array& a, const array& b, StreamOrDevice s /* = {} */) { auto dtype = promote_types(a.dtype(), b.dtype()); std::vector inputs = {astype(a, dtype, s), astype(b, dtype, s)}; if (a.shape() != b.shape()) { inputs = broadcast_arrays(inputs, s); } return array( inputs[0].shape(), bool_, std::make_unique(to_stream(s)), inputs); } array less(const array& a, const array& b, StreamOrDevice s /* = {} */) { auto dtype = promote_types(a.dtype(), b.dtype()); std::vector inputs = {astype(a, dtype, s), astype(b, dtype, s)}; if (a.shape() != b.shape()) { inputs = broadcast_arrays(inputs, s); } return array( inputs[0].shape(), bool_, std::make_unique(to_stream(s)), inputs); } array less_equal(const array& a, const array& b, StreamOrDevice s /* = {} */) { auto dtype = promote_types(a.dtype(), b.dtype()); std::vector inputs = {astype(a, dtype, s), astype(b, dtype, s)}; if (a.shape() != b.shape()) { inputs = broadcast_arrays(inputs, s); } return array( inputs[0].shape(), bool_, std::make_unique(to_stream(s)), inputs); } array array_equal( const array& a, const array& b, bool equal_nan, StreamOrDevice s /* = {} */) { if (a.shape() != b.shape()) { return array(false); } else { auto dtype = promote_types(a.dtype(), b.dtype()); equal_nan &= is_floating_point(dtype); return all( array( a.shape(), bool_, std::make_unique(to_stream(s), equal_nan), {astype(a, dtype, s), astype(b, dtype, s)}), false, s); } } array isnan(const array& a, StreamOrDevice s /* = {} */) { if (is_integral(a.dtype())) { return full(a.shape(), false, bool_, s); } return not_equal(a, a, s); } array isinf(const array& a, StreamOrDevice s /* = {} */) { return logical_or(isposinf(a, s), isneginf(a, s), s); } array isposinf(const array& a, StreamOrDevice s /* = {} */) { if (is_integral(a.dtype())) { return full(a.shape(), false, bool_, s); } return equal(a, array(std::numeric_limits::infinity(), a.dtype()), s); } array isneginf(const array& a, StreamOrDevice s /* = {} */) { if (is_integral(a.dtype())) { return full(a.shape(), false, bool_, s); } return equal(a, array(-std::numeric_limits::infinity(), a.dtype()), s); } array where( const array& a, const array& b, const array& c, StreamOrDevice s /* = {} */) { auto condition = astype(a, bool_, s); Dtype out_dtype = promote_types(b.dtype(), c.dtype()); auto inputs = broadcast_arrays( {condition, astype(b, out_dtype, s), astype(c, out_dtype, s)}, s); return array( inputs[0].shape(), out_dtype, std::make_unique