From 566df4277bf1e4c8815e7b41e3e1a93cfb79cdc1 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler <5055076+jonathan308@users.noreply.github.com> Date: Tue, 22 Sep 2026 00:20:33 -0700 Subject: [PATCH 01/16] feat(diffusiongemma): add native block generation, media and sampling --- .../HuggingFaceIntegrationMacros.swift | 9 +- .../MLXLLM/Models/DiffusionGemmaBlocks.swift | 233 ++++++ .../Models/DiffusionGemmaConfiguration.swift | 252 ++++++ .../DiffusionGemmaExpertReduction.swift | 63 ++ .../Models/DiffusionGemmaPagedGeometry.swift | 16 + .../DiffusionGemmaPersistentPrefix.swift | 138 ++++ .../Models/DiffusionGemmaPrefixCache.swift | 216 +++++ .../Models/DiffusionGemmaRequestCache.swift | 152 ++++ .../Models/DiffusionGemmaSoftEmbedding.swift | 104 +++ ...ffusionGemmaSoftEmbeddingDiagnostics.swift | 36 + .../Models/DiffusionGemmaTextModel.swift | 257 ++++++ .../Models/DiffusionGemmaWindowOrder.swift | 27 + .../ContinuousBatchingV2/CBv2Contracts.swift | 7 + .../CBv2DeadlineLeases.swift | 15 + .../NativeBlockCheckpointImport.swift | 224 +++++ .../NativeBlockCheckpointLease.swift | 20 + .../NativeBlockCheckpointMetadata.swift | 78 ++ .../NativeBlockContracts.swift | 75 ++ .../NativeBlockEngine.swift | 771 ++++++++++++++++++ .../NativeBlockPagedExecution.swift | 27 + .../NativeBlockPagedMemory.swift | 105 +++ .../NativeBlockPrefixCache.swift | 20 + .../NativeBlockTextDecoder.swift | 78 ++ .../Prefix/CompleteCheckpointContract.swift | 23 +- .../CompleteCheckpointManifestCoding.swift | 28 +- .../CompleteCheckpointManifestMemory.swift | 18 +- .../DiffusionGemmaCompiledSampler.swift | 135 +++ ...iffusionGemmaGenerationConfiguration.swift | 209 +++++ .../DiffusionGemmaPrefillGeometry.swift | 74 ++ .../MLXLMCommon/DiffusionGemmaSampler.swift | 254 ++++++ ...DiffusionGemmaTokenizerConfiguration.swift | 68 ++ .../SwiftJinjaSyntaxCompatibility.swift | 20 + .../Tool/GemmaToolFrameScanner.swift | 38 + .../Tool/Parsers/GemmaFunctionParser.swift | 38 +- .../MLXLMCommon/Tool/ToolCallFormat.swift | 2 +- .../MLXLMCommon/Tool/ToolCallProcessor.swift | 25 +- .../MLXLMServer/Protocol/OpenAIProtocol.swift | 30 + .../Runtime/ToolStreamHandler.swift | 4 +- .../MLXVLM/DiffusionGemmaBicubicRGB.swift | 94 +++ Libraries/MLXVLM/DiffusionGemmaEngine.swift | 422 ++++++++++ .../MLXVLM/DiffusionGemmaGeneration.swift | 66 ++ .../DiffusionGemmaGenerationSession.swift | 359 ++++++++ .../MLXVLM/DiffusionGemmaImagePixels.swift | 63 ++ .../MLXVLM/DiffusionGemmaMediaGeometry.swift | 54 ++ .../MLXVLM/DiffusionGemmaMediaInput.swift | 16 + .../MLXVLM/DiffusionGemmaModelFactory.swift | 129 +++ .../DiffusionGemmaPrefixPersistence.swift | 77 ++ .../MLXVLM/DiffusionGemmaProcessor.swift | 113 +++ ...DiffusionGemmaProcessorConfiguration.swift | 47 ++ .../DiffusionGemmaResidentPrefixCache.swift | 197 +++++ .../MLXVLM/DiffusionGemmaVideoFrames.swift | 84 ++ .../DiffusionGemmaVisionPreparation.swift | 48 ++ .../DiffusionGemmaVisualEmbeddings.swift | 103 +++ Libraries/MLXVLM/Models/DiffusionGemma.swift | 305 +++++++ .../Models/DiffusionGemmaVisionMath.swift | 37 + Libraries/MLXVLM/Models/Gemma4.swift | 186 ++++- Package.swift | 19 +- .../GemmaFunctionConstraintParserTests.swift | 36 + .../OpenAIResponsesMediaTests.swift | 62 ++ .../OpenAIToolHistoryDecodingTests.swift | 23 + .../DiffusionGemmaBicubicRGBTests.swift | 85 ++ .../DiffusionGemmaBlockOracleTests.swift | 140 ++++ .../DiffusionGemmaConfigurationTests.swift | 94 +++ .../DiffusionGemmaExpertReductionTests.swift | 230 ++++++ .../DiffusionGemmaFactoryTests.swift | 384 +++++++++ .../DiffusionGemmaFullTraceTests.swift | 94 +++ ...ionGemmaGenerationConfigurationTests.swift | 85 ++ .../DiffusionGemmaMediaGeometryTests.swift | 52 ++ .../DiffusionGemmaMediaPrefixLiveTests.swift | 101 +++ .../DiffusionGemmaMediaPrefixTests.swift | 168 ++++ .../DiffusionGemmaNativeSamplerTests.swift | 101 +++ .../DiffusionGemmaNoiseBindingTests.swift | 51 ++ ...ffusionGemmaPagedAttentionProbeTests.swift | 120 +++ .../DiffusionGemmaPagedEngineTests.swift | 94 +++ .../DiffusionGemmaPagedLiveTests.swift | 118 +++ .../DiffusionGemmaPagedStateTests.swift | 315 +++++++ .../DiffusionGemmaPersistentEngineTests.swift | 168 ++++ .../DiffusionGemmaPersistentLiveTests.swift | 140 ++++ .../DiffusionGemmaPersistentMediaTests.swift | 111 +++ .../DiffusionGemmaPersistentPrefixTests.swift | 141 ++++ .../DiffusionGemmaProcessorTests.swift | 139 ++++ .../DiffusionGemmaResidentPrefixTests.swift | 186 +++++ .../DiffusionGemmaSamplerTests.swift | 110 +++ .../DiffusionGemmaSoftEmbeddingTests.swift | 112 +++ ...usionGemmaTemplateCompatibilityTests.swift | 23 + ...DiffusionGemmaTextConfigurationTests.swift | 94 +++ .../DiffusionGemmaTextOracleTests.swift | 246 ++++++ .../DiffusionGemmaTokenizerLiveTests.swift | 38 + .../DiffusionGemmaTokenizerTests.swift | 78 ++ .../DiffusionGemmaVisionOracleTests.swift | 195 +++++ .../NativeBlockCheckpointMetadataTests.swift | 99 +++ .../MLXLMTests/NativeBlockDeadlineTests.swift | 176 ++++ Tests/MLXLMTests/NativeBlockEngineTests.swift | 305 +++++++ .../NativeBlockPagedMemoryTests.swift | 179 ++++ .../MLXLMTests/NativeDiffusionLiveTests.swift | 264 ++++++ .../diffusiongemma-block-oracle.json | 105 +++ .../diffusiongemma-block-oracle.safetensors | Bin 0 -> 140748 bytes ...usiongemma-chunked-text-oracle.safetensors | Bin 0 -> 16869 bytes .../diffusiongemma-legacy-vision.safetensors | Bin 0 -> 3544 bytes .../diffusiongemma-media-geometry.json | 327 ++++++++ .../Resources/diffusiongemma-root-config.json | 134 +++ .../Resources/diffusiongemma-text-config.json | 72 ++ .../Resources/diffusiongemma-text-oracle.json | 53 ++ .../diffusiongemma-text-oracle.safetensors | Bin 0 -> 193980 bytes .../diffusiongemma-video-types-oracle.json | 98 +++ ...fusiongemma-video-types-oracle.safetensors | Bin 0 -> 167764 bytes .../diffusiongemma-vision-bf-oracle.json | 123 +++ ...iffusiongemma-vision-bf-oracle.safetensors | Bin 0 -> 194896 bytes .../diffusiongemma-vision-oracle.json | 122 +++ .../diffusiongemma-vision-oracle.safetensors | Bin 0 -> 357072 bytes docs/diffusiongemma/LICENSE-MLX-VLM | 21 + docs/diffusiongemma/LICENSE-PILLOW | 30 + .../implementation-references.md | 194 +++++ docs/diffusiongemma/native-sampling.md | 47 ++ 114 files changed, 12724 insertions(+), 67 deletions(-) create mode 100644 Libraries/MLXLLM/Models/DiffusionGemmaBlocks.swift create mode 100644 Libraries/MLXLLM/Models/DiffusionGemmaConfiguration.swift create mode 100644 Libraries/MLXLLM/Models/DiffusionGemmaExpertReduction.swift create mode 100644 Libraries/MLXLLM/Models/DiffusionGemmaPagedGeometry.swift create mode 100644 Libraries/MLXLLM/Models/DiffusionGemmaPersistentPrefix.swift create mode 100644 Libraries/MLXLLM/Models/DiffusionGemmaPrefixCache.swift create mode 100644 Libraries/MLXLLM/Models/DiffusionGemmaRequestCache.swift create mode 100644 Libraries/MLXLLM/Models/DiffusionGemmaSoftEmbedding.swift create mode 100644 Libraries/MLXLLM/Models/DiffusionGemmaSoftEmbeddingDiagnostics.swift create mode 100644 Libraries/MLXLLM/Models/DiffusionGemmaTextModel.swift create mode 100644 Libraries/MLXLLM/Models/DiffusionGemmaWindowOrder.swift create mode 100644 Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockCheckpointImport.swift create mode 100644 Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockCheckpointLease.swift create mode 100644 Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockCheckpointMetadata.swift create mode 100644 Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockContracts.swift create mode 100644 Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockEngine.swift create mode 100644 Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockPagedExecution.swift create mode 100644 Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockPagedMemory.swift create mode 100644 Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockPrefixCache.swift create mode 100644 Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockTextDecoder.swift create mode 100644 Libraries/MLXLMCommon/DiffusionGemmaCompiledSampler.swift create mode 100644 Libraries/MLXLMCommon/DiffusionGemmaGenerationConfiguration.swift create mode 100644 Libraries/MLXLMCommon/DiffusionGemmaPrefillGeometry.swift create mode 100644 Libraries/MLXLMCommon/DiffusionGemmaSampler.swift create mode 100644 Libraries/MLXLMCommon/DiffusionGemmaTokenizerConfiguration.swift create mode 100644 Libraries/MLXLMCommon/SwiftJinjaSyntaxCompatibility.swift create mode 100644 Libraries/MLXLMCommon/Tool/GemmaToolFrameScanner.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaBicubicRGB.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaEngine.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaGeneration.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaGenerationSession.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaImagePixels.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaMediaGeometry.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaMediaInput.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaModelFactory.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaPrefixPersistence.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaProcessor.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaProcessorConfiguration.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaResidentPrefixCache.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaVideoFrames.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaVisionPreparation.swift create mode 100644 Libraries/MLXVLM/DiffusionGemmaVisualEmbeddings.swift create mode 100644 Libraries/MLXVLM/Models/DiffusionGemma.swift create mode 100644 Libraries/MLXVLM/Models/DiffusionGemmaVisionMath.swift create mode 100644 Tests/MLXLMServerTests/OpenAIResponsesMediaTests.swift create mode 100644 Tests/MLXLMServerTests/OpenAIToolHistoryDecodingTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaBicubicRGBTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaBlockOracleTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaConfigurationTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaExpertReductionTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaFactoryTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaFullTraceTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaGenerationConfigurationTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaMediaGeometryTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaMediaPrefixLiveTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaMediaPrefixTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaNativeSamplerTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaNoiseBindingTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaPagedAttentionProbeTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaPagedEngineTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaPagedLiveTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaPagedStateTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaPersistentEngineTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaPersistentLiveTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaPersistentMediaTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaPersistentPrefixTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaProcessorTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaResidentPrefixTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaSamplerTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaSoftEmbeddingTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaTemplateCompatibilityTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaTextConfigurationTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaTextOracleTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaTokenizerLiveTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaTokenizerTests.swift create mode 100644 Tests/MLXLMTests/DiffusionGemmaVisionOracleTests.swift create mode 100644 Tests/MLXLMTests/NativeBlockCheckpointMetadataTests.swift create mode 100644 Tests/MLXLMTests/NativeBlockDeadlineTests.swift create mode 100644 Tests/MLXLMTests/NativeBlockEngineTests.swift create mode 100644 Tests/MLXLMTests/NativeBlockPagedMemoryTests.swift create mode 100644 Tests/MLXLMTests/NativeDiffusionLiveTests.swift create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-block-oracle.json create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-block-oracle.safetensors create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-chunked-text-oracle.safetensors create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-legacy-vision.safetensors create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-media-geometry.json create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-root-config.json create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-text-config.json create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-text-oracle.json create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-text-oracle.safetensors create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-video-types-oracle.json create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-video-types-oracle.safetensors create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-vision-bf-oracle.json create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-vision-bf-oracle.safetensors create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-vision-oracle.json create mode 100644 Tests/MLXLMTests/Resources/diffusiongemma-vision-oracle.safetensors create mode 100644 docs/diffusiongemma/LICENSE-MLX-VLM create mode 100644 docs/diffusiongemma/LICENSE-PILLOW create mode 100644 docs/diffusiongemma/implementation-references.md create mode 100644 docs/diffusiongemma/native-sampling.md diff --git a/Libraries/MLXHuggingFaceMacros/HuggingFaceIntegrationMacros.swift b/Libraries/MLXHuggingFaceMacros/HuggingFaceIntegrationMacros.swift index 0d46f2305b..09f5983262 100644 --- a/Libraries/MLXHuggingFaceMacros/HuggingFaceIntegrationMacros.swift +++ b/Libraries/MLXHuggingFaceMacros/HuggingFaceIntegrationMacros.swift @@ -177,7 +177,14 @@ public struct TokenizerLoaderMacro: ExpressionMacro { // // import Tokenizers // - let upstream = try await Tokenizers.AutoTokenizer.from(modelFolder: directory) + let upstream: any Tokenizers.Tokenizer + if let inputs = try MLXLMCommon.DiffusionGemmaTokenizerConfiguration.load(from: directory) { + upstream = try Tokenizers.PreTrainedTokenizer( + tokenizerConfig: .init(inputs.configurationDictionary()), + tokenizerData: .init(inputs.dataDictionary())) + } else { + upstream = try await Tokenizers.AutoTokenizer.from(modelFolder: directory) + } return #adaptHuggingFaceTokenizer(upstream) } } diff --git a/Libraries/MLXLLM/Models/DiffusionGemmaBlocks.swift b/Libraries/MLXLLM/Models/DiffusionGemmaBlocks.swift new file mode 100644 index 0000000000..5a152ab47f --- /dev/null +++ b/Libraries/MLXLLM/Models/DiffusionGemmaBlocks.swift @@ -0,0 +1,233 @@ +// Adapted from MLX-VLM e79b0e041677ec4ca5333ba750376bb4e8c434cb, +// mlx_vlm/models/diffusion_gemma/language.py. +// Copyright © 2025 Prince Canuma. MIT license: docs/diffusiongemma/LICENSE-MLX-VLM. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +private let diffusionGemmaGEGLU: @Sendable (MLXArray, MLXArray) -> MLXArray = { + let body: @Sendable (MLXArray, MLXArray) -> MLXArray = { gate, up in + MLXNN.geluApproximate(gate) * up + } + return MLXHardwareInfo.isCompiledDecodeSupported ? compile(shapeless: true, body) : body +}() + +final class DiffusionGemmaRMSNormNoScale: Module { + let epsilon: Float + init(_ epsilon: Float) { + self.epsilon = epsilon + super.init() + } + func callAsFunction(_ x: MLXArray) -> MLXArray { + MLXFast.rmsNorm(x, weight: .mlxNone, eps: epsilon) + } +} + +final class DiffusionGemmaDenseMLP: Module { + @ModuleInfo(key: "gate_proj") var gate: Linear + @ModuleInfo(key: "up_proj") var up: Linear + @ModuleInfo(key: "down_proj") var down: Linear + init(_ config: DiffusionGemmaTextConfiguration) { + _gate.wrappedValue = Linear(config.hiddenSize, config.intermediateSize, bias: false) + _up.wrappedValue = Linear(config.hiddenSize, config.intermediateSize, bias: false) + _down.wrappedValue = Linear(config.intermediateSize, config.hiddenSize, bias: false) + } + func callAsFunction(_ x: MLXArray) -> MLXArray { down(diffusionGemmaGEGLU(gate(x), up(x))) } +} + +final class DiffusionGemmaRouter: Module { + @ModuleInfo var proj: Linear + @ModuleInfo var scale: MLXArray + @ModuleInfo(key: "per_expert_scale") var perExpertScale: MLXArray + let epsilon: Float + let rootSize: Float + let topK: Int + init(_ config: DiffusionGemmaTextConfiguration) { + _proj.wrappedValue = Linear(config.hiddenSize, config.expertCount, bias: false) + _scale.wrappedValue = .ones([config.hiddenSize]) + _perExpertScale.wrappedValue = .ones([config.expertCount]) + epsilon = config.rmsNormEpsilon + rootSize = pow(Float(config.hiddenSize), -0.5) + topK = config.topKExperts + } + func callAsFunction(_ x: MLXArray) -> (indices: MLXArray, weights: MLXArray) { + let normalized = MLXFast.rmsNorm(x, weight: .mlxNone, eps: epsilon) + let scores = proj(normalized * scale * rootSize) + let indices = argPartition(scores, kth: -topK, axis: -1)[.ellipsis, (-topK)...] + let selected = takeAlong(scores, indices, axis: -1) + let weights = softmax(selected, axis: -1, precise: true) * perExpertScale[indices] + return (indices, weights) + } +} + +final class DiffusionGemmaExperts: Module { + @ModuleInfo(key: "gate_up_proj") var gateUp: SwitchLinear + @ModuleInfo(key: "down_proj") var down: SwitchLinear + let intermediateSize: Int + init(_ config: DiffusionGemmaTextConfiguration) { + intermediateSize = config.moeIntermediateSize + _gateUp.wrappedValue = SwitchLinear( + inputDims: config.hiddenSize, + outputDims: 2 * config.moeIntermediateSize, numExperts: config.expertCount, bias: false) + _down.wrappedValue = SwitchLinear( + inputDims: config.moeIntermediateSize, + outputDims: config.hiddenSize, numExperts: config.expertCount, bias: false) + } + func callAsFunction(_ inputs: MLXArray, indices: MLXArray, weights: MLXArray) -> MLXArray { + var x = expandedDimensions(inputs, axes: [-2, -3]) + let sorted = indices.size >= 64 + var expertIndices = indices + var inverse: MLXArray? + if sorted { + let gathered = gatherSort(x: x, indices: indices) + (x, expertIndices, inverse) = (gathered.0, gathered.1, gathered.2) + } + let projected = gateUp(x, expertIndices, sortedIndices: sorted) + let gate = projected[.ellipsis, .. (MLXArray, MLXArray) + ) -> MLXArray { + let (batch, length) = (x.dim(0), x.dim(1)) + var q = queryNorm(query(x).reshaped(batch, length, heads, headDimension)).transposed( + 0, 2, 1, 3) + q = rope(q, offset: position) + let rawKeys = key(x).reshaped(batch, length, kvHeads, headDimension) + let rawValues = + value.map { $0(x).reshaped(batch, length, kvHeads, headDimension) } ?? rawKeys + let k = rope(keyNorm(rawKeys).transposed(0, 2, 1, 3), offset: position) + let v = valueNorm(rawValues).transposed(0, 2, 1, 3) + let (allKeys, allValues) = keyValues(k, v) + let attended = MLXFast.scaledDotProductAttention( + queries: q, keys: allKeys, values: allValues, scale: 1, mask: mask) + return output(attended.transposed(0, 2, 1, 3).reshaped(batch, length, -1)) + } +} + +/// Shared-weight text block with distinct encoder and denoiser learned scalars. +/// There is no autoregressive PLE or cross-layer KV sharing. +public final class DiffusionGemmaTextBlock: Module { + @ModuleInfo(key: "self_attn") var attention: DiffusionGemmaAttention + @ModuleInfo var mlp: DiffusionGemmaDenseMLP + @ModuleInfo var router: DiffusionGemmaRouter + @ModuleInfo var experts: DiffusionGemmaExperts + @ModuleInfo(key: "input_layernorm") var inputNorm: RMSNorm + @ModuleInfo(key: "post_attention_layernorm") var postAttentionNorm: RMSNorm + @ModuleInfo(key: "pre_feedforward_layernorm") var preFFN: RMSNorm + @ModuleInfo(key: "post_feedforward_layernorm") var postFFN: RMSNorm + @ModuleInfo(key: "post_feedforward_layernorm_1") var denseNorm: RMSNorm + @ModuleInfo(key: "pre_feedforward_layernorm_2") var preExpertNorm: RMSNorm + @ModuleInfo(key: "post_feedforward_layernorm_2") var expertNorm: RMSNorm + @ModuleInfo(key: "layer_scalar") var layerScalar: MLXArray + + public init(_ config: DiffusionGemmaTextConfiguration, layer: Int) { + precondition(config.layerTypes.indices.contains(layer)) + _attention.wrappedValue = DiffusionGemmaAttention(config, layer: layer) + _mlp.wrappedValue = DiffusionGemmaDenseMLP(config) + _router.wrappedValue = DiffusionGemmaRouter(config) + _experts.wrappedValue = DiffusionGemmaExperts(config) + _inputNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEpsilon) + _postAttentionNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEpsilon) + _preFFN.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEpsilon) + _postFFN.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEpsilon) + _denseNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEpsilon) + _preExpertNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEpsilon) + _expertNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEpsilon) + _layerScalar.wrappedValue = .ones([1]) + } + + public func callAsFunction( + _ x: MLXArray, position: Int, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + encoderScalar: MLXArray? = nil, + keyValues: (MLXArray, MLXArray) -> (MLXArray, MLXArray) + ) -> MLXArray { + let attended = attention(inputNorm(x), position: position, mask: mask, keyValues: keyValues) + let residual = x + postAttentionNorm(attended) + let dense = denseNorm(mlp(preFFN(residual))) + let flat = residual.reshaped(-1, residual.dim(-1)) + let routed = router(flat) + let expert = experts(preExpertNorm(flat), indices: routed.indices, weights: routed.weights) + .reshaped(residual.shape) + let combined = postFFN(dense + expertNorm(expert)) + return (residual + combined) * (encoderScalar ?? layerScalar) + } +} + +public final class DiffusionGemmaSelfConditioning: Module { + @ModuleInfo(key: "pre_norm") var preNorm: RMSNorm + @ModuleInfo(key: "post_norm") var postNorm: DiffusionGemmaRMSNormNoScale + @ModuleInfo(key: "gate_proj") var gate: Linear + @ModuleInfo(key: "up_proj") var up: Linear + @ModuleInfo(key: "down_proj") var down: Linear + public init(_ config: DiffusionGemmaTextConfiguration) { + _preNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEpsilon) + _postNorm.wrappedValue = DiffusionGemmaRMSNormNoScale(config.rmsNormEpsilon) + _gate.wrappedValue = Linear(config.hiddenSize, config.intermediateSize, bias: false) + _up.wrappedValue = Linear(config.hiddenSize, config.intermediateSize, bias: false) + _down.wrappedValue = Linear(config.intermediateSize, config.hiddenSize, bias: false) + } + public func callAsFunction(_ embeddings: MLXArray, softEmbeddings: MLXArray) -> MLXArray { + let normalized = preNorm(softEmbeddings) + return postNorm(embeddings + down(diffusionGemmaGEGLU(gate(normalized), up(normalized)))) + } +} diff --git a/Libraries/MLXLLM/Models/DiffusionGemmaConfiguration.swift b/Libraries/MLXLLM/Models/DiffusionGemmaConfiguration.swift new file mode 100644 index 0000000000..963c9e6116 --- /dev/null +++ b/Libraries/MLXLLM/Models/DiffusionGemmaConfiguration.swift @@ -0,0 +1,252 @@ +// Native DiffusionGemma text geometry; not an alias of autoregressive Gemma4. +// Reference: Transformers c587bc884db2c2e31fc2b8102314656b17aa07b1. +// See docs/diffusiongemma/implementation-references.md. + +import Foundation + +public struct DiffusionGemmaTextConfiguration: Codable, Sendable, Equatable { + public let modelType: String + public let vocabularySize: Int + public let hiddenSize: Int + public let intermediateSize: Int + public let moeIntermediateSize: Int + public let layerCount: Int + public let attentionHeads: Int + public let keyValueHeads: Int + public let globalKeyValueHeads: Int? + public let headDimension: Int + public let globalHeadDimension: Int + public let maxPositionEmbeddings: Int + public let slidingWindow: Int + public let expertCount: Int + public let topKExperts: Int + public let rmsNormEpsilon: Float + public let finalLogitSoftcap: Float + public let hiddenActivation: String + public let attentionBias: Bool + public let attentionDropout: Float + public let tieWordEmbeddings: Bool + public let bidirectionalAttention: String? + public let bosTokenId: Int? + public let padTokenId: Int? + public let dtype: String? + public let initializerRange: Float + public let eosTokenIds: [Int]? + public let layerTypes: [String] + public let ropeParameters: [String: RotaryParameters] + + public struct RotaryParameters: Codable, Sendable, Equatable { + public let type: String + public let theta: Float + public let partialRotaryFactor: Float? + enum CodingKeys: String, CodingKey { + case type = "rope_type" + case theta = "rope_theta" + case partialRotaryFactor = "partial_rotary_factor" + } + public init(type: String, theta: Float, partialRotaryFactor: Float? = nil) { + self.type = type + self.theta = theta + self.partialRotaryFactor = partialRotaryFactor + } + } + + enum CodingKeys: String, CodingKey { + case modelType = "model_type" + case vocabularySize = "vocab_size" + case hiddenSize = "hidden_size" + case intermediateSize = "intermediate_size" + case moeIntermediateSize = "moe_intermediate_size" + case layerCount = "num_hidden_layers" + case attentionHeads = "num_attention_heads" + case keyValueHeads = "num_key_value_heads" + case globalKeyValueHeads = "num_global_key_value_heads" + case headDimension = "head_dim" + case globalHeadDimension = "global_head_dim" + case maxPositionEmbeddings = "max_position_embeddings" + case slidingWindow = "sliding_window" + case expertCount = "num_experts" + case topKExperts = "top_k_experts" + case rmsNormEpsilon = "rms_norm_eps" + case finalLogitSoftcap = "final_logit_softcapping" + case hiddenActivation = "hidden_activation" + case attentionBias = "attention_bias" + case attentionDropout = "attention_dropout" + case tieWordEmbeddings = "tie_word_embeddings" + case bidirectionalAttention = "use_bidirectional_attention" + case bosTokenId = "bos_token_id" + case padTokenId = "pad_token_id" + case dtype = "dtype" + case initializerRange = "initializer_range" + case eosTokenIds = "eos_token_id" + case layerTypes = "layer_types" + case ropeParameters = "rope_parameters" + case perLayerConfiguration = "per_layer_config" + } + + public init(from decoder: Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + // This newer reference feature changes per-layer projection geometry. + // Do not silently load it using only the global dimensions. + if values.contains(.perLayerConfiguration) { + throw DiffusionGemmaConfigurationError.unsupported("per_layer_config") + } + modelType = + try values.decodeIfPresent(String.self, forKey: .modelType) ?? "diffusion_gemma_text" + vocabularySize = try values.decodeIfPresent(Int.self, forKey: .vocabularySize) ?? 262144 + hiddenSize = try values.decode(Int.self, forKey: .hiddenSize) + intermediateSize = try values.decode(Int.self, forKey: .intermediateSize) + moeIntermediateSize = try values.decode(Int.self, forKey: .moeIntermediateSize) + layerCount = try values.decode(Int.self, forKey: .layerCount) + attentionHeads = try values.decode(Int.self, forKey: .attentionHeads) + keyValueHeads = try values.decode(Int.self, forKey: .keyValueHeads) + globalKeyValueHeads = try values.decodeIfPresent(Int.self, forKey: .globalKeyValueHeads) + headDimension = try values.decodeIfPresent(Int.self, forKey: .headDimension) ?? 256 + globalHeadDimension = + try values.decodeIfPresent(Int.self, forKey: .globalHeadDimension) ?? 512 + maxPositionEmbeddings = + try values.decodeIfPresent(Int.self, forKey: .maxPositionEmbeddings) ?? 131072 + slidingWindow = try values.decodeIfPresent(Int.self, forKey: .slidingWindow) ?? 512 + expertCount = try values.decode(Int.self, forKey: .expertCount) + topKExperts = try values.decode(Int.self, forKey: .topKExperts) + rmsNormEpsilon = try values.decodeIfPresent(Float.self, forKey: .rmsNormEpsilon) ?? 1e-6 + finalLogitSoftcap = try values.decodeIfPresent(Float.self, forKey: .finalLogitSoftcap) ?? 30 + hiddenActivation = + try values.decodeIfPresent(String.self, forKey: .hiddenActivation) + ?? "gelu_pytorch_tanh" + attentionBias = try values.decodeIfPresent(Bool.self, forKey: .attentionBias) ?? false + attentionDropout = try values.decodeIfPresent(Float.self, forKey: .attentionDropout) ?? 0 + tieWordEmbeddings = + try values.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true + bidirectionalAttention = try values.decodeIfPresent( + String.self, forKey: .bidirectionalAttention) + bosTokenId = try values.decodeIfPresent(Int.self, forKey: .bosTokenId) + padTokenId = try values.decodeIfPresent(Int.self, forKey: .padTokenId) + dtype = try values.decodeIfPresent(String.self, forKey: .dtype) + initializerRange = try values.decodeIfPresent(Float.self, forKey: .initializerRange) ?? 0.02 + if try !values.contains(.eosTokenIds) || values.decodeNil(forKey: .eosTokenIds) { + eosTokenIds = nil + } else if let token = try? values.decode(Int.self, forKey: .eosTokenIds) { + eosTokenIds = [token] + } else { + eosTokenIds = try values.decode([Int].self, forKey: .eosTokenIds) + } + guard layerCount > 0 else { + throw DiffusionGemmaConfigurationError.invalid("num_hidden_layers") + } + if let declared = try values.decodeIfPresent([String].self, forKey: .layerTypes) { + layerTypes = declared + } else { + let count = layerCount + layerTypes = (0 ..< count).map { index in + (index + 1).isMultiple(of: 6) || index == count - 1 + ? "full_attention" : "sliding_attention" + } + } + ropeParameters = + try values.decodeIfPresent([String: RotaryParameters].self, forKey: .ropeParameters) + ?? [ + "sliding_attention": .init(type: "default", theta: 10000), + "full_attention": .init( + type: "proportional", theta: 1_000_000, partialRotaryFactor: 0.25), + ] + try validate() + } + + public func encode(to encoder: Encoder) throws { + var values = encoder.container(keyedBy: CodingKeys.self) + try values.encode(modelType, forKey: .modelType) + try values.encode(vocabularySize, forKey: .vocabularySize) + try values.encode(hiddenSize, forKey: .hiddenSize) + try values.encode(intermediateSize, forKey: .intermediateSize) + try values.encode(moeIntermediateSize, forKey: .moeIntermediateSize) + try values.encode(layerCount, forKey: .layerCount) + try values.encode(attentionHeads, forKey: .attentionHeads) + try values.encode(keyValueHeads, forKey: .keyValueHeads) + try values.encodeIfPresent(globalKeyValueHeads, forKey: .globalKeyValueHeads) + try values.encode(headDimension, forKey: .headDimension) + try values.encode(globalHeadDimension, forKey: .globalHeadDimension) + try values.encode(maxPositionEmbeddings, forKey: .maxPositionEmbeddings) + try values.encode(slidingWindow, forKey: .slidingWindow) + try values.encode(expertCount, forKey: .expertCount) + try values.encode(topKExperts, forKey: .topKExperts) + try values.encode(rmsNormEpsilon, forKey: .rmsNormEpsilon) + try values.encode(finalLogitSoftcap, forKey: .finalLogitSoftcap) + try values.encode(hiddenActivation, forKey: .hiddenActivation) + try values.encode(attentionBias, forKey: .attentionBias) + try values.encode(attentionDropout, forKey: .attentionDropout) + try values.encode(tieWordEmbeddings, forKey: .tieWordEmbeddings) + try values.encodeIfPresent(bidirectionalAttention, forKey: .bidirectionalAttention) + try values.encodeIfPresent(bosTokenId, forKey: .bosTokenId) + try values.encodeIfPresent(padTokenId, forKey: .padTokenId) + try values.encodeIfPresent(dtype, forKey: .dtype) + try values.encode(initializerRange, forKey: .initializerRange) + try values.encodeIfPresent(eosTokenIds, forKey: .eosTokenIds) + try values.encode(layerTypes, forKey: .layerTypes) + try values.encode(ropeParameters, forKey: .ropeParameters) + } + + private func validate() throws { + guard modelType == "diffusion_gemma_text" else { + throw DiffusionGemmaConfigurationError.unsupported("model_type") + } + for (name, value) in [ + ("vocab_size", vocabularySize), ("hidden_size", hiddenSize), + ("intermediate_size", intermediateSize), ("moe_intermediate_size", moeIntermediateSize), + ("num_attention_heads", attentionHeads), ("num_key_value_heads", keyValueHeads), + ("head_dim", headDimension), ("global_head_dim", globalHeadDimension), + ("max_position_embeddings", maxPositionEmbeddings), ("sliding_window", slidingWindow), + ("num_experts", expertCount), ("top_k_experts", topKExperts), + ] { + guard value > 0 else { throw DiffusionGemmaConfigurationError.invalid(name) } + } + guard vocabularySize <= Int(Int32.max), topKExperts <= expertCount else { + throw DiffusionGemmaConfigurationError.invalid("vocabulary/expert range") + } + let fullHeads = globalKeyValueHeads ?? keyValueHeads + guard fullHeads > 0, attentionHeads.isMultiple(of: keyValueHeads), + attentionHeads.isMultiple(of: fullHeads), + headDimension.isMultiple(of: 2), globalHeadDimension.isMultiple(of: 2) + else { throw DiffusionGemmaConfigurationError.invalid("attention geometry") } + guard layerTypes.count == layerCount, + layerTypes.allSatisfy({ ["sliding_attention", "full_attention"].contains($0) }), + layerTypes.last == "full_attention" + else { throw DiffusionGemmaConfigurationError.invalid("layer_types") } + guard hiddenActivation == "gelu_pytorch_tanh", tieWordEmbeddings else { + throw DiffusionGemmaConfigurationError.unsupported("activation/untied embeddings") + } + guard bidirectionalAttention == nil || bidirectionalAttention == "vision" else { + throw DiffusionGemmaConfigurationError.unsupported("use_bidirectional_attention") + } + guard rmsNormEpsilon.isFinite, rmsNormEpsilon > 0, + finalLogitSoftcap.isFinite, finalLogitSoftcap > 0, + attentionDropout.isFinite, (0 ..< 1).contains(attentionDropout), + initializerRange.isFinite, initializerRange >= 0 + else { + throw DiffusionGemmaConfigurationError.invalid("normalization/dropout/initialization") + } + for (kind, dimension) in [ + ("sliding_attention", headDimension), ("full_attention", globalHeadDimension), + ] { + guard let rope = ropeParameters[kind], rope.theta.isFinite, rope.theta > 0, + rope.type == (kind == "full_attention" ? "proportional" : "default") + else { throw DiffusionGemmaConfigurationError.unsupported("rope_parameters." + kind) } + let fraction = rope.partialRotaryFactor ?? 1 + let rotated = Float(dimension) * fraction + guard fraction.isFinite, fraction > 0, fraction <= 1, + rotated >= 2, rotated.rounded(.towardZero) == rotated, + Int(rotated).isMultiple(of: 2) + else { throw DiffusionGemmaConfigurationError.invalid("partial_rotary_factor") } + } + for token in [bosTokenId, padTokenId].compactMap({ $0 }) + (eosTokenIds ?? []) { + guard token >= 0, token < vocabularySize else { + throw DiffusionGemmaConfigurationError.invalid("special_token_ids") + } + } + } +} + +public enum DiffusionGemmaConfigurationError: Error, Sendable, Equatable { + case invalid(String) + case unsupported(String) +} diff --git a/Libraries/MLXLLM/Models/DiffusionGemmaExpertReduction.swift b/Libraries/MLXLLM/Models/DiffusionGemmaExpertReduction.swift new file mode 100644 index 0000000000..f6ce497274 --- /dev/null +++ b/Libraries/MLXLLM/Models/DiffusionGemmaExpertReduction.swift @@ -0,0 +1,63 @@ +// Native DiffusionGemma expert-output reduction; existing SDK kernel and order. +import Foundation +import MLX +import MLXLMCommon + +enum DiffusionGemmaExpertReduction { + /// Inference default. Explicit false restores the original graph. + /// Latched before inference; never mutate the environment during a request. + static let enabled = enabled( + from: ProcessInfo.processInfo.environment[ + "DARKBLOOM_DIFFUSION_EXPERT_UNSORT"]) + + static func enabled(from value: String?) -> Bool { + guard let value else { return true } + return ["1", "true", "yes", "on"].contains(value.lowercased()) + } + + /// The reused shader computes flattened addresses with uint arithmetic. + /// Keep larger logical tensors on the original 64-bit-aware graph without + /// imposing a smaller model context or constructing a large test buffer. + static func shaderIndexFits(assignmentCount: Int, hidden: Int) -> Bool { + guard assignmentCount > 0, hidden > 0 else { return false } + let (elements, overflow) = assignmentCount.multipliedReportingOverflow(by: hidden) + return !overflow && elements <= Int(UInt32.max) + } + + static func eligible( + _ outputs: MLXArray, inverse: MLXArray?, weights: MLXArray, enabled: Bool + ) -> Bool { + guard enabled, Device.defaultDevice().deviceType == .gpu, + StreamOrDevice.default.stream == Stream.gpu, + outputs.ndim == 3, outputs.dim(1) == 1, outputs.dim(2) == 2816, + shaderIndexFits(assignmentCount: outputs.dim(0), hidden: outputs.dim(2)), + outputs.dtype == .bfloat16, + weights.ndim == 2, weights.dim(1) == 8, weights.size >= 64, + weights.dtype == .bfloat16, outputs.dim(0) == weights.size, + let inverse, inverse.ndim == 1, inverse.dtype == .uint32, + inverse.size == weights.size + else { return false } + return true + } + + static func reduce( + _ outputs: MLXArray, inverse: MLXArray?, indicesShape: [Int], weights: MLXArray, + enabled: Bool + ) -> MLXArray { + if eligible(outputs, inverse: inverse, weights: weights, enabled: enabled), + indicesShape == weights.shape, let inverse + { + return weightedExpertUnsort( + sortedOutputs: outputs.squeezed(axis: -2), inverseOrder: inverse, + weights: weights) + } + // Preserve every legacy operation, including BF16 multiply rounding and + // reduction order, for training, CPU/custom streams and other geometries. + var restored = outputs + if let inverse { + restored = scatterUnsort(x: restored, invOrder: inverse, shape: indicesShape) + } + restored = restored.squeezed(axis: -2) + return (restored * expandedDimensions(weights, axis: -1)).sum(axis: -2) + } +} diff --git a/Libraries/MLXLLM/Models/DiffusionGemmaPagedGeometry.swift b/Libraries/MLXLLM/Models/DiffusionGemmaPagedGeometry.swift new file mode 100644 index 0000000000..cfc9ae44ce --- /dev/null +++ b/Libraries/MLXLLM/Models/DiffusionGemmaPagedGeometry.swift @@ -0,0 +1,16 @@ +import MLXLMCommon + +extension DiffusionGemmaTextConfiguration { + /// Committed encoder storage geometry. Canvas K/V is ephemeral and must + /// never be appended to these rows until the sampler commits a block. + public var diffusionPagedLayerKinds: [CBv2LayerKind] { + layerTypes.enumerated().map { index, kind in + let windowed = kind == "sliding_attention" + return .init( + attention: windowed ? .slidingWindow(slidingWindow) : .full, + headDim: windowed ? headDimension : globalHeadDimension, + kvHeads: windowed ? keyValueHeads : (globalKeyValueHeads ?? keyValueHeads), + queryHeads: attentionHeads, modelLayerIndex: index) + } + } +} diff --git a/Libraries/MLXLLM/Models/DiffusionGemmaPersistentPrefix.swift b/Libraries/MLXLLM/Models/DiffusionGemmaPersistentPrefix.swift new file mode 100644 index 0000000000..1f4de1fcb0 --- /dev/null +++ b/Libraries/MLXLLM/Models/DiffusionGemmaPersistentPrefix.swift @@ -0,0 +1,138 @@ +import Foundation +import MLX +import MLXLMCommon + +/// Immutable validation for a particular loaded model and its verified disk +/// identity. Dtype is an explicit loaded-model contract, not accepted from the +/// incoming manifest. No weights or live model objects are retained here. +public final class DiffusionGemmaPersistentPrefixCodec: @unchecked Sendable { + public let identity: CBv2CompleteCheckpointIdentity + private let configuration: DiffusionGemmaTextConfiguration + private let owner: UUID + private let dtype: CBv2CheckpointDType + private let codecIdentity = UUID() + private let prefillChunkSize: Int? + + init(configuration: DiffusionGemmaTextConfiguration, owner: UUID, + identity: CBv2CompleteCheckpointIdentity, dtype: DType, prefillChunkSize: Int? = nil) throws { + guard let nativeType = CBv2CheckpointDType(dtype), nativeType.isFloatingPoint, + [identity.modelAggregateHash, identity.promptContractID, identity.buildID, identity.numericsFingerprint] + .allSatisfy({ $0.count == 64 && $0.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) } }) + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + self.configuration = configuration; self.owner = owner + self.identity = identity; self.dtype = nativeType + guard prefillChunkSize == nil || (prefillChunkSize! > 0 && prefillChunkSize! <= configuration.maxPositionEmbeddings) + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + self.prefillChunkSize = prefillChunkSize + } + + private func descriptors(position: Int) throws -> [CBv2CheckpointTensorDescriptor] { + try configuration.layerTypes.enumerated().flatMap { index, kind in + let sliding = kind == "sliding_attention" + let heads = sliding ? configuration.keyValueHeads : (configuration.globalKeyValueHeads ?? configuration.keyValueHeads) + let dimension = sliding ? configuration.headDimension : configuration.globalHeadDimension + return try [CBv2CheckpointTensorRole.keys, .values].map { + try CBv2CheckpointTensorDescriptor(role: $0, layer: index, + shape: [1, heads, sliding ? min(position, configuration.slidingWindow) : position, dimension], + dtype: dtype) + } + } + } + + private func validate(_ manifest: CBv2CompleteCheckpointManifest, + prefixIdentity: DiffusionGemmaPrefixIdentity) throws { + _ = try manifest.validateStructure() + guard manifest.backendLayout == CBv2CompleteCheckpointManifest.diffusionBlockLayout, + manifest.identity == identity, + prefixIdentity.artifact == identity.modelAggregateHash, + prefixIdentity.template == identity.promptContractID, + prefixIdentity.numericalProfile == identity.numericsFingerprint + (prefillChunkSize.map { ":prefill-\($0)" } ?? ""), + prefillChunkSize == nil || manifest.chunkSize == prefillChunkSize, + manifest.mediaIdentity == prefixIdentity.mediaIdentity, + prefixIdentity.media == (prefixIdentity.mediaIdentity.map { + "media:" + $0.digest.map { String(format: "%02x", $0) }.joined() + } ?? "text-only"), + manifest.cacheSalt == prefixIdentity.tenantScope, + manifest.position <= configuration.maxPositionEmbeddings, + manifest.prefixTokens.allSatisfy({ $0 < configuration.vocabularySize }), + manifest.tensors == (try descriptors(position: manifest.position)), + let window = manifest.nativeBlockState, + window.windowPhysicalLength <= max(manifest.position, configuration.slidingWindow) + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + if manifest.position < configuration.slidingWindow { + guard window.windowPhysicalLength >= manifest.position, + window.windowCursor == manifest.position + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + } else { + guard window.windowPhysicalLength >= configuration.slidingWindow, + window.windowPhysicalLength == configuration.slidingWindow || window.windowCursor == window.windowPhysicalLength + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + } + } + + /// Donor backing must remain charged by its capture owner through export + /// completion. This adds a separate host-metadata reservation, not a second + /// model or a dense copy of the prefix. + public func export(_ checkpoint: DiffusionGemmaPrefixCheckpoint, chunkSize: Int, + engine: CBv2NativeBlockEngine) throws -> CBv2CompleteCheckpointExport { + guard checkpoint.configuration == configuration, checkpoint.owner == owner, checkpoint.compact else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let manifest = CBv2CompleteCheckpointManifest( + identity: identity, position: checkpoint.tokenCount, chunkSize: chunkSize, + prefixTokens: checkpoint.tokens.map(Int.init), cacheSalt: checkpoint.identity.tenantScope, + assistantCodecID: nil, tensors: try descriptors(position: checkpoint.tokenCount), + backendLayout: CBv2CompleteCheckpointManifest.diffusionBlockLayout, + mediaIdentity: checkpoint.identity.mediaIdentity, + nativeBlockState: .init(windowPhysicalLength: checkpoint.windowOrder.physicalLength, + windowCursor: checkpoint.windowOrder.cursor)) + try validate(manifest, prefixIdentity: checkpoint.identity) + return try .init(nativeBlockManifest: manifest, + arrays: checkpoint.layers.flatMap { [$0.keys, $0.values] }, engine: engine) + } + + /// No GPU allocation before exact artifact/build/numerics/scope/shape/token + /// validation. Chunk size is the requesting engine's actual cold policy. + public func importPlan(_ manifest: CBv2CompleteCheckpointManifest, + prefixIdentity: DiffusionGemmaPrefixIdentity, + promptTokens: [Int], chunkSize: Int, maximumNewTokens: Int = 1, + prefillGeometry: DiffusionGemmaPrefillGeometry? = nil, + engine: CBv2NativeBlockEngine) throws -> CBv2NativeBlockCheckpointImportPlan { + try validate(manifest, prefixIdentity: prefixIdentity) + if prefixIdentity.mediaIdentity != nil { + guard let prefillGeometry, prefillGeometry.promptCount == promptTokens.count, + prefillGeometry.chunkSize == chunkSize, + prefillGeometry.permitsRestore(position: manifest.position) + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + } else if prefillGeometry != nil { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + let (maximumLength, overflow) = promptTokens.count.addingReportingOverflow(maximumNewTokens) + guard manifest.chunkSize == chunkSize, promptTokens.count <= configuration.maxPositionEmbeddings, + maximumNewTokens > 0, !overflow, maximumLength <= configuration.maxPositionEmbeddings, + promptTokens.starts(with: manifest.prefixTokens), + promptTokens.allSatisfy({ $0 >= 0 && $0 < configuration.vocabularySize }) + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + return try .init(manifest: manifest, engine: engine, codecIdentity: codecIdentity, + maximumSequenceLength: maximumLength) + } + + public func adopt(_ staged: CBv2NativeBlockCheckpoint, + prefixIdentity: DiffusionGemmaPrefixIdentity) throws -> DiffusionGemmaPrefixCheckpoint { + try validate(staged.manifest, prefixIdentity: prefixIdentity) + guard staged.codecIdentity == codecIdentity else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + let storage = try staged.consume() + return .init(configuration: configuration, owner: owner, identity: prefixIdentity, + manifest: staged.manifest, storage: storage) + } +} + +extension DiffusionGemmaTextDecoder { + public func makePersistentPrefixCodec(verifiedIdentity: CBv2CompleteCheckpointIdentity, + kvDType: DType, prefillChunkSize: Int? = nil) throws -> DiffusionGemmaPersistentPrefixCodec { + let empty = try DiffusionGemmaRequestCache(configuration: configuration, expectedPromptLength: 0) + try validateCache(empty) + return try .init(configuration: configuration, owner: empty.owner!, identity: verifiedIdentity, + dtype: kvDType, prefillChunkSize: prefillChunkSize) + } +} diff --git a/Libraries/MLXLLM/Models/DiffusionGemmaPrefixCache.swift b/Libraries/MLXLLM/Models/DiffusionGemmaPrefixCache.swift new file mode 100644 index 0000000000..2961c4f150 --- /dev/null +++ b/Libraries/MLXLLM/Models/DiffusionGemmaPrefixCache.swift @@ -0,0 +1,216 @@ +import Foundation +import MLX +import MLXLMCommon + +/// Trusted engine-side context for an in-process committed prefix. These are +/// verified identities, not untrusted request metadata. A new weight/template, +/// tenant, media sequence, numerical contract or epoch must never reuse a hit. +public struct DiffusionGemmaPrefixIdentity: Sendable, Equatable { + public let tenantScope: String + public let artifact: String + public let template: String + public let media: String + public let mediaIdentity: CBv2HybridPrefixIdentity? + public let numericalProfile: String + public let epoch: String + + public init( + tenantScope: String, artifact: String, template: String, media: String, + numericalProfile: String, epoch: String, mediaIdentity: CBv2HybridPrefixIdentity? = nil + ) throws { + guard + [tenantScope, artifact, template, media, numericalProfile, epoch].allSatisfy({ + !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + }) + else { throw DiffusionGemmaModelError.invalidInput("incomplete prefix identity") } + self.tenantScope = tenantScope + self.artifact = artifact + self.template = template + self.media = media + self.mediaIdentity = mediaIdentity + self.numericalProfile = numericalProfile + self.epoch = epoch + } +} + +/// Evaluated, immutable committed encoder state. It owns no model, denoising +/// canvas, RNG or self-conditioning logits. Only this SDK can construct it; +/// arrays are deliberately not exposed for mutation or unchecked disk restore. +/// This is an in-process reuse primitive, NOT an authenticated persistent format. +public final class DiffusionGemmaPrefixCheckpoint { + public let tokenCount: Int + /// Logical retained payload bytes. Shared allocation capacity can be larger; + /// this must not be substituted for measured physical-memory admission. + public let retainedBytes: Int + public let physicalRetainedBytes: Int + public let compact: Bool + let configuration: DiffusionGemmaTextConfiguration + let owner: UUID + let identity: DiffusionGemmaPrefixIdentity + let tokens: [Int32] + let windowOrder: DiffusionGemmaWindowOrder + private(set) var layers: [(keys: MLXArray, values: MLXArray, offset: Int)] + private var importedStorage: CBv2NativeBlockCheckpointStorage? + private var importedManifest: CBv2CompleteCheckpointManifest? + var isImported: Bool { importedStorage != nil } + + fileprivate init( + cache: DiffusionGemmaRequestCache, identity: DiffusionGemmaPrefixIdentity, compact: Bool + ) + throws + { + guard let owner = cache.owner, cache.position > 0, + cache.committedTokenCount == cache.position, + cache.rows.allSatisfy({ $0.absoluteOffset == cache.position }) + else { throw DiffusionGemmaModelError.invalidInput("incomplete committed prefix") } + let layers = cache.snapshots().map { layer in + compact + ? ( + keys: MLX.where(MLXArray(true), layer.keys, layer.keys), + values: MLX.where(MLXArray(true), layer.values, layer.values), + offset: layer.offset + ) : layer + } + guard layers.count == cache.configuration.layerCount else { + throw DiffusionGemmaModelError.invalidInput("incomplete prefix layers") + } + // Freeze graph roots before a donor continues or is retired. Slice + // views retain the old value, not mutable cache objects; later updates + // cannot donate storage still referenced by this checkpoint. + try MLX.withError { errors in + eval(layers.flatMap { [$0.keys, $0.values] }) + try errors.check() + } + self.layers = layers + self.compact = compact + configuration = cache.configuration + self.owner = owner + self.identity = identity + tokens = cache.committedTokenBatches.flatMap { $0.asArray(Int32.self) } + windowOrder = cache.windowOrder + tokenCount = cache.position + retainedBytes = layers.reduce(0) { $0 + $1.keys.nbytes + $1.values.nbytes } + physicalRetainedBytes = try layers.flatMap { [$0.keys, $0.values] }.reduce(0) { + count, array in + guard let info = try array.evaluatedBufferInfo(), info.allocatedBytes >= array.nbytes + else { + throw CBv2CompleteCheckpointError.allocationFailed + } + let (total, overflow) = count.addingReportingOverflow(info.allocatedBytes) + guard !overflow else { throw CBv2CompleteCheckpointError.allocationFailed } + return total + } + } + + init( + configuration: DiffusionGemmaTextConfiguration, owner: UUID, + identity: DiffusionGemmaPrefixIdentity, manifest: CBv2CompleteCheckpointManifest, + storage: CBv2NativeBlockCheckpointStorage + ) { + self.configuration = configuration + self.owner = owner + self.identity = identity + tokens = manifest.prefixTokens.map(Int32.init) + tokenCount = manifest.position + let order = manifest.nativeBlockState! + windowOrder = .init(physicalLength: order.windowPhysicalLength, cursor: order.windowCursor) + layers = stride(from: 0, to: storage.arrays.count, by: 2).map { + (keys: storage.arrays[$0], values: storage.arrays[$0 + 1], offset: manifest.position) + } + retainedBytes = storage.arrays.reduce(0) { $0 + $1.nbytes } + physicalRetainedBytes = storage.nativeDestinationBytes + compact = true + importedStorage = storage + importedManifest = manifest + } + + deinit { + // Drop every alias before the destination and metadata permits retire. + layers.removeAll(keepingCapacity: false) + importedStorage = nil + importedManifest = nil + } + + /// Token/identity lookup without exposing mutable tensor state. + public func matches(tokens candidate: [Int32], identity: DiffusionGemmaPrefixIdentity) -> Bool { + self.identity == identity && candidate.starts(with: tokens) + } + public func samePrefix(as other: DiffusionGemmaPrefixCheckpoint) -> Bool { + owner == other.owner && identity == other.identity && tokens == other.tokens + } +} + +extension DiffusionGemmaTextDecoder { + /// Capture only after successful prompt/finalized-block encoding. The + /// caller owns identity verification and single-lane serialization. + public func checkpoint( + cache: DiffusionGemmaRequestCache, identity: DiffusionGemmaPrefixIdentity, + compact: Bool = false + ) throws -> DiffusionGemmaPrefixCheckpoint { + try validateCache(cache) + return try DiffusionGemmaPrefixCheckpoint( + cache: cache, identity: identity, compact: compact) + } + + /// Restore a complete committed prefix into a fresh independent request. + /// No model forward is run and no trailing-window replay is required. + /// The returned position is the amount to skip when encoding the suffix. + public func restorePrefix( + _ checkpoint: DiffusionGemmaPrefixCheckpoint, + identity: DiffusionGemmaPrefixIdentity, promptTokenIds: MLXArray, + maximumSequenceLength: Int? = nil, pagedBackend: PagedKVBackend? = nil + ) throws -> DiffusionGemmaRequestCache { + guard checkpoint.configuration == configuration, + checkpoint.identity == identity, + promptTokenIds.ndim == 2, promptTokenIds.dim(0) == 1, + promptTokenIds.dim(1) >= checkpoint.tokenCount, + promptTokenIds.dim(1) <= configuration.maxPositionEmbeddings, + promptTokenIds.dtype == .int32 || promptTokenIds.dtype == .uint32 + else { throw DiffusionGemmaModelError.invalidInput("prefix identity/shape/capacity") } + let tokens = promptTokenIds.asArray(Int32.self) + guard tokens.allSatisfy({ $0 >= 0 && $0 < configuration.vocabularySize }), + tokens.starts(with: checkpoint.tokens) + else { throw DiffusionGemmaModelError.invalidInput("prefix token mismatch") } + let cache = try DiffusionGemmaRequestCache( + configuration: configuration, expectedPromptLength: tokens.count, + maximumSequenceLength: maximumSequenceLength, pagedBackend: pagedBackend) + // Bind before copying any arrays. Same-shape weights from another model + // instance or a reload must not inherit a prior owner's checkpoint. + try validateCache(cache) + guard cache.owner == checkpoint.owner else { + throw DiffusionGemmaModelError.invalidInput("prefix model owner") + } + cache.retainImportedPrefix(checkpoint) + try cache.performStep { + for (row, layer) in zip(cache.rows, checkpoint.layers) { + if let paged = row as? PagedSequenceKV, let pagedBackend { + if paged.windowSize != nil { + paged.fastForward(to: layer.offset - layer.keys.dim(2)) + } + // Restore through bounded native page writes, not one oversized + // ring update or a replay of model computation. + let length = layer.keys.dim(2) + for start in stride( + from: 0, to: length, by: pagedBackend.pool.config.maxPrefillChunk) + { + let end = min(length, start + pagedBackend.pool.config.maxPrefillChunk) + _ = paged.update( + keys: layer.keys[0, 0..., start ..< end, 0...], + values: layer.values[0, 0..., start ..< end, 0...]) + } + continue + } + if let windowed = row as? CBv2WindowedSequenceKV { + windowed.fastForward(to: layer.offset - layer.keys.dim(2)) + } + _ = row.update(keys: layer.keys, values: layer.values) + } + cache.recordCommittedTokens( + MLXArray(checkpoint.tokens).reshaped(1, checkpoint.tokenCount), + restoredWindowOrder: checkpoint.windowOrder) + try validateCache(cache) + try cache.finishPagedStep([]) + } + return cache + } +} diff --git a/Libraries/MLXLLM/Models/DiffusionGemmaRequestCache.swift b/Libraries/MLXLLM/Models/DiffusionGemmaRequestCache.swift new file mode 100644 index 0000000000..b37efa8163 --- /dev/null +++ b/Libraries/MLXLLM/Models/DiffusionGemmaRequestCache.swift @@ -0,0 +1,152 @@ +// Native request-owned committed encoder storage. +import Foundation +import MLX +import MLXLMCommon + +/// Per-request committed encoder state. Denoising reads snapshots and NEVER +/// writes provisional canvas K/V here. Uses native full/windowed sequence stores. +public final class DiffusionGemmaRequestCache { + public let configuration: DiffusionGemmaTextConfiguration + public let maximumSequenceLength: Int + /// Experimental page-backed state uses native gathers plus the unchanged + /// SDPA graph. It is NOT the numerically different scalar paged kernel. + public var usesPagedStorage: Bool { pagedBackend != nil } + private let pagedBackend: PagedKVBackend? + private var failed = false + private(set) var rows: [any CBv2SequenceKV] + private var importedPrefixOwner: DiffusionGemmaPrefixCheckpoint? + private(set) var owner: UUID? + private(set) var committedTokenBatches = [MLXArray]() + private(set) var committedTokenCount = 0 + private(set) var windowOrder = DiffusionGemmaWindowOrder() + public var position: Int { rows.first?.absoluteOffset ?? 0 } + public var retainedBytes: Int { rows.reduce(0) { $0 + $1.byteCount } } + + func retainImportedPrefix(_ checkpoint: DiffusionGemmaPrefixCheckpoint) { + if checkpoint.isImported { importedPrefixOwner = checkpoint } + } + + deinit { + // Restored rows/graphs may alias the import's charged buffers. Retire + // every native row before releasing that external destination permit. + if let pagedBackend { pagedBackend.release(rows.map { Optional($0) }) } + rows.removeAll(keepingCapacity: false) + committedTokenBatches.removeAll(keepingCapacity: false) + importedPrefixOwner = nil + } + + public init( + configuration: DiffusionGemmaTextConfiguration, expectedPromptLength: Int, + maximumSequenceLength: Int? = nil, pagedBackend: PagedKVBackend? = nil + ) throws { + let maximum = maximumSequenceLength ?? configuration.maxPositionEmbeddings + guard maximum > 0, maximum <= configuration.maxPositionEmbeddings, + expectedPromptLength >= 0, expectedPromptLength <= maximum + else { + throw DiffusionGemmaModelError.invalidInput("prompt capacity") + } + self.configuration = configuration + self.maximumSequenceLength = maximum + self.pagedBackend = pagedBackend + if let pagedBackend { + let expected = configuration.diffusionPagedLayerKinds + guard pagedBackend.layerKinds == expected else { + throw DiffusionGemmaModelError.invalidInput("paged cache geometry") + } + let state = try pagedBackend.makeSequenceState( + layerKinds: expected, + promptLength: expectedPromptLength, maxLength: maximum) + guard state.count == expected.count, state.allSatisfy({ $0 != nil }) else { + pagedBackend.release(state) + throw DiffusionGemmaModelError.invalidInput("incomplete paged cache") + } + rows = state.compactMap { $0 } + return + } + rows = configuration.layerTypes.map { kind in + if kind == "sliding_attention" { + return CBv2WindowedSequenceKV( + window: configuration.slidingWindow, + kvHeads: configuration.keyValueHeads, headDim: configuration.headDimension) + } + return CBv2FullSequenceKV( + promptLength: expectedPromptLength, + maxLength: maximum, + kvHeads: configuration.globalKeyValueHeads ?? configuration.keyValueHeads, + headDim: configuration.globalHeadDimension) + } + } + + public func snapshots() -> [(keys: MLXArray, values: MLXArray, offset: Int)] { + rows.filter { $0.retainedCount > 0 }.map { $0.snapshot() } + } + + /// Explicit graph roots for the owner's evaluation/retirement fence. + public func stateArrays() -> [MLXArray] { + snapshots().flatMap { [$0.keys, $0.values] } + } + + func recordCommittedTokens( + _ tokens: MLXArray, restoredWindowOrder: DiffusionGemmaWindowOrder? = nil + ) { + // Keep a separate array context, not the caller's mutable wrapper. + committedTokenBatches.append(tokens[0..., 0...]) + windowOrder = + restoredWindowOrder + ?? windowOrder.appending( + tokens.dim(1), priorPosition: committedTokenCount, + window: configuration.slidingWindow) + committedTokenCount += tokens.dim(1) + } + + func validate( + for config: DiffusionGemmaTextConfiguration, owner requestedOwner: UUID, appendCount: Int, + kvDType: DType + ) throws { + guard !failed, configuration == config, rows.count == config.layerCount, + position == committedTokenCount, + rows.allSatisfy({ $0.absoluteOffset == position }), appendCount >= 0, + appendCount <= maximumSequenceLength, position <= maximumSequenceLength - appendCount + else { throw DiffusionGemmaModelError.invalidInput("cache identity/position/capacity") } + if let pagedBackend, appendCount > pagedBackend.pool.config.maxPrefillChunk { + throw DiffusionGemmaModelError.invalidInput( + "paged cache chunk exceeds configured bound") + } + if let pagedBackend, !pagedBackend.pool.layerDTypes.allSatisfy({ $0 == kvDType }) { + throw DiffusionGemmaModelError.invalidInput("paged cache native dtype") + } + if let owner, owner != requestedOwner { + throw DiffusionGemmaModelError.invalidInput("cache model owner") + } + owner = requestedOwner + } + + /// Page reads refer to mutable shared storage. An explicit native step + /// finishes before another step can write/recycle it, including direct SDK + /// calls that are not run by a scheduler. This path is experimental and is + /// never advertised as a fused paged-attention speedup. + func finishPagedStep(_ outputs: [MLXArray]) throws { + guard usesPagedStorage else { return } + try MLX.withError { errors in + eval(outputs.isEmpty ? stateArrays() : outputs) + StreamOrDevice.default.stream.synchronize() + try errors.check() + } + } + + func performStep(_ body: () throws -> Result) throws -> Result { + guard let pagedBackend else { return try body() } + guard !failed else { + throw DiffusionGemmaModelError.invalidInput("retired failed paged request") + } + return try pagedBackend.performNativeBlockStep( + body, + onFailure: { + failed = true + pagedBackend.release(rows.map { Optional($0) }) + rows.removeAll(keepingCapacity: false) + committedTokenBatches.removeAll(keepingCapacity: false) + importedPrefixOwner = nil + }) + } +} diff --git a/Libraries/MLXLLM/Models/DiffusionGemmaSoftEmbedding.swift b/Libraries/MLXLLM/Models/DiffusionGemmaSoftEmbedding.swift new file mode 100644 index 0000000000..2823e494bb --- /dev/null +++ b/Libraries/MLXLLM/Models/DiffusionGemmaSoftEmbedding.swift @@ -0,0 +1,104 @@ +// DiffusionGemma soft conditioning, using the packaged upstream MLX affine math. +import Cmlx +import Foundation +import MLX +import MLXLMCommon + +enum DiffusionGemmaSoftEmbedding { + // Experimental until full-model qualification. Removing the switch is rollback. + static let enabled = enabled( + from: ProcessInfo.processInfo.environment["DARKBLOOM_DIFFUSION_SOFT_EMBEDDING"]) + + static func enabled(from value: String?) -> Bool { + value.map { ["1", "true", "yes", "on"].contains($0.lowercased()) } ?? false + } + + // This existing non-evaluating C API rejects compile/grad/vmap tracing and + // retained graphs. No identities or arrays are retained by this projection. + static func outsideTransform(_ arrays: [MLXArray]) -> Bool { + arrays.allSatisfy { array in + var identity: UInt = 0 + var ordinary = false + return _mlx_array_constant_cache_identity(&identity, &ordinary, array.ctx) == 0 + && ordinary + } + } + + static func eligible( + _ x: MLXArray, weight: MLXArray, scales: MLXArray, biases: MLXArray?, + groupSize: Int, bits: Int, mode: QuantizationMode, inference: Bool, enabled: Bool + ) -> Bool { + guard enabled, inference, Device.defaultDevice().deviceType == .gpu, + StreamOrDevice.default.stream == Stream.gpu, + x.shape == [1, 256, 262144], x.dtype == .bfloat16, + weight.shape == [262144, 704], weight.dtype == .uint32, + scales.shape == [262144, 44], scales.dtype == .bfloat16, + let biases, biases.shape == scales.shape, biases.dtype == .bfloat16, + groupSize == 64, bits == 8, mode == .affine + else { return false } + return outsideTransform([x, weight, scales, biases]) + } + + static func accelerated( + _ x: MLXArray, weight: MLXArray, scales: MLXArray, biases: MLXArray?, + groupSize: Int, bits: Int, mode: QuantizationMode, inference: Bool, enabled: Bool + ) -> MLXArray? { + guard eligible( + x, weight: weight, scales: scales, biases: biases, groupSize: groupSize, + bits: bits, mode: mode, inference: inference, enabled: enabled), + let biases, let kernel + else { return nil } + // Same K traversal, dequantization and FP32 accumulation as qmm_n. + // Only BM changes from 32 to 64. The native canvas and sampler do not. + // Keep safe contiguous preparation for arbitrary input views/offsets. + let result = kernel( + [weight, scales, biases, x], template: [("T", DType.bfloat16)], + grid: (88 * 32, 4 * 2, 2), threadGroup: (32, 2, 2), + outputShapes: [[1, 256, 2816]], outputDTypes: [.bfloat16], + stream: .default)[0] + DiffusionGemmaSoftEmbeddingDiagnostics.recordDispatch() + return result + } + + static func project( + _ x: MLXArray, weight: MLXArray, scales: MLXArray, biases: MLXArray?, + groupSize: Int, bits: Int, mode: QuantizationMode, inference: Bool, enabled: Bool + ) -> MLXArray { + accelerated( + x, weight: weight, scales: scales, biases: biases, groupSize: groupSize, + bits: bits, mode: mode, inference: inference, enabled: enabled) + ?? quantizedMM( + x, weight, scales: scales, biases: biases, transpose: false, + groupSize: groupSize, bits: bits, mode: mode) + } + + private static let kernel: MLXFast.MLXFastKernel? = { + guard (try? Qwen4ExpMetalHeaders.validateResources()) != nil else { return nil } + var quantized = Qwen4ExpMetalHeaders.quantized + guard let start = quantized.range( + of: "\ntemplate \n[[kernel]]") + ?? quantized.range(of: "\n[[kernel]]") + else { return nil } + quantized = String(quantized[..( + w, scales, biases, x, y, Xs, Ws, + diffusion_soft_K, diffusion_soft_N, diffusion_soft_M, + threadgroup_position_in_grid, thread_index_in_threadgroup, + simdgroup_index_in_threadgroup, thread_index_in_simdgroup); + """, + header: header, ensureRowContiguous: true) + }() +} diff --git a/Libraries/MLXLLM/Models/DiffusionGemmaSoftEmbeddingDiagnostics.swift b/Libraries/MLXLLM/Models/DiffusionGemmaSoftEmbeddingDiagnostics.swift new file mode 100644 index 0000000000..314c051aff --- /dev/null +++ b/Libraries/MLXLLM/Models/DiffusionGemmaSoftEmbeddingDiagnostics.swift @@ -0,0 +1,36 @@ +import Foundation + +/// Opt-in qualification counters; no tensor readback or retained model state. +@_spi(DiffusionGemmaDiagnostics) +public enum DiffusionGemmaSoftEmbeddingDiagnostics { + public struct Snapshot: Equatable, Sendable { + public let armed: Bool + public let calls: UInt64 + } + + private final class State: @unchecked Sendable { + let lock = NSLock() + var armed = false + var calls: UInt64 = 0 + } + private static let state = State() + + public static func clearAndArm() { + state.lock.withLock { state.calls = 0; state.armed = true } + } + + public static func snapshot() -> Snapshot { + state.lock.withLock { Snapshot(armed: state.armed, calls: state.calls) } + } + + public static func snapshotAndDisarm() -> Snapshot { + state.lock.withLock { + state.armed = false + return Snapshot(armed: false, calls: state.calls) + } + } + + static func recordDispatch() { + state.lock.withLock { if state.armed { state.calls += 1 } } + } +} diff --git a/Libraries/MLXLLM/Models/DiffusionGemmaTextModel.swift b/Libraries/MLXLLM/Models/DiffusionGemmaTextModel.swift new file mode 100644 index 0000000000..4c8d42cb74 --- /dev/null +++ b/Libraries/MLXLLM/Models/DiffusionGemmaTextModel.swift @@ -0,0 +1,257 @@ +// Adapted from MLX-VLM e79b0e041677ec4ca5333ba750376bb4e8c434cb. +// Copyright © 2025 Prince Canuma. MIT: docs/diffusiongemma/LICENSE-MLX-VLM. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +public final class DiffusionGemmaEncoderScalar: Module { + @ModuleInfo(key: "layer_scalar") public var value: MLXArray + public override init() { + _value.wrappedValue = .ones([1]) + super.init() + } +} + +/// Only the encoder-specific learned scalars are registered here. The decoder +/// owns all shared text weights exactly once, avoiding duplicate quantization, +/// parameter enumeration and memory admission charges. +public final class DiffusionGemmaEncoderTextParameters: Module { + @ModuleInfo public var layers: [DiffusionGemmaEncoderScalar] + public init(layerCount: Int) { + _layers.wrappedValue = (0 ..< layerCount).map { _ in DiffusionGemmaEncoderScalar() } + } +} + +public final class DiffusionGemmaTextDecoder: Module { + public let configuration: DiffusionGemmaTextConfiguration + @ModuleInfo(key: "embed_tokens") public var embedTokens: Embedding + @ModuleInfo public var layers: [DiffusionGemmaTextBlock] + @ModuleInfo public var norm: RMSNorm + @ModuleInfo(key: "self_conditioning") public var selfConditioning: + DiffusionGemmaSelfConditioning + private let embeddingScale: Float + private let cacheOwner = UUID() + + public init(_ configuration: DiffusionGemmaTextConfiguration) { + self.configuration = configuration + embeddingScale = sqrt(Float(configuration.hiddenSize)) + _embedTokens.wrappedValue = Embedding( + embeddingCount: configuration.vocabularySize, + dimensions: configuration.hiddenSize) + _layers.wrappedValue = (0 ..< configuration.layerCount).map { + DiffusionGemmaTextBlock(configuration, layer: $0) + } + _norm.wrappedValue = RMSNorm( + dimensions: configuration.hiddenSize, eps: configuration.rmsNormEpsilon) + _selfConditioning.wrappedValue = DiffusionGemmaSelfConditioning(configuration) + } + + /// The pinned MLX quant reference retains FP32 conditioning logits, while + /// the original dense checkpoint rounds them to its embedding dtype. + /// Record this artifact-specific contract; a different policy needs new + /// numerical/quality qualification, not a hidden speed toggle. + public var selfConditioningLogitsDType: DType { + embedTokens is QuantizedEmbedding ? .float32 : embedTokens.weight.dtype + } + + func validateCache(_ cache: DiffusionGemmaRequestCache) throws { + try cache.validate( + for: configuration, owner: cacheOwner, appendCount: 0, kvDType: nativeKVDType) + } + + private var nativeKVDType: DType { + (embedTokens as? QuantizedEmbedding)?.scales.dtype ?? embedTokens.weight.dtype + } + + public func scaledEmbeddings(_ tokenIds: MLXArray) throws -> MLXArray { + try validateTokenIds(tokenIds) + return embedTokens(tokenIds) * embeddingScale + } + + private func validateTokenIds(_ ids: MLXArray) throws { + guard ids.ndim == 2, ids.dim(0) == 1, ids.dim(1) > 0, + ids.dtype == .int32 || ids.dtype == .uint32 + else { throw DiffusionGemmaModelError.invalidInput("token shape/type") } + guard logicalAnd(ids .>= 0, ids .< configuration.vocabularySize).all().item(Bool.self) + else { + throw DiffusionGemmaModelError.invalidInput("token range") + } + } + + /// Encode prompt or finalized-canvas tokens into request-owned KV. The + /// returned hidden state is optional work; callers needing only the cache + /// evaluate stateArrays() rather than materializing unused final-layer FFNs. + public func encode( + tokenIds: MLXArray, cache: DiffusionGemmaRequestCache, + encoderParameters: DiffusionGemmaEncoderTextParameters, + preparedEmbeddings: MLXArray? = nil, + visualBlockIds: MLXArray? = nil + ) throws -> MLXArray { + try cache.performStep { + try encodeStep( + tokenIds: tokenIds, cache: cache, encoderParameters: encoderParameters, + preparedEmbeddings: preparedEmbeddings, visualBlockIds: visualBlockIds) + } + } + + private func encodeStep( + tokenIds: MLXArray, cache: DiffusionGemmaRequestCache, + encoderParameters: DiffusionGemmaEncoderTextParameters, + preparedEmbeddings: MLXArray?, visualBlockIds: MLXArray? + ) throws -> MLXArray { + try validateTokenIds(tokenIds) + let length = tokenIds.dim(1) + try cache.validate( + for: configuration, owner: cacheOwner, appendCount: length, kvDType: nativeKVDType) + guard encoderParameters.layers.count == layers.count else { + throw DiffusionGemmaModelError.invalidInput("encoder scalars") + } + if let preparedEmbeddings, + preparedEmbeddings.shape != [1, length, configuration.hiddenSize] + { + throw DiffusionGemmaModelError.invalidInput("prepared embeddings") + } + if let visualBlockIds, visualBlockIds.shape != [1, length] { + throw DiffusionGemmaModelError.invalidInput("visual block shape") + } + var hidden = preparedEmbeddings ?? (embedTokens(tokenIds) * embeddingScale) + let position = cache.position + let nextWindowOrder = cache.windowOrder.appending( + length, priorPosition: position, window: configuration.slidingWindow) + for (index, block) in layers.enumerated() { + let row = cache.rows[index] + let sliding = configuration.layerTypes[index] == "sliding_attention" + let history = + sliding + ? min(row.retainedCount, configuration.slidingWindow - 1) : row.retainedCount + let mask = encoderMask( + length: length, history: history, + window: sliding ? configuration.slidingWindow : nil, + visualBlockIds: visualBlockIds) + hidden = block( + hidden, position: position, mask: mask, + encoderScalar: encoderParameters.layers[index].value + ) { keys, values in + let updated = row.update(keys: keys, values: values) + guard sliding, length == 1, position + 1 >= configuration.slidingWindow, + nextWindowOrder.cursor < configuration.slidingWindow + else { return updated } + // Match the reference's singleton reduction order. Snapshots + // and denoising remain canonical oldest-to-newest views. + let split = configuration.slidingWindow - nextWindowOrder.cursor + func ringOrder(_ value: MLXArray) -> MLXArray { + concatenated( + [value[.ellipsis, split..., 0...], value[.ellipsis, .. MLXFast.ScaledDotProductAttentionMaskMode { + if length == 1 { return .none } + if history == 0, visualBlockIds == nil, window == nil || length <= window! { + return .causal + } + let keyPositions = MLXArray(0 ..< (history + length)) + let queries = MLXArray(history ..< (history + length)).expandedDimensions(axis: -1) + var mask = queries .>= keyPositions + if let window { mask = logicalAnd(mask, queries .< keyPositions + window) } + mask = mask[.newAxis, .newAxis, 0..., 0...] + if let visualBlockIds, configuration.bidirectionalAttention == "vision" { + let q = visualBlockIds[0..., 0..., .newAxis] + let k = visualBlockIds[0..., .newAxis, 0...] + var overlay = logicalAnd(q .>= 0, q .== k)[0..., .newAxis, 0..., 0...] + if history > 0 { + overlay = concatenated( + [.zeros([1, 1, length, history], dtype: .bool), overlay], axis: -1) + } + mask = logicalOr(mask, overlay) + } + return .array(mask) + } + + public func denoise( + canvasIds: MLXArray, cache: DiffusionGemmaRequestCache, + selfConditioningLogits: MLXArray? = nil + ) throws -> MLXArray { + try cache.performStep { + try denoiseStep( + canvasIds: canvasIds, cache: cache, selfConditioningLogits: selfConditioningLogits) + } + } + + private func denoiseStep( + canvasIds: MLXArray, cache: DiffusionGemmaRequestCache, + selfConditioningLogits: MLXArray? + ) throws -> MLXArray { + try validateTokenIds(canvasIds) + try cache.validate( + for: configuration, owner: cacheOwner, appendCount: 0, kvDType: nativeKVDType) + let embeddings = embedTokens(canvasIds) * embeddingScale + let soft: MLXArray + if let logits = selfConditioningLogits { + guard logits.shape == canvasIds.shape + [configuration.vocabularySize] else { + throw DiffusionGemmaModelError.invalidInput("conditioning shape") + } + let probabilities = softmax(logits.asType(.float32), axis: -1, precise: true).asType( + embeddings.dtype) + if let packed = embedTokens as? QuantizedEmbedding { + soft = + DiffusionGemmaSoftEmbedding.project( + probabilities, weight: packed.weight, scales: packed.scales, + biases: packed.biases, groupSize: packed.groupSize, bits: packed.bits, + mode: packed.mode, inference: !training, + enabled: DiffusionGemmaSoftEmbedding.enabled + ) + .asType(embeddings.dtype) * embeddingScale + } else { + soft = + matmul(probabilities, embedTokens.weight).asType(embeddings.dtype) + * embeddingScale + } + } else { + soft = .zeros(like: embeddings) + } + var hidden = selfConditioning(embeddings, softEmbeddings: soft) + for (index, block) in layers.enumerated() { + let row = cache.rows[index] + var prefix: (MLXArray, MLXArray)? + if row.retainedCount > 0 { + let snapshot = row.snapshot() + let count = + configuration.layerTypes[index] == "sliding_attention" + ? min(row.retainedCount, configuration.slidingWindow - 1) : row.retainedCount + let start = snapshot.keys.dim(2) - count + prefix = ( + snapshot.keys[.ellipsis, start..., 0...], + snapshot.values[.ellipsis, start..., 0...] + ) + } + hidden = block(hidden, position: cache.position, mask: .none) { keys, values in + guard let prefix else { return (keys, values) } + return ( + concatenated([prefix.0, keys], axis: 2), + concatenated([prefix.1, values], axis: 2) + ) + } + } + let raw = embedTokens.asLinear(norm(hidden)).asType(.float32) + let result = tanh(raw / configuration.finalLogitSoftcap) * configuration.finalLogitSoftcap + try cache.finishPagedStep([result]) + return result + } +} + +public enum DiffusionGemmaModelError: Error, Sendable, Equatable { + case invalidInput(String) +} diff --git a/Libraries/MLXLLM/Models/DiffusionGemmaWindowOrder.swift b/Libraries/MLXLLM/Models/DiffusionGemmaWindowOrder.swift new file mode 100644 index 0000000000..6d19dfe444 --- /dev/null +++ b/Libraries/MLXLLM/Models/DiffusionGemmaWindowOrder.swift @@ -0,0 +1,27 @@ +/// The pinned reference exposes physical ring order to a singleton encoder +/// query, but temporal order to a multi-token query and the denoiser. Ordering +/// changes reduction rounding even though the logical attention set is equal. +/// Preserve this small native state separately from canonical temporal storage. +struct DiffusionGemmaWindowOrder: Equatable { + var physicalLength = 0 + var cursor = 0 + + func appending(_ count: Int, priorPosition: Int, window: Int) -> Self { + if count > 1 { + let length = min(priorPosition, window - 1) + count + return Self(physicalLength: length, cursor: length) + } + var next = self + if physicalLength == 0 || (priorPosition >= physicalLength && physicalLength < window) { + next.physicalLength += min(256, window - priorPosition) + next.cursor = priorPosition + } + if next.physicalLength > window { + next.physicalLength = window + next.cursor = window + } + if next.cursor == window { next.cursor = 0 } + next.cursor += 1 + return next + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift index 1cdd02df83..03df3ef38e 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift @@ -94,6 +94,9 @@ public struct CBv2Request: Sendable { /// from silently becoming an unscoped shared cache. Defaults true for /// local and backwards-compatible direct engine callers. public var prefixCacheEnabled: Bool + /// Native bridge's process-ledger reservation, never a wire/body control. + /// A changed cache budget may force cold serving, not a larger allocation. + public var nativeReservationBytes: Int? /// Correlation identity for prefix-cache donation receipts. This is /// deliberately separate from `id`, which remains the sampler and /// scheduler identity and may be reused after a request finishes. nil @@ -121,6 +124,7 @@ public struct CBv2Request: Sendable { id: CBv2RequestID, promptTokens: [Int], sampling: CBv2SamplingParams = .init(), maxTokens: Int, stopTokens: Set = [], stopStrings: [String] = [], priority: Int = 0, cacheSalt: String? = nil, prefixCacheEnabled: Bool = true, + nativeReservationBytes: Int? = nil, multimodal: CBv2MultimodalInput? = nil, positionState: CBv2PositionState? = nil, hybridPrefixIdentity: CBv2HybridPrefixIdentity? = nil, @@ -136,6 +140,7 @@ public struct CBv2Request: Sendable { self.priority = priority self.cacheSalt = cacheSalt self.prefixCacheEnabled = prefixCacheEnabled + self.nativeReservationBytes = nativeReservationBytes self.multimodal = multimodal self.positionState = positionState self.hybridPrefixIdentity = hybridPrefixIdentity @@ -948,6 +953,8 @@ public struct CBv2Usage: Sendable { public enum CBv2PrefixCacheTier: String, Sendable, Equatable { /// Zero-copy physical pages already resident in the paged KV pool. case resident + /// Complete in-memory snapshots, not zero-copy paged residency or SSD. + case memorySnapshot = "memory_snapshot" /// Materialized KV snapshots supplied through `CBv2PrefixCache`. case snapshot } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2DeadlineLeases.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2DeadlineLeases.swift index 84d205ba95..6f7f4379be 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2DeadlineLeases.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2DeadlineLeases.swift @@ -204,6 +204,7 @@ struct CBv2RequestLeaseState { /// actually advances (never from optimistic scheduler planning). private var lastComputedTokens: Int private var lastGeneratedTokens: Int + private var lastNativeWork: Int = 0 /// Whether the request has begun engine work. var isAdmitted: Bool { legacyWall == nil && admissionDeadline == nil } @@ -281,6 +282,20 @@ struct CBv2RequestLeaseState { } } + /// A native block engine confirms evaluated encoder/refinement quanta, + /// not speculative output tokens. Only a strictly newer completed quantum + /// refreshes its phase lease; the absolute ceiling still bounds nonconvergence. + /// AR callers keep their existing token-watermark semantics unchanged. + mutating func recordNativeProgress( + now: ContinuousClock.Instant, phase: Phase, completedWork: Int + ) { + guard legacyWall == nil, completedWork > lastNativeWork else { return } + if admissionDeadline != nil { markAdmitted(now: now) } + lastNativeWork = completedWork + self.phase = phase + progressDeadline = now.advanced(by: phase == .prefill ? prefillLease : decodeLease) + } + /// The request paused on backpressure: arm the backpressure lease. The /// progress lease is not consulted while paused (a slow consumer is not an /// engine stall). diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockCheckpointImport.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockCheckpointImport.swift new file mode 100644 index 0000000000..27f6fb63a7 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockCheckpointImport.swift @@ -0,0 +1,224 @@ +import Cmlx +import Foundation +import MLX + +/// Explicit native-block import; never constructs an AR/recurrent checkpoint. +/// The model codec validates identities and exact tensor geometry first. The +/// provider authenticates the full encrypted stream before calling finish. +public final class CBv2NativeBlockCheckpointImportPlan: @unchecked Sendable { + public let manifest: CBv2CompleteCheckpointManifest + public let nativeDestinationBytes: Int + public let scratchBytes: Int + public let maximumSequenceLength: Int + public let usesProcessMemoryOwner: Bool + let codecIdentity: UUID + private let engine: CBv2NativeBlockEngine + + package init( + manifest: CBv2CompleteCheckpointManifest, engine: CBv2NativeBlockEngine, + codecIdentity: UUID, + maximumSequenceLength: Int + ) throws { + _ = try manifest.validateStructure() + guard manifest.backendLayout == CBv2CompleteCheckpointManifest.diffusionBlockLayout else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + self.engine = engine + self.codecIdentity = codecIdentity + self.maximumSequenceLength = maximumSequenceLength + self.usesProcessMemoryOwner = engine.usesProcessMemoryOwner + self.manifest = try manifest.owningNativeMetadata(engine: engine) + var destination = 0 + var initialization = 0 + for descriptor in manifest.tensors { + destination = try CBv2CheckpointAllocationFootprint.add( + destination, + CBv2CheckpointAllocationFootprint.bound(descriptor.byteCount)) + initialization = try CBv2CheckpointAllocationFootprint.add( + initialization, + CBv2CheckpointAllocationFootprint.bound(descriptor.dtype.mlxDType.size)) + } + nativeDestinationBytes = destination + scratchBytes = try CBv2CheckpointAllocationFootprint.add( + initialization, + usesProcessMemoryOwner ? 0 : CBv2CompleteCheckpointManifest.maximumProviderScratchBytes) + } + + func coverDestinations(bytes: Int) throws -> CBv2MemoryCoverage? { + try engine.coverNativeCheckpointAllocation(bytes: bytes) + } + + public func allocate(onRelease: @escaping @Sendable () -> Void = {}) throws + -> CBv2NativeBlockCheckpointImport + { + let external = CBv2CheckpointReservation(onRelease: onRelease) + do { + let lease = try engine.reserveNativeCheckpoint( + bytes: + CBv2CheckpointAllocationFootprint.add(nativeDestinationBytes, scratchBytes)) + do { return try .init(plan: self, lease: lease, external: external) } catch { + lease.close() + throw error + } + } catch { + external.release() + throw error + } + } +} + +public final class CBv2NativeBlockCheckpointImport: @unchecked Sendable { + private let lock = NSLock() + private let manifest: CBv2CompleteCheckpointManifest + private let codecIdentity: UUID + private let maximumSequenceLength: Int + private var storage: CBv2NativeBlockCheckpointStorage? + private var tensorIndex = 0 + private var byteOffset = 0 + + fileprivate init( + plan: CBv2NativeBlockCheckpointImportPlan, lease: CBv2NativeBlockCheckpointLease, + external: CBv2CheckpointReservation + ) throws { + manifest = plan.manifest + codecIdentity = plan.codecIdentity + maximumSequenceLength = plan.maximumSequenceLength + let stream = StreamOrDevice.default + let arrays = try withError { errors in + let arrays = plan.manifest.tensors.map { + MLXArray.zeros($0.shape, dtype: $0.dtype.mlxDType, stream: stream) + } + do { + try errors.check() + eval(arrays) + stream.stream.synchronize() + try errors.check() + } catch { + stream.stream.synchronize() + throw error + } + return arrays + } + let footprint = try CBv2CheckpointAllocationFootprint.freshBytes(arrays) + guard footprint.actual <= plan.nativeDestinationBytes else { + throw CBv2CompleteCheckpointError.allocationFailed + } + storage = .init( + arrays: arrays, lease: lease, external: external, + nativeDestinationBytes: footprint.actual, + coverage: try plan.coverDestinations(bytes: footprint.actual)) + } + + public func appendSegment(tensorIndex: Int, byteOffset: Int, data: Data) throws { + try lock.withLock { + guard let storage else { throw CBv2CompleteCheckpointError.closed } + guard tensorIndex == self.tensorIndex, byteOffset == self.byteOffset, + manifest.tensors.indices.contains(tensorIndex), !data.isEmpty, + data.count <= CBv2CompleteCheckpointManifest.maximumSegmentBytes + else { throw CBv2CompleteCheckpointError.invalidSegment } + let descriptor = manifest.tensors[tensorIndex] + guard data.count % descriptor.dtype.mlxDType.size == 0, + data.count <= descriptor.byteCount - byteOffset, + let pointer = mlx_array_data_uint8(storage.arrays[tensorIndex].ctx) + else { throw CBv2CompleteCheckpointError.invalidSegment } + // Destinations are fresh, evaluated, contiguous and unpublished. + data.withUnsafeBytes { bytes in + UnsafeMutableRawPointer(mutating: pointer).advanced(by: byteOffset) + .copyMemory(from: bytes.baseAddress!, byteCount: data.count) + } + self.byteOffset += data.count + if self.byteOffset == descriptor.byteCount { + self.tensorIndex += 1 + self.byteOffset = 0 + } + } + } + + public func finish() throws -> CBv2NativeBlockCheckpoint { + try lock.withLock { + guard let storage else { throw CBv2CompleteCheckpointError.closed } + guard tensorIndex == manifest.tensors.count, byteOffset == 0 else { + throw CBv2CompleteCheckpointError.incompleteTransfer + } + self.storage = nil + return .init( + manifest: manifest, storage: storage, codecIdentity: codecIdentity, + maximumSequenceLength: maximumSequenceLength) + } + } + + public func close() { lock.withLock { storage = nil } } + deinit { close() } +} + +/// Single-use, opaque authenticated-transfer destination. Only a native model +/// codec can bind its arrays to a new loaded model owner. +public final class CBv2NativeBlockCheckpoint: @unchecked Sendable { + public let manifest: CBv2CompleteCheckpointManifest + public let maximumSequenceLength: Int + public let nativeDestinationBytes: Int + package let codecIdentity: UUID + private let lock = NSLock() + private var storage: CBv2NativeBlockCheckpointStorage? + fileprivate init( + manifest: CBv2CompleteCheckpointManifest, storage: CBv2NativeBlockCheckpointStorage, + codecIdentity: UUID, + maximumSequenceLength: Int + ) { + self.manifest = manifest + self.storage = storage + self.codecIdentity = codecIdentity + self.maximumSequenceLength = maximumSequenceLength + self.nativeDestinationBytes = storage.nativeDestinationBytes + } + package func consume() throws -> CBv2NativeBlockCheckpointStorage { + try lock.withLock { + guard let storage else { throw CBv2CompleteCheckpointError.closed } + self.storage = nil + return storage + } + } + public func close() { lock.withLock { storage = nil } } + deinit { close() } +} + +package final class CBv2NativeBlockCheckpointStorage { + package private(set) var arrays: [MLXArray] + private let lease: CBv2NativeBlockCheckpointLease + private let external: CBv2CheckpointReservation + private let coverage: CBv2MemoryCoverage? + package let nativeDestinationBytes: Int + fileprivate init( + arrays: [MLXArray], lease: CBv2NativeBlockCheckpointLease, + external: CBv2CheckpointReservation, nativeDestinationBytes: Int, + coverage: CBv2MemoryCoverage? + ) { + self.arrays = arrays + self.lease = lease + self.external = external + self.coverage = coverage + self.nativeDestinationBytes = nativeDestinationBytes + } + deinit { + arrays.removeAll(keepingCapacity: false) + coverage?.invalidate() + lease.close() + external.release() + } +} + +extension CBv2CompleteCheckpointExport { + package convenience init( + nativeBlockManifest manifest: CBv2CompleteCheckpointManifest, + arrays: [MLXArray], engine: CBv2NativeBlockEngine + ) throws { + _ = try manifest.validateStructure() + guard manifest.backendLayout == CBv2CompleteCheckpointManifest.diffusionBlockLayout, + arrays.count == manifest.tensors.count, + zip(arrays, manifest.tensors).allSatisfy({ + $0.shape == $1.shape && $0.dtype == $1.dtype.mlxDType + }) + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + self.init(manifest: try manifest.owningNativeMetadata(engine: engine), arrays: arrays) + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockCheckpointLease.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockCheckpointLease.swift new file mode 100644 index 0000000000..0bd7f5e7a5 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockCheckpointLease.swift @@ -0,0 +1,20 @@ +import Foundation + +/// A real native-engine capacity reservation, acquired before checkpoint +/// allocation. Storage owners drop their arrays before closing this lease. +public final class CBv2NativeBlockCheckpointLease: @unchecked Sendable { + public let bytes: Int + private let lock = NSLock() + private var release: (@Sendable () -> Void)? + + init(bytes: Int, release: @escaping @Sendable () -> Void) { + self.bytes = bytes + self.release = release + } + + public func close() { + let callback = lock.withLock { let value = release; release = nil; return value } + callback?() + } + deinit { close() } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockCheckpointMetadata.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockCheckpointMetadata.swift new file mode 100644 index 0000000000..7494713aa5 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockCheckpointMetadata.swift @@ -0,0 +1,78 @@ +import Foundation + +/// Native encoder ordering state. Diffusion canvases, RNG and provisional +/// logits are never checkpoint payloads. Model-specific geometry is checked by +/// the loaded native codec before allocation or adoption. +public struct CBv2NativeBlockCheckpointState: Codable, Sendable, Equatable { + public let windowPhysicalLength: Int + public let windowCursor: Int + + public init(windowPhysicalLength: Int, windowCursor: Int) { + self.windowPhysicalLength = windowPhysicalLength + self.windowCursor = windowCursor + } + + func validate() throws { + guard windowPhysicalLength > 0, windowPhysicalLength <= Int(Int32.max), + windowCursor > 0, windowCursor <= windowPhysicalLength + else { throw CBv2CompleteCheckpointError.invalidManifest } + } +} + +/// Canonical little-endian bit packing, only for the native-block layout. +/// A 262144-token, 19-bit vocabulary fits the existing 1 MiB encrypted manifest +/// bound including base64. Legacy checkpoint encodings are unchanged. This is +/// integer compression, not tensor quantization or a tokenizer transformation. +struct CBv2NativeBlockPackedTokens: Codable { + let bitWidth: Int + let bytes: Data + + init(tokens: [Int]) throws { + guard !tokens.isEmpty, tokens.count <= CBv2CompleteCheckpointManifest.maximumEncodedBytes / 2, + tokens.allSatisfy({ $0 >= 0 && $0 <= Int(Int32.max) }) + else { throw CBv2CompleteCheckpointError.invalidManifest } + let largest = tokens.max()! + bitWidth = max(1, Int.bitWidth - largest.leadingZeroBitCount) + var output = Data() + output.reserveCapacity((tokens.count * bitWidth + 7) / 8) + var buffer: UInt64 = 0 + var available = 0 + for token in tokens { + buffer |= UInt64(token) << available + available += bitWidth + while available >= 8 { + output.append(UInt8(truncatingIfNeeded: buffer)) + buffer >>= 8 + available -= 8 + } + } + if available > 0 { output.append(UInt8(truncatingIfNeeded: buffer)) } + bytes = output + } + + func unpack(count: Int) throws -> [Int] { + guard count > 1, count <= CBv2CompleteCheckpointManifest.maximumEncodedBytes / 2, + (1...31).contains(bitWidth), bytes.count == (count * bitWidth + 7) / 8 + else { throw CBv2CompleteCheckpointError.invalidManifest } + var result = [Int]() + result.reserveCapacity(count) + var buffer: UInt64 = 0 + var available = 0 + let mask = (UInt64(1) << bitWidth) - 1 + for byte in bytes { + buffer |= UInt64(byte) << available + available += 8 + while available >= bitWidth && result.count < count { + result.append(Int(buffer & mask)) + buffer >>= bitWidth + available -= bitWidth + } + } + // Reject alternate encodings and nonzero padding. The encrypted bytes + // and the decoded token sequence have one canonical representation. + guard result.count == count, buffer == 0, + bitWidth == max(1, Int.bitWidth - result.max()!.leadingZeroBitCount) + else { throw CBv2CompleteCheckpointError.invalidManifest } + return result + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockContracts.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockContracts.swift new file mode 100644 index 0000000000..7112fcd1a7 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockContracts.swift @@ -0,0 +1,75 @@ +import Foundation + +/// Native block-generation quantum. Only `committed` can reach an output +/// stream; prefill/refinement never masquerade as emitted tokens. +public enum CBv2NativeBlockStep: Sendable { + case prefill(computedTokens: Int, complete: Bool) + case progress + case committed(tokens: [Int], stopToken: Int?, finishReason: CBv2FinishReason?) +} + +/// Request state owned exclusively by a native engine queue. This deliberately +/// has no autoregressive logits/TokenIterator requirement. +public protocol CBv2NativeBlockSession: AnyObject { + var retainedBytes: Int { get } + /// Subset of retainedBytes physically owned by the shared paged backend. + /// Engine gauges substitute its actual backing once, not once per row. + var sharedStorageBytes: Int { get } + var activeTokenCount: Int { get } + var generatedTokenCount: Int { get } + var prefixUsage: CBv2Usage { get } + func advanceNative() throws -> CBv2NativeBlockStep + func finish(reason: CBv2FinishReason) + func cancel() +} + +extension CBv2NativeBlockSession { + public var sharedStorageBytes: Int { 0 } + public var prefixUsage: CBv2Usage { .init(promptTokens: 0, completionTokens: 0) } + public func finish(reason: CBv2FinishReason) {} +} + +/// Engine-queue-only cache resources inside the existing slot grant. Closures +/// must not retain model weights after clear; this is not extra memory capacity. +public struct CBv2NativeBlockSharedResources: Sendable { + public let maximumBytes: Int + public let retainedBytes: @Sendable () -> Int + public let trim: @Sendable (Int) -> Void + public let clear: @Sendable () -> Void + public init( + maximumBytes: Int, retainedBytes: @escaping @Sendable () -> Int, + trim: @escaping @Sendable (Int) -> Void, clear: @escaping @Sendable () -> Void + ) { + self.maximumBytes = maximumBytes + self.retainedBytes = retainedBytes + self.trim = trim + self.clear = clear + } +} + +/// Cancellation is visible during a blocking device quantum without moving +/// the session or any MLX array onto another thread. +public final class CBv2NativeBlockCancellation: @unchecked Sendable { + private let lock = NSLock() + private var cancelled = false + public var isCancelled: Bool { lock.withLock { cancelled } } + func cancel() { lock.withLock { cancelled = true } } +} + +public enum CBv2NativeBlockError: Error, Sendable, Equatable, LocalizedError { + case invalidConfiguration + case unsupportedRequest(String) + case duplicateRequest + case shuttingDown + case tokenizerRewroteCommittedText + + public var errorDescription: String? { + switch self { + case .invalidConfiguration: "Invalid native block engine configuration." + case .unsupportedRequest(let field): "Unsupported native block request: \(field)." + case .duplicateRequest: "A request with this identifier is already active." + case .shuttingDown: "The native block engine is draining." + case .tokenizerRewroteCommittedText: "Tokenizer rewrote previously committed output." + } + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockEngine.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockEngine.swift new file mode 100644 index 0000000000..18cb161b5b --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockEngine.swift @@ -0,0 +1,771 @@ +import Foundation + +/// Native block execution behind the existing provider engine protocol. +/// Tensor/session state is confined to `queue`; cross-thread controls and +/// capacity counters are protected by `lock`. Requests are stepped round-robin. +/// This is concurrent admission, NOT a claim of rectangular GPU batch fusion. +public final class CBv2NativeBlockEngine: CBv2Engine, @unchecked Sendable { + // Stable across retained metadata; unlike an address, never recycled when + // an old engine dies before a transfer owner is rebound to a new engine. + let checkpointOwnerIdentity = UUID() + public typealias SessionFactory = + @Sendable ( + CBv2Request, CBv2NativeBlockCancellation + ) throws -> any CBv2NativeBlockSession + + private final class Control: @unchecked Sendable { + let request: CBv2Request + let generation = UUID() + let cancellation = CBv2NativeBlockCancellation() + let reservation: Int + let submitted = DispatchTime.now().uptimeNanoseconds + var output: CBv2OutputStream! + // Engine lock protects these fields. + var running = false + var paused = false + var retainedBytes = 0 + var sharedStorageBytes = 0 + var activeTokens = 0 + var watchdogReason: CBv2FinishReason? + var usageSnapshot: CBv2Usage + // Engine queue owns lease transitions; the timer never touches these. + var lease: CBv2RequestLeaseState + var completedWork = 0 + init(request: CBv2Request, reservation: Int, config: CBv2EngineLoopConfig) { + self.request = request + self.reservation = reservation + usageSnapshot = .init(promptTokens: request.promptTokens.count, completionTokens: 0) + let now = config.clock.now() + lease = config.useLegacyRequestTimeout ? .legacy(now: now, wall: config.requestTimeout) + : .init(now: now, admissionLease: config.admissionLease, + prefillLease: config.prefillProgressLease, decodeLease: config.decodeProgressLease, + backpressureLease: config.backpressureLease, + safety: CBv2SafetyCeiling.duration(promptTokens: request.promptTokens.count, + maxTokens: request.maxTokens, admissionLease: config.admissionLease, + decodeFloorTPS: config.safetyCeilingDecodeFloorTPS), + computedTokens: 0, generatedTokens: 0) + } + } + private final class Row { + let control: Control + let session: any CBv2NativeBlockSession + let decoder: CBv2NativeBlockTextDecoder + var timing = CBv2RequestTiming() + var committedTokens = 0 + // With caller stop strings, text may be stable before token ownership + // is: UTF-8/cleanup can hold a suffix across blocks. Defer raw IDs until + // terminal reconciliation so a later match never retracts prior IDs. + var pendingStopTokens = [Int]() + init(control: Control, session: any CBv2NativeBlockSession, tokenizer: any Tokenizer) { + self.control = control + self.session = session + decoder = CBv2NativeBlockTextDecoder( + tokenizer: tokenizer, stopStrings: control.request.stopStrings) + timing.admittedNanos = max(1, DispatchTime.now().uptimeNanoseconds &- control.submitted) + } + } + + private let lock = NSLock() + private let queue = DispatchQueue(label: "mlx.native-block-engine", qos: .userInitiated) + private let tokenizer: any Tokenizer + private let reservationForRequest: @Sendable (CBv2Request) throws -> Int + private let maxConcurrentRequests: Int + private let maxWaiting: Int + private let outputBufferCapacity: Int + private let shutdownGraceSeconds: Double + private let loopConfig: CBv2EngineLoopConfig + private let watchdogQueue = DispatchQueue(label: "mlx.native-block-watchdog", qos: .utility) + private var watchdogTimer: DispatchSourceTimer? + // Engine lock protects watchdog state, but never GPU/session arrays. + private var stepStartedAt: ContinuousClock.Instant? + private var watchdogWakeQueued = false + private var healthy = true + private var wedgeCallback: (@Sendable (TimeInterval) -> Void)? + public var isHealthy: Bool { lock.withLock { healthy } } + public var onStepWedge: (@Sendable (TimeInterval) -> Void)? { + get { lock.withLock { wedgeCallback } } + set { lock.withLock { wedgeCallback = newValue } } + } + private let sharedResources: CBv2NativeBlockSharedResources? + package let pagedMemory: CBv2NativeBlockPagedMemory? + private var pagedBackingBytes = 0 + public var usesPagedStorage: Bool { pagedMemory != nil } + public var usesProcessMemoryOwner: Bool { pagedMemory?.usesProcessMemoryOwner == true } + public let completeNativePrefixCache: (any CBv2NativeBlockPrefixCache)? + private let checkpointPlanner: CBv2NativeBlockCheckpointPlanner? + private var sharedRetainedBytes = 0 + private var sharedReservationBytes = 0 + private var checkpointReservationBytes = 0 + private var accepting = true + private var bytesCapacity: Int + private var controls = [CBv2RequestID: Control]() + private var stepsExecuted = 0 + private var stepWallNanos: UInt64 = 0 + private var decodedRows: UInt64 = 0 + // Queue-confined state, including the only factory/weight owner. + private var factory: SessionFactory? + private var waiting = [Control]() + private var rows = [Row]() + private var cursor = 0 + private var pumpScheduled = false + private var draining = false + private var shutdownWaiters = [CheckedContinuation]() + + public init( + tokenizer: any Tokenizer, kvBytesCapacity: Int, + maxConcurrentRequests: Int = 4, maxWaiting: Int = 64, outputBufferCapacity: Int = 8, + shutdownGraceSeconds: Double = 10, + loopConfig: CBv2EngineLoopConfig = .init(), + sharedResources: CBv2NativeBlockSharedResources? = nil, + pagedMemory: CBv2NativeBlockPagedMemory? = nil, + completeNativePrefixCache: (any CBv2NativeBlockPrefixCache)? = nil, + checkpointPlanner: CBv2NativeBlockCheckpointPlanner? = nil, + reservationForRequest: @escaping @Sendable (CBv2Request) throws -> Int, + makeSession: @escaping SessionFactory + ) throws { + guard kvBytesCapacity > 0, maxConcurrentRequests > 0, maxWaiting >= 0, + !maxConcurrentRequests.addingReportingOverflow(maxWaiting).overflow, + outputBufferCapacity > 0, shutdownGraceSeconds.isFinite, + shutdownGraceSeconds >= 0, shutdownGraceSeconds <= 3600 + else { throw CBv2NativeBlockError.invalidConfiguration } + let intervals = [loopConfig.requestTimeout, loopConfig.admissionLease, + loopConfig.prefillProgressLease, loopConfig.decodeProgressLease, + loopConfig.backpressureLease, loopConfig.stepTimeout] + guard intervals.allSatisfy({ $0.isFinite && $0 >= 0 && $0 <= 1e9 }), + loopConfig.watchdogInterval.isFinite, loopConfig.watchdogInterval > 0, + loopConfig.watchdogInterval <= 60, + loopConfig.safetyCeilingDecodeFloorTPS.isFinite, + loopConfig.safetyCeilingDecodeFloorTPS > 0 else { + throw CBv2NativeBlockError.invalidConfiguration + } + guard + sharedResources == nil + || (sharedResources!.maximumBytes > 0 + && sharedResources!.maximumBytes < kvBytesCapacity) + else { + throw CBv2NativeBlockError.invalidConfiguration + } + self.tokenizer = tokenizer + self.bytesCapacity = kvBytesCapacity + self.maxConcurrentRequests = maxConcurrentRequests + self.maxWaiting = maxWaiting + self.outputBufferCapacity = outputBufferCapacity + self.shutdownGraceSeconds = shutdownGraceSeconds + self.loopConfig = loopConfig + self.sharedResources = sharedResources + try pagedMemory?.claimEngine(capacity: kvBytesCapacity) + self.pagedMemory = pagedMemory + guard (completeNativePrefixCache == nil) == (checkpointPlanner == nil) else { + throw CBv2NativeBlockError.invalidConfiguration + } + self.completeNativePrefixCache = completeNativePrefixCache + self.checkpointPlanner = checkpointPlanner + self.sharedReservationBytes = sharedResources?.maximumBytes ?? 0 + if let pagedMemory, let sharedResources { + do { try pagedMemory.setSharedReservation(bytes: sharedResources.maximumBytes) } catch { + self.sharedReservationBytes = 0 + } + } + self.reservationForRequest = reservationForRequest + self.factory = makeSession + startWatchdog() + } + + public func submit(_ request: CBv2Request) throws -> AsyncStream { + try submitWithRetirement(request).events + } + + /// A terminal stream is not proof that a blocked native step released its + /// arrays. External memory/cache owners retain this exact generation's loan. + public func submitWithRetirement(_ request: CBv2Request) throws -> ( + events: AsyncStream, retirement: CBv2RequestRetirement + ) { + guard !request.promptTokens.isEmpty, request.maxTokens > 0, + request.stopStrings.allSatisfy({ !$0.isEmpty }) + else { + throw CBv2NativeBlockError.unsupportedRequest("prompt/output/stop bounds") + } + // Model-specific validation and a conservative full-request reservation + // happen BEFORE enqueue, including unimplemented sampler/media controls. + var request = request + let cacheCanBeFunded = lock.withLock { + sharedResources.map { + $0.maximumBytes < bytesCapacity + && (pagedMemory == nil || sharedReservationBytes >= $0.maximumBytes) + } ?? false + } + var coldRequest = request + coldRequest.prefixCacheEnabled = false + let coldBytes = try reservationForRequest(coldRequest) + let desired = cacheCanBeFunded ? try reservationForRequest(request) : coldBytes + let claimed = request.nativeReservationBytes ?? desired + guard claimed >= coldBytes else { + throw CBv2KVError.capacityExhausted(needed: coldBytes, available: max(0, claimed)) + } + if !cacheCanBeFunded || claimed < desired { request.prefixCacheEnabled = false } + let bytes = try reservationForRequest(request) + guard bytes > 0 else { throw CBv2NativeBlockError.invalidConfiguration } + let control = Control(request: request, reservation: bytes, config: loopConfig) + let generation = control.generation + control.output = CBv2OutputStream( + id: request.id, capacity: outputBufferCapacity, + onBackpressure: { [weak self] id, paused in + self?.setPaused(id, generation: generation, paused: paused) + }, + onAbandoned: { [weak self] id in + self?.cancel(id, generation: generation) + }) + try lock.withLock { + guard accepting, healthy else { throw CBv2NativeBlockError.shuttingDown } + guard controls[request.id] == nil else { throw CBv2NativeBlockError.duplicateRequest } + let reserved = controls.values.reduce( + sharedReservationBytes + checkpointReservationBytes + ) { $0 + $1.reservation } + guard controls.count < maxConcurrentRequests + maxWaiting, + bytes <= max(0, bytesCapacity - reserved) + else { + throw CBv2KVError.capacityExhausted( + needed: bytes, available: max(0, bytesCapacity - reserved)) + } + try pagedMemory?.reserve( + id: request.id, + tokens: request.promptTokens.count + request.maxTokens, totalBytes: bytes) + controls[request.id] = control + } + queue.async { [self] in + if draining { control.cancellation.cancel() } + waiting.append(control) + schedulePump() + } + return (control.output.makeStream(), .init(stream: control.output)) + } + + /// The provider's process-global ledger uses this SAME request estimate, + /// avoiding a second architecture formula that undercharges or double-counts. + public func estimatedRequestBytes(_ request: CBv2Request) throws -> Int { + var request = request + if !lock.withLock({ + sharedResources.map { + $0.maximumBytes < bytesCapacity + && (pagedMemory == nil || sharedReservationBytes >= $0.maximumBytes) + } ?? false + }) { + request.prefixCacheEnabled = false + } + return try reservationForRequest(request) + } + + public func cancel(_ id: CBv2RequestID) { cancel(id, generation: nil) } + + /// Independent transfer owners share the SAME slot grant as active + /// requests and resident cache. This does not create process-global credit; + /// provider I/O and destinations must also retain their process reservation. + public func reserveNativeCheckpoint(bytes: Int) throws -> CBv2NativeBlockCheckpointLease { + var pagedLease: CBv2CheckpointReservation? + try lock.withLock { + guard accepting, bytes > 0 else { throw CBv2NativeBlockError.shuttingDown } + let reserved = controls.values.reduce( + sharedReservationBytes + checkpointReservationBytes + ) { $0 + $1.reservation } + guard bytes <= max(0, bytesCapacity - reserved) else { + throw CBv2KVError.capacityExhausted( + needed: bytes, available: max(0, bytesCapacity - reserved)) + } + pagedLease = try pagedMemory?.reserveTransient(bytes: bytes) + checkpointReservationBytes += bytes + } + let retainedLease = pagedLease + return .init(bytes: bytes) { [weak self, retainedLease] in + retainedLease?.release() + guard let self else { return } + self.lock.withLock { self.checkpointReservationBytes -= bytes } + } + } + + public func reserveNativeCheckpointReadScratch() throws -> CBv2CompleteCheckpointIOLease { + if usesProcessMemoryOwner { + guard lock.withLock({ accepting }) else { throw CBv2NativeBlockError.shuttingDown } + // Provider-owned host I/O has its own global reservation. Native + // allocation receives a separate exact charge after authentication. + return .init(reservation: .init(onRelease: {}), usesProcessMemoryOwner: true) + } + let lease = try reserveNativeCheckpoint( + bytes: CBv2CompleteCheckpointManifest.maximumProviderScratchBytes) + return .init(reservation: .init { lease.close() }) + } + + func coverNativeCheckpointAllocation(bytes: Int) throws -> CBv2MemoryCoverage? { + try pagedMemory?.admission.coverEvaluatedAllocation(bytes: bytes) + } + + public func planNativeCheckpointImport( + manifest: CBv2CompleteCheckpointManifest, + request: CBv2Request + ) throws -> CBv2NativeBlockCheckpointImportPlan { + guard let checkpointPlanner, lock.withLock({ accepting }) else { + throw CBv2NativeBlockError.unsupportedRequest("native checkpoint import") + } + // Run the same full request validation as ordinary admission before + // creating any manifest/destination ownership. + _ = try reservationForRequest(request) + return try checkpointPlanner(manifest, request, self) + } + private func cancel(_ id: CBv2RequestID, generation: UUID?) { + lock.withLock { + if let control = controls[id], generation == nil || control.generation == generation { + control.cancellation.cancel() + } + } + queue.async { [self] in schedulePump() } + } + private func setPaused(_ id: CBv2RequestID, generation: UUID, paused: Bool) { + let now = loopConfig.clock.now() + lock.withLock { + guard let control = controls[id], control.generation == generation else { return } + control.paused = paused + } + queue.async { [self] in + guard let control = lock.withLock({ controls[id] }), + control.generation == generation, + lock.withLock({ control.paused == paused }) else { return } + if paused { control.lease.markPaused(now: now) } + else { control.lease.markResumed(now: now) } + schedulePump() + } + } + public func capacity() -> CBv2CapacitySnapshot { + lock.withLock { + let active = controls.values.filter(\.running).count + return CBv2CapacitySnapshot( + activeRequests: active, waitingRequests: controls.count - active, + kvBytesInUse: controls.values.reduce( + sharedRetainedBytes + checkpointReservationBytes + pagedBackingBytes + ) { + $0 + $1.retainedBytes - $1.sharedStorageBytes + }, + kvBytesCapacity: bytesCapacity, kvBytesBackendCapacity: bytesCapacity, + kvBytesReserved: pagedMemory?.reservedBytes + ?? controls.values.reduce(sharedReservationBytes + checkpointReservationBytes) { + $0 + $1.reservation + }, + activeTokens: controls.values.reduce(0) { $0 + $1.activeTokens }, + stepsExecuted: stepsExecuted, stepWallNanosTotal: stepWallNanos, + decodeRowsTotal: decodedRows) + } + } + var pausedRequestCountForTesting: Int { lock.withLock { controls.values.filter(\.paused).count } } + public func updateKVBytesCapacity(_ bytes: Int) { + lock.withLock { + bytesCapacity = max(0, bytes) + pagedMemory?.updateCapacity(bytesCapacity) + if let sharedResources, sharedResources.maximumBytes < bytesCapacity, accepting { + if pagedMemory == nil { + sharedReservationBytes = max( + sharedReservationBytes, sharedResources.maximumBytes) + } else if (try? pagedMemory?.setSharedReservation( + bytes: sharedResources.maximumBytes)) != nil + { + sharedReservationBytes = max( + sharedReservationBytes, sharedResources.maximumBytes) + } + } + // Do not release an old cache promise until its actual trim. + } + queue.async { [self] in reconcileSharedResources() } + } + + private func reconcileSharedResources() { + if let pagedMemory { + let backing = pagedMemory.backend.bytesWired + lock.withLock { pagedBackingBytes = backing } + } + guard let sharedResources else { return } + if draining && lock.withLock({ controls.isEmpty }) { + sharedResources.clear() + try? pagedMemory?.setSharedReservation(bytes: 0) + lock.withLock { + sharedRetainedBytes = 0 + sharedReservationBytes = 0 + } + return + } + let capacity = lock.withLock { bytesCapacity } + var budget = sharedResources.maximumBytes < capacity ? sharedResources.maximumBytes : 0 + if budget > 0, let pagedMemory { + do { try pagedMemory.setSharedReservation(bytes: budget) } catch { budget = 0 } + } + sharedResources.trim(budget) + let retained = max(0, sharedResources.retainedBytes()) + if budget == 0 && retained == 0 { try? pagedMemory?.setSharedReservation(bytes: 0) } + lock.withLock { + sharedRetainedBytes = retained + let latestBudget = + sharedResources.maximumBytes < bytesCapacity ? sharedResources.maximumBytes : 0 + if latestBudget == budget || (pagedMemory != nil && budget == 0) { + sharedReservationBytes = max(budget, retained) + } else { + sharedReservationBytes = max(sharedReservationBytes, latestBudget, retained) + queue.async { [self] in reconcileSharedResources() } + } + } + } + + private func schedulePump() { + guard !pumpScheduled else { return } + let runnable = + !waiting.isEmpty + || rows.contains { row in + row.control.cancellation.isCancelled || !lock.withLock { row.control.paused } + } + guard runnable else { + completeDrainIfIdle() + return + } + pumpScheduled = true + queue.async { [self] in pump() } + } + private func pump() { + pumpScheduled = false + reconcileSharedResources() + expireLeases() + for control in waiting where control.cancellation.isCancelled { + finishWaiting(control, reason: terminalReason(control) ?? .cancelled) + } + waiting.removeAll { $0.cancellation.isCancelled } + for row in rows where row.control.cancellation.isCancelled { + finish(row, reason: terminalReason(row.control) ?? .cancelled) + } + waiting.sort { + $0.request.priority == $1.request.priority + ? $0.submitted < $1.submitted : $0.request.priority > $1.request.priority + } + while rows.count < maxConcurrentRequests, !waiting.isEmpty { + let control = waiting.removeFirst() + // The independent watchdog may have cancelled the waiting cohort + // while a preceding session factory was blocked. + if control.cancellation.isCancelled { + finishWaiting(control, reason: terminalReason(control) ?? .cancelled) + continue + } + guard let factory else { + finishWaiting(control, reason: .cancelled) + continue + } + do { + control.lease.markAdmitted(now: loopConfig.clock.now()) + beginQuantum() + let row = Row( + control: control, session: try factory(control.request, control.cancellation), + tokenizer: tokenizer) + endQuantum() + rows.append(row) + lock.withLock { control.running = true } + } catch { + endQuantum() + finishWaiting(control, reason: terminalReason(control) ?? .error("native_block_initialization_failed")) + } + } + expireLeases() + guard !rows.isEmpty else { + completeDrainIfIdle() + return + } + var selected: Row? + for _ in 0 ..< rows.count { + cursor %= rows.count + let row = rows[cursor] + cursor = (cursor + 1) % rows.count + if !lock.withLock({ row.control.paused }) { + selected = row + break + } + } + guard let row = selected else { + completeDrainIfIdle() + return + } + let before = DispatchTime.now().uptimeNanoseconds + do { + if row.control.cancellation.isCancelled { + finish(row, reason: terminalReason(row.control) ?? .cancelled) + schedulePump() + return + } + beginQuantum() + let step = try row.session.advanceNative() + endQuantum() + let ended = DispatchTime.now().uptimeNanoseconds + guard row.session.retainedBytes >= 0, + row.session.retainedBytes <= row.control.reservation, + row.session.sharedStorageBytes >= 0, + row.session.sharedStorageBytes <= row.session.retainedBytes + else { + throw CBv2KVError.capacityExhausted( + needed: row.session.retainedBytes, available: row.control.reservation) + } + let physicalPages = pagedMemory?.backend.bytesWired ?? 0 + lock.withLock { + stepsExecuted += 1 + pagedBackingBytes = physicalPages + stepWallNanos &+= ended &- before + row.control.retainedBytes = row.session.retainedBytes + row.control.sharedStorageBytes = row.session.sharedStorageBytes + row.control.activeTokens = row.session.activeTokenCount + } + row.timing.stepLatencyNanosSum &+= ended &- before + row.timing.stepLatencyNanosMax = max(row.timing.stepLatencyNanosMax, ended &- before) + row.timing.batchRowsSum += 1 + row.timing.batchRowsMin = 1 + row.timing.batchRowsMax = 1 + expireLeases() + if row.control.cancellation.isCancelled { + finish(row, reason: terminalReason(row.control) ?? .cancelled) + } else { + try consume(step, row: row, before: before, ended: ended) + // Confirmed work refreshes liveness without turning a draft + // canvas into a generated token or public stream event. + row.control.completedWork += 1 + let phase: CBv2RequestLeaseState.Phase + if case .prefill(_, let complete) = step { phase = complete ? .decode : .prefill } + else { phase = .decode } + row.control.lease.recordNativeProgress(now: loopConfig.clock.now(), + phase: phase, completedWork: row.control.completedWork) + var usage = row.session.prefixUsage + usage.promptTokens = row.control.request.promptTokens.count + usage.completionTokens = row.committedTokens + usage.timing = row.timing + lock.withLock { row.control.usageSnapshot = usage } + } + } catch is CancellationError { + endQuantum() + finish(row, reason: terminalReason(row.control) ?? .cancelled) + } catch { + endQuantum() + finish(row, reason: terminalReason(row.control) ?? .error("native_block_execution_failed")) + } + reconcileSharedResources() + schedulePump() + } + + private func consume(_ step: CBv2NativeBlockStep, row: Row, before: UInt64, ended: UInt64) + throws + { + switch step { + case .prefill(let computed, let complete): + guard row.session.generatedTokenCount == row.committedTokens else { + throw CBv2NativeBlockError.unsupportedRequest("provisional token accounting") + } + if row.timing.prefillFirstLaunchNanos == 0 { + row.timing.prefillFirstLaunchNanos = max(1, before &- row.control.submitted) + row.timing.kvAllocatedNanos = row.timing.prefillFirstLaunchNanos + } + if computed > 0 { row.timing.prefillChunks += 1 } + row.timing.prefillChunkTokensMax = max( + row.timing.prefillChunkTokensMax, UInt32(clamping: computed)) + if complete { row.timing.promptComputedNanos = max(1, ended &- row.control.submitted) } + case .progress: + guard row.session.generatedTokenCount == row.committedTokens else { + throw CBv2NativeBlockError.unsupportedRequest("provisional token accounting") + } + case .committed(let tokens, let stopToken, let finishReason): + let raw = tokens + (stopToken.map { [$0] } ?? []) + guard raw.allSatisfy({ $0 >= 0 }), + raw.count <= row.control.request.maxTokens - row.committedTokens, + row.session.generatedTokenCount == row.committedTokens + raw.count, + finishReason == nil || finishReason == .stop || finishReason == .length + else { + throw CBv2NativeBlockError.unsupportedRequest("committed block accounting") + } + row.committedTokens += raw.count + let defersTokens = !row.control.request.stopStrings.isEmpty + if defersTokens { row.pendingStopTokens.append(contentsOf: raw) } + if !raw.isEmpty { + if row.timing.firstTokenNanos == 0 { + row.timing.firstTokenNanos = max(1, ended &- row.control.submitted) + } else { + row.timing.decodeSteps += 1 + lock.withLock { decodedRows += 1 } + } + } + let text = try row.decoder.append(tokens, terminal: finishReason != nil) + var deliveredTokens = defersTokens ? [] : raw + if row.decoder.matchedStopString { + guard let count = row.decoder.stopTokenCount, + count > 0, count <= row.pendingStopTokens.count else { + throw CBv2NativeBlockError.unsupportedRequest("stop output accounting") + } + row.committedTokens = count + deliveredTokens = Array(row.pendingStopTokens.prefix(count)) + row.pendingStopTokens.removeAll() + } else if finishReason != nil && defersTokens { + deliveredTokens = row.pendingStopTokens + row.pendingStopTokens.removeAll() + } + if !deliveredTokens.isEmpty || !text.isEmpty { + row.control.output.emit(.delta(text: text, tokens: deliveredTokens, logprobs: nil)) + } + if row.decoder.matchedStopString { + finish(row, reason: .stop) + } else if let finishReason { + finish(row, reason: finishReason) + } + } + } + private func finishWaiting(_ control: Control, reason: CBv2FinishReason) { + pagedMemory?.release(id: control.request.id) + retireControl(control) + control.output.releaseEngineOwnership() + control.output.finish( + reason: reason, + usage: .init(promptTokens: control.request.promptTokens.count, completionTokens: 0)) + } + private func finish(_ row: Row, reason: CBv2FinishReason) { + // Cancellation/error can end a request between committed blocks. Flush + // only previously finalized IDs, never the session's provisional canvas. + // A matched stop already clipped and consumed this buffer above. + if !row.pendingStopTokens.isEmpty { + row.control.output.emit(.delta(text: "", tokens: row.pendingStopTokens, logprobs: nil)) + row.pendingStopTokens.removeAll() + } + let completion = row.committedTokens + var usage = row.session.prefixUsage + row.session.finish(reason: reason) + row.session.cancel() + rows.removeAll { $0 === row } + pagedMemory?.release(id: row.control.request.id) + retireControl(row.control) + row.timing.finishedNanos = max( + 1, DispatchTime.now().uptimeNanoseconds &- row.control.submitted) + usage.promptTokens = row.control.request.promptTokens.count + usage.completionTokens = completion + usage.timing = row.timing + reconcileSharedResources() + row.control.output.releaseEngineOwnership() + row.control.output.finish(reason: reason, usage: usage) + } + + /// Reject new work and cancel queued requests. Running requests may drain; + /// after the grace interval cancellation is observed at the next quantum. + /// Never report release while an in-flight device quantum still owns state. + public func shutdown() async { + lock.withLock { accepting = false } + // Providers normally close first, but direct SDK owners must also + // cancel pending transfers. Never call user/store code under our lock. + completeNativePrefixCache?.close() + await withCheckedContinuation { continuation in + queue.async { [self] in + draining = true + shutdownWaiters.append(continuation) + waiting.forEach { $0.cancellation.cancel() } + queue.asyncAfter(deadline: .now() + shutdownGraceSeconds) { [weak self] in + guard let self, self.draining else { return } + self.rows.forEach { $0.control.cancellation.cancel() } + self.schedulePump() + } + schedulePump() + completeDrainIfIdle() + } + } + } + private func completeDrainIfIdle() { + guard draining, lock.withLock({ controls.isEmpty }) else { return } + watchdogTimer?.cancel() + factory = nil + sharedResources?.clear() + try? pagedMemory?.setSharedReservation(bytes: 0) + lock.withLock { + sharedRetainedBytes = 0 + sharedReservationBytes = 0 + pagedBackingBytes = pagedMemory?.backend.bytesWired ?? 0 + } + let waiters = shutdownWaiters + shutdownWaiters.removeAll() + waiters.forEach { $0.resume() } + } + + private func retireControl(_ control: Control) { + lock.withLock { + controls.removeValue(forKey: control.request.id) + if controls.isEmpty, stepStartedAt == nil { healthy = true } + } + } + + private func terminalReason(_ control: Control) -> CBv2FinishReason? { + lock.withLock { control.watchdogReason } + } + + /// Engine-queue-only lease scan. A blocked GPU quantum is handled by the + /// independent watchdog; ordinary progress expiry retires at a safe boundary. + private func expireLeases() { + let now = loopConfig.clock.now() + for control in lock.withLock({ Array(controls.values) }) { + guard !control.cancellation.isCancelled, + let cause = control.lease.expiredCause(now: now, + isRunning: lock.withLock({ control.running }), + isPaused: lock.withLock({ control.paused })) else { continue } + let reason: CBv2FinishReason = cause == .legacyRequestTimeout + ? .error("request exceeded \(Int(loopConfig.requestTimeout))s deadline") + : .terminal(cause: cause, message: cause.diagnostic) + lock.withLock { control.watchdogReason = reason } + control.cancellation.cancel() + } + } + + private func beginQuantum() { lock.withLock { stepStartedAt = loopConfig.clock.now() } } + private func endQuantum() { + // A delayed polling callback cannot excuse an already-overdue quantum. + watchdogTick(scheduleWake: false) + lock.withLock { stepStartedAt = nil } + } + + private func startWatchdog() { + let timer = DispatchSource.makeTimerSource(queue: watchdogQueue) + timer.schedule(deadline: .now() + loopConfig.watchdogInterval, repeating: loopConfig.watchdogInterval) + timer.setEventHandler { [weak self] in self?.watchdogTick() } + timer.resume() + watchdogTimer = timer + } + + private func watchdogTick(scheduleWake: Bool = true) { + var terminals: [(Control, CBv2Usage)] = [] + var callback: (@Sendable (TimeInterval) -> Void)? + var elapsed = 0.0 + let wake = lock.withLock { + if let start = stepStartedAt, healthy { + let duration = loopConfig.clock.now() - start + elapsed = Double(duration.components.seconds) + Double(duration.components.attoseconds) / 1e18 + if elapsed > loopConfig.stepTimeout { + healthy = false + callback = wedgeCallback + for control in controls.values { + control.watchdogReason = .terminal(cause: .watchdog, message: CBv2TerminalCause.watchdog.diagnostic) + control.cancellation.cancel() + terminals.append((control, control.usageSnapshot)) + } + } + } + guard scheduleWake, !controls.isEmpty, !watchdogWakeQueued else { return false } + watchdogWakeQueued = true + return true + } + callback?(elapsed) + for (control, usage) in terminals { + // No row/page/refund mutation on this thread. The retirement handle + // stays unacknowledged until the owning engine queue actually drains. + control.output.finish(reason: .terminal(cause: .watchdog, + message: CBv2TerminalCause.watchdog.diagnostic), usage: usage) + } + if wake { + queue.async { [weak self] in + guard let self else { return } + self.lock.withLock { self.watchdogWakeQueued = false } + // All rows may be paused, so schedulePump's runnable predicate + // alone cannot drive lease expiry. Scan before asking it to run. + self.expireLeases() + self.schedulePump() + } + } + } + + deinit { watchdogTimer?.cancel() } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockPagedExecution.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockPagedExecution.swift new file mode 100644 index 0000000000..4895a312fe --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockPagedExecution.swift @@ -0,0 +1,27 @@ +import MLX + +extension PagedKVBackend { + /// Same failed-write boundary used by the AR scheduler, scoped to a native + /// block step. Callers retire the failed request's rows before reusing them; + /// resetting a fence is not a rollback of already-executed ring writes. + package func performNativeBlockStep(_ body: () throws -> Result, onFailure: () -> Void) + throws -> Result + { + let boundary = CBv2PagedWriteBoundary(pool: pool) + do { + return try MLX.withError { errors in + try pool.writeValidation.check() + let value = try body() + try pool.writeValidation.check() + try errors.check() + return value + } + } catch { + StreamOrDevice.default.stream.synchronize() + boundary.discardFailedGraphAfterSynchronization() + onFailure() + pool.writeValidation.clearAfterRetirement() + throw error + } + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockPagedMemory.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockPagedMemory.swift new file mode 100644 index 0000000000..808a490017 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockPagedMemory.swift @@ -0,0 +1,105 @@ +import Foundation + +/// Native blocks share the existing AdmissionV2 physical-floor and process +/// ledger. Nominal request pages overlap the pool's actual backing; canvas, +/// snapshot and transfer obligations remain additive. Only its owning native +/// engine queue may materialize or retire backend rows. +public final class CBv2NativeBlockPagedMemory: @unchecked Sendable { + package let backend: PagedKVBackend + package let admission: AdmissionV2 + public let usesProcessMemoryOwner: Bool + private let lock = NSLock() + private var sharedReservation: CBv2CheckpointReservation? + private var sharedBytes = 0 + private var engineClaimed = false + + package init( + layerKinds: [CBv2LayerKind], configuration: PagedKVPoolConfig, + processMemoryOwner: (any CBv2ProcessMemoryOwner)? + ) throws { + guard configuration.segmentSizeBytes != nil, configuration.capacityBytes > 0, + let dtypes = configuration.layerDTypes, dtypes.count == layerKinds.count + else { throw CBv2NativeBlockError.invalidConfiguration } + backend = try PagedKVBackend(layerKinds: layerKinds, config: configuration) + admission = AdmissionV2( + layerKinds: layerKinds, bytesCapacity: configuration.capacityBytes, + config: .init( + watermarkFraction: 0, elementBytes: configuration.dtype.size, + layerElementBytes: dtypes.map(\.size)), + residency: backend.kvResidency, processMemoryOwner: processMemoryOwner) + backend.pool.bindAdmission(admission) + usesProcessMemoryOwner = processMemoryOwner != nil + } + + /// Immutable-geometry projection; safe on the submitting thread. Only the + /// target page portion may overlap shared pool backing. + package func nominalBytes(tokens: Int) -> Int { admission.allocatedBytes(forTokens: tokens) } + + func claimEngine(capacity: Int) throws { + try lock.withLock { + guard !engineClaimed, admission.bytesCapacity == capacity else { + throw CBv2NativeBlockError.invalidConfiguration + } + engineClaimed = true + } + } + + package func reserve(id: CBv2RequestID, tokens: Int, totalBytes: Int) throws { + let nominal = nominalBytes(tokens: tokens) + guard tokens > 0, nominal >= 0, totalBytes >= nominal else { + throw CBv2NativeBlockError.invalidConfiguration + } + guard + let overhead = backend.pool.minimumSegmentedOverhead( + tokens: tokens, layerKinds: backend.layerKinds) + else { + throw CBv2NativeBlockError.invalidConfiguration + } + let (extra, overflow) = (totalBytes - nominal).addingReportingOverflow(overhead) + guard !overflow, + admission.canEverFit(promptTokens: tokens, maxTokens: 0, additionalBackendBytes: extra) + else { + throw CBv2KVError.capacityExhausted( + needed: overflow ? Int.max : totalBytes, + available: admission.admissibleBytesCapacity) + } + try admission.reserve( + id: id, additionalTokens: tokens, additionalBytes: totalBytes - nominal) + } + + package func release(id: CBv2RequestID) { admission.releaseAll(id: id) } + + func reserveTransient(bytes: Int) throws -> CBv2CheckpointReservation { + try admission.reserveTransient(bytes: bytes) + } + + /// The cache partition switches between its configured maximum and zero. + /// Shrinks happen only after queue-confined trim drops the actual owners. + /// A failed growth preserves the old charge and must leave capture disabled. + package func setSharedReservation(bytes: Int) throws { + try lock.withLock { + guard bytes >= 0 else { throw CBv2NativeBlockError.invalidConfiguration } + if bytes == sharedBytes { return } + if bytes == 0 { + sharedReservation?.release() + sharedReservation = nil + sharedBytes = 0 + return + } + guard sharedBytes == 0 else { throw CBv2NativeBlockError.invalidConfiguration } + sharedReservation = try admission.reserveTransient(bytes: bytes) + sharedBytes = bytes + } + } + + package func updateCapacity(_ bytes: Int) { + admission.updateBytesCapacity(max(0, bytes)) + backend.updateBytesCapacity(max(0, bytes)) + } + + public var reservedBytes: Int { admission.bytesReserved } + + // Do not explicitly retire Admission's process owner at engine shutdown: + // an authenticated transfer may still own buffers/leases after the last + // model request. The owner retires when its final real lease has drained. +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockPrefixCache.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockPrefixCache.swift new file mode 100644 index 0000000000..5921c62f02 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockPrefixCache.swift @@ -0,0 +1,20 @@ +import Foundation + +/// Provider-owned encrypted I/O and single-use native stage tickets. The +/// engine consumes already-authenticated state; it never reads disk on its +/// execution queue. This is deliberately separate from the AR cache protocol. +public protocol CBv2NativeBlockPrefixCache: AnyObject, Sendable { + var identity: CBv2CompleteCheckpointIdentity { get } + func acceptsCheckpoint(position: Int, packedBytes: Int) -> Bool + func takeNativeStaged(requestID: CBv2RequestID, tokens: [Int], cacheSalt: String?, + maximumSequenceLength: Int) -> CBv2NativeBlockCheckpoint? + /// Always close source before completion, including refusal/cancellation. + /// The engine's independent donor lease retires in that completion. + func donate(_ source: CBv2CompleteCheckpointExport, requestID: CBv2RequestID?, + tokens: [Int], cacheSalt: String?, completion: @escaping @Sendable ([Int]) -> Void) + func close() +} + +public typealias CBv2NativeBlockCheckpointPlanner = @Sendable ( + CBv2CompleteCheckpointManifest, CBv2Request, CBv2NativeBlockEngine +) throws -> CBv2NativeBlockCheckpointImportPlan diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockTextDecoder.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockTextDecoder.swift new file mode 100644 index 0000000000..7f339e2c00 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/NativeBlockTextDecoder.swift @@ -0,0 +1,78 @@ +import Foundation + +/// Decode complete committed blocks together, preserving tokenizer cleanup +/// inside a block. Hold trailing whitespace/incomplete UTF-8 until it is stable +/// across the next block; never repair or re-emit already-published bytes. +/// Unexpected non-boundary rewrites are recoverable errors, not corrupted JSON. +public final class CBv2NativeBlockTextDecoder { + private let tokenizer: any Tokenizer + private let holdback: StopHoldback + private let stopScalars: [[Unicode.Scalar]] + private var tokens = [Int]() + private var emitted = [UInt8]() + public private(set) var matchedStopString = false + /// Original token prefix through the token completing the selected stop. + /// A final token can contain additional bytes; tokens cannot be split or + /// recovered by re-encoding the displayed prefix. + public private(set) var stopTokenCount: Int? + + public init(tokenizer: any Tokenizer, stopStrings: [String]) { + self.tokenizer = tokenizer + self.holdback = StopHoldback(stopStrings: stopStrings) + self.stopScalars = stopStrings.filter { !$0.isEmpty }.map { Array($0.unicodeScalars) } + } + + public func append(_ block: [Int], terminal: Bool = false) throws -> String { + guard !matchedStopString else { return "" } + tokens.append(contentsOf: block) + let decoded = tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) + var scalars = Array(decoded.unicodeScalars) + if !terminal { + while let last = scalars.last, + last.value == 0xfffd || last.properties.isWhitespace + { + scalars.removeLast() + } + } + let bytes = Array(String(String.UnicodeScalarView(scalars)).utf8) + guard bytes.starts(with: emitted) else { + throw CBv2NativeBlockError.tokenizerRewroteCommittedText + } + let delta = String(decoding: bytes.dropFirst(emitted.count), as: UTF8.self) + emitted = bytes + let scan = holdback.ingest(delta) + matchedStopString = scan.stopped + if scan.stopped { stopTokenCount = try tokenBoundaryThroughStop(in: scalars) } + return scan.text + (terminal && !scan.stopped ? holdback.flush() : "") + } + + private func tokenBoundaryThroughStop(in scalars: [Unicode.Scalar]) throws -> Int { + // Match the holdback's exact scalar semantics, not Foundation's + // canonically equivalent string search. Earliest start wins; for + // overlapping stops at that start, use the first completed delimiter. + var selected: (start: Int, end: Int)? + for stop in stopScalars where stop.count <= scalars.count { + for start in 0...(scalars.count - stop.count) { + guard scalars[start..<(start + stop.count)].elementsEqual(stop) else { continue } + let end = start + stop.count + if selected == nil || start < selected!.start + || (start == selected!.start && end < selected!.end) { + selected = (start, end) + } + break + } + } + guard let selected, !tokens.isEmpty else { + throw CBv2NativeBlockError.unsupportedRequest("stop boundary") + } + let prefix = Array(String(String.UnicodeScalarView(scalars[.. 1, chunkSize > 1, - position % chunkSize == 0, prefixTokens.count == position, + position > 1, (backendLayout == Self.diffusionBlockLayout ? chunkSize > 0 : chunkSize > 1), + ((backendLayout == Self.diffusionBlockLayout && mediaIdentity != nil) + || position % chunkSize == 0), prefixTokens.count == position, position <= Self.maximumEncodedBytes / 2, prefixTokens.allSatisfy({ $0 >= 0 && $0 <= Int(Int32.max) }), !tensors.isEmpty, tensors.count <= 4096, @@ -185,6 +192,14 @@ public struct CBv2CompleteCheckpointManifest: Codable, Sendable, Equatable { (assistantCodecID?.utf8.count ?? 0) <= 512, !mediaTargetOnly || (mediaIdentity != nil && assistantCodecID == nil) else { throw CBv2CompleteCheckpointError.invalidManifest } + if backendLayout == Self.diffusionBlockLayout { + guard let nativeBlockState, assistantCodecID == nil, !mediaTargetOnly else { + throw CBv2CompleteCheckpointError.invalidManifest + } + try nativeBlockState.validate() + } else if nativeBlockState != nil { + throw CBv2CompleteCheckpointError.invalidManifest + } var total = 0 var roles = Set() for tensor in tensors { diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointManifestCoding.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointManifestCoding.swift index 821ff4e31f..3e4e4b9d2d 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointManifestCoding.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointManifestCoding.swift @@ -4,23 +4,35 @@ extension CBv2CompleteCheckpointManifest { private enum CodingKeys: String, CodingKey { case schemaVersion, identity, backendLayout, position, chunkSize case prefixTokens, cacheSalt, assistantCodecID, tensors, attentionLayers - case mediaIdentity, mediaTargetOnly + case mediaIdentity, mediaTargetOnly, nativeBlockState, packedPrefixTokens } public init(from decoder: any Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) + let backendLayout = try values.decode(String.self, forKey: .backendLayout) + let position = try values.decode(Int.self, forKey: .position) + let tokens: [Int] + if backendLayout == Self.diffusionBlockLayout { + guard !values.contains(.prefixTokens) else { throw CBv2CompleteCheckpointError.invalidManifest } + tokens = try values.decode(CBv2NativeBlockPackedTokens.self, forKey: .packedPrefixTokens) + .unpack(count: position) + } else { + guard !values.contains(.packedPrefixTokens) else { throw CBv2CompleteCheckpointError.invalidManifest } + tokens = try values.decode([Int].self, forKey: .prefixTokens) + } self.init( schemaVersion: try values.decode(Int.self, forKey: .schemaVersion), identity: try values.decode(CBv2CompleteCheckpointIdentity.self, forKey: .identity), - backendLayout: try values.decode(String.self, forKey: .backendLayout), - position: try values.decode(Int.self, forKey: .position), + backendLayout: backendLayout, + position: position, chunkSize: try values.decode(Int.self, forKey: .chunkSize), cacheSalt: try values.decodeIfPresent(String.self, forKey: .cacheSalt), assistantCodecID: try values.decodeIfPresent(String.self, forKey: .assistantCodecID), mediaIdentity: try values.decodeIfPresent(CBv2HybridPrefixIdentity.self, forKey: .mediaIdentity), mediaTargetOnly: try values.decodeIfPresent(Bool.self, forKey: .mediaTargetOnly) ?? false, + nativeBlockState: try values.decodeIfPresent(CBv2NativeBlockCheckpointState.self, forKey: .nativeBlockState), metadata: .init( - tokens: try values.decode([Int].self, forKey: .prefixTokens), + tokens: tokens, tensors: try values.decode([CBv2CheckpointTensorDescriptor].self, forKey: .tensors), attentionLayers: try values.decodeIfPresent([CBv2CheckpointAttentionLayer].self, forKey: .attentionLayers))) } @@ -32,11 +44,16 @@ extension CBv2CompleteCheckpointManifest { try values.encode(backendLayout, forKey: .backendLayout) try values.encode(position, forKey: .position) try values.encode(chunkSize, forKey: .chunkSize) - try values.encode(prefixTokens, forKey: .prefixTokens) + if backendLayout == Self.diffusionBlockLayout { + try values.encode(CBv2NativeBlockPackedTokens(tokens: prefixTokens), forKey: .packedPrefixTokens) + } else { + try values.encode(prefixTokens, forKey: .prefixTokens) + } try values.encodeIfPresent(cacheSalt, forKey: .cacheSalt) try values.encodeIfPresent(assistantCodecID, forKey: .assistantCodecID) try values.encodeIfPresent(mediaIdentity, forKey: .mediaIdentity) if mediaTargetOnly { try values.encode(true, forKey: .mediaTargetOnly) } + try values.encodeIfPresent(nativeBlockState, forKey: .nativeBlockState) try values.encode(tensors, forKey: .tensors) try values.encodeIfPresent(attentionLayers, forKey: .attentionLayers) } @@ -47,6 +64,7 @@ extension CBv2CompleteCheckpointManifest { && lhs.chunkSize == rhs.chunkSize && lhs.prefixTokens == rhs.prefixTokens && lhs.cacheSalt == rhs.cacheSalt && lhs.assistantCodecID == rhs.assistantCodecID && lhs.mediaIdentity == rhs.mediaIdentity && lhs.mediaTargetOnly == rhs.mediaTargetOnly + && lhs.nativeBlockState == rhs.nativeBlockState && lhs.tensors == rhs.tensors && lhs.attentionLayers == rhs.attentionLayers } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointManifestMemory.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointManifestMemory.swift index 4a1e239d04..1ffce2c308 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointManifestMemory.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointManifestMemory.swift @@ -10,14 +10,24 @@ final class CBv2CheckpointManifestMemory: @unchecked Sendable { final class Permit: @unchecked Sendable { let admission: ObjectIdentifier + let nativeOwner: UUID? let bytes: Int private let reservation: CBv2CheckpointReservation init(admission: AdmissionV2, position: Int) throws { self.bytes = try CBv2CheckpointManifestMemory.reservationBytes(position: position) self.admission = ObjectIdentifier(admission) + self.nativeOwner = nil self.reservation = try admission.reserveTransient(bytes: bytes) } + + init(nativeEngine: CBv2NativeBlockEngine, position: Int) throws { + self.bytes = try CBv2CheckpointManifestMemory.reservationBytes(position: position) + self.admission = ObjectIdentifier(nativeEngine) + self.nativeOwner = nativeEngine.checkpointOwnerIdentity + let lease = try nativeEngine.reserveNativeCheckpoint(bytes: bytes) + self.reservation = CBv2CheckpointReservation { lease.close() } + } } /// A conservative host allocation envelope, NOT exact stdlib heap usage. @@ -52,10 +62,16 @@ final class CBv2CheckpointManifestMemory: @unchecked Sendable { } extension CBv2CompleteCheckpointManifest { + func owningNativeMetadata(engine: CBv2NativeBlockEngine) throws -> Self { + if metadata.permit?.nativeOwner == engine.checkpointOwnerIdentity { return self } + let permit = try CBv2CheckpointManifestMemory.Permit(nativeEngine: engine, position: position) + return replacingMetadata(.init(tokens: prefixTokens, tensors: tensors, attentionLayers: attentionLayers, permit: permit)) + } + /// The provider still holds its I/O envelope during this ownership handoff. /// Replanning on the same loaded engine reuses the existing native owner. func owningMetadata(admission: AdmissionV2) throws -> Self { - if metadata.permit?.admission == ObjectIdentifier(admission) { return self } + if metadata.permit?.nativeOwner == nil && metadata.permit?.admission == ObjectIdentifier(admission) { return self } let permit = try CBv2CheckpointManifestMemory.Permit(admission: admission, position: position) return replacingMetadata(.init(tokens: prefixTokens, tensors: tensors, attentionLayers: attentionLayers, permit: permit)) } diff --git a/Libraries/MLXLMCommon/DiffusionGemmaCompiledSampler.swift b/Libraries/MLXLMCommon/DiffusionGemmaCompiledSampler.swift new file mode 100644 index 0000000000..9244f42e31 --- /dev/null +++ b/Libraries/MLXLMCommon/DiffusionGemmaCompiledSampler.swift @@ -0,0 +1,135 @@ +// Native DiffusionGemma sampling operations, with unchanged arithmetic and RNG. +import Cmlx +import Foundation +import MLX + +enum DiffusionGemmaCompiledSampler { + // Private qualification candidate. Unset/0 retains the original sampler. + static let enabled = ProcessInfo.processInfo.environment[ + "DARKBLOOM_DIFFUSION_COMPILED_SAMPLER"] == "1" + + static func eligible( + logits: MLXArray, canvas: MLXArray, embeddingDType: DType, + configuration: DiffusionGemmaGenerationConfiguration + ) -> Bool { + guard enabled, Device.defaultDevice().deviceType == .gpu, + StreamOrDevice.default.stream == Stream.gpu, + logits.shape == [1, 256, 262144], logits.dtype == .float32, + canvas.shape == [1, 256], canvas.dtype == .int32, embeddingDType == .float32, + configuration.stabilityThreshold == 1, + configuration.sampler.entropyBound == Float(0.1), + configuration.confidenceThreshold == Float(0.005) + else { return false } + return [logits, canvas].allSatisfy { array in + var identity: UInt = 0 + var ordinary = false + return _mlx_array_constant_cache_identity(&identity, &ordinary, array.ctx) == 0 + && ordinary + } + } + + // Bounded immutable functions capture flags only. All request arrays and + // randomness are explicit inputs. MLX owns compilation/evaluation locking; + // never hold a separate lock while entering one of these functions. + private static let functions: [@Sendable ([MLXArray]) -> [MLXArray]] = + (0..<16).map { flags in + compile { arrays in + graph(arrays, greedy: flags & 1 != 0, hasPrevious: flags & 2 != 0, + hasHistory: flags & 4 != 0, lastStep: flags & 8 != 0) + } + } + + static func call( + _ arrays: [MLXArray], greedy: Bool, hasPrevious: Bool, hasHistory: Bool, + lastStep: Bool + ) -> [MLXArray] { + let flags = (greedy ? 1 : 0) | (hasPrevious ? 2 : 0) + | (hasHistory ? 4 : 0) | (lastStep ? 8 : 0) + let result = functions[flags](arrays) + if result.count == 10 { DiffusionGemmaCompiledSamplerDiagnostics.recordDispatch() } + return result + } + + // Use the same integer primitive as native MLX uniform sampling. Keep its + // floating constants as graph inputs: the pinned literal printer rounds them. + static func randomBits(shape: [Int], key: MLXArray) -> MLXArray { + var result = mlx_array_new() + let dimensions = shape.map(Int32.init) + dimensions.withUnsafeBufferPointer { pointer in + _ = mlx_random_bits( + &result, pointer.baseAddress, pointer.count, 4, key.ctx, + StreamOrDevice.default.ctx) + } + return MLXArray(result) + } + + // Inputs: processed logits, random bits, native noise, canvas, argmax, + // finished, counts, conditioning, history, scaled logits, denominator, + // exclusive upper bound and the exact finite-log clamp. + private static func graph( + _ a: [MLXArray], greedy: Bool, hasPrevious: Bool, hasHistory: Bool, + lastStep: Bool + ) -> [MLXArray] { + let processed = a[0], finished = a[5] + let sampled: MLXArray + if greedy { + sampled = processed.argMax(axis: -1).asType(.int32) + } else { + // Same promotion/divide/clamp/affine/Gumbel construction as + // mlx/random.cpp, with no lossy printed RNG constants. + let uniform = Float(1) * minimum(a[1] / a[10], a[11]).asType(.float32) + Float(0) + let gumbel = -log(-log(uniform)) + sampled = (gumbel + a[9]).argMax(axis: -1).asType(.int32) + } + let logProbabilities = processed - processed.logSumExp(axis: -1, keepDims: true) + let finiteLog = maximum(logProbabilities, a[12]) + let entropy = -(exp(logProbabilities) * finiteLog).sum(axis: -1) + let order = argSort(entropy, axis: -1) + let sorted = takeAlong(entropy, order, axis: -1) + let accepted = sorted.cumsum(axis: -1) - sorted .<= Float(0.1) + let acceptance = putAlong(MLXArray.zeros(like: accepted), order, values: accepted, axis: -1) + let proposed = which(acceptance, sampled, a[2]) + let argmax = processed.argMax(axis: -1).asType(.int32) + let nextCanvas = which(finished[0..., .newAxis], a[3], proposed) + let nextArgmax = which(finished[0..., .newAxis], a[4], argmax) + let stable = hasHistory ? (a[8] .== nextArgmax).all(axis: -1) + : MLXArray.zeros([processed.dim(0)], dtype: .bool) + let completed = logicalOr(finished, logicalAnd(stable, entropy.mean(axis: -1) .< Float(0.005))) + let conditioning = hasPrevious + ? which(finished[0..., .newAxis, .newAxis], a[7], processed).asType(.float32) + : processed.asType(.float32) + let steps = a[6] + logicalNot(finished).asType(.int32) + let nextFinished = lastStep ? MLXArray.ones(like: completed) : completed + let validSample = logicalAnd(sampled .>= 0, sampled .< processed.dim(-1)).all() + let validNoise = logicalAnd(a[2] .>= 0, a[2] .< processed.dim(-1)).all() + return [nextCanvas, nextArgmax, nextFinished, conditioning, steps, acceptance, + sampled, a[2], validSample, validNoise] + } +} + +/// Explicitly armed diagnostics only; ordinary serving does not collect counts. +@_spi(DiffusionGemmaDiagnostics) +public enum DiffusionGemmaCompiledSamplerDiagnostics { + public struct Snapshot: Sendable, Equatable { + public let armed: Bool + public let calls: Int + } + private final class State: @unchecked Sendable { + let lock = NSLock() + var armed = false + var calls = 0 + } + private static let state = State() + public static func clearAndArm() { + state.lock.withLock { state.calls = 0; state.armed = true } + } + public static func snapshot() -> Snapshot { + state.lock.withLock { Snapshot(armed: state.armed, calls: state.calls) } + } + public static func snapshotAndDisarm() -> Int { + state.lock.withLock { state.armed = false; return state.calls } + } + static func recordDispatch() { + state.lock.withLock { if state.armed { state.calls += 1 } } + } +} diff --git a/Libraries/MLXLMCommon/DiffusionGemmaGenerationConfiguration.swift b/Libraries/MLXLMCommon/DiffusionGemmaGenerationConfiguration.swift new file mode 100644 index 0000000000..849e120545 --- /dev/null +++ b/Libraries/MLXLMCommon/DiffusionGemmaGenerationConfiguration.swift @@ -0,0 +1,209 @@ +// DiffusionGemma generation contract, based on the Apache-2.0 Transformers reference: +// https://github.com/huggingface/transformers/blob/c587bc884db2c2e31fc2b8102314656b17aa07b1/src/transformers/models/diffusion_gemma/generation_diffusion_gemma.py + +import Foundation + +/// Native block-diffusion controls. These are not autoregressive sampling settings. +/// In particular, the default output budget is not the model's context capacity. +/// Configuration decoding does not register or qualify a model implementation. +public struct DiffusionGemmaGenerationConfiguration: Codable, Sendable, Equatable { + public struct EntropyBoundSampler: Codable, Sendable, Equatable { + public let className: String + public let entropyBound: Float + + enum CodingKeys: String, CodingKey, CaseIterable { + case className = "_cls_name" + case entropyBound = "entropy_bound" + } + + public init(entropyBound: Float = 0.1) throws { + guard entropyBound.isFinite, entropyBound > 0 else { + throw DiffusionGemmaGenerationError.invalidConfiguration("entropy_bound") + } + self.className = "EntropyBoundSamplerConfig" + self.entropyBound = entropyBound + } + + public init(from decoder: Decoder) throws { + let keys = try decoder.container(keyedBy: AnyKey.self) + let supported = Set(CodingKeys.allCases.map(\.rawValue)) + for key in keys.allKeys where !supported.contains(key.stringValue) { + throw DiffusionGemmaGenerationError.unsupportedField( + "sampler_config." + key.stringValue) + } + let values = try decoder.container(keyedBy: CodingKeys.self) + let name = try values.decode(String.self, forKey: .className) + guard name == "EntropyBoundSamplerConfig" else { + throw DiffusionGemmaGenerationError.unsupportedSampler(name) + } + try self.init(entropyBound: values.decode(Float.self, forKey: .entropyBound)) + } + } + + public let maxNewTokens: Int + public let maxLength: Int? + public let maxDenoisingSteps: Int + public let sampler: EntropyBoundSampler + public let minimumTemperature: Float + public let maximumTemperature: Float + public let stabilityThreshold: Int + public let confidenceThreshold: Float + public let bosTokenId: Int? + public let padTokenId: Int? + public let eosTokenIds: [Int]? + + enum CodingKeys: String, CodingKey, CaseIterable { + case maxNewTokens = "max_new_tokens" + case maxLength = "max_length" + case maxDenoisingSteps = "max_denoising_steps" + case sampler = "sampler_config" + case minimumTemperature = "t_min" + case maximumTemperature = "t_max" + case stabilityThreshold = "stability_threshold" + case confidenceThreshold = "confidence_threshold" + case bosTokenId = "bos_token_id" + case padTokenId = "pad_token_id" + case eosTokenIds = "eos_token_id" + } + + public init( + maxNewTokens: Int = 256, + maxLength: Int? = nil, + maxDenoisingSteps: Int = 48, + sampler: EntropyBoundSampler? = nil, + minimumTemperature: Float = 0.4, + maximumTemperature: Float = 0.8, + stabilityThreshold: Int = 1, + confidenceThreshold: Float = 0.005, + bosTokenId: Int? = nil, + padTokenId: Int? = nil, + eosTokenIds: [Int]? = nil + ) throws { + guard maxNewTokens > 0 else { + throw DiffusionGemmaGenerationError.invalidConfiguration("max_new_tokens") + } + if let maxLength, maxLength <= 0 { + throw DiffusionGemmaGenerationError.invalidConfiguration("max_length") + } + guard maxDenoisingSteps > 0 else { + throw DiffusionGemmaGenerationError.invalidConfiguration("max_denoising_steps") + } + guard minimumTemperature.isFinite, minimumTemperature >= 0, + maximumTemperature.isFinite, maximumTemperature > minimumTemperature + else { + throw DiffusionGemmaGenerationError.invalidConfiguration("t_min/t_max") + } + guard stabilityThreshold >= 0 else { + throw DiffusionGemmaGenerationError.invalidConfiguration("stability_threshold") + } + guard confidenceThreshold.isFinite, confidenceThreshold > 0 else { + throw DiffusionGemmaGenerationError.invalidConfiguration("confidence_threshold") + } + let specialIds = [bosTokenId, padTokenId].compactMap { $0 } + (eosTokenIds ?? []) + guard specialIds.allSatisfy({ $0 >= 0 }) else { + throw DiffusionGemmaGenerationError.invalidConfiguration("special_token_ids") + } + self.maxNewTokens = maxNewTokens + self.maxLength = maxLength + self.maxDenoisingSteps = maxDenoisingSteps + self.sampler = try sampler ?? EntropyBoundSampler() + self.minimumTemperature = minimumTemperature + self.maximumTemperature = maximumTemperature + self.stabilityThreshold = stabilityThreshold + self.confidenceThreshold = confidenceThreshold + self.bosTokenId = bosTokenId + self.padTokenId = padTokenId + self.eosTokenIds = eosTokenIds + } + + public init(from decoder: Decoder) throws { + let keys = try decoder.container(keyedBy: AnyKey.self) + let supported = Set(CodingKeys.allCases.map(\.rawValue)) + let metadata: Set = ["transformers_version", "_commit_hash", "_from_model_config"] + for key in keys.allKeys + where !supported.contains(key.stringValue) + && !metadata.contains(key.stringValue) + { + // Unsupported runtime/cache/sampling controls must not disappear + // silently. Add support together with its execution and tests. + throw DiffusionGemmaGenerationError.unsupportedField(key.stringValue) + } + let values = try decoder.container(keyedBy: CodingKeys.self) + let eos: [Int]? + if try !values.contains(.eosTokenIds) || values.decodeNil(forKey: .eosTokenIds) { + eos = nil + } else if let single = try? values.decode(Int.self, forKey: .eosTokenIds) { + eos = [single] + } else { + eos = try values.decode([Int].self, forKey: .eosTokenIds) + } + try self.init( + maxNewTokens: values.decodeIfPresent(Int.self, forKey: .maxNewTokens) ?? 256, + maxLength: values.decodeIfPresent(Int.self, forKey: .maxLength), + maxDenoisingSteps: values.decodeIfPresent(Int.self, forKey: .maxDenoisingSteps) ?? 48, + sampler: values.decodeIfPresent(EntropyBoundSampler.self, forKey: .sampler), + minimumTemperature: values.decodeIfPresent(Float.self, forKey: .minimumTemperature) + ?? 0.4, + maximumTemperature: values.decodeIfPresent(Float.self, forKey: .maximumTemperature) + ?? 0.8, + stabilityThreshold: values.decodeIfPresent(Int.self, forKey: .stabilityThreshold) ?? 1, + confidenceThreshold: values.decodeIfPresent(Float.self, forKey: .confidenceThreshold) + ?? 0.005, + bosTokenId: values.decodeIfPresent(Int.self, forKey: .bosTokenId), + padTokenId: values.decodeIfPresent(Int.self, forKey: .padTokenId), + eosTokenIds: eos) + } + + /// `remainingStep` counts down N...1, as in the native reference. The final + /// evaluated step uses t_min + (t_max - t_min)/N, not exactly t_min. + public func temperature(remainingStep: Int) throws -> Float { + guard (1 ... maxDenoisingSteps).contains(remainingStep) else { + throw DiffusionGemmaGenerationError.invalidRemainingStep(remainingStep) + } + return minimumTemperature + + (maximumTemperature - minimumTemperature) + * (Float(remainingStep) / Float(maxDenoisingSteps)) + } + + /// Match the pinned native reference's length precedence: max_length takes + /// effect when max_new_tokens has its default value256, including explicit256. + public func outputTokenLimit(promptTokenCount: Int) throws -> Int { + guard promptTokenCount >= 0 else { + throw DiffusionGemmaGenerationError.invalidConfiguration("prompt length") + } + let limit = + (maxLength != nil && maxNewTokens == 256) + ? maxLength! - promptTokenCount : maxNewTokens + guard limit > 0 else { + throw DiffusionGemmaGenerationError.invalidConfiguration("output length") + } + return limit + } + + private struct AnyKey: CodingKey { + let stringValue: String + let intValue: Int? = nil + init?(stringValue: String) { self.stringValue = stringValue } + init?(intValue: Int) { return nil } + } +} + +public enum DiffusionGemmaGenerationError: Error, Sendable, Equatable, LocalizedError { + case invalidConfiguration(String) + case unsupportedSampler(String) + case unsupportedField(String) + case invalidRemainingStep(Int) + + public var errorDescription: String? { + switch self { + case .invalidConfiguration(let field): + "Invalid DiffusionGemma generation value for \(field)." + case .unsupportedSampler(let name): + "Unsupported DiffusionGemma sampler: \(name)." + case .unsupportedField(let field): + "Unsupported DiffusionGemma generation field: \(field)." + case .invalidRemainingStep(let step): + "DiffusionGemma denoising step \(step) is outside the configured countdown." + } + } +} diff --git a/Libraries/MLXLMCommon/DiffusionGemmaPrefillGeometry.swift b/Libraries/MLXLMCommon/DiffusionGemmaPrefillGeometry.swift new file mode 100644 index 0000000000..d260582381 --- /dev/null +++ b/Libraries/MLXLMCommon/DiffusionGemmaPrefillGeometry.swift @@ -0,0 +1,74 @@ +import Foundation + +/// Pure native cold-prefill geometry. Whole bidirectional media blocks may +/// move a boundary away from the nominal chunk grid; restored state must land +/// on the same boundary the current request would compute from cold. +public struct DiffusionGemmaPrefillGeometry: Sendable { + public let promptCount: Int + public let chunkSize: Int + public let boundaries: [Int] + public let capturePositions: Set + public let lastStableBoundary: Int? + public let lastAlignedStableBoundary: Int? + + public init(promptCount: Int, chunkSize: Int, spans: [CBv2ImageSpan] = []) throws { + guard promptCount > 0, chunkSize > 0, promptCount <= Int.max - chunkSize else { + throw CBv2NativeBlockError.unsupportedRequest("native prefill geometry") + } + var blocks = [CBv2ImageSpan]() + var previousEnd = 0 + for span in spans { + guard span.tokenOffset >= previousEnd, span.tokenOffset < promptCount, + span.length > 0, span.length <= 1120, + span.length <= promptCount - span.tokenOffset else { + throw CBv2NativeBlockError.unsupportedRequest("native media prefix geometry") + } + if let index = blocks.indices.last, + blocks[index].tokenOffset + blocks[index].length == span.tokenOffset { + guard blocks[index].length <= 1120 - span.length else { + throw CBv2NativeBlockError.unsupportedRequest("native visual block budget") + } + blocks[index].length += span.length + } else { blocks.append(span) } + previousEnd = span.tokenOffset + span.length + } + var ends = [Int](), stable = [Int](), start = 0 + while start < promptCount { + var naturalEnd = start + chunkSize + for block in blocks where block.tokenOffset < naturalEnd + && block.tokenOffset + block.length > naturalEnd { + naturalEnd = block.tokenOffset > start ? block.tokenOffset : block.tokenOffset + block.length + } + let end = min(naturalEnd, promptCount) + guard end > start else { throw CBv2NativeBlockError.unsupportedRequest("native prefill progress") } + ends.append(end) + if naturalEnd <= promptCount { stable.append(end) } + start = end + } + self.promptCount = promptCount + self.chunkSize = chunkSize + self.boundaries = ends + self.lastStableBoundary = stable.last + self.lastAlignedStableBoundary = stable.last { $0 % chunkSize == 0 } + self.capturePositions = Set([ends.first, stable.last, lastAlignedStableBoundary, promptCount].compactMap { $0 }) + } + + public func permitsRestore(position: Int) -> Bool { boundaries.contains(position) } + + /// Native media storage may address exact cold boundaries rather than an AR + /// token grid. A truncated final chunk is still not a stable branch point + /// for appended input, even when its position coincidentally aligns. + public func permitsPersistentCapture(position: Int) -> Bool { + position > 0 + && position <= (lastStableBoundary ?? 0) && boundaries.contains(position) + } + + public func chunkLength(start: Int) throws -> Int { + if start == promptCount { return 0 } + guard start >= 0, start == 0 || boundaries.contains(start), + let end = boundaries.first(where: { $0 > start }) else { + throw CBv2NativeBlockError.unsupportedRequest("native restore splits cold quantum") + } + return end - start + } +} diff --git a/Libraries/MLXLMCommon/DiffusionGemmaSampler.swift b/Libraries/MLXLMCommon/DiffusionGemmaSampler.swift new file mode 100644 index 0000000000..4746c963c4 --- /dev/null +++ b/Libraries/MLXLMCommon/DiffusionGemmaSampler.swift @@ -0,0 +1,254 @@ +// Native entropy-bound block diffusion. Algorithm reference: +// Transformers c587bc884db2c2e31fc2b8102314656b17aa07b1, generation_diffusion_gemma.py. +// See docs/diffusiongemma/implementation-references.md for provenance and scope. + +import Foundation +import MLX + +/// Numerical operations shared by the native runner and fixed-noise tests. +/// This sampler accepts/refines a whole canvas; it is not an AR token sampler. +public enum DiffusionGemmaSampling { + public static func tokenEntropy(_ processedLogits: MLXArray) throws -> MLXArray { + guard processedLogits.ndim == 3, processedLogits.shape.allSatisfy({ $0 > 0 }), + processedLogits.dtype.isFloatingPoint + else { throw DiffusionGemmaSamplingError.invalidShape("logits") } + let logits = processedLogits.asType(.float32) + let logProbabilities = logits - logits.logSumExp(axis: -1, keepDims: true) + // As in torch.distributions.Categorical, zero-probability masked entries + // contribute zero rather than 0 * -infinity. All-masked rows remain + // invalid and are rejected by the native request/logit validation gate. + let finiteLog = maximum(logProbabilities, -Float.greatestFiniteMagnitude) + return -(exp(logProbabilities) * finiteLog).sum(axis: -1) + } + + /// Select the largest lowest-entropy prefix whose sum excluding its maximum + /// is <= the configured bound. Selection is recomputed on every step. + public static func acceptanceMask(entropy: MLXArray, bound: Float) throws -> MLXArray { + guard entropy.ndim == 2, entropy.shape.allSatisfy({ $0 > 0 }), + entropy.dtype.isFloatingPoint, bound.isFinite, bound > 0 + else { throw DiffusionGemmaSamplingError.invalidShape("entropy/bound") } + let order = argSort(entropy, axis: -1) + let sorted = takeAlong(entropy, order, axis: -1) + let accepted = sorted.cumsum(axis: -1) - sorted .<= bound + return putAlong(MLXArray.zeros(like: accepted), order, values: accepted, axis: -1) + } +} + +/// Request-owned denoising state. The model's shared weights never own this object. +/// A caller may observe intermediate tensors for diagnostics, but may publish only +/// `finalizedCanvas()`. Prefix-cache mutation belongs after that commit boundary. +public final class DiffusionGemmaDenoisingState { + public let configuration: DiffusionGemmaGenerationConfiguration + public let vocabularySize: Int + public let embeddingDType: DType + public private(set) var currentCanvas: MLXArray + public private(set) var argmaxCanvas: MLXArray + public private(set) var selfConditioningLogits: MLXArray? + public private(set) var finishedRows: MLXArray + public private(set) var stepsUsed: MLXArray + public private(set) var remainingSteps: Int + private var argmaxHistory: [MLXArray] = [] + + /// Conservative live payload accounting (aliases may be counted twice), + /// separate from allocator/workspace and measured process footprint. + public var retainedPayloadBytes: Int { + ([currentCanvas, argmaxCanvas, finishedRows, stepsUsed] + argmaxHistory + + [selfConditioningLogits].compactMap { $0 }).reduce(0) { $0 + $1.nbytes } + } + + public init( + initialCanvas: MLXArray, + vocabularySize: Int, + embeddingDType: DType, + configuration: DiffusionGemmaGenerationConfiguration + ) throws { + guard initialCanvas.ndim == 2, initialCanvas.shape.allSatisfy({ $0 > 0 }), + initialCanvas.dtype == .int32 || initialCanvas.dtype == .uint32, + vocabularySize > 0, vocabularySize <= Int(Int32.max), embeddingDType.isFloatingPoint + else { throw DiffusionGemmaSamplingError.invalidShape("initial canvas") } + guard logicalAnd(initialCanvas .>= 0, initialCanvas .< vocabularySize).all().item(Bool.self) + else { + throw DiffusionGemmaSamplingError.invalidToken + } + self.configuration = configuration + self.vocabularySize = vocabularySize + self.embeddingDType = embeddingDType + self.currentCanvas = initialCanvas + self.argmaxCanvas = initialCanvas + self.finishedRows = MLXArray.zeros([initialCanvas.dim(0)], dtype: .bool) + self.stepsUsed = MLXArray.zeros([initialCanvas.dim(0)], dtype: .int32) + self.remainingSteps = configuration.maxDenoisingSteps + } + + /// Sampling/noise callbacks provide a deterministic injection seam. The native + /// runner supplies request-local RNG; independent fixtures provide fixed draws. + /// `sample` receives the already temperature-processed logits exactly once. + @discardableResult + public func step( + rawLogits: MLXArray, + sample: (MLXArray) throws -> MLXArray, + noise: () throws -> MLXArray + ) throws -> MLXArray { + guard remainingSteps > 0 else { throw DiffusionGemmaSamplingError.exhaustedCanvas } + guard rawLogits.shape == currentCanvas.shape + [vocabularySize], + rawLogits.dtype.isFloatingPoint + else { throw DiffusionGemmaSamplingError.invalidShape("decoder logits") } + let temperature = try configuration.temperature(remainingStep: remainingSteps) + let processed = rawLogits.asType(.float32) / temperature + let finite = isFinite(processed) + let validDistribution = logicalAnd( + logicalOr(finite, processed .== -Float.infinity).all(), + finite.any(axis: -1).all()) + guard validDistribution.item(Bool.self) else { + throw DiffusionGemmaSamplingError.invalidDistribution + } + let sampled = try sample(processed) + let randomCanvas = try noise() + for (name, value) in [("sampled canvas", sampled), ("noise canvas", randomCanvas)] { + guard value.shape == currentCanvas.shape, value.dtype == currentCanvas.dtype else { + throw DiffusionGemmaSamplingError.invalidShape(name) + } + guard logicalAnd(value .>= 0, value .< vocabularySize).all().item(Bool.self) else { + throw DiffusionGemmaSamplingError.invalidToken + } + } + let entropy = try DiffusionGemmaSampling.tokenEntropy(processed) + let acceptance = try DiffusionGemmaSampling.acceptanceMask( + entropy: entropy, bound: configuration.sampler.entropyBound) + let proposed = which(acceptance, sampled, randomCanvas) + let proposedArgmax = processed.argMax(axis: -1).asType(currentCanvas.dtype) + let rowMask = finishedRows[0..., .newAxis] + let nextCanvas = which(rowMask, currentCanvas, proposed) + let nextArgmax = which(rowMask, argmaxCanvas, proposedArgmax) + + var stable = MLXArray.ones([currentCanvas.dim(0)], dtype: .bool) + if configuration.stabilityThreshold > 0 { + if argmaxHistory.count < configuration.stabilityThreshold { + stable = MLXArray.zeros(like: stable) + } else { + for previous in argmaxHistory { + stable = logicalAnd(stable, (previous .== nextArgmax).all(axis: -1)) + } + } + } + let confident = entropy.mean(axis: -1) .< configuration.confidenceThreshold + let completed = logicalOr(finishedRows, logicalAnd(stable, confident)) + // Preserve a row's last self-conditioning exactly after it finishes, even + // while peers continue. Cast as the official generation contract does. + let nextConditioning: MLXArray + if let previous = selfConditioningLogits { + nextConditioning = which(finishedRows[0..., .newAxis, .newAxis], previous, processed) + .asType(embeddingDType) + } else { + nextConditioning = processed.asType(embeddingDType) + } + + // Mutate only after every throwable input/callback check has succeeded. + stepsUsed = stepsUsed + logicalNot(finishedRows).asType(.int32) + currentCanvas = nextCanvas + argmaxCanvas = nextArgmax + selfConditioningLogits = nextConditioning + remainingSteps -= 1 + finishedRows = remainingSteps == 0 ? MLXArray.ones(like: completed) : completed + if configuration.stabilityThreshold > 0 { + argmaxHistory.append(nextArgmax) + if argmaxHistory.count > configuration.stabilityThreshold { + argmaxHistory.removeFirst() + } + } + return acceptance + } + + /// Native request-local sampling. The arbitrary-callback `step` contract is + /// unchanged; this entrypoint may compile only the known native operations. + /// `nextKey` is invoked after distribution validation, in the original order. + @discardableResult + public func stepNative( + rawLogits: MLXArray, samplingTemperature: Float, + nextKey: () -> MLXArray + ) throws -> MLXArray { + guard samplingTemperature.isFinite, samplingTemperature >= 0 else { + throw DiffusionGemmaSamplingError.invalidShape("sampling temperature") + } + guard DiffusionGemmaCompiledSampler.eligible( + logits: rawLogits, canvas: currentCanvas, embeddingDType: embeddingDType, + configuration: configuration) + else { + return try step( + rawLogits: rawLogits, + sample: { processed in + if samplingTemperature == 0 { return processed.argMax(axis: -1).asType(.int32) } + return MLXRandom.categorical(processed / samplingTemperature, key: nextKey()).asType(.int32) + }, noise: { + MLXRandom.randInt(Int32(0).. 0 else { throw DiffusionGemmaSamplingError.exhaustedCanvas } + guard rawLogits.shape == currentCanvas.shape + [vocabularySize] else { + throw DiffusionGemmaSamplingError.invalidShape("decoder logits") + } + let temperature = try configuration.temperature(remainingStep: remainingSteps) + let processed = rawLogits.asType(.float32) / temperature + return try MLX.withError { errors in + let finite = isFinite(processed) + let valid = logicalAnd(logicalOr(finite, processed .== -Float.infinity).all(), + finite.any(axis: -1).all()).item(Bool.self) + try errors.check() + guard valid else { throw DiffusionGemmaSamplingError.invalidDistribution } + // A greedy draw consumes no key, exactly as the original session. + let sampleBits = samplingTemperature == 0 ? MLXArray(UInt32(0)) + : DiffusionGemmaCompiledSampler.randomBits(shape: processed.shape, key: nextKey()) + let randomCanvas = MLXRandom.randInt( + Int32(0).. 1 { argmaxHistory.removeFirst() } + return result[5] + } + } + + public func finalizedCanvas() throws -> MLXArray { + guard finishedRows.all().item(Bool.self) else { + throw DiffusionGemmaSamplingError.canvasNotFinal + } + return argmaxCanvas + } +} + +public enum DiffusionGemmaSamplingError: Error, Sendable, Equatable { + case invalidShape(String) + case exhaustedCanvas + case canvasNotFinal + case invalidDistribution + case invalidToken +} diff --git a/Libraries/MLXLMCommon/DiffusionGemmaTokenizerConfiguration.swift b/Libraries/MLXLMCommon/DiffusionGemmaTokenizerConfiguration.swift new file mode 100644 index 0000000000..36e70330bc --- /dev/null +++ b/Libraries/MLXLMCommon/DiffusionGemmaTokenizerConfiguration.swift @@ -0,0 +1,68 @@ +import CoreFoundation +import Foundation + +/// The released Gemma tokenizer preserves decoded whitespace by default. +/// swift-transformers otherwise assumes cleanup=true when the key is absent, +/// which changes literal punctuation and quoted tool values after generation. +/// Resolve this family default in memory, not by rewriting checkpoint files. +public enum DiffusionGemmaTokenizerConfiguration { + public struct Inputs: Sendable { + private let configuration: Data + private let data: Data + + fileprivate init(configuration: Data, data: Data) { + self.configuration = configuration + self.data = data + } + + public func configurationDictionary() throws -> [NSString: Any] { + try DiffusionGemmaTokenizerConfiguration.dictionary(configuration) + } + + public func dataDictionary() throws -> [NSString: Any] { + try DiffusionGemmaTokenizerConfiguration.dictionary(data) + } + } + + /// nil leaves every other processor on the existing loader path. The + /// processor identity also works for a separate tokenizer-only directory. + public static func load(from directory: URL) throws -> Inputs? { + let configurationURL = directory.appendingPathComponent("tokenizer_config.json") + guard FileManager.default.fileExists(atPath: configurationURL.path) else { return nil } + var configuration = try dictionary(Data(contentsOf: configurationURL)) + guard configuration["processor_class"] as? String == "DiffusionGemma4Processor" else { + return nil + } + guard let tokenizerClass = configuration["tokenizer_class"] as? String, + ["GemmaTokenizer", "GemmaTokenizerFast"].contains(tokenizerClass) + else { throw CocoaError(.coderReadCorrupt) } + if let explicit = configuration["clean_up_tokenization_spaces"] { + guard CFGetTypeID(explicit as CFTypeRef) == CFBooleanGetTypeID() else { + throw CocoaError(.coderReadCorrupt) + } + } else { + configuration["clean_up_tokenization_spaces"] = false + } + // Preserve the existing local loader's external-template precedence. + let jinja = directory.appendingPathComponent("chat_template.jinja") + let json = directory.appendingPathComponent("chat_template.json") + if FileManager.default.fileExists(atPath: jinja.path) { + configuration["chat_template"] = try String(contentsOf: jinja, encoding: .utf8) + } else if FileManager.default.fileExists(atPath: json.path), + let template = try dictionary(Data(contentsOf: json))["chat_template"] as? String + { + configuration["chat_template"] = template + } + return Inputs(configuration: try JSONSerialization.data(withJSONObject: configuration), + data: try Data(contentsOf: directory.appendingPathComponent("tokenizer.json"))) + } + + private static func dictionary(_ data: Data) throws -> [NSString: Any] { + // NSString keys preserve binary-distinct Unicode vocabulary entries, + // matching the upstream Hub configuration reader. + guard let value = try JSONSerialization.jsonObject(with: data) as? [NSString: Any] else { + throw CocoaError(.coderReadCorrupt) + } + return value + } +} diff --git a/Libraries/MLXLMCommon/SwiftJinjaSyntaxCompatibility.swift b/Libraries/MLXLMCommon/SwiftJinjaSyntaxCompatibility.swift new file mode 100644 index 0000000000..c491a916c7 --- /dev/null +++ b/Libraries/MLXLMCommon/SwiftJinjaSyntaxCompatibility.swift @@ -0,0 +1,20 @@ +import Foundation + +/// Syntax-only compatibility with Python Jinja's whitespace controls. +/// Mirrors the existing DarkBloom ProviderCoreFoundation normalizer's comment +/// and literal-brace rules. Request clock binding remains with the provider. +/// This transforms template syntax, never message content or generated output. +public enum SwiftJinjaSyntaxCompatibility { + public static func normalize(_ template: String) -> String { + var result = template + result = result.replacingOccurrences( + of: #"-#\}\s*"#, with: "#}", options: .regularExpression) + result = result.replacingOccurrences( + of: #"\s*\{#-"#, with: "{#", options: .regularExpression) + result = result.replacingOccurrences( + of: #"\{\s+\{\{-"#, with: "{{ '{' -}}{{-", options: .regularExpression) + result = result.replacingOccurrences( + of: #"\{\s+\{%-"#, with: "{{ '{' -}}{%-", options: .regularExpression) + return result + } +} diff --git a/Libraries/MLXLMCommon/Tool/GemmaToolFrameScanner.swift b/Libraries/MLXLMCommon/Tool/GemmaToolFrameScanner.swift new file mode 100644 index 0000000000..bde4243f90 --- /dev/null +++ b/Libraries/MLXLMCommon/Tool/GemmaToolFrameScanner.swift @@ -0,0 +1,38 @@ +/// Incremental native Gemma framing: an end tag inside a marker-quoted or +/// JSON-quoted argument is data, not a frame terminator. +struct GemmaToolFrameScanner { + private enum Quote { case none, json, native(String) } + private var quote = Quote.none + private var escaped = false + private var candidate = "" + private let end = "" + private let markers = ["<|\"|>", ""] + + mutating func consume(_ scalar: Unicode.Scalar) -> Bool { + let character = String(scalar) + switch quote { + case .json: + if escaped { escaped = false } + else if character == "\\" { escaped = true } + else if character == "\"" { quote = .none } + return false + case .native(let marker): + candidate += character + if candidate.hasSuffix(marker) { quote = .none; candidate = "" } + else if candidate.count > marker.count { candidate = String(candidate.suffix(marker.count)) } + return false + case .none: + if candidate.isEmpty && character != "<" { + if character == "\"" { quote = .json } + return false + } + candidate += character + if candidate == end { return true } + if markers.contains(candidate) { quote = .native(candidate); candidate = ""; return false } + if ([end] + markers).contains(where: { $0.hasPrefix(candidate) }) { return false } + candidate = character == "<" ? "<" : "" + if character == "\"" { quote = .json } + return false + } + } +} diff --git a/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift b/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift index 8bed944e9e..f3c4ce47f1 100644 --- a/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift +++ b/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift @@ -12,8 +12,9 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable { public let startTag: String? = "<|tool_call>" public let endTag: String? = "" - public let alternateStartTags: [String] = [""] - public let alternateEndTags: [String] = [""] + public var alternateStartTags: [String] { strict ? [] : [""] } + public var alternateEndTags: [String] { strict ? [] : [""] } + private let strict: Bool private let quoteMarkers = ["<|\"|>", ""] private let wrapperTags = [ @@ -23,14 +24,19 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable { "", ] - public init() {} + public init(strict: Bool = false) { self.strict = strict } public func parse(content: String, tools: [[String: any Sendable]]?) -> ToolCall? { // Strip tags if present. Gemma 4 emits the newer `<|tool_call>` form, // while older Gemma-family templates use ``. var text = content.trimmingCharacters(in: .whitespacesAndNewlines) - for tag in wrapperTags { - text = text.replacingOccurrences(of: tag, with: "") + if strict { + guard text.hasPrefix("<|tool_call>"), text.hasSuffix("") else { return nil } + text = String(text.dropFirst("<|tool_call>".count).dropLast("".count)) + .trimmingCharacters(in: .whitespacesAndNewlines) + guard text.hasPrefix("call:"), text.hasSuffix("}") else { return nil } + } else { + for tag in wrapperTags { text = text.replacingOccurrences(of: tag, with: "") } } // Pattern: call:(\w+)\{(.*?)\} @@ -66,6 +72,7 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable { } guard !declaredNames.isEmpty else { return rawName } if declaredNames.contains(rawName) { return rawName } + if strict { return nil } // Repair only a unique, nearby declared name. This covers observed // Gemma token glitches without turning arbitrary text into a tool call. @@ -103,13 +110,14 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable { tools: [[String: any Sendable]]? ) -> [String: JSONValue]? { let schema = argumentSchema(funcName: funcName, tools: tools) - var strict = GemmaArgumentValueParser(text) - if let parsed = strict.parseTopLevelArguments(), - strict.isAtEnd, + var parser = GemmaArgumentValueParser(text, rejectDuplicates: strict) + if let parsed = parser.parseTopLevelArguments(), + parser.isAtEnd, schema.allowsAdditional || parsed.keys.allSatisfy(schema.names.contains) { return parsed } + if strict { return nil } // Historical unconstrained auto output is intentionally accepted by // the bounded compatibility parser below (missing markers, comma- @@ -146,6 +154,14 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable { allowsAdditional: parameters["additionalProperties"] as? Bool != false) } + public func parseEOS(_ content: String, tools: [[String: any Sendable]]?) -> [ToolCall] { + if strict { return parse(content: content, tools: tools).map { [$0] } ?? [] } + var normalized = content + for tag in alternateStartTags { normalized = normalized.replacingOccurrences(of: tag, with: startTag!) } + return normalized.components(separatedBy: startTag!).filter { !$0.isEmpty } + .compactMap { parse(content: $0, tools: tools) } + } + private func parseArgumentKey(_ rawKey: Substring) -> String { let key = rawKey.trimmingCharacters(in: .whitespacesAndNewlines) return decodeJSONString(key) ?? key @@ -277,10 +293,12 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable { /// parser remains as a fallback only for historical unconstrained auto output. private struct GemmaArgumentValueParser { private let text: String + private let rejectDuplicates: Bool private var index: String.Index - init(_ text: String) { + init(_ text: String, rejectDuplicates: Bool = false) { self.text = text + self.rejectDuplicates = rejectDuplicates self.index = text.startIndex } @@ -298,6 +316,7 @@ private struct GemmaArgumentValueParser { guard let key = parseKey(), consume(":"), let value = parseValue() else { return nil } + if rejectDuplicates && output[key] != nil { return nil } output[key] = value skipWhitespace() if index == text.endIndex { return output } @@ -325,6 +344,7 @@ private struct GemmaArgumentValueParser { guard let key = parseKey(), consume(":"), let value = parseValue() else { return nil } + if rejectDuplicates && object[key] != nil { return nil } object[key] = value if consume("}") { return .object(object) } guard consume(",") else { return nil } diff --git a/Libraries/MLXLMCommon/Tool/ToolCallFormat.swift b/Libraries/MLXLMCommon/Tool/ToolCallFormat.swift index 88f70d8188..318fce5477 100644 --- a/Libraries/MLXLMCommon/Tool/ToolCallFormat.swift +++ b/Libraries/MLXLMCommon/Tool/ToolCallFormat.swift @@ -225,7 +225,7 @@ public enum ToolCallFormat: String, Sendable, Codable, CaseIterable { // Gemma4 `<|tool_call>` tags too, so we do not need upstream's separate // `.gemma4` format (8c61800). This is enforced by ToolTests / // ToolCallParserIntegrationTests. - if type.hasPrefix("gemma") { + if type.hasPrefix("gemma") || type == "diffusion_gemma" { return .gemma } diff --git a/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift b/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift index 67c61b22e2..3ceccfbaa5 100644 --- a/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift +++ b/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift @@ -30,6 +30,8 @@ public class ToolCallProcessor { private let tools: [[String: any Sendable]]? private let qwenStructuredFrames: Bool private var qwenFrameScanner: Qwen35ToolFrameScanner? + private let strictGemma: Bool + private var gemmaFrameScanner: GemmaToolFrameScanner? private var state = State.normal private var toolCallBuffer = "" private var activeEndTags: [String]? @@ -54,8 +56,9 @@ public class ToolCallProcessor { /// - Parameters: /// - format: The tool call format to use (defaults to `.json` for standard JSON format) /// - tools: Optional tool schemas for type-aware parsing - public init(format: ToolCallFormat = .json, tools: [[String: any Sendable]]? = nil) { - self.parser = format.createParser() + public init(format: ToolCallFormat = .json, tools: [[String: any Sendable]]? = nil, strictGemma: Bool = false) { + self.strictGemma = strictGemma && format == .gemma + self.parser = self.strictGemma ? GemmaFunctionParser(strict: true) : format.createParser() self.tools = tools self.qwenStructuredFrames = format == .qwen35 } @@ -116,6 +119,7 @@ public class ToolCallProcessor { state = .normal activeEndTags = nil qwenFrameScanner = nil + gemmaFrameScanner = nil return nil } @@ -128,6 +132,7 @@ public class ToolCallProcessor { state = .normal activeEndTags = nil qwenFrameScanner = nil + gemmaFrameScanner = nil if returnBufferedText && parsed.isEmpty { return buffered @@ -307,6 +312,7 @@ public class ToolCallProcessor { state = .normal activeEndTags = nil qwenFrameScanner = nil + gemmaFrameScanner = nil toolCallBuffer = "" // If the token contains the start character, there may be more tool calls to come @@ -350,6 +356,21 @@ public class ToolCallProcessor { } private func completedEndRange(_ endTags: [String], appendedChunk: String) -> Range? { + if strictGemma, let start = parser.startTag, let end = parser.endTag { + let input = gemmaFrameScanner == nil ? toolCallBuffer.dropFirst(start.count) : appendedChunk[...] + var scanner = gemmaFrameScanner ?? GemmaToolFrameScanner() + let scalars = input.unicodeScalars + for index in scalars.indices { + if scanner.consume(scalars[index]) { + let remaining = scalars.distance(from: scalars.index(after: index), to: scalars.endIndex) + let upper = toolCallBuffer.unicodeScalars.index(toolCallBuffer.unicodeScalars.endIndex, offsetBy: -remaining) + gemmaFrameScanner = scanner + return toolCallBuffer.unicodeScalars.index(upper, offsetBy: -end.unicodeScalars.count).. String? { diff --git a/Libraries/MLXVLM/DiffusionGemmaBicubicRGB.swift b/Libraries/MLXVLM/DiffusionGemmaBicubicRGB.swift new file mode 100644 index 0000000000..9931d98d79 --- /dev/null +++ b/Libraries/MLXVLM/DiffusionGemmaBicubicRGB.swift @@ -0,0 +1,94 @@ +// Native DiffusionGemma RGB8 resize; other model processors are unchanged. +// Adapted from Pillow 12.1.0 Resample.c, commit 46f45f674d47b5d8bc54230dda8fe9e214598b87. +// Copyright © 1997-2011 Secret Labs AB; © 1995-2011 Fredrik Lundh and contributors; +// © 2010 Jeffrey A. Clark and contributors. MIT-CMU: docs/diffusiongemma/LICENSE-PILLOW. +import Foundation + +enum DiffusionGemmaBicubicRGB { + enum Failure: Error { case invalidGeometry } + private struct Span { let start: Int; let weights: [Int32] } + private static let precision = 22 + private static let maximumPixels = 64 * 1024 * 1024 + + static func checkedPixelCount(_ width: Int, _ height: Int) throws -> Int { + guard width > 0, height > 0, width <= maximumPixels, height <= maximumPixels else { + throw Failure.invalidGeometry + } + let (count, overflow) = width.multipliedReportingOverflow(by: height) + guard !overflow, count <= maximumPixels else { throw Failure.invalidGeometry } + return count + } + private static func cubic(_ distance: Double) -> Double { + let x = abs(distance) + if x < 1 { return (1.5 * x - 2.5) * x * x + 1 } + if x < 2 { return (((x - 5) * x + 8) * x - 4) * -0.5 } + return 0 + } + private static func coefficients(input: Int, output: Int) throws -> [Span] { + // Pillow's full-image box endpoints are Float32 before widening. + let scale = Double(Float(input)) / Double(output) + let filterScale = max(scale, 1), support = 2 * max(scale, 1) + return try (0.. UInt8 { + UInt8(clamping: accumulator >> precision) + } + static func resize(_ input: [UInt8], width: Int, height: Int, + targetWidth: Int, targetHeight: Int) throws -> [UInt8] + { + let inputPixels = try checkedPixelCount(width, height) + let outputPixels = try checkedPixelCount(targetWidth, targetHeight) + let intermediatePixels = try checkedPixelCount(targetWidth, height) + guard input.count == inputPixels * 3 else { throw Failure.invalidGeometry } + try Task.checkCancellation() + if width == targetWidth && height == targetHeight { return input } + let rounding = Int64(1 << (precision - 1)) + var horizontal: [UInt8] + if width == targetWidth { horizontal = input } + else { + let spans = try coefficients(input: width, output: targetWidth) + horizontal = [UInt8](repeating: 0, count: intermediatePixels * 3) + for y in 0.. Void)? + init( + _ native: DiffusionGemmaGenerationSession, cacheOutcome: CBv2PrefixCacheOutcome = .disabled, + matchedPrefix: Int = 0, cacheTier: CBv2PrefixCacheTier = .memorySnapshot, + onFinish: ((Bool) -> Void)? = nil + ) { + self.native = native + self.initialCacheOutcome = cacheOutcome + self.matchedPrefix = matchedPrefix + self.cacheTier = cacheTier + self.onFinish = onFinish + } + var retainedBytes: Int { native.retainedStateBytes } + var sharedStorageBytes: Int { native.sharedPageBytes } + var activeTokenCount: Int { native.computedTokenCount } + var generatedTokenCount: Int { native.generatedTokenCount } + var prefixUsage: CBv2Usage { + let saved = native.reusedPromptTokenCount + let outcome: CBv2PrefixCacheOutcome = + saved > 0 + ? .hit + : matchedPrefix > 0 + ? (native.phase == .failed ? .adoptionFailed : .skippedPolicy) + : initialCacheOutcome + return .init( + promptTokens: 0, completionTokens: 0, prefixCacheHitTokens: saved, + prefixCacheOutcome: outcome, prefixCacheTier: saved > 0 ? cacheTier : nil, + prefixCacheMatchedTokens: saved, prefixCachePrefillTokensSaved: saved, + prefixCacheStrategy: saved > 0 ? .direct : nil) + } + func finish(reason: CBv2FinishReason) { + let success: Bool + switch reason { + case .stop, .length: success = true + default: success = false + } + onFinish?(success) + onFinish = nil + } + func cancel() { + onFinish?(false) + onFinish = nil + native.cancel() + } + func advanceNative() throws -> CBv2NativeBlockStep { + switch try native.advance() { + case .prefill(let computed, let complete): + return .prefill(computedTokens: computed, complete: complete) + case .refined: return .progress + case .committed(let tokens, let terminal): + let reason: CBv2FinishReason? = + terminal + ? (native.result?.finishReason == "stop" ? .stop : .length) : nil + return .committed( + tokens: tokens.map(Int.init), stopToken: native.terminalStopToken.map(Int.init), + finishReason: reason) + } + } +} + +/// Frozen evaluated weights shared only through the engine's single execution +/// queue. No request state belongs to this owner and no GPU arrays cross queues. +private final class DiffusionGemmaEngineOwner: @unchecked Sendable { + let model: DiffusionGemma + init(_ model: DiffusionGemma) { self.model = model } +} + +private struct DiffusionGemmaEnginePolicy: Sendable { + let configuration: DiffusionGemmaTextConfiguration + let generation: DiffusionGemmaGenerationConfiguration + let eos: [Int] + let itemBytes: Int + let canvasLength: Int + let prefillChunkSize: Int + let supportsMedia: Bool + let prefixRestoreBudget: Int + let pagedMemory: CBv2NativeBlockPagedMemory? + + func reservation(_ request: CBv2Request) throws -> Int { + let count = request.promptTokens.count + guard count > 0, request.maxTokens > 0, + count <= configuration.maxPositionEmbeddings - request.maxTokens, + request.promptTokens.allSatisfy({ $0 >= 0 && $0 < configuration.vocabularySize }), + request.stopTokens.allSatisfy({ $0 >= 0 && $0 < configuration.vocabularySize }) + else { throw CBv2NativeBlockError.unsupportedRequest("token range/context capacity") } + let p = request.sampling + guard p.temperature.isFinite, p.temperature >= 0, + p.topP == 1, p.topK == 0, p.minP == 0, + p.repetitionPenalty == 1, p.frequencyPenalty == 0, p.presencePenalty == 0, + p.logitBias.isEmpty, p.topLogprobs == 0 + else { + throw CBv2NativeBlockError.unsupportedRequest("non-native sampling/logprobs control") + } + guard request.positionState == nil, + request.hybridPrefixIdentity == nil || request.multimodal != nil, + request.tokenConstraint == nil + else { + throw CBv2NativeBlockError.unsupportedRequest( + "unprepared media/positions/diffusion constraint") + } + var mediaTokens = 0 + var mediaChunk = 0 + if let media = request.multimodal { + guard supportsMedia else { + throw CBv2NativeBlockError.unsupportedRequest("model has no native vision tower") + } + guard media.attention == .bidirectionalSpans, media.positionState == nil, + media.deepstackEmbeddings == nil + else { + throw CBv2NativeBlockError.unsupportedRequest("non-native visual control") + } + try DiffusionGemmaVisualEmbeddings.validate(spans: media.spans, promptCount: count) + mediaTokens = media.spans.reduce(0) { $0 + $1.length } + mediaChunk = + DiffusionGemmaVisualEmbeddings.coalesced(media.spans).map(\.length).max() ?? 0 + } + let mediaGeometry = try request.multimodal.map { + try DiffusionGemmaPrefillGeometry(promptCount: count, + chunkSize: prefillChunkSize, spans: $0.spans) + } + func product(_ factors: Int...) throws -> Int { + var result = 1 + for factor in factors { + let next = result.multipliedReportingOverflow(by: factor) + guard factor >= 0, !next.overflow else { + throw CBv2NativeBlockError.invalidConfiguration + } + result = next.partialValue + } + return result + } + func sum(_ parts: [Int]) throws -> Int { + try parts.reduce(0) { value, part in + let next = value.addingReportingOverflow(part) + guard !next.overflow else { throw CBv2NativeBlockError.invalidConfiguration } + return next.partialValue + } + } + let total = count + request.maxTokens + let initial = min( + configuration.maxPositionEmbeddings, + count + min(256, configuration.maxPositionEmbeddings - count)) + var capacity = initial + while capacity < total { + capacity = min( + configuration.maxPositionEmbeddings, + capacity + min(capacity, configuration.maxPositionEmbeddings - capacity)) + } + var parts = [Int]() + if let pagedMemory { + parts.append(pagedMemory.nominalBytes(tokens: total)) + // Exact page storage does not remove the native attention graph's + // temporary gathered K/V plus prefix+canvas concatenation. Charge + // those bounded views separately; only target pages overlap the + // backend physical floor. No activation/OS reserve is reduced. + for kind in configuration.layerTypes { + let windowed = kind == "sliding_attention" + let history = windowed ? min(total, configuration.slidingWindow) : total + let visible = try sum([history, max(prefillChunkSize, canvasLength, mediaChunk)]) + let logical = try product( + visible, + windowed + ? configuration.keyValueHeads + : (configuration.globalKeyValueHeads ?? configuration.keyValueHeads), + windowed ? configuration.headDimension : configuration.globalHeadDimension, + itemBytes) + parts.append( + try product(4, Memory.allocationFootprintUpperBound(byteCount: logical))) + } + } else { + for kind in configuration.layerTypes { + if kind == "sliding_attention" { + // Ring + pre-eviction chunk views retained by native storage. + let tokens = try sum([ + configuration.slidingWindow, configuration.slidingWindow - 1, + max(prefillChunkSize, canvasLength, mediaChunk), + ]) + parts.append( + try product( + 2, tokens, configuration.keyValueHeads, configuration.headDimension, + itemBytes)) + } else { + parts.append( + try product( + 2, capacity, + configuration.globalKeyValueHeads ?? configuration.keyValueHeads, + configuration.globalHeadDimension, itemBytes)) + } + } + } + // Conservative request-local logits/conditioning payload allowance; + // device workspace/activation and OS reserves stay with provider admission. + parts.append(try product(3, canvasLength, configuration.vocabularySize, 4)) + parts.append(try product(canvasLength, sum([generation.stabilityThreshold, 4]), 4)) + parts.append(try product(total, 16)) + // Request-retained visual values plus possible native-dtype cast. The + // original callback owner can coexist until retirement; count both. + parts.append(try product(mediaTokens, configuration.hiddenSize, 8)) + if let mediaGeometry { + // Engine capture policy and generation session can overlap with + // separate host boundary arrays. Fund their capacity/bookkeeping; + // this is not a second device KV charge. Text admission is unchanged. + parts.append(try sum([try product(mediaGeometry.boundaries.count, 32), 1024])) + } + if prefixRestoreBudget > 0, request.prefixCacheEnabled, request.cacheSalt != nil, + request.multimodal == nil || request.hybridPrefixIdentity != nil + { + // Cover both a pinned restore source and every staged compact + // endpoint, including if the slot is resliced during this request. + let positions = mediaGeometry?.capturePositions ?? Set([ + min(count, prefillChunkSize), count / prefillChunkSize * prefillChunkSize, count, + ]).filter { $0 > 0 } + var snapshots = [Int]() + for position in positions { + var source = [ + try product(position, 8), + try sum([try product(configuration.layerCount, 512), 64 * 1024]), + ] + for kind in configuration.layerTypes { + let windowed = kind == "sliding_attention" + let logical = try product( + windowed ? min(position, configuration.slidingWindow) : position, + windowed + ? configuration.keyValueHeads + : (configuration.globalKeyValueHeads ?? configuration.keyValueHeads), + windowed ? configuration.headDimension : configuration.globalHeadDimension, + itemBytes) + source.append( + try product(2, Memory.allocationFootprintUpperBound(byteCount: logical))) + } + snapshots.append(try sum(source)) + } + parts.append(min(prefixRestoreBudget, try sum(snapshots))) + } + return try sum(parts) + } + + func recipe(for request: CBv2Request) throws -> DiffusionGemmaGenerationConfiguration { + try DiffusionGemmaGenerationConfiguration( + maxNewTokens: request.maxTokens, maxDenoisingSteps: generation.maxDenoisingSteps, + sampler: generation.sampler, minimumTemperature: generation.minimumTemperature, + maximumTemperature: generation.maximumTemperature, + stabilityThreshold: generation.stabilityThreshold, + confidenceThreshold: generation.confidenceThreshold, bosTokenId: generation.bosTokenId, + padTokenId: generation.padTokenId, + eosTokenIds: Array(Set(eos).union(request.stopTokens)).sorted()) + } +} + +extension DiffusionGemmaContext { + /// Construct the native engine that can be consumed by DarkBloom's existing + /// EngineV2Bridge. This does not itself register/advertise a provider slot. + /// Media, constraints and persistent/paged caches must be integrated before + /// declaring complete serving support; unsupported controls fail explicitly. + public func makeNativeEngine( + kvBytesCapacity: Int, maxConcurrentRequests: Int = 4, + maxWaiting: Int = 64, prefillChunkSize: Int = 512, + prefixCache: DiffusionGemmaResidentPrefixConfiguration? = nil, + completePrefixCache: (any CBv2NativeBlockPrefixCache)? = nil, + retainMemoryPrefixes: Bool = true, + pagedConfiguration: PagedKVPoolConfig? = nil, + processMemoryOwner: (any CBv2ProcessMemoryOwner)? = nil, + loopConfig: CBv2EngineLoopConfig = .init() + ) throws -> CBv2NativeBlockEngine { + guard prefillChunkSize > 0 else { throw CBv2NativeBlockError.invalidConfiguration } + let embedding = model.model.decoder.embedTokens + let dtype = (embedding as? QuantizedEmbedding)?.scales.dtype ?? embedding.weight.dtype + guard dtype.isFloatingPoint else { throw CBv2NativeBlockError.invalidConfiguration } + let pageMemory: CBv2NativeBlockPagedMemory? + if var pagedConfiguration { + let types = Array(repeating: dtype, count: model.configuration.textConfig.layerCount) + guard pagedConfiguration.capacityBytes == kvBytesCapacity, + pagedConfiguration.dtype == dtype, + pagedConfiguration.layerDTypes == nil || pagedConfiguration.layerDTypes == types, + pagedConfiguration.maxPrefillChunk + >= max(prefillChunkSize, model.configuration.canvasLength) + else { throw CBv2NativeBlockError.invalidConfiguration } + pagedConfiguration.layerDTypes = types + pageMemory = try .init( + layerKinds: model.configuration.textConfig.diffusionPagedLayerKinds, + configuration: pagedConfiguration, processMemoryOwner: processMemoryOwner) + } else { + guard processMemoryOwner == nil else { throw CBv2NativeBlockError.invalidConfiguration } + pageMemory = nil + } + let persistence: DiffusionGemmaPrefixPersistence? + if let completePrefixCache { + guard let prefixCache, + prefixCache.artifactIdentity == completePrefixCache.identity.modelAggregateHash, + prefixCache.templateIdentity == completePrefixCache.identity.promptContractID, + prefixCache.numericalProfile == completePrefixCache.identity.numericsFingerprint + else { + throw CBv2NativeBlockError.invalidConfiguration + } + persistence = try .init( + store: completePrefixCache, + codec: model.model.decoder.makePersistentPrefixCodec( + verifiedIdentity: completePrefixCache.identity, + kvDType: dtype, prefillChunkSize: prefillChunkSize), chunkSize: prefillChunkSize + ) + } else { + persistence = nil + } + let policy = DiffusionGemmaEnginePolicy( + configuration: model.configuration.textConfig, generation: generationConfiguration, + eos: generationConfiguration.eosTokenIds ?? model.configuration.base.eosTokenIds?.values + ?? model.configuration.textConfig.eosTokenIds ?? [], + itemBytes: dtype.size, canvasLength: model.configuration.canvasLength, + prefillChunkSize: prefillChunkSize, + supportsMedia: model.configuration.visionConfig != nil, + prefixRestoreBudget: prefixCache?.maximumBytes ?? 0, pagedMemory: pageMemory) + let owner = DiffusionGemmaEngineOwner(model) + let cache = prefixCache.map { + DiffusionGemmaResidentPrefixCache( + configuration: $0, chunkSize: prefillChunkSize, + retainsPublishedEntries: retainMemoryPrefixes, persistence: persistence) + } + let shared = cache.map { cache in + CBv2NativeBlockSharedResources( + maximumBytes: cache.configuration.maximumBytes, + retainedBytes: { cache.retainedBytes }, trim: { cache.trim(to: $0) }, + clear: { cache.clear() }) + } + let planner: CBv2NativeBlockCheckpointPlanner? + if let cache, let persistence { + planner = { manifest, request, engine in + guard let identity = try cache.identity(for: request) else { + throw CBv2CompleteCheckpointError.incompatibleCheckpoint + } + return try persistence.codec.importPlan( + manifest, prefixIdentity: identity, + promptTokens: request.promptTokens, chunkSize: prefillChunkSize, + maximumNewTokens: request.maxTokens, + prefillGeometry: try request.multimodal.map { + try DiffusionGemmaPrefillGeometry(promptCount: request.promptTokens.count, + chunkSize: prefillChunkSize, spans: $0.spans) + }, engine: engine) + } + } else { + planner = nil + } + let engine = try CBv2NativeBlockEngine( + tokenizer: tokenizer, kvBytesCapacity: kvBytesCapacity, + maxConcurrentRequests: maxConcurrentRequests, maxWaiting: maxWaiting, + loopConfig: loopConfig, + sharedResources: shared, + pagedMemory: pageMemory, + completeNativePrefixCache: completePrefixCache, checkpointPlanner: planner, + reservationForRequest: { try policy.reservation($0) }, + makeSession: { request, cancellation in + let requestKey = UUID() + let tokens = request.promptTokens.map(Int32.init) + let geometry = try request.multimodal.map { + try DiffusionGemmaPrefillGeometry(promptCount: tokens.count, + chunkSize: prefillChunkSize, spans: $0.spans) + } + let hasUnboundMedia = + request.multimodal == nil && (tokens.contains(Int32(owner.model.configuration.imageTokenId)) + || owner.model.configuration.videoTokenId.map { tokens.contains(Int32($0)) } + == true) + let identity = try !hasUnboundMedia ? cache?.identity(for: request) : nil + let durable = identity.flatMap { + persistence?.take(request: request, identity: $0, geometry: geometry) + } + let diskHit = durable?.checkpoint + let hit = + diskHit ?? identity.flatMap { cache?.lookup(tokens: tokens, identity: $0, geometry: geometry) } + let outcome: CBv2PrefixCacheOutcome = + cache == nil + ? .disabled + : cache?.enabled == false + ? .skippedCapacity + : identity == nil + ? .skippedPolicy : durable?.failed == true ? .adoptionFailed : .miss + let capture: ((DiffusionGemmaRequestCache, Bool) throws -> Void)? + if let cache, let identity, hit?.tokenCount != tokens.count { + capture = { state, _ in + try cache.capture( + model: owner.model, cache: state, promptTokens: tokens, + request: requestKey, identity: identity, geometry: geometry) + } + } else { + capture = nil + } + let native = try DiffusionGemmaGenerationSession( + model: owner.model, + promptTokenIds: MLXArray(tokens).reshaped( + 1, request.promptTokens.count), + generation: policy.recipe(for: request), + seed: request.sampling.seed ?? UInt64.random(in: .min ... .max), + samplingTemperature: request.sampling.temperature, + prefillChunkSize: prefillChunkSize, pagedBackend: pageMemory?.backend, + multimodal: request.multimodal, + prefixCheckpoint: hit, prefixIdentity: identity, onEncodedBoundary: capture, + isCancelled: { cancellation.isCancelled }) + return DiffusionGemmaEngineSession( + native, cacheOutcome: outcome, matchedPrefix: hit?.tokenCount ?? 0, + cacheTier: diskHit == nil ? .memorySnapshot : .snapshot, + onFinish: cache.map { cache in + { + cache.finish( + request: requestKey, successful: $0, input: request, reused: hit) + } + }) + }) + persistence?.engine = engine + return engine + } +} diff --git a/Libraries/MLXVLM/DiffusionGemmaGeneration.swift b/Libraries/MLXVLM/DiffusionGemmaGeneration.swift new file mode 100644 index 0000000000..6eed279634 --- /dev/null +++ b/Libraries/MLXVLM/DiffusionGemmaGeneration.swift @@ -0,0 +1,66 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +public struct DiffusionGemmaGenerationResult: Sendable { + /// Actual output only: excludes EOS and unused canvas slots. + public let tokenIds: [Int32] + /// Native accounting includes a terminal EOS when one was generated. + public let generatedTokenCount: Int + public let finishReason: String + public let promptTokenCount: Int + public let reusedPromptTokenCount: Int + public let committedCanvasCount: Int + public let denoisingSteps: Int + public let workTokenCount: Int + public let prefillSeconds: Double + public let firstCommittedOutputSeconds: Double? + public internal(set) var totalSeconds: Double +} + +extension DiffusionGemma { + /// Native single-request runner. State, noise and cache are local to the + /// invocation; the weights are shared and unchanged. Continuous batching is + /// a separate scheduler integration, not a claim made by this convenience API. + /// Only finalized visible tokens reach onCommittedBlock, never draft canvases. + public func generateNative( + promptTokenIds: MLXArray, + generation: DiffusionGemmaGenerationConfiguration, + seed: UInt64, + samplingTemperature: Float = 1, + prefillChunkSize: Int? = nil, + pagedBackend: PagedKVBackend? = nil, + pixelValues: MLXArray? = nil, + visualOutputLengths: [Int]? = nil, + visualBlockIds: MLXArray? = nil, + multimodal: CBv2MultimodalInput? = nil, + prefixCheckpoint: DiffusionGemmaPrefixCheckpoint? = nil, + prefixIdentity: DiffusionGemmaPrefixIdentity? = nil, + onPromptCheckpoint: ((DiffusionGemmaPrefixCheckpoint) throws -> Void)? = nil, + isCancelled: @escaping () -> Bool = { Task.isCancelled }, + onCommittedBlock: ([Int32]) throws -> Void = { _ in } + ) throws -> DiffusionGemmaGenerationResult { + let started = ProcessInfo.processInfo.systemUptime + let session = try DiffusionGemmaGenerationSession( + model: self, promptTokenIds: promptTokenIds, generation: generation, seed: seed, + samplingTemperature: samplingTemperature, prefillChunkSize: prefillChunkSize, + pagedBackend: pagedBackend, + pixelValues: pixelValues, visualOutputLengths: visualOutputLengths, + visualBlockIds: visualBlockIds, multimodal: multimodal, prefixCheckpoint: prefixCheckpoint, + prefixIdentity: prefixIdentity, onPromptCheckpoint: onPromptCheckpoint, + isCancelled: isCancelled) + while session.phase != .finished { + if case .committed(let tokens, _) = try session.advance(), !tokens.isEmpty { + try onCommittedBlock(tokens) + } + } + guard var result = session.result else { + throw DiffusionGemmaModelError.invalidInput("missing terminal generation result") + } + // The synchronous convenience call includes consumer callback time; + // the session's intrinsic timing alone must not inflate this rate. + result.totalSeconds = ProcessInfo.processInfo.systemUptime - started + return result + } +} diff --git a/Libraries/MLXVLM/DiffusionGemmaGenerationSession.swift b/Libraries/MLXVLM/DiffusionGemmaGenerationSession.swift new file mode 100644 index 0000000000..aa268fb5ea --- /dev/null +++ b/Libraries/MLXVLM/DiffusionGemmaGenerationSession.swift @@ -0,0 +1,359 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +/// One request's native block state, owned by a single engine execution lane. +/// Each advance performs at most one encoder forward or one denoising step. +/// No provisional canvas is exposed to streaming, billing or prefix consumers. +public final class DiffusionGemmaGenerationSession { + public enum Phase: Sendable, Equatable { + case prefill, denoising, encodeCommitted, finished, cancelled, failed + } + public enum Step: Sendable { + case prefill(computedTokens: Int, complete: Bool) + case refined + case committed(tokens: [Int32], terminal: Bool) + } + + public private(set) var phase: Phase = .prefill + public private(set) var result: DiffusionGemmaGenerationResult? + public private(set) var generatedTokenCount = 0 + public private(set) var denoisingSteps = 0 + public private(set) var reusedPromptTokenCount = 0 + public private(set) var terminalStopToken: Int32? + public var committedCachePosition: Int { cache?.position ?? 0 } + public var retainedCacheBytes: Int { cache?.retainedBytes ?? 0 } + public var sharedPageBytes: Int { pagedBackend == nil ? 0 : retainedCacheBytes } + public var retainedStateBytes: Int { + retainedCacheBytes + (state?.retainedPayloadBytes ?? 0) + + (prompt?.nbytes ?? 0) + (pixels?.nbytes ?? 0) + (visualBlockIds?.nbytes ?? 0) + + (preparedMedia?.retainedBytes ?? 0) + + (prefix?.retainedBytes ?? 0) + } + public var computedTokenCount: Int { + (result == nil ? min(promptCount, cache?.position ?? 0) : promptCount) + generatedTokenCount + } + + private let model: DiffusionGemma + private let generation: DiffusionGemmaGenerationConfiguration + private let temperature: Float + private let outputLimit: Int + private let eos: Set + private let promptCount: Int + private let prefillChunkSize: Int? + private let mediaPrefillGeometry: DiffusionGemmaPrefillGeometry? + private let pagedBackend: PagedKVBackend? + private let started = ProcessInfo.processInfo.systemUptime + private let isCancelled: () -> Bool + private var prompt: MLXArray? + private var pixels: MLXArray? + private var visualOutputLengths: [Int]? + private var visualBlockIds: MLXArray? + private var preparedMedia: DiffusionGemmaVisualEmbeddings? + private var prefix: DiffusionGemmaPrefixCheckpoint? + private let prefixIdentity: DiffusionGemmaPrefixIdentity? + private var onPromptCheckpoint: ((DiffusionGemmaPrefixCheckpoint) throws -> Void)? + private var onEncodedBoundary: ((DiffusionGemmaRequestCache, Bool) throws -> Void)? + private var cache: DiffusionGemmaRequestCache? + private var state: DiffusionGemmaDenoisingState? + private var key: MLXArray + private var output = [Int32]() + private var committedCanvas: [Int32]? + private var canvasCount = 0 + private var workTokens = 0 + private var prefillSeconds: Double = 0 + private var firstOutputSeconds: Double? + + public init( + model: DiffusionGemma, promptTokenIds: MLXArray, + generation: DiffusionGemmaGenerationConfiguration, seed: UInt64, + samplingTemperature: Float = 1, prefillChunkSize: Int? = nil, + pagedBackend: PagedKVBackend? = nil, + pixelValues: MLXArray? = nil, visualOutputLengths: [Int]? = nil, + visualBlockIds: MLXArray? = nil, + multimodal: CBv2MultimodalInput? = nil, + prefixCheckpoint: DiffusionGemmaPrefixCheckpoint? = nil, + prefixIdentity: DiffusionGemmaPrefixIdentity? = nil, + onPromptCheckpoint: ((DiffusionGemmaPrefixCheckpoint) throws -> Void)? = nil, + onEncodedBoundary: ((DiffusionGemmaRequestCache, Bool) throws -> Void)? = nil, + isCancelled: @escaping () -> Bool = { Task.isCancelled } + ) throws { + guard promptTokenIds.ndim == 2, promptTokenIds.dim(0) == 1, promptTokenIds.dim(1) > 0, + samplingTemperature.isFinite, samplingTemperature >= 0, + prefillChunkSize == nil || prefillChunkSize! > 0 + else { throw DiffusionGemmaModelError.invalidInput("generation inputs") } + let count = promptTokenIds.dim(1) + let limit = try generation.outputTokenLimit(promptTokenCount: count) + guard count <= model.configuration.textConfig.maxPositionEmbeddings - limit else { + throw DiffusionGemmaModelError.invalidInput("logical context capacity") + } + if let pagedBackend { + let largestChunk = max(prefillChunkSize ?? count, model.configuration.canvasLength, + multimodal.map { DiffusionGemmaVisualEmbeddings.coalesced($0.spans).map(\.length).max() ?? 0 } ?? 0) + guard largestChunk <= pagedBackend.pool.config.maxPrefillChunk else { + throw DiffusionGemmaModelError.invalidInput("native paged write quantum exceeds pool bound") + } + } + let eosValues = + generation.eosTokenIds ?? model.configuration.base.eosTokenIds?.values + ?? model.configuration.textConfig.eosTokenIds ?? [] + guard + eosValues.allSatisfy({ $0 >= 0 && $0 < model.configuration.textConfig.vocabularySize }) + else { + throw DiffusionGemmaModelError.invalidInput("EOS token range") + } + if prefixCheckpoint != nil || onPromptCheckpoint != nil || onEncodedBoundary != nil { + guard let prefixIdentity, pixelValues == nil, + visualOutputLengths == nil, visualBlockIds == nil + else { throw DiffusionGemmaModelError.invalidInput("unbound prefix identity/media") } + if multimodal != nil { + guard prefixIdentity.mediaIdentity != nil, prefixIdentity.media != "text-only" else { + throw DiffusionGemmaModelError.invalidInput("unbound prefix identity/media") + } + } else { + guard prefixIdentity.mediaIdentity == nil, prefixIdentity.media == "text-only", + !(promptTokenIds .== model.configuration.imageTokenId).any().item(Bool.self), + model.configuration.videoTokenId == nil + || !(promptTokenIds .== model.configuration.videoTokenId!).any().item(Bool.self) + else { throw DiffusionGemmaModelError.invalidInput("unbound prefix identity/media") } + } + } + guard + multimodal == nil + || (pixelValues == nil && visualBlockIds == nil && visualOutputLengths == nil) + else { + throw DiffusionGemmaModelError.invalidInput("ambiguous native media source") + } + guard multimodal == nil || model.configuration.visionConfig != nil else { + throw DiffusionGemmaModelError.invalidInput("native media requires a vision model") + } + // Chunked media needs processor-owned spans and slicing. Until that + // integration exists, refuse instead of silently splitting a visual block. + if let prefillChunkSize, count > prefillChunkSize, + pixelValues != nil || visualBlockIds != nil || visualOutputLengths != nil + { + throw DiffusionGemmaModelError.invalidInput("unprepared chunked media") + } + self.model = model + self.generation = generation + self.temperature = samplingTemperature + self.outputLimit = limit + self.eos = Set(eosValues.map(Int32.init)) + self.promptCount = count + self.prefillChunkSize = prefillChunkSize + self.mediaPrefillGeometry = try multimodal.map { + try DiffusionGemmaPrefillGeometry(promptCount: count, + chunkSize: prefillChunkSize ?? count, spans: $0.spans) + } + self.pagedBackend = pagedBackend + self.prompt = promptTokenIds[0..., 0...] + self.pixels = pixelValues + self.visualOutputLengths = visualOutputLengths + self.visualBlockIds = visualBlockIds + self.preparedMedia = try multimodal.map { + try DiffusionGemmaVisualEmbeddings( + input: $0, promptCount: count, + hiddenSize: model.configuration.textConfig.hiddenSize) + } + self.prefix = prefixCheckpoint + self.prefixIdentity = prefixIdentity + self.onPromptCheckpoint = onPromptCheckpoint + self.onEncodedBoundary = onEncodedBoundary + self.isCancelled = isCancelled + self.key = MLXRandom.key(seed) + } + + /// Cancellation is terminal: uncommitted state is dropped and cannot be + /// resumed or donated. The engine serializes this call with advance(). + public func cancel() { + guard phase != .finished, phase != .failed, phase != .cancelled else { return } + phase = .cancelled + releaseBuffers() + } + + public func advance() throws -> Step { + if phase == .cancelled { throw CancellationError() } + guard phase != .finished, phase != .failed else { + throw DiffusionGemmaModelError.invalidInput("terminal generation session") + } + if isCancelled() { + cancel() + throw CancellationError() + } + do { + return try MLX.withError { errors in + switch phase { + case .prefill: return try prefill(errors: errors) + case .encodeCommitted: + guard let cache, let committedCanvas else { + throw DiffusionGemmaModelError.invalidInput( + "missing finalized encoder state") + } + _ = try model.encode( + tokenIds: MLXArray(committedCanvas).reshaped(1, committedCanvas.count), + cache: cache) + eval(cache.stateArrays()) + try errors.check() + self.committedCanvas = nil + phase = .denoising + return .refined + case .denoising: return try denoise(errors: errors) + default: throw DiffusionGemmaModelError.invalidInput("terminal generation session") + } + } + } catch { + if error is CancellationError { phase = .cancelled } else { phase = .failed } + releaseBuffers() + throw error + } + } + + private func prefill(errors: MLX.ErrorBox) throws -> Step { + guard let prompt else { throw DiffusionGemmaModelError.invalidInput("missing prompt") } + if cache == nil { + if let prefix, let prefixIdentity { + guard mediaPrefillGeometry?.permitsRestore(position: prefix.tokenCount) ?? true else { + throw DiffusionGemmaModelError.invalidInput("prefix splits native media quantum") + } + cache = try model.model.decoder.restorePrefix( + prefix, identity: prefixIdentity, promptTokenIds: prompt, + maximumSequenceLength: pagedBackend == nil ? nil : promptCount + outputLimit, + pagedBackend: pagedBackend) + } else { + cache = try model.makeCache(expectedPromptLength: promptCount, + maximumSequenceLength: pagedBackend == nil ? nil : promptCount + outputLimit, + pagedBackend: pagedBackend) + } + reusedPromptTokenCount = cache!.position + prefix = nil + } + let cache = cache! + let start = cache.position + let count = + try mediaPrefillGeometry?.chunkLength(start: start) + ?? min(promptCount - start, prefillChunkSize ?? promptCount) + if count > 0 { + let chunk = prompt[0..., start ..< (start + count)] + if let preparedMedia { + try preparedMedia.encode(model: model, tokens: chunk, cache: cache, start: start) + } else { + _ = try model.encode( + tokenIds: chunk, cache: cache, + pixelValues: pixels, visualOutputLengths: visualOutputLengths, + visualBlockIds: visualBlockIds) + } + } + eval(cache.stateArrays()) + try errors.check() + if isCancelled() { throw CancellationError() } + let complete = cache.position == promptCount + if count > 0 { try onEncodedBoundary?(cache, complete) } + if complete { + if let onPromptCheckpoint, let prefixIdentity { + try onPromptCheckpoint( + model.model.decoder.checkpoint(cache: cache, identity: prefixIdentity)) + } + onPromptCheckpoint = nil + onEncodedBoundary = nil + promptCleanup() + prefillSeconds = ProcessInfo.processInfo.systemUptime - started + phase = .denoising + } + return .prefill(computedTokens: count, complete: complete) + } + + private func nextKey() -> MLXArray { + let parts = MLXRandom.split(key: key) + key = parts.0 + return parts.1 + } + private func noise() -> MLXArray { + MLXRandom.randInt( + Int32(0) ..< Int32(model.configuration.textConfig.vocabularySize), + [1, model.configuration.canvasLength], key: nextKey()) + } + private func denoise(errors: MLX.ErrorBox) throws -> Step { + guard let cache else { + throw DiffusionGemmaModelError.invalidInput("missing encoder state") + } + if state == nil { + state = try DiffusionGemmaDenoisingState( + initialCanvas: noise(), + vocabularySize: model.configuration.textConfig.vocabularySize, + embeddingDType: model.model.decoder.selfConditioningLogitsDType, + configuration: generation) + } + let state = state! + let logits = try model.denoise( + canvasIds: state.currentCanvas, cache: cache, + selfConditioningLogits: state.selfConditioningLogits) + try state.stepNative( + rawLogits: logits, samplingTemperature: temperature, nextKey: nextKey) + try errors.check() + eval( + state.currentCanvas, state.argmaxCanvas, state.finishedRows, + state.selfConditioningLogits!) + try errors.check() + denoisingSteps += 1 + workTokens += model.configuration.canvasLength + guard state.remainingSteps == 0 || state.finishedRows.all().item(Bool.self) else { + return .refined + } + if isCancelled() { throw CancellationError() } + let canvas = try state.finalizedCanvas().asArray(Int32.self) + try errors.check() + canvasCount += 1 + var block = [Int32]() + var finish = "length" + for token in canvas.prefix(outputLimit - generatedTokenCount) { + generatedTokenCount += 1 + if eos.contains(token) { + terminalStopToken = token + finish = "stop" + break + } + block.append(token) + } + if !block.isEmpty { + if firstOutputSeconds == nil { + firstOutputSeconds = ProcessInfo.processInfo.systemUptime - started + } + output.append(contentsOf: block) + } + self.state = nil + let terminal = finish == "stop" || generatedTokenCount == outputLimit + if terminal { + result = DiffusionGemmaGenerationResult( + tokenIds: output, generatedTokenCount: generatedTokenCount, finishReason: finish, + promptTokenCount: promptCount, reusedPromptTokenCount: reusedPromptTokenCount, + committedCanvasCount: canvasCount, denoisingSteps: denoisingSteps, + workTokenCount: workTokens, + prefillSeconds: prefillSeconds, firstCommittedOutputSeconds: firstOutputSeconds, + totalSeconds: ProcessInfo.processInfo.systemUptime - started) + phase = .finished + releaseBuffers() + } else { + committedCanvas = canvas + phase = .encodeCommitted + } + return .committed(tokens: block, terminal: terminal) + } + + private func promptCleanup() { + prompt = nil + pixels = nil + visualBlockIds = nil + visualOutputLengths = nil + preparedMedia = nil + } + private func releaseBuffers() { + promptCleanup() + cache = nil + state = nil + prefix = nil + committedCanvas = nil + onPromptCheckpoint = nil + onEncodedBoundary = nil + } +} diff --git a/Libraries/MLXVLM/DiffusionGemmaImagePixels.swift b/Libraries/MLXVLM/DiffusionGemmaImagePixels.swift new file mode 100644 index 0000000000..0e1534f433 --- /dev/null +++ b/Libraries/MLXVLM/DiffusionGemmaImagePixels.swift @@ -0,0 +1,63 @@ +import CoreImage +import Foundation +import MLX +import MLXLLM + +private let diffusionImageContext = CIContext(options: [.cacheIntermediates: false]) + +/// The released processor resizes RGB8 in its encoded color space, rounds and +/// clips each separable pass, then scales to FP32. A floating CoreImage resize +/// in linear light is not the same operation even when both are called bicubic. +enum DiffusionGemmaImagePixels { + static func prepare(_ image: CIImage, width: Int, height: Int, + geometry: DiffusionGemmaMediaGeometry) throws -> MLXArray + { + do { + let count = try DiffusionGemmaBicubicRGB.checkedPixelCount(width, height) + _ = try DiffusionGemmaBicubicRGB.checkedPixelCount(geometry.width, geometry.height) + try Task.checkCancellation() + var rgba = [UInt8](repeating: 0, count: count * 4) + defer { diffusionImageContext.clearCaches() } + try rgba.withUnsafeMutableBytes { bytes in + let destination = CIRenderDestination(bitmapData: bytes.baseAddress!, + width: width, height: height, bytesPerRow: width * 4, format: .RGBA8) + destination.colorSpace = CGColorSpace(name: CGColorSpace.sRGB) + destination.alphaMode = .unpremultiplied + // RGB reference buffers store their first row at the top. + // CIRenderDestination otherwise defaults to Cartesian order. + destination.isFlipped = true + destination.isDithered = false + destination.isClamped = true + let task = try diffusionImageContext.startTask(toRender: image, + from: image.extent, to: destination, at: .zero) + _ = try task.waitUntilCompleted() + } + try Task.checkCancellation() + var rgb = [UInt8]() + rgb.reserveCapacity(count * 3) + for pixel in 0.. Self + { + guard width > 0, height > 0, patchSize > 0, poolingSize > 0, + [70, 140, 280, 560, 1120].contains(maxSoftTokens) + else { throw DiffusionGemmaModelError.invalidInput("media geometry") } + let sideProduct = patchSize.multipliedReportingOverflow(by: poolingSize) + guard !sideProduct.overflow, sideProduct.partialValue > 0 else { + throw DiffusionGemmaModelError.invalidInput("media geometry overflow") + } + let side = sideProduct.partialValue + let maximum = side.multipliedReportingOverflow(by: maxSoftTokens) + guard !maximum.overflow else { + throw DiffusionGemmaModelError.invalidInput("media geometry overflow") + } + let targetPixels = Double(maxSoftTokens) * Double(side) * Double(side) + let factor = sqrt(targetPixels / (Double(height) * Double(width))) + var targetHeight = floor(factor * Double(height) / Double(side)) * Double(side) + var targetWidth = floor(factor * Double(width) / Double(side)) * Double(side) + guard targetHeight != 0 || targetWidth != 0 else { + throw DiffusionGemmaModelError.invalidInput("empty resized media") + } + // Reference thin-image handling also clamps the long axis; simply + // setting a zero dimension to one patch group can exceed the budget. + if targetHeight == 0 { + targetHeight = Double(side) + targetWidth = min(floor(Double(width) / Double(height)) * Double(side), Double(maximum.partialValue)) + } else if targetWidth == 0 { + targetWidth = Double(side) + targetHeight = min(floor(Double(height) / Double(width)) * Double(side), Double(maximum.partialValue)) + } + guard let h = Int(exactly: targetHeight), let w = Int(exactly: targetWidth), + h > 0, w > 0, h.isMultiple(of: side), w.isMultiple(of: side) + else { throw DiffusionGemmaModelError.invalidInput("resized media range") } + let tokens = (h / side).multipliedReportingOverflow(by: w / side) + guard !tokens.overflow, tokens.partialValue > 0, tokens.partialValue <= maxSoftTokens else { + throw DiffusionGemmaModelError.invalidInput("resized media budget") + } + return Self(width: w, height: h, softTokens: tokens.partialValue) + } +} diff --git a/Libraries/MLXVLM/DiffusionGemmaMediaInput.swift b/Libraries/MLXVLM/DiffusionGemmaMediaInput.swift new file mode 100644 index 0000000000..59aa31180b --- /dev/null +++ b/Libraries/MLXVLM/DiffusionGemmaMediaInput.swift @@ -0,0 +1,16 @@ +import MLX +import MLXLMCommon + +/// Prepared image rows in prompt order. Pixels are evaluated before return and +/// must remain immutable while the native model consumes this request. +public struct DiffusionGemmaMediaInput: @unchecked Sendable { + public struct Frame { + public enum Kind: Sendable { case image, videoFrame } + public let kind: Kind + public let pixels: MLXArray + public let span: CBv2ImageSpan + public let timestampSeconds: Double? + } + public let tokens: [Int32] + public let frames: [Frame] +} diff --git a/Libraries/MLXVLM/DiffusionGemmaModelFactory.swift b/Libraries/MLXVLM/DiffusionGemmaModelFactory.swift new file mode 100644 index 0000000000..dee35a73f5 --- /dev/null +++ b/Libraries/MLXVLM/DiffusionGemmaModelFactory.swift @@ -0,0 +1,129 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +/// Native diffusion context, deliberately distinct from the autoregressive +/// ModelContext. A caller cannot accidentally feed this model to TokenIterator. +public struct DiffusionGemmaContext { + public let configuration: ResolvedModelConfiguration + public let model: DiffusionGemma + public let generationConfiguration: DiffusionGemmaGenerationConfiguration + public let tokenizer: any Tokenizer + public let chatTemplate: String + public let processor: DiffusionGemmaProcessor? + + /// Apply the checkpoint's exact template with syntax-only Jinja compatibility. + /// Tools, reasoning and history remain template inputs, never string repairs. + /// Media expansion is a separate processor operation, not performed here. + public func renderTokens( + messages: [[String: any Sendable]], tools: [[String: any Sendable]]? = nil, + additionalContext: [String: any Sendable]? = nil + ) throws -> [Int32] { + let tokens = try tokenizer.applyChatTemplate( + messages: messages, chatTemplate: chatTemplate, + tools: tools, additionalContext: additionalContext) + guard !tokens.isEmpty, tokens.count < model.configuration.textConfig.maxPositionEmbeddings, + tokens.allSatisfy({ $0 >= 0 && $0 < model.configuration.textConfig.vocabularySize }) + else { throw DiffusionGemmaModelError.invalidInput("rendered token range/capacity") } + return tokens.map(Int32.init) + } +} + +/// The same exclusive-access primitive used by the ordinary model container. +/// Serialization here is not a claim of native continuous-batching support. +public final class DiffusionGemmaContainer: Sendable { + private let context: SerialAccessContainer + + public init(context: consuming DiffusionGemmaContext) { + self.context = .init(context) + } + + public func perform( + _ action: @Sendable (DiffusionGemmaContext) async throws -> sending R + ) async rethrows -> sending R { + try await context.read { try await action($0) } + } + + /// Linear transfer of decoded media into the container's serialized scope. + /// As with ModelContainer, evaluate arrays before returning them as owned + /// request data; never share mutable UserInput across concurrent requests. + public func perform(nonSendable values: consuming V, + _ action: @Sendable (DiffusionGemmaContext, V) async throws -> R) async rethrows -> sending R + { + let transferred = SendableBox(values) + return try await context.read { try await action($0, transferred.consume()) } + } +} + +/// Explicit native factory. Generic AR factories continue to reject this type; +/// serving integrations must select this factory and the block-diffusion runner. +public final class DiffusionGemmaModelFactory: GenericModelFactory, Sendable { + public static let shared = DiffusionGemmaModelFactory() + public let modelRegistry = AbstractModelRegistry() + public init() {} + + public func _wrap(_ context: DiffusionGemmaContext) -> DiffusionGemmaContainer { + .init(context: context) + } + + public func _load( + configuration: ResolvedModelConfiguration, tokenizerLoader: any TokenizerLoader + ) async throws -> sending DiffusionGemmaContext { + let directory = configuration.modelDirectory + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory), + isDirectory.boolValue + else { throw DiffusionGemmaModelError.invalidInput("missing model directory") } + // No unchecked AR stopping overrides. Native callers select an explicit + // DiffusionGemmaGenerationConfiguration per request instead. + guard configuration.extraEOSTokens.isEmpty, configuration.eosTokenIds.isEmpty else { + throw DiffusionGemmaModelError.invalidInput("AR stopping overrides on diffusion load") + } + let decoder = JSONDecoder.json5() + let configBytes = try Data(contentsOf: directory.appendingPathComponent("config.json")) + let config = try decoder.decode(DiffusionGemmaConfiguration.self, from: configBytes) + let generation = try decoder.decode( + DiffusionGemmaGenerationConfiguration.self, + from: Data(contentsOf: directory.appendingPathComponent("generation_config.json"))) + let specialIds = + (generation.eosTokenIds ?? config.base.eosTokenIds?.values ?? config.textConfig + .eosTokenIds + ?? []) + [generation.bosTokenId, generation.padTokenId].compactMap { $0 } + guard specialIds.allSatisfy({ $0 >= 0 && $0 < config.textConfig.vocabularySize }) else { + throw DiffusionGemmaModelError.invalidInput("generation special token range") + } + let template = SwiftJinjaSyntaxCompatibility.normalize( + try String( + contentsOf: configuration.tokenizerDirectory.appendingPathComponent( + "chat_template.jinja"), + encoding: .utf8)) + guard !template.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw DiffusionGemmaModelError.invalidInput("empty chat template") + } + // Resolve small metadata/tokenizer failures before constructing weights. + // This consumes the bytes read above, never a second config/template read. + let tokenizer = try await tokenizerLoader.load(from: configuration.tokenizerDirectory) + let processor: DiffusionGemmaProcessor? + if config.visionConfig != nil { + let settings = try decoder.decode(DiffusionGemmaProcessorConfiguration.self, + from: Data(contentsOf: directory.appendingPathComponent("processor_config.json"))) + processor = try DiffusionGemmaProcessor(configuration: settings, model: config, + tokenizer: tokenizer, template: template) + } else { processor = nil } + try Task.checkCancellation() + let model = DiffusionGemma(config) + try MLX.withError { errors in + try loadWeights(modelDirectory: directory, model: model, + perLayerQuantization: config.base.perLayerQuantization) + model.train(false) + eval(model) + try errors.check() + } + try Task.checkCancellation() + return DiffusionGemmaContext( + configuration: configuration, model: model, generationConfiguration: generation, + tokenizer: tokenizer, chatTemplate: template, processor: processor) + } +} diff --git a/Libraries/MLXVLM/DiffusionGemmaPrefixPersistence.swift b/Libraries/MLXVLM/DiffusionGemmaPrefixPersistence.swift new file mode 100644 index 0000000000..76230cf1f1 --- /dev/null +++ b/Libraries/MLXVLM/DiffusionGemmaPrefixPersistence.swift @@ -0,0 +1,77 @@ +import Foundation +import MLXLLM +import MLXLMCommon + +/// No model owner and no disk reads. Mutable setup ends before the engine is +/// exposed; request adoption/donation run on its execution queue. +final class DiffusionGemmaPrefixPersistence: @unchecked Sendable { + let store: any CBv2NativeBlockPrefixCache + let codec: DiffusionGemmaPersistentPrefixCodec + let chunkSize: Int + weak var engine: CBv2NativeBlockEngine? + + init(store: any CBv2NativeBlockPrefixCache, codec: DiffusionGemmaPersistentPrefixCodec, chunkSize: Int) { + self.store = store; self.codec = codec; self.chunkSize = chunkSize + } + + func take(request: CBv2Request, identity: DiffusionGemmaPrefixIdentity, + geometry: DiffusionGemmaPrefillGeometry? = nil) + -> (checkpoint: DiffusionGemmaPrefixCheckpoint?, failed: Bool) { + guard let receipt = request.prefixCacheReceiptID else { return (nil, false) } + let (maximum, overflow) = request.promptTokens.count.addingReportingOverflow(request.maxTokens) + guard !overflow, let staged = store.takeNativeStaged(requestID: receipt, + tokens: request.promptTokens, cacheSalt: request.checkpointCacheSalt, maximumSequenceLength: maximum) + else { return (nil, false) } + do { + guard identity.mediaIdentity == nil || geometry?.permitsRestore(position: staged.manifest.position) == true + else { throw CBv2CompleteCheckpointError.incompatibleCheckpoint } + return (try codec.adopt(staged, prefixIdentity: identity), false) + } + catch { staged.close(); return (nil, true) } + } + + func accepts(_ checkpoint: DiffusionGemmaPrefixCheckpoint, request: CBv2Request) -> Bool { + if let media = request.multimodal { + guard let geometry = try? DiffusionGemmaPrefillGeometry( + promptCount: request.promptTokens.count, chunkSize: chunkSize, spans: media.spans), + geometry.permitsPersistentCapture(position: checkpoint.tokenCount) else { return false } + } + return (request.multimodal != nil || checkpoint.tokenCount % chunkSize == 0) + && store.acceptsCheckpoint(position: checkpoint.tokenCount, packedBytes: checkpoint.retainedBytes) + } + + func donate(_ checkpoint: DiffusionGemmaPrefixCheckpoint, request: CBv2Request) { + guard let engine, accepts(checkpoint, request: request) else { return } + do { + // The LRU may evict this snapshot while I/O runs. Fund independent + // ownership BEFORE the request/shared-cache reservation can retire. + let lease = try engine.reserveNativeCheckpoint(bytes: checkpoint.physicalRetainedBytes) + let donor = DiffusionGemmaCheckpointDonor(checkpoint: checkpoint, lease: lease) + do { + let source = try codec.export(checkpoint, chunkSize: chunkSize, engine: engine) + store.donate(source, requestID: request.prefixCacheReceiptID, tokens: request.promptTokens, + cacheSalt: request.checkpointCacheSalt) { [donor] _ in donor.close() } + } catch { donor.close() } + } catch { + // Optional cache capacity must not turn successful generation into + // a failure or spend beyond the slot grant. + } + } +} + +private final class DiffusionGemmaCheckpointDonor: @unchecked Sendable { + private let lock = NSLock() + private var checkpoint: DiffusionGemmaPrefixCheckpoint? + private var lease: CBv2NativeBlockCheckpointLease? + init(checkpoint: DiffusionGemmaPrefixCheckpoint, lease: CBv2NativeBlockCheckpointLease) { + self.checkpoint = checkpoint; self.lease = lease + } + func close() { + let retiring = lock.withLock { + checkpoint = nil + let value = lease; lease = nil; return value + } + retiring?.close() + } + deinit { close() } +} diff --git a/Libraries/MLXVLM/DiffusionGemmaProcessor.swift b/Libraries/MLXVLM/DiffusionGemmaProcessor.swift new file mode 100644 index 0000000000..a1259cf078 --- /dev/null +++ b/Libraries/MLXVLM/DiffusionGemmaProcessor.swift @@ -0,0 +1,113 @@ +import AVFoundation +import CoreImage +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +/// Native processor, separate from Gemma4's fixed image-token expansion. It +/// preserves typed message/tool history and explicit image/text ordering. +public struct DiffusionGemmaProcessor: Sendable { + let configuration: DiffusionGemmaProcessorConfiguration + let model: DiffusionGemmaConfiguration + let tokenizer: any Tokenizer + let template: String + + public init(configuration: DiffusionGemmaProcessorConfiguration, + model: DiffusionGemmaConfiguration, tokenizer: any Tokenizer, template: String) throws + { + try configuration.validate(model: model) + self.configuration = configuration + self.model = model + self.tokenizer = tokenizer + self.template = template + } + + public func prepare(input: UserInput, + afterEvaluation: () throws -> Void = {}) async throws -> DiffusionGemmaMediaInput + { + try Task.checkCancellation() + guard input.processing.resize == nil, input.processing.minPixels == nil, input.processing.maxPixels == nil else { + throw DiffusionGemmaModelError.invalidInput("native media uses its declared pixel budget") + } + let messages = Gemma4MessageGenerator().generate(from: input) + let rendered = try tokenizer.applyChatTemplate(messages: messages, chatTemplate: template, + tools: input.tools, additionalContext: input.additionalContext) + let imageID = try checkedToken("<|image|>", expected: model.imageTokenId) + let videoID = try checkedToken("<|video|>", expected: model.videoTokenId) + guard rendered.filter({ $0 == imageID }).count == input.images.count, + rendered.filter({ $0 == videoID }).count == input.videos.count + else { throw DiffusionGemmaModelError.invalidInput("unbound media placeholders") } + var tokens = [Int32]() + var frames = [DiffusionGemmaMediaInput.Frame]() + var imageIndex = 0, videoIndex = 0 + func append(_ values: [Int]) throws { + guard values.count <= model.textConfig.maxPositionEmbeddings - tokens.count, + values.allSatisfy({ $0 >= 0 && $0 < model.textConfig.vocabularySize }) + else { throw DiffusionGemmaModelError.invalidInput("expanded media prompt capacity") } + tokens.append(contentsOf: values.map(Int32.init)) + } + func prepareImage(_ image: CIImage, budget: Int) throws -> (pixels: MLXArray, geometry: DiffusionGemmaMediaGeometry) { + let value = try pixels(image, budget: budget) + eval(value.pixels) + try afterEvaluation() + try Task.checkCancellation() + return value + } + func appendImage(_ prepared: (pixels: MLXArray, geometry: DiffusionGemmaMediaGeometry), + kind: DiffusionGemmaMediaInput.Frame.Kind, timestamp: Double?) throws + { + try append([model.beginImageTokenId]) + let span = CBv2ImageSpan(tokenOffset: tokens.count, length: prepared.geometry.softTokens) + try append(Array(repeating: imageID, count: span.length)) + try append([model.endImageTokenId]) + frames.append(.init(kind: kind, pixels: prepared.pixels, span: span, timestampSeconds: timestamp)) + } + for token in rendered { + try Task.checkCancellation() + if token == imageID { + try appendImage(prepareImage(input.images[imageIndex].asCIImage(), budget: configuration.imageSoftTokenBudget), + kind: .image, timestamp: nil) + imageIndex += 1 + } else if token == videoID { + // The released native model consumes videos as timestamped image + // frames, not a separate Gemma4 video tower/patch payload. + let selected = try await DiffusionGemmaVideoFrames.sample(input.videos[videoIndex]) { frame in + // No separate video budget is declared by this artifact. + // Preserve its image budget for the documented frame route. + (image: try prepareImage(frame.frame, budget: configuration.imageSoftTokenBudget), seconds: frame.timeStamp.seconds) + } + for (index, frame) in selected.enumerated() { + let second = Int(frame.seconds.rounded(.towardZero)) + let timestamp = String(format: "%02d:%02d ", second / 60, second % 60) + try append(tokenizer.encode(text: (index == 0 ? "" : " ") + timestamp, addSpecialTokens: false)) + try appendImage(frame.image, kind: .videoFrame, timestamp: frame.seconds) + } + videoIndex += 1 + } else { try append([token]) } + } + guard !tokens.isEmpty else { throw DiffusionGemmaModelError.invalidInput("empty native prompt") } + return DiffusionGemmaMediaInput(tokens: tokens, frames: frames) + } + + private func checkedToken(_ name: String, expected: Int?) throws -> Int { + guard let value = tokenizer.convertTokenToId(name), value >= 0, + value < model.textConfig.vocabularySize, expected == nil || expected == value + else { throw DiffusionGemmaModelError.invalidInput("native media vocabulary mismatch") } + return value + } + + private func pixels(_ original: CIImage, budget: Int) throws + -> (pixels: MLXArray, geometry: DiffusionGemmaMediaGeometry) + { + let extent = original.extent + guard extent.origin.x.isFinite, extent.origin.y.isFinite, + let width = Int(exactly: extent.width), let height = Int(exactly: extent.height) + else { throw DiffusionGemmaModelError.invalidInput("nonfinite/nonintegral media extent") } + let geometry = try DiffusionGemmaMediaGeometry.resized(width: width, height: height, + patchSize: configuration.patchSize, poolingSize: configuration.poolingSize, maxSoftTokens: budget) + let image = original.transformed(by: .init(translationX: -extent.minX, y: -extent.minY)) + return (try DiffusionGemmaImagePixels.prepare(image, width: width, height: height, + geometry: geometry), geometry) + } +} diff --git a/Libraries/MLXVLM/DiffusionGemmaProcessorConfiguration.swift b/Libraries/MLXVLM/DiffusionGemmaProcessorConfiguration.swift new file mode 100644 index 0000000000..701f1545ac --- /dev/null +++ b/Libraries/MLXVLM/DiffusionGemmaProcessorConfiguration.swift @@ -0,0 +1,47 @@ +import Foundation +import MLXLLM + +/// Decode-only native image contract. Unsupported transforms reject instead of +/// being silently ignored. Video-as-images uses the same trained pixel path. +public struct DiffusionGemmaProcessorConfiguration: Decodable, Sendable { + public let patchSize: Int + public let poolingSize: Int + public let imageSoftTokenBudget: Int + + private enum Keys: String, CodingKey { + case processorClass = "processor_class", image = "image_processor" + } + private enum ImageKeys: String, CodingKey { + case type = "image_processor_type", patch = "patch_size", pool = "pooling_kernel_size" + case budget = "max_soft_tokens", resize = "do_resize", rescale = "do_rescale" + case normalize = "do_normalize", rgb = "do_convert_rgb", factor = "rescale_factor", resample + } + + public init(from decoder: Decoder) throws { + let root = try decoder.container(keyedBy: Keys.self) + guard try root.decode(String.self, forKey: .processorClass) == "DiffusionGemma4Processor" else { + throw DiffusionGemmaModelError.invalidInput("native processor class") + } + let image = try root.nestedContainer(keyedBy: ImageKeys.self, forKey: .image) + patchSize = try image.decode(Int.self, forKey: .patch) + poolingSize = try image.decode(Int.self, forKey: .pool) + imageSoftTokenBudget = try image.decode(Int.self, forKey: .budget) + guard try image.decode(String.self, forKey: .type) == "Gemma4ImageProcessor", + try image.decodeIfPresent(Bool.self, forKey: .resize) ?? true, + try image.decodeIfPresent(Bool.self, forKey: .rescale) ?? true, + try !(image.decodeIfPresent(Bool.self, forKey: .normalize) ?? false), + try image.decodeIfPresent(Bool.self, forKey: .rgb) ?? true, + try image.decodeIfPresent(Double.self, forKey: .factor) ?? (1 / 255) == 1 / 255, + try image.decodeIfPresent(Int.self, forKey: .resample) ?? 3 == 3 + else { throw DiffusionGemmaModelError.invalidInput("unsupported native image transform") } + _ = try DiffusionGemmaMediaGeometry.resized(width: 1, height: 1, + patchSize: patchSize, poolingSize: poolingSize, maxSoftTokens: imageSoftTokenBudget) + } + + public func validate(model: DiffusionGemmaConfiguration) throws { + guard let vision = model.visionConfig, + patchSize == vision.patchSize, poolingSize == vision.poolingKernelSize, + imageSoftTokenBudget == model.visionSoftTokensPerImage + else { throw DiffusionGemmaModelError.invalidInput("processor/model vision geometry mismatch") } + } +} diff --git a/Libraries/MLXVLM/DiffusionGemmaResidentPrefixCache.swift b/Libraries/MLXVLM/DiffusionGemmaResidentPrefixCache.swift new file mode 100644 index 0000000000..e21fab0fb7 --- /dev/null +++ b/Libraries/MLXVLM/DiffusionGemmaResidentPrefixCache.swift @@ -0,0 +1,197 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +/// In-process only. The native owner/epoch binds evaluated weights; these +/// strings must come from trusted serving configuration, not request metadata. +public struct DiffusionGemmaResidentPrefixConfiguration: Sendable { + public let maximumBytes: Int + public let maximumEntries: Int + public let artifactIdentity: String + public let templateIdentity: String + public let numericalProfile: String + + public init( + maximumBytes: Int, maximumEntries: Int = 8, + artifactIdentity: String, templateIdentity: String, numericalProfile: String + ) throws { + guard maximumBytes > 0, maximumEntries > 0, maximumEntries <= 1024, + [artifactIdentity, templateIdentity, numericalProfile].allSatisfy({ + !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && $0.utf8.count <= 4096 + }) + else { + throw CBv2NativeBlockError.invalidConfiguration + } + self.maximumBytes = maximumBytes + self.maximumEntries = maximumEntries + self.artifactIdentity = artifactIdentity + self.templateIdentity = templateIdentity + self.numericalProfile = numericalProfile + } +} + +/// Engine-queue confined: compact copies are evaluated synchronously before +/// publication. Staged and published snapshots share one bounded LRU budget. +final class DiffusionGemmaResidentPrefixCache: @unchecked Sendable { + private struct Entry { + let request: UUID + let checkpoint: DiffusionGemmaPrefixCheckpoint + let identity: DiffusionGemmaPrefixIdentity + let chargedBytes: Int + var published: Bool + } + let configuration: DiffusionGemmaResidentPrefixConfiguration + let retainsPublishedEntries: Bool + let persistence: DiffusionGemmaPrefixPersistence? + private let epoch = UUID().uuidString + private let chunkSize: Int + private var entries = [Entry]() // Oldest use first. + private var byteLimit: Int + var enabled: Bool { byteLimit > 0 } + var retainedBytes: Int { entries.reduce(0) { $0 + $1.chargedBytes } } + + init(configuration: DiffusionGemmaResidentPrefixConfiguration, chunkSize: Int, + retainsPublishedEntries: Bool = true, persistence: DiffusionGemmaPrefixPersistence? = nil) { + self.configuration = configuration + self.chunkSize = chunkSize + self.byteLimit = configuration.maximumBytes + self.retainsPublishedEntries = retainsPublishedEntries + self.persistence = persistence + } + + func identity(for request: CBv2Request) throws -> DiffusionGemmaPrefixIdentity? { + guard request.prefixCacheEnabled, request.positionState == nil, + let scope = request.cacheSalt, + !scope.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + scope.utf8.count <= 4096 + else { return nil } + let mediaIdentity: CBv2HybridPrefixIdentity? + if let media = request.multimodal { + guard (retainsPublishedEntries || persistence != nil), media.attention == .bidirectionalSpans, + media.positionState == nil, media.deepstackEmbeddings == nil, + let bound = request.hybridPrefixIdentity else { return nil } + mediaIdentity = bound + } else { + guard request.hybridPrefixIdentity == nil else { return nil } + mediaIdentity = nil + } + return try .init( + tenantScope: request.checkpointCacheSalt ?? scope, artifact: configuration.artifactIdentity, + template: configuration.templateIdentity, + media: mediaIdentity.map { "media:" + $0.digest.map { String(format: "%02x", $0) }.joined() } ?? "text-only", + numericalProfile: configuration.numericalProfile + ":prefill-\(chunkSize)", epoch: epoch, + mediaIdentity: mediaIdentity + ) + } + + func lookup(tokens: [Int32], identity: DiffusionGemmaPrefixIdentity, + geometry: DiffusionGemmaPrefillGeometry? = nil) + -> DiffusionGemmaPrefixCheckpoint? + { + guard identity.mediaIdentity == nil || geometry != nil else { return nil } + let candidates = entries.indices.filter { + let entry = entries[$0] + // An appended request may reuse only the exact cold chunk boundary. + // Full short/unaligned snapshots remain usable for identical prompts. + return entry.published && entry.checkpoint.matches(tokens: tokens, identity: identity) + && (entry.checkpoint.tokenCount == tokens.count + || (geometry?.permitsRestore(position: entry.checkpoint.tokenCount) + ?? (entry.checkpoint.tokenCount % chunkSize == 0))) + } + guard + let index = candidates.max(by: { + entries[$0].checkpoint.tokenCount < entries[$1].checkpoint.tokenCount + }) + else { return nil } + let hit = entries.remove(at: index) + entries.append(hit) + return hit.checkpoint + } + + static func metadataCharge(tokens: Int, layers: Int, identity: DiffusionGemmaPrefixIdentity) + -> Int + { + // Token-array capacity + bounded bookkeeping, separate from device KV. + tokens * 8 + layers * 512 + 1024 + + [ + identity.tenantScope, identity.artifact, identity.template, identity.media, + identity.numericalProfile, identity.epoch, + ].reduce(0) { $0 + $1.utf8.count * 2 } + } + + func capture( + model: DiffusionGemma, cache: DiffusionGemmaRequestCache, + promptTokens: [Int32], request: UUID, identity: DiffusionGemmaPrefixIdentity, + geometry: DiffusionGemmaPrefillGeometry? = nil + ) throws { + let promptCount = promptTokens.count + let position = cache.position + guard identity.mediaIdentity == nil || geometry != nil else { return } + let captures = geometry?.capturePositions + ?? Set([promptCount, promptCount / chunkSize * chunkSize, min(promptCount, chunkSize)]) + let firstBoundary = geometry?.boundaries.first ?? min(promptCount, chunkSize) + let lastBoundary = geometry?.lastStableBoundary ?? (promptCount / chunkSize * chunkSize) + guard position > 0, captures.contains(position) + else { return } + let bytes = try + cache.stateArrays().reduce(0) { try $0 + Memory.allocationFootprintUpperBound(byteCount: $1.nbytes) } + + Self.metadataCharge( + tokens: position, layers: cache.configuration.layerCount, identity: identity) + guard bytes > 0, bytes <= byteLimit else { return } + // Preserve the donor's aligned branch point when an unaligned exact + // endpoint cannot coexist; losing it would turn every appended turn cold. + func protected(_ entry: Entry) -> Bool { + entry.checkpoint.matches(tokens: promptTokens, identity: identity) + && (entry.checkpoint.tokenCount == firstBoundary + || (entry.checkpoint.tokenCount == lastBoundary && position != lastBoundary)) + } + while retainedBytes > byteLimit - bytes || entries.count >= configuration.maximumEntries { + guard let victim = entries.firstIndex(where: { !protected($0) }) else { return } + entries.remove(at: victim) + } + let checkpoint = try model.model.decoder.checkpoint( + cache: cache, identity: identity, compact: true) + guard checkpoint.physicalRetainedBytes <= bytes else { + throw CBv2NativeBlockError.invalidConfiguration + } + entries.append( + .init( + request: request, checkpoint: checkpoint, identity: identity, + chargedBytes: bytes, published: false)) + } + + func finish(request: UUID, successful: Bool, input: CBv2Request? = nil, + reused: DiffusionGemmaPrefixCheckpoint? = nil) { + if successful { + let staged = entries.filter { $0.request == request && !$0.published } + entries.removeAll { $0.request == request && !$0.published } + if let persistence, let input { + let candidates = staged.map(\.checkpoint) + (reused.map { [$0] } ?? []) + if let donor = candidates.filter({ + persistence.accepts($0, request: input) + }).max(by: { $0.tokenCount < $1.tokenCount }) { + persistence.donate(donor, request: input) + } + } + guard retainsPublishedEntries else { return } + for var entry in staged { + entries.removeAll { $0.published && $0.checkpoint.samePrefix(as: entry.checkpoint) } + entry.published = true + entries.append(entry) + } + } else { + entries.removeAll { $0.request == request && !$0.published } + } + } + + func trim(to bytes: Int) { + byteLimit = min(max(0, bytes), configuration.maximumBytes) + while retainedBytes > byteLimit { entries.removeFirst() } + } + func clear() { + entries.removeAll() + byteLimit = 0 + persistence?.store.close() + } +} diff --git a/Libraries/MLXVLM/DiffusionGemmaVideoFrames.swift b/Libraries/MLXVLM/DiffusionGemmaVideoFrames.swift new file mode 100644 index 0000000000..0d1ff727a8 --- /dev/null +++ b/Libraries/MLXVLM/DiffusionGemmaVideoFrames.swift @@ -0,0 +1,84 @@ +@preconcurrency import AVFoundation +import CoreImage +import Foundation +import MLXLLM +import MLXLMCommon + +/// Google documents videos as image sequences, at one frame/s for at most60s. +/// No audio extraction, temporary plaintext file or Gemma4 video-feature path. +enum DiffusionGemmaVideoFrames { + static func sample(_ video: UserInput.Video, + transform: (UserInput.VideoFrame) throws -> Result) async throws -> [Result] + { + try Task.checkCancellation() + switch video { + case .frames(let frames): return try sampleProvided(frames).map(transform) + case .avAsset(let asset): return try await sampleAsset(asset, transform: transform) + case .memoryBacked(let owner): return try await owner.withAsset { try await sampleAsset($0, transform: transform) } + case .url(let url): return try await sampleAsset(AVURLAsset(url: url), transform: transform) + } + } + + private static func seconds(duration: Double) throws -> [Double] { + guard duration.isFinite, duration >= 0, duration <= 60 else { + throw DiffusionGemmaModelError.invalidInput("native video duration must not exceed60s") + } + return (0.. [UserInput.VideoFrame] { + guard let first = frames.first else { throw DiffusionGemmaModelError.invalidInput("empty video frames") } + let origin = first.timeStamp.seconds + let times = frames.map { $0.timeStamp.seconds - origin } + guard origin.isFinite, origin >= 0, times.allSatisfy({ $0.isFinite && $0 >= 0 }), + zip(times, times.dropFirst()).allSatisfy({ $0 <= $1 }) + else { throw DiffusionGemmaModelError.invalidInput("unordered/nonfinite video timestamps") } + _ = try seconds(duration: times.last!) + // Provided frames describe sample instants, so include an integer + // final sample; an asset duration instead names an exclusive endpoint. + let selected = (0..(_ asset: AVAsset, + transform: (UserInput.VideoFrame) throws -> Result) async throws -> [Result] + { + let tracks = try await asset.loadTracks(withMediaType: .video) + guard let track = tracks.first, try await track.load(.isDecodable) else { + throw DiffusionGemmaModelError.invalidInput("undecodable video") + } + let duration = try await asset.load(.duration) + let times = try seconds(duration: duration.seconds).map { + CMTime(seconds: $0, preferredTimescale: 1_000_000) + } + let generator = AVAssetImageGenerator(asset: asset) + generator.appliesPreferredTrackTransform = true + generator.requestedTimeToleranceBefore = .zero + generator.requestedTimeToleranceAfter = .zero + var frames = [(requested: Double, frame: Result)]() + defer { generator.cancelAllCGImageGeneration() } + for await result in generator.images(for: times) { + try Task.checkCancellation() + switch result { + case .success(requestedTime: let requested, let image, actualTime: let actual): + guard actual.seconds.isFinite, actual.seconds >= 0, actual.seconds <= duration.seconds else { + throw DiffusionGemmaModelError.invalidInput("invalid decoded video timestamp") + } + let pixels = CIImage(cgImage: image, options: [.colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!]) + // Transform/evaluate each frame now. Retaining60 full-resolution + // CGImages until the final resize would amplify decode memory. + frames.append((requested.seconds, try transform(.init(frame: pixels, timeStamp: actual)))) + case .failure: + throw DiffusionGemmaModelError.invalidInput("video frame extraction failed") + } + } + guard frames.count == times.count else { throw DiffusionGemmaModelError.invalidInput("incomplete video extraction") } + return frames.sorted { $0.requested < $1.requested }.map(\.frame) + } +} diff --git a/Libraries/MLXVLM/DiffusionGemmaVisionPreparation.swift b/Libraries/MLXVLM/DiffusionGemmaVisionPreparation.swift new file mode 100644 index 0000000000..1c573f831d --- /dev/null +++ b/Libraries/MLXVLM/DiffusionGemmaVisionPreparation.swift @@ -0,0 +1,48 @@ +import MLX +import MLXLLM +import MLXLMCommon + +extension DiffusionGemma { + /// Mirrors the native tower's padding to MLX's supported fused head sizes. + /// Serving admission uses the real fallback head multiplicity otherwise. + public var visionAttentionGeometry: (patchSize: Int, attentionHeadFactor: Int)? { + guard let vision = configuration.visionConfig else { return nil } + let padded = [64, 80, 128].first { vision.headDim <= $0 } ?? vision.headDim + return (vision.patchSize, [64, 80, 128].contains(padded) ? 1 : vision.numAttentionHeads) + } + /// Evaluate the actual native tower/projector one frame at a time. The + /// callback lets serving code check its scoped MLX error box after each + /// evaluation, before beginning another frame. + public func prepareVision(_ input: DiffusionGemmaMediaInput, + afterEvaluation: () throws -> Void = {}) throws -> CBv2MultimodalInput? + { + guard !input.frames.isEmpty else { return nil } + guard let vision = configuration.visionConfig, let tower = model.encoder.visionTower, + let projection = model.encoder.embedVision + else { throw DiffusionGemmaModelError.invalidInput("missing native vision modules") } + let spans = input.frames.map(\.span) + try DiffusionGemmaVisualEmbeddings.validate(spans: spans, promptCount: input.tokens.count) + let dtype = try model.decoder.scaledEmbeddings(MLXArray([Int32(configuration.textConfig.padTokenId ?? 0)]).reshaped(1, 1)).dtype + var features = [MLXArray]() + for frame in input.frames { + try Task.checkCancellation() + let pixels = frame.pixels + let side = vision.patchSize * vision.poolingKernelSize + guard pixels.ndim == 4, pixels.dim(0) == 1, pixels.dim(1) == 3, + pixels.dtype.isFloatingPoint, pixels.dim(2) > 0, pixels.dim(3) > 0, + pixels.dim(2).isMultiple(of: side), pixels.dim(3).isMultiple(of: side), + (pixels.dim(2) / side) * (pixels.dim(3) / side) == frame.span.length, + input.tokens[frame.span.tokenOffset..<(frame.span.tokenOffset + frame.span.length)] + .allSatisfy({ $0 == Int32(configuration.imageTokenId) }) + else { throw DiffusionGemmaModelError.invalidInput("native frame/prompt geometry mismatch") } + let value = projection(tower(pixels, outputLength: frame.span.length)).asType(dtype) + eval(value) + try afterEvaluation() + guard value.shape == [1, frame.span.length, configuration.textConfig.hiddenSize] else { + throw DiffusionGemmaModelError.invalidInput("native visual feature shape") + } + features.append(value) + } + return CBv2MultimodalInput(spans: spans) { features } + } +} diff --git a/Libraries/MLXVLM/DiffusionGemmaVisualEmbeddings.swift b/Libraries/MLXVLM/DiffusionGemmaVisualEmbeddings.swift new file mode 100644 index 0000000000..c81140ba44 --- /dev/null +++ b/Libraries/MLXVLM/DiffusionGemmaVisualEmbeddings.swift @@ -0,0 +1,103 @@ +import MLX +import MLXLLM +import MLXLMCommon + +/// Immutable evaluated media features owned by one native generation session. +/// There is no autoregressive model/cache adapter and no provisional KV owner. +public struct DiffusionGemmaVisualEmbeddings { + let spans: [CBv2ImageSpan] + let blocks: [CBv2ImageSpan] + let values: [MLXArray] + public var retainedBytes: Int { values.reduce(0) { $0 + $1.nbytes } } + var maximumBlockLength: Int { blocks.map(\.length).max() ?? 0 } + + static func validate(spans: [CBv2ImageSpan], promptCount: Int) throws { + guard !spans.isEmpty, promptCount > 0 else { + throw DiffusionGemmaModelError.invalidInput("empty visual spans") + } + var end = 0 + for span in spans { + guard span.tokenOffset >= end, span.tokenOffset < promptCount, + span.length > 0, span.length <= 1120, + span.length <= promptCount - span.tokenOffset + else { throw DiffusionGemmaModelError.invalidInput("native visual span range/order") } + end = span.tokenOffset + span.length + } + guard coalesced(spans).allSatisfy({ $0.length <= 1120 }) else { + throw DiffusionGemmaModelError.invalidInput("native visual block budget") + } + } + + static func coalesced(_ spans: [CBv2ImageSpan]) -> [CBv2ImageSpan] { + var blocks = [CBv2ImageSpan]() + for span in spans { + if let last = blocks.indices.last, blocks[last].tokenOffset + blocks[last].length == span.tokenOffset { + blocks[last].length += span.length + } else { blocks.append(span) } + } + return blocks + } + + public init(input: CBv2MultimodalInput, promptCount: Int, hiddenSize: Int) throws { + guard input.attention == .bidirectionalSpans, input.positionState == nil, input.deepstackEmbeddings == nil else { + throw DiffusionGemmaModelError.invalidInput("non-native visual attention/positions") + } + try Self.validate(spans: input.spans, promptCount: promptCount) + let provided = try input.embeddings() + guard provided.count == input.spans.count else { + throw DiffusionGemmaModelError.invalidInput("native visual feature count") + } + self.spans = input.spans + self.blocks = Self.coalesced(input.spans) + self.values = try zip(input.spans, provided).map { span, value in + let shaped = value.ndim == 2 ? value.expandedDimensions(axis: 0) : value + guard shaped.shape == [1, span.length, hiddenSize], + [.float16, .bfloat16, .float32].contains(shaped.dtype) else { + throw DiffusionGemmaModelError.invalidInput("native visual feature dimensions") + } + eval(shaped) + return shaped[0..., 0..., 0...] + } + } + + func chunkLength(start: Int, requested: Int, promptCount: Int) throws -> Int { + guard start >= 0, requested > 0, start < promptCount else { + throw DiffusionGemmaModelError.invalidInput("media chunk range") + } + var end = start + min(requested, promptCount - start) + for block in blocks where block.tokenOffset < end && block.tokenOffset + block.length > end { + end = block.tokenOffset > start ? block.tokenOffset : block.tokenOffset + block.length + } + guard end > start, end <= promptCount else { + throw DiffusionGemmaModelError.invalidInput("media chunk progress") + } + return end - start + } + + func encode(model: DiffusionGemma, tokens: MLXArray, cache: DiffusionGemmaRequestCache, start: Int) throws { + let count = tokens.dim(1), end = start + tokens.dim(1) + guard cache.position == start else { throw DiffusionGemmaModelError.invalidInput("media chunk cache position") } + let local = spans.indices.filter { spans[$0].tokenOffset < end && spans[$0].tokenOffset + spans[$0].length > start } + guard local.allSatisfy({ spans[$0].tokenOffset >= start && spans[$0].tokenOffset + spans[$0].length <= end }) else { + throw DiffusionGemmaModelError.invalidInput("split visual span") + } + if local.isEmpty { _ = try model.encode(tokenIds: tokens, cache: cache); return } + var blockIDs = Array(repeating: Int32(-1), count: count) + for (index, block) in blocks.enumerated() where block.tokenOffset < end && block.tokenOffset + block.length > start { + guard block.tokenOffset >= start, block.tokenOffset + block.length <= end else { + throw DiffusionGemmaModelError.invalidInput("split visual block") + } + for position in block.tokenOffset..<(block.tokenOffset + block.length) { blockIDs[position - start] = Int32(index) } + } + let blocks = MLXArray(blockIDs).reshaped(1, count) + let embeddedIDs = which(blocks .>= 0, MLXArray(Int32(model.configuration.textConfig.padTokenId ?? 0)), tokens) + let embedded = try model.model.decoder.scaledEmbeddings(embeddedIDs) + for index in local { + let span = spans[index] + embedded[0..., (span.tokenOffset - start)..<(span.tokenOffset + span.length - start), 0...] = values[index].asType(embedded.dtype) + } + _ = try model.model.decoder.encode(tokenIds: tokens, cache: cache, + encoderParameters: model.model.encoder.languageModel, + preparedEmbeddings: embedded, visualBlockIds: blocks) + } +} diff --git a/Libraries/MLXVLM/Models/DiffusionGemma.swift b/Libraries/MLXVLM/Models/DiffusionGemma.swift new file mode 100644 index 0000000000..daef2425a8 --- /dev/null +++ b/Libraries/MLXVLM/Models/DiffusionGemma.swift @@ -0,0 +1,305 @@ +// Native shared encoder + block denoiser for diffusion_gemma. +// Architecture references and license attribution: docs/diffusiongemma/implementation-references.md. + +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +public struct DiffusionGemmaConfiguration: Codable, Sendable { + public let textConfig: DiffusionGemmaTextConfiguration + public let visionConfig: Gemma4VisionConfig? + public let canvasLength: Int + public let imageTokenId: Int + public let videoTokenId: Int? + public let beginImageTokenId: Int + public let endImageTokenId: Int + public let visionSoftTokensPerImage: Int + public let tieWordEmbeddings: Bool + public let dtype: String? + public let initializerRange: Float + public let base: BaseConfiguration + public var modelType: String { base.modelType } + + enum CodingKeys: String, CodingKey { + case textConfig = "text_config" + case visionConfig = "vision_config" + case canvasLength = "canvas_length" + case imageTokenId = "image_token_id" + case videoTokenId = "video_token_id" + case beginImageTokenId = "boi_token_id" + case endImageTokenId = "eoi_token_id" + case visionSoftTokensPerImage = "vision_soft_tokens_per_image" + case tieWordEmbeddings = "tie_word_embeddings" + case dtype + case initializerRange = "initializer_range" + } + enum VisionExtraKeys: String, CodingKey { + case ropeParameters = "rope_parameters" + case modelType = "model_type" + case activation = "hidden_activation" + case attentionBias = "attention_bias" + case globalHeadDimension = "global_head_dim" + } + + public init(from decoder: Decoder) throws { + base = try BaseConfiguration(from: decoder) + let c = try decoder.container(keyedBy: CodingKeys.self) + textConfig = try c.decode(DiffusionGemmaTextConfiguration.self, forKey: .textConfig) + visionConfig = try c.decodeIfPresent(Gemma4VisionConfig.self, forKey: .visionConfig) + canvasLength = try c.decodeIfPresent(Int.self, forKey: .canvasLength) ?? 256 + imageTokenId = try c.decodeIfPresent(Int.self, forKey: .imageTokenId) ?? 258880 + videoTokenId = try c.decodeIfPresent(Int.self, forKey: .videoTokenId) + beginImageTokenId = try c.decodeIfPresent(Int.self, forKey: .beginImageTokenId) ?? 255999 + endImageTokenId = try c.decodeIfPresent(Int.self, forKey: .endImageTokenId) ?? 258882 + visionSoftTokensPerImage = + try c.decodeIfPresent(Int.self, forKey: .visionSoftTokensPerImage) + ?? visionConfig?.defaultOutputLength ?? 280 + tieWordEmbeddings = try c.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true + dtype = try c.decodeIfPresent(String.self, forKey: .dtype) + initializerRange = try c.decodeIfPresent(Float.self, forKey: .initializerRange) ?? 0.02 + guard base.modelType == "diffusion_gemma", tieWordEmbeddings, canvasLength > 0, + canvasLength <= textConfig.maxPositionEmbeddings, + initializerRange.isFinite, initializerRange >= 0 + else { throw DiffusionGemmaModelError.invalidInput("root architecture") } + if let visionConfig { + let extras = try c.superDecoder(forKey: .visionConfig).container( + keyedBy: VisionExtraKeys.self) + let type = + try extras.decodeIfPresent(String.self, forKey: .modelType) ?? "gemma4_vision" + let activation = + try extras.decodeIfPresent(String.self, forKey: .activation) ?? "gelu_pytorch_tanh" + let bias = try extras.decodeIfPresent(Bool.self, forKey: .attentionBias) ?? false + let globalHead = + try extras.decodeIfPresent(Int.self, forKey: .globalHeadDimension) + ?? visionConfig.headDim + let rope = + try extras.decodeIfPresent([String: StringOrNumber].self, forKey: .ropeParameters) + ?? [:] + guard type == "gemma4_vision", activation == "gelu_pytorch_tanh", !bias, + globalHead == visionConfig.headDim, + rope.keys.allSatisfy({ ["rope_type", "rope_theta"].contains($0) }), + rope["rope_type"] == nil || rope["rope_type"] == .string("default") + else { throw DiffusionGemmaModelError.invalidInput("unsupported vision architecture") } + guard !visionConfig.useClippedLinears, visionConfig.rmsNormEps == 1e-6, + visionConfig.patchSize > 0, visionConfig.poolingKernelSize > 0, + visionConfig.hiddenSize > 0, visionConfig.numHiddenLayers > 0, + visionConfig.numAttentionHeads > 0, visionConfig.numKeyValueHeads > 0, + visionConfig.headDim > 0, visionConfig.headDim.isMultiple(of: 4), + visionConfig.numAttentionHeads.isMultiple(of: visionConfig.numKeyValueHeads), + visionConfig.positionEmbeddingSize > 0, visionConfig.ropeTheta.isFinite, + visionConfig.ropeTheta > 0, + visionConfig.defaultOutputLength > 0, + visionSoftTokensPerImage > 0, imageTokenId >= 0, + imageTokenId < textConfig.vocabularySize + else { throw DiffusionGemmaModelError.invalidInput("vision configuration") } + } + } + + public func encode(to encoder: Encoder) throws { + // Preserve the entire per-module quantization map and EOS through the + // shared metadata contract, not just the default bit depth. + try base.encode(to: encoder) + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(textConfig, forKey: .textConfig) + if let visionConfig { + let visionEncoder = c.superEncoder(forKey: .visionConfig) + try visionConfig.encode(to: visionEncoder) + var extra = visionEncoder.container(keyedBy: VisionExtraKeys.self) + try extra.encode( + [ + "rope_theta": StringOrNumber.float(visionConfig.ropeTheta), + "rope_type": .string("default"), + ], forKey: .ropeParameters) + try extra.encode("gemma4_vision", forKey: .modelType) + try extra.encode("gelu_pytorch_tanh", forKey: .activation) + try extra.encode(false, forKey: .attentionBias) + try extra.encode(visionConfig.headDim, forKey: .globalHeadDimension) + } + try c.encode(canvasLength, forKey: .canvasLength) + try c.encode(imageTokenId, forKey: .imageTokenId) + try c.encodeIfPresent(videoTokenId, forKey: .videoTokenId) + try c.encode(beginImageTokenId, forKey: .beginImageTokenId) + try c.encode(endImageTokenId, forKey: .endImageTokenId) + try c.encode(visionSoftTokensPerImage, forKey: .visionSoftTokensPerImage) + try c.encode(tieWordEmbeddings, forKey: .tieWordEmbeddings) + try c.encodeIfPresent(dtype, forKey: .dtype) + try c.encode(initializerRange, forKey: .initializerRange) + } +} + +/// DiffusionGemma normalizes vision features BEFORE the learned projection. +/// Do not substitute the existing AR wrapper's post-projection normalization. +final class DiffusionGemmaVisionProjection: Module { + @ModuleInfo(key: "embedding_projection") var projection: Linear + let epsilon: Float + init(vision: Gemma4VisionConfig, hiddenSize: Int) { + epsilon = vision.rmsNormEps + _projection.wrappedValue = Linear(vision.hiddenSize, hiddenSize, bias: false) + } + func callAsFunction(_ features: MLXArray) -> MLXArray { + projection(MLXFast.rmsNorm(features, weight: .mlxNone, eps: epsilon)) + } +} + +public final class DiffusionGemmaEncoder: Module { + @ModuleInfo(key: "language_model") public var languageModel: DiffusionGemmaEncoderTextParameters + @ModuleInfo(key: "vision_tower") var visionTower: Gemma4VisionTower? + @ModuleInfo(key: "embed_vision") var embedVision: DiffusionGemmaVisionProjection? + init(_ config: DiffusionGemmaConfiguration) { + _languageModel.wrappedValue = DiffusionGemmaEncoderTextParameters( + layerCount: config.textConfig.layerCount) + if let vision = config.visionConfig { + _visionTower.wrappedValue = Gemma4VisionTower(vision, contract: .diffusionGemma) + _embedVision.wrappedValue = DiffusionGemmaVisionProjection( + vision: vision, hiddenSize: config.textConfig.hiddenSize) + } + } +} + +public final class DiffusionGemmaBackbone: Module { + @ModuleInfo public var encoder: DiffusionGemmaEncoder + @ModuleInfo public var decoder: DiffusionGemmaTextDecoder + init(_ config: DiffusionGemmaConfiguration) { + _encoder.wrappedValue = DiffusionGemmaEncoder(config) + _decoder.wrappedValue = DiffusionGemmaTextDecoder(config.textConfig) + } +} + +/// Native model surface. Generic autoregressive registration is intentionally +/// separate: a loaded diffusion model must never fall through TokenIterator. +public final class DiffusionGemma: Module, BaseLanguageModel, QuantizationPathAliasing { + public let configuration: DiffusionGemmaConfiguration + @ModuleInfo public var model: DiffusionGemmaBackbone + public init(_ configuration: DiffusionGemmaConfiguration) { + self.configuration = configuration + _model.wrappedValue = DiffusionGemmaBackbone(configuration) + } + public func makeCache(expectedPromptLength: Int, maximumSequenceLength: Int? = nil, + pagedBackend: PagedKVBackend? = nil) throws -> DiffusionGemmaRequestCache { + try DiffusionGemmaRequestCache( + configuration: configuration.textConfig, + expectedPromptLength: expectedPromptLength, + maximumSequenceLength: maximumSequenceLength, pagedBackend: pagedBackend) + } + + public func encode( + tokenIds: MLXArray, cache: DiffusionGemmaRequestCache, + pixelValues: MLXArray? = nil, visualOutputLengths: [Int]? = nil, + visualBlockIds: MLXArray? = nil + ) throws -> MLXArray { + guard tokenIds.ndim == 2, tokenIds.dim(0) == 1, tokenIds.dim(1) > 0, + cache.configuration == configuration.textConfig, + tokenIds.dim(1) <= configuration.textConfig.maxPositionEmbeddings - cache.position + else { throw DiffusionGemmaModelError.invalidInput("encoder input/capacity") } + // Same placeholder substitution as the native reference. Real media + // preparation/HTTP validation owns presence and provenance checks. + var imageMask = tokenIds .== configuration.imageTokenId + if let video = configuration.videoTokenId { + imageMask = logicalOr(imageMask, tokenIds .== video) + } + // The released config may omit video_token_id. Its processor still + // supplies video positions through native media types (resolved here + // to contiguous visual block IDs). Those positions must select both + // feature substitution AND attention, not just the attention overlay. + if let visualBlockIds { + guard visualBlockIds.shape == tokenIds.shape, visualBlockIds.dtype == .int32, + (visualBlockIds .>= -1).all().item(Bool.self) + else { throw DiffusionGemmaModelError.invalidInput("visual block identity") } + imageMask = logicalOr(imageMask, visualBlockIds .>= 0) + } + let ids = which( + imageMask, MLXArray(Int32(configuration.textConfig.padTokenId ?? 0)), tokenIds) + var embeddings = try model.decoder.scaledEmbeddings(ids) + var blockIds = visualBlockIds + if let pixelValues { + guard let tower = model.encoder.visionTower, let projector = model.encoder.embedVision, + let vision = configuration.visionConfig, + pixelValues.ndim == 4, pixelValues.dtype.isFloatingPoint, pixelValues.dim(0) > 0, + pixelValues.dim(1) == 3, + pixelValues.dim(2) > 0, pixelValues.dim(3) > 0, + pixelValues.dim(2).isMultiple(of: vision.patchSize * vision.poolingKernelSize), + pixelValues.dim(3).isMultiple(of: vision.patchSize * vision.poolingKernelSize) + else { throw DiffusionGemmaModelError.invalidInput("vision inputs") } + let actualLength = + (pixelValues.dim(2) / (vision.patchSize * vision.poolingKernelSize)) + * (pixelValues.dim(3) / (vision.patchSize * vision.poolingKernelSize)) + let lengths = + visualOutputLengths + ?? Array( + repeating: actualLength, + count: pixelValues.dim(0)) + guard lengths.count == pixelValues.dim(0), + actualLength > 0, actualLength <= 1120, + lengths.allSatisfy({ $0 == actualLength }) + else { + throw DiffusionGemmaModelError.invalidInput("vision output budget") + } + let flags = imageMask.asArray(Bool.self) + let positions = flags.enumerated().compactMap { $0.element ? Int32($0.offset) : nil } + guard positions.count == lengths.reduce(0, +) else { + throw DiffusionGemmaModelError.invalidInput("vision placeholder count") + } + var projected = [MLXArray]() + for index in 0 ..< pixelValues.dim(0) { + let image = pixelValues[index ..< (index + 1), 0..., 0..., 0...] + let maxPatches = + lengths[index] * vision.poolingKernelSize * vision.poolingKernelSize + guard image.dim(3) / vision.patchSize <= maxPatches else { + throw DiffusionGemmaModelError.invalidInput("vision grid width") + } + projected.append(projector(tower(image, outputLength: lengths[index]))) + } + let features = concatenated(projected, axis: 1).asType(embeddings.dtype) + let flat = embeddings.reshaped(-1, configuration.textConfig.hiddenSize) + flat[MLXArray(positions)] = features.reshaped(-1, configuration.textConfig.hiddenSize) + embeddings = flat.reshaped(embeddings.shape) + if blockIds == nil { + var next: Int32 = -1 + var previous = false + let ids: [Int32] = flags.map { isVisual in + if isVisual && !previous { next += 1 } + previous = isVisual + return isVisual ? next : -1 + } + blockIds = MLXArray(ids).reshaped(tokenIds.shape) + } + } + return try model.decoder.encode( + tokenIds: tokenIds, cache: cache, + encoderParameters: model.encoder.languageModel, preparedEmbeddings: embeddings, + visualBlockIds: blockIds) + } + + public func denoise( + canvasIds: MLXArray, cache: DiffusionGemmaRequestCache, + selfConditioningLogits: MLXArray? = nil + ) throws -> MLXArray { + try model.decoder.denoise( + canvasIds: canvasIds, cache: cache, + selfConditioningLogits: selfConditioningLogits) + } + + public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + var result = [String: MLXArray]() + for (original, value) in weights { + var name = original + if name.hasSuffix(".experts.down_proj") || name.hasSuffix(".experts.gate_up_proj") { + name += ".weight" + } + if name.hasPrefix("model.encoder.vision_tower.") { + name = name.replacingOccurrences(of: ".linear.", with: ".") + } + // Preserve an alias collision as an unexpected input key so strict + // weight loading rejects it, rather than choosing one payload. + guard result[name] == nil else { return weights } + result[name] = value + } + return result + } + + public func quantizationPathAliases(for path: String) -> [String] { + path.hasPrefix("model.encoder.vision_tower.") ? [path + ".linear"] : [] + } +} diff --git a/Libraries/MLXVLM/Models/DiffusionGemmaVisionMath.swift b/Libraries/MLXVLM/Models/DiffusionGemmaVisionMath.swift new file mode 100644 index 0000000000..e7205e99d2 --- /dev/null +++ b/Libraries/MLXVLM/Models/DiffusionGemmaVisionMath.swift @@ -0,0 +1,37 @@ +import MLX + +/// Explicit FP32 power contract of the pinned MLX vision reference. Generic +/// Metal `pow` depends on library/compiler math-function defaults; multiplication +/// and a compiled x**2 are not bit-identical substitutes for this operation. +/// Scope this to the new architecture, preserving all existing model numerics. +enum DiffusionGemmaVisionMath { + private static let squareKernel = MLXFast.metalKernel( + name: "diffusion_gemma_vision_precise_square", + inputNames: ["x"], outputNames: ["out"], + source: """ + uint i = thread_position_in_grid.x; + out[i] = metal::precise::powr(metal::abs(x[i]), 2.0f); + """) + + static func square(_ input: MLXArray) -> MLXArray { + let x = input.asType(.float32) + return squareKernel( + [x], grid: (x.size, 1, 1), threadGroup: (min(256, x.size), 1, 1), + outputShapes: [x.shape], outputDTypes: [.float32])[0] + } + + private static let powerKernel = MLXFast.metalKernel( + name: "diffusion_gemma_vision_precise_positive_power", + inputNames: ["exponents", "base"], outputNames: ["out"], + source: """ + uint i = thread_position_in_grid.x; + out[i] = metal::precise::powr(base, exponents[i]); + """) + + static func positivePower(base: Float, exponents: MLXArray) -> MLXArray { + let x = exponents.asType(.float32) + return powerKernel( + [x, MLXArray(base)], grid: (x.size, 1, 1), threadGroup: (min(256, x.size), 1, 1), + outputShapes: [x.shape], outputDTypes: [.float32])[0] + } +} diff --git a/Libraries/MLXVLM/Models/Gemma4.swift b/Libraries/MLXVLM/Models/Gemma4.swift index 8749f42611..9c3a8ed9cd 100644 --- a/Libraries/MLXVLM/Models/Gemma4.swift +++ b/Libraries/MLXVLM/Models/Gemma4.swift @@ -42,14 +42,19 @@ private func gemma4IntExtent(_ size: CGSize) throws -> (Int, Int) { private class VisionRMSNorm: Module, UnaryLayer { let weight: MLXArray let eps: Float - init(dimensions: Int, eps: Float = 1e-6) { + let fused: Bool + let usePower: Bool + init(dimensions: Int, eps: Float = 1e-6, fused: Bool = false, usePower: Bool = false) { self.weight = MLXArray.ones([dimensions]) self.eps = eps + self.fused = fused + self.usePower = usePower super.init() } func callAsFunction(_ x: MLXArray) -> MLXArray { + if fused { return MLXFast.rmsNorm(x, weight: weight, eps: eps) } let xf = x.asType(.float32) - let v = (xf * xf).mean(axis: -1, keepDims: true) + let v = (usePower ? DiffusionGemmaVisionMath.square(xf) : xf * xf).mean(axis: -1, keepDims: true) return ((xf * rsqrt(v + eps)) * weight.asType(.float32)).asType(x.dtype) } } @@ -59,14 +64,22 @@ func rmsNormNoScale(_ x: MLXArray, eps: Float = 1e-6) -> MLXArray { MLXFast.rmsNorm(x, weight: MLXArray.mlxNone, eps: eps) } -private func visionRmsNormNoScale(_ x: MLXArray, eps: Float = 1e-6) -> MLXArray { +private func visionRmsNormNoScale(_ x: MLXArray, eps: Float = 1e-6, usePower: Bool = false) -> MLXArray { let xf = x.asType(.float32) - let v = (xf * xf).mean(axis: -1, keepDims: true) + let v = (usePower ? DiffusionGemmaVisionMath.square(xf) : xf * xf).mean(axis: -1, keepDims: true) return (xf * rsqrt(v + eps)).asType(x.dtype) } // MARK: - Configurations +/// Keep the existing Gemma4 path unchanged. DiffusionGemma's pinned vision +/// reference has different normalization/SDPA/grid contracts despite sharing +/// the same checkpoint parameter names. +enum Gemma4VisionContract { + case gemma4 + case diffusionGemma +} + public struct Gemma4VisionConfig: Codable, Sendable { let hiddenSize: Int let intermediateSize: Int @@ -235,7 +248,8 @@ private func rotateHalf(_ x: MLXArray) -> MLXArray { return concatenated([-x[.ellipsis, half...], x[.ellipsis, .. MLXArray { +private func applyMultidimensionalRope(_ inputs: MLXArray, positions: MLXArray, base: Float, + contract: Gemma4VisionContract = .gemma4) -> MLXArray { let headDim = inputs.dim(-1) let ndim = positions.dim(-1) let chPerDim = 2 * (headDim / (2 * ndim)) @@ -245,7 +259,8 @@ private func applyMultidimensionalRope(_ inputs: MLXArray, positions: MLXArray, for d in 0 ..< ndim { let xPart = inputs[.ellipsis, (d * chPerDim) ..< ((d + 1) * chPerDim)] let freqExp = (2.0 / Float(chPerDim)) * MLXArray(0 ..< halfPerDim).asType(.float32) - let timescale = pow(base, freqExp) + let timescale = contract == .diffusionGemma + ? DiffusionGemmaVisionMath.positivePower(base: base, exponents: freqExp) : pow(base, freqExp) let sinInp = positions[.ellipsis, d ..< (d + 1)].asType(.float32) / timescale var cosD = cos(sinInp) var sinD = sin(sinInp) @@ -269,6 +284,7 @@ private class VisionAttn: Module { let numKVHeads: Int let headDim: Int let ropeBase: Float + let contract: Gemma4VisionContract @ModuleInfo(key: "q_proj") var qProj: Linear @ModuleInfo(key: "k_proj") var kProj: Linear @@ -277,7 +293,8 @@ private class VisionAttn: Module { @ModuleInfo(key: "q_norm") var qNorm: VisionRMSNorm @ModuleInfo(key: "k_norm") var kNorm: VisionRMSNorm - init(_ cfg: Gemma4VisionConfig) { + init(_ cfg: Gemma4VisionConfig, contract: Gemma4VisionContract = .gemma4) { + self.contract = contract numHeads = cfg.numAttentionHeads numKVHeads = cfg.numKeyValueHeads headDim = cfg.headDim @@ -286,19 +303,29 @@ private class VisionAttn: Module { _kProj.wrappedValue = Linear(cfg.hiddenSize, numKVHeads * headDim, bias: false) _vProj.wrappedValue = Linear(cfg.hiddenSize, numKVHeads * headDim, bias: false) _oProj.wrappedValue = Linear(numHeads * headDim, cfg.hiddenSize, bias: false) - _qNorm.wrappedValue = VisionRMSNorm(dimensions: headDim) - _kNorm.wrappedValue = VisionRMSNorm(dimensions: headDim) + _qNorm.wrappedValue = VisionRMSNorm(dimensions: headDim, usePower: contract == .diffusionGemma) + _kNorm.wrappedValue = VisionRMSNorm(dimensions: headDim, usePower: contract == .diffusionGemma) super.init() } - func callAsFunction(_ x: MLXArray, positions: MLXArray, mask: MLXArray?) -> MLXArray { + func callAsFunction(_ x: MLXArray, positions: MLXArray, mask: MLXArray?, + trace: ((String, MLXArray) -> Void)? = nil) -> MLXArray { let (B, L) = (x.dim(0), x.dim(1)) var q = qProj(x).reshaped(B, L, numHeads, headDim) var k = kProj(x).reshaped(B, L, numKVHeads, headDim) var v = vProj(x).reshaped(B, L, numKVHeads, headDim) - q = qNorm(q); k = kNorm(k); v = visionRmsNormNoScale(v) - q = applyMultidimensionalRope(q, positions: positions, base: ropeBase) - k = applyMultidimensionalRope(k, positions: positions, base: ropeBase) + trace?("qRaw", q); trace?("kRaw", k); trace?("vRaw", v) + if let trace { + let squared = DiffusionGemmaVisionMath.square(q) + let mean = squared.mean(axis: -1, keepDims: true) + trace("qSquared", squared); trace("qMean", mean) + trace("qInv", rsqrt(mean + Float(1e-6))) + } + q = qNorm(q); k = kNorm(k); v = visionRmsNormNoScale(v, usePower: contract == .diffusionGemma) + trace?("qNorm", q); trace?("kNorm", k); trace?("vNorm", v) + q = applyMultidimensionalRope(q, positions: positions, base: ropeBase, contract: contract) + k = applyMultidimensionalRope(k, positions: positions, base: ropeBase, contract: contract) + trace?("qRope", q); trace?("kRope", k) q = q.transposed(0, 2, 1, 3); k = k.transposed(0, 2, 1, 3); v = v.transposed(0, 2, 1, 3) // vmlx #52: Gemma 4 vision tower weights are float16 and attention // scores can exceed ±65504, producing -inf → NaN propagation through @@ -306,32 +333,57 @@ private class VisionAttn: Module { // float32 for the SDPA, then cast back. Mirrors the Python // v1.3.29 patch. let origDType = q.dtype - if origDType == .float16 { + if origDType == .float16 && contract == .gemma4 { q = q.asType(.float32) k = k.asType(.float32) v = v.asType(.float32) } + if contract == .diffusionGemma { + // Same zero-padding as MLX-VLM ensure_fused_sdpa; the released + // 72-wide heads use the 80-wide fused reduction, then slice back. + let target = [64, 80, 128].first { headDim <= $0 } ?? headDim + if target != headDim { + let widths: [IntOrPair] = [0, 0, 0, [0, target - headDim]] + q = padded(q, widths: widths) + k = padded(k, widths: widths) + v = padded(v, widths: widths) + } + } var out = MLXFast.scaledDotProductAttention( queries: q, keys: k, values: v, scale: 1.0, mask: mask != nil ? .array(mask!) : .none) - if origDType == .float16 { + if contract == .diffusionGemma { out = out[.ellipsis, .. MLXArray { downProj(safeGeluApproximate(gateProj(x)) * upProj(x)) } + func callAsFunction(_ x: MLXArray, trace: ((String, MLXArray) -> Void)? = nil) -> MLXArray { + let gate = gateProj(x) + let activated = contract == .diffusionGemma ? geluApproximate(gate) : safeGeluApproximate(gate) + let up = upProj(x) + trace?("gate", gate); trace?("up", up); trace?("activation", activated) + let down = downProj(activated * up) + trace?("down", down) + return down + } } private class VisionBlock: Module { @@ -342,19 +394,29 @@ private class VisionBlock: Module { @ModuleInfo(key: "pre_feedforward_layernorm") var preFFLN: VisionRMSNorm @ModuleInfo(key: "post_feedforward_layernorm") var postFFLN: VisionRMSNorm - init(_ cfg: Gemma4VisionConfig) { - _selfAttn.wrappedValue = VisionAttn(cfg) - self.mlp = VisionMLP(cfg) - _inputLN.wrappedValue = VisionRMSNorm(dimensions: cfg.hiddenSize, eps: cfg.rmsNormEps) - _postAttnLN.wrappedValue = VisionRMSNorm(dimensions: cfg.hiddenSize, eps: cfg.rmsNormEps) - _preFFLN.wrappedValue = VisionRMSNorm(dimensions: cfg.hiddenSize, eps: cfg.rmsNormEps) - _postFFLN.wrappedValue = VisionRMSNorm(dimensions: cfg.hiddenSize, eps: cfg.rmsNormEps) + init(_ cfg: Gemma4VisionConfig, contract: Gemma4VisionContract = .gemma4) { + _selfAttn.wrappedValue = VisionAttn(cfg, contract: contract) + self.mlp = VisionMLP(cfg, contract: contract) + let fused = contract == .diffusionGemma + _inputLN.wrappedValue = VisionRMSNorm(dimensions: cfg.hiddenSize, eps: cfg.rmsNormEps, fused: fused) + _postAttnLN.wrappedValue = VisionRMSNorm(dimensions: cfg.hiddenSize, eps: cfg.rmsNormEps, fused: fused) + _preFFLN.wrappedValue = VisionRMSNorm(dimensions: cfg.hiddenSize, eps: cfg.rmsNormEps, fused: fused) + _postFFLN.wrappedValue = VisionRMSNorm(dimensions: cfg.hiddenSize, eps: cfg.rmsNormEps, fused: fused) super.init() } - func callAsFunction(_ x: MLXArray, positions: MLXArray, mask: MLXArray?) -> MLXArray { - var h = x + postAttnLN(selfAttn(inputLN(x), positions: positions, mask: mask)) - h = h + postFFLN(mlp(preFFLN(h))) + func callAsFunction(_ x: MLXArray, positions: MLXArray, mask: MLXArray?, + trace: ((String, MLXArray) -> Void)? = nil) -> MLXArray { + let normalized = inputLN(x) + trace?("inputNorm", normalized) + let post = postAttnLN(selfAttn(normalized, positions: positions, mask: mask, trace: trace)) + trace?("postAttention", post) + var h = x + post + trace?("residual", h) + let pre = preFFLN(h) + trace?("preFFN", pre) + h = h + postFFLN(mlp(pre, trace: trace)) + trace?("output", h) return h } } @@ -421,27 +483,38 @@ private class VisionPooler: Module { private class VisionEncoder: Module { @ModuleInfo var layers: [VisionBlock] - init(_ cfg: Gemma4VisionConfig) { - _layers.wrappedValue = (0 ..< cfg.numHiddenLayers).map { _ in VisionBlock(cfg) } + init(_ cfg: Gemma4VisionConfig, contract: Gemma4VisionContract = .gemma4) { + _layers.wrappedValue = (0 ..< cfg.numHiddenLayers).map { _ in VisionBlock(cfg, contract: contract) } super.init() } - func callAsFunction(_ x: MLXArray, pos: MLXArray, mask: MLXArray?) -> MLXArray { - var h = x; for l in layers { h = l(h, positions: pos, mask: mask) }; return h + func callAsFunction(_ x: MLXArray, pos: MLXArray, mask: MLXArray?, + trace: ((String, MLXArray) -> Void)? = nil) -> MLXArray { + var h = x + for (index, layer) in layers.enumerated() { + let observe: ((String, MLXArray) -> Void)? = trace.map { callback in + { name, array in callback("block\(index)." + name, array) } + } + h = layer(h, positions: pos, mask: mask, trace: observe) + } + return h } } -private class VisionTower: Module { +// Shared tower implementation; architecture-specific projectors remain separate. +class Gemma4VisionTower: Module { let cfg: Gemma4VisionConfig - @ModuleInfo(key: "patch_embedder") var patchEmb: VisionPatchEmbedder - @ModuleInfo var encoder: VisionEncoder - @ModuleInfo var pooler: VisionPooler + let contract: Gemma4VisionContract + @ModuleInfo(key: "patch_embedder") private var patchEmb: VisionPatchEmbedder + @ModuleInfo private var encoder: VisionEncoder + @ModuleInfo private var pooler: VisionPooler @ModuleInfo(key: "std_bias") var stdBias: MLXArray? @ModuleInfo(key: "std_scale") var stdScale: MLXArray? - init(_ cfg: Gemma4VisionConfig) { + init(_ cfg: Gemma4VisionConfig, contract: Gemma4VisionContract = .gemma4) { self.cfg = cfg + self.contract = contract _patchEmb.wrappedValue = VisionPatchEmbedder(cfg) - self.encoder = VisionEncoder(cfg) + self.encoder = VisionEncoder(cfg, contract: contract) self.pooler = VisionPooler(cfg) if cfg.standardize { _stdBias.wrappedValue = MLXArray.zeros([cfg.hiddenSize]); _stdScale.wrappedValue = MLXArray.ones([cfg.hiddenSize]) } super.init() @@ -451,7 +524,11 @@ private class VisionTower: Module { /// defaults to the image budget (`defaultOutputLength`); video frames pass a /// smaller per-frame budget so the local patch budget (`outputLength * pool^2`) /// and the pooler output both shrink to the trained video-frame representation. - func callAsFunction(_ pixels: MLXArray, outputLength: Int? = nil) -> MLXArray { + func callAsFunction(_ pixels: MLXArray, outputLength: Int? = nil, + trace: ((String, MLXArray) -> Void)? = nil) -> MLXArray { + if contract == .diffusionGemma { + return diffusionFeatures(pixels, outputLength: outputLength, trace: trace) + } let (B, _, H, W) = (pixels.dim(0), pixels.dim(1), pixels.dim(2), pixels.dim(3)) let outLen = outputLength ?? cfg.defaultOutputLength let localMaxPatches = max(1, outLen) * cfg.poolingKernelSize * cfg.poolingKernelSize @@ -507,6 +584,33 @@ private class VisionTower: Module { if cfg.standardize, let sb = stdBias, let ss = stdScale { h = (h - sb) * ss } return h } + + /// Raw images are already resized to a patch/pool-aligned grid by the + /// processor. The reference uses the actual grid, not a padded maximum + /// budget; changing that length also changes attention and pooled features. + private func diffusionFeatures(_ pixels: MLXArray, outputLength: Int?, + trace: ((String, MLXArray) -> Void)?) -> MLXArray { + let batch = pixels.dim(0) + let height = pixels.dim(2) / cfg.patchSize + let width = pixels.dim(3) / cfg.patchSize + let count = height * width + let length = count / (cfg.poolingKernelSize * cfg.poolingKernelSize) + precondition(height.isMultiple(of: cfg.poolingKernelSize) && width.isMultiple(of: cfg.poolingKernelSize)) + precondition(length > 0 && (outputLength == nil || outputLength == length)) + var positions = [Int32]() + for y in 0..