diff --git a/Libraries/MLXLLM/Models/Gemma4Text.swift b/Libraries/MLXLLM/Models/Gemma4Text.swift index 6a43da54fd..cc20da328c 100644 --- a/Libraries/MLXLLM/Models/Gemma4Text.swift +++ b/Libraries/MLXLLM/Models/Gemma4Text.swift @@ -841,6 +841,50 @@ public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider { return processedWeights } + // MARK: - Native Prefill Bridge + + /// Override prepare() to use the native C++ prefill bridge when NATIVE_PREFILL=1. + /// The bridge bypasses Swift MLXArray/ARC overhead for 2-3x faster prefill. + /// Falls back to default chunked prefill when the bridge is unavailable. + public func prepare(_ input: LMInput, cache: [KVCache], windowSize: Int?) throws + -> PrepareResult + { + let bridge = GemmaPrefillBridge.shared + + if bridge.isEnabled { + if bridge.ensureInitialized(config: config, model: self) { + let (ms, ok) = bridge.runAndInjectKV( + tokenArray: input.text.tokens, + cache: cache, + numLayers: config.hiddenLayers + ) + if ok { + print(String(format: "[pb2] Native prefill %.0fms (%d tokens)", + ms, input.text.tokens.size)) + // Return last token for the iterator's "prime the pump" step + let lastToken = input.text[(-1)...] + return .tokens(lastToken) + } + print("[pb2] Bridge run failed, falling back to default prefill") + } + } + + // Default chunked prefill (same as LLMModel extension) + let prefillStepSize = windowSize ?? 512 + var y = input.text + + while y.tokens.size > 1 { + let chunkSize = min(prefillStepSize, y.tokens.size - 1) + let chunkInput = y[.newAxis, .. [KVCache] { var caches = [KVCache]() diff --git a/Libraries/MLXLLM/Models/GemmaPrefillBridge.swift b/Libraries/MLXLLM/Models/GemmaPrefillBridge.swift new file mode 100644 index 0000000000..00a5983216 --- /dev/null +++ b/Libraries/MLXLLM/Models/GemmaPrefillBridge.swift @@ -0,0 +1,197 @@ +// +// GemmaPrefillBridge.swift +// mlx-swift-lm +// +// Gemma 4 native prefill bridge using dlopen/dlsym. +// Loads libprefill_bridge_gemma.dylib at runtime to avoid SPM LTO +// miscompilation. The dylib shares the host MLX allocator via +// -undefined dynamic_lookup. +// +// Opt-in: set NATIVE_PREFILL=1 environment variable. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +// MARK: - C function pointer types + +// int gemma_init(int, int, int, int, int, int) +private typealias GemmaInitFn = @convention(c) (Int32, Int32, Int32, Int32, Int32, Int32) -> Int32 + +// int gemma_set_weight(const char*, void*) +private typealias GemmaSetWeightFn = @convention(c) (UnsafePointer, UnsafeMutableRawPointer) -> Int32 + +// int gemma_finalize(void) +private typealias GemmaFinalizeFn = @convention(c) () -> Int32 + +// int gemma_run_array(void*, double*, float*) +private typealias GemmaRunArrayFn = @convention(c) ( + UnsafeMutableRawPointer, UnsafeMutablePointer, UnsafeMutablePointer +) -> Int32 + +// void gemma_get_kv_handles(int, void**, void**) +private typealias GemmaGetKVHandlesFn = @convention(c) ( + Int32, UnsafeMutablePointer, + UnsafeMutablePointer +) -> Void + +// void gemma_cleanup(void) +private typealias GemmaCleanupFn = @convention(c) () -> Void + +// MARK: - Bridge + +final class GemmaPrefillBridge { + static let shared = GemmaPrefillBridge() + + private var handle: UnsafeMutableRawPointer? + private var initialized = false + + // Resolved function pointers + private var fnInit: GemmaInitFn? + private var fnSetWeight: GemmaSetWeightFn? + private var fnFinalize: GemmaFinalizeFn? + private var fnRunArray: GemmaRunArrayFn? + private var fnGetKVHandles: GemmaGetKVHandlesFn? + private var fnCleanup: GemmaCleanupFn? + + /// Whether the native prefill bridge is available and opted-in + var isEnabled: Bool { + ProcessInfo.processInfo.environment["NATIVE_PREFILL"] == "1" + } + + /// Load the dylib and resolve all symbols. Returns false on failure. + private func loadLibrary() -> Bool { + if handle != nil { return true } + + // Search paths: next to the binary, .build release dir, Sources dir + let candidates = [ + "libprefill_bridge_gemma.dylib", + Bundle.main.bundlePath + "/libprefill_bridge_gemma.dylib", + Bundle.main.bundlePath + "/../libprefill_bridge_gemma.dylib", + ] + + for path in candidates { + if let h = dlopen(path, RTLD_NOW | RTLD_LOCAL) { + handle = h + break + } + } + + guard let h = handle else { + print("[pb2] Failed to load libprefill_bridge_gemma.dylib") + return false + } + + // Resolve symbols + fnInit = unsafeBitCast(dlsym(h, "gemma_init"), to: GemmaInitFn.self) + fnSetWeight = unsafeBitCast(dlsym(h, "gemma_set_weight"), to: GemmaSetWeightFn.self) + fnFinalize = unsafeBitCast(dlsym(h, "gemma_finalize"), to: GemmaFinalizeFn.self) + fnRunArray = unsafeBitCast(dlsym(h, "gemma_run_array"), to: GemmaRunArrayFn.self) + fnGetKVHandles = unsafeBitCast( + dlsym(h, "gemma_get_kv_handles"), to: GemmaGetKVHandlesFn.self) + fnCleanup = unsafeBitCast(dlsym(h, "gemma_cleanup"), to: GemmaCleanupFn.self) + + // Verify all symbols resolved + guard fnInit != nil, fnSetWeight != nil, fnFinalize != nil, + fnRunArray != nil, fnGetKVHandles != nil, fnCleanup != nil + else { + print("[pb2] Failed to resolve all symbols from bridge dylib") + dlclose(h) + handle = nil + return false + } + + print("[pb2] Loaded libprefill_bridge_gemma.dylib") + return true + } + + /// Initialize the bridge with model config and weights. + func ensureInitialized(config: Gemma4TextConfiguration, model: Module) -> Bool { + if initialized { return true } + guard loadLibrary() else { return false } + + // TODO: derive sliding_window_pattern from config.layerTypes instead of hardcoding + let rc = fnInit!( + Int32(config.hiddenLayers), + Int32(config.hiddenSize), + Int32(config.attentionHeads), + Int32(config.kvHeads), + Int32(config.slidingWindow), + 3 // sliding_window_pattern: every 5th layer is full attention + ) + if rc != 0 { + print("[pb2] init failed with code \(rc)") + return false + } + + // Pass all model weights to the C++ bridge + let params = model.parameters().flattened() + var weightCount = 0 + for (key, arr) in params { + let bridgeKey = "model." + key + guard let rawPtr = arr.ctx.ctx else { continue } + let status = bridgeKey.withCString { cKey in + fnSetWeight!(cKey, rawPtr) + } + if status == 0 { weightCount += 1 } + } + print("[pb2] Passed \(weightCount) weights to bridge") + + let finRC = fnFinalize!() + if finRC != 0 { + print("[pb2] finalize failed with code \(finRC)") + return false + } + + initialized = true + print("[pb2] Bridge initialized for gemma4_text") + return true + } + + /// Run native prefill and inject K/V into Swift caches. + /// Returns (elapsed_ms, success). + func runAndInjectKV(tokenArray: MLXArray, cache: [KVCache], numLayers: Int) -> (Double, Bool) { + guard initialized else { return (0, false) } + + let tokens2d = tokenArray.dim(0) == 1 ? tokenArray : tokenArray.reshaped(1, tokenArray.size) + var ms: Double = 0 + var checksum: Float = 0 + + guard let rawPtr = tokens2d.ctx.ctx else { return (0, false) } + let rc = fnRunArray!(rawPtr, &ms, &checksum) + if rc != 0 { return (0, false) } + + // Inject K/V from bridge into Swift caches + for i in 0.. +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mlx/mlx.h" +#include "generic_prefill.h" + +using namespace mlx::core; + +// ============================================================================ +// Reliable observer — NEVER use raw sum(abs(x)) on float16. +// MLX's float16 reduction kernel produces wrong results for large arrays. +// ============================================================================ + +static float safe_abssum(const array& a) { + // Cast to float32 before reducing to avoid float16 reduction bug + auto f32 = astype(a, float32); + auto result = sum(abs(f32)); + eval({result}); + return result.item(); +} + +// CPU-side checksum: read first N float16 elements, hash them +static uint64_t cpu_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; +} + +// ============================================================================ +// 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}); + + auto out = o_proj(attn); + + return out; +} + +// ============================================================================ +// 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; + } + + if (c == 0 && (i == 0 || i == (int)layers.size() - 1)) { + char buf[64]; + snprintf(buf, sizeof(buf), "L%d post_layer", i); + } + + // 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) { + } + } + + auto out = final_norm(h); + return out; + } +}; + +// ============================================================================ +// 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) { + } + } + + // 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 { + + 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/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..653d8d5657 --- /dev/null +++ b/Sources/NativePrefillBridge/prefill_bridge_gemma.cpp @@ -0,0 +1,788 @@ +// 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)); + } else { + } + + std::vector layers; + layers.reserve(g_num_layers); + for (int i = 0; i < g_num_layers; i++) { + 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 { + 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..3561307192 --- /dev/null +++ b/Sources/NativePrefillBridge/prefill_bridge_qwen.cpp @@ -0,0 +1,1048 @@ +// 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) + } +} + +// ============================================================================ +// 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; + + 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] 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 { + 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/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