Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
b07eeb8
Add DeepSeek-V4 (deepseek_v4) text model
Augustas11 Nov 13, 2026
71b60ec
Add DeepSeek-V4 tests, tiny fixture and fixture generator
Augustas11 Nov 13, 2026
d849fe4
DeepSeek-V4: exact indexer top-k by default, required compress_ratios
Augustas11 Nov 13, 2026
3c56fb1
DeepSeek-V4: carry the overlap window across calls
Augustas11 Nov 13, 2026
89b68d3
DeepSeek-V4: generate the tiny fixture from DeepSeek's reference
Augustas11 Nov 13, 2026
45f6efb
DeepSeek-V4: follow the reference's float32 placement
Augustas11 Nov 13, 2026
7324f75
DeepSeek-V4: keep the reference's float32 weights in float32 at load
Augustas11 Nov 13, 2026
aadd057
DeepseekV4Tests: wrap one assertion as swift-format does
Augustas11 Nov 13, 2026
53b39aa
DeepSeek-V4: keep the RMSNorm weights in float32 at load
Augustas11 Nov 14, 2026
fb74094
DeepSeek-V4: compile the query head normalization on the GPU
Augustas11 Nov 14, 2026
7fda001
DeepSeek-V4: fewer compressor casts per step
Augustas11 Nov 14, 2026
ca80ba9
DeepSeek-V4: compile one function per device type
Augustas11 Nov 14, 2026
b11433c
DeepseekV4Tests: norm weight update and device-order logits checks
Augustas11 Nov 14, 2026
b516e59
DeepseekV4Tests: prefill the device-order check in 7-token chunks
Augustas11 Nov 15, 2026
aa99986
DeepseekV4Tests: build the tiny model in code, drop the safetensors f…
Augustas11 Nov 17, 2026
0711691
DeepseekV4Tests: smaller tests, pinned reference generator
Augustas11 Nov 17, 2026
9f23239
DeepSeek-V4: remove the opt-in HISA indexer selection
Augustas11 Nov 17, 2026
8f2c9a1
DeepSeek-V4: shorten comments to one or two lines
Augustas11 Nov 17, 2026
b6b3328
DeepseekV4Tests: run the 250-token reference case by default
Augustas11 Nov 17, 2026
1894f62
DeepseekV4Tests: fused-kernel check on random rows, fewer duplicates
Augustas11 Nov 17, 2026
389849e
Merge upstream/main into deepseek-v4-text-model
Augustas11 Nov 30, 2026
7269d91
Send hyper-connection widths not divisible by 4 to the op path
Augustas11 Nov 30, 2026
a6c0ef2
Reject KV cache requests DeepSeek-V4 cannot honour
Augustas11 Nov 30, 2026
316fffe
Trim and save DeepSeek-V4 pool caches
Augustas11 Nov 30, 2026
02263fd
Register the DeepSeek-V4 pool cache when the model is made
Augustas11 Nov 30, 2026
73f1429
Give DeepSeek-V4 windows the requested rewind reserve
Augustas11 Nov 30, 2026
1f00a70
Document that DeepSeek-V4 rejects KV quantization only in newCache
Augustas11 Nov 30, 2026
a4b7bb2
Check DeepSeek-V4 pool cache shapes and offset on restore
Augustas11 Nov 30, 2026
43e5b03
Define the DeepSeek-V4 pool cache's isTrimmable as isTrimmable(after: 0)
Augustas11 Nov 30, 2026
dfd984a
Copy the kept DeepSeek-V4 pool windows out of the prefill chunk
Augustas11 Nov 30, 2026
867b0c3
Parse DeepSeek-V4 DSML tool calls
Augustas11 Nov 30, 2026
f2e670a
Declare DeepSeek-V4 reasoning with a string thinking_mode
Augustas11 Nov 30, 2026
bad1faf
Ship a DeepSeek-V4 chat template
Augustas11 Nov 30, 2026
e069611
Write DeepSeek-V4 template JSON without tojson
Augustas11 Dec 1, 2026
c027e1b
Require object arguments in the DeepSeek-V4 template
Augustas11 Dec 1, 2026
b2e5980
Check the DeepSeek-V4 template against DeepSeek's encoder
Augustas11 Dec 1, 2026
a0b1fde
Keep a checkpoint template that already prompts DSML
Augustas11 Dec 1, 2026
a972b35
Throw when a tokenizer cannot render a given chat template
Augustas11 Dec 1, 2026
4054017
Drop the unused chat template override from ParoQuantLoader
Augustas11 Dec 1, 2026
21b1df5
Narrow DeepSeek-V4 tool format inference
Augustas11 Dec 1, 2026
2f3fed8
Close a DSML invoke only between its parameters
Augustas11 Dec 1, 2026
6e89092
Render the DeepSeek-V4 template fixture through the tokenizer
Augustas11 Dec 1, 2026
8973e81
Declare DeepSeek-V4's budget transition
Augustas11 Dec 1, 2026
3afcaf3
Docs: use code voice for package-internal chatTemplate(replacingTempl…
Augustas11 Dec 2, 2026
74fb152
Tokenizer: move chat template rendering to ChatTemplateRendering refi…
Augustas11 Dec 2, 2026
c243213
IntegrationTesting: cast tokenizer to ChatTemplateRendering in Deepse…
Augustas11 Dec 2, 2026
5b0316e
Merge upstream/main into deepseek-v4-text-model
Augustas11 Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Copyright © 2026 Apple Inc.

import Foundation
import HuggingFace
import MLXHuggingFace
import MLXLLM
import MLXLMCommon
import Testing
import Tokenizers

private let deepseekV4Downloader: any Downloader = #hubDownloader()
private let deepseekV4TokenizerLoader: any TokenizerLoader = #huggingFaceTokenizerLoader()

/// swift-transformers renders ``DeepseekV4ChatTemplate`` exactly as Python's Jinja does.
///
/// The expected strings come from `tools/deepseek-v4-chat-template.py`, which renders
/// the same conversations (tool calls, tool results, thinking on and off) with jinja2
/// in the environment Hugging Face transformers uses and checks each against
/// DeepSeek's own encoder. Rendering goes through the tokenizer's
/// `applyChatTemplate(messages:chatTemplate:tools:additionalContext:)`, the path
/// `LLMModelFactory` uses, so whichever swift-jinja swift-transformers resolves is
/// the one tested.
struct DeepseekV4ChatTemplateTests {
private struct Case {
let name: String
let context: [String: any Sendable]
let expected: String
}

private static func fixture() throws -> (template: String, cases: [Case]) {
let url = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("tools/deepseek-v4-chat-template.json")
let object = try JSONSerialization.jsonObject(with: Data(contentsOf: url))
let fixture = try #require(object as? [String: Any])
let template = try #require(fixture["template"] as? String)
let cases = try #require(fixture["cases"] as? [[String: Any]]).map { entry in
Case(
name: try #require(entry["name"] as? String),
context: try #require(sendable(entry["context"] as Any) as? [String: any Sendable]),
expected: try #require(entry["expected"] as? String))
}
return (template, cases)
}

/// JSON as the Swift values a caller passes, with booleans kept apart from numbers.
private static func sendable(_ value: Any) -> any Sendable {
switch value {
case let number as NSNumber where CFGetTypeID(number) == CFBooleanGetTypeID():
return number.boolValue
case let number as NSNumber:
return number.intValue
case let string as String:
return string
case let array as [Any]:
return array.map(sendable)
case let object as [String: Any]:
return object.mapValues(sendable)
default:
return String(describing: value)
}
}

private static func tokenizer() async throws -> any MLXLMCommon.Tokenizer {
let directory = try await deepseekV4Downloader.download(
id: "deepseek-ai/DeepSeek-V4-Flash",
revision: "60d8d70770c6776ff598c94bb586a859a38244f1",
matching: ["tokenizer.json", "tokenizer_config.json"],
useLatest: false, progressHandler: { _ in })
return try await deepseekV4TokenizerLoader.load(from: directory)
}

@Test func fixtureMatchesTheShippedTemplate() throws {
#expect(try Self.fixture().template == DeepseekV4ChatTemplate.jinja)
}

@Test func swiftTransformersRendersWhatPythonJinjaRenders() async throws {
let cases = try Self.fixture().cases
#expect(cases.count >= 5)
let tokenizer = try #require(
try await Self.tokenizer() as? any MLXLMCommon.ChatTemplateRendering)
for testCase in cases {
var context = testCase.context
let messages = try #require(
context.removeValue(forKey: "messages") as? [[String: any Sendable]])
let tools = context.removeValue(forKey: "tools") as? [[String: any Sendable]]
// The tokenizer supplies these from tokenizer_config.json and its own argument.
let bosToken = context.removeValue(forKey: "bos_token") as? String
let addGenerationPrompt = context.removeValue(forKey: "add_generation_prompt") as? Bool
#expect(bosToken == "<|begin▁of▁sentence|>")
#expect(addGenerationPrompt == true)

let rendered = try tokenizer.applyChatTemplate(
messages: messages, chatTemplate: DeepseekV4ChatTemplate.jinja, tools: tools,
additionalContext: context.isEmpty ? nil : context)
#expect(
rendered == tokenizer.encode(text: testCase.expected, addSpecialTokens: false),
"\(testCase.name)")
#expect(
tokenizer.decode(tokenIds: rendered, skipSpecialTokens: false)
== testCase.expected, "\(testCase.name)")
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright © 2026 Apple Inc.

import Foundation
import MLX
import MLXLLM
import MLXLMCommon
import MLXNN
import XCTest

final class DeepseekV4CheckpointTests: XCTestCase {

private func checkpoint() throws -> (URL, DeepseekV4Configuration, BaseConfiguration) {
guard let path = ProcessInfo.processInfo.environment["MLX_DEEPSEEK_V4_CHECKPOINT"] else {
throw XCTSkip(
"Set MLX_DEEPSEEK_V4_CHECKPOINT to an MXFP4 MLX conversion of DeepSeek-V4-Flash")
}
let directory = URL(filePath: path)
let data = try Data(contentsOf: directory.appending(component: "config.json"))
let config = try JSONDecoder().decode(DeepseekV4Configuration.self, from: data)
try config.validateModelConfiguration()
return (directory, config, try JSONDecoder().decode(BaseConfiguration.self, from: data))
}

/// The safetensors headers against the module tree after sanitize and per-layer
/// quantization; no weight is read.
func testCheckpointLayoutMatchesModuleTree() throws {
let (directory, config, base) = try checkpoint()
try Device.withDefaultDevice(.cpu) {
let dtypes: [String: DType] = [
"BF16": .bfloat16, "F32": .float32, "U8": .uint8, "U32": .uint32,
"I64": .int64, "I32": .int32,
]
var weights = [String: MLXArray]()
let files = try FileManager.default.contentsOfDirectory(atPath: directory.path())
.filter { $0.hasSuffix(".safetensors") }
XCTAssertFalse(files.isEmpty)
for file in files {
let handle = try FileHandle(
forReadingFrom: directory.appending(component: file))
defer { try? handle.close() }
let size = try XCTUnwrap(handle.read(upToCount: 8)).withUnsafeBytes {
$0.loadUnaligned(as: UInt64.self)
}
let header = try XCTUnwrap(handle.read(upToCount: Int(size)))
let entries = try XCTUnwrap(
JSONSerialization.jsonObject(with: header) as? [String: Any])
for (name, value) in entries where name != "__metadata__" {
let entry = try XCTUnwrap(value as? [String: Any])
let shape = try XCTUnwrap(entry["shape"] as? [Int])
let dtype = try XCTUnwrap(dtypes[try XCTUnwrap(entry["dtype"] as? String)])
weights[name] = MLXArray.zeros(shape, dtype: dtype)
}
}
let model = DeepseekV4Model(config)
let sanitized = model.sanitize(weights: weights)
quantize(model: model) { path, _ in
sanitized["\(path).scales"] != nil
? base.perLayerQuantization?.quantization(layer: path)?.asTuple : nil
}
try model.update(
parameters: ModuleParameters.unflattened(sanitized), verify: [.all])
let modes = Dictionary(
uniqueKeysWithValues: model.leafModules().flattened().compactMap {
key, module -> (String, QuantizationMode)? in
(module as? any Quantized).map { (key, $0.mode) }
})
XCTAssertEqual(modes["layers.2.ffn.switch_mlp.gate_proj"], .mxfp4)
XCTAssertEqual(modes["layers.2.ffn.shared_experts.w1"], .mxfp8)
XCTAssertEqual(modes["layers.2.attn.wo_a"], .mxfp8)
XCTAssertEqual(modes["layers.2.attn.indexer.wq_b"], .mxfp8)
XCTAssertNil(modes["layers.2.attn.compressor.wkv"])
XCTAssertNil(modes["head"])
}
}

/// The loaded checkpoint prefills 512 tokens in chunks and decodes 8 greedy steps with
/// finite logits.
func testCheckpointPrefillAndDecode() throws {
let (directory, config, base) = try checkpoint()
let model = DeepseekV4Model(config)
try loadWeights(
modelDirectory: directory, model: model,
perLayerQuantization: base.perLayerQuantization)
model.train(false) // as `ModelContext` does: the inference path (fused kernel on the GPU)
let count = 512
let tokens = MLXArray((0 ..< count).map { Int32(($0 * 7 + 3) % model.vocabularySize) })
.reshaped(1, count)
let cache = try model.newCache(parameters: nil)
var logits = MLXArray()
for offset in stride(from: 0, to: count, by: 256) {
logits = model(tokens[0..., offset ..< (offset + 256)], cache: cache)[0..., (-1)...]
eval(logits)
eval(cache)
}
XCTAssertTrue(all(isFinite(logits)).item(Bool.self), "prefill")
for _ in 0 ..< 8 {
logits = model(argMax(logits[0, -1]).reshaped(1, 1), cache: cache)
eval(logits)
XCTAssertTrue(all(isFinite(logits)).item(Bool.self), "decode")
}
}
}
16 changes: 9 additions & 7 deletions Libraries/MLXFoundationModels/MLXLanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -825,7 +825,7 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
// but the resolved configuration carries a reasoning
// config, the model must not be allowed to think:
//
// - Toggleable strategies (`.templateFlag`) re-render the
// - Toggleable strategies (`.templateFlag`, `.templateValue`) re-render the
// prompt with thinking off (handled below per path).
// - Non-suppressible strategies (`.alwaysOn`) raise
// `unsupportedCapability` BEFORE generation, regardless
Expand Down Expand Up @@ -933,7 +933,7 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
let thinkThenCallConfig: ReasoningConfig? = {
guard declaresReasoning,
let cfg = resolved.reasoningConfig,
case .templateFlag(_, let defaultOn) = cfg.promptStrategy,
let defaultOn = cfg.promptStrategy.toggleDefault,
Self.thinkingEnabled(
for: request.contextOptions.reasoningLevel,
defaultOn: defaultOn)
Expand All @@ -950,7 +950,8 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
// Thread `enable_thinking` through the tool-aware template
// so the prompt's thinking state matches how we drive
// generation. For a toggleable model (`.templateFlag`, e.g.
// Qwen3 whose `enable_thinking` defaults ON) the effective
// Qwen3 whose `enable_thinking` defaults ON, or
// `.templateValue`, e.g. DeepSeek-V4's `thinking_mode`) the effective
// value is:
// - reasoning declared: honor the requested level, falling
// back to the template's own `defaultOn` when the caller
Expand All @@ -971,16 +972,17 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
// rejected by the capability gate above; `.none`/no-config
// models take no context.
let toolAwareContext: [String: any Sendable]?
if case .templateFlag(let key, let defaultOn)? =
resolved.reasoningConfig?.promptStrategy
if let strategy = resolved.reasoningConfig?.promptStrategy,
let defaultOn = strategy.toggleDefault
{
let enabled =
declaresReasoning
? Self.thinkingEnabled(
for: request.contextOptions.reasoningLevel,
defaultOn: defaultOn)
: false
toolAwareContext = [key: enabled]
toolAwareContext = try strategy.additionalContext(
forThinkingEnabled: enabled)
} else {
toolAwareContext = nil
}
Expand Down Expand Up @@ -1893,7 +1895,7 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
}
}

/// The effective thinking state for a `.templateFlag` model: an
/// The effective thinking state for a toggleable model: an
/// unspecified level defers to the template's own `defaultOn`.
///
/// Resolve through this rather than collapsing the optional at the call site.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public struct TokenizerAdaptorMacro: ExpressionMacro {
// import Tokenizers
//
{ (huggingFaceTokenizer: Tokenizers.Tokenizer) -> MLXLMCommon.Tokenizer in
struct TokenizerBridge: MLXLMCommon.Tokenizer {
struct TokenizerBridge: MLXLMCommon.ChatTemplateRendering {
private let upstream: any Tokenizers.Tokenizer

init(_ upstream: any Tokenizers.Tokenizer) {
Expand Down Expand Up @@ -121,6 +121,18 @@ public struct TokenizerAdaptorMacro: ExpressionMacro {
throw MLXLMCommon.TokenizerError.missingChatTemplate
}
}

func applyChatTemplate(
messages: [[String: any Sendable]],
chatTemplate: String,
tools: [[String: any Sendable]]?,
additionalContext: [String: any Sendable]?
) throws -> [Int] {
try upstream.applyChatTemplate(
messages: messages, chatTemplate: .literal(chatTemplate),
addGenerationPrompt: true, truncation: false, maxLength: nil,
tools: tools, additionalContext: additionalContext)
}
}

return TokenizerBridge(huggingFaceTokenizer)
Expand Down
11 changes: 9 additions & 2 deletions Libraries/MLXLLM/LLMModelFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ public enum LLMTypeRegistry {
"internlm2": create(InternLM2Configuration.self, InternLM2Model.init),
"deepseek_v2": create(DeepseekV2Configuration.self, DeepseekV2Model.init),
"deepseek_v3": create(DeepseekV3Configuration.self, DeepseekV3Model.init),
"deepseek_v4": create(DeepseekV4Configuration.self, DeepseekV4Model.init),
"granite": create(GraniteConfiguration.self, GraniteModel.init),
"helium": create(HeliumConfiguration.self, HeliumModel.init),
"granitemoehybrid": create(
Expand Down Expand Up @@ -691,7 +692,8 @@ private struct LLMUserInputProcessor: UserInputProcessor {
let messages = messageGenerator.generate(from: input)
do {
let promptTokens = try tokenizer.applyChatTemplate(
messages: messages, tools: input.tools, additionalContext: input.additionalContext)
messages: messages, overridingTemplate: configuration.chatTemplate,
tools: input.tools, additionalContext: input.additionalContext)

return LMInput(tokens: MLXArray(promptTokens))
} catch TokenizerError.missingChatTemplate {
Expand Down Expand Up @@ -828,6 +830,10 @@ public final class LLMModelFactory: GenericModelFactory {
modelId: modelId, modelType: baseConfig.modelType)
?? model.reasoningConfig
}
if mutableConfiguration.chatTemplate == nil {
mutableConfiguration.chatTemplate = model.chatTemplate(
replacingTemplateIn: configuration.tokenizerDirectory)
}

// Load tokenizer and weights in parallel
async let tokenizerTask = tokenizerLoader.load(
Expand Down Expand Up @@ -856,7 +862,7 @@ public final class LLMModelFactory: GenericModelFactory {
configuration.tokenizerDirectory == modelDirectory
? nil
: .directory(configuration.tokenizerDirectory)
let modelConfig = ModelConfiguration(
var modelConfig = ModelConfiguration(
directory: modelDirectory,
tokenizerSource: tokenizerSource,
defaultPrompt: configuration.defaultPrompt,
Expand All @@ -867,6 +873,7 @@ public final class LLMModelFactory: GenericModelFactory {
reasoningConfig: mutableConfiguration.reasoningConfig,
messageGenerator: mutableConfiguration.messageGenerator,
generationConfig: mutableConfiguration.generationConfig)
modelConfig.chatTemplate = mutableConfiguration.chatTemplate

let processor = LLMUserInputProcessor(
tokenizer: tokenizer, configuration: modelConfig,
Expand Down
18 changes: 18 additions & 0 deletions Libraries/MLXLLM/Models/DeepseekV4+Chat.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright © 2026 Apple Inc.

import MLXLMCommon

// MARK: - Chat conventions

extension DeepseekV4Model {
/// DeepSeek-V4 writes tool calls in DSML (`<|DSML|tool_calls>` blocks).
public var toolCallFormat: ToolCallFormat? { .deepseekV4 }

/// `<think>` / `</think>`, toggled by the string `thinking_mode` template argument.
public var reasoningConfig: ReasoningConfig? { .deepseekV4 }

/// The official checkpoint ships no chat template and conversions ship one
/// without tools; see ``DeepseekV4ChatTemplate``. A checkpoint whose own
/// template prompts DSML tool calls keeps it.
public var chatTemplate: String? { DeepseekV4ChatTemplate.jinja }
}
Loading
Loading