|
| 1 | +// Copyright © 2026 Apple Inc. |
| 2 | + |
| 3 | +#include <MetalPerformanceShaders/MetalPerformanceShaders.h> |
| 4 | + |
| 5 | +#include "mlx/allocator.h" |
| 6 | +#include "mlx/backend/metal/device.h" |
| 7 | +#include "mlx/primitives.h" |
| 8 | + |
| 9 | +namespace mlx::core { |
| 10 | +namespace { |
| 11 | + |
| 12 | +id<MTLBuffer> metal_buffer(const array& a) { |
| 13 | + return (__bridge id<MTLBuffer>)(void*)a.buffer().ptr(); |
| 14 | +} |
| 15 | + |
| 16 | +id<MTLDevice> metal_device(metal::Device& device) { |
| 17 | + return (__bridge id<MTLDevice>)(void*)device.mtl_device(); |
| 18 | +} |
| 19 | + |
| 20 | +id<MTLCommandBuffer> metal_command_buffer(metal::CommandEncoder& encoder) { |
| 21 | + return (__bridge id<MTLCommandBuffer>)(void*)encoder.get_command_buffer(); |
| 22 | +} |
| 23 | + |
| 24 | +MPSMatrixDescriptor* |
| 25 | +matrix_descriptor(int rows, int columns, MPSDataType dtype) { |
| 26 | + const auto row_bytes = static_cast<NSUInteger>(columns) * |
| 27 | + (dtype == MPSDataTypeUInt32 ? sizeof(uint32_t) : sizeof(float)); |
| 28 | + return [MPSMatrixDescriptor matrixDescriptorWithRows:rows |
| 29 | + columns:columns |
| 30 | + rowBytes:row_bytes |
| 31 | + dataType:dtype]; |
| 32 | +} |
| 33 | + |
| 34 | +} // namespace |
| 35 | + |
| 36 | +void Inverse::eval_gpu(const std::vector<array>& inputs, array& output) { |
| 37 | + if (inputs[0].dtype() != float32) { |
| 38 | + throw std::invalid_argument( |
| 39 | + "[Inverse::eval_gpu] Metal inversion supports float32 arrays only."); |
| 40 | + } |
| 41 | + |
| 42 | + output.set_data(allocator::malloc(output.nbytes())); |
| 43 | + if (output.size() == 0) { |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + auto& encoder = metal::get_command_encoder(stream()); |
| 48 | + const auto& input = inputs[0]; |
| 49 | + const auto& rhs = inputs[1]; |
| 50 | + |
| 51 | + const int order = input.shape(-1); |
| 52 | + const size_t batch_size = input.size() / (order * order); |
| 53 | + array lu(input.shape(), float32, nullptr, {}); |
| 54 | + array pivots({static_cast<int>(batch_size), order}, uint32, nullptr, {}); |
| 55 | + lu.set_data(allocator::malloc(lu.nbytes())); |
| 56 | + pivots.set_data(allocator::malloc(pivots.nbytes())); |
| 57 | + |
| 58 | + // MPS needs a separate command buffer after MLX compute work. |
| 59 | + encoder.end_encoding(); |
| 60 | + auto retained_inputs = std::make_shared<std::vector<array>>( |
| 61 | + std::initializer_list<array>{input, rhs}); |
| 62 | + auto input_command_buffer = metal_command_buffer(encoder); |
| 63 | + [input_command_buffer addCompletedHandler:^(id<MTLCommandBuffer>) { |
| 64 | + (void)retained_inputs; |
| 65 | + }]; |
| 66 | + encoder.commit(); |
| 67 | + |
| 68 | + auto matrix = matrix_descriptor(order, order, MPSDataTypeFloat32); |
| 69 | + auto pivot_matrix = matrix_descriptor(1, order, MPSDataTypeUInt32); |
| 70 | + auto decomposition = [[MPSMatrixDecompositionLU alloc] |
| 71 | + initWithDevice:metal_device(metal::device(stream().device)) |
| 72 | + rows:order |
| 73 | + columns:order]; |
| 74 | + auto solve = [[MPSMatrixSolveLU alloc] |
| 75 | + initWithDevice:metal_device(metal::device(stream().device)) |
| 76 | + transpose:NO |
| 77 | + order:order |
| 78 | +numberOfRightHandSides:order]; |
| 79 | + auto command_buffer = metal_command_buffer(encoder); |
| 80 | + auto retained_arrays = std::make_shared<std::vector<array>>( |
| 81 | + std::initializer_list<array>{input, rhs, lu, pivots}); |
| 82 | + auto resources = [[NSMutableArray alloc] init]; |
| 83 | + [resources addObject:matrix]; |
| 84 | + [resources addObject:pivot_matrix]; |
| 85 | + [resources addObject:decomposition]; |
| 86 | + [resources addObject:solve]; |
| 87 | + [decomposition release]; |
| 88 | + [solve release]; |
| 89 | + |
| 90 | + const auto matrix_bytes = static_cast<size_t>(order) * order * sizeof(float); |
| 91 | + const auto pivot_bytes = static_cast<size_t>(order) * sizeof(uint32_t); |
| 92 | + for (size_t batch = 0; batch < batch_size; ++batch) { |
| 93 | + auto source = [[MPSMatrix alloc] initWithBuffer:metal_buffer(input) |
| 94 | + offset:input.offset() + batch * matrix_bytes |
| 95 | + descriptor:matrix]; |
| 96 | + auto factor = [[MPSMatrix alloc] initWithBuffer:metal_buffer(lu) |
| 97 | + offset:lu.offset() + batch * matrix_bytes |
| 98 | + descriptor:matrix]; |
| 99 | + auto right_hand_side = [[MPSMatrix alloc] |
| 100 | + initWithBuffer:metal_buffer(rhs) |
| 101 | + offset:rhs.offset() + batch * matrix_bytes |
| 102 | + descriptor:matrix]; |
| 103 | + auto solution = [[MPSMatrix alloc] initWithBuffer:metal_buffer(output) |
| 104 | + offset:output.offset() + batch * matrix_bytes |
| 105 | + descriptor:matrix]; |
| 106 | + auto pivot_indices = [[MPSMatrix alloc] |
| 107 | + initWithBuffer:metal_buffer(pivots) |
| 108 | + offset:pivots.offset() + batch * pivot_bytes |
| 109 | + descriptor:pivot_matrix]; |
| 110 | + [resources addObject:source]; |
| 111 | + [resources addObject:factor]; |
| 112 | + [resources addObject:right_hand_side]; |
| 113 | + [resources addObject:solution]; |
| 114 | + [resources addObject:pivot_indices]; |
| 115 | + [source release]; |
| 116 | + [factor release]; |
| 117 | + [right_hand_side release]; |
| 118 | + [solution release]; |
| 119 | + [pivot_indices release]; |
| 120 | + |
| 121 | + [decomposition encodeToCommandBuffer:command_buffer |
| 122 | + sourceMatrix:source |
| 123 | + resultMatrix:factor |
| 124 | + pivotIndices:pivot_indices |
| 125 | + status:nil]; |
| 126 | + [solve encodeToCommandBuffer:command_buffer |
| 127 | + sourceMatrix:factor |
| 128 | + rightHandSideMatrix:right_hand_side |
| 129 | + pivotIndices:pivot_indices |
| 130 | + solutionMatrix:solution]; |
| 131 | + } |
| 132 | + [command_buffer addCompletedHandler:^(id<MTLCommandBuffer>) { |
| 133 | + (void)retained_arrays; |
| 134 | + [resources release]; |
| 135 | + }]; |
| 136 | + |
| 137 | + encoder.register_output_array(output); |
| 138 | + // Register the MPS result with MLX's command-encoder dependency tracking. |
| 139 | + encoder.set_input_array(output, 0); |
| 140 | + encoder.end_encoding(); |
| 141 | +} |
| 142 | + |
| 143 | +} // namespace mlx::core |
0 commit comments