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);
63 void dispatch_threadgroups(MTL::Size grid_dims, MTL::Size group_dims);
64 void dispatch_threads(MTL::Size grid_dims, MTL::Size group_dims);
66
67 void set_compute_pipeline_state(MTL::ComputePipelineState* kernel) {
68 enc_->setComputePipelineState(kernel);
69 }
70
71 void wait_for_fence(MTL::Fence* fence) {
72 enc_->waitForFence(fence);
73 }
74
75 void update_fence(MTL::Fence* fence) {
76 enc_->updateFence(fence);
77 }
78
79 template <typename T>
80 void set_vector_bytes(const std::vector<T>& vec, size_t nelems, int idx) {
81 enc_->setBytes(vec.data(), nelems * sizeof(T), idx);
82 }
83 template <typename T>
84 void set_vector_bytes(const std::vector<T>& vec, int idx) {
85 return set_vector_bytes(vec, vec.size(), idx);
86 }
87
88 template <typename T>
89 void set_bytes(const T* v, int n, int idx) {
90 return enc_->setBytes(v, n * sizeof(T), idx);
91 }
92
93 template <typename T>
94 void set_bytes(const T& v, int idx) {
95 return enc_->setBytes(&v, sizeof(T), idx);
96 }
97
102
103 // Inputs to all kernels in the encoder including temporaries
104 std::unordered_set<const void*>& inputs() {
105 return all_inputs_;
106 };
107
108 // Outputs of all kernels in the encoder including temporaries
109 std::unordered_set<const void*> outputs() {
110 return all_outputs_;
111 };
112
113 private:
114 MTL::ComputeCommandEncoder* enc_;
115 bool needs_barrier_{false};
116 bool concurrent_{false};
117 std::unordered_set<MTL::Resource*> prev_outputs_;
118 std::unordered_set<MTL::Resource*> next_outputs_;
119 std::unordered_set<MTL::Resource*> concurrent_outputs_;
120 std::unordered_set<const void*> all_inputs_;
121 std::unordered_set<const void*> all_outputs_;
122};
123
124struct Fence {
125 Fence(MTL::Fence* fence) : fence(fence) {}
127 fence->release();
128 }
129 MTL::Fence* fence;
130};
131
133 DeviceStream(MTL::CommandQueue* queue) : queue(queue) {};
135 queue->release();
136 if (buffer != nullptr) {
137 buffer->release();
138 }
139 };
140 MTL::CommandQueue* queue;
141 // A map of prior command encoder outputs to their corresponding fence
142 std::unordered_map<const void*, std::shared_ptr<Fence>> outputs;
143 // Used to allow thread-safe access to the outputs map
144 std::mutex fence_mtx;
145
146 // The buffer and buffer op count are updated
147 // between command buffers
148 MTL::CommandBuffer* buffer{nullptr};
150
151 // The command encoder, fence, and temporaries are updated between command
152 // encoders
153 std::unique_ptr<CommandEncoder> encoder{nullptr};
154 std::shared_ptr<Fence> fence;
155 std::vector<array> temporaries;
156};
157
158class Device {
159 public:
161 Device(const Device&) = delete;
162 Device& operator=(const Device&) = delete;
164
165 MTL::Device* mtl_device() {
166 return device_;
167 };
168
169 const std::string& get_architecture() {
170 return arch_;
171 }
172
173 void new_queue(int index);
174 MTL::CommandBuffer* get_command_buffer(int index);
177 void commit_command_buffer(int index);
179 void end_encoding(int index);
180
182 const std::string& lib_name,
183 const std::string& lib_path);
184
185 // Note, this should remain in the header so that it is not dynamically
186 // linked
187 void register_library(const std::string& lib_name) {
188 if (auto it = library_map_.find(lib_name); it == library_map_.end()) {
189 register_library(lib_name, get_colocated_mtllib_path(lib_name));
190 }
191 }
192
193 MTL::Library* get_library(
194 const std::string& name,
195 const std::function<std::string(void)>& builder);
196
197 MTL::ComputePipelineState* get_kernel(
198 const std::string& base_name,
199 MTL::Library* mtl_lib,
200 const std::string& hash_name = "",
201 const MTLFCList& func_consts = {},
202 const std::vector<MTL::Function*>& linked_functions = {});
203
204 MTL::ComputePipelineState* get_kernel(
205 const std::string& base_name,
206 const std::string& lib_name = "mlx",
207 const std::string& hash_name = "",
208 const MTLFCList& func_consts = {},
209 const std::vector<MTL::Function*>& linked_functions = {});
210
211 MTL::ArgumentEncoder* argument_encoder(
212 const std::vector<MTL::ArgumentDescriptor*>& arg_descs) const;
213
214 // Record temporary arrays for the given stream index
215 void add_temporary(array arr, int index);
216 void add_temporaries(std::vector<array> arrays, int index);
217
218 void set_residency_set(const MTL::ResidencySet* residency_set);
219
220 private:
221 DeviceStream& get_stream_(int index) {
222 return stream_map_.find(index)->second;
223 }
224 MTL::Library* get_library_cache_(const std::string& name);
225
226 MTL::Library* get_library_(const std::string& name);
227 MTL::Library* build_library_(const std::string& source_string);
228
229 MTL::Function* get_function_(const std::string& name, MTL::Library* mtl_lib);
230
231 MTL::Function* get_function_(
232 const std::string& name,
233 const std::string& specialized_name,
234 const MTLFCList& func_consts,
235 MTL::Library* mtl_lib);
236
237 MTL::LinkedFunctions* get_linked_functions_(
238 const std::vector<MTL::Function*>& funcs);
239
240 MTL::ComputePipelineState* get_kernel_(
241 const std::string& name,
242 const MTL::Function* mtl_function);
243
244 MTL::ComputePipelineState* get_kernel_(
245 const std::string& name,
246 const MTL::Function* mtl_function,
247 const MTL::LinkedFunctions* linked_functions);
248
249 MTL::ComputePipelineState* get_kernel_(
250 const std::string& base_name,
251 MTL::Library* mtl_lib,
252 const std::string& hash_name,
253 const MTLFCList& func_consts = {},
254 const std::vector<MTL::Function*>& linked_functions = {});
255
256 MTL::Device* device_;
257 std::unordered_map<int32_t, DeviceStream> stream_map_;
258
259 std::shared_mutex kernel_mtx_;
260 std::unordered_map<std::string, MTL::ComputePipelineState*> kernel_map_;
261
262 std::shared_mutex library_mtx_;
263 std::unordered_map<std::string, MTL::Library*> library_map_;
264 const MTL::ResidencySet* residency_set_{nullptr};
265 std::string arch_;
266};
267
269
270} // namespace mlx::core::metal
Definition array.h:23
Definition device.h:158
void set_residency_set(const MTL::ResidencySet *residency_set)
int get_command_buffer_ops(int index)
MTL::Device * mtl_device()
Definition device.h:165
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:169
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:187
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)
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:104
CommandEncoder & operator=(const CommandEncoder &)=delete
ConcurrentContext start_concurrent()
Definition device.h:98
void set_vector_bytes(const std::vector< T > &vec, size_t nelems, int idx)
Definition device.h:80
void set_output_array(array &a, int idx, int64_t offset=0)
void set_compute_pipeline_state(MTL::ComputePipelineState *kernel)
Definition device.h:67
void set_vector_bytes(const std::vector< T > &vec, int idx)
Definition device.h:84
void dispatch_threadgroups(MTL::Size grid_dims, MTL::Size group_dims)
void set_bytes(const T *v, int n, int idx)
Definition device.h:89
void set_input_array(const array &a, int idx, int64_t offset=0)
void set_bytes(const T &v, int idx)
Definition device.h:94
CommandEncoder(const CommandEncoder &)=delete
void update_fence(MTL::Fence *fence)
Definition device.h:75
std::unordered_set< const void * > outputs()
Definition device.h:109
void wait_for_fence(MTL::Fence *fence)
Definition device.h:71
Definition device.h:132
~DeviceStream()
Definition device.h:134
std::unordered_map< const void *, std::shared_ptr< Fence > > outputs
Definition device.h:142
DeviceStream(MTL::CommandQueue *queue)
Definition device.h:133
std::unique_ptr< CommandEncoder > encoder
Definition device.h:153
std::mutex fence_mtx
Definition device.h:144
MTL::CommandQueue * queue
Definition device.h:140
std::shared_ptr< Fence > fence
Definition device.h:154
MTL::CommandBuffer * buffer
Definition device.h:148
int buffer_ops
Definition device.h:149
std::vector< array > temporaries
Definition device.h:155
Definition device.h:124
Fence(MTL::Fence *fence)
Definition device.h:125
~Fence()
Definition device.h:126
MTL::Fence * fence
Definition device.h:129