Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
18 changes: 12 additions & 6 deletions Libraries/MLXLLM/LLMModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,26 @@ extension LLMModel {

/// Default prepare step for ``LLMModel``.
///
/// This will evaluate the prompt in chunks until there is a small number of
/// tokens left to feed into the `TokenIterator`.
/// Matches Python mlx-lm's `generate_step` prefill loop: process every
/// prompt token except the LAST one through chunked prefill (with
/// `eval(cache)` + `clearCache()` between chunks). The trailing token is
/// returned to the iterator's "primes the pump" call.
public func prepare(_ input: LMInput, cache: [KVCache], windowSize: Int?) throws
-> PrepareResult
{
let prefillStepSize = windowSize ?? 512
var y = input.text

// Prepare the prompt in chunks if larger than the prefill size
while y.tokens.size > prefillStepSize {
let input = y[.newAxis, ..<prefillStepSize]
// Prepare the prompt in chunks, leaving exactly 1 token for the iterator.
while y.tokens.size > 1 {
let chunkSize = min(prefillStepSize, y.tokens.size - 1)
let input = y[.newAxis, ..<chunkSize]
_ = self(input, cache: cache.isEmpty ? nil : cache, state: nil)
eval(cache)
y = y[prefillStepSize...]
y = y[chunkSize...]
// Free intermediate activation buffers between chunks to reduce memory pressure,
// matching Python mlx-lm's mx.clear_cache() after each prefill chunk.
MLX.Memory.clearCache()
}

return .tokens(y)
Expand Down
2 changes: 1 addition & 1 deletion Libraries/MLXLLM/Models/FalconH1.swift
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ class FalconH1Mixer: Module {
let paddedInput = concatenated([convState, convInput], axis: 1)

if let cache = cache {
cache[0] = paddedInput[0..., (-(convKernelSize - 1))...]
cache[0] = paddedInput[0..., (-(convKernelSize - 1))...].contiguous()
}

let convOutput = conv1d(paddedInput)
Expand Down
8 changes: 5 additions & 3 deletions Libraries/MLXLLM/Models/Gemma3nText.swift
Original file line number Diff line number Diff line change
Expand Up @@ -801,7 +801,9 @@ public class Gemma3nLanguageModel: Module {
h = inputsEmbeds
} else if let inputs {
h = embedTokens(inputs)
h = (h * MLXArray(_embedTokensScale, dtype: .float32)).asType(h.dtype)
// Use bare Float scalar to avoid fp32 promotion. The explicit
// .float32 + .asType round-trip adds 2 needless AsType dispatches.
h = h * _embedTokensScale
} else {
fatalError("Either inputs or inputsEmbeds must be provided")
}
Expand Down Expand Up @@ -915,8 +917,8 @@ public class Gemma3nLanguageModel: Module {
)
let tokens = MLX.where(perLayerInputsMask, inputIds, MLXArray.zeros(like: inputIds))
var result = embedTokensPerLayer(tokens)
result = (result * MLXArray(_embedTokensPerLayerScale, dtype: .float32)).asType(
result.dtype)
// Use bare Float scalar to avoid fp32 promotion (see Gemma3n PLE fix).
result = result * _embedTokensPerLayerScale
result = result.reshaped(
Array(inputIds.shape) + [config.numHiddenLayers, config.hiddenSizePerLayerInput]
)
Expand Down
2 changes: 1 addition & 1 deletion Libraries/MLXLLM/Models/GraniteMoeHybrid.swift
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ class GraniteMoeHybridMamba2Mixer: Module {
if let cache {
let end = padded.dim(1)
let start = max(0, end - (convKernelSize - 1))
cache[0] = padded[0..., start ..< end, 0...]
cache[0] = padded[0..., start ..< end, 0...].contiguous()
}

let convOutput = conv1d(padded)
Expand Down
2 changes: 1 addition & 1 deletion Libraries/MLXLLM/Models/Jamba.swift
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ class JambaMambaMixer: Module {
}

let convOut = conv1d(xFull)
let newConvState = xFull[0..., (1 - K)..., 0...]
let newConvState = xFull[0..., (1 - K)..., 0...].contiguous()
x = silu(convOut)

let A = -exp(A_Log)
Expand Down
2 changes: 1 addition & 1 deletion Libraries/MLXLLM/Models/LFM2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ class LFM2ShortConv: Module {

Bx = concatenated([state!, Bx], axis: -2)
if let cache {
cache[0] = Bx[0..., (Bx.dim(1) - (lCache - 1))..., 0...]
cache[0] = Bx[0..., (Bx.dim(1) - (lCache - 1))..., 0...].contiguous()
}

let convOut = conv(Bx)
Expand Down
2 changes: 1 addition & 1 deletion Libraries/MLXLLM/Models/LFM2MoE.swift
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ class LFM2MoEShortConv: Module {
Bx = concatenated([state!, Bx], axis: -2)
if let cache {
let start = Bx.dim(1) - (lCache - 1)
cache[0] = Bx[0..., start..., 0...]
cache[0] = Bx[0..., start..., 0...].contiguous()
}

let convOut = conv(Bx)
Expand Down
16 changes: 11 additions & 5 deletions Libraries/MLXLLM/Models/NemotronH.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,8 @@ private class NemotronHRMSNormGated: Module {
let unflattened = states.reshaped(newShape)

// Python: x = mx.fast.rms_norm(x, weight=None, eps=self.eps)
// Apply RMS norm per group WITHOUT scaling (pass ones as weight)
// Swift rmsNorm doesn't accept nil, so we use identity weight
let identityWeight = MLXArray.ones([groupSize])
let normed = MLXFast.rmsNorm(unflattened, weight: identityWeight, eps: eps)
// Apply RMS norm per group WITHOUT scaling
let normed = MLXFast.rmsNorm(unflattened, weight: MLXArray.mlxNone, eps: eps)

// Python: return self.weight * x.flatten(-2)
// Flatten back to [..., hidden] and apply learned weight
Expand Down Expand Up @@ -180,7 +178,7 @@ private class NemotronHMamba2Mixer: Module, NemotronHMixer {
if let cache {
let end = padded.dim(1)
let start = max(0, end - (convKernelSize - 1))
cache[0] = padded[0..., start ..< end, 0...]
cache[0] = padded[0..., start ..< end, 0...].contiguous()
}

let convOutput = conv1d(padded)
Expand Down Expand Up @@ -675,6 +673,7 @@ private class NemotronHBackbone: Module {
}()

// Track which cache to use for each layer
let isPrefill = hidden.dim(1) > 1
var cacheCounter = 0
for layer in layers {
let c: KVCache?
Expand All @@ -686,6 +685,13 @@ private class NemotronHBackbone: Module {
}

hidden = layer(hidden, attentionMask: attentionMask, ssmMask: ssmMask, cache: c)

// During prefill, eval after each layer to free activation buffers.
// Without this, the lazy graph spans all layers and peak memory scales
// with model depth × sequence length.
if isPrefill, let c {
eval(hidden, c)
}
}

return normF(hidden)
Expand Down
2 changes: 1 addition & 1 deletion Libraries/MLXLLM/Models/Qwen3Next.swift
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ public final class Qwen3NextGatedDeltaNet: Module {

let convInput = concatenated([convState, mixedQKV], axis: 1)
if let cache {
cache[0] = convInput[0..., (1 - convKernelSize)..., 0...]
cache[0] = convInput[0..., (1 - convKernelSize)..., 0...].contiguous()
}

let convOut = silu(conv1d(convInput))
Expand Down
4 changes: 3 additions & 1 deletion Libraries/MLXLLM/Models/SSM.swift
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,12 @@ public func segsum(_ x: MLXArray, mask: MLXArray? = nil) -> MLXArray {
var xSegsum = MLX.cumsum(x, axis: -2)

if let mask = mask {
// Match xSegsum dtype to avoid fp32 promotion.
// A/B tested: bf16 segsum produces identical output to fp32 at 128-1024 context.
xSegsum = which(
mask[.ellipsis, .newAxis, 0...] * mask[.ellipsis, .newAxis],
xSegsum,
MLXArray(-Float.infinity)
MLXArray(Float(-Float.infinity), dtype: xSegsum.dtype)
)
}

Expand Down