MLX
 
Loading...
Searching...
No Matches
device.h
Go to the documentation of this file.
1// Copyright © 2023-2024 Apple Inc.
2
3#pragma once
4
5#include <Metal/Metal.hpp>
6#include <dlfcn.h>
7#include <filesystem>
8#include <functional>
9#include <mutex>
10#include <shared_mutex>
11#include <string>
12#include <unordered_map>
13#include <unordered_set>
14
15#include "mlx/array.h"
16#include "mlx/device.h"
17
18namespace fs = std::filesystem;
19
20namespace mlx::core::metal {
21
22// Note, this function must be left inline in a header so that it is not
23// dynamically linked.
24inline std::string get_colocated_mtllib_path(const std::string& lib_name) {
25 Dl_info info;
26 std::string mtllib_path;
27 std::string lib_ext = lib_name + ".metallib";
28
29 int success = dladdr((void*)get_colocated_mtllib_path, &info);
30 if (success) {
31 auto mtllib = fs::path(info.dli_fname).remove_filename() / lib_ext;
32 mtllib_path = mtllib.c_str();
33 }
34
35 return mtllib_path;
36}
37
38using MTLFCList =
39 std::vector<std::tuple<const void*, MTL::DataType, NS::UInteger>>;
40
42 CommandEncoder(MTL::CommandBuffer* cbuf);
45
48 enc.concurrent_ = true;
49 }
51 enc.concurrent_ = false;
52 enc.prev_outputs_.insert(
53 enc.concurrent_outputs_.begin(), enc.concurrent_outputs_.end());
54 enc.concurrent_outputs_.clear();
55 }
56
57 private:
58 CommandEncoder& enc;
59 };
60
61 void set_input_array(const array& a, int idx, int64_t offset = 0);
62 void set_output_array(array& a, int idx, int64_t offset = 0);
64 void dispatch_threadgroups(MTL::Size grid_dims, MTL::Size group_dims);
65 void dispatch_threads(MTL::Size grid_dims, MTL::Size group_dims);
67 void set_buffer(const MTL::Buffer* buf, int idx, int64_t offset = 0);
68
69 void set_compute_pipeline_state(MTL::ComputePipelineState* kernel) {
70 enc_->setComputePipelineState(kernel);
71 }
72
73 void wait_for_fence(MTL::Fence* fence) {
74 enc_->waitForFence(fence);
75 }
76
77 void update_fence(MTL::Fence* fence) {
78 enc_->updateFence(fence);
79 }
80
81 template <typename T>
82 void set_vector_bytes(const std::vector<T>& vec, size_t nelems, int idx) {
83 enc_->setBytes(vec.data(), nelems * sizeof(T), idx);
84 }
85 template <typename T>
86 void set_vector_bytes(const std::vector<T>& vec, int idx) {
87 return set_vector_bytes(vec, vec.size(), idx);
88 }
89
90 template <typename T>
91 void set_bytes(const T* v, int n, int idx) {
92 return enc_->setBytes(v, n * sizeof(T), idx);
93 }
94
95 template <typename T>
96 void set_bytes(const T& v, int idx) {
97 return enc_->setBytes(&v, sizeof(T), idx);
98 }
99
104
105 // Inputs to all kernels in the encoder including temporaries
106 std::unordered_set<const void*>& inputs() {
107 return all_inputs_;
108 };
109
110 // Outputs of all kernels in the encoder including temporaries
111 std::unordered_set<const void*> outputs() {
112 return all_outputs_;
113 };
114
115 void barrier();
116
117 private:
118 MTL::ComputeCommandEncoder* enc_;
119 bool needs_barrier_{false};
120 bool concurrent_{false};
121 std::unordered_set<MTL::Resource*> prev_outputs_;
122 std::unordered_set<MTL::Resource*> next_outputs_;
123 std::unordered_set<MTL::Resource*> concurrent_outputs_;
124 std::unordered_set<const void*> all_inputs_;
125 std::unordered_set<const void*> all_outputs_;
126};
127
128struct Fence {
129 Fence(MTL::Fence* fence) : fence(fence) {}
131 fence->release();
132 }
133 MTL::Fence* fence;
134};
135
137 DeviceStream(MTL::CommandQueue* queue) : queue(queue) {};
139 queue->release();
140 if (buffer != nullptr) {
141 buffer->release();
142 }
143 };
144 MTL::CommandQueue* queue;
145 // A map of prior command encoder outputs to their corresponding fence
146 std::unordered_map<const void*, std::shared_ptr<Fence>> outputs;
147 // Used to allow thread-safe access to the outputs map
148 std::mutex fence_mtx;
149
150 // The buffer and buffer op count are updated
151 // between command buffers
152 MTL::CommandBuffer* buffer{nullptr};
154
155 // The command encoder, fence, and temporaries are updated between command
156 // encoders
157 std::unique_ptr<CommandEncoder> encoder{nullptr};
158 std::shared_ptr<Fence> fence;
159 std::vector<array> temporaries;
160};
161
162class Device {
163 public:
165 Device(const Device&) = delete;
166 Device& operator=(const Device&) = delete;
168
169 MTL::Device* mtl_device() {
170 return device_;
171 };
172
173 const std::string& get_architecture() {
174 return arch_;
175 }
176
177 void new_queue(int index);
178 MTL::CommandBuffer* get_command_buffer(int index);
181 void commit_command_buffer(int index);
183 void end_encoding(int index);
184
186 const std::string& lib_name,
187 const std::string& lib_path);
188
189 // Note, this should remain in the header so that it is not dynamically
190 // linked
191 void register_library(const std::string& lib_name) {
192 if (auto it = library_map_.find(lib_name); it == library_map_.end()) {
193 register_library(lib_name, get_colocated_mtllib_path(lib_name));
194 }
195 }
196
197 MTL::Library* get_library(
198 const std::string& name,
199 const std::function<std::string(void)>& builder);
200
201 MTL::ComputePipelineState* get_kernel(
202 const std::string& base_name,
203 MTL::Library* mtl_lib,
204 const std::string& hash_name = "",
205 const MTLFCList& func_consts = {},
206 const std::vector<MTL::Function*>& linked_functions = {});
207
208 MTL::ComputePipelineState* get_kernel(
209 const std::string& base_name,
210 const std::string& lib_name = "mlx",
211 const std::string& hash_name = "",
212 const MTLFCList& func_consts = {},
213 const std::vector<MTL::Function*>& linked_functions = {});
214
215 MTL::ArgumentEncoder* argument_encoder(
216 const std::vector<MTL::ArgumentDescriptor*>& arg_descs) const;
217
218 // Record temporary arrays for the given stream index
219 void add_temporary(array arr, int index);
220 void add_temporaries(std::vector<array> arrays, int index);
221
222 void set_residency_set(const MTL::ResidencySet* residency_set);
223
224 private:
225 DeviceStream& get_stream_(int index) {
226 return stream_map_.find(index)->second;
227 }
228 MTL::Library* get_library_cache_(const std::string& name);
229
230 MTL::Library* get_library_(const std::string& name);
231 MTL::Library* build_library_(const std::string& source_string);
232
233 MTL::Function* get_function_(const std::string& name, MTL::Library* mtl_lib);
234
235 MTL::Function* get_function_(
236 const std::string& name,
237 const std::string& specialized_name,
238 const MTLFCList& func_consts,
239 MTL::Library* mtl_lib);
240
241 MTL::LinkedFunctions* get_linked_functions_(
242 const std::vector<MTL::Function*>& funcs);
243
244 MTL::ComputePipelineState* get_kernel_(
245 const std::string& name,
246 const MTL::Function* mtl_function);
247
248 MTL::ComputePipelineState* get_kernel_(
249 const std::string& name,
250 const MTL::Function* mtl_function,
251 const MTL::LinkedFunctions* linked_functions);
252
253 MTL::ComputePipelineState* get_kernel_(
254 const std::string& base_name,
255 MTL::Library* mtl_lib,
256 const std::string& hash_name,
257 const MTLFCList& func_consts = {},
258 const std::vector<MTL::Function*>& linked_functions = {});
259
260 MTL::Device* device_;
261 std::unordered_map<int32_t, DeviceStream> stream_map_;
262
263 std::shared_mutex kernel_mtx_;
264 std::unordered_map<std::string, MTL::ComputePipelineState*> kernel_map_;
265
266 std::shared_mutex library_mtx_;
267 std::unordered_map<std::string, MTL::Library*> library_map_;
268 const MTL::ResidencySet* residency_set_{nullptr};
269 std::string arch_;
270};
271
273
274} // namespace mlx::core::metal
Definition array.h:24
Definition device.h:162
void set_residency_set(const MTL::ResidencySet *residency_set)
int get_command_buffer_ops(int index)
MTL::Device * mtl_device()
Definition device.h:169
void register_library(const std::string &lib_name, const std::string &lib_path)
MTL::CommandBuffer * get_command_buffer(int index)
void end_encoding(int index)
const std::string & get_architecture()
Definition device.h:173
MTL::ComputePipelineState * get_kernel(const std::string &base_name, MTL::Library *mtl_lib, const std::string &hash_name="", const MTLFCList &func_consts={}, const std::vector< MTL::Function * > &linked_functions={})
MTL::ArgumentEncoder * argument_encoder(const std::vector< MTL::ArgumentDescriptor * > &arg_descs) const
void add_temporaries(std::vector< array > arrays, int index)
MTL::Library * get_library(const std::string &name, const std::function< std::string(void)> &builder)
void increment_command_buffer_ops(int index)
void new_queue(int index)
void commit_command_buffer(int index)
void register_library(const std::string &lib_name)
Definition device.h:191
Device(const Device &)=delete
void add_temporary(array arr, int index)
Device & operator=(const Device &)=delete
MTL::ComputePipelineState * get_kernel(const std::string &base_name, const std::string &lib_name="mlx", const std::string &hash_name="", const MTLFCList &func_consts={}, const std::vector< MTL::Function * > &linked_functions={})
CommandEncoder & get_command_encoder(int index)
Definition allocator.h:13
std::string get_colocated_mtllib_path(const std::string &lib_name)
Definition device.h:24
std::vector< std::tuple< const void *, MTL::DataType, NS::UInteger > > MTLFCList
Definition device.h:38
Device & device(mlx::core::Device)
ConcurrentContext(CommandEncoder &enc)
Definition device.h:47
CommandEncoder(MTL::CommandBuffer *cbuf)
Definition device.h:7
ConcurrentContext(CommandEncoder &enc)
Definition device.h:47
Definition device.h:41
void dispatch_threads(MTL::Size grid_dims, MTL::Size group_dims)
CommandEncoder(MTL::CommandBuffer *cbuf)
std::unordered_set< const void * > & inputs()
Definition device.h:106
CommandEncoder & operator=(const CommandEncoder &)=delete
ConcurrentContext start_concurrent()
Definition device.h:100
void set_vector_bytes(const std::vector< T > &vec, size_t nelems, int idx)
Definition device.h:82
void set_output_array(array &a, int idx, int64_t offset=0)
void set_compute_pipeline_state(MTL::ComputePipelineState *kernel)
Definition device.h:69
void set_vector_bytes(const std::vector< T > &vec, int idx)
Definition device.h:86
void dispatch_threadgroups(MTL::Size grid_dims, MTL::Size group_dims)
void set_bytes(const T *v, int n, int idx)
Definition device.h:91
void set_input_array(const array &a, int idx, int64_t offset=0)
void set_bytes(const T &v, int idx)
Definition device.h:96
CommandEncoder(const CommandEncoder &)=delete
void set_buffer(const MTL::Buffer *buf, int idx, int64_t offset=0)
void update_fence(MTL::Fence *fence)
Definition device.h:77
std::unordered_set< const void * > outputs()
Definition device.h:111
void wait_for_fence(MTL::Fence *fence)
Definition device.h:73
Definition device.h:136
~DeviceStream()
Definition device.h:138
std::unordered_map< const void *, std::shared_ptr< Fence > > outputs
Definition device.h:146
DeviceStream(MTL::CommandQueue *queue)
Definition device.h:137
std::unique_ptr< CommandEncoder > encoder
Definition device.h:157
std::mutex fence_mtx
Definition device.h:148
MTL::CommandQueue * queue
Definition device.h:144
std::shared_ptr< Fence > fence
Definition device.h:158
MTL::CommandBuffer * buffer
Definition device.h:152
int buffer_ops
Definition device.h:153
std::vector< array > temporaries
Definition device.h:159
Fence(MTL::Fence *fence)
Definition device.h:129
~Fence()
Definition device.h:130
MTL::Fence * fence
Definition device.h:133