From 729cfecb1b19a8fd9b8ae9bc2a140aef7c69542d Mon Sep 17 00:00:00 2001 From: Aleksei Boklag <146362331+goodmai@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:49:18 +0100 Subject: [PATCH 1/2] =?UTF-8?q?feat(inkling):=20Inkling=202=20Mini=20P1=20?= =?UTF-8?q?=E2=80=94=20looped=20text=20stack=20in=20plain=20MLX=20ops,=20o?= =?UTF-8?q?Q/mlx-lm=20weight=20layouts,=20TinyModel=20(#650)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Inkling2Model (inkling2_loop / inkling2): prelude, core x num_passes and coda over 48 layer visits; passes 2-3 restart from the prelude output and read cross-pass messages (depth attention over the previous pass's blocks) through rank-r gates on q, k, v and the MoE input. - Attention without RoPE: learned relative logits (r_proj x rel_logits_proj), per-token sinks, sigmoid output gate, q/k/rel L2 clips, value norm without gamma, log-scaled query temperature on global layers; static short convs on local K/V, dynamic ones on global K/V, short convs after attention and MLP. - Depth-attention residuals over 6-layer blocks; sigmoid + bias router with route_scale; softcapped SwiGLU over interleaved gate/up expert rows. - Caches: a flat [attention, ArraysCache(4)] per visit; local layers use Inkling2WindowKVCache (temporal order, compacted to the window, exact key positions), treated as snapshot-only so hybrid prompt-cache reuse works. - Weights: mlx-lm layout as is; oMLX oQ layout (fused in_proj / q_proj / k_proj / v_proj rows, packed loop controllers, loop_message queries) mapped to it; modules quantized from the packed weights' shapes. - TinyModel.inkling2Loop (6 layers, core 2..<4 x 3, window 8) with tests: decode in chunks of 1/4/7 equals the full forward, loop changes output, oQ layout round-trips, window cache positions and trim; joins the all-family suites (prompt-cache reuse passes; Quest and batched decode refused). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012cicguZMN3jhNGmf5327oh --- .../HybridPrefixSnapshot.swift | 2 +- .../MLXInferenceEngine+Loading.swift | 4 + .../BasaltInference/ModelCapabilities.swift | 1 + .../Models/Inkling2/Inkling2Attention.swift | 154 ++++++++++++++++++ .../Models/Inkling2/Inkling2Checkpoint.swift | 98 +++++++++++ .../Inkling2/Inkling2DecoderLayer.swift | 101 ++++++++++++ .../Models/Inkling2/Inkling2Layers.swift | 112 +++++++++++++ .../Models/Inkling2/Inkling2Model.swift | 113 +++++++++++++ .../Models/Inkling2/Inkling2Primitives.swift | 92 +++++++++++ .../Inkling2/Inkling2WindowKVCache.swift | 83 ++++++++++ Tests/BasaltTests/FeatureMatrixTests.swift | 4 +- Tests/BasaltTests/Fixtures/TinyModels.swift | 23 ++- Tests/BasaltTests/Inkling2ModelTests.swift | 149 +++++++++++++++++ 13 files changed, 930 insertions(+), 6 deletions(-) create mode 100644 Sources/BasaltInference/Models/Inkling2/Inkling2Attention.swift create mode 100644 Sources/BasaltInference/Models/Inkling2/Inkling2Checkpoint.swift create mode 100644 Sources/BasaltInference/Models/Inkling2/Inkling2DecoderLayer.swift create mode 100644 Sources/BasaltInference/Models/Inkling2/Inkling2Layers.swift create mode 100644 Sources/BasaltInference/Models/Inkling2/Inkling2Model.swift create mode 100644 Sources/BasaltInference/Models/Inkling2/Inkling2Primitives.swift create mode 100644 Sources/BasaltInference/Models/Inkling2/Inkling2WindowKVCache.swift create mode 100644 Tests/BasaltTests/Inkling2ModelTests.swift diff --git a/Sources/BasaltInference/HybridPrefixSnapshot.swift b/Sources/BasaltInference/HybridPrefixSnapshot.swift index e684a09a..09d9dfc0 100644 --- a/Sources/BasaltInference/HybridPrefixSnapshot.swift +++ b/Sources/BasaltInference/HybridPrefixSnapshot.swift @@ -5,7 +5,7 @@ import BasaltCore extension KVCache { var isSnapshotOnly: Bool { - self is ArraysCache || type(of: self) == RotatingKVCache.self + self is ArraysCache || type(of: self) == RotatingKVCache.self || self is Inkling2WindowKVCache } var holdsWholeContext: Bool { diff --git a/Sources/BasaltInference/MLXInferenceEngine+Loading.swift b/Sources/BasaltInference/MLXInferenceEngine+Loading.swift index f2a548f9..cb7203b6 100644 --- a/Sources/BasaltInference/MLXInferenceEngine+Loading.swift +++ b/Sources/BasaltInference/MLXInferenceEngine+Loading.swift @@ -58,6 +58,10 @@ extension MLXInferenceEngine { } } await ModelFamilyAliases.registerAll() + for type in Inkling2Model.modelTypes { + await registry.registerModelType(type) { data in try Inkling2Model(configurationData: data) } + await VLMTypeRegistry.shared.registerModelType(type) { data in try Inkling2Model(configurationData: data) } + } await registry.registerModelType(FlintModel.modelType) { data in FlintModel(try JSONDecoder.json5().decode(FlintConfiguration.self, from: data).validated()) } diff --git a/Sources/BasaltInference/ModelCapabilities.swift b/Sources/BasaltInference/ModelCapabilities.swift index 50f2c728..62d0e526 100644 --- a/Sources/BasaltInference/ModelCapabilities.swift +++ b/Sources/BasaltInference/ModelCapabilities.swift @@ -110,6 +110,7 @@ struct ModelCapabilities: Equatable, Sendable { (["gemma4", "gemma4_text", "gemma4_unified", "gemma4_unified_text"], gemma4), ([FlintModel.modelType], flint), (["falcon_h1", "falcon-h1"], falconH1), + (Inkling2Model.modelTypes, ModelCapabilities(verified: [])), ([PaddleOCRVL.modelType], ModelCapabilities(verified: all.subtracting([.mtp, .cacheBlend, .kvQuantization, .kvZones, .kvHeadSplit, .quest]))), ([DeepSeekOCR.modelType, DeepSeekOCR2.modelType], ModelCapabilities(verified: all.subtracting([.mtp, .cacheBlend, .kvQuantization, .kvZones, .kvHeadSplit, .quest]))), ] diff --git a/Sources/BasaltInference/Models/Inkling2/Inkling2Attention.swift b/Sources/BasaltInference/Models/Inkling2/Inkling2Attention.swift new file mode 100644 index 00000000..6140cc7d --- /dev/null +++ b/Sources/BasaltInference/Models/Inkling2/Inkling2Attention.swift @@ -0,0 +1,154 @@ +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +final class Inkling2RelativeLogits: Module { + var proj: MLXArray + + init(relativeDim: Int, extent: Int) { + proj = MLXArray.zeros([relativeDim, extent]) + } +} + +final class Inkling2ClipScale: Module { + var scale: MLXArray + + init(heads: Int, dims: Int) { + scale = MLXArray.ones([heads, dims]) + } +} + +final class Inkling2KVConvolution: Module { + @ModuleInfo(key: "conv1d") var conv: Inkling2DepthwiseWeight? + @ParameterInfo(key: "static_weight") var staticWeight: MLXArray? + @ModuleInfo(key: "weight_proj") var weightProj: Linear? + let kernel: Int + let heads: Int + + init(dims: Int, inputDims: Int, heads: Int, kernel: Int, dynamic: Bool) { + self.kernel = kernel + self.heads = heads + if dynamic { + _staticWeight.wrappedValue = MLXArray.zeros([kernel, dims]) + _weightProj.wrappedValue = Linear(inputDims, heads * kernel, bias: false) + } else { + _conv.wrappedValue = Inkling2DepthwiseWeight(dims: dims, kernel: kernel) + } + } + + func callAsFunction(_ x: MLXArray, input: MLXArray, state: MLXArray?) -> (MLXArray, MLXArray) { + if let conv { return Inkling2Ops.shortConvolution(x, weight: conv.weight, state: state, kernel: kernel) } + guard let staticWeight, let weightProj else { return (x, Inkling2Ops.convWindow(x, state: state, kernel: kernel)) } + return Inkling2Ops.dynamicConvolution(x, dynamic: weightProj(input), staticWeight: staticWeight, heads: heads, state: state, kernel: kernel) + } +} + +struct Inkling2Positions { + var query: Int + var key: Int +} + +struct Inkling2AttentionInputs { + var query: MLXArray + var key: MLXArray + var value: MLXArray +} + +final class Inkling2Attention: Module { + let heads: Int + let kvHeads: Int + let headDim: Int + let window: Int + let scale: Float + let config: Inkling2Configuration + let global: Bool + + @ModuleInfo(key: "q_proj") var qProj: Linear + @ModuleInfo(key: "k_proj") var kProj: Linear + @ModuleInfo(key: "v_proj") var vProj: Linear + @ModuleInfo(key: "r_proj") var rProj: Linear + @ModuleInfo(key: "o_proj") var oProj: Linear + @ModuleInfo(key: "gate_proj") var gateProj: Linear + @ModuleInfo(key: "sink_proj") var sinkProj: Linear + @ModuleInfo(key: "rel_logits_proj") var relativeLogits: Inkling2RelativeLogits + @ModuleInfo(key: "q_l2_clip") var queryClip: Inkling2ClipScale + @ModuleInfo(key: "rel_l2_clip") var relativeClip: Inkling2ClipScale + @ModuleInfo(key: "k_sconv") var keyConv: Inkling2KVConvolution + @ModuleInfo(key: "v_sconv") var valueConv: Inkling2KVConvolution + + init(_ config: Inkling2Configuration, global: Bool) { + self.config = config + self.global = global + (heads, kvHeads, headDim) = (config.heads, config.kvHeads, config.headDim) + window = global ? 0 : config.slidingWindow + scale = 1 / Float(config.headDim).squareRoot() + let (dims, qDims, kvDims) = (config.hiddenSize, config.heads * config.headDim, config.kvHeads * config.headDim) + _qProj.wrappedValue = Linear(dims, qDims, bias: false) + _kProj.wrappedValue = Linear(dims, kvDims, bias: false) + _vProj.wrappedValue = Linear(dims, kvDims, bias: false) + _rProj.wrappedValue = Linear(dims, config.heads * config.relativeDim, bias: false) + _oProj.wrappedValue = Linear(qDims, dims, bias: false) + _gateProj.wrappedValue = Linear(dims, qDims, bias: false) + _sinkProj.wrappedValue = Linear(dims, config.heads, bias: false) + _relativeLogits.wrappedValue = Inkling2RelativeLogits(relativeDim: config.relativeDim, extent: global ? config.relativeExtent : config.slidingWindow) + _queryClip.wrappedValue = Inkling2ClipScale(heads: config.heads, dims: config.headDim) + _relativeClip.wrappedValue = Inkling2ClipScale(heads: config.heads, dims: config.relativeDim) + _keyConv.wrappedValue = Inkling2KVConvolution(dims: kvDims, inputDims: dims, heads: config.kvHeads, kernel: config.shortConvKernel, dynamic: global) + _valueConv.wrappedValue = Inkling2KVConvolution(dims: kvDims, inputDims: dims, heads: config.kvHeads, kernel: config.shortConvKernel, dynamic: global) + } + + func callAsFunction(_ inputs: Inkling2AttentionInputs, cache: KVCache?, conv: inout [MLXArray?]) -> MLXArray { + let (batch, length) = (inputs.query.dim(0), inputs.query.dim(1)) + let hidden = inputs.query + let (keys, keyWindow) = keyConv(kProj(inputs.key), input: inputs.key, state: conv[0]) + let (values, valueWindow) = valueConv(vProj(inputs.value), input: inputs.value, state: conv[1]) + (conv[0], conv[1]) = (keyWindow, valueWindow) + let start = cache?.offset ?? 0 + var queries = Inkling2Ops.l2Clip(qProj(hidden).reshaped(batch, length, heads, headDim), scale: queryClip.scale, threshold: config.qkClip) + var relative = Inkling2Ops.l2Clip(rProj(hidden).reshaped(batch, length, heads, config.relativeDim), scale: relativeClip.scale, threshold: config.relativeClip) + if global { + let positions = (MLXArray(Int32(start) ..< Int32(start + length)).asType(.float32) + 1) / Float(config.logScalingFloor) + let tau = (1 + config.logScalingAlpha * log(maximum(positions, 1))).reshaped(1, length, 1, 1) + queries = (queries.asType(.float32) * tau).asType(queries.dtype) + relative = (relative.asType(.float32) * tau).asType(relative.dtype) + } + let bias = matmul(relative, relativeLogits.proj.asType(relative.dtype)) + let k = Inkling2Ops.l2Clip(keys.reshaped(batch, length, kvHeads, headDim), scale: nil, threshold: config.qkClip).transposed(0, 2, 1, 3) + let v = Inkling2Ops.unitRMS(values.reshaped(batch, length, kvHeads, headDim), eps: config.rmsNormEps).asType(values.dtype).transposed(0, 2, 1, 3) + var (allKeys, allValues) = (k, v) + var keyStart = 0 + if let window = cache as? Inkling2WindowKVCache { + (allKeys, allValues) = window.update(keys: k, values: v) + keyStart = window.lastKeyStart + } else if let cache { + (allKeys, allValues) = cache.update(keys: k, values: v) + } else { + keyStart = start + } + let out = attend(queries.transposed(0, 2, 1, 3), allKeys, allValues, bias: bias, sinks: sinkProj(hidden), positions: Inkling2Positions(query: start, key: keyStart)) + let gated = out.reshaped(batch, length, -1).asType(.float32) * sigmoid(gateProj(hidden).asType(.float32)) + return oProj(gated.asType(hidden.dtype)) + } + + func attend(_ q: MLXArray, _ k: MLXArray, _ v: MLXArray, bias: MLXArray, sinks: MLXArray, positions: Inkling2Positions) -> MLXArray { + let (queryStart, keyStart) = (positions.query, positions.key) + let (batch, length, keysCount) = (q.dim(0), q.dim(2), k.dim(2)) + let extent = bias.dim(-1) + let queryPositions = MLXArray(Int32(queryStart) ..< Int32(queryStart + length)) + let keyPositions = MLXArray(Int32(keyStart) ..< Int32(keyStart + keysCount)) + let distance = queryPositions.expandedDimensions(axis: 1) - keyPositions.expandedDimensions(axis: 0) + var visible = distance .>= 0 + if window > 0 { visible = visible .&& (distance .< Int32(window)) } + let index = broadcast(clip(distance, min: 0, max: extent - 1), to: [batch, heads, length, keysCount]) + let gathered = takeAlong(bias.transposed(0, 2, 1, 3), index, axis: -1).asType(.float32) + let positional = MLX.where(distance .< Int32(extent), gathered, MLXArray(Float(0))) + let mask = MLX.where(visible, positional, MLXArray(-Float.infinity)).reshaped(batch, kvHeads, -1, length, keysCount) + let grouped = q.asType(.float32).reshaped(batch, kvHeads, -1, length, headDim) + let scores = matmul(grouped, k.asType(.float32).expandedDimensions(axis: 2).swappedAxes(-1, -2)) * scale + mask + let sinkLogits = sinks.asType(.float32).transposed(0, 2, 1).reshaped(batch, kvHeads, -1, length, 1) + let weights = softmax(concatenated([scores, sinkLogits], axis: -1), axis: -1, precise: true)[.ellipsis, .. [String: MLXArray] { + let dropped = weights.filter { key, _ in !(key.hasPrefix("vision_tower.") || key.hasPrefix("model.vision_tower.") || key.hasPrefix("mtp.")) } + guard dropped.keys.contains(where: { $0.hasPrefix("model.layers.") }) else { return dropped } + return fromOQ(dropped, config: config) + } + + static func fromOQ(_ weights: [String: MLXArray], config: Inkling2Configuration) -> [String: MLXArray] { + var out: [String: MLXArray] = [:] + var messageQueries: [Int: MLXArray] = [:] + let renames = ["model.embed.": text + "embed_tokens.", "model.embed_norm.": text + "embed_norm.", "model.norm.": text + "norm.", "model.final_input.": text + "final_input."] + for (key, value) in weights { + if let (from, to) = renames.first(where: { key.hasPrefix($0.key) }) { + out[to + key.dropFirst(from.count)] = value + } else if key.hasPrefix("model.layers.") { + let parts = key.split(separator: ".", maxSplits: 3).map(String.init) + guard parts.count == 4, let index = Int(parts[2]) else { continue } + if parts[3] == "loop_message.query" { messageQueries[index] = value; continue } + layer(parts[3], value, index: index, config: config, into: &out) + } else { + out[key] = value + } + } + if let loop = config.loop, !messageQueries.isEmpty { + let rows = (loop.coreStart ..< loop.coreEnd).compactMap { messageQueries[$0] } + if rows.count == loop.coreEnd - loop.coreStart { out[text + "message_input.query"] = stacked(rows) } + } + return out + } + + static func layer(_ name: String, _ value: MLXArray, index: Int, config: Inkling2Configuration, into out: inout [String: MLXArray]) { + let pre = text + "layers.\(index)." + let attention = pre + "self_attn." + let (q, kv, r) = (config.heads * config.headDim, config.kvHeads * config.headDim, config.heads * config.relativeDim) + let dynamicTaps = config.kvHeads * config.shortConvKernel + let simple: [String: String] = [ + "attn_input.query": pre + "attention_input.query", "mlp_input.query": pre + "mlp_input.query", + "attn_norm.weight": pre + "input_layernorm.weight", "mlp_norm.weight": pre + "post_attention_layernorm.weight", + "q_input_norm.weight": pre + "q_input_layernorm.weight", "k_input_norm.weight": pre + "k_input_layernorm.weight", + "v_input_norm.weight": pre + "v_input_layernorm.weight", "attn.q_scale": attention + "q_l2_clip.scale", + "attn.r_scale": attention + "rel_l2_clip.scale", "attn.rel_proj": attention + "rel_logits_proj.proj", + "attn.k_static": attention + "k_sconv.static_weight", "attn.v_static": attention + "v_sconv.static_weight", + "mlp.router_weight": pre + "mlp.gate.weight", "mlp.router_bias": pre + "mlp.gate.e_score_correction_bias", + ] + if let target = simple[name] { out[target] = value; return } + let convs = ["attn_conv": pre + "post_attention_convolution.conv1d.weight", "mlp_conv": pre + "post_mlp_convolution.conv1d.weight", + "attn.k_conv": attention + "k_sconv.conv1d.weight", "attn.v_conv": attention + "v_sconv.conv1d.weight"] + if let target = convs[name] { out[target] = value.expandedDimensions(axis: -1); return } + let (stem, part) = splitPart(name) + switch stem { + case "attn.o_proj": out[attention + "o_proj." + part] = value + case "mlp.experts.w13": out[pre + "mlp.experts.gate_up_proj." + part] = value + case "mlp.experts.w2": out[pre + "mlp.experts.down_proj." + part] = value + case "attn.in_proj": rows(value, part, [("q_proj", q), ("k_proj", kv), ("v_proj", kv), ("r_proj", r), ("gate_proj", q), ("sink_proj", config.heads)], prefix: attention, into: &out) + case "attn.q_proj": rows(value, part, [("q_proj", q), ("r_proj", r), ("gate_proj", q), ("sink_proj", config.heads)], prefix: attention, into: &out) + case "attn.k_proj": rows(value, part, [("k_proj", kv), ("k_sconv.weight_proj", dynamicTaps)], prefix: attention, into: &out) + case "attn.v_proj": rows(value, part, [("v_proj", kv), ("v_sconv.weight_proj", dynamicTaps)], prefix: attention, into: &out) + case "loop_down": loopDown(value, prefix: pre, into: &out) + case "loop_gain_forget": loopGainForget(value, prefix: pre, into: &out) + default: out[pre + name] = value + } + } + + static func splitPart(_ name: String) -> (String, String) { + guard let dot = name.lastIndex(of: "."), quantParts.contains(String(name[name.index(after: dot)...])) else { return (name, "weight") } + return (String(name[.. 0 { _attentionInput.wrappedValue = Inkling2Query(rows: global ? 3 : 1, dims: dims) } + _mlpInput.wrappedValue = Inkling2Query(rows: 1, dims: dims) + _attention.wrappedValue = Inkling2Attention(config, global: global) + _mlp.wrappedValue = Inkling2SparseMoE(config) + _postAttentionNorm.wrappedValue = RMSNorm(dimensions: dims, eps: config.rmsNormEps) + _postAttentionConv.wrappedValue = Inkling2ShortConvolution(dims: dims, kernel: kernel) + _postMLPConv.wrappedValue = Inkling2ShortConvolution(dims: dims, kernel: kernel) + if global { + _queryNorm.wrappedValue = RMSNorm(dimensions: dims, eps: config.rmsNormEps) + _keyNorm.wrappedValue = RMSNorm(dimensions: dims, eps: config.rmsNormEps) + _valueNorm.wrappedValue = RMSNorm(dimensions: dims, eps: config.rmsNormEps) + } else { + _inputNorm.wrappedValue = RMSNorm(dimensions: dims, eps: config.rmsNormEps) + } + if let loop = config.loop, (loop.coreStart ..< loop.coreEnd).contains(index) { + _queryGate.wrappedValue = Inkling2MessageGate(dims: dims, rank: loop.gateRank) + _keyGate.wrappedValue = Inkling2MessageGate(dims: dims, rank: loop.gateRank) + _valueGate.wrappedValue = Inkling2MessageGate(dims: dims, rank: loop.gateRank) + _mlpGate.wrappedValue = Inkling2MessageGate(dims: dims, rank: loop.gateRank) + } + } + + func callAsFunction( + _ hidden: MLXArray, blocks: MLXArray?, cache: KVCache?, conv: ArraysCache?, messages: MLXArray? + ) -> (MLXArray, MLXArray?) { + let dtype = hidden.dtype + var states: [MLXArray?] = (0 ..< 4).map { conv?[$0] } + let normedResidual = Inkling2Ops.unitRMS(hidden) + let inputs = attentionInputs(hidden, mixed: attentionInput.map { $0(blocks!, normedResidual) }, messages: messages, dtype: dtype) + let attended = attention(inputs, cache: cache, conv: &states) + let (afterAttention, attentionWindow) = postAttentionConv(attended, state: states[2]) + states[2] = attentionWindow + var blocks = blocks + var residual = afterAttention.asType(.float32) + if blockBoundary { + let block = normedResidual.expandedDimensions(axis: 0) + blocks = blocks.map { concatenated([$0, block], axis: 0) } ?? block + } else { + residual = hidden.asType(.float32) + residual + } + var x = mlpInput(blocks!, Inkling2Ops.unitRMS(residual))[.ellipsis, 0, 0...] + if let mlpGate, let messages { x = mlpGate(x, message: messages[.ellipsis, 3, 0...]) } + let (afterMLP, mlpWindow) = postMLPConv(mlp(postAttentionNorm(x).asType(dtype)), state: states[3]) + states[3] = mlpWindow + if let conv { + for (slot, window) in states.enumerated() { + if let window { conv[slot] = Inkling2Ops.convState(window, kernel: kernel) } + } + } + return ((residual + afterMLP.asType(.float32)).asType(dtype), blocks) + } + + private func attentionInputs(_ hidden: MLXArray, mixed: MLXArray?, messages: MLXArray?, dtype: DType) -> Inkling2AttentionInputs { + var (q, k, v) = global + ? (mixed?[.ellipsis, 0, 0...] ?? hidden, mixed?[.ellipsis, 1, 0...] ?? hidden, mixed?[.ellipsis, 2, 0...] ?? hidden) + : (mixed?[.ellipsis, 0, 0...] ?? hidden, mixed?[.ellipsis, 0, 0...] ?? hidden, mixed?[.ellipsis, 0, 0...] ?? hidden) + if let messages, let queryGate, let keyGate, let valueGate { + q = queryGate(q, message: messages[.ellipsis, 0, 0...]) + k = keyGate(k, message: messages[.ellipsis, 1, 0...]) + v = valueGate(v, message: messages[.ellipsis, 2, 0...]) + } + if let queryNorm, let keyNorm, let valueNorm { + return Inkling2AttentionInputs(query: queryNorm(q).asType(dtype), key: keyNorm(k).asType(dtype), value: valueNorm(v).asType(dtype)) + } + let norm = inputNorm! + return Inkling2AttentionInputs(query: norm(q).asType(dtype), key: norm(k).asType(dtype), value: norm(v).asType(dtype)) + } +} diff --git a/Sources/BasaltInference/Models/Inkling2/Inkling2Layers.swift b/Sources/BasaltInference/Models/Inkling2/Inkling2Layers.swift new file mode 100644 index 00000000..ef391be3 --- /dev/null +++ b/Sources/BasaltInference/Models/Inkling2/Inkling2Layers.swift @@ -0,0 +1,112 @@ +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +final class Inkling2Router: Module { + let topK: Int + let routeScale: Float + var weight: MLXArray + @ParameterInfo(key: "e_score_correction_bias") var correction: MLXArray + + init(_ config: Inkling2Configuration) { + (topK, routeScale) = (config.expertsPerToken, config.routeScale) + weight = MLXArray.zeros([config.experts, config.hiddenSize], dtype: .float32) + _correction.wrappedValue = MLXArray.zeros([config.experts], dtype: .float32) + } + + func callAsFunction(_ x: MLXArray) -> (MLXArray, MLXArray) { + let scores = sigmoid(matmul(x.asType(.float32), weight.asType(.float32).transposed())) + let biased = scores + correction.asType(.float32) + let indices = argPartition(-biased, kth: topK - 1, axis: -1)[.ellipsis, .. MLXArray { + var input = expandedDimensions(x, axes: [-2, -3]) + let sorts = indices.size >= 64 + var order = indices + var inverse: MLXArray? + if sorts { (input, order, inverse) = gatherSort(x: input, indices: indices) } + let gateUpOut = gateUp(input, order, sortedIndices: sorts) + let activated = Inkling2Ops.softcappedSwiGLU( + gateUpOut[.ellipsis, .stride(by: 2)], gateUpOut[.ellipsis, .stride(from: 1, by: 2)], gateCap: gateCap, upCap: upCap) + var out = down(activated, order, sortedIndices: sorts) + if let inverse { out = scatterUnsort(x: out, invOrder: inverse, shape: indices.shape) } + return out.squeezed(axis: -2) + } +} + +final class Inkling2SparseMoE: Module { + @ModuleInfo(key: "gate") var router: Inkling2Router + @ModuleInfo(key: "experts") var experts: Inkling2Experts + + init(_ config: Inkling2Configuration) { + _router.wrappedValue = Inkling2Router(config) + _experts.wrappedValue = Inkling2Experts(config) + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + let (indices, weights) = router(x) + let out = experts(x, indices: indices).asType(.float32) * weights.expandedDimensions(axis: -1) + return out.sum(axis: -2).asType(x.dtype) + } +} + +final class Inkling2Query: Module { + var query: MLXArray + + init(rows: Int, dims: Int) { + query = MLXArray.zeros([rows, dims], dtype: .float32) + } + + func callAsFunction(_ blocks: MLXArray, _ partial: MLXArray) -> MLXArray { + Inkling2Ops.depthAttention(blocks, partial, query: query.reshaped(-1, partial.dim(-1))) + } +} + +final class Inkling2MessageGate: Module { + @ModuleInfo(key: "down_proj") var downProj: Linear + @ModuleInfo(key: "forget_gate_proj") var forgetProj: Linear + @ModuleInfo(key: "message_gate_proj") var messageProj: Linear + + init(dims: Int, rank: Int) { + _downProj.wrappedValue = Linear(2 * dims, rank, bias: false) + _forgetProj.wrappedValue = Linear(rank, dims, bias: false) + _messageProj.wrappedValue = Linear(rank, dims, bias: false) + } + + func callAsFunction(_ hidden: MLXArray, message: MLXArray) -> MLXArray { + let joined = concatenated([Inkling2Ops.unitRMS(hidden), Inkling2Ops.unitRMS(message)], axis: -1) + let reduced = downProj(joined.asType(downProj.weight.dtype)).asType(.float32) + let forget = tanh(forgetProj(reduced)) + let gain = tanh(messageProj(reduced)) + return (1 - forget) * hidden.asType(.float32) + gain * message.asType(.float32) + } +} + +final class Inkling2MessageInput: Module { + var query: MLXArray + + init(looped: Int, dims: Int) { + query = MLXArray.zeros([looped, 4, dims], dtype: .float32) + } + + func callAsFunction(_ bank: (blocks: MLXArray, partial: MLXArray), layer: Int) -> MLXArray { + Inkling2Ops.depthAttention(bank.blocks, bank.partial, query: query[layer]) + } +} diff --git a/Sources/BasaltInference/Models/Inkling2/Inkling2Model.swift b/Sources/BasaltInference/Models/Inkling2/Inkling2Model.swift new file mode 100644 index 00000000..3676860a --- /dev/null +++ b/Sources/BasaltInference/Models/Inkling2/Inkling2Model.swift @@ -0,0 +1,113 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +final class Inkling2TextModel: Module { + let config: Inkling2Configuration + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + @ModuleInfo(key: "embed_norm") var embedNorm: RMSNorm + @ModuleInfo(key: "layers") var layers: [Inkling2DecoderLayer] + @ModuleInfo(key: "final_input") var finalInput: Inkling2Query + @ModuleInfo(key: "norm") var norm: RMSNorm + @ModuleInfo(key: "message_input") var messageInput: Inkling2MessageInput? + + init(_ config: Inkling2Configuration) { + self.config = config + _embedTokens.wrappedValue = Embedding(embeddingCount: config.vocabSize, dimensions: config.hiddenSize) + _embedNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + _layers.wrappedValue = (0 ..< config.layers).map { Inkling2DecoderLayer(config, index: $0) } + _finalInput.wrappedValue = Inkling2Query(rows: 1, dims: config.hiddenSize) + _norm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + if let loop = config.loop { + _messageInput.wrappedValue = Inkling2MessageInput(looped: loop.coreEnd - loop.coreStart, dims: config.hiddenSize) + } + } + + func callAsFunction(_ tokens: MLXArray, cache: [KVCache]?) -> MLXArray { + let embedded = embedNorm(embedTokens(tokens)) + var visit = 0 + func run(_ range: Range, _ hidden: MLXArray, _ blocks: MLXArray?, bank: (blocks: MLXArray, partial: MLXArray)?) -> (MLXArray, MLXArray?) { + var (h, b) = (hidden, blocks) + for (offset, index) in range.enumerated() { + let messages = bank.flatMap { bank in messageInput.map { $0(bank, layer: offset) } } + let attentionCache = cache?[2 * visit] + let convCache = cache?[2 * visit + 1] as? ArraysCache + (h, b) = layers[index](h, blocks: b, cache: attentionCache, conv: convCache, messages: messages) + visit += 1 + } + return (h, b) + } + var (hidden, blocks): (MLXArray, MLXArray?) + if let loop = config.loop { + let prelude = run(0 ..< loop.coreStart, embedded, nil, bank: nil) + (hidden, blocks) = prelude + for pass in 0 ..< loop.numPasses { + var bank: (blocks: MLXArray, partial: MLXArray)? + if pass > 0, let current = blocks { + let skip = (prelude.1?.dim(0) ?? 0) + 1 + bank = (current[skip...], Inkling2Ops.unitRMS(hidden)) + (hidden, blocks) = prelude + } + (hidden, blocks) = run(loop.coreStart ..< loop.coreEnd, hidden, blocks, bank: bank) + } + (hidden, blocks) = run(loop.coreEnd ..< config.layers, hidden, blocks, bank: nil) + } else { + (hidden, blocks) = run(0 ..< config.layers, embedded, nil, bank: nil) + } + let readout = finalInput(blocks!, Inkling2Ops.unitRMS(hidden))[.ellipsis, 0, 0...] + return norm(readout).asType(embedded.dtype) + } +} + +final class Inkling2Inner: Module { + @ModuleInfo(key: "language_model") var languageModel: Inkling2TextModel + + init(_ config: Inkling2Configuration) { + _languageModel.wrappedValue = Inkling2TextModel(config) + } +} + +public final class Inkling2Model: Module, LLMModel, LoRAModel { + public static let modelTypes = ["inkling2_loop", "inkling2"] + + public let vocabularySize: Int + let config: Inkling2Configuration + @ModuleInfo(key: "model") var model: Inkling2Inner + @ModuleInfo(key: "lm_head") var lmHead: Linear + + init(_ config: Inkling2Configuration) { + self.config = config + vocabularySize = config.unpaddedVocabSize + _model.wrappedValue = Inkling2Inner(config) + _lmHead.wrappedValue = Linear(config.hiddenSize, config.vocabSize, bias: false) + } + + public convenience init(configurationData data: Data) throws { + self.init(try JSONDecoder().decode(Inkling2Configuration.self, from: data).validated()) + } + + public var loraLayers: [Module] { model.languageModel.layers } + + public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { + let hidden = model.languageModel(inputs, cache: cache) + let logits = lmHead(hidden).asType(.float32) + let capped = tanh(logits / config.finalLogitSoftcap) * config.finalLogitSoftcap + return capped[.ellipsis, .. [any KVCache] { + let local = Set(config.localLayers) + return config.visitOrder.flatMap { index -> [any KVCache] in + let attention: any KVCache = local.contains(index) ? Inkling2WindowKVCache(window: config.slidingWindow) : KVCacheSimple() + return [attention, ArraysCache(size: 4)] + } + } + + public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + let mapped = Inkling2Checkpoint.sanitized(weights, config: config) + FlintModel.quantizeModulesMatchingPackedWeights(in: self, weights: mapped) + return mapped + } +} diff --git a/Sources/BasaltInference/Models/Inkling2/Inkling2Primitives.swift b/Sources/BasaltInference/Models/Inkling2/Inkling2Primitives.swift new file mode 100644 index 00000000..561f75cc --- /dev/null +++ b/Sources/BasaltInference/Models/Inkling2/Inkling2Primitives.swift @@ -0,0 +1,92 @@ +import Foundation +import MLX +import MLXNN + +enum Inkling2Ops { + static func unitRMS(_ x: MLXArray, eps: Float = 1e-6) -> MLXArray { + let states = x.asType(.float32) + return states * rsqrt((states * states).mean(axis: -1, keepDims: true) + eps) + } + + static func l2Clip(_ x: MLXArray, scale: MLXArray?, threshold: Float) -> MLXArray { + var states = x.asType(.float32) + if let scale { states = states * scale.asType(.float32) } + let norm = sqrt((states * states).sum(axis: -1, keepDims: true)) + return (states * minimum(threshold / (norm + 1e-6), 1)).asType(x.dtype) + } + + static func softcappedSwiGLU(_ gate: MLXArray, _ up: MLXArray, gateCap: Float, upCap: Float) -> MLXArray { + let g = gate.asType(.float32) + let u = up.asType(.float32) + return (tanh(g / gateCap) * gateCap * sigmoid(g) * (tanh(u / upCap) * upCap)).asType(gate.dtype) + } + + static func depthAttention(_ blocks: MLXArray, _ partial: MLXArray, query: MLXArray) -> MLXArray { + let stacked = concatenated([blocks, partial.expandedDimensions(axis: 0)], axis: 0) + let sources = stacked.movedAxis(source: 0, destination: -2) + let scale = 1 / Float(partial.dim(-1)).squareRoot() + let weights = softmax(matmul(sources, query.asType(.float32).transposed()) * scale, axis: -2, precise: true) + return matmul(weights.swappedAxes(-1, -2), sources) + } + + static func convWindow(_ x: MLXArray, state: MLXArray?, kernel: Int) -> MLXArray { + let states = x.asType(.float32) + let previous = state ?? MLXArray.zeros([states.dim(0), kernel - 1, states.dim(-1)], dtype: .float32) + return concatenated([previous.asType(.float32), states], axis: 1) + } + + static func convState(_ window: MLXArray, kernel: Int) -> MLXArray { + let length = window.dim(1) + return window[0..., (length - (kernel - 1))..., 0...] + 0 + } +} + +final class Inkling2DepthwiseWeight: Module { + var weight: MLXArray + + init(dims: Int, kernel: Int) { + weight = MLXArray.zeros([dims, kernel, 1]) + } +} + +final class Inkling2ShortConvolution: Module { + let kernel: Int + @ModuleInfo(key: "conv1d") var conv: Inkling2DepthwiseWeight + + init(dims: Int, kernel: Int) { + self.kernel = kernel + _conv.wrappedValue = Inkling2DepthwiseWeight(dims: dims, kernel: kernel) + } + + func callAsFunction(_ x: MLXArray, state: MLXArray?) -> (MLXArray, MLXArray) { + Inkling2Ops.shortConvolution(x, weight: conv.weight, state: state, kernel: kernel) + } +} + +extension Inkling2Ops { + static func shortConvolution(_ x: MLXArray, weight: MLXArray, state: MLXArray?, kernel: Int) -> (MLXArray, MLXArray) { + let length = x.dim(1) + let window = convWindow(x, state: state, kernel: kernel) + let taps = weight[0..., 0..., 0].asType(.float32) + var out = MLXArray.zeros(like: x.asType(.float32)) + for k in 0 ..< kernel { + out = out + window[0..., k ..< (k + length), 0...] * taps[0..., k] + } + let mixed = (out.asType(weight.dtype).asType(.float32) + x.asType(.float32)) / Float(kernel + 1).squareRoot() + return (mixed.asType(x.dtype), window) + } + + static func dynamicConvolution( + _ x: MLXArray, dynamic: MLXArray, staticWeight: MLXArray, heads: Int, state: MLXArray?, kernel: Int + ) -> (MLXArray, MLXArray) { + let (batch, length, channels) = (x.dim(0), x.dim(1), x.dim(2)) + let weights = staticWeight.asType(.float32).transposed().reshaped(heads, -1, kernel) + + dynamic.asType(.float32).reshaped(batch, length, heads, 1, kernel) + let window = convWindow(x, state: state, kernel: kernel) + let lags = (0 ..< kernel).map { lag in window[0..., (kernel - 1 - lag) ..< (kernel - 1 - lag + length), 0...] } + let windows = stacked(lags, axis: -1).reshaped(batch, length, heads, -1, kernel) + let out = (windows * weights).sum(axis: -1).reshaped(batch, length, channels) + let mixed = (out + x.asType(.float32)) / Float(2 * kernel + 1).squareRoot() + return (mixed.asType(x.dtype), window) + } +} diff --git a/Sources/BasaltInference/Models/Inkling2/Inkling2WindowKVCache.swift b/Sources/BasaltInference/Models/Inkling2/Inkling2WindowKVCache.swift new file mode 100644 index 00000000..46f270b4 --- /dev/null +++ b/Sources/BasaltInference/Models/Inkling2/Inkling2WindowKVCache.swift @@ -0,0 +1,83 @@ +import Foundation +import MLX +import MLXLMCommon + +final class Inkling2WindowKVCache: KVCache { + let window: Int + private var keys: MLXArray? + private var values: MLXArray? + private(set) var offset = 0 + private(set) var firstPosition = 0 + + init(window: Int) { + self.window = window + } + + var maxSize: Int? { window } + var isTrimmable: Bool { true } + + func innerState() -> [MLXArray] { [keys, values].compactMap { $0 } } + + var state: [MLXArray] { + get { [keys, values].compactMap { $0 } } + set { + guard newValue.count == 2 else { (keys, values) = (nil, nil); return } + (keys, values) = (newValue[0], newValue[1]) + firstPosition = offset - newValue[0].dim(2) + } + } + + var metaState: [String] { + get { [String(offset), String(firstPosition)] } + set { + guard newValue.count == 2, let stored = Int(newValue[0]), let first = Int(newValue[1]) else { return } + (offset, firstPosition) = (stored, first) + } + } + + func update(keys newKeys: MLXArray, values newValues: MLXArray) -> (MLXArray, MLXArray) { + let length = newKeys.dim(2) + if let keys, let values { + self.keys = concatenated([keys, newKeys], axis: 2) + self.values = concatenated([values, newValues], axis: 2) + } else { + (keys, values) = (newKeys, newValues) + } + offset += length + let held = self.keys!.dim(2) + let needed = window - 1 + length + let start = max(0, held - needed) + let visibleKeys = self.keys![0..., 0..., start..., 0...] + let visibleValues = self.values![0..., 0..., start..., 0...] + let keyStart = firstPosition + start + if held > 2 * window + length { + let keep = max(0, held - (window - 1)) + self.keys = self.keys![0..., 0..., keep..., 0...] + 0 + self.values = self.values![0..., 0..., keep..., 0...] + 0 + firstPosition += keep + } + lastKeyStart = keyStart + return (visibleKeys, visibleValues) + } + + private(set) var lastKeyStart = 0 + + func trim(_ n: Int) -> Int { + guard let keys, let values else { return 0 } + let removable = min(n, keys.dim(2)) + self.keys = keys[0..., 0..., ..<(keys.dim(2) - removable), 0...] + self.values = values[0..., 0..., ..<(values.dim(2) - removable), 0...] + offset -= removable + return removable + } + + func makeMask(n: Int, windowSize: Int?, returnArray: Bool) -> MLXFast.ScaledDotProductAttentionMaskMode { + n > 1 ? .causal : .none + } + + func copy() -> any KVCache { + let copied = Inkling2WindowKVCache(window: window) + (copied.keys, copied.values, copied.offset, copied.firstPosition) = (keys, values, offset, firstPosition) + return copied + } +} diff --git a/Tests/BasaltTests/FeatureMatrixTests.swift b/Tests/BasaltTests/FeatureMatrixTests.swift index 7ae59ad5..64e13d8b 100644 --- a/Tests/BasaltTests/FeatureMatrixTests.swift +++ b/Tests/BasaltTests/FeatureMatrixTests.swift @@ -16,7 +16,7 @@ struct FeatureMatrixTests { case .mtp: [.qwen35, .prism].contains(family) case .cacheBlend: [.qwen3, .qwen3HeadDim32].contains(family) case .kvZones, .headSplit, .headSplitZoned: family == .qwen3HeadDim32 - case .quest: ![.gemma4, .gemma4Moe, .gemma4KEqV, .gemma4Unified, .flint].contains(family) + case .quest: ![.gemma4, .gemma4Moe, .gemma4KEqV, .gemma4Unified, .flint, .inkling2Loop].contains(family) case .kvSharedRow: family == .gemma4KEqV } } @@ -118,7 +118,7 @@ struct FeatureMatrixTests { } @Test("Four concurrent requests decoded in one batch each get their solo greedy text, sliding-window families included (#319, #255)", - .timeLimit(.minutes(1)), arguments: families) + .timeLimit(.minutes(1)), arguments: families.filter { $0 != .inkling2Loop }) func batchedDecodeMatchesSolo(family: TinyModel.Family) async throws { let expected = try await BatchedRoutingTests.solo(4, family: family) let engine = await BatchFixture.engine(try TinyModel.make(family), id: "tiny-\(family)", batchSlots: 4) diff --git a/Tests/BasaltTests/Fixtures/TinyModels.swift b/Tests/BasaltTests/Fixtures/TinyModels.swift index bc092d01..c98fb1e9 100644 --- a/Tests/BasaltTests/Fixtures/TinyModels.swift +++ b/Tests/BasaltTests/Fixtures/TinyModels.swift @@ -8,7 +8,7 @@ import MLXVLM enum TinyModel { enum Family: String, CaseIterable, Sendable { - case qwen3Small, qwen3, qwen3HeadDim32, qwen35, qwen35Moe, gemma3, gemma4, gemma4Moe, gemma4KEqV, gemma4Unified, qwen3Moe, sigmoidMoe, nemotronH, lfm2, lfm2Moe, prism, paddleOCR, deepSeekOCR, deepSeekOCR2, flint, ricursive, museGlimmer, museGlimmerText, ltxVideo, kandinskyCrossDiT, moeVideoDiT + case qwen3Small, qwen3, qwen3HeadDim32, qwen35, qwen35Moe, gemma3, gemma4, gemma4Moe, gemma4KEqV, gemma4Unified, inkling2Loop, qwen3Moe, sigmoidMoe, nemotronH, lfm2, lfm2Moe, prism, paddleOCR, deepSeekOCR, deepSeekOCR2, flint, ricursive, museGlimmer, museGlimmerText, ltxVideo, kandinskyCrossDiT, moeVideoDiT func model(_ config: Data) throws -> any LanguageModel { let decoder = JSONDecoder.json5() @@ -26,7 +26,7 @@ enum TinyModel { case .ricursive: RicursiveModel(try decoder.decode(RicursiveConfiguration.self, from: config).validated()) case .museGlimmerText: MuseGlimmerTextModel(try MuseGlimmerTextConfiguration.decodeFlexible(from: config)) case .ltxVideo, .kandinskyCrossDiT, .moeVideoDiT: try videoModel(config, decoder: decoder) - case .gemma4Unified, .paddleOCR, .deepSeekOCR, .deepSeekOCR2, .museGlimmer: try multimodalModel(config, decoder: decoder) + case .gemma4Unified, .paddleOCR, .deepSeekOCR, .deepSeekOCR2, .museGlimmer, .inkling2Loop: try multimodalModel(config, decoder: decoder) } } @@ -39,6 +39,7 @@ enum TinyModel { private func multimodalModel(_ config: Data, decoder: JSONDecoder) throws -> any LanguageModel { if self == .gemma4Unified { return try TinyGemma4Unified.model(config) } + if self == .inkling2Loop { return try Inkling2Model(configurationData: config) } if self == .paddleOCR { return PaddleOCRVL(try decoder.decode(PaddleOCRVLConfiguration.self, from: config)) } if self == .deepSeekOCR { return DeepSeekOCR(try decoder.decode(DeepSeekOCRConfiguration.self, from: config).validated()) } if self == .museGlimmer { return MuseGlimmerVLM(try decoder.decode(MuseGlimmerConfiguration.self, from: config)) } @@ -54,6 +55,7 @@ enum TinyModel { case .gemma4, .gemma4Moe, .qwen3Moe, .sigmoidMoe: 228 case .gemma4Unified: 274 case .gemma4KEqV: 645 + case .inkling2Loop: 650 case .nemotronH: 30 case .lfm2: 97 case .lfm2Moe: 83 @@ -73,7 +75,7 @@ enum TinyModel { var weightScale: Float { switch self { case .qwen3Small, .gemma3: 4 - case .qwen3, .qwen3HeadDim32, .gemma4, .gemma4Moe, .gemma4KEqV, .gemma4Unified, .qwen35, .qwen35Moe, .qwen3Moe, .sigmoidMoe, .nemotronH, .lfm2, .lfm2Moe, .prism, .paddleOCR, .deepSeekOCR, .deepSeekOCR2, .flint, .ricursive, .museGlimmer, .museGlimmerText, .ltxVideo, .kandinskyCrossDiT, .moeVideoDiT: 1 + case .qwen3, .qwen3HeadDim32, .gemma4, .gemma4Moe, .gemma4KEqV, .gemma4Unified, .inkling2Loop, .qwen35, .qwen35Moe, .qwen3Moe, .sigmoidMoe, .nemotronH, .lfm2, .lfm2Moe, .prism, .paddleOCR, .deepSeekOCR, .deepSeekOCR2, .flint, .ricursive, .museGlimmer, .museGlimmerText, .ltxVideo, .kandinskyCrossDiT, .moeVideoDiT: 1 } } @@ -109,6 +111,16 @@ enum TinyModel { "vocab_size_per_layer_input": 256, "sliding_window": \(slidingWindow), "sliding_window_pattern": 2, "use_double_wide_mlp": false, "rms_norm_eps": 1e-6} """ + case .inkling2Loop: """ + {"model_type": "inkling2_loop", "text_config": {"model_type": "inkling2_loop_text", "hidden_size": 64, "num_hidden_layers": 6, + "vocab_size": 272, "unpadded_vocab_size": 256, "num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 16, + "d_rel": 4, "rel_extent": 8, "log_scaling_n_floor": 4, "log_scaling_alpha": 0.1, "rms_norm_eps": 1e-6, + "qk_l2_clip_threshold": 22.627416997969522, "rel_l2_clip_threshold": 8.0, "local_layer_ids": [0, 2, 4], + "sconv_kernel_size": 4, "final_logit_softcapping": 30.0, "sliding_window_size": 8, "n_layers_per_attn_res_block": 2, + "n_routed_experts": 8, "num_experts_per_tok": 2, "n_shared_experts": 0, "intermediate_size": 32, + "mlp_gate_softcap": 4.0, "mlp_up_softcap": 25.0, "route_scale": 8.0, + "loop_config": {"core_start": 2, "core_end": 4, "num_passes": 3, "gate_rank": 8, "is_varloop": false}}} + """ case .gemma4KEqV: """ {"model_type": "gemma4_text", "hidden_size": 64, "num_hidden_layers": 4, "intermediate_size": 128, "num_attention_heads": 4, "num_key_value_heads": 2, "num_global_key_value_heads": 1, "head_dim": 16, @@ -266,6 +278,11 @@ enum TinyModel { $0.0.hasSuffix(".gate.weight") || $0.0.hasSuffix(".expert_bias") || $0.0.hasSuffix(".softmax_offset") } model.update(parameters: ModuleParameters.unflattened(specialized.map { ($0.0, MLXRandom.normal($0.1.shape) * 0.25) })) + } else if family == .inkling2Loop { + let zeroed = model.parameters().flattened().filter { key, _ in + [".query", ".proj", ".static_weight", "conv1d.weight", ".gate.weight", ".e_score_correction_bias"].contains { key.hasSuffix($0) } + } + model.update(parameters: ModuleParameters.unflattened(zeroed.map { ($0.0, MLXRandom.normal($0.1.shape) * 0.25) })) } else if family == .ricursive { let lambdas = model.parameters().flattened().filter { $0.0.hasSuffix(".value_res_lambda") } model.update(parameters: ModuleParameters.unflattened(lambdas.map { ($0.0, MLXRandom.normal($0.1.shape) * 0.5) })) diff --git a/Tests/BasaltTests/Inkling2ModelTests.swift b/Tests/BasaltTests/Inkling2ModelTests.swift new file mode 100644 index 00000000..66acf32a --- /dev/null +++ b/Tests/BasaltTests/Inkling2ModelTests.swift @@ -0,0 +1,149 @@ +import Foundation +import MLX +import MLXLMCommon +import MLXNN +import Testing +@testable import BasaltCore +@testable import BasaltInference + +@Suite("Inkling 2 P1: looped text stack on the inkling2Loop TinyModel (#650)", .serialized) +struct Inkling2ModelTests { + static let tokens: [Int32] = [5, 19, 42, 7, 88, 13, 64, 21, 9, 31, 200, 3, 3, 150, 77, 12, 44, 101, 6, 250] + + static func model() throws -> Inkling2Model { + try #require(try TinyModel.make(.inkling2Loop) as? Inkling2Model) + } + + @Test("Two cache slots per layer visit: prelude 2 + core 2 × 3 passes + coda 2 = 10 visits, windowed caches on local layers") + func cacheLayout() throws { + let model = try Self.model() + let caches = try model.newCache(parameters: nil) + #expect(caches.count == 20) + #expect(model.config.visitOrder == [0, 1, 2, 3, 2, 3, 2, 3, 4, 5]) + #expect(caches.enumerated().filter { $0.offset.isMultiple(of: 2) }.map { $0.element is Inkling2WindowKVCache } == [true, false, true, false, true, false, true, false, true, false]) + #expect(caches.enumerated().filter { !$0.offset.isMultiple(of: 2) }.allSatisfy { $0.element is ArraysCache }) + } + + @Test("Token-by-token decode through the caches gives the full-sequence logits at every position, past the 8-token window", arguments: [1, 4, 7]) + func decodeMatchesFullForward(chunk: Int) throws { + let model = try Self.model() + let full = model(MLXArray(Self.tokens)[.newAxis], cache: nil).asType(.float32) + let caches = try model.newCache(parameters: nil) + var steps: [MLXArray] = [] + var start = 0 + while start < Self.tokens.count { + let end = min(Self.tokens.count, start + chunk) + steps.append(model(MLXArray(Array(Self.tokens[start ..< end]))[.newAxis], cache: caches).asType(.float32)) + start = end + } + let stepped = concatenated(steps, axis: 1) + let gap = abs(stepped - full).max().item(Float.self) + #expect(stepped.shape == [1, Self.tokens.count, 256]) + #expect(gap <= 2e-3, "max logit gap \(gap)") + } + + @Test("The loop matters: one pass gives different logits than three, and passes 2 and 3 read messages") + func loopChangesOutput() throws { + let model = try Self.model() + let three = model(MLXArray(Self.tokens)[.newAxis], cache: nil) + var single = model.config + single.loop = Inkling2Configuration.Loop(coreStart: 2, coreEnd: 4, numPasses: 1, gateRank: 8) + let onePass = Inkling2Model(single) + onePass.update(parameters: model.parameters()) + let one = onePass(MLXArray(Self.tokens)[.newAxis], cache: nil) + #expect(abs(three - one).max().item(Float.self) > 1e-3) + } + + @Test("The oQ pack layout (fused projections, packed loop controllers) maps back to the same parameters") + func oqLayoutRoundTrip() throws { + let model = try Self.model() + let params = Dictionary(uniqueKeysWithValues: model.parameters().flattened()) + let packed = Inkling2OQFixture.pack(params, config: model.config) + #expect(packed.keys.contains("model.layers.0.attn.in_proj.weight") && packed.keys.contains("model.layers.2.loop_down")) + let restored = Inkling2Checkpoint.sanitized(packed, config: model.config) + #expect(Set(restored.keys) == Set(params.keys)) + for (key, value) in params { + let back = try #require(restored[key], "\(key)") + #expect(back.shape == value.shape && abs(back - value).max().item(Float.self) == 0, "\(key)") + } + } + + @Test("The window cache keeps at least window − 1 earlier tokens, reports where its keys start, and trims") + func windowCache() { + let cache = Inkling2WindowKVCache(window: 4) + var lastStart = 0 + for step in 0 ..< 12 { + let k = MLXArray.ones([1, 1, 1, 2]) * Float(step) + let (keys, _) = cache.update(keys: k, values: k) + lastStart = cache.lastKeyStart + #expect(keys.dim(2) == min(step + 1, 4)) + #expect(keys[0, 0, -1, 0].item(Float.self) == Float(step)) + #expect(keys[0, 0, 0, 0].item(Float.self) == Float(lastStart)) + } + #expect(cache.offset == 12 && lastStart == 8) + #expect(cache.trim(2) == 2 && cache.offset == 10) + } +} + +enum Inkling2OQFixture { + static func pack(_ params: [String: MLXArray], config: Inkling2Configuration) -> [String: MLXArray] { + let text = Inkling2Checkpoint.text + var out: [String: MLXArray] = [:] + var used = Set() + func take(_ key: String) -> MLXArray { used.insert(key); return params[key]! } + for index in 0 ..< config.layers { + let pre = text + "layers.\(index)." + let attention = pre + "self_attn." + let oq = "model.layers.\(index)." + let global = !config.localLayers.contains(index) + if global { + out[oq + "attn.q_proj.weight"] = concatenated(["q_proj", "r_proj", "gate_proj", "sink_proj"].map { take(attention + $0 + ".weight") }) + out[oq + "attn.k_proj.weight"] = concatenated([take(attention + "k_proj.weight"), take(attention + "k_sconv.weight_proj.weight")]) + out[oq + "attn.v_proj.weight"] = concatenated([take(attention + "v_proj.weight"), take(attention + "v_sconv.weight_proj.weight")]) + } else { + out[oq + "attn.in_proj.weight"] = concatenated(["q_proj", "k_proj", "v_proj", "r_proj", "gate_proj", "sink_proj"].map { take(attention + $0 + ".weight") }) + out[oq + "attn.k_conv"] = take(attention + "k_sconv.conv1d.weight").squeezed(axis: -1) + out[oq + "attn.v_conv"] = take(attention + "v_sconv.conv1d.weight").squeezed(axis: -1) + } + if config.loop.map({ ($0.coreStart ..< $0.coreEnd).contains(index) }) == true { + let gates = Inkling2Checkpoint.messageGates + out[oq + "loop_down"] = stacked(gates.map { gate in + let down = take(pre + gate + "_message_gate.down_proj.weight") + return down.reshaped(down.dim(0), 2, -1).transposed(1, 2, 0) + }) + out[oq + "loop_gain_forget"] = stacked(gates.map { gate in + concatenated([take(pre + gate + "_message_gate.message_gate_proj.weight").transposed(), + take(pre + gate + "_message_gate.forget_gate_proj.weight").transposed()], axis: 1) + }) + out[oq + "loop_message.query"] = take(text + "message_input.query")[index - config.loop!.coreStart] + } + for (from, to) in [("post_attention_convolution.conv1d.weight", "attn_conv"), ("post_mlp_convolution.conv1d.weight", "mlp_conv")] { + out[oq + to] = take(pre + from).squeezed(axis: -1) + } + } + let renames: [(String, String)] = [ + ("attention_input.query", "attn_input.query"), ("input_layernorm.weight", "attn_norm.weight"), + ("post_attention_layernorm.weight", "mlp_norm.weight"), ("self_attn.q_l2_clip.scale", "attn.q_scale"), + ("self_attn.rel_l2_clip.scale", "attn.r_scale"), ("self_attn.rel_logits_proj.proj", "attn.rel_proj"), + ("self_attn.k_sconv.static_weight", "attn.k_static"), ("self_attn.v_sconv.static_weight", "attn.v_static"), + ("mlp.gate.weight", "mlp.router_weight"), ("mlp.gate.e_score_correction_bias", "mlp.router_bias"), + ("mlp.experts.gate_up_proj.weight", "mlp.experts.w13.weight"), ("mlp.experts.down_proj.weight", "mlp.experts.w2.weight"), + ("self_attn.o_proj.weight", "attn.o_proj.weight"), ("q_input_layernorm.weight", "q_input_norm.weight"), + ("k_input_layernorm.weight", "k_input_norm.weight"), ("v_input_layernorm.weight", "v_input_norm.weight"), + ] + for (key, value) in params where !used.contains(key) { + if key == text + "embed_tokens.weight" { out["model.embed.weight"] = value; continue } + if key == "lm_head.weight" { out[key] = value; continue } + if key.hasPrefix(text + "layers.") { + let rest = key.dropFirst((text + "layers.").count) + let index = rest.prefix { $0 != "." } + let name = String(rest.dropFirst(index.count + 1)) + let mapped = renames.first { $0.0 == name }?.1 ?? name + out["model.layers.\(index).\(mapped)"] = value + } else { + out["model." + key.dropFirst(text.count)] = value + } + } + return out + } +} From d0378de77c2bd56a44f5284c554d939501ca2f44 Mon Sep 17 00:00:00 2001 From: Aleksei Boklag <146362331+goodmai@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:31:39 +0100 Subject: [PATCH 2/2] fix(inkling): verify prompt-cache reuse, lookup planning and grammar jump-forward for inkling2 Every known family must verify the base capabilities GenerationPlanTests checks; prompt-cache reuse is covered by the fixture suites, lookup is still refused at runtime by PromptLookupTokenIterator.supports for these caches, and KV quantization stays off. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012cicguZMN3jhNGmf5327oh --- Sources/BasaltInference/ModelCapabilities.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/BasaltInference/ModelCapabilities.swift b/Sources/BasaltInference/ModelCapabilities.swift index 62d0e526..02982503 100644 --- a/Sources/BasaltInference/ModelCapabilities.swift +++ b/Sources/BasaltInference/ModelCapabilities.swift @@ -110,7 +110,7 @@ struct ModelCapabilities: Equatable, Sendable { (["gemma4", "gemma4_text", "gemma4_unified", "gemma4_unified_text"], gemma4), ([FlintModel.modelType], flint), (["falcon_h1", "falcon-h1"], falconH1), - (Inkling2Model.modelTypes, ModelCapabilities(verified: [])), + (Inkling2Model.modelTypes, ModelCapabilities(verified: [.speculativeLookup, .promptCacheReuse, .grammarJumpForward])), ([PaddleOCRVL.modelType], ModelCapabilities(verified: all.subtracting([.mtp, .cacheBlend, .kvQuantization, .kvZones, .kvHeadSplit, .quest]))), ([DeepSeekOCR.modelType, DeepSeekOCR2.modelType], ModelCapabilities(verified: all.subtracting([.mtp, .cacheBlend, .kvQuantization, .kvZones, .kvHeadSplit, .quest]))), ]