|
| 1 | +#define NS_PRIVATE_IMPLEMENTATION |
| 2 | +#define MTL_PRIVATE_IMPLEMENTATION |
| 3 | + |
| 4 | +// Include metal-cpp headers from system |
| 5 | +#include <Metal/Metal.hpp> |
| 6 | +#include <Foundation/NSSharedPtr.hpp> |
| 7 | + |
| 8 | +#include <torch/torch.h> |
| 9 | + |
| 10 | +// C interface from metallib_loader.mm |
| 11 | +extern "C" void* loadEmbeddedMetalLibrary(void* device, const char** errorMsg); |
| 12 | +extern "C" void* getMPSDevice(); |
| 13 | +extern "C" void* getMPSCommandQueue(); |
| 14 | + |
| 15 | +namespace { |
| 16 | + |
| 17 | +MTL::Buffer* getMTLBuffer(const torch::Tensor& tensor) { |
| 18 | + return reinterpret_cast<MTL::Buffer*>(const_cast<void*>(tensor.storage().data())); |
| 19 | +} |
| 20 | + |
| 21 | +NS::String* makeNSString(const std::string& value) { |
| 22 | + return NS::String::string(value.c_str(), NS::StringEncoding::UTF8StringEncoding); |
| 23 | +} |
| 24 | + |
| 25 | +MTL::Library* loadLibrary(MTL::Device* device) { |
| 26 | + const char* errorMsg = nullptr; |
| 27 | + void* library = loadEmbeddedMetalLibrary(reinterpret_cast<void*>(device), &errorMsg); |
| 28 | + |
| 29 | + TORCH_CHECK(library != nullptr, "Failed to create Metal library from embedded data: ", |
| 30 | + errorMsg ? errorMsg : "Unknown error"); |
| 31 | + |
| 32 | + if (errorMsg) { |
| 33 | + free(const_cast<char*>(errorMsg)); |
| 34 | + } |
| 35 | + |
| 36 | + return reinterpret_cast<MTL::Library*>(library); |
| 37 | +} |
| 38 | + |
| 39 | +} // namespace |
| 40 | + |
| 41 | +void dispatchReluKernel(const torch::Tensor& input, torch::Tensor& output) { |
| 42 | + // Use PyTorch's MPS device and command queue (these are borrowed references, not owned) |
| 43 | + MTL::Device* device = reinterpret_cast<MTL::Device*>(getMPSDevice()); |
| 44 | + TORCH_CHECK(device != nullptr, "Failed to get MPS device"); |
| 45 | + |
| 46 | + MTL::CommandQueue* commandQueue = reinterpret_cast<MTL::CommandQueue*>(getMPSCommandQueue()); |
| 47 | + TORCH_CHECK(commandQueue != nullptr, "Failed to get MPS command queue"); |
| 48 | + |
| 49 | + MTL::Library* libraryPtr = reinterpret_cast<MTL::Library*>(loadLibrary(device)); |
| 50 | + NS::SharedPtr<MTL::Library> library = NS::TransferPtr(libraryPtr); |
| 51 | + |
| 52 | + const std::string kernelName = |
| 53 | + std::string("relu_forward_kernel_") + (input.scalar_type() == torch::kFloat ? "float" : "half"); |
| 54 | + NS::SharedPtr<NS::String> kernelNameString = NS::TransferPtr(makeNSString(kernelName)); |
| 55 | + |
| 56 | + NS::SharedPtr<MTL::Function> computeFunction = |
| 57 | + NS::TransferPtr(library->newFunction(kernelNameString.get())); |
| 58 | + TORCH_CHECK(computeFunction.get() != nullptr, "Failed to create Metal function for ", kernelName); |
| 59 | + |
| 60 | + NS::Error* pipelineError = nullptr; |
| 61 | + NS::SharedPtr<MTL::ComputePipelineState> pipelineState = |
| 62 | + NS::TransferPtr(device->newComputePipelineState(computeFunction.get(), &pipelineError)); |
| 63 | + TORCH_CHECK(pipelineState.get() != nullptr, |
| 64 | + "Failed to create compute pipeline state: ", |
| 65 | + pipelineError ? pipelineError->localizedDescription()->utf8String() : "Unknown error"); |
| 66 | + |
| 67 | + // Don't use SharedPtr for command buffer/encoder - they're managed by PyTorch's command queue |
| 68 | + MTL::CommandBuffer* commandBuffer = commandQueue->commandBuffer(); |
| 69 | + TORCH_CHECK(commandBuffer != nullptr, "Failed to create Metal command buffer"); |
| 70 | + |
| 71 | + MTL::ComputeCommandEncoder* encoder = commandBuffer->computeCommandEncoder(); |
| 72 | + TORCH_CHECK(encoder != nullptr, "Failed to create compute command encoder"); |
| 73 | + |
| 74 | + encoder->setComputePipelineState(pipelineState.get()); |
| 75 | + |
| 76 | + auto* inputBuffer = getMTLBuffer(input); |
| 77 | + auto* outputBuffer = getMTLBuffer(output); |
| 78 | + TORCH_CHECK(inputBuffer != nullptr, "Input buffer is null"); |
| 79 | + TORCH_CHECK(outputBuffer != nullptr, "Output buffer is null"); |
| 80 | + |
| 81 | + encoder->setBuffer(inputBuffer, input.storage_offset() * input.element_size(), 0); |
| 82 | + encoder->setBuffer(outputBuffer, output.storage_offset() * output.element_size(), 1); |
| 83 | + |
| 84 | + const NS::UInteger totalThreads = input.numel(); |
| 85 | + NS::UInteger threadGroupSize = pipelineState->maxTotalThreadsPerThreadgroup(); |
| 86 | + if (threadGroupSize > totalThreads) { |
| 87 | + threadGroupSize = totalThreads; |
| 88 | + } |
| 89 | + |
| 90 | + const MTL::Size gridSize = MTL::Size::Make(totalThreads, 1, 1); |
| 91 | + const MTL::Size threadsPerThreadgroup = MTL::Size::Make(threadGroupSize, 1, 1); |
| 92 | + |
| 93 | + encoder->dispatchThreads(gridSize, threadsPerThreadgroup); |
| 94 | + encoder->endEncoding(); |
| 95 | + |
| 96 | + commandBuffer->commit(); |
| 97 | +} |
| 98 | + |
| 99 | +void relu(torch::Tensor& out, const torch::Tensor& input) { |
| 100 | + TORCH_CHECK(input.device().is_mps(), "input must be a MPS tensor"); |
| 101 | + TORCH_CHECK(input.is_contiguous(), "input must be contiguous"); |
| 102 | + TORCH_CHECK(input.scalar_type() == torch::kFloat || input.scalar_type() == torch::kHalf, |
| 103 | + "Unsupported data type: ", input.scalar_type()); |
| 104 | + |
| 105 | + TORCH_CHECK(input.sizes() == out.sizes(), |
| 106 | + "Tensors must have the same shape. Got input shape: ", |
| 107 | + input.sizes(), " and output shape: ", out.sizes()); |
| 108 | + |
| 109 | + TORCH_CHECK(input.scalar_type() == out.scalar_type(), |
| 110 | + "Tensors must have the same data type. Got input dtype: ", |
| 111 | + input.scalar_type(), " and output dtype: ", out.scalar_type()); |
| 112 | + |
| 113 | + TORCH_CHECK(input.device() == out.device(), |
| 114 | + "Tensors must be on the same device. Got input device: ", |
| 115 | + input.device(), " and output device: ", out.device()); |
| 116 | + |
| 117 | + dispatchReluKernel(input, out); |
| 118 | +} |
0 commit comments