|
| 1 | +/* |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the BSD-style license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +#include "mlx_mutable_state.h" |
| 10 | + |
| 11 | +#include "MLXExecutor.h" |
| 12 | +#include "MLXLoader.h" |
| 13 | + |
| 14 | +#include <executorch/runtime/platform/log.h> |
| 15 | + |
| 16 | +#include <mutex> |
| 17 | +#include <unordered_map> |
| 18 | + |
| 19 | +namespace executorch { |
| 20 | +namespace backends { |
| 21 | +namespace mlx { |
| 22 | + |
| 23 | +using ::executorch::runtime::Error; |
| 24 | +using ::executorch::runtime::Result; |
| 25 | + |
| 26 | +namespace { |
| 27 | + |
| 28 | +struct HandleInfo { |
| 29 | + const MLXProgram* program{nullptr}; |
| 30 | + MutableBufferData* default_buffers{nullptr}; |
| 31 | +}; |
| 32 | + |
| 33 | +struct Context { |
| 34 | + // Delegate handles associated with this loaded program (one per loaded |
| 35 | + // method). Keyed by opaque MLXHandle pointer. |
| 36 | + std::unordered_map<const void*, HandleInfo> handles; |
| 37 | + // Per-session mutable buffers: token -> (handle -> buffers). Allocated lazily |
| 38 | + // on first execute for a given (session, handle). |
| 39 | + std::unordered_map<int, std::unordered_map<const void*, MutableBufferData>> |
| 40 | + sessions; |
| 41 | + int next_token{0}; |
| 42 | +}; |
| 43 | + |
| 44 | +// Process-global registry. MLX serializes execution via its own global mutex and |
| 45 | +// the engine serializes per session, but the registry itself is guarded here so |
| 46 | +// context/session lifecycle calls from other threads are safe. |
| 47 | +std::mutex& registry_mutex() { |
| 48 | + static std::mutex m; |
| 49 | + return m; |
| 50 | +} |
| 51 | + |
| 52 | +std::unordered_map<MutableStateContext, Context>& contexts() { |
| 53 | + static std::unordered_map<MutableStateContext, Context> c; |
| 54 | + return c; |
| 55 | +} |
| 56 | + |
| 57 | +std::unordered_map<const void*, MutableStateContext>& handle_ctx() { |
| 58 | + static std::unordered_map<const void*, MutableStateContext> m; |
| 59 | + return m; |
| 60 | +} |
| 61 | + |
| 62 | +MutableStateContext g_next_ctx = 1; // 0 is reserved as invalid. |
| 63 | + |
| 64 | +// Thread-local load scope and active (ctx, session) selection. |
| 65 | +thread_local MutableStateContext tl_loading_ctx = kInvalidMutableContext; |
| 66 | +thread_local MutableStateContext tl_active_ctx = kInvalidMutableContext; |
| 67 | +thread_local int tl_active_token = kNoMutableSession; |
| 68 | + |
| 69 | +} // namespace |
| 70 | + |
| 71 | +namespace detail { |
| 72 | + |
| 73 | +MutableStateContext mutable_state_create_context() { |
| 74 | + std::lock_guard<std::mutex> g(registry_mutex()); |
| 75 | + MutableStateContext ctx = g_next_ctx++; |
| 76 | + if (ctx == kInvalidMutableContext) { |
| 77 | + ctx = g_next_ctx++; |
| 78 | + } |
| 79 | + contexts()[ctx]; |
| 80 | + return ctx; |
| 81 | +} |
| 82 | + |
| 83 | +void mutable_state_destroy_context(MutableStateContext ctx) { |
| 84 | + std::lock_guard<std::mutex> g(registry_mutex()); |
| 85 | + auto it = contexts().find(ctx); |
| 86 | + if (it == contexts().end()) { |
| 87 | + return; |
| 88 | + } |
| 89 | + for (const auto& kv : it->second.handles) { |
| 90 | + handle_ctx().erase(kv.first); |
| 91 | + } |
| 92 | + contexts().erase(it); |
| 93 | +} |
| 94 | + |
| 95 | +void mutable_state_begin_load(MutableStateContext ctx) { |
| 96 | + tl_loading_ctx = ctx; |
| 97 | +} |
| 98 | + |
| 99 | +void mutable_state_end_load() { |
| 100 | + tl_loading_ctx = kInvalidMutableContext; |
| 101 | +} |
| 102 | + |
| 103 | +bool mutable_state_available(MutableStateContext ctx) { |
| 104 | + if (ctx == kInvalidMutableContext) { |
| 105 | + return false; |
| 106 | + } |
| 107 | + std::lock_guard<std::mutex> g(registry_mutex()); |
| 108 | + return contexts().count(ctx) != 0; |
| 109 | +} |
| 110 | + |
| 111 | +int64_t mutable_state_bytes_per_session(MutableStateContext ctx) { |
| 112 | + std::lock_guard<std::mutex> g(registry_mutex()); |
| 113 | + auto it = contexts().find(ctx); |
| 114 | + if (it == contexts().end()) { |
| 115 | + return 0; |
| 116 | + } |
| 117 | + int64_t total = 0; |
| 118 | + for (const auto& kv : it->second.handles) { |
| 119 | + const MutableBufferData* bufs = kv.second.default_buffers; |
| 120 | + if (bufs == nullptr) { |
| 121 | + continue; |
| 122 | + } |
| 123 | + for (const auto& t : bufs->tensors) { |
| 124 | + if (t.has_value()) { |
| 125 | + total += static_cast<int64_t>(t->nbytes()); |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + return total; |
| 130 | +} |
| 131 | + |
| 132 | +Error mutable_state_validate_coverage(MutableStateContext ctx) { |
| 133 | + // MLX clones all mutable buffers by tid; there is no FQN coverage to verify. |
| 134 | + (void)ctx; |
| 135 | + return Error::Ok; |
| 136 | +} |
| 137 | + |
| 138 | +Result<int> mutable_state_create_session(MutableStateContext ctx) { |
| 139 | + std::lock_guard<std::mutex> g(registry_mutex()); |
| 140 | + auto it = contexts().find(ctx); |
| 141 | + if (it == contexts().end()) { |
| 142 | + ET_LOG(Error, "mutable_state_create_session: unknown context %d", ctx); |
| 143 | + return Error::InvalidState; |
| 144 | + } |
| 145 | + int token = it->second.next_token++; |
| 146 | + // Per-handle buffers are allocated lazily on first execute. |
| 147 | + it->second.sessions[token]; |
| 148 | + return token; |
| 149 | +} |
| 150 | + |
| 151 | +void mutable_state_destroy_session(MutableStateContext ctx, int token) { |
| 152 | + std::lock_guard<std::mutex> g(registry_mutex()); |
| 153 | + auto it = contexts().find(ctx); |
| 154 | + if (it == contexts().end()) { |
| 155 | + return; |
| 156 | + } |
| 157 | + it->second.sessions.erase(token); |
| 158 | +} |
| 159 | + |
| 160 | +void mutable_state_set_active(MutableStateContext ctx, int token) { |
| 161 | + tl_active_ctx = ctx; |
| 162 | + tl_active_token = token; |
| 163 | +} |
| 164 | + |
| 165 | +} // namespace detail |
| 166 | + |
| 167 | +void mutable_state_note_handle( |
| 168 | + const void* handle, |
| 169 | + const MLXProgram* program, |
| 170 | + MutableBufferData* default_buffers) { |
| 171 | + if (tl_loading_ctx == kInvalidMutableContext) { |
| 172 | + return; // No multi-session owner active during this load: single-session. |
| 173 | + } |
| 174 | + std::lock_guard<std::mutex> g(registry_mutex()); |
| 175 | + auto it = contexts().find(tl_loading_ctx); |
| 176 | + if (it == contexts().end()) { |
| 177 | + return; |
| 178 | + } |
| 179 | + it->second.handles[handle] = HandleInfo{program, default_buffers}; |
| 180 | + handle_ctx()[handle] = tl_loading_ctx; |
| 181 | +} |
| 182 | + |
| 183 | +void mutable_state_forget_handle(const void* handle) { |
| 184 | + std::lock_guard<std::mutex> g(registry_mutex()); |
| 185 | + auto hit = handle_ctx().find(handle); |
| 186 | + if (hit == handle_ctx().end()) { |
| 187 | + return; |
| 188 | + } |
| 189 | + auto cit = contexts().find(hit->second); |
| 190 | + if (cit != contexts().end()) { |
| 191 | + cit->second.handles.erase(handle); |
| 192 | + for (auto& session : cit->second.sessions) { |
| 193 | + session.second.erase(handle); |
| 194 | + } |
| 195 | + } |
| 196 | + handle_ctx().erase(hit); |
| 197 | +} |
| 198 | + |
| 199 | +Error mutable_state_rebind_for_execute( |
| 200 | + const void* handle, |
| 201 | + ExecutionState& state) { |
| 202 | + std::lock_guard<std::mutex> g(registry_mutex()); |
| 203 | + auto hit = handle_ctx().find(handle); |
| 204 | + if (hit == handle_ctx().end()) { |
| 205 | + // Handle was not loaded under a multi-session owner: keep default buffers. |
| 206 | + return Error::Ok; |
| 207 | + } |
| 208 | + auto cit = contexts().find(hit->second); |
| 209 | + if (cit == contexts().end()) { |
| 210 | + return Error::Ok; |
| 211 | + } |
| 212 | + Context& ctx = cit->second; |
| 213 | + HandleInfo& info = ctx.handles[handle]; |
| 214 | + |
| 215 | + const bool active_for_this_ctx = |
| 216 | + tl_active_token != kNoMutableSession && tl_active_ctx == hit->second; |
| 217 | + |
| 218 | + if (!active_for_this_ctx) { |
| 219 | + // No session selected. Refuse if sessions exist (running against the default |
| 220 | + // buffers here would not isolate state from created sessions). |
| 221 | + if (!ctx.sessions.empty()) { |
| 222 | + ET_LOG( |
| 223 | + Error, |
| 224 | + "mutable_state_rebind_for_execute: no active session selected but " |
| 225 | + "sessions exist for this program"); |
| 226 | + return Error::InvalidState; |
| 227 | + } |
| 228 | + state.mutable_buffers = info.default_buffers; |
| 229 | + return Error::Ok; |
| 230 | + } |
| 231 | + |
| 232 | + auto sit = ctx.sessions.find(tl_active_token); |
| 233 | + if (sit == ctx.sessions.end()) { |
| 234 | + ET_LOG( |
| 235 | + Error, |
| 236 | + "mutable_state_rebind_for_execute: unknown session token %d", |
| 237 | + tl_active_token); |
| 238 | + return Error::InvalidState; |
| 239 | + } |
| 240 | + |
| 241 | + auto& per_handle = sit->second; |
| 242 | + auto bit = per_handle.find(handle); |
| 243 | + if (bit == per_handle.end()) { |
| 244 | + // First execute for this (session, handle): allocate fresh zeroed buffers. |
| 245 | + // Constants/weights stay shared (ExecutionState::constants is untouched); |
| 246 | + // only the mutable buffers are per-session. |
| 247 | + MutableBufferData buffers; |
| 248 | + try { |
| 249 | + load_mutable_buffers(*info.program, buffers); |
| 250 | + } catch (const std::exception& e) { |
| 251 | + ET_LOG( |
| 252 | + Error, |
| 253 | + "mutable_state_rebind_for_execute: failed to allocate session " |
| 254 | + "buffers: %s", |
| 255 | + e.what()); |
| 256 | + return Error::MemoryAllocationFailed; |
| 257 | + } |
| 258 | + bit = per_handle.emplace(handle, std::move(buffers)).first; |
| 259 | + } |
| 260 | + // unordered_map keeps element pointers stable across rehash, so this remains |
| 261 | + // valid for the duration of the execute. |
| 262 | + state.mutable_buffers = &bit->second; |
| 263 | + return Error::Ok; |
| 264 | +} |
| 265 | + |
| 266 | +} // namespace mlx |
| 267 | +} // namespace backends |
| 268 | +} // namespace executorch |
0 commit comments