diff --git a/Libraries/MLXLLM/LLMModelFactory.swift b/Libraries/MLXLLM/LLMModelFactory.swift index a09cbc5799..a951841435 100644 --- a/Libraries/MLXLLM/LLMModelFactory.swift +++ b/Libraries/MLXLLM/LLMModelFactory.swift @@ -57,6 +57,7 @@ public enum LLMTypeRegistry { "mimo": create(MiMoConfiguration.self, MiMoModel.init), "mimo_v2_flash": create(MiMoV2FlashConfiguration.self, MiMoV2FlashModel.init), "minimax": create(MiniMaxConfiguration.self, MiniMaxModel.init), + "minimax_m2": create(MiniMaxM2Configuration.self, MiniMaxM2Model.init), "glm4": create(GLM4Configuration.self, GLM4Model.init), "glm4_moe": create(GLM4MoEConfiguration.self, GLM4MoEModel.init), "glm4_moe_lite": create(GLM4MoELiteConfiguration.self, GLM4MoELiteModel.init), diff --git a/Libraries/MLXLLM/Models/GPTOSS.swift b/Libraries/MLXLLM/Models/GPTOSS.swift index dd9eb0c9c5..e017808efd 100644 --- a/Libraries/MLXLLM/Models/GPTOSS.swift +++ b/Libraries/MLXLLM/Models/GPTOSS.swift @@ -8,6 +8,7 @@ // port of https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/gpt_oss.py import Foundation +import NativePrefillBridge import MLX import MLXLMCommon import MLXNN @@ -436,9 +437,32 @@ public class GPTOSSModel: Module, LLMModel, KVCacheDimensionProvider { public func prepare(_ input: LMInput, cache: [KVCache], windowSize: Int?) throws -> PrepareResult { - let prefillStepSize = max(windowSize ?? 512, 2048) var y = input.text + if ProcessInfo.processInfo.environment["NATIVE_PREFILL"] == "1" { + let bridge = GenericPrefillBridge.shared + let json = """ + {"model_type":"gpt_oss","hidden_size":\(configuration.hiddenSize),"num_hidden_layers":\(configuration.hiddenLayers),"num_attention_heads":\(configuration.attentionHeads),"num_key_value_heads":\(configuration.kvHeads),"head_dim":\(configuration.headDim),"intermediate_size":\(configuration.intermediateSize),"vocab_size":\(configuration.vocabularySize),"rms_norm_eps":\(String(format:"%.0e",Double(configuration.rmsNormEps))),"rope_theta":\(String(format:"%.0f",Double(configuration.ropeTheta))),"tie_word_embeddings":false,"num_local_experts":\(configuration.localExperts),"num_experts_per_tok":\(configuration.expertsPerToken),"rope_type":"\({ if case .string(let s) = configuration.ropeScaling?["rope_type"] { return s } else { return "" } }())","yarn_factor":\(configuration.ropeScaling?["factor"]?.asFloat() ?? 1.0),"yarn_beta_fast":\(configuration.ropeScaling?["beta_fast"]?.asFloat() ?? 32.0),"yarn_beta_slow":\(configuration.ropeScaling?["beta_slow"]?.asFloat() ?? 1.0),"yarn_original_max_pos":\(configuration.ropeScaling?["original_max_position_embeddings"]?.asInt() ?? 4096)} + """ + if bridge.ensureInitialized(modelType: "gpt_oss", model: model, config: json) { + let allTokens = input.text.tokens + let prefillCount = allTokens.size - 1 + if prefillCount > 0 { + let tokenSlice = allTokens[0 ..< prefillCount].reshaped(-1) + let (ms, ok) = bridge.runAndInjectKV( + tokenArray: tokenSlice, cache: cache, numLayers: configuration.hiddenLayers) + if ok { + print(String(format: "[GenericPrefill] %d tokens in %.1fms (%.0f t/s)", + prefillCount, ms, Double(prefillCount) / (ms / 1000))) + let lastToken = allTokens[prefillCount ..< allTokens.size] + return .tokens(LMInput.Text(tokens: lastToken)) + } + } + } + } + + let prefillStepSize = max(windowSize ?? 512, 2048) + // Match Python mlx-lm: process every prefill token except the LAST one // through chunked prefill so we always hit the eval+clearCache between // chunks, even when the prompt fits in a single chunk. diff --git a/Libraries/MLXLLM/Models/Gemma3Text.swift b/Libraries/MLXLLM/Models/Gemma3Text.swift index cef72fc889..115026abc0 100644 --- a/Libraries/MLXLLM/Models/Gemma3Text.swift +++ b/Libraries/MLXLLM/Models/Gemma3Text.swift @@ -10,6 +10,7 @@ import Foundation import MLX import MLXLMCommon +import NativePrefillBridge import MLXNN public struct Gemma3TextConfiguration: Codable { @@ -434,6 +435,28 @@ public class Gemma3TextModel: Module, LLMModel { return .tokens(.init(tokens: emptyToken)) } + if ProcessInfo.processInfo.environment["NATIVE_PREFILL"] == "1" { + let bridge = GenericPrefillBridge.shared + let json = """ + {"model_type":"gemma3_text","hidden_size":\(config.hiddenSize),"num_hidden_layers":\(config.hiddenLayers),"num_attention_heads":\(config.attentionHeads),"num_key_value_heads":\(config.kvHeads),"head_dim":\(config.headDim),"intermediate_size":\(config.intermediateSize),"vocab_size":\(config.vocabularySize),"rms_norm_eps":\(String(format:"%.0e",Double(config.rmsNormEps))),"rope_theta":\(String(format:"%.0f",Double(config.ropeTheta))),"sliding_window":\(config.slidingWindow),"sliding_pattern":\(config.slidingWindowPattern),"tie_word_embeddings":false} + """ + if bridge.ensureInitialized(modelType: "gemma3_text", model: model, config: json) { + let allTokens = input.text.tokens + let prefillCount = allTokens.size - 1 + if prefillCount > 0 { + let tokenSlice = allTokens[0 ..< prefillCount].reshaped(-1) + let (ms, ok) = bridge.runAndInjectKV( + tokenArray: tokenSlice, cache: cache, numLayers: config.hiddenLayers) + if ok { + print(String(format: "[GenericPrefill] %d tokens in %.1fms (%.0f t/s)", + prefillCount, ms, Double(prefillCount) / (ms / 1000))) + let lastToken = allTokens[prefillCount ..< allTokens.size] + return .tokens(LMInput.Text(tokens: lastToken)) + } + } + } + } + return .tokens(input.text) } } diff --git a/Libraries/MLXLLM/Models/Gemma4.swift b/Libraries/MLXLLM/Models/Gemma4.swift index 8972a9904e..386dd40f1f 100644 --- a/Libraries/MLXLLM/Models/Gemma4.swift +++ b/Libraries/MLXLLM/Models/Gemma4.swift @@ -11,269 +11,154 @@ import Foundation import MLX import MLXLMCommon import MLXNN +// MARK: - Gemma Prefill Bridge (C++ dylib via dlopen) -// MARK: - Native Prefill Bridge (C++ dylib) - -/// Lazy-loaded bridge to native C++ prefill for timing comparison. +/// Lazy-loaded bridge to native C++ prefill. +/// Uses dlopen to load the bridge dylib, avoiding SPM's link-time optimization +/// which miscompiles quantized_matmul. The dylib uses -undefined dynamic_lookup +/// to share the host's MLX allocator (no dual-allocator OOM). +/// /// Activated by setting NATIVE_PREFILL=1 environment variable. -/// TODO: Once validated, replace Swift prefill entirely with native K/V injection. -private final class NativePrefillBridge { - static let shared = NativePrefillBridge() +private final class GemmaPrefillBridge { + static let shared = GemmaPrefillBridge() private var handle: UnsafeMutableRawPointer? - private var initFn: (@convention(c) (UnsafePointer) -> Int32)? - private var runFn: (@convention(c) (UnsafePointer, Int32, UnsafeMutablePointer?, UnsafeMutablePointer?) -> Int32)? - private var cleanupFn: (@convention(c) () -> Void)? private var initialized = false - /// Whether native prefill is enabled via env var - static var isEnabled: Bool { - ProcessInfo.processInfo.environment["NATIVE_PREFILL"] == "1" - } - - /// Load dylib and init model weights. Returns true on success. - func ensureInitialized() -> Bool { - if initialized { return true } - - // Load the dylib - let dylibPath = "/tmp/libprefill_bridge.dylib" - guard let h = dlopen(dylibPath, RTLD_NOW) else { - let err = String(cString: dlerror()) - print("[NativePrefill] Failed to load \(dylibPath): \(err)") - return false - } - handle = h - - // Resolve symbols - guard let initSym = dlsym(h, "prefill_bridge_init"), - let runSym = dlsym(h, "prefill_bridge_run2"), - let cleanSym = dlsym(h, "prefill_bridge_cleanup") else { - let err = String(cString: dlerror()) - print("[NativePrefill] Symbol lookup failed: \(err)") - return false + // Function pointer types matching the C API + private typealias InitFn = @convention(c) (Int32, Int32, Int32, Int32, Int32, Int32) -> Int32 + private typealias SetWeightFn = @convention(c) (UnsafePointer, UnsafeMutableRawPointer) -> Int32 + private typealias FinalizeFn = @convention(c) () -> Int32 + private typealias RunFn = @convention(c) (UnsafePointer, Int32, UnsafeMutablePointer, UnsafeMutablePointer) -> Int32 + private typealias RunArrayFn = @convention(c) (UnsafeMutableRawPointer, UnsafeMutablePointer, UnsafeMutablePointer) -> Int32 + private typealias GetKVFn = @convention(c) (Int32, UnsafeMutablePointer, UnsafeMutablePointer) -> Void + private typealias NumLayersFn = @convention(c) () -> Int32 + + // Resolved symbols + private var fnInit: InitFn? + private var fnSetWeight: SetWeightFn? + private var fnFinalize: FinalizeFn? + private var fnRun: RunFn? + private var fnRunArray: RunArrayFn? + private var fnGetKV: GetKVFn? + private var fnNumLayers: NumLayersFn? + + private func loadDylib() -> Bool { + if handle != nil { return true } + let searchPaths = [ + Bundle.main.executableURL?.deletingLastPathComponent() + .appendingPathComponent("libprefill_bridge_gemma.dylib").path, + "Sources/NativePrefillBridge/libprefill_bridge_gemma.dylib", + ".build/arm64-apple-macosx/release/libprefill_bridge_gemma.dylib", + ].compactMap { $0 } + + for path in searchPaths { + if let h = dlopen(path, RTLD_NOW) { + handle = h + print("[GemmaPrefill] Loaded dylib: \(path)") + break + } } - - initFn = unsafeBitCast(initSym, to: (@convention(c) (UnsafePointer) -> Int32).self) - runFn = unsafeBitCast(runSym, to: (@convention(c) (UnsafePointer, Int32, UnsafeMutablePointer?, UnsafeMutablePointer?) -> Int32).self) - cleanupFn = unsafeBitCast(cleanSym, to: (@convention(c) () -> Void).self) - - // Init with model path — look for HF cache path via env or use default - let modelPath = ProcessInfo.processInfo.environment["NATIVE_PREFILL_MODEL_PATH"] - ?? NSString(string: "~/.cache/huggingface/hub/models--mlx-community--gemma-4-e2b-it-4bit").expandingTildeInPath - print("[NativePrefill] Initializing with model path: \(modelPath)") - - let status = initFn!(modelPath) - if status != 0 { - print("[NativePrefill] Init failed with status \(status)") + guard let h = handle else { + print("[GemmaPrefill] dylib not found. Run: ./scripts/build-prefill-bridge.sh") return false } - initialized = true - print("[NativePrefill] Bridge initialized successfully") - return true - } - - /// Run native prefill and return (elapsed_ms, checksum). Returns nil on failure. - func run(tokenIds: [Int32]) -> (elapsedMs: Double, checksum: Float)? { - guard initialized, let runFn = runFn else { return nil } - - var elapsedMs: Double = 0 - var checksum: Float = 0 - - let status = tokenIds.withUnsafeBufferPointer { buf in - runFn(buf.baseAddress!, Int32(buf.count), &elapsedMs, &checksum) - } - - if status != 0 { - print("[NativePrefill] Run failed with status \(status)") - return nil - } - - return (elapsedMs, checksum) - } - - /// Export K/V from layer and inject into Swift cache. - /// Returns true on success. - func exportKVToCache(layerIdx: Int, cache: KVCache) -> Bool { - guard initialized, let h = handle else { return false } - - // Resolve export functions lazily - typealias KVBytesFn = @convention(c) (Int32) -> Int - typealias ExportFn = @convention(c) (Int32, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutablePointer, UnsafeMutablePointer, UnsafeMutablePointer) -> Int32 - - guard let bytesSym = dlsym(h, "prefill_bridge_kv_bytes"), - let exportSym = dlsym(h, "prefill_bridge_export_kv") else { return false } - - let kvBytes = unsafeBitCast(bytesSym, to: KVBytesFn.self) - let exportKV = unsafeBitCast(exportSym, to: ExportFn.self) - - let nbytes = kvBytes(Int32(layerIdx)) - if nbytes == 0 { return false } - - // Allocate CPU buffers - let kBuf = UnsafeMutableRawPointer.allocate(byteCount: nbytes, alignment: 16) - let vBuf = UnsafeMutableRawPointer.allocate(byteCount: nbytes, alignment: 16) - defer { kBuf.deallocate(); vBuf.deallocate() } - - var kvHeads: Int32 = 0, seqLen: Int32 = 0, headDim: Int32 = 0 - let status = exportKV(Int32(layerIdx), kBuf, vBuf, &kvHeads, &seqLen, &headDim) - if status != 0 { return false } - - // Create MLXArrays from CPU data - // bfloat16 is stored as UInt16 in memory — create as UInt16 then reinterpret - let shape: [Int32] = [1, kvHeads, seqLen, headDim] - let count = Int(kvHeads * seqLen * headDim) - - let kData = Data(bytes: kBuf, count: nbytes) - let vData = Data(bytes: vBuf, count: nbytes) - let kArray = MLXArray(kData, shape.map { Int($0) }, type: UInt16.self).asType(.bfloat16) - let vArray = MLXArray(vData, shape.map { Int($0) }, type: UInt16.self).asType(.bfloat16) - - // Inject into cache by calling update() - let _ = cache.update(keys: kArray, values: vArray) + fnInit = unsafeBitCast(dlsym(h, "gemma_init"), to: InitFn.self) + fnSetWeight = unsafeBitCast(dlsym(h, "gemma_set_weight"), to: SetWeightFn.self) + fnFinalize = unsafeBitCast(dlsym(h, "gemma_finalize"), to: FinalizeFn.self) + fnRun = unsafeBitCast(dlsym(h, "gemma_run"), to: RunFn.self) + fnRunArray = unsafeBitCast(dlsym(h, "gemma_run_array"), to: RunArrayFn.self) + fnGetKV = unsafeBitCast(dlsym(h, "gemma_get_kv_handles"), to: GetKVFn.self) + fnNumLayers = unsafeBitCast(dlsym(h, "gemma_num_layers"), to: NumLayersFn.self) return true } - // MARK: - V2 (weight-sharing bridge) - - private var v2Handle: UnsafeMutableRawPointer? - private var v2Initialized = false - - typealias PB2Init = @convention(c) (Int32, Int32, Int32, Int32, Int32, Int32) -> Int32 - typealias PB2SetWeight = @convention(c) (UnsafePointer, UnsafeMutableRawPointer) -> Int32 - typealias PB2Finalize = @convention(c) () -> Int32 - typealias PB2Run = @convention(c) (UnsafePointer, Int32, UnsafeMutablePointer, UnsafeMutablePointer) -> Int32 - typealias PB2Cleanup = @convention(c) () -> Void - - func ensureInitializedV2(model: Gemma4ModelInner, config: Gemma4TextConfiguration) -> Bool { - if v2Initialized { return true } - - guard let h = dlopen("/tmp/libprefill_bridge_v2.dylib", RTLD_NOW) else { - print("[NativePrefill] V2 dylib not found") - return false - } - v2Handle = h - - guard let initSym = dlsym(h, "pb2_init"), - let setSym = dlsym(h, "pb2_set_weight"), - let finSym = dlsym(h, "pb2_finalize") else { - print("[NativePrefill] V2 symbols not found") - return false - } - - let pb2Init = unsafeBitCast(initSym, to: PB2Init.self) - let pb2Set = unsafeBitCast(setSym, to: PB2SetWeight.self) - let pb2Fin = unsafeBitCast(finSym, to: PB2Finalize.self) + func ensureInitialized(model: Gemma4ModelInner, config: Gemma4TextConfiguration) -> Bool { + if initialized { return true } + guard loadDylib(), let fnInit, let fnSetWeight, let fnFinalize, let fnRun else { return false } - // Init architecture - // slidingWindowPattern: count how many layers before first "full_attention" let pattern = config.layerTypes.prefix(while: { $0 != "full_attention" }).count + 1 - // Only build non-shared layers (first 15) let nonShared = config.hiddenLayers - config.numKvSharedLayers - let rc = pb2Init( + let rc = fnInit( Int32(nonShared), Int32(config.hiddenSize), Int32(config.attentionHeads), Int32(config.kvHeads), Int32(config.slidingWindow), Int32(pattern)) - if rc != 0 { print("[NativePrefill] V2 init failed"); return false } + if rc != 0 { print("[GemmaPrefill] init failed"); return false } - // Pass model weights let params = model.parameters().flattened() var weightCount = 0 for (key, arr) in params { - // Bridge expects keys WITHOUT "model." prefix let rawPtr = arr.ctx.ctx let status = key.withCString { cKey in - pb2Set(cKey, rawPtr!) + fnSetWeight(cKey, rawPtr!) } if status == 0 { weightCount += 1 } } - print("[NativePrefill] V2: passed \(weightCount) weights to bridge") + print("[GemmaPrefill] Passed \(weightCount) weights") - let finRC = pb2Fin() - if finRC != 0 { print("[NativePrefill] V2 finalize failed"); return false } + let finRC = fnFinalize() + if finRC != 0 { print("[GemmaPrefill] finalize failed"); return false } - v2Initialized = true - print("[NativePrefill] V2 initialized (weight-sharing)") + initialized = true + print("[GemmaPrefill] Initialized") - // Pre-warm: run a tiny forward to materialize lazy weights on GPU - if let runSym = dlsym(h, "pb2_run") { - let warmRun = unsafeBitCast(runSym, to: PB2Run.self) + // Pre-warm + do { var warmMs: Double = 0; var warmCk: Float = 0 let warmTokens: [Int32] = [1, 2, 3, 4] warmTokens.withUnsafeBufferPointer { buf in - let _ = warmRun(buf.baseAddress!, 4, &warmMs, &warmCk) + let _ = fnRun(buf.baseAddress!, 4, &warmMs, &warmCk) } - print(String(format: "[NativePrefill] V2 pre-warmed in %.0fms", warmMs)) + print(String(format: "[GemmaPrefill] Pre-warmed in %.0fms", warmMs)) } return true } - func runV2(tokenIds: [Int32]) -> (elapsedMs: Double, checksum: Float)? { - guard v2Initialized, let h = v2Handle, - let runSym = dlsym(h, "pb2_run") else { return nil } - let pb2Run = unsafeBitCast(runSym, to: PB2Run.self) - + func run(tokenIds: [Int32]) -> (elapsedMs: Double, checksum: Float)? { + guard initialized, let fnRun else { return nil } var ms: Double = 0 var ck: Float = 0 let rc = tokenIds.withUnsafeBufferPointer { buf in - pb2Run(buf.baseAddress!, Int32(buf.count), &ms, &ck) + fnRun(buf.baseAddress!, Int32(buf.count), &ms, &ck) } return rc == 0 ? (ms, ck) : nil } + func runZeroCopy(tokenArray: MLXArray) -> (elapsedMs: Double, checksum: Float)? { + guard initialized, let fnRunArray else { return nil } + var ms: Double = 0 + var ck: Float = 0 + let rc = fnRunArray(tokenArray.ctx.ctx, &ms, &ck) + return rc == 0 ? (ms, ck) : nil + } + /// Run native prefill and inject K/V into Swift caches. /// Returns (elapsed_ms, success). Caches are populated on success. - func runAndInjectKV(tokenIds: [Int32], cache: [KVCache], numLayers: Int) -> (Double, Bool) { - guard v2Initialized, let h = v2Handle else { return (0, false) } - - // Run native prefill - guard let result = runV2(tokenIds: tokenIds) else { return (0, false) } - - // Zero-copy K/V injection: get raw mlx::core::array* pointers from bridge - // and wrap in MLXArray by setting the ctx field directly - typealias GetPtr = @convention(c) (Int32) -> UnsafeMutableRawPointer? + func runAndInjectKV(tokenArray: MLXArray, cache: [KVCache], numLayers: Int) -> (Double, Bool) { + guard initialized else { return (0, false) } - guard let kSym = dlsym(h, "pb2_get_k_ptr"), - let vSym = dlsym(h, "pb2_get_v_ptr") else { - return (result.elapsedMs, false) - } - let getK = unsafeBitCast(kSym, to: GetPtr.self) - let getV = unsafeBitCast(vSym, to: GetPtr.self) - - // Resolve export for CPU-copy fallback - typealias KVNb = @convention(c) (Int32) -> Int - typealias KVSh = @convention(c) (Int32, UnsafeMutablePointer, UnsafeMutablePointer, UnsafeMutablePointer) -> Int32 - typealias KVEx = @convention(c) (Int32, UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Int32 - let kvNb = unsafeBitCast(dlsym(h, "pb2_kv_nbytes")!, to: KVNb.self) - let kvSh = unsafeBitCast(dlsym(h, "pb2_kv_shape")!, to: KVSh.self) - let kvEx = unsafeBitCast(dlsym(h, "pb2_export_kv")!, to: KVEx.self) + // Run native prefill — zero-copy, token array stays on GPU + guard let result = runZeroCopy(tokenArray: tokenArray) else { return (0, false) } + // Zero-copy K/V injection: gemma_get_kv_handles creates heap-allocated + // mlx::core::array copies (via `new array(attn.last_k)`) that share the + // underlying GPU data buffer via shared_ptr. No memcpy of tensor data. + // MLXArray.fromCppArray() wraps the pointer, taking ownership. for i in 0.. 0 else { return (result.elapsedMs, false) } - var kvH: Int32 = 0, seqL: Int32 = 0, hd: Int32 = 0 - let _ = kvSh(Int32(i), &kvH, &seqL, &hd) - - // CPU copy — correct but adds ~2ms for 15 layers at 1K tokens - let kBuf = UnsafeMutableRawPointer.allocate(byteCount: nb, alignment: 16) - let vBuf = UnsafeMutableRawPointer.allocate(byteCount: nb, alignment: 16) - let rc = kvEx(Int32(i), kBuf, vBuf) - guard rc == 0 else { kBuf.deallocate(); vBuf.deallocate(); return (result.elapsedMs, false) } - - let shape = [1, Int(kvH), Int(seqL), Int(hd)] - let elems = shape.reduce(1, *) - let bpe = nb / elems - let kArr: MLXArray - let vArr: MLXArray - if bpe == 2 { - kArr = MLXArray(Data(bytes: kBuf, count: nb), shape, type: UInt16.self).view(dtype: .bfloat16) - vArr = MLXArray(Data(bytes: vBuf, count: nb), shape, type: UInt16.self).view(dtype: .bfloat16) - } else { - kArr = MLXArray(Data(bytes: kBuf, count: nb), shape, type: Float.self).asType(.bfloat16) - vArr = MLXArray(Data(bytes: vBuf, count: nb), shape, type: Float.self).asType(.bfloat16) + var kPtr: UnsafeMutableRawPointer? = nil + var vPtr: UnsafeMutableRawPointer? = nil + fnGetKV?(Int32(i), &kPtr, &vPtr) + guard let k = kPtr, let v = vPtr else { + return (result.elapsedMs, false) } - kBuf.deallocate(); vBuf.deallocate() + // Zero-copy: wrap heap-allocated mlx::core::array* as MLXArray. + // Force contiguous — bridge arrays have non-standard strides from + // transpose/reshape chains in the C++ forward pass. Non-contiguous + // K/V in cache causes slower SDPA reads during decode (~5% penalty). + let kArr = MLXArray.fromCppArray(k).contiguous() + let vArr = MLXArray.fromCppArray(v).contiguous() let _ = cache[i].update(keys: kArr, values: vArr) } @@ -531,15 +416,17 @@ class Gemma4Attention: Module { @ModuleInfo(key: "v_proj") var vProj: Linear? @ModuleInfo(key: "o_proj") var oProj: Linear + @ModuleInfo(key: "q_norm") var qNorm: RMSNorm @ModuleInfo(key: "k_norm") var kNorm: RMSNorm let rmsNormEps: Float let rope: any OffsetLayer - // Fused RMSNorm + RoPE via MLXFast.rmsNormRoPE (framework-level compiled kernel). - // invFreqs stored in wrapper to avoid Module loading issues with bare MLXArray properties. - let fusedInvFreqs: FusedNormRoPEKernel? // reuses class as invFreqs container + // Inverse frequencies for fused RMSNorm + RoPE (MLXFast.rmsNormRoPE framework kernel). + // Computed at init, not loaded from checkpoint. Underscore prefix prevents + // Module weight loading from looking for this key in the checkpoint. + let _fusedInvFreqs: MLXArray? /// Set GEMMA4_FUSED_NORM_ROPE=0 to disable for A/B testing. private static let useFusedNormRoPE: Bool = { @@ -587,9 +474,9 @@ class Gemma4Attention: Module { stride(from: Float(0), to: Float(headDim), by: 2) ) / Float(headDim) let freqs = pow(MLXArray(config.ropeTheta), exponents) - self.fusedInvFreqs = FusedNormRoPEKernel(invFreqs: 1.0 / freqs) + self._fusedInvFreqs = 1.0 / freqs } else { - self.fusedInvFreqs = nil + self._fusedInvFreqs = nil } } else { // ProportionalRoPE: pairs are formed across the full head_dim (e.g., 512), @@ -608,9 +495,9 @@ class Gemma4Attention: Module { let paddingCount = (headDim - ropeDim) / 2 let infPadding = MLXArray(Array(repeating: Float.infinity, count: paddingCount)) let allFreqs = concatenated([realFreqs, infPadding], axis: 0) - self.fusedInvFreqs = FusedNormRoPEKernel(invFreqs: 1.0 / allFreqs) + self._fusedInvFreqs = 1.0 / allFreqs } else { - self.fusedInvFreqs = nil + self._fusedInvFreqs = nil } } @@ -680,24 +567,14 @@ class Gemma4Attention: Module { ) -> MLXArray { let (B, L, _) = (x.dim(0), x.dim(1), x.dim(2)) - // Log shapes/strides for first call only - struct FirstCall { static var logged = false } - if !FirstCall.logged && L > 100 { - FirstCall.logged = true - if let ql = qProj as? QuantizedLinear { - print("[ATTN-L0] qProj: w=\(ql.weight.shape) s=\(ql.scales.shape) b=\(ql.biases?.shape ?? []) bits=\(ql.bits) gs=\(ql.groupSize)") - } - print("[ATTN-L0] x: \(x.shape) dtype=\(x.dtype)") - } - var queries = qProj(x).reshaped(B, L, nHeads, -1) if useSharedKV, let sharedKV = sharedKVArrays { let (cachedKeys, cachedValues) = sharedKV let offset = donorOffset ?? cache?.offset ?? 0 - if let fusedInvFreqs { + if let _fusedInvFreqs { queries = MLXFast.rmsNormRoPE( - queries, weight: qNorm.weight, invFreqs: fusedInvFreqs.invFreqs, + queries, weight: qNorm.weight, invFreqs: _fusedInvFreqs, eps: rmsNormEps, offset: offset, nHeads: nHeads, seqLen: L) queries = queries.transposed(0, 2, 1, 3) } else { @@ -732,9 +609,9 @@ class Gemma4Attention: Module { values = MLXFast.rmsNorm(values, weight: MLXArray.mlxNone, eps: rmsNormEps) let offset = cache?.offset ?? 0 - if let fusedInvFreqs { + if let _fusedInvFreqs { // Fused norm+rope via framework kernel: 2 dispatches instead of 4 - let invFreqs = fusedInvFreqs.invFreqs + let invFreqs = _fusedInvFreqs queries = MLXFast.rmsNormRoPE( queries, weight: qNorm.weight, invFreqs: invFreqs, eps: rmsNormEps, offset: offset, nHeads: nHeads, seqLen: L) @@ -787,10 +664,11 @@ private let compiledGeglu: @Sendable (MLXArray, MLXArray) -> MLXArray = /// Fused RMSNorm + residual add: residual + rmsNorm(x, weight, eps). /// Saves 1 encoder dispatch per call (norm and add fused into single kernel). /// Applied at every post-attention and post-FFN norm+add site in the decoder layer. +/// compiledNormResidual is UNUSED — kept for reference. +/// compile() cannot fuse across fast::RMSNorm (opaque custom primitive). +/// Use MLXFast.rmsNormResidual() framework kernel instead (rms_norm_residual.metal). private let compiledNormResidual: @Sendable (MLXArray, MLXArray, MLXArray) -> MLXArray = compile(shapeless: true) { x, residual, weight in - // eps is captured via the weight's associated norm; we use a standard value. - // Note: eps must be a literal for compile() — it's baked into the compiled graph. residual + MLXFast.rmsNorm(x, weight: weight, eps: 1e-6) } @@ -941,14 +819,12 @@ class Gemma4TransformerBlock: Module { ) -> MLXArray { let inputNorm = inputLayerNorm(x) let attnOut = selfAttention(inputNorm, mask: mask, cache: cache, useSharedKV: useSharedKV, sharedKVArrays: sharedKVArrays, donorOffset: donorOffset) - // Manual `residual + norm(x)` instead of compiledNormResidual. - // The compiled fused op was apparently materializing intermediate - // copies inside its traced graph at every layer during prefill, - // simultaneously slowing prefill 2-3x and ballooning peak GPU memory - // by 1-2 GB. Replacing it with the explicit `residual + norm(x)` - // recovers prefill throughput AND drops memory. - // (See PR description for the measurements.) - var h = x + postAttentionLayerNorm(attnOut) + // Fused RMSNorm + residual add via framework Metal kernel (rms_norm_residual.metal). + // Single dispatch replaces separate rmsNorm + add (saves 90 dispatches/token). + var h = MLXFast.rmsNormResidual( + attnOut, residual: x, + weight: postAttentionLayerNorm.weight, + eps: postAttentionLayerNorm.eps) // FFN with pre/post norms: shared MLP + MoE if let experts, let router, @@ -973,14 +849,18 @@ class Gemma4TransformerBlock: Module { h2 = h2.sum(axis: -2) h2 = postNorm2(h2) - // Manual norm+add (see compiledNormResidual note above). let ffnOut = h1 + h2 - h = h + postFeedforwardLayerNorm(ffnOut) + h = MLXFast.rmsNormResidual( + ffnOut, residual: h, + weight: postFeedforwardLayerNorm.weight, + eps: postFeedforwardLayerNorm.eps) } else { - // Manual norm+add (see compiledNormResidual note above). let preFFNNorm = preFeedforwardLayerNorm(h) let ffnOut = sharedMLP(preFFNNorm) - h = h + postFeedforwardLayerNorm(ffnOut) + h = MLXFast.rmsNormResidual( + ffnOut, residual: h, + weight: postFeedforwardLayerNorm.weight, + eps: postFeedforwardLayerNorm.eps) } // Per-Layer Embeddings (PLE) — fuse gelu + mul @@ -1192,7 +1072,7 @@ public class Gemma4ModelInner: Module { // shared layer ops because they're not ancestors of the cache arrays. // Saves ~580 graph ops per chunk (1318→738) = ~44% fewer GPU dispatches. if prefillMode { - print("[PREFILL-SKIP] layer \(i) shared, skipping") + // Shared layers don't write to cache — skip during prefill continue } h = layer(h, mask: maskMode, cache: nil, perLayerInput: pli, @@ -1249,26 +1129,31 @@ public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider { public func prepare(_ input: LMInput, cache: [KVCache], windowSize: Int?) throws -> PrepareResult { - let prefillStepSize = max(windowSize ?? 512, 2048) + // Larger chunks reduce per-chunk overhead (graph building, eval barriers, + // weight re-reads). 4096 balances speed and memory for pure attention models. + let prefillStepSize = max(windowSize ?? 512, 4096) var y = input.text - // Native prefill offload v2 (NATIVE_PREFILL=1) - if NativePrefillBridge.isEnabled { - let bridge = NativePrefillBridge.shared - if bridge.ensureInitializedV2(model: model, config: config) { + // Native prefill offload (opt-in via NATIVE_PREFILL=1) + if ProcessInfo.processInfo.environment["NATIVE_PREFILL"] == "1" { + let bridge = GemmaPrefillBridge.shared + if bridge.ensureInitialized(model: model, config: config) { let allTokens = input.text.tokens let prefillCount = allTokens.size - 1 if prefillCount > 0 { + // Zero-copy: pass MLXArray directly to bridge (stays on GPU). + // Avoids eval() + .asArray() GPU→CPU→GPU roundtrip. let tokenSlice = allTokens[0 ..< prefillCount].reshaped(-1) - eval(tokenSlice) - let tokenIds = tokenSlice.asArray(Int32.self) let nonShared = config.hiddenLayers - config.numKvSharedLayers let (ms, ok) = bridge.runAndInjectKV( - tokenIds: tokenIds, cache: cache, numLayers: nonShared) + tokenArray: tokenSlice, cache: cache, numLayers: nonShared) - if ok { - return .tokens(y) + if ok, ms > 0 { + let bridgeTokS = Double(prefillCount) / (ms / 1000.0) + print(String(format: "[GemmaPrefill] bridge: %.1fms = %.0f tok/s (%d tokens)", ms, bridgeTokS, prefillCount)) + let lastToken = allTokens[prefillCount ..< allTokens.size] + return .tokens(LMInput.Text(tokens: lastToken)) } } } @@ -1285,18 +1170,23 @@ public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider { let input = y[.newAxis, .. PrepareResult + { + var y = input.text + + if ProcessInfo.processInfo.environment["NATIVE_PREFILL"] == "1" { + let bridge = GenericPrefillBridge.shared + let json = """ + {"model_type":"generic","hidden_size":\(configuration.hiddenSize),"num_hidden_layers":\(configuration.hiddenLayers),"num_attention_heads":\(configuration.attentionHeads),"num_key_value_heads":\(configuration.kvHeads),"head_dim":\(configuration.resolvedHeadDimensions),"intermediate_size":\(configuration.intermediateSize),"vocab_size":\(configuration.vocabularySize),"rms_norm_eps":\(String(format:"%.0e",Double(configuration.rmsNormEps))),"rope_theta":\(String(format:"%.0f",Double(configuration.ropeTheta))),"tie_word_embeddings":\(configuration.tieWordEmbeddings)} + """ + if bridge.ensureInitialized(modelType: "generic", model: model, config: json) { + let allTokens = input.text.tokens + let prefillCount = allTokens.size - 1 + if prefillCount > 0 { + let tokenSlice = allTokens[0 ..< prefillCount].reshaped(-1) + let (ms, ok) = bridge.runAndInjectKV( + tokenArray: tokenSlice, cache: cache, numLayers: configuration.hiddenLayers) + if ok { + print(String(format: "[GenericPrefill] %d tokens in %.1fms (%.0f t/s)", + prefillCount, ms, Double(prefillCount) / (ms / 1000))) + let lastToken = allTokens[prefillCount ..< allTokens.size] + return .tokens(LMInput.Text(tokens: lastToken)) + } + } + } + } + + // Default Swift prefill + let prefillStepSize = max(windowSize ?? 512, 4096) + while y.tokens.size > 1 { + let chunkSize = min(prefillStepSize, y.tokens.size - 1) + let input = y[.newAxis, .. MLXArray { let out = model(inputs, cache: cache) if let lmHead { diff --git a/Libraries/MLXLLM/Models/MiniMaxM2.swift b/Libraries/MLXLLM/Models/MiniMaxM2.swift new file mode 100644 index 0000000000..dd3919fe7b --- /dev/null +++ b/Libraries/MLXLLM/Models/MiniMaxM2.swift @@ -0,0 +1,438 @@ +// Port of https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/minimax.py + +import Foundation +import MLX +import MLXLMCommon +import MLXNN +import NativePrefillBridge + +// MARK: - Generic Prefill Bridge (SPM C++ target — shared allocator) + +final class GenericPrefillBridge { + static let shared = GenericPrefillBridge() + + private var initializedModelType: String? = nil + + func ensureInitialized(modelType: String, model: Module, config configJSON: String) -> Bool { + if initializedModelType == modelType { return true } + + // If switching model types, cleanup first + if initializedModelType != nil { + gp_cleanup() + initializedModelType = nil + } + + let rc = configJSON.withCString { gp_init($0) } + if rc != 0 { print("[GenericPrefill] init failed"); return false } + + let params = model.parameters().flattened() + var weightCount = 0 + for (key, arr) in params { + let bridgeKey = "model." + key + let rawPtr = arr.ctx.ctx + let status = bridgeKey.withCString { cKey in + gp_set_weight(cKey, rawPtr!) + } + if status == 0 { weightCount += 1 } + } + print("[GenericPrefill] Passed \(weightCount) weights") + + let finRC = gp_finalize() + if finRC != 0 { print("[GenericPrefill] finalize failed"); return false } + + initializedModelType = modelType + print("[GenericPrefill] Initialized for \(modelType)") + + // Warmup: run a dummy forward pass to materialize all weight GPU buffers. + // Without this, the first real forward pass produces garbage because the + // Metal allocator reclaims unevaluated weight buffers during graph construction. + var warmMs: Double = 0 + let warmTokens = MLXArray([1, 2, 3, 4]).reshaped(1, 4) + let _ = gp_run(warmTokens.ctx.ctx!, &warmMs) + print(String(format: "[GenericPrefill] Pre-warmed in %.0fms", warmMs)) + + return true + } + + // Convenience for MiniMax + func ensureInitialized(model: MiniMaxM2ModelInner, config: MiniMaxM2Configuration) -> Bool { + let json = """ + {"model_type":"minimax_m2","hidden_size":\(config.hiddenSize),"num_hidden_layers":\(config.hiddenLayers),"num_attention_heads":\(config.attentionHeads),"num_key_value_heads":\(config.kvHeads),"head_dim":\(config.headDim),"intermediate_size":\(config.intermediateSize),"vocab_size":\(config.vocabularySize),"rms_norm_eps":\(String(format:"%.0e",Double(config.rmsNormEps))),"rope_theta":\(String(format:"%.0f",Double(config.ropeTheta))),"rotary_dim":\(config.rotaryDim),"tie_word_embeddings":\(config.tieWordEmbeddings),"use_qk_norm":\(config.useQkNorm),"num_local_experts":\(config.numLocalExperts),"num_experts_per_tok":\(config.numExpertsPerTok),"scoring_func":"\(config.scoringFunc)"} + """ + return ensureInitialized(modelType: "minimax_m2", model: model, config: json) + } + + func runAndInjectKV(tokenArray: MLXArray, cache: [KVCache], numLayers: Int) -> (Double, Bool) { + guard initializedModelType != nil else { return (0, false) } + + let tokens2d = tokenArray.dim(0) == 1 ? tokenArray : tokenArray.reshaped(1, tokenArray.size) + var ms: Double = 0 + let rc = gp_run(tokens2d.ctx.ctx!, &ms) + if rc != 0 { return (0, false) } + + for i in 0.. MLXArray { + let (B, L, _) = (x.dim(0), x.dim(1), x.dim(2)) + + var queries = qProj(x) + var keys = kProj(x) + var values = vProj(x) + + // QK norm applied BEFORE reshape (per-layer norm) + if useQkNorm { + queries = qNorm!(queries) + keys = kNorm!(keys) + } + + queries = queries.reshaped(B, L, numHeads, headDim).transposed(0, 2, 1, 3) + keys = keys.reshaped(B, L, numKVHeads, headDim).transposed(0, 2, 1, 3) + values = values.reshaped(B, L, numKVHeads, headDim).transposed(0, 2, 1, 3) + + if let cache { + queries = rope(queries, offset: cache.offset) + keys = rope(keys, offset: cache.offset) + (keys, values) = cache.update(keys: keys, values: values) + } else { + queries = rope(queries) + keys = rope(keys) + } + + let output = MLXFast.scaledDotProductAttention( + queries: queries, keys: keys, values: values, + scale: scale, mask: mask) + + .transposed(0, 2, 1, 3) + .reshaped(B, L, -1) + + return oProj(output) + } +} + +// MARK: - MoE + +class MiniMaxM2SparseMoeBlock: Module { + let numExpertsPerTok: Int + + @ModuleInfo(key: "gate") var gate: Linear + @ModuleInfo(key: "switch_mlp") var switchMLP: SwitchGLU + @ParameterInfo(key: "e_score_correction_bias") var correctionBias: MLXArray + + init(_ config: MiniMaxM2Configuration) { + self.numExpertsPerTok = config.numExpertsPerTok + _gate.wrappedValue = Linear(config.hiddenSize, config.numLocalExperts, bias: false) + _switchMLP.wrappedValue = SwitchGLU( + inputDims: config.hiddenSize, + hiddenDims: config.intermediateSize, + numExperts: config.numLocalExperts + ) + _correctionBias.wrappedValue = MLXArray.zeros([config.numLocalExperts]) + super.init() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + let gates = gate(x.asType(.float32)) + + // Sigmoid scoring (not softmax) + let scores = sigmoid(gates) + let origScores = scores + let correctedScores = scores + correctionBias + + // Top-k expert selection + let k = numExpertsPerTok + let inds = argPartition(-correctedScores, kth: k - 1, axis: -1)[.ellipsis, .. MLXArray { + let r = x + selfAttn(inputLayerNorm(x), mask: mask, cache: cache) + return r + moe(postAttentionLayerNorm(r)) + } +} + +// MARK: - Model + +class MiniMaxM2ModelInner: Module { + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + let layers: [MiniMaxM2DecoderLayer] + @ModuleInfo var norm: RMSNorm + + init(_ config: MiniMaxM2Configuration) { + _embedTokens.wrappedValue = Embedding(embeddingCount: config.vocabularySize, dimensions: config.hiddenSize) + self.layers = (0.. MLXArray { + var h = embedTokens(inputs) + + let mask = makeAttentionMask(n: h.dim(1), cache: cache?.first) + + for (i, layer) in layers.enumerated() { + h = layer(h, mask: mask, cache: cache?[i]) + } + return norm(h) + } +} + +// MARK: - LLM Model + +public class MiniMaxM2Model: Module, LLMModel, KVCacheDimensionProvider, LoRAModel { + public var loraLayers: [Module] { model.layers.map { $0 } } + public let vocabularySize: Int + public let kvHeads: [Int] + + @ModuleInfo var model: MiniMaxM2ModelInner + @ModuleInfo(key: "lm_head") var lmHead: Linear? + + let config: MiniMaxM2Configuration + + public init(_ config: MiniMaxM2Configuration) { + self.config = config + self.vocabularySize = config.vocabularySize + self.model = MiniMaxM2ModelInner(config) + self.kvHeads = Array(repeating: config.kvHeads, count: config.hiddenLayers) + + if !config.tieWordEmbeddings { + _lmHead.wrappedValue = Linear(config.hiddenSize, config.vocabularySize, bias: false) + } + super.init() + } + + public func prepare(_ input: LMInput, cache: [KVCache], windowSize: Int?) throws + -> PrepareResult + { + var y = input.text + // Native prefill offload (opt-in via NATIVE_PREFILL=1) + if ProcessInfo.processInfo.environment["NATIVE_PREFILL"] == "1" { + let bridge = GenericPrefillBridge.shared + if bridge.ensureInitialized(model: model, config: config) { + let allTokens = input.text.tokens + let prefillCount = allTokens.size - 1 + if prefillCount > 0 { + let tokenSlice = allTokens[0 ..< prefillCount].reshaped(-1) + let (ms, ok) = bridge.runAndInjectKV( + tokenArray: tokenSlice, cache: cache, numLayers: config.hiddenLayers) + if ok { + print(String(format: "[GenericPrefill] %d tokens in %.1fms (%.0f t/s)", + prefillCount, ms, Double(prefillCount) / (ms / 1000))) + let lastToken = allTokens[prefillCount ..< allTokens.size] + return .tokens(LMInput.Text(tokens: lastToken)) + } + } + } + // Fall through to Swift prefill on failure + } + + // Default Swift prefill + let prefillStepSize = max(windowSize ?? 512, 4096) + while y.tokens.size > 1 { + let chunkSize = min(prefillStepSize, y.tokens.size - 1) + let input = y[.newAxis, .. MLXArray { + var out = model(inputs, cache: cache) + if config.tieWordEmbeddings { + out = model.embedTokens.asLinear(out) + } else { + out = lmHead!(out) + } + return out + } + + public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + var processedWeights = weights + + // Restructure MoE expert weights: experts.N.wX.weight → switch_mlp.{gate,up,down}_proj.weight + if processedWeights["model.layers.0.block_sparse_moe.experts.0.w1.weight"] != nil { + let mapping = ["w1": "gate_proj", "w2": "down_proj", "w3": "up_proj"] + for l in 0.. PrepareResult + { + var y = input.text + + if ProcessInfo.processInfo.environment["NATIVE_PREFILL"] == "1" { + let bridge = GenericPrefillBridge.shared + let headDim = args.hiddenSize / args.attentionHeads + let json = """ + {"model_type":"phi3","hidden_size":\(args.hiddenSize),"num_hidden_layers":\(args.hiddenLayers),"num_attention_heads":\(args.attentionHeads),"num_key_value_heads":\(args.kvHeads),"head_dim":\(headDim),"intermediate_size":\(args.intermediateSize),"vocab_size":\(args.vocabularySize),"rms_norm_eps":\(String(format:"%.0e",Double(args.rmsNormEps))),"rope_theta":\(String(format:"%.0f",Double(args.ropeTheta))),"tie_word_embeddings":\(args.tieWordEmbeddings)} + """ + if bridge.ensureInitialized(modelType: "phi3", model: model, config: json) { + let allTokens = input.text.tokens + let prefillCount = allTokens.size - 1 + if prefillCount > 0 { + let tokenSlice = allTokens[0 ..< prefillCount].reshaped(-1) + let (ms, ok) = bridge.runAndInjectKV( + tokenArray: tokenSlice, cache: cache, numLayers: args.hiddenLayers) + if ok { + print(String(format: "[GenericPrefill] %d tokens in %.1fms (%.0f t/s)", + prefillCount, ms, Double(prefillCount) / (ms / 1000))) + let lastToken = allTokens[prefillCount ..< allTokens.size] + return .tokens(LMInput.Text(tokens: lastToken)) + } + } + } + } + + // Default Swift prefill + let prefillStepSize = max(windowSize ?? 512, 4096) + while y.tokens.size > 1 { + let chunkSize = min(prefillStepSize, y.tokens.size - 1) + let input = y[.newAxis, .. MLXArray { let out = model(inputs, cache: cache) if args.tieWordEmbeddings { diff --git a/Libraries/MLXLLM/Models/Qwen2.swift b/Libraries/MLXLLM/Models/Qwen2.swift index 2b336b826c..49fcf43e94 100644 --- a/Libraries/MLXLLM/Models/Qwen2.swift +++ b/Libraries/MLXLLM/Models/Qwen2.swift @@ -9,6 +9,7 @@ import Foundation import MLX import MLXLMCommon import MLXNN +import NativePrefillBridge // port of https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/qwen2.py @@ -188,6 +189,58 @@ public class Qwen2Model: Module, LLMModel, KVCacheDimensionProvider { } } + public func prepare(_ input: LMInput, cache: [KVCache], windowSize: Int?) throws + -> PrepareResult + { + var y = input.text + FileHandle.standardError.write(Data("[Qwen2] prepare() called, tokens=\(y.tokens.size), cache=\(cache.count) layers\n".utf8)) + + if ProcessInfo.processInfo.environment["NATIVE_PREFILL"] == "1" { + let bridge = QwenPrefillBridge.shared + let headDim = configuration.hiddenSize / configuration.attentionHeads + let json = """ + {"model_type":"qwen2","hidden_size":\(configuration.hiddenSize),"num_hidden_layers":\(configuration.hiddenLayers),"num_attention_heads":\(configuration.attentionHeads),"num_key_value_heads":\(configuration.kvHeads),"head_dim":\(headDim),"intermediate_size":\(configuration.intermediateSize),"vocab_size":\(configuration.vocabularySize),"rms_norm_eps":\(String(format:"%.0e",Double(configuration.rmsNormEps))),"rope_theta":\(String(format:"%.0f",Double(configuration.ropeTheta))),"tie_word_embeddings":\(configuration.tieWordEmbeddings),"use_qk_norm":false} + """ + if bridge.ensureInitialized(modelType: "qwen2", model: model, config: json) { + let allTokens = input.text.tokens + let prefillCount = allTokens.size - 1 + if prefillCount > 0 { + let tokenSlice = allTokens[0 ..< prefillCount].reshaped(-1) + let (ms, ok) = bridge.runAndInjectKV( + tokenArray: tokenSlice, cache: cache, numLayers: configuration.hiddenLayers) + FileHandle.standardError.write(Data("[Qwen2] bridge run: ok=\(ok) ms=\(ms)\n".utf8)) + if ok { + // Check KV cache shapes and offset + for (i, c) in cache.prefix(2).enumerated() { + let state = c.innerState() + FileHandle.standardError.write(Data("[Qwen2] cache[\(i)] offset=\(c.offset) shapes=\(state.map { "\($0.shape)" })\n".utf8)) + } + FileHandle.standardError.write(Data("[Qwen2] bridge prefill OK, \(prefillCount) tokens\n".utf8)) + let lastToken = allTokens[prefillCount ..< allTokens.size] + return .tokens(LMInput.Text(tokens: lastToken)) + } + } + } + } + + // Default Swift prefill + let prefillStepSize = max(windowSize ?? 512, 4096) + while y.tokens.size > 1 { + let chunkSize = min(prefillStepSize, y.tokens.size - 1) + let input = y[.newAxis, .. MLXArray { var out = model(inputs, cache: cache) if let lmHead { diff --git a/Libraries/MLXLLM/Models/Qwen3.swift b/Libraries/MLXLLM/Models/Qwen3.swift index 86555c464a..32c99a019a 100644 --- a/Libraries/MLXLLM/Models/Qwen3.swift +++ b/Libraries/MLXLLM/Models/Qwen3.swift @@ -9,6 +9,7 @@ import Foundation import MLX import MLXLMCommon import MLXNN +import NativePrefillBridge // port of https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/qwen3.py @@ -196,6 +197,51 @@ public class Qwen3Model: Module, LLMModel, KVCacheDimensionProvider { } } + public func prepare(_ input: LMInput, cache: [KVCache], windowSize: Int?) throws + -> PrepareResult + { + var y = input.text + + if ProcessInfo.processInfo.environment["NATIVE_PREFILL"] == "1" { + let bridge = QwenPrefillBridge.shared + let json = """ + {"model_type":"qwen3","hidden_size":\(configuration.hiddenSize),"num_hidden_layers":\(configuration.hiddenLayers),"num_attention_heads":\(configuration.attentionHeads),"num_key_value_heads":\(configuration.kvHeads),"head_dim":\(configuration.headDim),"intermediate_size":\(configuration.intermediateSize),"vocab_size":\(configuration.vocabularySize),"rms_norm_eps":\(String(format:"%.0e",Double(configuration.rmsNormEps))),"rope_theta":\(String(format:"%.0f",Double(configuration.ropeTheta))),"tie_word_embeddings":\(configuration.tieWordEmbeddings),"use_qk_norm":true} + """ + if bridge.ensureInitialized(modelType: "qwen3", model: model, config: json) { + let allTokens = input.text.tokens + let prefillCount = allTokens.size - 1 + if prefillCount > 0 { + let tokenSlice = allTokens[0 ..< prefillCount].reshaped(-1) + let (ms, ok) = bridge.runAndInjectKV( + tokenArray: tokenSlice, cache: cache, numLayers: configuration.hiddenLayers) + if ok { + print(String(format: "[QwenPrefill] %d tokens in %.1fms (%.0f t/s)", + prefillCount, ms, Double(prefillCount) / (ms / 1000))) + let lastToken = allTokens[prefillCount ..< allTokens.size] + return .tokens(LMInput.Text(tokens: lastToken)) + } + } + } + } + + // Default Swift prefill + let prefillStepSize = max(windowSize ?? 512, 4096) + while y.tokens.size > 1 { + let chunkSize = min(prefillStepSize, y.tokens.size - 1) + let input = y[.newAxis, .. MLXArray { var out = model(inputs, cache: cache) if let lmHead { diff --git a/Libraries/MLXLLM/Models/Qwen3MoE.swift b/Libraries/MLXLLM/Models/Qwen3MoE.swift index 79a3d7c8ad..48126ee42f 100644 --- a/Libraries/MLXLLM/Models/Qwen3MoE.swift +++ b/Libraries/MLXLLM/Models/Qwen3MoE.swift @@ -9,6 +9,7 @@ import Foundation import MLX import MLXLMCommon import MLXNN +import NativePrefillBridge // port of https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/qwen3_moe.py @@ -245,6 +246,51 @@ public class Qwen3MoEModel: Module, LLMModel, KVCacheDimensionProvider { } } + public func prepare(_ input: LMInput, cache: [KVCache], windowSize: Int?) throws + -> PrepareResult + { + var y = input.text + + if ProcessInfo.processInfo.environment["NATIVE_PREFILL"] == "1" { + let bridge = QwenPrefillBridge.shared + let json = """ + {"model_type":"qwen3_moe","hidden_size":\(configuration.hiddenSize),"num_hidden_layers":\(configuration.hiddenLayers),"num_attention_heads":\(configuration.attentionHeads),"num_key_value_heads":\(configuration.kvHeads),"head_dim":\(configuration.headDim),"intermediate_size":\(configuration.moeIntermediateSize),"vocab_size":\(configuration.vocabularySize),"rms_norm_eps":\(String(format:"%.0e",Double(configuration.rmsNormEps))),"rope_theta":\(String(format:"%.0f",Double(configuration.ropeTheta))),"tie_word_embeddings":\(configuration.tieWordEmbeddings),"use_qk_norm":true,"num_local_experts":\(configuration.numExperts),"num_experts_per_tok":\(configuration.numExpertsPerToken),"scoring_func":"softmax"} + """ + if bridge.ensureInitialized(modelType: "qwen3_moe", model: model, config: json) { + let allTokens = input.text.tokens + let prefillCount = allTokens.size - 1 + if prefillCount > 0 { + let tokenSlice = allTokens[0 ..< prefillCount].reshaped(-1) + let (ms, ok) = bridge.runAndInjectKV( + tokenArray: tokenSlice, cache: cache, numLayers: configuration.hiddenLayers) + if ok { + print(String(format: "[QwenPrefill] %d tokens in %.1fms (%.0f t/s)", + prefillCount, ms, Double(prefillCount) / (ms / 1000))) + let lastToken = allTokens[prefillCount ..< allTokens.size] + return .tokens(LMInput.Text(tokens: lastToken)) + } + } + } + } + + // Default Swift prefill + let prefillStepSize = max(windowSize ?? 512, 4096) + while y.tokens.size > 1 { + let chunkSize = min(prefillStepSize, y.tokens.size - 1) + let input = y[.newAxis, .. MLXArray { var out = model(inputs, cache: cache) if let lmHead { diff --git a/Libraries/MLXLLM/Models/QwenPrefillBridge.swift b/Libraries/MLXLLM/Models/QwenPrefillBridge.swift new file mode 100644 index 0000000000..62eae8771e --- /dev/null +++ b/Libraries/MLXLLM/Models/QwenPrefillBridge.swift @@ -0,0 +1,81 @@ +// +// QwenPrefillBridge.swift +// mlx-swift-lm +// +// Qwen-family dedicated native prefill bridge. +// Wraps the C API from prefill_bridge_qwen.h for use by Qwen2, Qwen3, and Qwen3MoE. +// Separated from GenericPrefillBridge to allow Qwen-specific tuning +// (eval barriers, MoE dispatch) without risking regressions on other models. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN +import NativePrefillBridge + +final class QwenPrefillBridge { + static let shared = QwenPrefillBridge() + + private var initializedModelType: String? = nil + + func ensureInitialized(modelType: String, model: Module, config configJSON: String) -> Bool { + if initializedModelType == modelType { return true } + + // If switching model types, cleanup first + if initializedModelType != nil { + qwen_cleanup() + initializedModelType = nil + } + + let rc = configJSON.withCString { qwen_init($0) } + if rc != 0 { print("[QwenPrefill] init failed"); return false } + + let params = model.parameters().flattened() + var weightCount = 0 + for (key, arr) in params { + let bridgeKey = "model." + key + let rawPtr = arr.ctx.ctx + let status = bridgeKey.withCString { cKey in + qwen_set_weight(cKey, rawPtr!) + } + if status == 0 { weightCount += 1 } + } + print("[QwenPrefill] Passed \(weightCount) weights") + + let finRC = qwen_finalize() + if finRC != 0 { print("[QwenPrefill] finalize failed"); return false } + + initializedModelType = modelType + print("[QwenPrefill] Initialized for \(modelType)") + + // Warmup: run a dummy forward pass to materialize all weight GPU buffers + var warmMs: Double = 0 + let warmTokens = MLXArray([1, 2, 3, 4]).reshaped(1, 4) + let _ = qwen_run(warmTokens.ctx.ctx!, &warmMs) + print(String(format: "[QwenPrefill] Pre-warmed in %.0fms", warmMs)) + + return true + } + + func runAndInjectKV(tokenArray: MLXArray, cache: [KVCache], numLayers: Int) -> (Double, Bool) { + guard initializedModelType != nil else { return (0, false) } + + let tokens2d = tokenArray.dim(0) == 1 ? tokenArray : tokenArray.reshaped(1, tokenArray.size) + var ms: Double = 0 + let rc = qwen_run(tokens2d.ctx.ctx!, &ms) + if rc != 0 { return (0, false) } + + for i in 0.. Any { + switch self { + case .string(let v): return v + case .int(let v): return v + case .double(let v): return v + case .bool(let v): return v + case .null: return NSNull() + case .array(let v): return v.map { $0.toAny() } + case .object(let v): return v.mapValues { $0.toAny() } as [String: Any] + } + } +} + +struct ChatResponse: Codable { + let id: String + let object: String + let created: Int + let model: String + let system_fingerprint: String + let choices: [Choice] + let usage: Usage? + + struct Choice: Codable { + let index: Int + let message: Message? + let delta: Message? + let finish_reason: String? + } + + struct Message: Codable { + let role: String? + let content: String? + let reasoning_content: String? + + init(role: String? = nil, content: String? = nil, reasoning_content: String? = nil) { + self.role = role + self.content = content + self.reasoning_content = reasoning_content + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(role, forKey: .role) + try container.encodeIfPresent(content, forKey: .content) + try container.encodeIfPresent(reasoning_content, forKey: .reasoning_content) + } + + enum CodingKeys: String, CodingKey { + case role, content, reasoning_content + } + } + + struct Usage: Codable { + let prompt_tokens: Int + let completion_tokens: Int + let total_tokens: Int + } +} + +// MARK: - Minimal HTTP Server using URLSession's HTTPServer +// Using a raw socket server via Foundation for zero dependencies + +// MARK: - Server Prompt Cache (Multi-Session) + +struct CachedSession { + let id: UUID = UUID() + var tokenIds: [Int] + var kvCache: [KVCache] + var lastUsed: Date +} + +/// Multi-session prompt cache with LCP (longest common prefix) matching. +/// Keeps up to `maxSessions` cached KV states. When a new request arrives, +/// finds the session with the longest matching token prefix, trims KV to +/// that prefix, and returns only the new tokens to prefill. +struct CacheMetrics { + var totalRequests: Int = 0 + var cacheHits: Int = 0 + var cacheMisses: Int = 0 + var trimFailures: Int = 0 + var totalPrefillTokens: Int = 0 + var totalReusedTokens: Int = 0 + var totalPrefillMs: Double = 0 + var totalDecodeMs: Double = 0 + var totalDecodeTokens: Int = 0 + var evictions: Int = 0 + + var hitRate: Double { totalRequests > 0 ? Double(cacheHits) / Double(totalRequests) : 0 } + var avgPrefillTokens: Double { totalRequests > 0 ? Double(totalPrefillTokens) / Double(totalRequests) : 0 } + var avgPrefillMs: Double { totalRequests > 0 ? totalPrefillMs / Double(totalRequests) : 0 } + var avgDecodeTokensPerSec: Double { totalDecodeMs > 0 ? Double(totalDecodeTokens) / (totalDecodeMs / 1000) : 0 } +} + +actor ServerPromptCache { + var sessions: [CachedSession] = [] + let maxSessions: Int + var metrics = CacheMetrics() + + init(maxSessions: Int = 3) { + self.maxSessions = maxSessions + } + + func recordRequest(hit: Bool, prefillTokens: Int, reusedTokens: Int) { + metrics.totalRequests += 1 + if hit { metrics.cacheHits += 1 } else { metrics.cacheMisses += 1 } + metrics.totalPrefillTokens += prefillTokens + metrics.totalReusedTokens += reusedTokens + } + + func recordTiming(prefillMs: Double, decodeMs: Double, decodeTokens: Int) { + metrics.totalPrefillMs += prefillMs + metrics.totalDecodeMs += decodeMs + metrics.totalDecodeTokens += decodeTokens + } + + func recordEviction() { metrics.evictions += 1 } + func recordTrimFailure() { metrics.trimFailures += 1 } + func getMetrics() -> CacheMetrics { metrics } + func getSessionCount() -> Int { sessions.count } + + /// Find the session with the longest common prefix match. + /// Returns (kvCache, newTokensToProcess, cacheStatus, sessionId). + func fetch(tokens newTokens: [Int], model: any LanguageModel) -> ([KVCache], [Int], CacheStatus, UUID) { + var bestIdx = -1 + var bestPrefix = 0 + + for (i, session) in sessions.enumerated() { + let prefix = commonPrefix(session.tokenIds, newTokens) + if prefix > bestPrefix { + bestPrefix = prefix + bestIdx = i + } + } + + if bestIdx >= 0 && bestPrefix > 0 { + let session = sessions[bestIdx] + // Trim based on actual KV cache size, not tokenIds.count. + // The cache may have extra decode tokens from interrupted generation. + let actualCacheSize = session.kvCache.first?.offset ?? session.tokenIds.count + let trimAmount = actualCacheSize - bestPrefix + + // If the new request extends the cached session (same prefix, more tokens), + // we can trim and use in-place. If it diverges (different suffix), we need + // to copy so the original stays intact for future reuse. + let isExtension = (bestPrefix == session.tokenIds.count) || (trimAmount == 0) + + if isExtension { + // Same conversation continuing — use in-place, no copy needed + if trimAmount > 0 { + for c in session.kvCache { + if c.trim(trimAmount) == 0 { + metrics.trimFailures += 1 + return freshCache(tokens: newTokens, model: model) + } + } + } + sessions[bestIdx].lastUsed = Date() + sessions[bestIdx].tokenIds = Array(newTokens[0.. 0 { + for c in copiedCache { + if c.trim(trimAmount) == 0 { + metrics.trimFailures += 1 + return freshCache(tokens: newTokens, model: model) + } + } + } + + evictIfNeeded() + let newSession = CachedSession(tokenIds: Array(newTokens[0.. ([KVCache], [Int], CacheStatus, UUID) { + evictIfNeeded() + let cache = model.newCache(parameters: nil) + let session = CachedSession(tokenIds: [], kvCache: cache, lastUsed: Date()) + sessions.append(session) + let status = CacheStatus.miss(totalTokens: tokens.count, sessionsCount: sessions.count) + recordRequest(hit: false, prefillTokens: tokens.count, reusedTokens: 0) + return (cache, tokens, status, session.id) + } + + /// Save token state after generation completes. + func save(sessionId: UUID, tokens: [Int]) { + if let idx = sessions.firstIndex(where: { $0.id == sessionId }) { + sessions[idx].tokenIds = tokens + sessions[idx].lastUsed = Date() + } + } + + private func evictIfNeeded() { + while sessions.count >= maxSessions { + if let oldest = sessions.enumerated().min(by: { $0.element.lastUsed < $1.element.lastUsed }) { + log("Evicting session \(oldest.offset) (\(oldest.element.tokenIds.count) tokens, idle \(Int(-oldest.element.lastUsed.timeIntervalSinceNow))s)") + sessions.remove(at: oldest.offset) + } + } + } + + /// Evict idle sessions, keeping at most `keep` sessions. + func evictIdle(keep: Int) { + while sessions.count > keep { + if let oldest = sessions.enumerated().min(by: { $0.element.lastUsed < $1.element.lastUsed }) { + log("Memory pressure eviction: session \(oldest.offset) (\(oldest.element.tokenIds.count) tokens)") + sessions.remove(at: oldest.offset) + metrics.evictions += 1 + } + } + } + + /// Flush all cached sessions (e.g., on model change or critical memory pressure) + func flush() { + let count = sessions.count + sessions.removeAll() + metrics.evictions += count + log("Flushed all \(count) cached sessions") + } + + private func commonPrefix(_ a: [Int], _ b: [Int]) -> Int { + let maxLen = min(a.count, b.count) + for i in 0..] = [] + // Prefill semaphore: only one slot prefills at a time to avoid GPU contention + private var prefillBusy = false + private var prefillWaiters: [CheckedContinuation] = [] + + init(slotCount: Int) { + self.slotCount = slotCount + var s: [ServerSlot] = [] + for i in 0.. ServerSlot { + if let slot = slots.first(where: { $0.state == .idle }) { + slot.state = .prefilling + return slot + } + // All slots busy -- queue the caller + return await withCheckedContinuation { cont in + slotWaiters.append(cont) + } + } + + /// Try to acquire a slot without waiting. Returns nil if all busy (for 503 responses). + func tryAcquireSlot() -> ServerSlot? { + if let slot = slots.first(where: { $0.state == .idle }) { + slot.state = .prefilling + return slot + } + return nil + } + + /// Release a slot back to idle and wake the next queued waiter, if any. + func releaseSlot(_ slot: ServerSlot) { + slot.reset() + if let waiter = slotWaiters.first { + slotWaiters.removeFirst() + slot.state = .prefilling + waiter.resume(returning: slot) + } + } + + /// Get a snapshot of all slot states for the /slots endpoint. + func slotStatus() -> [(id: Int, state: String, requestId: String, promptTokens: Int, genTokens: Int, elapsed: Double)] { + slots.map { slot in + let elapsed = slot.state == .idle ? 0 : CFAbsoluteTimeGetCurrent() - slot.startTime + return (id: slot.id, state: slot.state.rawValue, requestId: slot.requestId, + promptTokens: slot.promptTokenCount, genTokens: slot.generationTokenCount, + elapsed: elapsed) + } + } + + /// Count of active (non-idle) slots. + func activeSlotCount() -> Int { + slots.filter { $0.state != .idle }.count + } + + /// Number of requests waiting in the queue. + func queueDepth() -> Int { + slotWaiters.count + } +} + +final class SimpleHTTPServer { + let port: UInt16 + let container: ModelContainer + let modelId: String + let promptCache: ServerPromptCache + let slotManager: SlotManager + let slotCount: Int + private var serverSocket: Int32 = -1 + private var memoryPressureSource: DispatchSourceMemoryPressure? + static let maxBodySize = 10 * 1024 * 1024 + + /// Compute max sessions based on available physical memory. + /// Conservative: assume ~1.5GB per cached session (14K tokens FP16 KV for 30B MoE). + static func autoMaxSessions() -> Int { + let totalGB = Double(ProcessInfo.processInfo.physicalMemory) / (1024 * 1024 * 1024) + // Reserve 20GB for model + OS, then ~1.5GB per session + let available = max(totalGB - 20, 2) + let sessions = Int(available / 1.5) + return max(2, min(sessions, 10)) // clamp 2-10 + } + + init(port: UInt16, container: ModelContainer, modelId: String, slotCount: Int = 4) { + self.port = port + self.container = container + self.modelId = modelId + self.slotCount = slotCount + let maxSess = SimpleHTTPServer.autoMaxSessions() + self.promptCache = ServerPromptCache(maxSessions: maxSess) + self.slotManager = SlotManager(slotCount: slotCount) + log("Auto-configured: \(maxSess) max cached sessions (\(ProcessInfo.processInfo.physicalMemory / (1024*1024*1024))GB RAM)") + log("Parallel inference slots: \(slotCount)") + } + + func start() throws { + serverSocket = socket(AF_INET, SOCK_STREAM, 0) + guard serverSocket >= 0 else { throw ServerError.socketCreation } + + var opt: Int32 = 1 + setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &opt, socklen_t(MemoryLayout.size)) + + var addr = sockaddr_in() + addr.sin_family = sa_family_t(AF_INET) + addr.sin_port = port.bigEndian + addr.sin_addr.s_addr = INADDR_ANY + + let bindResult = withUnsafePointer(to: &addr) { ptr in + ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(serverSocket, $0, socklen_t(MemoryLayout.size)) } + } + guard bindResult == 0 else { throw ServerError.bind(port) } + + guard listen(serverSocket, 64) == 0 else { throw ServerError.listen } + + log("Listening on http://127.0.0.1:\(port)") + log("Endpoints: GET /v1/models, POST /v1/chat/completions, GET /tokenizer_info, POST /tokenize, GET /metrics, GET /slots") + + // Monitor macOS memory pressure — evict idle sessions under pressure + let source = DispatchSource.makeMemoryPressureSource( + eventMask: [.warning, .critical], queue: .global()) + source.setEventHandler { [promptCache] in + Task { + let event = source.data + if event.contains(.critical) { + log("MEMORY PRESSURE: critical — flushing all cached sessions") + await promptCache.flush() + } else if event.contains(.warning) { + log("MEMORY PRESSURE: warning — evicting idle sessions") + await promptCache.evictIdle(keep: 1) + } + } + } + source.resume() + memoryPressureSource = source + + while true { + let client = accept(serverSocket, nil, nil) + guard client >= 0 else { continue } + Task { await handleClient(client) } + } + } + + func handleClient(_ fd: Int32) async { + defer { close(fd) } + + let requestStart = CFAbsoluteTimeGetCurrent() + var method = "?" + var path = "?" + var originHeader: String? = nil + + do { + // Read headers first + var headerData = Data() + var byte: UInt8 = 0 + while headerData.count < 65536 { + let n = read(fd, &byte, 1) + guard n == 1 else { return } + headerData.append(byte) + // Detect end of headers: \r\n\r\n + if headerData.count >= 4 && + headerData[headerData.count-4] == 0x0D && headerData[headerData.count-3] == 0x0A && + headerData[headerData.count-2] == 0x0D && headerData[headerData.count-1] == 0x0A { + break + } + } + + let headerStr = String(data: headerData, encoding: .utf8) ?? "" + let lines = headerStr.split(separator: "\r\n", omittingEmptySubsequences: false) + guard let firstLine = lines.first else { return } + + let parts = firstLine.split(separator: " ") + guard parts.count >= 2 else { return } + method = String(parts[0]) + path = String(parts[1]).split(separator: "?").first.map(String.init) ?? String(parts[1]) + + // Parse Content-Length, Origin header, and read body + var contentLength = 0 + for line in lines { + let lower = line.lowercased() + if lower.hasPrefix("content-length:") { + contentLength = Int(lower.dropFirst(15).trimmingCharacters(in: .whitespaces)) ?? 0 + } + if lower.hasPrefix("origin:") { + originHeader = String(line.dropFirst(7)).trimmingCharacters(in: .whitespaces) + } + } + let corsOrigin = originHeader ?? "*" + + // Enforce max body size (10MB) + if contentLength > SimpleHTTPServer.maxBodySize { + log("\(method) \(path) — body too large (\(contentLength) bytes)") + sendResponse(fd: fd, status: 413, + body: "{\"error\":{\"message\":\"request body too large (max \(SimpleHTTPServer.maxBodySize / 1024 / 1024)MB)\",\"type\":\"invalid_request_error\",\"code\":413}}", + contentType: "application/json; charset=utf-8", corsOrigin: corsOrigin) + return + } + + var bodyData = Data() + if contentLength > 0 { + bodyData.reserveCapacity(contentLength) + var remaining = contentLength + var buf = [UInt8](repeating: 0, count: min(remaining, 65536)) + while remaining > 0 { + let toRead = min(remaining, buf.count) + let n = read(fd, &buf, toRead) + guard n > 0 else { break } + bodyData.append(contentsOf: buf[0.. any Sendable { + if let s = v as? String { return s } + if let n = v as? Int { return n } + if let b = v as? Bool { return b } + if let d = v as? Double { return d } + if let arr = v as? [Any] { return arr.map { convert($0) } as [any Sendable] } + if let dict = v as? [String: Any] { + return dict.mapValues { convert($0) } as [String: any Sendable] + } + return String(describing: v) + } + return tool.mapValues { convert($0) } as [String: any Sendable] + } + // Try with tools first; fall back to without if template doesn't support them + do { + let thinkCtx: [String: any Sendable] = ["enable_thinking": true] + tokens = try ctx.tokenizer.applyChatTemplate(messages: messages, tools: toolSpecs, additionalContext: thinkCtx) + } catch { + log("Chat template with tools failed (\(error)), retrying without tools") + // Inject tool descriptions into system prompt instead + var toolDesc = "Available tools:\n" + for tool in toolSpecs { + if let fn = tool["function"] as? [String: Any], + let name = fn["name"] as? String { + let desc = fn["description"] as? String ?? "" + toolDesc += "- \(name): \(desc)\n" + } + } + if var sys = messages.first, sys["role"] == "system" { + sys["content"] = (sys["content"] ?? "") + "\n\n" + toolDesc + var adjusted = messages + adjusted[0] = sys + tokens = try ctx.tokenizer.applyChatTemplate(messages: adjusted) + } else { + var adjusted = messages + adjusted.insert(["role": "system", "content": toolDesc], at: 0) + tokens = try ctx.tokenizer.applyChatTemplate(messages: adjusted) + } + } + } else { + // Pass enable_thinking for models that support it (Qwen3, etc.) + let thinkingContext: [String: any Sendable] = ["enable_thinking": true] + tokens = try ctx.tokenizer.applyChatTemplate(messages: messages, tools: nil, additionalContext: thinkingContext) + } + // Prompt caching: reuse KV state from previous requests + let prefillStart = CFAbsoluteTimeGetCurrent() + let (reusedCache, newTokens, cacheStatus, sessionId) = await promptCache.fetch(tokens: tokens, model: ctx.model) + let tokenArray = MLXArray(newTokens.isEmpty ? tokens : newTokens) + let input = LMInput(text: LMInput.Text(tokens: tokenArray)) + + var params = GenerateParameters(temperature: request.temperature ?? 0.6) + if let maxTokens = request.max_tokens { + params.maxTokens = maxTokens + } + + // Set tool call format if tools are present + if toolsAny != nil { + ctx.configuration.toolCallFormat = .xmlFunction + } + + slot.promptTokenCount = tokens.count + slot.state = .generating + log("slot[\(slot.id)] \(cacheStatus.logString) prefill=\(newTokens.count) stream=\(isStreaming) tools=\(toolsAny?.count ?? 0)") + + // Always send keepalives for streaming to prevent client ReadTimeout + // during prefill (bridge init + forward pass can take 10-100s for MoE models) + // Keepalive timer: sends real SSE data chunks every 2s during prefill + // to prevent client ReadTimeout. Uses GCD (not async Task) because + // generate() blocks the cooperative thread pool during GPU inference. + var keepaliveTimer: DispatchSourceTimer? = nil + if isStreaming { + let header = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream; charset=utf-8\r\nCache-Control: no-cache\r\nConnection: keep-alive\r\nAccess-Control-Allow-Origin: \(corsOrigin)\r\nAccess-Control-Allow-Credentials: true\r\n\r\n" + _ = header.withCString { write(fd, $0, Int(strlen($0))) } + + let timer = DispatchSource.makeTimerSource(queue: .global()) + let keepaliveFd = fd + timer.schedule(deadline: .now() + 2, repeating: 2.0) + timer.setEventHandler { + let chunk = "data: {\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":null}]}\n\n" + _ = chunk.withCString { write(keepaliveFd, $0, Int(strlen($0))) } + } + timer.resume() + keepaliveTimer = timer + } + + if isStreaming { + var prefillDone = false + + let reqModel = request.model + var hadToolCall = false + // Send role chunk immediately so client knows we're alive (content:null per OpenAI spec) + writeSSE(fd: fd, requestId: requestId, role: "assistant", content: nil, finishReason: nil, requestModel: reqModel, includeNullContent: true) + // Flush immediately + _ = "".withCString { _ in fcntl(fd, F_FULLFSYNC) } + + do { + // Accumulate ALL text, parse tool calls at the end. + // Streaming text is emitted in real-time UNLESS we detect the + // start of a tool call, at which point we buffer until complete. + // For thinking models: send content as reasoning_content delta. + var fullText = "" + var thinkText = "" // accumulated think block content + var emittedUpTo = 0 // index in fullText that we've already sent + var inThinkBlock = false + + var tokenCount = 0 + for try await generation in try generate( + input: input, cache: reusedCache, parameters: params, context: ctx + ) { + if !prefillDone { + prefillDone = true + keepaliveTimer?.cancel() + await releasePrefillOnce() + log(" first token arrived, prefill done") + } + tokenCount += 1 + + switch generation { + case .chunk(let text): + fullText += text + if tokenCount <= 3 || tokenCount % 50 == 0 { + log(" chunk[\(tokenCount)]: +\(text.count)ch fullText=\(fullText.count)ch emitted=\(emittedUpTo) think=\(inThinkBlock)") + } + + // Handle ... blocks from thinking models. + // Handles ... and bare (opening consumed by template). + // Must run before tool-call holdback to avoid `<` in being buffered. + if emittedUpTo == 0 && !inThinkBlock { + // Check if response starts with thinking content + let trimmed = fullText.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.hasPrefix("") { + log(" think block ended, fullText=\(fullText.count)ch") + if let range = fullText.range(of: "") { + // Extract think content (strip the tag itself) + var thinkContent = String(fullText[..") { + thinkContent = String(thinkContent[tagEnd.upperBound...]) + } + // Send any remaining think content as reasoning_content + let newThink = thinkContent.count > thinkText.count ? String(thinkContent[thinkContent.index(thinkContent.startIndex, offsetBy: thinkText.count)...]) : "" + if !newThink.isEmpty { + writeSSE(fd: fd, requestId: requestId, role: nil, content: nil, finishReason: nil, reasoningContent: newThink, requestModel: reqModel) + } + thinkText = thinkContent + + let afterThink = String(fullText[range.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines) + fullText = afterThink + emittedUpTo = 0 + inThinkBlock = false + if fullText.isEmpty { continue } + } + } else { + // Still in think block -- stream as reasoning_content + // Extract think content so far (strip tag) + var thinkContent = fullText + if let tagEnd = thinkContent.range(of: "") { + thinkContent = String(thinkContent[tagEnd.upperBound...]) + } + // Send only new think tokens + let newThink = thinkContent.count > thinkText.count ? String(thinkContent[thinkContent.index(thinkContent.startIndex, offsetBy: thinkText.count)...]) : "" + if !newThink.isEmpty { + writeSSE(fd: fd, requestId: requestId, role: nil, content: nil, finishReason: nil, reasoningContent: newThink, requestModel: reqModel) + thinkText = thinkContent + } + continue + } + } + + // After tool calls, suppress any trailing XML tags + if hadToolCall { + // Strip any remaining XML closing tags from post-tool-call text + let remaining = String(fullText[fullText.index(fullText.startIndex, offsetBy: emittedUpTo)...]) + let stripped = remaining + .replacingOccurrences(of: "", with: "") + .replacingOccurrences(of: "", with: "") + .replacingOccurrences(of: "", with: "") + .trimmingCharacters(in: .whitespacesAndNewlines) + if stripped.isEmpty { + emittedUpTo = fullText.count + continue + } + } + + // Skip leading whitespace after think-block removal + if emittedUpTo == 0 && !fullText.isEmpty { + let trimmed = fullText.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { continue } + if trimmed.count < fullText.count { + fullText = trimmed + } + } + + // Check if there's a potential tool call starting in the un-emitted portion + let unemitted = String(fullText[fullText.index(fullText.startIndex, offsetBy: emittedUpTo)...]) + + if unemitted.contains("") || unemitted.contains("") || unemitted.contains("") || unemitted.contains("") || unemitted.contains("") || unemitted.contains("") { + // Complete tool call — parse and emit + let tcs = parseAllToolCalls(unemitted) + if !tcs.isEmpty { + hadToolCall = true + for tc in tcs { + emitToolCallSSE(fd: fd, requestId: requestId, name: tc.name, arguments: tc.arguments, requestModel: reqModel) + } + } else { + writeSSE(fd: fd, requestId: requestId, role: nil, content: unemitted, finishReason: nil, requestModel: reqModel) + } + emittedUpTo = fullText.count + } + // Incomplete — keep buffering, don't emit + } else if unemitted.contains("<") { + // Hold back only if `<` looks like start of a known tag. + // Don't hold back for comparison operators (x < y) or random `<`. + let tagPrefixes = [" 0 { log(" fullText preview: \(String(fullText.prefix(400)))") } + if hadToolCall { log(" hadToolCall=true, unemitted=\(fullText.count - emittedUpTo)ch") } + // Flush any remaining buffered text + if emittedUpTo < fullText.count { + let remaining = String(fullText[fullText.index(fullText.startIndex, offsetBy: emittedUpTo)...]) + let remainTCs = parseAllToolCalls(remaining) + if !remainTCs.isEmpty { + hadToolCall = true + for tc in remainTCs { + emitToolCallSSE(fd: fd, requestId: requestId, name: tc.name, arguments: tc.arguments, requestModel: reqModel) + } + } else if !remaining.isEmpty { + writeSSE(fd: fd, requestId: requestId, role: nil, content: remaining, finishReason: nil, requestModel: reqModel) + } + } + let maxTok = request.max_tokens ?? Int.max + let fr = hadToolCall ? "tool_calls" : (info.generationTokenCount >= maxTok ? "length" : "stop") + let responseModel = reqModel ?? modelId + let usageJSON = ",\"usage\":{\"prompt_tokens\":\(info.promptTokenCount),\"completion_tokens\":\(info.generationTokenCount),\"total_tokens\":\(info.promptTokenCount + info.generationTokenCount)}" + let finalEvent = "data: {\"id\":\"\(requestId)\",\"object\":\"chat.completion.chunk\",\"created\":\(Int(Date().timeIntervalSince1970)),\"model\":\"\(responseModel)\",\"system_fingerprint\":\"mlx-swift-v1\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"\(fr)\"}]\(usageJSON)}\n\ndata: [DONE]\n\n" + _ = finalEvent.withCString { write(fd, $0, Int(strlen($0))) } + } + } + } catch { + await releasePrefillOnce() + // Generation error during streaming — send error SSE event and close cleanly + log("ERROR during streaming generation: \(error)") + let errMsg = error.localizedDescription.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + let errEvent = "data: {\"error\":{\"message\":\"\(errMsg)\",\"type\":\"server_error\",\"code\":500}}\n\ndata: [DONE]\n\n" + _ = errEvent.withCString { write(fd, $0, Int(strlen($0))) } + } + // Record timing and save cache + let elapsed = (CFAbsoluteTimeGetCurrent() - prefillStart) * 1000 + await promptCache.recordTiming(prefillMs: 0, decodeMs: elapsed, decodeTokens: 0) + await promptCache.save(sessionId: sessionId, tokens: tokens) + } else { + keepaliveTimer?.cancel() + + // Non-streaming: collect all text + var fullText = "" + var completionTokens = 0 + var toolCalls: [(name: String, args: String)] = [] + for try await generation in try generate( + input: input, cache: reusedCache, parameters: params, context: ctx + ) { + if !prefillReleased { await releasePrefillOnce() } + switch generation { + case .chunk(let text): + fullText += text + completionTokens += 1 + case .toolCall(let tc): + let argsDict = tc.function.arguments.mapValues { $0.anyValue } + let argsJSON = (try? JSONSerialization.data(withJSONObject: argsDict)) ?? Data() + toolCalls.append((name: tc.function.name, args: String(data: argsJSON, encoding: .utf8) ?? "{}")) + default: break + } + } + + // Strip ... blocks from thinking models, preserving as reasoning_content + log(" non-streaming fullText (\(fullText.count)ch): \(String(fullText.prefix(400)))") + log(" non-streaming fullText repr: \(fullText.debugDescription.prefix(400))") + var reasoningContent: String? = nil + if let thinkEnd = fullText.range(of: "") { + var thinkContent = String(fullText[..") { + thinkContent = String(thinkContent[tagEnd.upperBound...]) + } + reasoningContent = thinkContent.trimmingCharacters(in: .whitespacesAndNewlines) + fullText = String(fullText[thinkEnd.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines) + } else if fullText.hasPrefix("") { + // Incomplete think block -- strip it entirely, still save as reasoning + var thinkContent = fullText + if let tagEnd = thinkContent.range(of: "") { + thinkContent = String(thinkContent[tagEnd.upperBound...]) + } + reasoningContent = thinkContent.trimmingCharacters(in: .whitespacesAndNewlines) + if reasoningContent?.isEmpty == true { reasoningContent = nil } + fullText = "" + } + + // Parse tool calls from accumulated text (MiniMax XML, , etc.) + // These come through as .chunk text, not .toolCall events + if toolCalls.isEmpty { + let parsed = parseAllToolCalls(fullText) + if !parsed.isEmpty { + for tc in parsed { + toolCalls.append((name: tc.name, args: tc.arguments)) + } + fullText = "" // tool call consumed the text + } + } + + // Echo request model name if provided, otherwise use local modelId + let responseModel = request.model ?? modelId + + // Build response with tool_calls if present + let maxTok = request.max_tokens ?? Int.max + let finishReason: String + if !toolCalls.isEmpty { + finishReason = "tool_calls" + } else if completionTokens >= maxTok { + finishReason = "length" + } else { + finishReason = "stop" + } + var responseBody: String + if toolCalls.isEmpty { + let response = ChatResponse( + id: requestId, object: "chat.completion", + created: Int(Date().timeIntervalSince1970), model: responseModel, + system_fingerprint: "mlx-swift-v1", + choices: [.init(index: 0, message: .init(role: "assistant", content: fullText, reasoning_content: reasoningContent), + delta: nil, finish_reason: finishReason)], + usage: .init(prompt_tokens: tokens.count, completion_tokens: completionTokens, + total_tokens: tokens.count + completionTokens)) + responseBody = String(data: try JSONEncoder().encode(response), encoding: .utf8)! + } else { + // Build tool_calls response manually (ChatResponse doesn't have tool_calls field) + let tcJSON = toolCalls.enumerated().map { (i, tc) in + "{\"id\":\"call_\(UUID().uuidString.prefix(8))\",\"type\":\"function\",\"function\":{\"name\":\"\(tc.name)\",\"arguments\":\(tc.args)}}" + }.joined(separator: ",") + let content = "\"\(fullText.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"").replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\r", with: "\\r"))\"" + let rcField: String + if let rc = reasoningContent { + let rcEscaped = rc.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"").replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\r", with: "\\r") + rcField = ",\"reasoning_content\":\"\(rcEscaped)\"" + } else { + rcField = "" + } + responseBody = "{\"id\":\"\(requestId)\",\"object\":\"chat.completion\",\"created\":\(Int(Date().timeIntervalSince1970)),\"model\":\"\(responseModel)\",\"system_fingerprint\":\"mlx-swift-v1\",\"choices\":[{\"index\":0,\"message\":{\"role\":\"assistant\",\"content\":\(content)\(rcField),\"tool_calls\":[\(tcJSON)]},\"finish_reason\":\"\(finishReason)\"}],\"usage\":{\"prompt_tokens\":\(tokens.count),\"completion_tokens\":\(completionTokens),\"total_tokens\":\(tokens.count + completionTokens)}}" + } + sendResponse(fd: fd, status: 200, body: responseBody, + contentType: "application/json; charset=utf-8", corsOrigin: corsOrigin) + // Record timing and save cache + let elapsed = (CFAbsoluteTimeGetCurrent() - prefillStart) * 1000 + await promptCache.recordTiming(prefillMs: 0, decodeMs: elapsed, decodeTokens: 0) + await promptCache.save(sessionId: sessionId, tokens: tokens) + } + } catch { + log("ERROR in handleChat: \(error)") + let errMsg = error.localizedDescription.replacingOccurrences(of: "\"", with: "'") + let err = "{\"error\":{\"message\":\"\(errMsg)\",\"type\":\"server_error\",\"code\":500}}" + sendResponse(fd: fd, status: 500, body: err, contentType: "application/json; charset=utf-8", corsOrigin: corsOrigin) + } + } + + func handleCompletions(fd: Int32, prompt: String, maxTokens: Int, temperature: Float, stream: Bool, corsOrigin: String = "*") async { + let requestId = "cmpl-\(UUID().uuidString.prefix(8))" + + // Acquire an inference slot (shared pool with chat completions) + let slot = await slotManager.acquireSlot() + slot.requestId = requestId + slot.startTime = CFAbsoluteTimeGetCurrent() + slot.state = .generating + log("slot[\(slot.id)] acquired for \(requestId) (completions)") + defer { Task { await slotManager.releaseSlot(slot) } } + + do { + let ctx = await container.perform { ctx in ctx } + let tokens = ctx.tokenizer.encode(text: prompt) + let tokenArray = MLXArray(tokens) + let input = LMInput(text: LMInput.Text(tokens: tokenArray)) + + var params = GenerateParameters(temperature: temperature) + params.maxTokens = maxTokens + + log("completions: \(tokens.count) prompt tokens, max_tokens=\(maxTokens), stream=\(stream)") + + if stream { + let header = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream; charset=utf-8\r\nCache-Control: no-cache\r\nConnection: keep-alive\r\nAccess-Control-Allow-Origin: \(corsOrigin)\r\nAccess-Control-Allow-Credentials: true\r\n\r\n" + _ = header.withCString { write(fd, $0, Int(strlen($0))) } + + let result = try await container.generate(input: input, parameters: params) + for try await event in result { + if let chunk = event.chunk { + let escaped = chunk.replacingOccurrences(of: "\\", with: "\\\\") + .replacingOccurrences(of: "\"", with: "\\\"") + .replacingOccurrences(of: "\n", with: "\\n") + let sseData = "{\"id\":\"\(requestId)\",\"object\":\"text_completion\",\"choices\":[{\"index\":0,\"text\":\"\(escaped)\",\"finish_reason\":null}]}" + let sse = "data: \(sseData)\n\n" + _ = sse.withCString { write(fd, $0, Int(strlen($0))) } + } + if event.info != nil { + let sseData = "{\"id\":\"\(requestId)\",\"object\":\"text_completion\",\"choices\":[{\"index\":0,\"text\":\"\",\"finish_reason\":\"stop\"}]}" + let sse = "data: \(sseData)\n\ndata: [DONE]\n\n" + _ = sse.withCString { write(fd, $0, Int(strlen($0))) } + } + } + } else { + var fullText = "" + let result = try await container.generate(input: input, parameters: params) + var usage: (prompt: Int, completion: Int) = (tokens.count, 0) + for try await event in result { + if let chunk = event.chunk { fullText += chunk; usage.completion += 1 } + } + let escaped = fullText.replacingOccurrences(of: "\\", with: "\\\\") + .replacingOccurrences(of: "\"", with: "\\\"") + .replacingOccurrences(of: "\n", with: "\\n") + let body = "{\"id\":\"\(requestId)\",\"object\":\"text_completion\",\"model\":\"\(modelId)\",\"choices\":[{\"index\":0,\"text\":\"\(escaped)\",\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":\(usage.prompt),\"completion_tokens\":\(usage.completion),\"total_tokens\":\(usage.prompt + usage.completion)}}" + sendResponse(fd: fd, status: 200, body: body, contentType: "application/json; charset=utf-8", corsOrigin: corsOrigin) + } + } catch { + let errMsg = String(describing: error).replacingOccurrences(of: "\"", with: "'") + sendResponse(fd: fd, status: 500, body: "{\"error\":{\"message\":\"\(errMsg)\",\"type\":\"server_error\",\"code\":500}}", contentType: "application/json; charset=utf-8", corsOrigin: corsOrigin) + } + } + + /// Parse XML tool call from text: value + /// Handles both ...... and bare + /// Parse ALL tool calls from text. Returns array of (name, arguments). + func parseAllToolCalls(_ text: String) -> [(name: String, arguments: String)] { + // Try MiniMax format first (can have multiple blocks) + let minimax = parseAllMiniMaxToolCalls(text) + if !minimax.isEmpty { return minimax } + // Fall back to single generic parse + if let tc = parseToolCallXML(text) { return [tc] } + return [] + } + + func parseToolCallXML(_ text: String) -> (name: String, arguments: String)? { + // Try MiniMax format: value + let all = parseAllMiniMaxToolCalls(text) + if let first = all.first { return first } + + // Try generic format: value + guard let funcStart = text.range(of: "", range: funcStart.upperBound..", range: paramStart.upperBound..", range: pNameEnd.upperBound..ls -la + /// Parse ALL blocks from a MiniMax tool call (supports multiple tools in one response) + func parseAllMiniMaxToolCalls(_ text: String) -> [(name: String, arguments: String)] { + guard text.contains("... blocks + var searchStart = text.startIndex + while let invokeStart = text.range(of: "", range: invokeStart.upperBound.. but no and outputs parameters directly + if results.isEmpty && text.contains("") else { break } + let paramName = String(afterParam[afterParam.startIndex..", range: valueStart.. tag)") + } + } + + return results + } + + /// Parse a single ... block + func parseSingleMiniMaxInvoke(_ text: String) -> (name: String, arguments: String)? { + guard let invokeStart = text.range(of: "") else { break } + let paramName = String(afterParam[afterParam.startIndex..", range: valueStart.. (name: String, arguments: String)? { + guard text.contains("") || text.contains(" + guard let invokeStart = text.range(of: "value + var args: [String: String] = [:] + var search = nameEnd.upperBound + while let paramStart = text.range(of: "") else { break } + let paramName = String(afterParam[afterParam.startIndex..", range: valueStart.. String { + s.replacingOccurrences(of: "\\", with: "\\\\") + .replacingOccurrences(of: "\"", with: "\\\"") + .replacingOccurrences(of: "\n", with: "\\n") + .replacingOccurrences(of: "\r", with: "\\r") + } + var parts: [String] = [] + if let role = role { parts.append("\"role\":\"\(escape(role))\"") } + if let content = content { + parts.append("\"content\":\"\(escape(content))\"") + } else if includeNullContent { + parts.append("\"content\":null") + } + if let rc = reasoningContent { parts.append("\"reasoning_content\":\"\(escape(rc))\"") } + let deltaJson = "{\(parts.joined(separator: ","))}" + + let fr = finishReason.map { "\"\($0)\"" } ?? "null" + let responseModel = requestModel ?? modelId + let event = "data: {\"id\":\"\(requestId)\",\"object\":\"chat.completion.chunk\",\"created\":\(Int(Date().timeIntervalSince1970)),\"model\":\"\(responseModel)\",\"system_fingerprint\":\"mlx-swift-v1\",\"choices\":[{\"index\":0,\"delta\":\(deltaJson),\"finish_reason\":\(fr)}]}\n\n" + _ = event.withCString { write(fd, $0, Int(strlen($0))) } + } + + func sendResponse(fd: Int32, status: Int, body: String, contentType: String, extraHeaders: String = "", corsOrigin: String = "*") { + let statusText: String + switch status { + case 200: statusText = "OK" + case 204: statusText = "No Content" + case 400: statusText = "Bad Request" + case 413: statusText = "Payload Too Large" + case 404: statusText = "Not Found" + case 500: statusText = "Internal Server Error" + case 503: statusText = "Service Unavailable" + default: statusText = "Unknown" + } + let response = "HTTP/1.1 \(status) \(statusText)\r\nContent-Type: \(contentType)\r\nContent-Length: \(body.utf8.count)\r\nAccess-Control-Allow-Origin: \(corsOrigin)\r\nAccess-Control-Allow-Credentials: true\r\n\(extraHeaders)\r\n\(body)" + _ = response.withCString { write(fd, $0, Int(strlen($0))) } + } + + enum ServerError: Error { + case socketCreation, bind(UInt16), listen + } +} + +// MARK: - Entry Point + +@main +struct MLXServerApp { + @MainActor + static func main() async throws { + // Ignore SIGPIPE -- client disconnects during streaming should not crash the server + signal(SIGPIPE, SIG_IGN) + + let args = CommandLine.arguments + let model = args.firstIndex(of: "--model").flatMap { i in + i + 1 < args.count ? args[i + 1] : nil + } ?? "mlx-community/gemma-4-e2b-it-4bit" + + let port = args.firstIndex(of: "--port").flatMap { i in + i + 1 < args.count ? UInt16(args[i + 1]) : nil + } ?? 8080 + + let slots = args.firstIndex(of: "--slots").flatMap { i in + i + 1 < args.count ? Int(args[i + 1]) : nil + } ?? 4 // Default to 4 parallel slots (like llama-server) + + log("Loading model: \(model)") + let config: ModelConfiguration + if model.hasPrefix("/") || model.hasPrefix("~") || model.hasPrefix(".") { + // Local path + let expandedPath = NSString(string: model).expandingTildeInPath + config = ModelConfiguration(directory: URL(fileURLWithPath: expandedPath)) + } else { + // HuggingFace model ID + config = ModelConfiguration(id: model) + } + // Try LLM first, fall back to VLM (for Qwen3-VL, Gemma4-VL, etc.) + let container: ModelContainer + do { + container = try await LLMModelFactory.shared.loadContainer( + configuration: config) { p in + if p.fractionCompleted > 0.99 { log("Model loaded (LLM)") } + } + } catch { + log("LLM load failed (\(error)), trying VLM...") + container = try await VLMModelFactory.shared.loadContainer( + configuration: config) { p in + if p.fractionCompleted > 0.99 { log("Model loaded (VLM)") } + } + } + + let server = SimpleHTTPServer(port: port, container: container, modelId: model, slotCount: slots) + try server.start() + } +} diff --git a/Sources/MLXServer/test_cache.py b/Sources/MLXServer/test_cache.py new file mode 100644 index 0000000000..9edb3aa3e3 --- /dev/null +++ b/Sources/MLXServer/test_cache.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +""" +Server prompt cache test suite. +Tests multi-session caching, prefix reuse, eviction, and interleaving. +Requires MLXServer running on localhost:8080. +""" +import json +import time +import urllib.request +import sys + +URL = "http://127.0.0.1:8080/v1/chat/completions" +PASS = 0 +FAIL = 0 + +def req(messages, tools=None, max_tokens=5, stream=False): + """Send a request and return (response_dict, elapsed_ms).""" + body = {"model": "test", "messages": messages, "max_tokens": max_tokens, "stream": stream} + if tools: + body["tools"] = tools + data = json.dumps(body).encode() + t0 = time.time() + r = urllib.request.Request(URL, data=data, headers={"Content-Type": "application/json"}) + resp = urllib.request.urlopen(r, timeout=60) + elapsed = (time.time() - t0) * 1000 + result = json.loads(resp.read().decode()) + return result, elapsed + +def check(name, condition, detail=""): + global PASS, FAIL + if condition: + PASS += 1 + print(f" ✓ {name}") + else: + FAIL += 1 + print(f" ✗ {name} — {detail}") + +def test_basic_cache_hit(): + """Same system prompt, different user message → prefix reuse.""" + print("\n=== Test: Basic Cache Hit ===") + sys_msg = "You are a helpful assistant who answers briefly." + + _, t1 = req([{"role": "system", "content": sys_msg}, {"role": "user", "content": "hi"}]) + _, t2 = req([{"role": "system", "content": sys_msg}, {"role": "user", "content": "what is 2+2"}]) + + check("Second request faster", t2 < t1 * 0.8, f"t1={t1:.0f}ms t2={t2:.0f}ms") + check("Second request under 200ms", t2 < 200, f"t2={t2:.0f}ms") + +def test_cache_miss(): + """Completely different system prompt → cache miss.""" + print("\n=== Test: Cache Miss ===") + + _, t1 = req([{"role": "system", "content": "You are a pirate captain."}, {"role": "user", "content": "ahoy"}]) + _, t2 = req([{"role": "system", "content": "You are a space explorer."}, {"role": "user", "content": "greetings"}]) + + # Both should be similar speed (both cold) + check("Both requests take similar time", abs(t1 - t2) < t1 * 0.5, f"t1={t1:.0f}ms t2={t2:.0f}ms") + +def test_session_interleave(): + """Alternating between two sessions → both get cache hits.""" + print("\n=== Test: Session Interleave ===") + sys_a = "You are assistant Alpha. Always start with 'Alpha here.'" + sys_b = "You are assistant Beta. Always start with 'Beta here.'" + + # Cold start both sessions + _, ta1 = req([{"role": "system", "content": sys_a}, {"role": "user", "content": "hello"}]) + _, tb1 = req([{"role": "system", "content": sys_b}, {"role": "user", "content": "hello"}]) + + # Return to session A + _, ta2 = req([{"role": "system", "content": sys_a}, {"role": "user", "content": "what time is it"}]) + # Return to session B + _, tb2 = req([{"role": "system", "content": sys_b}, {"role": "user", "content": "what day is it"}]) + + # With KV deep copy, returning to a previous session gets a full prefix hit + check("Session A return is cached (KV copy)", ta2 < ta1 * 0.9, f"ta1={ta1:.0f}ms ta2={ta2:.0f}ms") + check("Session B return is cached (KV copy)", tb2 < tb1 * 0.9, f"tb1={tb1:.0f}ms tb2={tb2:.0f}ms") + +def test_conversation_growth(): + """Growing conversation → each turn reuses previous prefix.""" + print("\n=== Test: Conversation Growth ===") + sys = "You are helpful." + msgs = [{"role": "system", "content": sys}] + + times = [] + for i, user_msg in enumerate(["hi", "what is 2+2", "and 3+3", "what about 4+4"]): + msgs.append({"role": "user", "content": user_msg}) + result, t = req(msgs, max_tokens=10) + content = result["choices"][0]["message"]["content"] + msgs.append({"role": "assistant", "content": content}) + times.append(t) + + # Turn 2 reuses system prompt prefix; with small prompts the difference is subtle + check("Turn 2 not dramatically slower than turn 1", times[1] < times[0] * 1.5, f"t1={times[0]:.0f}ms t2={times[1]:.0f}ms") + check("Turn 4 not much slower than turn 2", times[3] < times[1] * 2, f"t2={times[1]:.0f}ms t4={times[3]:.0f}ms") + +def test_eviction(): + """More sessions than maxSessions → oldest evicted.""" + print("\n=== Test: Eviction (max 3 sessions) ===") + sessions = [ + "You are Alice, a cheerful assistant.", + "You are Bob, a grumpy assistant.", + "You are Carol, a wise assistant.", + "You are Dave, a funny assistant.", + ] + + # Fill 3 sessions + for i, sys in enumerate(sessions[:3]): + req([{"role": "system", "content": sys}, {"role": "user", "content": f"hello {i}"}]) + + # 4th session should evict the oldest (session 0) + req([{"role": "system", "content": sessions[3]}, {"role": "user", "content": "hello 3"}]) + + # Session 1 should still be cached + _, t_cached = req([{"role": "system", "content": sessions[1]}, {"role": "user", "content": "still here?"}]) + + # Session 0 should be evicted (cold) + _, t_evicted = req([{"role": "system", "content": sessions[0]}, {"role": "user", "content": "are you still here?"}]) + + # This is a soft check — both are fast for small prompts, but the pattern should hold + check("Session 1 still cached (not evicted)", t_cached < 300, f"t={t_cached:.0f}ms") + +def test_tool_calls(): + """Tool definitions in prefix → reused across requests.""" + print("\n=== Test: Tool Call Caching ===") + tools = [{"type": "function", "function": {"name": "run_command", "description": "Run a shell command", "parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}}] + sys = "You are a coding assistant." + + _, t1 = req([{"role": "system", "content": sys}, {"role": "user", "content": "list files"}], tools=tools) + _, t2 = req([{"role": "system", "content": sys}, {"role": "user", "content": "show disk usage"}], tools=tools) + + check("Tool request cached", t2 < t1 * 0.8, f"t1={t1:.0f}ms t2={t2:.0f}ms") + +def test_usage_in_response(): + """Response includes usage stats.""" + print("\n=== Test: Usage Stats ===") + result, _ = req([{"role": "user", "content": "hi"}]) + usage = result.get("usage", {}) + check("Has prompt_tokens", "prompt_tokens" in usage, str(usage)) + check("Has completion_tokens", "completion_tokens" in usage, str(usage)) + check("prompt_tokens > 0", usage.get("prompt_tokens", 0) > 0, str(usage)) + +def test_health_endpoint(): + """Health endpoint returns 200 with ok status.""" + print("\n=== Test: Health Endpoint ===") + resp = urllib.request.urlopen("http://127.0.0.1:8080/health", timeout=5) + data = json.loads(resp.read().decode()) + check("Status code 200", resp.status == 200, f"status={resp.status}") + check("Body has status=ok", data.get("status") == "ok", str(data)) + +def test_malformed_request(): + """Malformed JSON body returns 400, not a crash.""" + print("\n=== Test: Malformed Request ===") + bad_bodies = [ + b"not json at all", + b'{"model": "test"}', # missing messages + b'{"messages": "not an array"}', + ] + for i, body in enumerate(bad_bodies): + try: + r = urllib.request.Request(URL, data=body, headers={"Content-Type": "application/json"}) + urllib.request.urlopen(r, timeout=10) + check(f"Bad body {i} rejected", False, "got 200 instead of error") + except urllib.error.HTTPError as e: + check(f"Bad body {i} returns 400", e.code == 400, f"code={e.code}") + except Exception as e: + check(f"Bad body {i} handled", False, str(e)) + +def test_server_survives_bad_request(): + """Server stays alive after a bad request.""" + print("\n=== Test: Server Survives Bad Request ===") + # Send garbage + try: + r = urllib.request.Request(URL, data=b"garbage", headers={"Content-Type": "application/json"}) + urllib.request.urlopen(r, timeout=10) + except: + pass # Expected to fail + + # Now send a good request — server should still work + try: + result, _ = req([{"role": "user", "content": "hi"}]) + has_choices = "choices" in result + check("Good request after bad succeeds", has_choices, str(result)[:100]) + except Exception as e: + check("Good request after bad succeeds", False, str(e)) + +def test_oversized_request(): + """Request body exceeding 10MB returns 413.""" + print("\n=== Test: Oversized Request (413) ===") + # Build a request with Content-Length > 10MB + # We use a socket to send the header without actually sending 10MB of data + import socket + try: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.settimeout(5) + s.connect(("127.0.0.1", 8080)) + # Claim body is 11MB but don't actually send it all + header = ( + "POST /v1/chat/completions HTTP/1.1\r\n" + "Host: 127.0.0.1:8080\r\n" + "Content-Type: application/json\r\n" + "Content-Length: 11534336\r\n" + "\r\n" + ) + s.sendall(header.encode()) + # Read response — server should reject before reading body + resp = b"" + try: + while True: + chunk = s.recv(4096) + if not chunk: + break + resp += chunk + except socket.timeout: + pass + s.close() + resp_str = resp.decode("utf-8", errors="replace") + check("Returns 413", "413" in resp_str, resp_str[:200]) + except Exception as e: + check("Returns 413", False, str(e)) + +def test_auto_session_config(): + """Server auto-configures session count based on RAM.""" + print("\n=== Test: Auto Session Config ===") + resp = urllib.request.urlopen("http://127.0.0.1:8080/metrics", timeout=5) + data = json.loads(resp.read().decode()) + max_sess = data.get("cache", {}).get("sessions_max", 0) + check("sessions_max >= 2", max_sess >= 2, f"max={max_sess}") + check("sessions_max <= 10", max_sess <= 10, f"max={max_sess}") + +def test_metrics_endpoint(): + """GET /metrics returns cache and throughput stats.""" + print("\n=== Test: Metrics Endpoint ===") + # Make a request first to populate metrics + req([{"role": "user", "content": "hi"}]) + + resp = urllib.request.urlopen("http://127.0.0.1:8080/metrics", timeout=5) + data = json.loads(resp.read().decode()) + check("Has cache section", "cache" in data, str(data)[:200]) + check("Has throughput section", "throughput" in data, str(data)[:200]) + check("requests > 0", data.get("cache", {}).get("requests", 0) > 0, str(data.get("cache", {}))) + check("hit_rate is a number", isinstance(data.get("cache", {}).get("hit_rate"), (int, float)), str(data.get("cache", {}))) + check("sessions_active >= 0", data.get("cache", {}).get("sessions_active", -1) >= 0, str(data.get("cache", {}))) + +if __name__ == "__main__": + # Check server is up + try: + urllib.request.urlopen("http://127.0.0.1:8080/health", timeout=5) + except: + print("ERROR: Server not running on localhost:8080") + sys.exit(1) + + print("Server Prompt Cache Test Suite") + print("=" * 40) + + test_basic_cache_hit() + test_cache_miss() + test_session_interleave() + test_conversation_growth() + test_eviction() + test_tool_calls() + test_usage_in_response() + test_health_endpoint() + test_malformed_request() + test_server_survives_bad_request() + test_oversized_request() + test_auto_session_config() + test_metrics_endpoint() + + print(f"\n{'=' * 40}") + print(f"Results: {PASS} passed, {FAIL} failed") + sys.exit(1 if FAIL > 0 else 0) diff --git a/Sources/NativePrefillBridge/generic_prefill.cpp b/Sources/NativePrefillBridge/generic_prefill.cpp new file mode 100644 index 0000000000..0f3268b036 --- /dev/null +++ b/Sources/NativePrefillBridge/generic_prefill.cpp @@ -0,0 +1,1427 @@ +// generic_prefill.cpp — Model-agnostic native prefill bridge +// +// Shared infrastructure for any MLX model. Model-specific layer forward +// passes are dispatched by model_type. Currently supports: +// - gemma4_text (Gemma 4 E2B/A4B with shared KV, PLE, sliding/full attention) +// - minimax_m2 (MiniMax M2.7 with 256-expert SwitchGLU MoE) +// +// Adding a new model: implement a LayerForward function and register it. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mlx/mlx.h" +#include "generic_prefill.h" + +using namespace mlx::core; + +// ============================================================================ +// Shared primitives +// ============================================================================ + +static constexpr float DEFAULT_RMS_EPS = 1e-6f; + +struct QuantizedLinear { + std::optional weight; + std::optional scales; + std::optional biases; // quantization biases + std::optional linear_bias; // linear layer bias (e.g., Qwen2 attention) + int group_size = 64; + int bits = 4; + bool quantized = true; + + array operator()(const array& x) const { + if (quantized) { + auto out = quantized_matmul(x, *weight, *scales, *biases, + true, group_size, bits, "affine"); + if (linear_bias) out = out + *linear_bias; + return out; + } else { + auto out = matmul(x, transpose(*weight)); + if (linear_bias) out = out + *linear_bias; + return out; + } + } +}; + +struct Norm { + std::optional weight; + float eps = 1e-6f; + + array operator()(const array& x) const { + if (weight) return fast::rms_norm(x, *weight, eps); + return fast::rms_norm(x, std::nullopt, eps); + } +}; + +struct Embedding { + std::optional weight; + std::optional scales; + std::optional biases; + int group_size = 64; + int bits = 4; + bool quantized = false; + + array operator()(const array& indices) const { + if (quantized) { + auto w = take(*weight, indices, 0); + auto s = take(*scales, indices, 0); + auto b = take(*biases, indices, 0); + return dequantize(w, s, b, group_size, bits, "affine"); + } + return take(*weight, indices, 0); + } +}; + +// ============================================================================ +// Model config — parsed from JSON +// ============================================================================ + +struct ModelConfig { + std::string model_type; + int hidden_size = 0; + int num_layers = 0; + int num_heads = 0; + int num_kv_heads = 0; + int head_dim = 0; + int intermediate_size = 0; + int vocab_size = 0; + float rms_norm_eps = 1e-6f; + float rope_theta = 10000.0f; + int rotary_dim = 0; // 0 = full head_dim + bool tie_word_embeddings = false; + bool use_qk_norm = false; + + // MoE params + int num_local_experts = 0; + int num_experts_per_tok = 0; + std::string scoring_func = "softmax"; + + // Gemma4 params + int sliding_window = 0; + int sliding_pattern = 0; + int num_kv_shared_layers = 0; + int hidden_per_layer = 0; + int total_layers = 0; + float partial_rotary_factor = 1.0f; + float global_rope_theta = 1000000.0f; + int global_head_dim = 0; + + // YaRN RoPE params + std::string rope_type = ""; // "", "yarn", "linear", "llama3" + float yarn_factor = 1.0f; + float yarn_beta_fast = 32.0f; + float yarn_beta_slow = 1.0f; + int yarn_original_max_pos = 4096; + float yarn_mscale = 1.0f; + float yarn_mscale_all_dim = 0.0f; + + // Quantization + int quant_bits = 4; + int quant_group_size = 64; + + bool is_moe() const { return num_local_experts > 0; } +}; + +// ============================================================================ +// KV Cache (same as decode bridge) +// ============================================================================ + +struct KVCache { + std::optional keys; + std::optional values; + int offset = 0; + + bool has_data() const { return keys.has_value(); } + + void append(const array& k, const array& v, int seq_len) { + if (keys) { + keys = concatenate({*keys, k}, 2); + values = concatenate({*values, v}, 2); + } else { + keys = k; + values = v; + } + offset += seq_len; + } + + void reset() { + keys.reset(); + values.reset(); + offset = 0; + } +}; + +// ============================================================================ +// YaRN RoPE frequency computation +// ============================================================================ + +// Compute YaRN-corrected RoPE frequencies. +// Returns: [dims/2] frequency tensor suitable for fast::rope(..., freqs) +// Also returns the mscale factor to apply to Q/K before RoPE. +static std::pair compute_yarn_freqs( + int dims, float base, float factor, + int original_max_pos, float beta_fast, float beta_slow, + float mscale_val, float mscale_all_dim) { + + // yarnFindCorrectionDim: find the dimension index for a given rotation count + auto find_correction_dim = [&](float num_rotations) -> float { + return (float)dims + * std::log((float)original_max_pos / (num_rotations * 2.0f * M_PI)) + / (2.0f * std::log(base)); + }; + + // yarnFindCorrectionRange + int low = std::max(0, (int)std::floor(find_correction_dim(beta_fast))); + int high = std::min(dims - 1, (int)std::ceil(find_correction_dim(beta_slow))); + + // yarnGetMscale + auto get_mscale = [](float scale, float ms) -> float { + if (scale <= 1.0f) return 1.0f; + return 0.1f * ms * std::log(scale) + 1.0f; + }; + + float mscale = get_mscale(factor, mscale_val) / get_mscale(factor, mscale_all_dim); + + // Compute base frequencies: base^(i / dims) for i in [0, 2, 4, ..., dims-2] + int half = dims / 2; + auto indices = astype(arange(0, dims, 2), float32); + auto base_freqs = power(array(base, float32), indices / (float)dims); + + // freqExtra = base_freqs (unscaled) + // freqInter = factor * base_freqs (interpolated) + auto freq_extra = base_freqs; + auto freq_inter = array(factor, float32) * base_freqs; + + // yarnLinearRampMask: linear interpolation mask between low and high + float max_val = (low == high) ? (float)high + 0.001f : (float)high; + auto ramp = (astype(arange(0, half), float32) - (float)low) / (max_val - (float)low); + ramp = clip(ramp, array(0.0f), array(1.0f)); + auto freq_mask = array(1.0f, float32) - ramp; + + // Final frequency combination (matches Swift exactly): + // freqs = (freqInter * freqExtra) / (freqInter * freqMask + freqExtra * (1 - freqMask)) + auto freqs = (freq_inter * freq_extra) + / (freq_inter * freq_mask + freq_extra * (array(1.0f, float32) - freq_mask)); + + eval({freqs}); + return {freqs, mscale}; +} + +// ============================================================================ +// Generic attention (works for all models) +// ============================================================================ + +static array generic_attention( + const array& x, + const QuantizedLinear& q_proj, + const QuantizedLinear& k_proj, + const QuantizedLinear& v_proj, + const QuantizedLinear& o_proj, + const Norm* q_norm, + const Norm* k_norm, + int num_heads, int num_kv_heads, int head_dim, + bool qk_norm_before_reshape, // MiniMax: true, Gemma4: false + float rope_theta, int rotary_dim, + const array* rope_freqs, // for proportional RoPE (Gemma4 full layers) + KVCache& cache, + int rope_offset = 0, // position offset for chunked prefill + float custom_scale = 0.0f, // 0 = use 1/sqrt(head_dim) + float yarn_mscale = 1.0f, // YaRN mscale for Q/K before RoPE + const std::optional& sinks = {} // attention sinks (GPT-OSS) +) { + int B = x.shape(0); + int S = x.shape(1); + + auto q = q_proj(x); + auto k = k_proj(x); + auto v = v_proj(x); + + if (q_norm && qk_norm_before_reshape) { + q = (*q_norm)(q); k = (*k_norm)(k); + } + + q = transpose(reshape(q, {B, S, num_heads, head_dim}), {0, 2, 1, 3}); + k = transpose(reshape(k, {B, S, num_kv_heads, head_dim}), {0, 2, 1, 3}); + v = transpose(reshape(v, {B, S, num_kv_heads, head_dim}), {0, 2, 1, 3}); + + if (q_norm && !qk_norm_before_reshape) { + q = (*q_norm)(q); k = (*k_norm)(k); + } + + if (yarn_mscale != 1.0f) { + q = q * array(yarn_mscale, q.dtype()); + k = k * array(yarn_mscale, k.dtype()); + } + + int actual_rotary = rotary_dim > 0 ? rotary_dim : head_dim; + if (rope_freqs && rope_freqs->ndim() == 1) { + q = fast::rope(q, head_dim, false, std::nullopt, 1.0f, rope_offset, *rope_freqs); + k = fast::rope(k, head_dim, false, std::nullopt, 1.0f, rope_offset, *rope_freqs); + } else { + q = fast::rope(q, actual_rotary, false, rope_theta, 1.0f, rope_offset); + k = fast::rope(k, actual_rotary, false, rope_theta, 1.0f, rope_offset); + } + + auto kv_dtype = k_proj.scales ? k_proj.scales->dtype() : float16; + k = astype(k, kv_dtype); + v = astype(v, kv_dtype); + + cache.append(k, v, S); + + float scale = custom_scale > 0.0f ? custom_scale + : 1.0f / std::sqrt(static_cast(head_dim)); + + auto attn = fast::scaled_dot_product_attention( + q, *cache.keys, *cache.values, scale, "causal", std::nullopt, sinks); + + attn = reshape(transpose(attn, {0, 2, 1, 3}), {B, S, num_heads * head_dim}); + + return o_proj(attn); +} + +// ============================================================================ +// MoE routing (MiniMax: sigmoid + top-k + correction bias) +// ============================================================================ + +static array moe_forward( + const array& x, + const QuantizedLinear& gate, + const array& correction_bias, + // SwitchGLU expert weights: [num_experts, hidden, dim] stacked + const array& gate_proj_w, const array& gate_proj_s, const std::optional& gate_proj_b, + const array& up_proj_w, const array& up_proj_s, const std::optional& up_proj_b, + const array& down_proj_w, const array& down_proj_s, const std::optional& down_proj_b, + int num_experts_per_tok, + int group_size, + int gate_bits, int up_bits, int down_bits, + const std::string& scoring_func +) { + // Route: compute gate scores and select top-k experts + auto gates = gate(astype(x, float32)); + array scores = array(0.0f); + if (scoring_func == "sigmoid") { + scores = sigmoid(gates); + } else { + scores = softmax(gates, -1); + } + + int k = num_experts_per_tok; + // Select top-k experts. Use raw gates for argpartition (monotonic with softmax) + // to match Swift's implementation and avoid unnecessary negative(softmax) copies. + // For sigmoid routing with correction_bias (MiniMax), apply bias before selection. + array sort_keys = array(0.0f); + if (scoring_func == "sigmoid" && correction_bias.size() > 1) { + sort_keys = negative(scores + correction_bias); + } else { + sort_keys = negative(gates); // Match Swift: argPartition(-gates) + } + auto inds = argpartition(sort_keys, k - 1, -1); + inds = slice(inds, {0, 0, 0}, {inds.shape(0), inds.shape(1), k}); + auto sel_scores = take_along_axis(scores, inds, -1); + + // Normalize + sel_scores = sel_scores / (sum(sel_scores, -1, true) + 1e-20f); + sel_scores = astype(sel_scores, x.dtype()); + + // SwitchGLU via gather_qmm with expert-sorted dispatch + // Sorting tokens by expert index improves GPU cache locality (38-48% at T≥1024) + auto B = x.shape(0); + auto S = x.shape(1); + + // Sort by expert for cache-friendly dispatch (matches Swift's SwitchGLU) + bool do_sort = true; // always sort — expert locality is always beneficial + + auto x_exp = expand_dims(x, {-2, -3}); // [B, S, 1, 1, D] + array use_x = x_exp; + array use_inds = inds; + array inv_order = array(0); + + if (do_sort) { + // Flatten indices [B, S, K] → [B*S*K] + auto flat_inds = flatten(inds); + auto order = argsort(flat_inds); + inv_order = argsort(order); + + // Reorder x: flatten to [B*S, 1, 1, D], gather by order/K + auto x_flat = flatten(x_exp, 0, 1); // [B*S, 1, 1, D] + auto token_idx = astype(order / array(k), uint32); // which token each slot maps to + use_x = take(x_flat, token_idx, 0); // [B*S*K, 1, 1, D] + use_inds = reshape(take(flat_inds, order, 0), {-1, 1}); // [B*S*K, 1] sorted + } + + // Detect quantization mode from biases presence and scales dtype + // affine: has biases (float16/bfloat16 scales) + // mxfp4: no biases (uint8 scales) + auto detect_mode = [](const std::optional& b, const array& s) -> std::string { + if (!b || b->size() <= 1) { + // No biases — check scales dtype for MXFP variants + if (s.dtype() == uint8) return "mxfp4"; + return "affine"; // fallback + } + return "affine"; + }; + + auto gate_out = gather_qmm( + use_x, gate_proj_w, gate_proj_s, gate_proj_b, + std::nullopt, use_inds, + true, group_size, gate_bits, detect_mode(gate_proj_b, gate_proj_s), do_sort); + + auto up_out = gather_qmm( + use_x, up_proj_w, up_proj_s, up_proj_b, + std::nullopt, use_inds, + true, group_size, up_bits, detect_mode(up_proj_b, up_proj_s), do_sort); + + // SiLU activation on gate, multiply with up + auto hidden_act = (gate_out * sigmoid(gate_out)) * up_out; + + auto down_out = gather_qmm( + hidden_act, down_proj_w, down_proj_s, down_proj_b, + std::nullopt, use_inds, + true, group_size, down_bits, detect_mode(down_proj_b, down_proj_s), do_sort); + + // Squeeze extra dim from gather_qmm output + down_out = squeeze(down_out, {-2}); // [N, D] where N=B*S*K (sorted) or [B,S,K,D] + + if (do_sort) { + // Unsort back to original token order and reshape + down_out = take(down_out, inv_order, 0); // [B*S*K, D] + down_out = reshape(down_out, {B, S, k, -1}); // [B, S, K, D] + } + + auto y = sum(down_out * expand_dims(sel_scores, -1), -2); + + return y; +} + +// ============================================================================ +// Standard MLP (GeGLU for Gemma4, SiLU+gate for others) +// ============================================================================ + +static array gelu_approx(const array& x) { + auto dt = x.dtype(); + auto x3 = power(x, array(3, dt)); + auto inner = array(0.7978845608028654f, dt) * (x + array(0.044715f, dt) * x3); + return array(0.5f, dt) * x * (array(1.0f, dt) + tanh(inner)); +} + +static array mlp_forward( + const array& x, + const QuantizedLinear& gate_proj, + const QuantizedLinear& up_proj, + const QuantizedLinear& down_proj, + const std::string& activation = "silu" +) { + auto gate = gate_proj(x); + auto up = up_proj(x); + if (activation == "gelu") { + return down_proj(gelu_approx(gate) * up); + } + return down_proj((gate * sigmoid(gate)) * up); +} + +// ============================================================================ +// Generic layer +// ============================================================================ + +struct MoEWeights { + QuantizedLinear gate; + std::optional correction_bias; + std::optional switch_gate_w, switch_gate_s, switch_gate_b; + std::optional switch_up_w, switch_up_s, switch_up_b; + std::optional switch_down_w, switch_down_s, switch_down_b; + int num_experts_per_tok = 0; + int gate_bits = 4; + int up_bits = 4; + int down_bits = 4; + std::string scoring_func = "softmax"; +}; + +struct PLEWeights { + QuantizedLinear gate, proj; + Norm post_norm; + std::optional layer_scalar; +}; + +struct Layer { + Norm input_norm; + Norm post_attn_norm; + + // Attention + QuantizedLinear q_proj, k_proj, v_proj, o_proj; + Norm q_norm, k_norm; + bool has_qk_norm = false; + bool qk_norm_before_reshape = false; + float rope_theta = 10000.0f; + int rotary_dim = 0; + std::optional rope_freqs; + + // Custom attention scale (Gemma3 uses queryPreAttnScalar^(-0.5)) + float attn_scale = 0.0f; // 0 = use default 1/sqrt(head_dim) + + // YaRN mscale: applied to Q/K before RoPE (1.0 = no scaling) + float yarn_mscale = 1.0f; + + // Attention sinks (GPT-OSS) + std::optional sinks; + + // MLP (standard dense path) + QuantizedLinear gate_proj, up_proj, down_proj; + std::string mlp_activation = "silu"; // "silu" or "gelu" + + // Gemma3 extra norms (pre/post feedforward) + Norm pre_ff_norm, post_ff_norm; + bool has_gemma3_norms = false; + bool is_sliding = false; // sliding window attention layer + + // MoE (only allocated for MoE models) + bool is_moe = false; + std::optional moe; + + // Gemma4 PLE (only allocated for Gemma4) + bool has_ple = false; + std::optional ple; + + int num_heads = 0, num_kv_heads = 0, head_dim = 0; + int group_size = 64, bits = 4; + + KVCache cache; +}; + +// ============================================================================ +// Model +// ============================================================================ + +struct GenericModel { + ModelConfig config; + Embedding embed_tokens; + std::vector layers; + Norm final_norm; + + // Gemma4 PLE + Embedding embed_per_layer; + QuantizedLinear per_layer_projection; + Norm per_layer_projection_norm; + bool has_ple = false; + float embed_scale = 1.0f; + float pl_embed_scale = 1.0f; + float pl_input_scale = 0.707f; + + static constexpr int CHUNK_SIZE = 4096; + + // Eval barrier cadence: every EVAL_CADENCE layers to prevent + // lazy-graph pressure from reclaiming weight Metal buffers. + static constexpr int EVAL_CADENCE = 8; + + array forward(const array& token_ids) { + int B = token_ids.shape(0); + int S = token_ids.shape(1); + + auto all_h = embed_tokens(token_ids); + if (embed_scale != 1.0f) { + all_h = all_h * array(embed_scale, all_h.dtype()); + } + + // Gemma4 PLE setup (over full sequence) + array combined_per_layer = array(0.0f); + if (has_ple) { + auto pli = embed_per_layer(token_ids) * array(pl_embed_scale, bfloat16); + pli = reshape(pli, {B, S, config.total_layers, config.hidden_per_layer}); + auto plp = per_layer_projection(all_h); + plp = reshape(plp, {B, S, config.total_layers, config.hidden_per_layer}); + plp = per_layer_projection_norm(plp); + combined_per_layer = (plp + pli) * array(pl_input_scale, bfloat16); + } + + int num_chunks = (S + CHUNK_SIZE - 1) / CHUNK_SIZE; + array h = array(0.0f); + + for (int c = 0; c < num_chunks; c++) { + int chunk_start = c * CHUNK_SIZE; + int chunk_end = std::min(chunk_start + CHUNK_SIZE, S); + int chunk_len = chunk_end - chunk_start; + + h = slice(all_h, {0, chunk_start, 0}, {B, chunk_end, config.hidden_size}); + + for (int i = 0; i < (int)layers.size(); i++) { + auto& layer = layers[i]; + auto residual = h; + + auto normed = layer.input_norm(h); + + auto attn_out = generic_attention( + normed, + layer.q_proj, layer.k_proj, layer.v_proj, layer.o_proj, + layer.has_qk_norm ? &layer.q_norm : nullptr, + layer.has_qk_norm ? &layer.k_norm : nullptr, + layer.num_heads, layer.num_kv_heads, layer.head_dim, + layer.qk_norm_before_reshape, + layer.rope_theta, layer.rotary_dim, + layer.rope_freqs && layer.rope_freqs->ndim() == 1 ? &*layer.rope_freqs : nullptr, + layer.cache, + chunk_start, + layer.attn_scale, + layer.yarn_mscale, + layer.sinks + ); + + if (layer.has_gemma3_norms) { + // Gemma3: post_attn_norm on attention output, then add residual + h = residual + layer.post_attn_norm(attn_out); + } else { + h = residual + attn_out; + } + + residual = h; + if (layer.is_moe) { + auto normed_ff = layer.post_attn_norm(h); + h = residual + moe_forward( + normed_ff, layer.moe->gate, *layer.moe->correction_bias, + *layer.moe->switch_gate_w, *layer.moe->switch_gate_s, layer.moe->switch_gate_b, + *layer.moe->switch_up_w, *layer.moe->switch_up_s, layer.moe->switch_up_b, + *layer.moe->switch_down_w, *layer.moe->switch_down_s, layer.moe->switch_down_b, + layer.moe->num_experts_per_tok, layer.group_size, + layer.moe->gate_bits, layer.moe->up_bits, layer.moe->down_bits, + layer.moe->scoring_func + ); + } else if (layer.has_gemma3_norms) { + // Gemma3: pre_ff_norm → MLP → post_ff_norm → add residual + auto pre_ff = layer.pre_ff_norm(h); + auto mlp_out = mlp_forward(pre_ff, layer.gate_proj, layer.up_proj, layer.down_proj, layer.mlp_activation); + h = residual + layer.post_ff_norm(mlp_out); + } else { + auto normed_ff = layer.post_attn_norm(h); + h = residual + mlp_forward(normed_ff, layer.gate_proj, layer.up_proj, layer.down_proj, layer.mlp_activation); + } + + // PLE (Gemma4) + if (layer.has_ple) { + residual = h; + auto pli = slice(combined_per_layer, + {0, chunk_start, i, 0}, {B, chunk_end, i + 1, config.hidden_per_layer}); + pli = reshape(pli, {B, chunk_len, config.hidden_per_layer}); + auto gate = layer.ple->gate(h); + gate = gelu_approx(gate) * pli; + gate = layer.ple->proj(gate); + gate = layer.ple->post_norm(gate); + h = residual + gate; + h = h * *layer.ple->layer_scalar; + } + + // Periodic eval barrier to prevent lazy-graph pressure + // from reclaiming weight Metal buffers. + // Include embedding weight/scales/biases to keep them pinned. + if ((i + 1) % EVAL_CADENCE == 0 || i == (int)layers.size() - 1) { + std::vector to_sync = {h}; + if (layer.cache.has_data()) { + to_sync.push_back(*layer.cache.keys); + to_sync.push_back(*layer.cache.values); + } + if (embed_tokens.weight) to_sync.push_back(*embed_tokens.weight); + if (embed_tokens.scales) to_sync.push_back(*embed_tokens.scales); + if (embed_tokens.biases) to_sync.push_back(*embed_tokens.biases); + eval(to_sync); + } + } + + // Final chunk eval — sync all KV caches + std::vector to_eval = {h}; + for (auto& layer : layers) { + if (layer.cache.has_data()) { + to_eval.push_back(*layer.cache.keys); + to_eval.push_back(*layer.cache.values); + } + } + eval(to_eval); + + if (num_chunks > 1) { + fprintf(stderr, "[gp] chunk %d/%d done (%d tokens)\n", + c + 1, num_chunks, chunk_len); + } + } + + return final_norm(h); + } +}; + +// ============================================================================ +// Global state +// ============================================================================ + +static std::unique_ptr g_model; +static std::unordered_map g_weights; +static ModelConfig g_config; +static bool g_initialized = false; +static bool g_finalized = false; + +// ============================================================================ +// Weight helpers +// ============================================================================ + +static array extract_array(void* ptr) { + return *static_cast(ptr); +} + +static array get_w(const std::string& key) { + auto it = g_weights.find(key); + if (it == g_weights.end()) throw std::runtime_error("Missing weight: " + key); + return it->second; +} + +static bool has_w(const std::string& key) { + return g_weights.count(key) > 0; +} + +// Split a fused [N, D] quantized weight into two halves along dim 0 +// Used for fused qkv_proj → q_proj + kv_proj, or gate_up_proj → gate + up +// Returns two QuantizedLinears via out params to avoid std::pair construction issues +static void split_fused_qlinear(QuantizedLinear& out1, QuantizedLinear& out2, + const std::string& prefix, int split_at, int gs = 0, int b = 0) { + if (gs == 0) gs = g_config.quant_group_size; + auto w = get_w(prefix + ".weight"); + auto s = get_w(prefix + ".scales"); + // Quantization biases are optional (not present in symmetric/MXFP quant) + bool has_qbiases = has_w(prefix + ".biases"); + array bi = has_qbiases ? get_w(prefix + ".biases") : array(0.0f); + int w_last = w.shape(-1); + int s_last = s.shape(-1); + if (s_last > 0 && b == 0) { + int ratio = w_last / s_last; + b = ratio * 32 / gs; + } + if (b == 0) b = g_config.quant_bits; + + // split_at is in OUTPUT dimension (dim 0 of weight) + // For quantized weights, the packed dim is dim 1, so we split dim 0 + int scale_split = split_at / gs; // scales have output_dim / group_size cols... no + // Actually for quantized: weight=[out, packed_in], scales=[out, groups] + // Split along dim 0 (output dimension) + auto w1 = slice(w, {0, 0}, {split_at, w.shape(1)}); + auto w2 = slice(w, {split_at, 0}, {w.shape(0), w.shape(1)}); + auto s1 = slice(s, {0, 0}, {split_at, s.shape(1)}); + auto s2 = slice(s, {split_at, 0}, {s.shape(0), s.shape(1)}); + + // Split quantization biases if present + std::optional b1_opt, b2_opt; + if (has_qbiases) { + b1_opt = slice(bi, {0, 0}, {split_at, bi.shape(1)}); + b2_opt = slice(bi, {split_at, 0}, {bi.shape(0), bi.shape(1)}); + } + + // Split linear bias if present + std::optional lb1, lb2; + if (has_w(prefix + ".bias")) { + auto lbias = get_w(prefix + ".bias"); + lb1 = slice(lbias, {0}, {split_at}); + lb2 = slice(lbias, {split_at}, {lbias.shape(0)}); + } + + out1.weight = w1; out1.scales = s1; out1.biases = b1_opt.value_or(array(0.0f)); + out1.linear_bias = lb1; out1.group_size = gs; out1.bits = b; out1.quantized = true; + out2.weight = w2; out2.scales = s2; out2.biases = b2_opt.value_or(array(0.0f)); + out2.linear_bias = lb2; out2.group_size = gs; out2.bits = b; out2.quantized = true; +} + +static QuantizedLinear make_qlinear(const std::string& prefix, int gs = 0, int b = 0) { + if (gs == 0) gs = g_config.quant_group_size; + // Check if weight is quantized (has scales) + if (has_w(prefix + ".scales")) { + auto w = get_w(prefix + ".weight"); + auto s = get_w(prefix + ".scales"); + auto bi = get_w(prefix + ".biases"); + // Auto-detect bits from weight/scales shape ratio + // ratio = weight.shape(-1) / scales.shape(-1) = bits * group_size / 32 + int w_last = w.shape(-1); + int s_last = s.shape(-1); + if (s_last > 0 && b == 0) { + int ratio = w_last / s_last; + b = ratio * 32 / gs; // bits = ratio * 32 / group_size + } + if (b == 0) b = g_config.quant_bits; + // Check for linear bias (e.g., Qwen2 attention has bias: true) + std::optional lb; + if (has_w(prefix + ".bias")) { + lb = get_w(prefix + ".bias"); + } + return {w, s, bi, lb, gs, b, true}; + } + // Unquantized linear + if (b == 0) b = g_config.quant_bits; + std::optional lb; + if (has_w(prefix + ".bias")) lb = get_w(prefix + ".bias"); + return {get_w(prefix + ".weight"), array(0.0f), array(0.0f), lb, gs, b, false}; +} + +static int detect_bits(const std::string& weight_key, const std::string& scales_key, int gs = 64) { + if (!has_w(weight_key) || !has_w(scales_key)) return g_config.quant_bits; + auto w = get_w(weight_key); + auto s = get_w(scales_key); + int w_last = w.shape(-1); + int s_last = s.shape(-1); + if (s_last <= 0) return g_config.quant_bits; + return (w_last * 32) / (s_last * gs); +} + +static Norm make_norm(const std::string& prefix) { + return {get_w(prefix + ".weight"), g_config.rms_norm_eps}; +} + +static Embedding make_embedding(const std::string& prefix) { + bool q = has_w(prefix + ".scales"); + Embedding emb; + // Use direct weight reference. Swift already evaluated these arrays, + // so they have pinned GPU buffers. The add-zero copy is unnecessary. + emb.weight = get_w(prefix + ".weight"); + eval({*emb.weight}); + if (q) { + emb.scales = get_w(prefix + ".scales"); + emb.biases = get_w(prefix + ".biases"); + eval({*emb.scales, *emb.biases}); + emb.group_size = g_config.quant_group_size; + emb.bits = detect_bits(prefix + ".weight", prefix + ".scales", g_config.quant_group_size); + emb.quantized = true; + } + return emb; +} + +// ============================================================================ +// Config parsing (minimal JSON — just extract what we need) +// ============================================================================ + +static std::string json_string(const std::string& json, const std::string& key) { + auto pos = json.find("\"" + key + "\""); + if (pos == std::string::npos) return ""; + pos = json.find(":", pos); + auto start = json.find("\"", pos + 1); + auto end = json.find("\"", start + 1); + return json.substr(start + 1, end - start - 1); +} + +static int json_int(const std::string& json, const std::string& key, int def = 0) { + auto pos = json.find("\"" + key + "\""); + if (pos == std::string::npos) return def; + pos = json.find(":", pos); + auto start = json.find_first_of("-0123456789", pos + 1); + auto end = json.find_first_not_of("-0123456789", start); + return std::stoi(json.substr(start, end - start)); +} + +static float json_float(const std::string& json, const std::string& key, float def = 0) { + auto pos = json.find("\"" + key + "\""); + if (pos == std::string::npos) return def; + pos = json.find(":", pos); + auto start = json.find_first_of("-0123456789.", pos + 1); + auto end = json.find_first_not_of("-0123456789.eE+-", start); + return std::stof(json.substr(start, end - start)); +} + +static bool json_bool(const std::string& json, const std::string& key, bool def = false) { + auto pos = json.find("\"" + key + "\""); + if (pos == std::string::npos) return def; + pos = json.find(":", pos); + auto val_start = json.find_first_not_of(" \t\n", pos + 1); + return json.substr(val_start, 4) == "true"; +} + +// ============================================================================ +// Build model from config + weights +// ============================================================================ + +static void build_minimax_layer(Layer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + if (g_config.use_qk_norm) { + layer.q_norm = make_norm(p + ".self_attn.q_norm"); + layer.k_norm = make_norm(p + ".self_attn.k_norm"); + layer.has_qk_norm = true; + layer.qk_norm_before_reshape = true; // MiniMax: norm before reshape + } + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = g_config.rotary_dim; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + // Auto-detect per-layer attention bits from weight shapes + layer.bits = layer.q_proj.bits; + + // MoE + layer.is_moe = true; + layer.moe.emplace(); + layer.moe->gate = make_qlinear(p + ".block_sparse_moe.gate"); + layer.moe->correction_bias = get_w(p + ".block_sparse_moe.e_score_correction_bias"); + layer.moe->switch_gate_w = get_w(p + ".block_sparse_moe.switch_mlp.gate_proj.weight"); + layer.moe->switch_gate_s = get_w(p + ".block_sparse_moe.switch_mlp.gate_proj.scales"); + layer.moe->switch_gate_b = get_w(p + ".block_sparse_moe.switch_mlp.gate_proj.biases"); + layer.moe->switch_up_w = get_w(p + ".block_sparse_moe.switch_mlp.up_proj.weight"); + layer.moe->switch_up_s = get_w(p + ".block_sparse_moe.switch_mlp.up_proj.scales"); + layer.moe->switch_up_b = get_w(p + ".block_sparse_moe.switch_mlp.up_proj.biases"); + layer.moe->switch_down_w = get_w(p + ".block_sparse_moe.switch_mlp.down_proj.weight"); + layer.moe->switch_down_s = get_w(p + ".block_sparse_moe.switch_mlp.down_proj.scales"); + layer.moe->switch_down_b = get_w(p + ".block_sparse_moe.switch_mlp.down_proj.biases"); + // Auto-detect per-layer MoE bits from weight shapes + std::string moe_p = p + ".block_sparse_moe.switch_mlp"; + layer.moe->gate_bits = detect_bits(moe_p + ".gate_proj.weight", moe_p + ".gate_proj.scales"); + layer.moe->up_bits = detect_bits(moe_p + ".up_proj.weight", moe_p + ".up_proj.scales"); + layer.moe->down_bits = detect_bits(moe_p + ".down_proj.weight", moe_p + ".down_proj.scales"); + layer.moe->num_experts_per_tok = g_config.num_experts_per_tok; + layer.moe->scoring_func = g_config.scoring_func; +} + +static void build_qwen3_moe_layer(Layer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + if (g_config.use_qk_norm) { + layer.q_norm = make_norm(p + ".self_attn.q_norm"); + layer.k_norm = make_norm(p + ".self_attn.k_norm"); + layer.has_qk_norm = true; + layer.qk_norm_before_reshape = false; // Qwen3: norm AFTER reshape (per-head) + } + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = g_config.rotary_dim; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + layer.bits = layer.q_proj.bits; + + // MoE -- Qwen3 uses mlp.gate and mlp.switch_mlp (not block_sparse_moe) + layer.is_moe = true; + layer.moe.emplace(); + layer.moe->gate = make_qlinear(p + ".mlp.gate"); + // Qwen3 uses softmax routing, no correction_bias + layer.moe->correction_bias = array(0.0f); + layer.moe->switch_gate_w = get_w(p + ".mlp.switch_mlp.gate_proj.weight"); + layer.moe->switch_gate_s = get_w(p + ".mlp.switch_mlp.gate_proj.scales"); + layer.moe->switch_gate_b = get_w(p + ".mlp.switch_mlp.gate_proj.biases"); + layer.moe->switch_up_w = get_w(p + ".mlp.switch_mlp.up_proj.weight"); + layer.moe->switch_up_s = get_w(p + ".mlp.switch_mlp.up_proj.scales"); + layer.moe->switch_up_b = get_w(p + ".mlp.switch_mlp.up_proj.biases"); + layer.moe->switch_down_w = get_w(p + ".mlp.switch_mlp.down_proj.weight"); + layer.moe->switch_down_s = get_w(p + ".mlp.switch_mlp.down_proj.scales"); + layer.moe->switch_down_b = get_w(p + ".mlp.switch_mlp.down_proj.biases"); + std::string moe_p = p + ".mlp.switch_mlp"; + layer.moe->gate_bits = detect_bits(moe_p + ".gate_proj.weight", moe_p + ".gate_proj.scales"); + layer.moe->up_bits = detect_bits(moe_p + ".up_proj.weight", moe_p + ".up_proj.scales"); + layer.moe->down_bits = detect_bits(moe_p + ".down_proj.weight", moe_p + ".down_proj.scales"); + layer.moe->num_experts_per_tok = g_config.num_experts_per_tok; + layer.moe->scoring_func = "softmax"; // Qwen3 always uses softmax +} + +// Qwen2/Qwen3 dense layer builder -- handles attention bias, QK norm +static void build_qwen_dense_layer(Layer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + if (g_config.use_qk_norm) { + layer.q_norm = make_norm(p + ".self_attn.q_norm"); + layer.k_norm = make_norm(p + ".self_attn.k_norm"); + layer.has_qk_norm = true; + layer.qk_norm_before_reshape = false; // Qwen: norm after reshape + } + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = g_config.rotary_dim; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + layer.bits = layer.q_proj.bits; + + // Dense MLP (SiLU-gated) + layer.is_moe = false; + layer.gate_proj = make_qlinear(p + ".mlp.gate_proj"); + layer.up_proj = make_qlinear(p + ".mlp.up_proj"); + layer.down_proj = make_qlinear(p + ".mlp.down_proj"); + + // Force-eval all layer weights to pin GPU buffers. + // Without this, the Metal allocator reclaims weight buffers when + // subsequent layers are constructed (hundreds of array(0.0f) defaults). + std::vector layer_weights = { + *layer.q_proj.weight, *layer.q_proj.scales, + *layer.k_proj.weight, *layer.k_proj.scales, + *layer.v_proj.weight, *layer.v_proj.scales, + *layer.o_proj.weight, *layer.o_proj.scales, + *layer.gate_proj.weight, *layer.gate_proj.scales, + *layer.up_proj.weight, *layer.up_proj.scales, + *layer.down_proj.weight, *layer.down_proj.scales, + *layer.input_norm.weight, *layer.post_attn_norm.weight + }; + if (layer.q_proj.linear_bias) { + layer_weights.push_back(*layer.q_proj.linear_bias); + layer_weights.push_back(*layer.k_proj.linear_bias); + layer_weights.push_back(*layer.v_proj.linear_bias); + } + eval(layer_weights); +} + +// Phi3 layer builder — handles fused qkv_proj and gate_up_proj +static void build_phi3_layer(Layer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + + // Fused QKV: split into Q, K, V + // qkv_proj output dim = (num_heads + 2*num_kv_heads) * head_dim + int q_dim = g_config.num_heads * g_config.head_dim; + int kv_dim = g_config.num_kv_heads * g_config.head_dim; + { + // Split: [q_dim, kv_dim, kv_dim] along output dim 0 + auto qkv_w = get_w(p + ".self_attn.qkv_proj.weight"); + auto qkv_s = get_w(p + ".self_attn.qkv_proj.scales"); + auto qkv_b = get_w(p + ".self_attn.qkv_proj.biases"); + int gs = g_config.quant_group_size; + int w_last = qkv_w.shape(-1); + int s_last = qkv_s.shape(-1); + int bits = (s_last > 0) ? (w_last * 32) / (s_last * gs) : g_config.quant_bits; + + auto make_split = [&](int start, int end) -> QuantizedLinear { + auto w = slice(qkv_w, {start, 0}, {end, qkv_w.shape(1)}); + auto s = slice(qkv_s, {start, 0}, {end, qkv_s.shape(1)}); + auto b = slice(qkv_b, {start, 0}, {end, qkv_b.shape(1)}); + return {w, s, b, std::nullopt, gs, bits, true}; + }; + layer.q_proj = make_split(0, q_dim); + layer.k_proj = make_split(q_dim, q_dim + kv_dim); + layer.v_proj = make_split(q_dim + kv_dim, q_dim + 2 * kv_dim); + } + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = g_config.rotary_dim; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + layer.bits = layer.q_proj.bits; + + // Fused gate_up_proj: split into gate and up (equal halves) + { + auto gu_w = get_w(p + ".mlp.gate_up_proj.weight"); + int half = gu_w.shape(0) / 2; + split_fused_qlinear(layer.gate_proj, layer.up_proj, p + ".mlp.gate_up_proj", half); + } + layer.down_proj = make_qlinear(p + ".mlp.down_proj"); + layer.is_moe = false; +} + +// GPT-OSS layer builder — standard attention + MoE with fused gate_up SwitchGLU +static void build_gptoss_layer(Layer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + // Attention sinks + if (has_w(p + ".self_attn.sinks")) { + auto s = get_w(p + ".self_attn.sinks"); + // Only use sinks if they're non-zero + eval({s}); + float smax = max(abs(s)).item(); + if (smax > 0.0f) { + layer.sinks = s; + } + } + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = 0; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + layer.bits = layer.q_proj.bits; + + // YaRN RoPE: compute corrected frequencies if configured + if (g_config.rope_type == "yarn" && g_config.yarn_factor > 1.0f) { + auto [freqs, mscale] = compute_yarn_freqs( + g_config.head_dim, g_config.rope_theta, g_config.yarn_factor, + g_config.yarn_original_max_pos, g_config.yarn_beta_fast, g_config.yarn_beta_slow, + g_config.yarn_mscale, g_config.yarn_mscale_all_dim); + layer.rope_freqs = freqs; + layer.yarn_mscale = mscale; + if (idx == 0) { + fprintf(stderr, "[gp] YaRN: mscale=%.6f freqs_size=%d\n", + mscale, (int)freqs.size()); + } + } + + // GPT-OSS MLP uses FusedGateUpSwitchGLU with stacked expert weights [E, out, in] + // The gate_up_proj is fused: first half is gate, second half is up + // Route through MoE path with gather_qmm + layer.is_moe = true; + layer.moe.emplace(); + layer.moe->gate = make_qlinear(p + ".mlp.router"); + layer.moe->correction_bias = array(0.0f); // GPT-OSS uses softmax routing, no correction + + // Fused gate_up_proj: [E, gate_dim+up_dim, packed_in] + // Need to split into separate gate and up for gather_qmm + auto gu_w = get_w(p + ".mlp.experts.gate_up_proj.weight"); + auto gu_s = get_w(p + ".mlp.experts.gate_up_proj.scales"); + int E = gu_w.shape(0); + int fused_out = gu_w.shape(1); + int half = fused_out / 2; + + // Split along dim 1 (output dim): [E, half, in] each + layer.moe->switch_gate_w = slice(gu_w, {0, 0, 0}, {E, half, gu_w.shape(2)}); + layer.moe->switch_gate_s = slice(gu_s, {0, 0, 0}, {E, half, gu_s.shape(2)}); + layer.moe->switch_up_w = slice(gu_w, {0, half, 0}, {E, fused_out, gu_w.shape(2)}); + layer.moe->switch_up_s = slice(gu_s, {0, half, 0}, {E, fused_out, gu_s.shape(2)}); + + // Quantization biases: optional (MXFP4 doesn't have them) + if (has_w(p + ".mlp.experts.gate_up_proj.biases")) { + auto gu_b = get_w(p + ".mlp.experts.gate_up_proj.biases"); + layer.moe->switch_gate_b = slice(gu_b, {0, 0, 0}, {E, half, gu_b.shape(2)}); + layer.moe->switch_up_b = slice(gu_b, {0, half, 0}, {E, fused_out, gu_b.shape(2)}); + } + // else: leave as std::nullopt — gather_qmm handles absent biases + + // down_proj: [E, out, in] + layer.moe->switch_down_w = get_w(p + ".mlp.experts.down_proj.weight"); + layer.moe->switch_down_s = get_w(p + ".mlp.experts.down_proj.scales"); + if (has_w(p + ".mlp.experts.down_proj.biases")) { + layer.moe->switch_down_b = get_w(p + ".mlp.experts.down_proj.biases"); + } + + // Bits detection: MXFP4 uses uint8 scales, so detect_bits formula doesn't apply + // Use config quant_bits (default 4) for MXFP4 models + std::string moe_p = p + ".mlp.experts"; + auto gs_scales = get_w(moe_p + ".gate_up_proj.scales"); + if (gs_scales.dtype() == uint8) { + // MXFP4: bits=4, group_size derived from weight/scales shapes + // w=[E, out, packed_in] (uint32), s=[E, out, groups] (uint8) + // in_dim = packed_in * 32 / bits, group_size = in_dim / groups + auto w0 = get_w(moe_p + ".gate_up_proj.weight"); + int packed_in = w0.shape(2); + int groups = gs_scales.shape(2); + int in_dim = packed_in * 32 / 4; // uint32 packing: 8 values per uint32 + layer.group_size = in_dim / groups; + layer.moe->gate_bits = 4; + layer.moe->up_bits = 4; + layer.moe->down_bits = 4; + } else { + layer.moe->gate_bits = detect_bits(moe_p + ".gate_up_proj.weight", moe_p + ".gate_up_proj.scales"); + layer.moe->up_bits = layer.moe->gate_bits; + layer.moe->down_bits = detect_bits(moe_p + ".down_proj.weight", moe_p + ".down_proj.scales"); + } + layer.moe->num_experts_per_tok = g_config.num_experts_per_tok; + layer.moe->scoring_func = "softmax"; +} + +// Gemma3 clip residual: clamp the updated residual to prevent overflow +static array clip_residual(const array& x, const array& r) { + // Gemma uses soft capping: tanh(residual / 50) * 50 + // But in practice the Swift code just does x + r without explicit clipping + // for the text-only path. Let's match the Swift behavior. + return x + r; +} + +// Gemma3 layer builder — handles 4 norms, QK norm, GELU, sliding/global RoPE +static void build_gemma3_layer(Layer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + layer.pre_ff_norm = make_norm(p + ".pre_feedforward_layernorm"); + layer.post_ff_norm = make_norm(p + ".post_feedforward_layernorm"); + layer.has_gemma3_norms = true; + + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + layer.q_norm = make_norm(p + ".self_attn.q_norm"); + layer.k_norm = make_norm(p + ".self_attn.k_norm"); + layer.has_qk_norm = true; + layer.qk_norm_before_reshape = false; // Gemma3: per-head norm + + // Sliding window pattern: most layers are sliding, every Nth is global + int pattern = g_config.sliding_pattern > 0 ? g_config.sliding_pattern : 6; + layer.is_sliding = ((idx + 1) % pattern != 0); + + // Different RoPE for sliding vs global layers + if (layer.is_sliding) { + // Sliding layers use local base freq (default 10000) + layer.rope_theta = 10000.0f; // TODO: parse rope_local_base_freq from config + } else { + // Global layers use the main rope_theta with scaling + layer.rope_theta = g_config.rope_theta; + } + layer.rotary_dim = 0; // full head_dim + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + layer.bits = layer.q_proj.bits; + + // Custom attention scale: queryPreAttnScalar^(-0.5) + // For gemma3-4b, queryPreAttnScalar = head_dim = 256, so scale = 1/16 + float query_pre_attn_scalar = static_cast(g_config.head_dim); // default + layer.attn_scale = 1.0f / std::sqrt(query_pre_attn_scalar); + + // MLP uses GELU activation + layer.gate_proj = make_qlinear(p + ".mlp.gate_proj"); + layer.up_proj = make_qlinear(p + ".mlp.up_proj"); + layer.down_proj = make_qlinear(p + ".mlp.down_proj"); + layer.mlp_activation = "gelu"; + layer.is_moe = false; +} + +static GenericModel build_model() { + GenericModel m; + m.config = g_config; + // NOTE: embedding and final_norm are built AFTER layers. + // layers.resize() creates hundreds of default array(0.0f) objects + // which can cause the Metal allocator to reclaim GPU buffers + // backing previously-assigned arrays (embedding scales, etc.). + + if (g_config.model_type == "gemma4_text" || g_config.model_type == "gemma4" || + g_config.model_type == "gemma3" || g_config.model_type == "gemma3_text") { + m.embed_scale = std::sqrt(static_cast(g_config.hidden_size)); + } + + // Build embedding and norm FIRST (before layer loop). + // Layer default-construction creates many arrays which can trigger + // MLX Metal buffer reclamation. Building embedding first and verifying + // it survives the loop is the key test. + m.embed_tokens = make_embedding("model.embed_tokens"); + m.final_norm = make_norm("model.norm"); + + int num_layers = g_config.num_layers; + m.layers.reserve(num_layers); + + for (int i = 0; i < num_layers; i++) { + m.layers.emplace_back(); + + if (g_config.model_type == "minimax_m2") { + build_minimax_layer(m.layers[i], i); + } else if (g_config.model_type == "qwen3_moe") { + build_qwen3_moe_layer(m.layers[i], i); + } else if (g_config.model_type == "qwen2" || g_config.model_type == "qwen3") { + build_qwen_dense_layer(m.layers[i], i); + } else if (g_config.model_type == "phi3") { + build_phi3_layer(m.layers[i], i); + } else if (g_config.model_type == "gemma3" || g_config.model_type == "gemma3_text") { + build_gemma3_layer(m.layers[i], i); + } else if (g_config.model_type == "gpt_oss") { + build_gptoss_layer(m.layers[i], i); + } else { + // Generic transformer layer + std::string p = "model.layers." + std::to_string(i); + m.layers[i].input_norm = make_norm(p + ".input_layernorm"); + m.layers[i].post_attn_norm = make_norm(p + ".post_attention_layernorm"); + m.layers[i].q_proj = make_qlinear(p + ".self_attn.q_proj"); + m.layers[i].k_proj = make_qlinear(p + ".self_attn.k_proj"); + m.layers[i].v_proj = make_qlinear(p + ".self_attn.v_proj"); + m.layers[i].o_proj = make_qlinear(p + ".self_attn.o_proj"); + m.layers[i].gate_proj = make_qlinear(p + ".mlp.gate_proj"); + m.layers[i].up_proj = make_qlinear(p + ".mlp.up_proj"); + m.layers[i].down_proj = make_qlinear(p + ".mlp.down_proj"); + m.layers[i].num_heads = g_config.num_heads; + m.layers[i].num_kv_heads = g_config.num_kv_heads; + m.layers[i].head_dim = g_config.head_dim; + m.layers[i].rope_theta = g_config.rope_theta; + m.layers[i].rotary_dim = g_config.rotary_dim; + } + } + + return m; +} + +// ============================================================================ +// C ABI +// ============================================================================ + +extern "C" { + +int gp_init(const char* config_json) { + try { + std::string json(config_json); + g_config.model_type = json_string(json, "model_type"); + g_config.hidden_size = json_int(json, "hidden_size", 3072); + g_config.num_layers = json_int(json, "num_hidden_layers", 62); + g_config.num_heads = json_int(json, "num_attention_heads", 48); + g_config.num_kv_heads = json_int(json, "num_key_value_heads", 8); + g_config.head_dim = json_int(json, "head_dim", 128); + g_config.intermediate_size = json_int(json, "intermediate_size", 1536); + g_config.vocab_size = json_int(json, "vocab_size", 200064); + g_config.rms_norm_eps = json_float(json, "rms_norm_eps", 1e-6f); + g_config.rope_theta = json_float(json, "rope_theta", 5000000.0f); + g_config.rotary_dim = json_int(json, "rotary_dim", 64); + g_config.tie_word_embeddings = json_bool(json, "tie_word_embeddings", false); + g_config.use_qk_norm = json_bool(json, "use_qk_norm", true); + g_config.num_local_experts = json_int(json, "num_local_experts", 0); + g_config.num_experts_per_tok = json_int(json, "num_experts_per_tok", 0); + g_config.scoring_func = json_string(json, "scoring_func"); + if (g_config.scoring_func.empty()) g_config.scoring_func = "softmax"; + g_config.sliding_window = json_int(json, "sliding_window", 0); + g_config.sliding_pattern = json_int(json, "sliding_pattern", 0); + + // YaRN RoPE params + g_config.rope_type = json_string(json, "rope_type"); + g_config.yarn_factor = json_float(json, "yarn_factor", 1.0f); + g_config.yarn_beta_fast = json_float(json, "yarn_beta_fast", 32.0f); + g_config.yarn_beta_slow = json_float(json, "yarn_beta_slow", 1.0f); + g_config.yarn_original_max_pos = json_int(json, "yarn_original_max_pos", 4096); + g_config.yarn_mscale = json_float(json, "yarn_mscale", 1.0f); + g_config.yarn_mscale_all_dim = json_float(json, "yarn_mscale_all_dim", 0.0f); + + g_weights.clear(); + g_model.reset(); + g_initialized = true; + g_finalized = false; + + fprintf(stderr, "[gp] Init: model_type=%s layers=%d hidden=%d heads=%d/%d experts=%d rope_theta=%.0f rms_eps=%.1e head_dim=%d\n", + g_config.model_type.c_str(), g_config.num_layers, + g_config.hidden_size, g_config.num_heads, g_config.num_kv_heads, + g_config.num_local_experts, g_config.rope_theta, g_config.rms_norm_eps, + g_config.head_dim); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[gp] init error: %s\n", e.what()); + return -1; + } +} + +int gp_set_weight(const char* key, void* arr_ptr) { + if (!g_initialized || g_finalized) return -1; + try { + auto arr = extract_array(arr_ptr); + std::string k(key); + g_weights.insert_or_assign(k, arr); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[gp] set_weight error for '%s': %s\n", key, e.what()); + return -1; + } +} + +int gp_finalize(void) { + if (!g_initialized || g_finalized) return -1; + try { + fprintf(stderr, "[gp] Finalizing with %zu weights\n", g_weights.size()); + + g_model = std::make_unique(build_model()); + g_finalized = true; + g_weights.clear(); + + fprintf(stderr, "[gp] Model built (%d layers)\n", g_config.num_layers); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[gp] finalize error: %s\n", e.what()); + return -1; + } +} + +int gp_run(void* token_array_ptr, double* out_elapsed_ms) { + if (!g_model) return -1; + try { + auto& tokens = *static_cast(token_array_ptr); + auto t0 = std::chrono::high_resolution_clock::now(); + + // Reset KV caches before forward + for (auto& layer : g_model->layers) { + layer.cache.reset(); + } + + auto output = g_model->forward(tokens); + + // Eval all KV caches + std::vector to_eval; + for (auto& layer : g_model->layers) { + if (layer.cache.has_data()) { + to_eval.push_back(*layer.cache.keys); + to_eval.push_back(*layer.cache.values); + } + } + eval(to_eval); + + // Free intermediate activation buffers (critical for MoE with 256 experts) + // DO NOT clear_cache -- reclaims weight buffers + + auto t1 = std::chrono::high_resolution_clock::now(); + if (out_elapsed_ms) { + *out_elapsed_ms = std::chrono::duration(t1 - t0).count(); + } + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[gp] run error: %s\n", e.what()); + return -1; + } +} + +int gp_num_cache_layers(void) { + return g_model ? (int)g_model->layers.size() : 0; +} + +void* gp_get_k_ptr(int layer_idx) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return nullptr; + auto& c = g_model->layers[layer_idx].cache; + if (!c.keys) return nullptr; + return new mlx::core::array(*c.keys); +} + +void* gp_get_v_ptr(int layer_idx) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return nullptr; + auto& c = g_model->layers[layer_idx].cache; + if (!c.values) return nullptr; + return new mlx::core::array(*c.values); +} + +int gp_kv_shape(int layer_idx, int* kv_heads, int* seq_len, int* head_dim) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return -1; + auto& c = g_model->layers[layer_idx].cache; + if (!c.has_data()) return -2; + *kv_heads = c.keys->shape(1); + *seq_len = c.keys->shape(2); + *head_dim = c.keys->shape(3); + return 0; +} + +void gp_cleanup(void) { + g_model.reset(); + g_weights.clear(); + g_initialized = false; + g_finalized = false; +} + +} // extern "C" diff --git a/Sources/NativePrefillBridge/generic_prefill.h b/Sources/NativePrefillBridge/generic_prefill.h new file mode 100644 index 0000000000..cddc1b96ff --- /dev/null +++ b/Sources/NativePrefillBridge/generic_prefill.h @@ -0,0 +1,50 @@ +// generic_prefill.h — Model-agnostic native prefill bridge +// +// Supports multiple model architectures via runtime config. +// Same weight-sharing pattern as prefill_bridge_v2: Swift passes +// MLXArray.ctx pointers, bridge copies metadata (shares GPU buffer). +#ifndef GENERIC_PREFILL_H +#define GENERIC_PREFILL_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// Initialize with model config JSON string +// Parses model_type, layer count, dimensions, etc. +int gp_init(const char* config_json); + +// Set a weight tensor (pass Swift's MLXArray.ctx pointer) +int gp_set_weight(const char* key, void* arr_ptr); + +// Mark initialization complete — builds model from weights +int gp_finalize(void); + +// Run prefill on token array (pass MLXArray.ctx pointer) +// Returns 0 on success +int gp_run(void* token_array_ptr, double* out_elapsed_ms); + +// Get number of KV cache layers +int gp_num_cache_layers(void); + +// Get K/V array pointers for cache injection into Swift +// Returns heap-allocated mlx::core::array* (caller takes ownership) +void* gp_get_k_ptr(int layer_idx); +void* gp_get_v_ptr(int layer_idx); + +// KV shape info +int gp_kv_shape(int layer_idx, int* kv_heads, int* seq_len, int* head_dim); + +// Cleanup +void gp_cleanup(void); + +// Allocator bug repro (standalone test, no model needed) +int gp_repro_allocator_bug(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Sources/NativePrefillBridge/libgeneric_prefill.dylib b/Sources/NativePrefillBridge/libgeneric_prefill.dylib new file mode 100755 index 0000000000..ada3a28ba5 Binary files /dev/null and b/Sources/NativePrefillBridge/libgeneric_prefill.dylib differ diff --git a/Sources/NativePrefillBridge/mlx_allocator_repro.cpp b/Sources/NativePrefillBridge/mlx_allocator_repro.cpp new file mode 100644 index 0000000000..af12334976 --- /dev/null +++ b/Sources/NativePrefillBridge/mlx_allocator_repro.cpp @@ -0,0 +1,129 @@ +// Minimal repro: MLX GPU compute path reads wrong buffer for live arrays +// +// PROVEN: CPU memory is stable. MLX sum(abs()) returns wrong values. +// This test splits the observer to isolate where the GPU path diverges. + +#include +#include +#include +#include "mlx/mlx.h" + +using namespace mlx::core; + +// CPU-side float16 abssum for ground truth +static double cpu_f16_abssum(const array& a) { + auto* raw = static_cast<_Float16*>(const_cast(a.buffer()).raw_ptr()); + double s = 0; + for (int i = 0; i < (int)a.size(); i++) { + s += std::abs(static_cast(raw[i])); + } + return s; +} + +// CPU-side: read first N float16 values and return a checksum +static uint64_t cpu_f16_hash(const array& a, int n = 256) { + auto* raw = static_cast(const_cast(a.buffer()).raw_ptr()); + uint64_t h = 0; + for (int i = 0; i < std::min(n, (int)a.size()); i++) { + h = h * 31 + raw[i]; + } + return h; +} + +extern "C" { + +int gp_repro_allocator_bug(void) { + fprintf(stderr, "\n=== MLX GPU BINDING BUG REPRO ===\n"); + + // 1. Create and eval a persistent array + auto long_lived = random::normal({32768, 64}, float16); + eval({long_lived}); + + double cpu_baseline = cpu_f16_abssum(long_lived); + uint64_t hash_baseline = cpu_f16_hash(long_lived); + void* buf_ptr = long_lived.buffer().raw_ptr(); + fprintf(stderr, "baseline: cpu_abssum=%.2f buf=%p hash=%llx\n", + cpu_baseline, buf_ptr, hash_baseline); + + // 2. Test MLX ops on long_lived BEFORE any pressure + { + auto a = abs(long_lived); + eval({a}); + double cpu_abs = cpu_f16_abssum(a); + float mlx_sum_a = sum(a).item(); + fprintf(stderr, "pre-pressure: abs cpu_abssum=%.2f sum(abs) via mlx=%.6f\n", + cpu_abs, mlx_sum_a); + } + + // 3. One round of pressure + { + int D = 4096; + auto x = random::normal({4, D}, float16); + auto q = matmul(x, transpose(random::normal({D, D}, float16))); + auto k = matmul(x, transpose(random::normal({D, D}, float16))); + auto v = matmul(x, transpose(random::normal({D, D}, float16))); + auto out = matmul(x, transpose(random::normal({D, D}, float16))); + auto gate = matmul(x, transpose(random::normal({14336, D}, float16))); + auto up = matmul(x, transpose(random::normal({14336, D}, float16))); + auto down = matmul(gate * sigmoid(gate) * up, + transpose(random::normal({D, 14336}, float16))); + eval({out, down}); + } + + // 4. Test each op individually AFTER pressure + fprintf(stderr, "\n--- after 1 round of pressure ---\n"); + + // 4a. CPU ground truth + double cpu_after = cpu_f16_abssum(long_lived); + uint64_t hash_after = cpu_f16_hash(long_lived); + void* ptr_after = long_lived.buffer().raw_ptr(); + fprintf(stderr, "cpu: abssum=%.2f hash=%llx ptr=%p %s\n", + cpu_after, hash_after, ptr_after, + (hash_after == hash_baseline) ? "STABLE" : "CHANGED"); + + // 4b. abs() alone — eval it, then check its output on CPU + { + auto a = abs(long_lived); + eval({a}); + void* abs_ptr = const_cast(a.buffer()).raw_ptr(); + double cpu_abs_out = cpu_f16_abssum(a); + fprintf(stderr, "abs(long_lived): output cpu_abssum=%.2f output buf=%p same_as_input=%s\n", + cpu_abs_out, abs_ptr, (abs_ptr == buf_ptr) ? "YES(donated!)" : "no"); + } + + // 4c. sum() on a tiny known-good array + { + auto tiny = array({1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); + eval({tiny}); + float s = sum(tiny).item(); + fprintf(stderr, "sum([1..5]): mlx=%.6f expected=15.0 %s\n", + s, (std::abs(s - 15.0f) < 0.01f) ? "OK" : "WRONG"); + } + + // 4d. Full sum(abs(long_lived)) via MLX + { + float mlx_val = sum(abs(long_lived)).item(); + fprintf(stderr, "sum(abs(long_lived)): mlx=%.6f cpu=%.2f ratio=%.4f %s\n", + mlx_val, cpu_after, mlx_val / cpu_after, + (std::abs(mlx_val - cpu_after) / cpu_after > 0.01) ? "DIVERGED" : "OK"); + } + + // 4e. Force CPU eval path if possible: convert to float32, eval, read back + { + auto f32 = astype(long_lived, float32); + eval({f32}); + auto* f32_raw = static_cast(f32.buffer().raw_ptr()); + double cpu_f32_sum = 0; + for (int i = 0; i < std::min(1000, (int)f32.size()); i++) { + cpu_f32_sum += std::abs(f32_raw[i]); + } + float mlx_f32_sum = sum(abs(f32)).item(); + fprintf(stderr, "astype(f32): cpu_first1000=%.2f mlx_full=%.6f\n", + cpu_f32_sum, mlx_f32_sum); + } + + fprintf(stderr, "=== END REPRO ===\n\n"); + return 0; +} + +} // extern "C" diff --git a/Sources/NativePrefillBridge/prefill_bridge_gemma.cpp b/Sources/NativePrefillBridge/prefill_bridge_gemma.cpp new file mode 100644 index 0000000000..deb20242a7 --- /dev/null +++ b/Sources/NativePrefillBridge/prefill_bridge_gemma.cpp @@ -0,0 +1,795 @@ +// prefill_bridge_gemma.cpp — Gemma-family native prefill bridge +// +// Accepts EXTERNAL weight arrays from Swift instead of loading safetensors. +// The arr_ptr passed to gemma_set_weight() is MLXArray.ctx — a raw +// mlx::core::array* owned by Swift. We copy the mlx::core::array (cheap: +// ~100 bytes metadata, shared_ptr to underlying buffer) so the bridge holds +// a reference but does NOT own or free the Swift-side array. +// +// Forward pass is IDENTICAL to prefill_bridge.cpp: +// - 15 non-shared layers (0–14) +// - Sliding attention (head_dim=256) at layers 0-3, 5-8, 10-13 +// - Full attention (head_dim=512) at layers 4, 9, 14 +// - GeGLU MLP (gelu_approx), 4-bit quantized weights +// - Per-layer input gating +// - RMSNorm with direct weight (NOT 1+weight) +// - Proportional RoPE for full layers, standard RoPE for sliding +// - Causal SDPA +// +// Build: +// clang++ -std=c++20 -O3 -shared -fPIC \ +// -I/opt/homebrew/lib/python3.13/site-packages/mlx/include \ +// -I/Users/tom/dev/mlx-swift/Source/Cmlx/mlx-c \ +// -I/tmp \ +// -L/opt/homebrew/lib/python3.13/site-packages/mlx/lib -lmlx \ +// -framework Metal -framework Foundation -framework Accelerate \ +// -Wl,-rpath,/opt/homebrew/lib/python3.13/site-packages/mlx/lib \ +// -o /tmp/libprefill_bridge_v2.dylib /tmp/prefill_bridge_v2.cpp + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "mlx/mlx.h" +#include "prefill_bridge_gemma.h" + +// Private mlx-c header — gives us mlx_array_get_() to extract C++ array +// from the opaque C handle. We only use this to understand the struct layout; +// the actual arr_ptr from Swift is MLXArray.ctx which is already mlx::core::array*. +// Including it anyway for documentation and the inline helpers. +#include "mlx/c/private/array.h" + +using namespace mlx::core; + +// ============================================================================ +// Architecture constants — set by gemma_init() +// ============================================================================ +static int g_num_layers = 0; +static int g_hidden_size = 0; +static int g_num_heads = 0; +static int g_num_kv_heads = 0; +static int g_sliding_window = 0; +static int g_sliding_pattern = 0; // every Nth layer is full attention + +// Derived constants (Gemma 4 E2B defaults — recomputed in gemma_init) +static int g_head_dim_slide = 256; +static int g_head_dim_full = 512; +static int g_intermediate = 0; +static int g_total_layers = 0; +static int g_hidden_per_layer = 256; + +// Quantization params (hardcoded for 4-bit Gemma 4 E2B) +static constexpr int BITS = 4; +static constexpr int GROUP_SIZE = 64; +static constexpr float RMS_EPS = 1e-6f; + +// RoPE params +static constexpr float ROPE_THETA_SLIDING = 10000.0f; +static constexpr float ROPE_THETA_FULL = 1000000.0f; + +static bool is_full_attention(int layer_idx) { + return g_sliding_pattern > 0 && ((layer_idx + 1) % g_sliding_pattern == 0); +} + +// ============================================================================ +// Helper: GELU approximate (tanh approximation) +// ============================================================================ +static array gelu_approx(const array& x) { + // Must match Python's nn.gelu_approx exactly: + // 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x**3))) + // + // Two critical details: + // 1. x**3 = power(x, 3) — single op, one final round. + // x*x*x = two bf16 multiplies with intermediate rounding → different. + // 2. Python float scalars are "universal" type that don't promote bf16. + // C++ array(float, bf16) pre-rounds; array(float) promotes to f32. + // Use bf16 constants (pre-rounded) + power() to get closest match. + auto dt = x.dtype(); + static const float kSqrt2OverPi = 0.7978845608028654f; + auto x3 = power(x, array(3, dt)); + auto inner = array(kSqrt2OverPi, dt) * (x + array(0.044715f, dt) * x3); + return array(0.5f, dt) * x * (array(1.0f, dt) + tanh(inner)); +} + +// ============================================================================ +// Layer components — same structs as v1 but weights stored as array copies +// ============================================================================ + +struct QuantizedLinear { + array weight; // uint32 packed + array scales; // bfloat16 + array biases; // bfloat16 + + array operator()(const array& x) const { + return quantized_matmul( + x, weight, scales, biases, + /*transpose=*/true, + /*group_size=*/GROUP_SIZE, + /*bits=*/BITS, + /*mode=*/"affine"); + } +}; + +struct RMSNorm { + array weight; // learned scale — used directly (NOT 1+weight) + + array operator()(const array& x) const { + return fast::rms_norm(x, weight, RMS_EPS); + } +}; + +static array rms_norm_no_scale(const array& x) { + return fast::rms_norm(x, std::nullopt, RMS_EPS); +} + +struct QuantizedEmbedding { + array weight; // [vocab, packed_cols] uint32 + array scales; // [vocab, num_groups] bfloat16 + array biases; // [vocab, num_groups] bfloat16 + + array operator()(const array& indices) const { + auto w = take(weight, indices, 0); + auto s = take(scales, indices, 0); + auto b = take(biases, indices, 0); + return dequantize(w, s, b, GROUP_SIZE, BITS, "affine"); + } +}; + +struct ScaledLinear { + array weight; // [out, in] bfloat16 + float scalar; + + array operator()(const array& x) const { + auto out = matmul(x, transpose(weight)); + // Python ScaledLinear: (x @ W.T) * scalar, where scalar is Python float + // When W is bf16, x is bf16, matmul output is bf16 + // bf16 * Python float → bf16 (MLX keeps lower dtype) + return out * array(scalar, bfloat16); + } +}; + +struct Attention { + QuantizedLinear q_proj, k_proj; + std::shared_ptr v_proj; // optional: null when k_eq_v + QuantizedLinear o_proj; + RMSNorm q_norm, k_norm; + int head_dim; + int num_heads; + int num_kv_heads; + bool is_sliding; + float rope_theta; + array rope_freqs; // precomputed for full (proportional), empty for sliding + + mutable array last_k = array({}, bfloat16); + mutable array last_v = array({}, bfloat16); + + array operator()(const array& x) const { + int B = x.shape(0); + int S = x.shape(1); + + auto q = q_proj(x); + auto k = k_proj(x); + auto v = v_proj ? (*v_proj)(x) : k; // k_eq_v: V = K when no v_proj + + q = transpose(reshape(q, {B, S, num_heads, head_dim}), {0, 2, 1, 3}); + k = transpose(reshape(k, {B, S, num_kv_heads, head_dim}), {0, 2, 1, 3}); + v = transpose(reshape(v, {B, S, num_kv_heads, head_dim}), {0, 2, 1, 3}); + + q = q_norm(q); + k = k_norm(k); + v = rms_norm_no_scale(v); + + // RoPE: sliding = standard, full = proportional (precomputed freqs) + if (is_sliding) { + q = fast::rope(q, head_dim, false, rope_theta, 1.0f, 0); + k = fast::rope(k, head_dim, false, rope_theta, 1.0f, 0); + } else { + q = fast::rope(q, head_dim, false, std::nullopt, 1.0f, 0, rope_freqs); + k = fast::rope(k, head_dim, false, std::nullopt, 1.0f, 0, rope_freqs); + } + + // Store K/V in bfloat16 to match Swift's cache dtype + // Python's cache.update_and_fetch() stores bf16, then SDPA reads bf16 back. + // We must use bf16 K/V for SDPA to match Python exactly. + last_k = astype(k, bfloat16); + last_v = astype(v, bfloat16); + k = last_k; + v = last_v; + + // SDPA (scale=1.0 for Gemma4) + float scale = 1.0f; + auto make_attn = [&]() -> array { + if (is_sliding && S > g_sliding_window) { + auto rinds = arange(S); + auto linds = reshape(arange(S), {S, 1}); + auto mask_arr = (linds >= rinds) & (linds < (rinds + g_sliding_window)); + return fast::scaled_dot_product_attention( + q, k, v, scale, /*mask_mode=*/"", /*mask_arr=*/mask_arr); + } else if (is_sliding) { + return fast::scaled_dot_product_attention( + q, k, v, scale, "causal"); + } else { + return fast::scaled_dot_product_attention( + q, k, v, scale, "causal"); + } + }; + auto attn_out = make_attn(); + + attn_out = reshape( + transpose(attn_out, {0, 2, 1, 3}), + {B, S, num_heads * head_dim}); + + return o_proj(attn_out); + } +}; + +struct MLP { + QuantizedLinear gate_proj, up_proj, down_proj; + + array operator()(const array& x) const { + auto gate = gate_proj(x); + auto up = up_proj(x); + return down_proj(gelu_approx(gate) * up); + } +}; + +struct TransformerLayer { + RMSNorm input_layernorm; + Attention self_attn; + RMSNorm post_attention_layernorm; + RMSNorm pre_feedforward_layernorm; + MLP mlp; + RMSNorm post_feedforward_layernorm; + + // PLE fields — optional for models without PLE + std::shared_ptr per_layer_input_gate; + std::shared_ptr per_layer_projection; + std::shared_ptr post_per_layer_input_norm; + std::shared_ptr layer_scalar; + bool has_ple = false; + + array operator()(const array& x, const array& per_layer_input) const { + // Pre-norm attention with residual + auto residual = x; + auto h = input_layernorm(x); + h = self_attn(h); + h = post_attention_layernorm(h); + h = residual + h; + + // Pre-norm MLP with residual + residual = h; + auto ff = pre_feedforward_layernorm(h); + ff = mlp(ff); + ff = post_feedforward_layernorm(ff); + h = residual + ff; + + // Per-layer input gating (PLE) — only for models with PLE + if (has_ple) { + residual = h; + auto gate = (*per_layer_input_gate)(h); + gate = gelu_approx(gate); + gate = gate * per_layer_input; + gate = (*per_layer_projection)(gate); + gate = (*post_per_layer_input_norm)(gate); + h = residual + gate; + + h = h * (*layer_scalar); + } + + return h; + } +}; + +struct Model { + QuantizedEmbedding embed_tokens; + std::shared_ptr embed_tokens_per_layer; + std::shared_ptr per_layer_model_projection; + std::shared_ptr per_layer_projection_norm; + bool has_ple = false; + std::vector layers; + RMSNorm final_norm; + + // Precomputed scale constants (avoid per-call array creation) + array embed_scale_arr = array(0.0f); + array pl_embed_scale_arr = array(0.0f); + array pl_input_scale_arr = array(0.0f); + + void precompute_scales() { + // Match Python: scalars stored as bf16 (Python float * bf16 → bf16) + embed_scale_arr = array(std::sqrt(static_cast(g_hidden_size)), bfloat16); + pl_embed_scale_arr = array(std::sqrt(static_cast(g_hidden_per_layer)), bfloat16); + pl_input_scale_arr = array(std::pow(2.0f, -0.5f), bfloat16); + } + + array forward(const array& token_ids) const { + int B = token_ids.shape(0); + int S = token_ids.shape(1); + + auto h = embed_tokens(token_ids) * embed_scale_arr; + + // PLE (Per-Layer Embeddings) — optional, only for models with hiddenSizePerLayerInput > 0 + array combined_per_layer = array(0.0f); + if (has_ple) { + auto per_layer_inputs = (*embed_tokens_per_layer)(token_ids) * pl_embed_scale_arr; + per_layer_inputs = reshape(per_layer_inputs, {B, S, g_total_layers, g_hidden_per_layer}); + + auto per_layer_proj = per_layer_model_projection->operator()(h); + per_layer_proj = reshape(per_layer_proj, {B, S, g_total_layers, g_hidden_per_layer}); + per_layer_proj = (*per_layer_projection_norm)(per_layer_proj); + + combined_per_layer = (per_layer_proj + per_layer_inputs) * pl_input_scale_arr; + } + + // Run through non-shared layers + for (int i = 0; i < g_num_layers; i++) { + if (has_ple) { + auto pli = slice(combined_per_layer, + {0, 0, i, 0}, + {B, S, i + 1, g_hidden_per_layer}); + pli = reshape(pli, {B, S, g_hidden_per_layer}); + h = layers[i](h, pli); + } else { + // No PLE: pass zero PLE input + auto pli = zeros({B, S, std::max(g_hidden_per_layer, 1)}, h.dtype()); + h = layers[i](h, pli); + } + } + + // Skip final norm during prefill — K/V eval doesn't need it + return h; + } +}; + +// ============================================================================ +// Global state +// ============================================================================ +static std::shared_ptr g_model = nullptr; +static std::unordered_map g_weight_store; +static bool g_initialized = false; +static bool g_finalized = false; + +// ============================================================================ +// Weight extraction from Swift's MLXArray.ctx +// +// Swift passes MLXArray.ctx which is the void* inside the mlx_array struct. +// That void* points to a heap-allocated mlx::core::array. +// We COPY the mlx::core::array (cheap — shares underlying data buffer via +// shared_ptr) so the bridge holds a reference without owning Swift's object. +// ============================================================================ +static array extract_array(void* arr_ptr) { + if (!arr_ptr) { + throw std::runtime_error("gemma_set_weight: null arr_ptr"); + } + // arr_ptr IS the mlx::core::array* (the ctx field from mlx_array struct) + auto* cpp_array = static_cast(arr_ptr); + // Copy — shares underlying data buffer, just bumps refcount (~100 bytes metadata) + return *cpp_array; +} + +// ============================================================================ +// Build helpers — pull from g_weight_store +// ============================================================================ +static array get_weight(const std::string& key) { + auto it = g_weight_store.find(key); + if (it != g_weight_store.end()) return it->second; + fprintf(stderr, "[pb2] WARNING: weight not found: %s\n", key.c_str()); + throw std::runtime_error("Missing weight: " + key); +} + +static bool has_weight(const std::string& key) { + return g_weight_store.count(key) > 0; +} + +static QuantizedLinear make_quantized_linear(const std::string& prefix) { + return { + get_weight(prefix + ".weight"), + get_weight(prefix + ".scales"), + get_weight(prefix + ".biases"), + }; +} + +static RMSNorm make_rms_norm(const std::string& prefix) { + return {get_weight(prefix + ".weight")}; +} + +static QuantizedEmbedding make_quantized_embedding(const std::string& prefix) { + return { + get_weight(prefix + ".weight"), + get_weight(prefix + ".scales"), + get_weight(prefix + ".biases"), + }; +} + +static Attention make_attention(const std::string& prefix, int layer_idx) { + bool full = is_full_attention(layer_idx); + int hd = full ? g_head_dim_full : g_head_dim_slide; + float theta = full ? ROPE_THETA_FULL : ROPE_THETA_SLIDING; + + // Proportional RoPE freqs for full-attention layers + // partial_rotary_factor=0.25: only first 25% of dims are rotated, + // remaining get inf (identity). Matches Python's ProportionalRoPE. + array freqs({}, float32); + if (full) { + int rotated_dims = hd / 4; // partial_rotary_factor=0.25 + auto exponents = arange(0, rotated_dims, 2, float32); + exponents = exponents / static_cast(hd); + auto rotated_freqs = power(array(theta, float32), exponents); + auto inf_freqs = mlx::core::full( + {(hd - rotated_dims) / 2}, + std::numeric_limits::infinity(), float32); + freqs = concatenate({rotated_freqs, inf_freqs}); + } + + // v_proj: present for sliding layers, absent for full layers with k_eq_v + std::shared_ptr v; + if (has_weight(prefix + ".v_proj.weight")) { + auto _v = make_quantized_linear(prefix + ".v_proj"); + v = std::make_shared(std::move(_v)); + } + + return { + make_quantized_linear(prefix + ".q_proj"), + make_quantized_linear(prefix + ".k_proj"), + std::move(v), + make_quantized_linear(prefix + ".o_proj"), + make_rms_norm(prefix + ".q_norm"), + make_rms_norm(prefix + ".k_norm"), + hd, + g_num_heads, + g_num_kv_heads, + !full, + theta, + freqs, + }; +} + +static MLP make_mlp(const std::string& prefix) { + return { + make_quantized_linear(prefix + ".gate_proj"), + make_quantized_linear(prefix + ".up_proj"), + make_quantized_linear(prefix + ".down_proj"), + }; +} + +static TransformerLayer make_layer(int layer_idx) { + std::string prefix = "layers." + std::to_string(layer_idx); + + // Build core layer components + auto attn = make_attention(prefix + ".self_attn", layer_idx); + auto mlp_block = make_mlp(prefix + ".mlp"); + + // PLE fields — only if weights exist + std::shared_ptr ple_gate, ple_proj; + std::shared_ptr ple_norm; + std::shared_ptr ple_scalar; + bool layer_has_ple = false; + if (has_weight(prefix + ".per_layer_input_gate.weight")) { + auto _g = make_quantized_linear(prefix + ".per_layer_input_gate"); + ple_gate = std::make_shared(std::move(_g)); + auto _p = make_quantized_linear(prefix + ".per_layer_projection"); + ple_proj = std::make_shared(std::move(_p)); + auto _n = make_rms_norm(prefix + ".post_per_layer_input_norm"); + ple_norm = std::make_shared(std::move(_n)); + auto _s = get_weight(prefix + ".layer_scalar"); + ple_scalar = std::make_shared(std::move(_s)); + layer_has_ple = true; + } + + return TransformerLayer{ + make_rms_norm(prefix + ".input_layernorm"), + std::move(attn), + make_rms_norm(prefix + ".post_attention_layernorm"), + make_rms_norm(prefix + ".pre_feedforward_layernorm"), + std::move(mlp_block), + make_rms_norm(prefix + ".post_feedforward_layernorm"), + std::move(ple_gate), std::move(ple_proj), + std::move(ple_norm), std::move(ple_scalar), + layer_has_ple, + }; +} + +static std::shared_ptr build_model() { + auto embed_tokens = make_quantized_embedding("embed_tokens"); + + // PLE: optional + bool ple_active = has_weight("embed_tokens_per_layer.weight"); + std::shared_ptr embed_tokens_per_layer; + std::shared_ptr per_layer_model_projection; + std::shared_ptr per_layer_projection_norm; + if (ple_active) { + auto _e = make_quantized_embedding("embed_tokens_per_layer"); + embed_tokens_per_layer = std::make_shared(std::move(_e)); + float projection_scalar = 1.0f / std::sqrt(static_cast(g_hidden_size)); + auto _sl = ScaledLinear{get_weight("per_layer_model_projection.weight"), projection_scalar}; + per_layer_model_projection = std::make_shared(std::move(_sl)); + auto _rn = make_rms_norm("per_layer_projection_norm"); + per_layer_projection_norm = std::make_shared(std::move(_rn)); + fprintf(stderr, "[pb2] PLE enabled\n"); + } else { + fprintf(stderr, "[pb2] PLE disabled (no embed_tokens_per_layer weights)\n"); + } + + std::vector layers; + layers.reserve(g_num_layers); + for (int i = 0; i < g_num_layers; i++) { + fprintf(stderr, "[pb2] Building layer %d/%d (%s, head_dim=%d)\n", + i, g_num_layers, + is_full_attention(i) ? "full" : "sliding", + is_full_attention(i) ? g_head_dim_full : g_head_dim_slide); + layers.push_back(make_layer(i)); + } + + auto final_norm = make_rms_norm("norm"); + + return std::shared_ptr(new Model{ + std::move(embed_tokens), + std::move(embed_tokens_per_layer), + std::move(per_layer_model_projection), + std::move(per_layer_projection_norm), + ple_active, + std::move(layers), + std::move(final_norm), + }); +} + +// ============================================================================ +// C ABI +// ============================================================================ +extern "C" { + +int gemma_init(int num_layers, int hidden_size, int num_heads, int num_kv_heads, + int sliding_window, int sliding_window_pattern) { + try { + g_num_layers = num_layers; + g_hidden_size = hidden_size; + g_num_heads = num_heads; + g_num_kv_heads = num_kv_heads; + g_sliding_window = sliding_window; + g_sliding_pattern = sliding_window_pattern; + + // Derived constants for Gemma 4 E2B architecture + // head_dim_slide = hidden_size * 2 / num_heads (256 for 1536/8 * ... — actually from config) + // For Gemma 4 E2B: slide=256, full=512, intermediate=6144 + // TODO: Make these configurable if needed for other models + g_head_dim_slide = 256; + g_head_dim_full = 512; + g_intermediate = hidden_size * 4; // 6144 for hidden=1536 + g_total_layers = 35; // Gemma 4 E2B total + g_hidden_per_layer = 256; // hidden_size_per_layer_input + + g_weight_store.clear(); + g_model.reset(); + g_initialized = true; + g_finalized = false; + + fprintf(stderr, "[pb2] Initialized: %d layers, hidden=%d, heads=%d/%d, pattern=%d\n", + num_layers, hidden_size, num_heads, num_kv_heads, sliding_window_pattern); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[pb2] init error: %s\n", e.what()); + return -1; + } +} + +int gemma_set_weight(const char* key, void* arr_ptr) { + if (!g_initialized || g_finalized) { + fprintf(stderr, "[pb2] set_weight called in wrong state (init=%d, final=%d)\n", + g_initialized, g_finalized); + return -1; + } + + try { + array copied = extract_array(arr_ptr); + g_weight_store.insert_or_assign(std::string(key), std::move(copied)); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[pb2] set_weight error for '%s': %s\n", key, e.what()); + return -1; + } +} + +int gemma_finalize(void) { + if (!g_initialized || g_finalized) { + fprintf(stderr, "[pb2] finalize called in wrong state\n"); + return -1; + } + + try { + fprintf(stderr, "[pb2] Finalizing with %zu weight tensors\n", g_weight_store.size()); + g_model = build_model(); + g_model->precompute_scales(); + g_finalized = true; + + // Clear the weight store — model now holds all the array copies + g_weight_store.clear(); + + fprintf(stderr, "[pb2] Model built successfully (zero-copy weight sharing with Swift)\n"); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[pb2] finalize error: %s\n", e.what()); + return -1; + } +} + +// Zero-copy variant: accepts raw mlx::core::array* (avoids GPU→CPU→GPU roundtrip for tokens) +extern "C" +int gemma_run_array(void* token_arr_ptr, + double* out_elapsed_ms, float* out_checksum) { + if (!g_model || !token_arr_ptr) { + fprintf(stderr, "[pb2] run_array called before finalize or with null ptr\n"); + return -1; + } + + try { + // Zero-copy: use the Swift MLXArray's underlying data directly + auto& tokens_1d = *static_cast(token_arr_ptr); + auto tokens = reshape(tokens_1d, {1, static_cast(tokens_1d.size())}); + + auto t0 = std::chrono::high_resolution_clock::now(); + auto output = g_model->forward(tokens); + + std::vector cache_arrays; + for (auto& layer : g_model->layers) { + cache_arrays.push_back(layer.self_attn.last_k); + cache_arrays.push_back(layer.self_attn.last_v); + } + eval(cache_arrays); + auto t1 = std::chrono::high_resolution_clock::now(); + + double elapsed_ms = std::chrono::duration(t1 - t0).count(); + + auto& layer0_k = g_model->layers[0].self_attn.last_k; + eval(layer0_k); + auto checksum_arr = astype(sum(layer0_k), float32); + eval(checksum_arr); + float checksum = checksum_arr.item(); + + if (out_elapsed_ms) *out_elapsed_ms = elapsed_ms; + if (out_checksum) *out_checksum = checksum; + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[pb2] run_array error: %s\n", e.what()); + return -1; + } +} + +int gemma_run(const int32_t* token_ids, int token_count, + double* out_elapsed_ms, float* out_checksum) { + if (!g_model) { + fprintf(stderr, "[pb2] run called before finalize\n"); + return -1; + } + + try { + // Create token ID tensor [1, token_count] + auto tokens = array(token_ids, {1, token_count}, int32); + eval(tokens); + + // Timed forward pass + auto t0 = std::chrono::high_resolution_clock::now(); + auto output = g_model->forward(tokens); + + // Eval all layer K AND V tensors + std::vector cache_arrays; + for (auto& layer : g_model->layers) { + cache_arrays.push_back(layer.self_attn.last_k); + cache_arrays.push_back(layer.self_attn.last_v); + } + eval(cache_arrays); + auto t1 = std::chrono::high_resolution_clock::now(); + + double elapsed_ms = std::chrono::duration(t1 - t0).count(); + + // Checksum: sum of layer 0's K + auto& layer0_k = g_model->layers[0].self_attn.last_k; + eval(layer0_k); + auto checksum_arr = astype(sum(layer0_k), float32); + eval(checksum_arr); + float checksum = checksum_arr.item(); + + if (out_elapsed_ms) *out_elapsed_ms = elapsed_ms; + if (out_checksum) *out_checksum = checksum; + + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[pb2] run error: %s\n", e.what()); + return -1; + } +} + +void gemma_cleanup(void) { + g_model.reset(); + g_weight_store.clear(); + g_initialized = false; + g_finalized = false; + fprintf(stderr, "[pb2] Cleaned up\n"); +} + +} // extern "C" + +// ============================================================================ +// K/V export for Swift cache injection +// ============================================================================ + +// Get number of non-shared layers (= number of caches to populate) +extern "C" int gemma_num_layers() { + return g_model ? (int)g_model->layers.size() : 0; +} + +// Get K/V shape for a layer after forward: [1, kv_heads, seq_len, head_dim] +extern "C" int gemma_kv_shape(int layer_idx, int* out_kv_heads, int* out_seq_len, int* out_head_dim) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return -1; + auto& k = g_model->layers[layer_idx].self_attn.last_k; + if (k.size() == 0) return -2; + // Shape: [B, kv_heads, seq_len, head_dim] + *out_kv_heads = k.shape(1); + *out_seq_len = k.shape(2); + *out_head_dim = k.shape(3); + return 0; +} + +// Get byte size of K (or V) for a layer +extern "C" size_t gemma_kv_nbytes(int layer_idx) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return 0; + auto& k = g_model->layers[layer_idx].self_attn.last_k; + return k.nbytes(); +} + +// Export K and V as CPU-side bfloat16 data. +// Caller allocates out_k and out_v buffers of gemma_kv_nbytes() each. +extern "C" int gemma_export_kv(int layer_idx, void* out_k, void* out_v) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return -1; + auto& attn = g_model->layers[layer_idx].self_attn; + if (attn.last_k.size() == 0) return -2; + + eval({attn.last_k, attn.last_v}); + + std::memcpy(out_k, attn.last_k.data(), attn.last_k.nbytes()); + std::memcpy(out_v, attn.last_v.data(), attn.last_v.nbytes()); + return 0; +} + +// Checksum of a layer's K: sum(K) as float +extern "C" float gemma_layer_k_checksum(int layer_idx) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return 0; + auto& k = g_model->layers[layer_idx].self_attn.last_k; + if (k.size() == 0) return 0; + eval(k); + auto s = astype(sum(k), float32); + eval(s); + return s.item(); +} + +// Zero-copy K/V access: return raw mlx::core::array* pointers +// Swift can pass these to mlx-c functions via the ctx field +extern "C" void* gemma_get_k_ptr(int layer_idx) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return nullptr; + return &(g_model->layers[layer_idx].self_attn.last_k); +} +extern "C" void* gemma_get_v_ptr(int layer_idx) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return nullptr; + return &(g_model->layers[layer_idx].self_attn.last_v); +} + +// Create new heap-allocated mlx::core::array copies of K/V for a layer. +// Returns raw pointers via out params. Shares underlying GPU data buffer via shared_ptr. +// Caller takes ownership and must eventually delete (or pass to MLXArray which handles it). +extern "C" void gemma_get_kv_handles(int layer_idx, void** out_k_ptr, void** out_v_ptr) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) { + if (out_k_ptr) *out_k_ptr = nullptr; + if (out_v_ptr) *out_v_ptr = nullptr; + return; + } + auto& attn = g_model->layers[layer_idx].self_attn; + + // new array(...) creates a lightweight copy that shares the underlying data buffer + if (out_k_ptr) *out_k_ptr = new mlx::core::array(attn.last_k); + if (out_v_ptr) *out_v_ptr = new mlx::core::array(attn.last_v); +} + diff --git a/Sources/NativePrefillBridge/prefill_bridge_gemma.h b/Sources/NativePrefillBridge/prefill_bridge_gemma.h new file mode 100644 index 0000000000..63e758c1dd --- /dev/null +++ b/Sources/NativePrefillBridge/prefill_bridge_gemma.h @@ -0,0 +1,43 @@ +// prefill_bridge_gemma.h — Gemma-family native prefill bridge +// +// Dedicated prefill bridge for Gemma-4 E2B architectures. +// Accepts external weight arrays instead of loading its own. +#ifndef PREFILL_BRIDGE_GEMMA_H +#define PREFILL_BRIDGE_GEMMA_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// Initialize bridge with model architecture (no weight loading) +int gemma_init(int num_layers, int hidden_size, int num_heads, int num_kv_heads, + int sliding_window, int sliding_window_pattern); + +// Set a weight tensor for the bridge (pass Swift's mlx_array ctx pointer) +// key: weight name like "layers.0.self_attn.q_proj.weight" +// arr_ptr: the mlx_array opaque handle from Swift (MLXArray.ctx) +int gemma_set_weight(const char* key, void* arr_ptr); + +// Mark initialization complete (all weights set) +int gemma_finalize(void); + +// Run prefill +int gemma_run(const int32_t* token_ids, int token_count, + double* out_elapsed_ms, float* out_checksum); + +// Run prefill with MLXArray pointer (zero-copy) +int gemma_run_array(void* token_arr_ptr, double* out_elapsed_ms, float* out_checksum); + +// Get K/V cache handles for a layer +void gemma_get_kv_handles(int layer_idx, void** out_k_ptr, void** out_v_ptr); + +// Cleanup +void gemma_cleanup(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Sources/NativePrefillBridge/prefill_bridge_qwen.cpp b/Sources/NativePrefillBridge/prefill_bridge_qwen.cpp new file mode 100644 index 0000000000..d88b9ed86d --- /dev/null +++ b/Sources/NativePrefillBridge/prefill_bridge_qwen.cpp @@ -0,0 +1,1061 @@ +// prefill_bridge_qwen.cpp — Qwen-family native prefill bridge +// +// Dedicated bridge for Qwen2, Qwen3 (dense), and Qwen3 MoE. +// Key differences from generic_prefill.cpp: +// - Qwen-specific eval barrier tuning +// - MoE routing optimized for softmax-only (no sigmoid/correction_bias) +// - Single forward path per architecture variant (no runtime dispatch) +// - Independent from other model families — changes here don't affect +// Mistral, Phi-4, GPT-OSS, etc. +// +// Architecture support: +// - qwen2: dense with optional attention bias, no QK norm +// - qwen3: dense with QK norm (per-head, after reshape) +// - qwen3_moe: MoE with SwitchGLU, softmax routing, QK norm + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mlx/mlx.h" +#include "prefill_bridge_qwen.h" + +using namespace mlx::core; + +// ============================================================================ +// Per-stage profiler — enabled by QWEN_PROFILE=1 +// +// Forces eval+sync after each stage to get true GPU wall-clock time. +// This DESTROYS graph fusion, so numbers will be ~2-3x slower than +// production. The point is relative attribution, not absolute speed. +// ============================================================================ + +struct QwenProfiler { + bool enabled = false; + + // Accumulate across all layers + double embed_ms = 0, input_norm_ms = 0; + double qkv_proj_ms = 0, qk_norm_ms = 0, rope_ms = 0; + double kv_append_ms = 0, sdpa_ms = 0, o_proj_ms = 0; + double post_norm_ms = 0; + double moe_routing_ms = 0, moe_sort_ms = 0; + double moe_gqmm_gate_up_ms = 0, moe_silu_ms = 0, moe_gqmm_down_ms = 0; + double moe_combine_ms = 0; + double dense_mlp_ms = 0; + double eval_barrier_ms = 0, final_norm_ms = 0; + double residual_ms = 0; // residual adds + int layer_count = 0; + + using clock = std::chrono::high_resolution_clock; + clock::time_point tp; + + void tick() { if (enabled) tp = clock::now(); } + + double tock_ms() { + if (!enabled) return 0; + auto now = clock::now(); + return std::chrono::duration(now - tp).count(); + } + + // eval + sync + return elapsed since last tick + double sync_tock(const array& a) { + if (!enabled) return 0; + eval({a}); + return tock_ms(); + } + double sync_tock(const std::vector& v) { + if (!enabled) return 0; + eval(v); + return tock_ms(); + } + + void reset() { + embed_ms = input_norm_ms = 0; + qkv_proj_ms = qk_norm_ms = rope_ms = 0; + kv_append_ms = sdpa_ms = o_proj_ms = 0; + post_norm_ms = 0; + moe_routing_ms = moe_sort_ms = 0; + moe_gqmm_gate_up_ms = moe_silu_ms = moe_gqmm_down_ms = 0; + moe_combine_ms = 0; + dense_mlp_ms = 0; + eval_barrier_ms = final_norm_ms = 0; + residual_ms = 0; + layer_count = 0; + } + + void report(int seq_len) { + if (!enabled) return; + double moe_gqmm_ms = moe_gqmm_gate_up_ms + moe_silu_ms + moe_gqmm_down_ms; + double total = embed_ms + input_norm_ms + qkv_proj_ms + qk_norm_ms + + rope_ms + kv_append_ms + sdpa_ms + o_proj_ms + post_norm_ms + + moe_routing_ms + moe_sort_ms + moe_gqmm_ms + moe_combine_ms + + dense_mlp_ms + eval_barrier_ms + final_norm_ms + residual_ms; + + auto pct = [&](double v) { return total > 0 ? 100.0 * v / total : 0; }; + + fprintf(stderr, "\n[qwen-profile] === %d tokens, %d layers ===\n", seq_len, layer_count); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "embedding", embed_ms, pct(embed_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "input_norm", input_norm_ms, pct(input_norm_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "qkv_proj", qkv_proj_ms, pct(qkv_proj_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "qk_norm", qk_norm_ms, pct(qk_norm_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "rope", rope_ms, pct(rope_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "kv_append", kv_append_ms, pct(kv_append_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "sdpa", sdpa_ms, pct(sdpa_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "o_proj", o_proj_ms, pct(o_proj_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "residual_add", residual_ms, pct(residual_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "post_norm", post_norm_ms, pct(post_norm_ms)); + if (moe_routing_ms > 0 || moe_gqmm_ms > 0) { + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "moe_routing", moe_routing_ms, pct(moe_routing_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "moe_sort", moe_sort_ms, pct(moe_sort_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "moe_gqmm_total", moe_gqmm_ms, pct(moe_gqmm_ms)); + fprintf(stderr, "[qwen-profile] %-18s %8.1fms (%5.1f%%)\n", "gate+up", moe_gqmm_gate_up_ms, pct(moe_gqmm_gate_up_ms)); + fprintf(stderr, "[qwen-profile] %-18s %8.1fms (%5.1f%%)\n", "silu*up", moe_silu_ms, pct(moe_silu_ms)); + fprintf(stderr, "[qwen-profile] %-18s %8.1fms (%5.1f%%)\n", "down", moe_gqmm_down_ms, pct(moe_gqmm_down_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "moe_combine", moe_combine_ms, pct(moe_combine_ms)); + } + if (dense_mlp_ms > 0) + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "dense_mlp", dense_mlp_ms, pct(dense_mlp_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "eval_barrier", eval_barrier_ms, pct(eval_barrier_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "final_norm", final_norm_ms, pct(final_norm_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms\n", "TOTAL", total); + fprintf(stderr, "[qwen-profile] %-20s %8.0f tok/s (profiled, ~2-3x slower than production)\n", + "throughput", seq_len / (total / 1000.0)); + } +}; + +static QwenProfiler g_prof; + +// ============================================================================ +// Primitives (same as generic but self-contained) +// ============================================================================ + +struct QuantizedLinear { + std::optional weight, scales, biases, linear_bias; + int group_size = 64, bits = 4; + bool quantized = true; + + array operator()(const array& x) const { + if (quantized) { + auto out = quantized_matmul(x, *weight, *scales, *biases, + true, group_size, bits, "affine"); + if (linear_bias) out = out + *linear_bias; + return out; + } + auto out = matmul(x, transpose(*weight)); + if (linear_bias) out = out + *linear_bias; + return out; + } +}; + +struct Norm { + std::optional weight; + float eps = 1e-6f; + array operator()(const array& x) const { + if (weight) return fast::rms_norm(x, *weight, eps); + return fast::rms_norm(x, std::nullopt, eps); + } +}; + +struct Embedding { + std::optional weight, scales, biases; + int group_size = 64, bits = 4; + bool quantized = false; + + array operator()(const array& indices) const { + if (quantized) { + return dequantize( + take(*weight, indices, 0), + take(*scales, indices, 0), + take(*biases, indices, 0), + group_size, bits, "affine"); + } + return take(*weight, indices, 0); + } +}; + +struct KVCache { + std::optional keys, values; + int offset = 0; + bool has_data() const { return keys.has_value(); } + void append(const array& k, const array& v, int S) { + if (keys) { + keys = concatenate({*keys, k}, 2); + values = concatenate({*values, v}, 2); + } else { + keys = k; values = v; + } + offset += S; + } + void reset() { keys.reset(); values.reset(); offset = 0; } +}; + +// ============================================================================ +// Config +// ============================================================================ + +struct QwenConfig { + std::string model_type; // "qwen2", "qwen3", "qwen3_moe" + int hidden_size = 0, num_layers = 0, num_heads = 0, num_kv_heads = 0; + int head_dim = 0, intermediate_size = 0, vocab_size = 0; + float rms_norm_eps = 1e-6f, rope_theta = 1000000.0f; + int rotary_dim = 0; + bool tie_word_embeddings = false, use_qk_norm = false; + int num_local_experts = 0, num_experts_per_tok = 0; + int quant_bits = 4, quant_group_size = 64; + bool is_moe() const { return num_local_experts > 0; } +}; + +// ============================================================================ +// MoE forward (Qwen3 softmax-only, no correction bias) +// ============================================================================ + +static array qwen_moe_forward( + const array& x, + const QuantizedLinear& gate, + const array& gate_w, const array& gate_s, const std::optional& gate_b, + const array& up_w, const array& up_s, const std::optional& up_b, + const array& down_w, const array& down_s, const std::optional& down_b, + int num_experts_per_tok, int group_size, + int gate_bits, int up_bits, int down_bits +) { + // Softmax routing (Qwen3 MoE only uses softmax, no sigmoid/correction) + // Match Swift: no float32 cast on gate input, use precise softmax instead + auto gates = gate(x); + auto scores = softmax(gates, -1, true); // precise=true matches Swift + int k = num_experts_per_tok; + + auto inds = argpartition(negative(gates), k - 1, -1); + inds = slice(inds, {0, 0, 0}, {inds.shape(0), inds.shape(1), k}); + auto sel_scores = take_along_axis(scores, inds, -1); + sel_scores = sel_scores / (sum(sel_scores, -1, true) + 1e-20f); + sel_scores = astype(sel_scores, x.dtype()); + + int B = x.shape(0), S = x.shape(1); + + // Expert-sorted dispatch (matches Swift gatherSort/scatterUnsort pattern) + auto x_exp = expand_dims(x, {-2, -3}); + auto flat_inds = flatten(inds); + auto order = argsort(flat_inds); + auto inv_order = argsort(order); + auto x_sorted = take(flatten(x_exp, 0, -3), floor_divide(order, array(k)), 0); + auto sorted_inds = take(flat_inds, order, 0); + + auto gate_out = gather_qmm(x_sorted, gate_w, gate_s, gate_b, + std::nullopt, sorted_inds, true, group_size, gate_bits, "affine", true); + auto up_out = gather_qmm(x_sorted, up_w, up_s, up_b, + std::nullopt, sorted_inds, true, group_size, up_bits, "affine", true); + + auto hidden = (gate_out * sigmoid(gate_out)) * up_out; + + auto down_out = gather_qmm(hidden, down_w, down_s, down_b, + std::nullopt, sorted_inds, true, group_size, down_bits, "affine", true); + + down_out = squeeze(down_out, {-2}); + down_out = take(down_out, inv_order, 0); + down_out = reshape(down_out, {inds.shape(0), inds.shape(1), k, -1}); + + return sum(down_out * expand_dims(sel_scores, -1), -2); +} + +// Fused gate+up variant: single gather_qmm for gate+up, then split output +static array qwen_moe_forward_fused( + const array& x, + const QuantizedLinear& gate, + const array& fused_w, const array& fused_s, const std::optional& fused_b, + int gate_up_split, + const array& down_w, const array& down_s, const std::optional& down_b, + int num_experts_per_tok, int group_size, + int fused_bits, int down_bits +) { + auto gates = gate(x); + auto scores = softmax(gates, -1, true); + int k = num_experts_per_tok; + + auto inds = argpartition(negative(gates), k - 1, -1); + inds = slice(inds, {0, 0, 0}, {inds.shape(0), inds.shape(1), k}); + auto sel_scores = take_along_axis(scores, inds, -1); + sel_scores = sel_scores / (sum(sel_scores, -1, true) + 1e-20f); + sel_scores = astype(sel_scores, x.dtype()); + + int B = x.shape(0), S = x.shape(1); + + auto x_exp = expand_dims(x, {-2, -3}); + auto flat_inds = flatten(inds); + auto order = argsort(flat_inds); + auto inv_order = argsort(order); + auto x_sorted = take(flatten(x_exp, 0, -3), floor_divide(order, array(k)), 0); + auto sorted_inds = take(flat_inds, order, 0); + + // Single gather_qmm for gate+up (fused along output dim) + auto fused_out = gather_qmm(x_sorted, fused_w, fused_s, fused_b, + std::nullopt, sorted_inds, true, group_size, fused_bits, "affine", true); + + auto gate_out = slice(fused_out, {0, 0, 0, 0}, + {fused_out.shape(0), fused_out.shape(1), fused_out.shape(2), gate_up_split}); + auto up_out = slice(fused_out, {0, 0, 0, gate_up_split}, + {fused_out.shape(0), fused_out.shape(1), fused_out.shape(2), fused_out.shape(3)}); + + auto hidden = (gate_out * sigmoid(gate_out)) * up_out; + + auto down_out = gather_qmm(hidden, down_w, down_s, down_b, + std::nullopt, sorted_inds, true, group_size, down_bits, "affine", true); + + down_out = squeeze(down_out, {-2}); + down_out = take(down_out, inv_order, 0); + down_out = reshape(down_out, {inds.shape(0), inds.shape(1), k, -1}); + + return sum(down_out * expand_dims(sel_scores, -1), -2); +} + +// ============================================================================ +// Dense MLP +// ============================================================================ + +static array qwen_mlp_forward( + const array& x, + const QuantizedLinear& gate_proj, + const QuantizedLinear& up_proj, + const QuantizedLinear& down_proj +) { + auto gate = gate_proj(x); + auto up = up_proj(x); + return down_proj((gate * sigmoid(gate)) * up); +} + +// ============================================================================ +// Attention +// ============================================================================ + +static array qwen_attention( + const array& x, + const QuantizedLinear& q_proj, const QuantizedLinear& k_proj, + const QuantizedLinear& v_proj, const QuantizedLinear& o_proj, + const Norm* q_norm, const Norm* k_norm, + int num_heads, int num_kv_heads, int head_dim, + float rope_theta, int rotary_dim, + KVCache& cache, int rope_offset +) { + int B = x.shape(0), S = x.shape(1); + auto q = q_proj(x), k = k_proj(x), v = v_proj(x); + + q = reshape(q, {B, S, num_heads, head_dim}); + k = reshape(k, {B, S, num_kv_heads, head_dim}); + v = reshape(v, {B, S, num_kv_heads, head_dim}); + + // QK norm applied BEFORE transpose (matches Swift — norm on contiguous layout) + if (q_norm) { q = (*q_norm)(q); k = (*k_norm)(k); } + + q = transpose(q, {0, 2, 1, 3}); + k = transpose(k, {0, 2, 1, 3}); + v = transpose(v, {0, 2, 1, 3}); + + int rot = rotary_dim > 0 ? rotary_dim : head_dim; + q = fast::rope(q, rot, false, rope_theta, 1.0f, rope_offset); + k = fast::rope(k, rot, false, rope_theta, 1.0f, rope_offset); + + // KV dtype matches model's quantization scales + auto kv_dtype = k_proj.scales ? k_proj.scales->dtype() : float16; + k = astype(k, kv_dtype); + v = astype(v, kv_dtype); + cache.append(k, v, S); + + float scale = 1.0f / std::sqrt(static_cast(head_dim)); + auto attn = fast::scaled_dot_product_attention( + q, *cache.keys, *cache.values, scale, "causal"); + + attn = reshape(transpose(attn, {0, 2, 1, 3}), {B, S, num_heads * head_dim}); + return o_proj(attn); +} + +// ============================================================================ +// Layer +// ============================================================================ + +struct MoEWeights { + QuantizedLinear gate; + // Original per-projection weights (kept for reference/fallback) + std::optional gate_w, gate_s, gate_b; + std::optional up_w, up_s, up_b; + std::optional down_w, down_s, down_b; + // Fused gate+up weights (concatenated along output dim for single gather_qmm) + std::optional fused_gate_up_w, fused_gate_up_s, fused_gate_up_b; + int gate_up_split = 0; // output dim to split at (= intermediate_size / pack_factor) + int num_experts_per_tok = 0; + int gate_bits = 4, up_bits = 4, down_bits = 4; + bool use_fused_gate_up = false; +}; + +struct QwenLayer { + Norm input_norm, post_attn_norm; + QuantizedLinear q_proj, k_proj, v_proj, o_proj; + Norm q_norm, k_norm; + bool has_qk_norm = false; + + // Dense MLP (qwen2/qwen3 dense) + QuantizedLinear gate_proj, up_proj, down_proj; + + // MoE (qwen3_moe) + bool is_moe = false; + std::optional moe; + + float rope_theta = 1000000.0f; + int rotary_dim = 0; + int num_heads = 0, num_kv_heads = 0, head_dim = 0; + int group_size = 64; + + KVCache cache; +}; + +// ============================================================================ +// Model +// ============================================================================ + +struct QwenModel { + QwenConfig config; + Embedding embed_tokens; + std::vector layers; + Norm final_norm; + + // Tunable: how many layers per eval barrier. + // Set via QWEN_EVAL_CADENCE env var for experimentation. + int eval_cadence = 8; + + // Production forward — no profiling overhead + array forward(const array& token_ids) { + int B = token_ids.shape(0), S = token_ids.shape(1); + auto h = embed_tokens(token_ids); + + for (int i = 0; i < (int)layers.size(); i++) { + auto& L = layers[i]; + auto residual = h; + + auto normed = L.input_norm(h); + auto attn_out = qwen_attention(normed, + L.q_proj, L.k_proj, L.v_proj, L.o_proj, + L.has_qk_norm ? &L.q_norm : nullptr, + L.has_qk_norm ? &L.k_norm : nullptr, + L.num_heads, L.num_kv_heads, L.head_dim, + L.rope_theta, L.rotary_dim, + L.cache, 0); + h = residual + attn_out; + + residual = h; + if (L.is_moe) { + auto normed_ff = L.post_attn_norm(h); + if (L.moe->use_fused_gate_up) { + h = residual + qwen_moe_forward_fused(normed_ff, + L.moe->gate, + *L.moe->fused_gate_up_w, *L.moe->fused_gate_up_s, L.moe->fused_gate_up_b, + L.moe->gate_up_split, + *L.moe->down_w, *L.moe->down_s, L.moe->down_b, + L.moe->num_experts_per_tok, L.group_size, + L.moe->gate_bits, L.moe->down_bits); + } else { + h = residual + qwen_moe_forward(normed_ff, + L.moe->gate, + *L.moe->gate_w, *L.moe->gate_s, L.moe->gate_b, + *L.moe->up_w, *L.moe->up_s, L.moe->up_b, + *L.moe->down_w, *L.moe->down_s, L.moe->down_b, + L.moe->num_experts_per_tok, L.group_size, + L.moe->gate_bits, L.moe->up_bits, L.moe->down_bits); + } + } else { + auto normed_ff = L.post_attn_norm(h); + h = residual + qwen_mlp_forward(normed_ff, + L.gate_proj, L.up_proj, L.down_proj); + } + + // No intermediate barriers — single eval at the end in qwen_run + // matches Swift's pattern of building one massive lazy graph + } + + return final_norm(h); + } + + // Profiled forward — eval+sync after every stage for accurate attribution. + // ~2-3x slower than production due to killed graph fusion. + array forward_profiled(const array& token_ids) { + auto& P = g_prof; + P.reset(); + int B = token_ids.shape(0), S = token_ids.shape(1); + + // Embedding + P.tick(); + auto h = embed_tokens(token_ids); + P.embed_ms += P.sync_tock(h); + + for (int i = 0; i < (int)layers.size(); i++) { + auto& L = layers[i]; + P.layer_count++; + + // Input norm + P.tick(); + auto normed = L.input_norm(h); + P.input_norm_ms += P.sync_tock(normed); + + // Q/K/V projections + P.tick(); + auto q = L.q_proj(normed), k = L.k_proj(normed), v = L.v_proj(normed); + P.qkv_proj_ms += P.sync_tock({q, k, v}); + + // Reshape (norm before transpose — matches Swift contiguous layout) + q = reshape(q, {B, S, L.num_heads, L.head_dim}); + k = reshape(k, {B, S, L.num_kv_heads, L.head_dim}); + v = reshape(v, {B, S, L.num_kv_heads, L.head_dim}); + + // QK norm (before transpose — on contiguous layout) + if (L.has_qk_norm) { + P.tick(); + q = L.q_norm(q); k = L.k_norm(k); + P.qk_norm_ms += P.sync_tock({q, k}); + } + + q = transpose(q, {0, 2, 1, 3}); + k = transpose(k, {0, 2, 1, 3}); + v = transpose(v, {0, 2, 1, 3}); + + // RoPE + P.tick(); + int rot = L.rotary_dim > 0 ? L.rotary_dim : L.head_dim; + q = fast::rope(q, rot, false, L.rope_theta, 1.0f, 0); + k = fast::rope(k, rot, false, L.rope_theta, 1.0f, 0); + P.rope_ms += P.sync_tock({q, k}); + + // KV cache append + P.tick(); + auto kv_dtype = L.k_proj.scales ? L.k_proj.scales->dtype() : float16; + k = astype(k, kv_dtype); + v = astype(v, kv_dtype); + L.cache.append(k, v, S); + P.kv_append_ms += P.sync_tock({*L.cache.keys, *L.cache.values}); + + // SDPA + P.tick(); + float scale = 1.0f / std::sqrt(static_cast(L.head_dim)); + auto attn = fast::scaled_dot_product_attention( + q, *L.cache.keys, *L.cache.values, scale, "causal"); + P.sdpa_ms += P.sync_tock(attn); + + // O proj + P.tick(); + attn = reshape(transpose(attn, {0, 2, 1, 3}), {B, S, L.num_heads * L.head_dim}); + auto attn_out = L.o_proj(attn); + P.o_proj_ms += P.sync_tock(attn_out); + + // Residual add + P.tick(); + h = h + attn_out; + P.residual_ms += P.sync_tock(h); + + // Post-attention norm + P.tick(); + auto normed_ff = L.post_attn_norm(h); + P.post_norm_ms += P.sync_tock(normed_ff); + + // MoE or dense MLP + if (L.is_moe) { + // MoE routing (gate + softmax + topk + score normalize) + P.tick(); + auto gates = L.moe->gate(normed_ff); + auto scores = softmax(gates, -1, true); + int kk = L.moe->num_experts_per_tok; + auto inds = argpartition(negative(gates), kk - 1, -1); + inds = slice(inds, {0, 0, 0}, {inds.shape(0), inds.shape(1), kk}); + auto sel_scores = take_along_axis(scores, inds, -1); + sel_scores = sel_scores / (sum(sel_scores, -1, true) + 1e-20f); + sel_scores = astype(sel_scores, normed_ff.dtype()); + P.moe_routing_ms += P.sync_tock({inds, sel_scores}); + + // Expert sort + dispatch prep + P.tick(); + auto x_exp = expand_dims(normed_ff, {-2, -3}); + auto flat_inds = flatten(inds); + auto order = argsort(flat_inds); + auto inv_order = argsort(order); + auto x_sorted = take(flatten(x_exp, 0, -3), floor_divide(order, array(kk)), 0); + auto sorted_inds = take(flat_inds, order, 0); + P.moe_sort_ms += P.sync_tock({x_sorted, sorted_inds, inv_order}); + + // gather_qmm: gate + up (fused or separate) + P.tick(); + std::optional gate_out_opt, up_out_opt; + if (L.moe->use_fused_gate_up) { + auto fused_out = gather_qmm(x_sorted, + *L.moe->fused_gate_up_w, *L.moe->fused_gate_up_s, L.moe->fused_gate_up_b, + std::nullopt, sorted_inds, true, L.group_size, L.moe->gate_bits, "affine", true); + int sp = L.moe->gate_up_split; + gate_out_opt = slice(fused_out, {0, 0, 0, 0}, + {fused_out.shape(0), fused_out.shape(1), fused_out.shape(2), sp}); + up_out_opt = slice(fused_out, {0, 0, 0, sp}, + {fused_out.shape(0), fused_out.shape(1), fused_out.shape(2), fused_out.shape(3)}); + } else { + gate_out_opt = gather_qmm(x_sorted, *L.moe->gate_w, *L.moe->gate_s, L.moe->gate_b, + std::nullopt, sorted_inds, true, L.group_size, L.moe->gate_bits, "affine", true); + up_out_opt = gather_qmm(x_sorted, *L.moe->up_w, *L.moe->up_s, L.moe->up_b, + std::nullopt, sorted_inds, true, L.group_size, L.moe->up_bits, "affine", true); + } + auto& gate_out = *gate_out_opt; + auto& up_out = *up_out_opt; + P.moe_gqmm_gate_up_ms += P.sync_tock({gate_out, up_out}); + + // SiLU activation + elementwise multiply + P.tick(); + auto hidden = (gate_out * sigmoid(gate_out)) * up_out; + P.moe_silu_ms += P.sync_tock(hidden); + + // gather_qmm: down projection + P.tick(); + auto down_out = gather_qmm(hidden, *L.moe->down_w, *L.moe->down_s, L.moe->down_b, + std::nullopt, sorted_inds, true, L.group_size, L.moe->down_bits, "affine", true); + P.moe_gqmm_down_ms += P.sync_tock(down_out); + + // Combine (unsort + weighted sum + residual) + P.tick(); + down_out = squeeze(down_out, {-2}); + down_out = take(down_out, inv_order, 0); + down_out = reshape(down_out, {inds.shape(0), inds.shape(1), kk, -1}); + auto moe_out = sum(down_out * expand_dims(sel_scores, -1), -2); + h = h + moe_out; + P.moe_combine_ms += P.sync_tock(h); + } else { + P.tick(); + auto mlp_out = qwen_mlp_forward(normed_ff, + L.gate_proj, L.up_proj, L.down_proj); + h = h + mlp_out; + P.dense_mlp_ms += P.sync_tock(h); + } + + // Eval barrier (still needed even in profiled mode for KV correctness) + if ((i + 1) % eval_cadence == 0 || i == (int)layers.size() - 1) { + P.tick(); + std::vector to_sync = {h}; + if (L.cache.has_data()) { + to_sync.push_back(*L.cache.keys); + to_sync.push_back(*L.cache.values); + } + eval(to_sync); + P.eval_barrier_ms += P.tock_ms(); + } + } + + P.tick(); + auto out = final_norm(h); + P.final_norm_ms += P.sync_tock(out); + P.report(S); + + return out; + } +}; + +// ============================================================================ +// Global state +// ============================================================================ + +static std::unique_ptr g_model; +static std::unordered_map g_weights; +static QwenConfig g_config; +static bool g_initialized = false, g_finalized = false; + +// ============================================================================ +// Weight helpers +// ============================================================================ + +static array extract_array(void* ptr) { return *static_cast(ptr); } + +static array get_w(const std::string& key) { + auto it = g_weights.find(key); + if (it == g_weights.end()) throw std::runtime_error("Missing weight: " + key); + return it->second; +} + +static bool has_w(const std::string& key) { return g_weights.count(key) > 0; } + +static QuantizedLinear make_qlinear(const std::string& prefix) { + int gs = g_config.quant_group_size; + if (has_w(prefix + ".scales")) { + auto w = get_w(prefix + ".weight"); + auto s = get_w(prefix + ".scales"); + auto bi = get_w(prefix + ".biases"); + int w_last = w.shape(-1), s_last = s.shape(-1); + int b = (s_last > 0) ? (w_last * 32) / (s_last * gs) : g_config.quant_bits; + if (b == 0) b = g_config.quant_bits; + std::optional lb; + if (has_w(prefix + ".bias")) lb = get_w(prefix + ".bias"); + return {w, s, bi, lb, gs, b, true}; + } + std::optional lb; + if (has_w(prefix + ".bias")) lb = get_w(prefix + ".bias"); + return {get_w(prefix + ".weight"), array(0.0f), array(0.0f), lb, gs, g_config.quant_bits, false}; +} + +static int detect_bits(const std::string& wk, const std::string& sk) { + if (!has_w(wk) || !has_w(sk)) return g_config.quant_bits; + return (get_w(wk).shape(-1) * 32) / (get_w(sk).shape(-1) * g_config.quant_group_size); +} + +static Norm make_norm(const std::string& prefix) { + return {get_w(prefix + ".weight"), g_config.rms_norm_eps}; +} + +static Embedding make_embedding(const std::string& prefix) { + Embedding emb; + emb.weight = get_w(prefix + ".weight"); + eval({*emb.weight}); + if (has_w(prefix + ".scales")) { + emb.scales = get_w(prefix + ".scales"); + emb.biases = get_w(prefix + ".biases"); + eval({*emb.scales, *emb.biases}); + emb.group_size = g_config.quant_group_size; + emb.bits = detect_bits(prefix + ".weight", prefix + ".scales"); + emb.quantized = true; + } + return emb; +} + +// ============================================================================ +// Layer builders +// ============================================================================ + +static void build_dense_layer(QwenLayer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + if (g_config.use_qk_norm) { + layer.q_norm = make_norm(p + ".self_attn.q_norm"); + layer.k_norm = make_norm(p + ".self_attn.k_norm"); + layer.has_qk_norm = true; + } + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = g_config.rotary_dim; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + + layer.gate_proj = make_qlinear(p + ".mlp.gate_proj"); + layer.up_proj = make_qlinear(p + ".mlp.up_proj"); + layer.down_proj = make_qlinear(p + ".mlp.down_proj"); + layer.is_moe = false; + + // Force-eval layer weights to pin GPU buffers + std::vector lw = { + *layer.q_proj.weight, *layer.q_proj.scales, + *layer.k_proj.weight, *layer.k_proj.scales, + *layer.v_proj.weight, *layer.v_proj.scales, + *layer.o_proj.weight, *layer.o_proj.scales, + *layer.gate_proj.weight, *layer.gate_proj.scales, + *layer.up_proj.weight, *layer.up_proj.scales, + *layer.down_proj.weight, *layer.down_proj.scales, + *layer.input_norm.weight, *layer.post_attn_norm.weight + }; + if (layer.q_proj.linear_bias) { + lw.push_back(*layer.q_proj.linear_bias); + lw.push_back(*layer.k_proj.linear_bias); + lw.push_back(*layer.v_proj.linear_bias); + } + eval(lw); +} + +static void build_moe_layer(QwenLayer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + if (g_config.use_qk_norm) { + layer.q_norm = make_norm(p + ".self_attn.q_norm"); + layer.k_norm = make_norm(p + ".self_attn.k_norm"); + layer.has_qk_norm = true; + } + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = g_config.rotary_dim; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + + layer.is_moe = true; + layer.moe.emplace(); + layer.moe->gate = make_qlinear(p + ".mlp.gate"); + layer.moe->gate_w = get_w(p + ".mlp.switch_mlp.gate_proj.weight"); + layer.moe->gate_s = get_w(p + ".mlp.switch_mlp.gate_proj.scales"); + layer.moe->gate_b = get_w(p + ".mlp.switch_mlp.gate_proj.biases"); + layer.moe->up_w = get_w(p + ".mlp.switch_mlp.up_proj.weight"); + layer.moe->up_s = get_w(p + ".mlp.switch_mlp.up_proj.scales"); + layer.moe->up_b = get_w(p + ".mlp.switch_mlp.up_proj.biases"); + layer.moe->down_w = get_w(p + ".mlp.switch_mlp.down_proj.weight"); + layer.moe->down_s = get_w(p + ".mlp.switch_mlp.down_proj.scales"); + layer.moe->down_b = get_w(p + ".mlp.switch_mlp.down_proj.biases"); + std::string moe_p = p + ".mlp.switch_mlp"; + layer.moe->gate_bits = detect_bits(moe_p + ".gate_proj.weight", moe_p + ".gate_proj.scales"); + layer.moe->up_bits = detect_bits(moe_p + ".up_proj.weight", moe_p + ".up_proj.scales"); + layer.moe->down_bits = detect_bits(moe_p + ".down_proj.weight", moe_p + ".down_proj.scales"); + layer.moe->num_experts_per_tok = g_config.num_experts_per_tok; + + // Fuse gate+up weights: concatenate along output dim (axis=1) for single gather_qmm. + // Only valid when gate and up have identical quantization config. + // NOTE: measured ~+1% at 1k but -3% at 4k — larger N hurts kernel efficiency. + // Disabled by default. Set QWEN_FUSE_GATE_UP=1 to enable. + const char* fuse_env = std::getenv("QWEN_FUSE_GATE_UP"); + if (fuse_env && std::string(fuse_env) == "1" && layer.moe->gate_bits == layer.moe->up_bits) { + auto& gw = *layer.moe->gate_w; + auto& uw = *layer.moe->up_w; + auto& gs = *layer.moe->gate_s; + auto& us = *layer.moe->up_s; + auto& gb = *layer.moe->gate_b; + auto& ub = *layer.moe->up_b; + layer.moe->fused_gate_up_w = concatenate({gw, uw}, 1); + layer.moe->fused_gate_up_s = concatenate({gs, us}, 1); + layer.moe->fused_gate_up_b = concatenate({gb, ub}, 1); + layer.moe->gate_up_split = gw.shape(1); // split point in output dim + eval({*layer.moe->fused_gate_up_w, *layer.moe->fused_gate_up_s, + *layer.moe->fused_gate_up_b}); + layer.moe->use_fused_gate_up = true; + if (idx == 0) + fprintf(stderr, "[qwen] Fused gate+up: [%d,%d,%d] (split@%d)\n", + layer.moe->fused_gate_up_w->shape(0), + layer.moe->fused_gate_up_w->shape(1), + layer.moe->fused_gate_up_w->shape(2), + layer.moe->gate_up_split); + } +} + +// ============================================================================ +// Model builder +// ============================================================================ + +static QwenModel build_model() { + QwenModel m; + m.config = g_config; + + // Tunable eval cadence from env + const char* cadence_env = std::getenv("QWEN_EVAL_CADENCE"); + m.eval_cadence = cadence_env ? std::atoi(cadence_env) : 8; + fprintf(stderr, "[qwen] eval_cadence=%d\n", m.eval_cadence); + + m.embed_tokens = make_embedding("model.embed_tokens"); + m.final_norm = make_norm("model.norm"); + + int N = g_config.num_layers; + m.layers.reserve(N); + for (int i = 0; i < N; i++) { + m.layers.emplace_back(); + if (g_config.is_moe()) { + build_moe_layer(m.layers[i], i); + } else { + build_dense_layer(m.layers[i], i); + } + } + + // Log MoE weight shapes for optimization analysis + if (g_config.is_moe() && N > 0 && m.layers[0].is_moe) { + auto& moe = *m.layers[0].moe; + auto shape_str = [](const array& a) { + std::string s = "["; + for (int d = 0; d < a.ndim(); d++) { + if (d) s += ","; + s += std::to_string(a.shape(d)); + } + return s + "]"; + }; + fprintf(stderr, "[qwen] MoE shapes (layer 0): gate_w=%s up_w=%s down_w=%s\n", + shape_str(*moe.gate_w).c_str(), shape_str(*moe.up_w).c_str(), + shape_str(*moe.down_w).c_str()); + fprintf(stderr, "[qwen] MoE scales: gate_s=%s\n", shape_str(*moe.gate_s).c_str()); + fprintf(stderr, "[qwen] MoE bits: gate=%d up=%d down=%d, group_size=%d\n", + moe.gate_bits, moe.up_bits, moe.down_bits, m.layers[0].group_size); + } + + fprintf(stderr, "[qwen] Model built: %d layers, %s\n", + N, g_config.is_moe() ? "MoE" : "dense"); + return m; +} + +// ============================================================================ +// JSON parsing (minimal) +// ============================================================================ + +static std::string json_str(const std::string& j, const std::string& k) { + auto p = j.find("\"" + k + "\""); + if (p == std::string::npos) return ""; + p = j.find(":", p); auto s = j.find("\"", p+1); auto e = j.find("\"", s+1); + return j.substr(s+1, e-s-1); +} +static int json_int(const std::string& j, const std::string& k, int d=0) { + auto p = j.find("\"" + k + "\""); + if (p == std::string::npos) return d; + p = j.find(":", p); auto s = j.find_first_of("-0123456789", p+1); + auto e = j.find_first_not_of("-0123456789", s); + return std::stoi(j.substr(s, e-s)); +} +static float json_float(const std::string& j, const std::string& k, float d=0) { + auto p = j.find("\"" + k + "\""); + if (p == std::string::npos) return d; + p = j.find(":", p); auto s = j.find_first_of("-0123456789.", p+1); + auto e = j.find_first_not_of("-0123456789.eE+-", s); + return std::stof(j.substr(s, e-s)); +} +static bool json_bool(const std::string& j, const std::string& k, bool d=false) { + auto p = j.find("\"" + k + "\""); + if (p == std::string::npos) return d; + p = j.find(":", p); auto s = j.find_first_not_of(" \t\n", p+1); + return j.substr(s, 4) == "true"; +} + +// ============================================================================ +// C ABI +// ============================================================================ + +extern "C" { + +int qwen_init(const char* config_json) { + try { + std::string j(config_json); + g_config.model_type = json_str(j, "model_type"); + g_config.hidden_size = json_int(j, "hidden_size", 2048); + g_config.num_layers = json_int(j, "num_hidden_layers", 28); + g_config.num_heads = json_int(j, "num_attention_heads", 16); + g_config.num_kv_heads = json_int(j, "num_key_value_heads", 2); + g_config.head_dim = json_int(j, "head_dim", 128); + g_config.intermediate_size = json_int(j, "intermediate_size", 8960); + g_config.vocab_size = json_int(j, "vocab_size", 151936); + g_config.rms_norm_eps = json_float(j, "rms_norm_eps", 1e-6f); + g_config.rope_theta = json_float(j, "rope_theta", 1000000.0f); + g_config.rotary_dim = json_int(j, "rotary_dim", 0); + g_config.tie_word_embeddings = json_bool(j, "tie_word_embeddings", false); + g_config.use_qk_norm = json_bool(j, "use_qk_norm", false); + g_config.num_local_experts = json_int(j, "num_local_experts", 0); + g_config.num_experts_per_tok = json_int(j, "num_experts_per_tok", 0); + + g_weights.clear(); + g_model.reset(); + g_initialized = true; + g_finalized = false; + + // Profiling: QWEN_PROFILE=1 enables per-stage timing + const char* prof_env = std::getenv("QWEN_PROFILE"); + g_prof.enabled = prof_env && std::string(prof_env) == "1"; + if (g_prof.enabled) + fprintf(stderr, "[qwen] PROFILING ENABLED — will eval+sync per stage (slower)\n"); + + fprintf(stderr, "[qwen] Init: type=%s layers=%d hidden=%d heads=%d/%d hd=%d experts=%d\n", + g_config.model_type.c_str(), g_config.num_layers, + g_config.hidden_size, g_config.num_heads, g_config.num_kv_heads, + g_config.head_dim, g_config.num_local_experts); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[qwen] init error: %s\n", e.what()); + return -1; + } +} + +int qwen_set_weight(const char* key, void* arr_ptr) { + if (!g_initialized || g_finalized) return -1; + try { + g_weights.insert_or_assign(std::string(key), extract_array(arr_ptr)); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[qwen] set_weight error '%s': %s\n", key, e.what()); + return -1; + } +} + +int qwen_finalize(void) { + if (!g_initialized || g_finalized) return -1; + try { + fprintf(stderr, "[qwen] Finalizing with %zu weights\n", g_weights.size()); + g_model = std::make_unique(build_model()); + g_finalized = true; + g_weights.clear(); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[qwen] finalize error: %s\n", e.what()); + return -1; + } +} + +int qwen_run(void* token_array_ptr, double* out_elapsed_ms) { + if (!g_model) return -1; + try { + auto& tokens = *static_cast(token_array_ptr); + auto t0 = std::chrono::high_resolution_clock::now(); + + for (auto& layer : g_model->layers) layer.cache.reset(); + + auto output = g_prof.enabled + ? g_model->forward_profiled(tokens) + : g_model->forward(tokens); + + // Async eval of all KV caches — non-blocking, GPU work overlaps + // with Swift-side KV injection. The arrays will be materialized + // when Swift's cache.update() accesses them. + std::vector to_eval; + for (auto& layer : g_model->layers) { + if (layer.cache.has_data()) { + to_eval.push_back(*layer.cache.keys); + to_eval.push_back(*layer.cache.values); + } + } + async_eval(to_eval); + + auto t1 = std::chrono::high_resolution_clock::now(); + if (out_elapsed_ms) + *out_elapsed_ms = std::chrono::duration(t1 - t0).count(); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[qwen] run error: %s\n", e.what()); + return -1; + } +} + +int qwen_num_cache_layers(void) { + return g_model ? (int)g_model->layers.size() : 0; +} + +void* qwen_get_k_ptr(int i) { + if (!g_model || i < 0 || i >= (int)g_model->layers.size()) return nullptr; + auto& c = g_model->layers[i].cache; + return c.keys ? new array(*c.keys) : nullptr; +} + +void* qwen_get_v_ptr(int i) { + if (!g_model || i < 0 || i >= (int)g_model->layers.size()) return nullptr; + auto& c = g_model->layers[i].cache; + return c.values ? new array(*c.values) : nullptr; +} + +int qwen_kv_shape(int i, int* kv_heads, int* seq_len, int* head_dim) { + if (!g_model || i < 0 || i >= (int)g_model->layers.size()) return -1; + auto& c = g_model->layers[i].cache; + if (!c.has_data()) return -2; + *kv_heads = c.keys->shape(1); + *seq_len = c.keys->shape(2); + *head_dim = c.keys->shape(3); + return 0; +} + +void qwen_cleanup(void) { + g_model.reset(); + g_weights.clear(); + g_initialized = false; + g_finalized = false; +} + +} // extern "C" diff --git a/Sources/NativePrefillBridge/prefill_bridge_qwen.h b/Sources/NativePrefillBridge/prefill_bridge_qwen.h new file mode 100644 index 0000000000..9b00ee11c9 --- /dev/null +++ b/Sources/NativePrefillBridge/prefill_bridge_qwen.h @@ -0,0 +1,47 @@ +// prefill_bridge_qwen.h — Qwen-family native prefill bridge +// +// Dedicated prefill bridge for Qwen2, Qwen3, and Qwen3-MoE architectures. +// Separated from generic_prefill.cpp to allow Qwen-specific tuning +// (eval barriers, graph structure, MoE dispatch) without risking +// regressions on other model families. +// +// Integration: called from Qwen Swift model prepare() methods. +#ifndef PREFILL_BRIDGE_QWEN_H +#define PREFILL_BRIDGE_QWEN_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// Initialize with Qwen model config JSON +int qwen_init(const char* config_json); + +// Set a weight tensor (pass Swift's MLXArray.ctx pointer) +int qwen_set_weight(const char* key, void* arr_ptr); + +// Mark initialization complete — builds model from weights +int qwen_finalize(void); + +// Run prefill on token array (pass MLXArray.ctx pointer) +int qwen_run(void* token_array_ptr, double* out_elapsed_ms); + +// Get number of KV cache layers +int qwen_num_cache_layers(void); + +// Get K/V array pointers for cache injection +void* qwen_get_k_ptr(int layer_idx); +void* qwen_get_v_ptr(int layer_idx); + +// KV shape info +int qwen_kv_shape(int layer_idx, int* kv_heads, int* seq_len, int* head_dim); + +// Cleanup +void qwen_cleanup(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Sources/PrefillBench/main.swift b/Sources/PrefillBench/main.swift index 51c75af476..a0cb770d2f 100644 --- a/Sources/PrefillBench/main.swift +++ b/Sources/PrefillBench/main.swift @@ -1,217 +1,102 @@ import Foundation import MLX -import MLXNN import MLXLLM import MLXLMCommon - -typealias PB2Init = @convention(c) (Int32, Int32, Int32, Int32, Int32, Int32) -> Int32 -typealias PB2SetWeight = @convention(c) (UnsafePointer, UnsafeMutableRawPointer) -> Int32 -typealias PB2Finalize = @convention(c) () -> Int32 -typealias PB2Run = @convention(c) (UnsafePointer, Int32, UnsafeMutablePointer, UnsafeMutablePointer) -> Int32 -typealias PB2TestWeight = @convention(c) (UnsafePointer, UnsafeMutableRawPointer) -> Int32 -typealias PB2Cleanup = @convention(c) () -> Void +import MLXNN +import NativePrefillBridge func log(_ msg: String) { - FileHandle.standardError.write(Data("[Swift] \(msg)\n".utf8)) + FileHandle.standardError.write(Data("[Bench] \(msg)\n".utf8)) } @main struct PrefillBenchmark { + @MainActor static func main() async { setlinebuf(stdout) - let mode = CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "swift" - log("START mode=\(mode)") + log("=== MLX Swift End-to-End Benchmark ===") do { - let config = ModelConfiguration(id: "mlx-community/gemma-4-e2b-it-4bit") - let container = try await LLMModelFactory.shared.loadContainer( - configuration: config) { p in - if p.fractionCompleted > 0.99 { log("Loaded") } - } - log("MODEL_LOADED") - - let data = try Data(contentsOf: URL(fileURLWithPath: "/tmp/bench_tokens_1024.json")) - let json = try JSONSerialization.jsonObject(with: data) as! [String: Any] - let allTokens = (json["tokens"] as! [Int]).map { Int32($0) } - - if mode == "inject" { - guard let lib = dlopen("/tmp/libprefill_bridge_v2.dylib", RTLD_NOW) else { - log("ERROR: \(String(cString: dlerror()))"); return - } - let pb2Init = unsafeBitCast(dlsym(lib, "pb2_init")!, to: PB2Init.self) - let pb2Set = unsafeBitCast(dlsym(lib, "pb2_set_weight")!, to: PB2SetWeight.self) - let pb2Fin = unsafeBitCast(dlsym(lib, "pb2_finalize")!, to: PB2Finalize.self) - let pb2Run = unsafeBitCast(dlsym(lib, "pb2_run")!, to: PB2Run.self) - let pb2Test = unsafeBitCast(dlsym(lib, "pb2_test_weight")!, to: PB2TestWeight.self) - log("Bridge symbols loaded") - - // Init + pass weights + finalize inside perform - try await container.perform { ctx in - log("Inside perform") - let model = ctx.model - - let _ = pb2Init(15, 1536, 8, 1, 512, 5) - log("pb2_init done") - - // Test one weight first - guard let module = model as? Module else { log("Not a Module!"); return } - let params = module.parameters().flattened() - log("Got \(params.count) params") - - // Find a known key and test the borrow - if let (key, arr) = params.first(where: { $0.0.contains("q_proj.scales") }) { - let k = key.hasPrefix("model.") ? String(key.dropFirst(6)) : key - log("Testing weight: \(k)") - let rawPtr = arr.ctx.ctx! - let testRC = k.withCString { pb2Test($0, rawPtr) } - log("Test result: \(testRC)") - } - - // Pass all weights - var count = 0 - for (key, arr) in params { - let k = key.hasPrefix("model.") ? String(key.dropFirst(6)) : key - let _ = k.withCString { pb2Set($0, arr.ctx.ctx!) } - count += 1 - } - log("Set \(count) weights") - - let finRC = pb2Fin() - log("Finalize: \(finRC)") - if finRC != 0 { return } + let args = CommandLine.arguments - // Isolated bridge timing: 16 and 1024 tokens - var ms: Double = 0; var ck: Float = 0 - for n in [16, 1024] { - let toks = Array(allTokens.prefix(n)) - // warmup - for _ in 0..<3 { let _ = pb2Run(toks, Int32(n), &ms, &ck) } - // timed - var times: [Double] = [] - for _ in 0..<5 { let _ = pb2Run(toks, Int32(n), &ms, &ck); times.append(ms) } - let avg = times.reduce(0, +) / 5.0 - log(String(format: "Bridge %4d tok: %.1fms (%.0f tok/s) cksum=%.4f", - n, avg, Double(n)/(avg/1000.0), ck)) - } - - // --- Task 2: K/V injection --- - typealias PB2KVNbytes = @convention(c) (Int32) -> Int - typealias PB2KVShape = @convention(c) (Int32, UnsafeMutablePointer, UnsafeMutablePointer, UnsafeMutablePointer) -> Int32 - typealias PB2ExportKV = @convention(c) (Int32, UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Int32 - - let kvNbytes = unsafeBitCast(dlsym(lib, "pb2_kv_nbytes")!, to: PB2KVNbytes.self) - let kvShape = unsafeBitCast(dlsym(lib, "pb2_kv_shape")!, to: PB2KVShape.self) - let exportKV = unsafeBitCast(dlsym(lib, "pb2_export_kv")!, to: PB2ExportKV.self) - - let cache = model.newCache(parameters: nil) - log("Cache created: \(cache.count) entries") - for i in 0..<15 { - log(" export layer \(i)...") - let nb = kvNbytes(Int32(i)) - log(" nb=\(nb)") - guard nb > 0 else { log("Layer \(i): no data"); continue } - var kvH: Int32 = 0, seqL: Int32 = 0, hd: Int32 = 0 - let _ = kvShape(Int32(i), &kvH, &seqL, &hd) - log(" shape: [\(kvH),\(seqL),\(hd)]") - - let kBuf = UnsafeMutableRawPointer.allocate(byteCount: nb, alignment: 16) - let vBuf = UnsafeMutableRawPointer.allocate(byteCount: nb, alignment: 16) - log(" allocated bufs") - let rc = exportKV(Int32(i), kBuf, vBuf) - log(" exported rc=\(rc)") - guard rc == 0 else { kBuf.deallocate(); vBuf.deallocate(); log("Export \(i) failed"); continue } - - let shape = [1, Int(kvH), Int(seqL), Int(hd)] - let numElements = shape.reduce(1, *) - let bpe = nb / numElements - let kData = Data(bytes: kBuf, count: nb) - let vData = Data(bytes: vBuf, count: nb) - kBuf.deallocate(); vBuf.deallocate() - - let kArr: MLXArray - let vArr: MLXArray - if bpe == 2 { - // bfloat16 — view as bf16 - kArr = MLXArray(kData, shape, type: UInt16.self).view(dtype: .bfloat16) - vArr = MLXArray(vData, shape, type: UInt16.self).view(dtype: .bfloat16) - } else { - // float32 — convert to bf16 - kArr = MLXArray(kData, shape, type: Float.self).asType(.bfloat16) - vArr = MLXArray(vData, shape, type: Float.self).asType(.bfloat16) - } + // Standalone allocator bug repro — no model needed + if args.contains("--repro-allocator") { + let rc = gp_repro_allocator_bug() + log("Allocator repro returned: \(rc) (\(rc == 0 ? "OK" : "BUG REPRODUCED"))") + return + } - log(" Layer \(i): K=\(kArr.shape) nb=\(nb)") - let _ = cache[i].update(keys: kArr, values: vArr) - } - log("All layers injected, evaluating cache...") - eval(cache) - let c0sum = MLX.sum(cache[0].state[0]).item(Float.self) - log(String(format: "Cache[0] K cksum: %.4f (bridge: %.4f) %@", - c0sum, ck, abs(c0sum - ck) < 0.01 ? "✓" : "✗")) + let modelId = args.firstIndex(of: "--model").flatMap { i in + i + 1 < args.count ? args[i + 1] : nil + } ?? "mlx-community/gemma-4-e2b-it-4bit" - // --- Task 3: Decode correctness --- - log("--- DECODE (native prefill → Swift decode) ---") - let lastTok = MLXArray([Array(allTokens.prefix(16)).last!]).reshaped(1, 1) - var nativeDecode: [Int32] = [] - var inp = lastTok - for _ in 0..<8 { - let logits = model(inp, cache: cache) - let next = MLX.argMax(logits[0..., -1, 0...], axis: -1) - eval(next) - let tok = next.item(Int32.self) - nativeDecode.append(tok) - inp = MLXArray([tok]).reshaped(1, 1) - } - log("Native decode: \(nativeDecode)") + let modelConfig: ModelConfiguration + if modelId.hasPrefix("/") || modelId.hasPrefix("~") || modelId.hasPrefix(".") { + let expanded = NSString(string: modelId).expandingTildeInPath + modelConfig = ModelConfiguration(directory: URL(fileURLWithPath: expanded)) + } else { + modelConfig = ModelConfiguration(id: modelId) + } - log("--- DECODE (Swift prefill → Swift decode) ---") - let swiftCache = model.newCache(parameters: nil) - let swiftArr = MLXArray(Array(allTokens.prefix(16))).reshaped(1, 16) - let _ = model(swiftArr, cache: swiftCache); eval(swiftCache) + log("Loading: \(modelId)") + let container = try await LLMModelFactory.shared.loadContainer( + configuration: modelConfig) { p in + if p.fractionCompleted > 0.99 { log("Model loaded") } + } - var swiftDecode: [Int32] = [] - inp = lastTok - for _ in 0..<8 { - let logits = model(inp, cache: swiftCache) - let next = MLX.argMax(logits[0..., -1, 0...], axis: -1) - eval(next) - let tok = next.item(Int32.self) - swiftDecode.append(tok) - inp = MLXArray([tok]).reshaped(1, 1) - } - log("Swift decode: \(swiftDecode)") - log("MATCH: \(nativeDecode == swiftDecode ? "YES ✓" : "NO ✗")") + let defaultTokenPath = FileManager.default.fileExists(atPath: "/tmp/bench_tokens_32k.json") + ? "/tmp/bench_tokens_32k.json" : "/tmp/bench_tokens_1024.json" + let tokenPath = args.firstIndex(of: "--tokens").flatMap { i in + i + 1 < args.count ? args[i + 1] : nil + } ?? defaultTokenPath + let data = try Data(contentsOf: URL(fileURLWithPath: tokenPath)) + let json = try JSONSerialization.jsonObject(with: data) as! [String: Any] + let allTokens = (json["tokens"] as! [Int]).map { Int32($0) } + log("\(allTokens.count) frozen tokens from \(tokenPath)") + + let sizes = [128, 256, 512, 1024, 2048, 4096, 8192, 16384].filter { $0 <= allTokens.count } + let decodeCount = 16 + + for n in sizes { + let tokens = Array(allTokens.prefix(n)) + let tokenArray = MLXArray(tokens.map { Int($0) }) + let input = LMInput(text: LMInput.Text(tokens: tokenArray)) + var params = GenerateParameters(temperature: 0) + // KV compression: set via KV_SCHEME env (e.g. KV_SCHEME=turbo4) + if let scheme = ProcessInfo.processInfo.environment["KV_SCHEME"] { + params.kvScheme = scheme } - log("After perform") - dlclose(lib) - } else { - // Swift-only path - for n in [16, 1024] { - let tokens = Array(allTokens.prefix(n)) - try await container.perform { ctx in - let model = ctx.model - let arr = MLXArray(tokens).reshaped(1, n) - for _ in 0..<3 { - let c = model.newCache(parameters: nil) - let _ = model(arr, cache: c); eval(c) - Stream.gpu.synchronize(); MLX.Memory.clearCache() - } - var times: [Double] = [] - for _ in 0..<5 { - let c = model.newCache(parameters: nil) - let t0 = CFAbsoluteTimeGetCurrent() - let _ = model(arr, cache: c); eval(c) - Stream.gpu.synchronize() - times.append((CFAbsoluteTimeGetCurrent() - t0) * 1000) - MLX.Memory.clearCache() - } - let avg = times.reduce(0, +) / 5.0 - log(String(format: "Swift %4d tok: %.1fms (%.0f tok/s)", - n, avg, Double(n)/(avg/1000.0))) - } + // Warmup + let ctx0 = try await container.perform { ctx in ctx } + var wc = 0 + for try await _ in try generate( + input: input, parameters: params, context: ctx0 + ) { wc += 1; if wc >= decodeCount { break } } + + // Timed + let ctx1 = try await container.perform { ctx in ctx } + let t0 = CFAbsoluteTimeGetCurrent() + var firstTokTime: Double = 0 + var count = 0 + for try await _ in try generate( + input: input, parameters: params, context: ctx1 + ) { + count += 1 + if count == 1 { firstTokTime = CFAbsoluteTimeGetCurrent() } + if count >= decodeCount { break } } + let totalTime = CFAbsoluteTimeGetCurrent() + let prefillMs = (firstTokTime - t0) * 1000 + let decodeMs = (totalTime - firstTokTime) * 1000 + let decToks = count - 1 + + log(String(format: "%5d tok | prefill %7.1fms (%6.0f t/s) | decode %7.1fms (%5.1f t/s)", + n, prefillMs, Double(n) / (prefillMs / 1000), + decodeMs, Double(decToks) / (decodeMs / 1000))) + MLX.Memory.clearCache() } + log("Done.") } catch { log("ERROR: \(error)") diff --git a/Tests/Benchmarks/InferenceBenchmark.swift b/Tests/Benchmarks/InferenceBenchmark.swift index 61ec0791cd..353f328d77 100644 --- a/Tests/Benchmarks/InferenceBenchmark.swift +++ b/Tests/Benchmarks/InferenceBenchmark.swift @@ -321,7 +321,7 @@ struct InferenceBenchmarks { ("What is my partner's name?", "Alice"), ] static let minimalSystemPrompt = "You are a helpful assistant. Keep responses concise." - static let simpleQuery = "Hello! What is your name and what can you help me with?" + static let simpleQuery = ProcessInfo.processInfo.environment["MLX_BENCH_PROMPT"] ?? "Hello! What is your name and what can you help me with?" /// Default context limit for non-scaling methods. /// Enforced via maxKVSize (RotatingKVCache) to simulate a realistic chat deployment. static let defaultContextLimit = 4096 @@ -333,10 +333,45 @@ struct InferenceBenchmarks { // MARK: - Entry Point /// Single benchmark entry point. All configuration comes from env vars. + /// Print build environment for debugging — confirms NAX, bridge, model template. + /// If prefill < 10K tok/s on Gemma E2B, something is wrong. + static func printBuildEnvironment() { + let bridge = ProcessInfo.processInfo.environment["NATIVE_PREFILL"] == "1" + + // NAX check: if Cmlx was compiled with NAX, the .o files exist + let naxObj = FileManager.default.fileExists( + atPath: ".build/arm64-apple-macosx/release/Cmlx.build/mlx-generated/steel_attention_nax.cpp.o") + print("[ENV] NAX: \(naxObj ? "ENABLED ✓" : "DISABLED ✗ — merge ekryski/mlx-swift#2, swift package clean, rebuild")") + + print("[ENV] Bridge: \(bridge ? "ENABLED (NATIVE_PREFILL=1)" : "OFF (Swift prefill)")") + if bridge { + let paths = ["Sources/NativePrefillBridge/libprefill_bridge_gemma.dylib", + ".build/arm64-apple-macosx/release/libprefill_bridge_gemma.dylib"] + let found = paths.first { FileManager.default.fileExists(atPath: $0) } + print("[ENV] Bridge dylib: \(found ?? "NOT FOUND — run: ./scripts/build-prefill-bridge.sh")") + } + + // Gemma 4 template check + if let modelPath = ProcessInfo.processInfo.environment["MLX_BENCH_MODEL"], + modelPath.lowercased().contains("gemma") { + let tcPath = (modelPath as NSString).expandingTildeInPath + "/tokenizer_config.json" + if let data = try? Data(contentsOf: URL(fileURLWithPath: tcPath)), + let tc = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { + if let tmpl = tc["chat_template"] as? String, tmpl.count > 100 { + print("[ENV] Gemma template: OK (\(tmpl.count) chars)") + } else { + print("[ENV] Gemma template: MISSING ✗ — run: python3 scripts/fix-gemma4-template.py \(modelPath)") + } + } + } + } + @Test @MainActor func benchmark() async throws { // Force line-buffered stdout so progress lines appear immediately when piped setlinebuf(stdout) + Self.printBuildEnvironment() + let family = try resolveFamily() let kv = BenchEnv.kvConfig let (variant, repoId) = try await resolveVariant(family: family) @@ -536,7 +571,7 @@ struct InferenceBenchmarks { contextSize: Int, messages: [Message], systemPrompt: String?, - maxTokens: Int = 200, + maxTokens: Int = Int(ProcessInfo.processInfo.environment["MLX_BENCH_MAX_TOKENS"].flatMap { Int($0) } ?? 200), includeTools: Bool = false, validation: ValidationCheck? = nil, warmup: Bool = false @@ -613,8 +648,11 @@ struct InferenceBenchmarks { do { lmInput = try await container.prepare(input: userInput) } catch { - print("[BENCH] Template error: \(error). Retrying without tools...") - let fallbackInput = UserInput(prompt: .messages(allMessages)) + // Some models (e.g. Mistral) don't support system messages or tools. + // Retry with just the user messages, no system prompt, no tools. + let userOnly = allMessages.filter { ($0["role"] as? String) != "system" } + print("[BENCH] Template error: \(error). Retrying without system/tools...") + let fallbackInput = UserInput(prompt: .messages(userOnly)) lmInput = try await container.prepare(input: fallbackInput) } var promptTokens = lmInput.text.tokens.dim(lmInput.text.tokens.ndim - 1) @@ -1362,9 +1400,19 @@ struct InferenceBenchmarks { if let cached = ModelCache.shared.get(repoId) { return cached } - let modelConfig = family.extraEOSTokens.isEmpty - ? ModelConfiguration(id: repoId) - : ModelConfiguration(id: repoId, extraEOSTokens: Set(family.extraEOSTokens)) + // Support local paths: if repoId starts with / or ~, treat as directory + let isLocal = repoId.hasPrefix("/") || repoId.hasPrefix("~") || repoId.hasPrefix(".") + let modelConfig: ModelConfiguration + if isLocal { + let expanded = NSString(string: repoId).expandingTildeInPath + modelConfig = family.extraEOSTokens.isEmpty + ? ModelConfiguration(directory: URL(fileURLWithPath: expanded)) + : ModelConfiguration(directory: URL(fileURLWithPath: expanded), extraEOSTokens: Set(family.extraEOSTokens)) + } else { + modelConfig = family.extraEOSTokens.isEmpty + ? ModelConfiguration(id: repoId) + : ModelConfiguration(id: repoId, extraEOSTokens: Set(family.extraEOSTokens)) + } let container = try await LLMModelFactory.shared.loadContainer(configuration: modelConfig) { p in if p.fractionCompleted < 0.01 || p.fractionCompleted > 0.99 { print("[BENCH] Loading: \(String(format: "%.0f", p.fractionCompleted * 100))%") diff --git a/docs/qwen-prefill-optimization.md b/docs/qwen-prefill-optimization.md new file mode 100644 index 0000000000..2aeb89fe44 --- /dev/null +++ b/docs/qwen-prefill-optimization.md @@ -0,0 +1,107 @@ +# Qwen Prefill Optimization Log + +## Summary + +The native prefill bridge (generic_prefill.cpp) for Qwen models matches Swift-only +prefill performance within ~3% across all context sizes. The bridge overhead from +eval barriers, embedding workarounds, and KV cache management is minimal compared +to the raw compute (quantized matmuls, SDPA) which dominates wall time. + +Two clean-up optimizations were applied: +1. **Embedding simplification**: Removed unnecessary `add-zero + eval` copies in + `make_embedding()`. Swift arrays already have pinned GPU buffers, so direct + reference is sufficient (eval still called to ensure pinning). +2. **MoE routing fix**: Changed expert selection to use raw gate logits + (`argpartition(-gates)`) instead of post-softmax scores, matching the Swift + implementation. Functionally equivalent (softmax is monotonic) but avoids + unnecessary `negative(softmax + 0)` graph nodes. + +## Baseline Results + +All measurements on Apple Silicon, release build, no background processes. +Numbers from back-to-back runs (second benefits from warm cache). + +### Qwen2.5-3B-Instruct-4bit (dense, 36 layers, qwen2) + +| Tokens | Bridge (t/s) | Swift (t/s) | Delta | +|--------|-------------|-------------|-------| +| 128 | 1861 | 1843 | +1.0% | +| 256 | 2158 | 2110 | +2.3% | +| 512 | 2290 | 2353 | -2.7% | +| 1024 | 2395 | 2473 | -3.2% | +| 2048 | 2412 | 2494 | -3.3% | +| 4096 | 2315 | 2409 | -3.9% | + +### Qwen3-4B-4bit (dense, 36 layers, qwen3) + +| Tokens | Bridge (t/s) | Swift (t/s) | Delta | +|--------|-------------|-------------|-------| +| 128 | 1314 | 1295 | +1.5% | +| 256 | 1476 | 1528 | -3.4% | +| 512 | 1593 | 1635 | -2.6% | +| 1024 | 1641 | 1684 | -2.6% | +| 2048 | 1628 | 1682 | -3.2% | +| 4096 | 1532 | 1592 | -3.8% | + +### Qwen3-Coder-30B-A3B MoE (48 layers, 128 experts, 6-bit, qwen3_moe) + +| Tokens | Bridge (t/s) | Swift (t/s) | Delta | +|--------|-------------|-------------|-------| +| 128 | 1054 | (*) | | +| 256 | 1386 | (*) | | +| 512 | 1543 | (*) | | +| 1024 | 1690 | (*) | | + +(*) Swift-only MoE baseline not obtained due to extreme model loading time +(>30min for 18GB model with 48 x 128 expert weights). Expected to match bridge +within ~3% since both use the same underlying MLX ops (gather_qmm, SDPA). + +## Architecture Analysis + +### Generic bridge overhead sources (vs Gemma v2 specialized bridge): +1. **Eval barriers every 8 layers** -- required to prevent Metal allocator from + reclaiming weight buffers. Removing them degrades correctness. +2. **Per-layer weight eval during build** -- pins GPU buffers for 36-48 layer + models. Required for correctness. +3. **Post-forward KV eval** -- syncs all KV caches after forward. May overlap + with chunk-end eval but removing it doesn't help (< 1ms). +4. **Embedding ownership workaround** -- `add-zero + eval` was unnecessary. + Simplified to direct reference + eval (neutral perf impact). + +### Why the bridge can't beat Swift for Qwen: +- Swift's `prepare()` already processes tokens in a single chunk (up to 4096 tokens) + with one `asyncEval` at the end. This is effectively the same strategy as the bridge. +- The compute is dominated by `quantized_matmul` (dense layers) and `gather_qmm` + (MoE layers), which are the same Metal kernels in both paths. +- The bridge adds ~3% overhead from eval barrier synchronization (4 eval points + per 36-layer model), but this prevents memory corruption. + +### MoE compute profile (Qwen3-Coder-30B): +- Attention: 19M params/layer (7% of compute) +- MoE: 269M active params/layer (93% of compute, top-8 of 128 experts) +- Theoretical roofline at 150 GB/s: ~14.8K t/s at 1024 tokens +- Measured: 1.69K t/s = 11% of roofline (gather_qmm cache locality limits) + +## Optimizations Tested + +| Optimization | Impact | Status | +|-------------|--------|--------| +| Remove embedding add-zero copy | Neutral | Applied (cleaner code) | +| MoE routing: use raw gates for argpartition | Neutral | Applied (matches Swift) | +| Remove mid-forward eval barriers | **Regression** (allocator corruption) | Reverted | +| Remove per-layer build eval | **Regression** (weight buffer reclaimed) | Reverted | +| Remove post-forward KV eval | **Regression** (timing measurement artifact) | Reverted | +| Increase EVAL_CADENCE (8 -> 36) | Neutral | Reverted (no benefit) | +| Remove eval barriers entirely | **-20% decode regression** | Reverted | + +## Conclusion + +The generic prefill bridge achieves near-parity with Swift for Qwen models. +Further optimization requires either: +1. **MLX kernel improvements** (faster gather_qmm, better MoE dispatch) +2. **Model-specific tricks** (fused gate+up projections, which require weight + restructuring at load time) +3. **Hardware-specific tuning** (SDPA tiling for specific Apple Silicon variants) + +None of these are bridge-side optimizations -- they require changes to the +underlying MLX framework. diff --git a/scripts/benchmark.sh b/scripts/benchmark.sh index 2da0f5fc4e..825eb030f5 100755 --- a/scripts/benchmark.sh +++ b/scripts/benchmark.sh @@ -41,6 +41,7 @@ PPL=false BASELINE=false BATCH=1 THINK=false +BRIDGE=false QUICK_CONTEXTS="128,1024,4096,32768" # ───────────────────────────────────────────── @@ -114,6 +115,7 @@ while [[ $# -gt 0 ]]; do --baseline) BASELINE=true; shift ;; --batch) BATCH="$2"; shift 2 ;; --think) THINK=true; shift ;; + --bridge) BRIDGE=true; shift ;; -h|--help) show_help; exit 0 ;; *) log_error "Unknown argument: $1"; show_help; exit 1 ;; esac @@ -240,6 +242,12 @@ for q in "${QUANTS[@]}"; do unset MLX_BENCH_THINK fi + if $BRIDGE; then + export NATIVE_PREFILL=1 + else + unset NATIVE_PREFILL + fi + log_info "Running: quant=$q kv=$kv method=$METHOD" # Stream filtered output in real-time. diff --git a/scripts/build-prefill-bridge.sh b/scripts/build-prefill-bridge.sh new file mode 100755 index 0000000000..570e16b9e9 --- /dev/null +++ b/scripts/build-prefill-bridge.sh @@ -0,0 +1,46 @@ +#!/bin/bash +# Build the native C++ prefill bridges as standalone dylibs. +# +# Two modes: +# --standalone: Link Cmlx objects INTO the dylib (own MLX copy, max perf) +# (default): Use -undefined dynamic_lookup (share host MLX, safe allocator) +# +# Usage: ./scripts/build-prefill-bridge.sh [--standalone] +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" +SRC_DIR="$PROJECT_ROOT/Sources/NativePrefillBridge" +MLX_SWIFT="${MLX_SWIFT_PATH:-$PROJECT_ROOT/.build/checkouts/mlx-swift}" +MLX_INC="$MLX_SWIFT/Source/Cmlx/mlx" +MLX_C_INC="$MLX_SWIFT/Source/Cmlx/mlx-c" +RELEASE_DIR="$PROJECT_ROOT/.build/arm64-apple-macosx/release" + +STANDALONE=false +[ "${1:-}" = "--standalone" ] && STANDALONE=true + +COMMON="-std=c++20 -O3 -DNDEBUG -fPIC -I$MLX_INC -I$MLX_C_INC -I$SRC_DIR -target arm64-apple-macosx14.0" + +if $STANDALONE; then + CMLX_OBJS=$(find "$RELEASE_DIR/Cmlx.build" -name "*.o" 2>/dev/null) + if [ -z "$CMLX_OBJS" ]; then + echo "ERROR: No Cmlx objects. Run 'swift build -c release' first." + exit 1 + fi + LINK_FLAGS="$CMLX_OBJS -framework Metal -framework Foundation -framework Accelerate" + echo "Building STANDALONE dylibs (embedded MLX)..." +else + LINK_FLAGS="-Wl,-undefined,dynamic_lookup" + echo "Building DYNAMIC dylibs (shared host MLX)..." +fi + +for src in prefill_bridge_gemma prefill_bridge_qwen; do + dylib="$SRC_DIR/lib${src}.dylib" + echo " ${src}.cpp -> $dylib" + clang++ $COMMON -shared $LINK_FLAGS -o "$dylib" "$SRC_DIR/${src}.cpp" + cp "$dylib" "$RELEASE_DIR/" 2>/dev/null || true + TEST_BUNDLE="$RELEASE_DIR/mlx-swift-lmPackageTests.xctest/Contents/MacOS/" + cp "$dylib" "$TEST_BUNDLE" 2>/dev/null || true +done + +echo "Done." +ls -lh "$SRC_DIR"/libprefill_bridge_*.dylib diff --git a/scripts/fix-gemma4-template.py b/scripts/fix-gemma4-template.py new file mode 100644 index 0000000000..708b12ada4 --- /dev/null +++ b/scripts/fix-gemma4-template.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Fix Gemma 4 MLX community quants that ship without chat_template. + +MLX community quantizations of Gemma 4 (E2B, E4B, 26B-A4B, 31B) are missing +the chat_template field in tokenizer_config.json. Without it, the model echoes +input or produces garbage instead of following instructions. + +Usage: + python3 scripts/fix-gemma4-template.py ~/models/gemma-4-e2b-it-4bit + python3 scripts/fix-gemma4-template.py ~/models/gemma-4-26b-a4b-4bit +""" +import json, sys, os + +if len(sys.argv) < 2: + print("Usage: python3 fix-gemma4-template.py ") + sys.exit(1) + +model_path = os.path.expanduser(sys.argv[1]) +tc_path = os.path.join(model_path, "tokenizer_config.json") +jinja_path = os.path.join(model_path, "chat_template.jinja") + +if not os.path.exists(tc_path): + print(f"ERROR: {tc_path} not found") + sys.exit(1) + +tc = json.load(open(tc_path)) + +# Check if already has template +if "chat_template" in tc and len(tc["chat_template"]) > 100: + print(f"OK: chat_template already present ({len(tc['chat_template'])} chars)") + sys.exit(0) + +# Download jinja from E2B repo (all Gemma 4 variants use the same template) +if not os.path.exists(jinja_path): + print("Downloading chat_template.jinja from mlx-community/gemma-4-e2b-it-4bit...") + from huggingface_hub import hf_hub_download + src = hf_hub_download("mlx-community/gemma-4-e2b-it-4bit", "chat_template.jinja") + import shutil + shutil.copy(src, jinja_path) + print(f" Saved: {jinja_path}") + +template = open(jinja_path).read() +tc["chat_template"] = template +json.dump(tc, open(tc_path, "w"), indent=2) +print(f"FIXED: Injected chat_template ({len(template)} chars) into {tc_path}")