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.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 MTL::ComputeCommandEncoder* operator->() {
62 return enc_;
63 }
64
65 void set_input_array(const array& a, int idx, int64_t offset = 0);
66 void set_output_array(array& a, int idx, int64_t offset = 0);
67 void dispatchThreadgroups(MTL::Size grid_dims, MTL::Size group_dims);
68 void dispatchThreads(MTL::Size grid_dims, MTL::Size group_dims);
69
74
75 // Inputs to all kernels in the encoder including temporaries
76 std::unordered_set<const void*>& inputs() {
77 return all_inputs_;
78 };
79
80 // Outputs of all kernels in the encoder including temporaries
81 std::unordered_set<const void*> outputs() {
82 return all_outputs_;
83 };
84
85 private:
86 MTL::ComputeCommandEncoder* enc_;
87 bool concurrent_{false};
88 std::unordered_set<MTL::Resource*> outputs_;
89 std::unordered_set<MTL::Resource*> concurrent_outputs_;
90 std::unordered_set<const void*> all_inputs_;
91 std::unordered_set<const void*> all_outputs_;
92};
93
94struct Fence {
95 Fence(MTL::Fence* fence) : fence(fence) {}
97 fence->release();
98 }
99 MTL::Fence* fence;
100};
101
103 DeviceStream(MTL::CommandQueue* queue) : queue(queue) {};
105 queue->release();
106 if (buffer != nullptr) {
107 buffer->release();
108 }
109 };
110 MTL::CommandQueue* queue;
111 // A map of prior command encoder outputs to their corresponding fence
112 std::unordered_map<const void*, std::shared_ptr<Fence>> outputs;
113 // Used to allow thread-safe access to the outputs map
114 std::mutex fence_mtx;
115
116 // The buffer and buffer op count are updated
117 // between command buffers
118 MTL::CommandBuffer* buffer{nullptr};
120
121 // The command encoder, fence, and temporaries are updated between command
122 // encoders
123 std::unique_ptr<CommandEncoder> encoder{nullptr};
124 std::shared_ptr<Fence> fence;
125 std::vector<array> temporaries;
126};
127
128class Device {
129 public:
131 Device(const Device&) = delete;
132 Device& operator=(const Device&) = delete;
134
135 MTL::Device* mtl_device() {
136 return device_;
137 };
138
139 void new_queue(int index);
140 MTL::CommandBuffer* get_command_buffer(int index);
143 void commit_command_buffer(int index);
145 void end_encoding(int index);
146
148 const std::string& lib_name,
149 const std::string& lib_path);
150
151 // Note, this should remain in the header so that it is not dynamically
152 // linked
153 void register_library(const std::string& lib_name) {
154 if (auto it = library_map_.find(lib_name); it == library_map_.end()) {
155 register_library(lib_name, get_colocated_mtllib_path(lib_name));
156 }
157 }
158
159 MTL::Library* get_library(
160 const std::string& name,
161 const std::function<std::string(void)>& builder);
162
163 MTL::ComputePipelineState* get_kernel(
164 const std::string& base_name,
165 MTL::Library* mtl_lib,
166 const std::string& hash_name = "",
167 const MTLFCList& func_consts = {},
168 const std::vector<MTL::Function*>& linked_functions = {});
169
170 MTL::ComputePipelineState* get_kernel(
171 const std::string& base_name,
172 const std::string& lib_name = "mlx",
173 const std::string& hash_name = "",
174 const MTLFCList& func_consts = {},
175 const std::vector<MTL::Function*>& linked_functions = {});
176
177 MTL::ArgumentEncoder* argument_encoder(
178 const std::vector<MTL::ArgumentDescriptor*>& arg_descs) const;
179
180 // Record temporary arrays for the given stream index
181 void add_temporary(array arr, int index);
182 void add_temporaries(std::vector<array> arrays, int index);
183
184 void set_residency_set(const MTL::ResidencySet* residency_set);
185
186 private:
187 DeviceStream& get_stream_(int index) {
188 return stream_map_.find(index)->second;
189 }
190 MTL::Library* get_library_cache_(const std::string& name);
191
192 MTL::Library* get_library_(const std::string& name);
193 MTL::Library* build_library_(const std::string& source_string);
194
195 MTL::Function* get_function_(const std::string& name, MTL::Library* mtl_lib);
196
197 MTL::Function* get_function_(
198 const std::string& name,
199 const std::string& specialized_name,
200 const MTLFCList& func_consts,
201 MTL::Library* mtl_lib);
202
203 MTL::LinkedFunctions* get_linked_functions_(
204 const std::vector<MTL::Function*>& funcs);
205
206 MTL::ComputePipelineState* get_kernel_(
207 const std::string& name,
208 const MTL::Function* mtl_function);
209
210 MTL::ComputePipelineState* get_kernel_(
211 const std::string& name,
212 const MTL::Function* mtl_function,
213 const MTL::LinkedFunctions* linked_functions);
214
215 MTL::ComputePipelineState* get_kernel_(
216 const std::string& base_name,
217 MTL::Library* mtl_lib,
218 const std::string& hash_name,
219 const MTLFCList& func_consts = {},
220 const std::vector<MTL::Function*>& linked_functions = {});
221
222 MTL::Device* device_;
223 std::unordered_map<int32_t, DeviceStream> stream_map_;
224
225 std::shared_mutex kernel_mtx_;
226 std::unordered_map<std::string, MTL::ComputePipelineState*> kernel_map_;
227
228 std::shared_mutex library_mtx_;
229 std::unordered_map<std::string, MTL::Library*> library_map_;
230 const MTL::ResidencySet* residency_set_{nullptr};
231};
232
234
235} // namespace mlx::core::metal
Definition array.h:20
Definition device.h:128
void set_residency_set(const MTL::ResidencySet *residency_set)
int get_command_buffer_ops(int index)
MTL::Device * mtl_device()
Definition device.h:135
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)
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:153
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 dispatchThreads(MTL::Size grid_dims, MTL::Size group_dims)
CommandEncoder(MTL::CommandBuffer *cbuf)
std::unordered_set< const void * > & inputs()
Definition device.h:76
CommandEncoder & operator=(const CommandEncoder &)=delete
ConcurrentContext start_concurrent()
Definition device.h:70
void set_output_array(array &a, int idx, int64_t offset=0)
void dispatchThreadgroups(MTL::Size grid_dims, MTL::Size group_dims)
MTL::ComputeCommandEncoder * operator->()
Definition device.h:61
void set_input_array(const array &a, int idx, int64_t offset=0)
CommandEncoder(const CommandEncoder &)=delete
std::unordered_set< const void * > outputs()
Definition device.h:81
Definition device.h:102
~DeviceStream()
Definition device.h:104
std::unordered_map< const void *, std::shared_ptr< Fence > > outputs
Definition device.h:112
DeviceStream(MTL::CommandQueue *queue)
Definition device.h:103
std::unique_ptr< CommandEncoder > encoder
Definition device.h:123
std::mutex fence_mtx
Definition device.h:114
MTL::CommandQueue * queue
Definition device.h:110
std::shared_ptr< Fence > fence
Definition device.h:124
MTL::CommandBuffer * buffer
Definition device.h:118
int buffer_ops
Definition device.h:119
std::vector< array > temporaries
Definition device.h:125
Definition device.h:94
Fence(MTL::Fence *fence)
Definition device.h:95
~Fence()
Definition device.h:96
MTL::Fence * fence
Definition device.h:99