Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat(inkling): Inkling 2 Mini P1 — looped text stack in plain MLX ops…
…, oQ/mlx-lm weight layouts, TinyModel (#650)

- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012cicguZMN3jhNGmf5327oh
  • Loading branch information
goodmai and claude committed Nov 22, 2026
commit 729cfecb1b19a8fd9b8ae9bc2a140aef7c69542d
2 changes: 1 addition & 1 deletion Sources/BasaltInference/HybridPrefixSnapshot.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 4 additions & 0 deletions Sources/BasaltInference/MLXInferenceEngine+Loading.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand Down
1 change: 1 addition & 0 deletions Sources/BasaltInference/ModelCapabilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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]))),
]
Expand Down
154 changes: 154 additions & 0 deletions Sources/BasaltInference/Models/Inkling2/Inkling2Attention.swift
Original file line number Diff line number Diff line change
@@ -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, ..<keysCount]
let out = matmul(weights.asType(v.dtype), v.expandedDimensions(axis: 2))
return out.reshaped(batch, heads, length, headDim).transposed(0, 2, 1, 3)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import Foundation
import MLX

enum Inkling2Checkpoint {
static let text = "model.language_model."
static let quantParts = ["weight", "scales", "biases"]
static let messageGates = ["q", "k", "v", "mlp"]

static func sanitized(_ weights: [String: MLXArray], config: Inkling2Configuration) -> [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[..<dot]), String(name[name.index(after: dot)...]))
}

static func rows(_ value: MLXArray, _ part: String, _ pieces: [(String, Int)], prefix: String, into out: inout [String: MLXArray]) {
var start = 0
for (name, count) in pieces {
out[prefix + name + "." + part] = value[start ..< (start + count)]
start += count
}
}

static func loopDown(_ value: MLXArray, prefix: String, into out: inout [String: MLXArray]) {
let rank = value.dim(-1)
for (slot, gate) in messageGates.enumerated() {
out[prefix + gate + "_message_gate.down_proj.weight"] = value[slot].transposed(2, 0, 1).reshaped(rank, -1)
}
}

static func loopGainForget(_ value: MLXArray, prefix: String, into out: inout [String: MLXArray]) {
let dims = value.dim(-1) / 2
for (slot, gate) in messageGates.enumerated() {
out[prefix + gate + "_message_gate.message_gate_proj.weight"] = value[slot][0..., ..<dims].transposed()
out[prefix + gate + "_message_gate.forget_gate_proj.weight"] = value[slot][0..., dims...].transposed()
}
}
}
Loading
Loading