Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix: simplify mlx-server backend with new ChatSession update (#7538)

Louis305e2a8bdc77
diff --git a/.gitignore b/.gitignore
index 6994708ac..ca807a51f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -63,6 +63,4 @@ src-tauri/resources/
test-data
llm-docs
.claude/agents
-mlx-server/.build
-mlx-server/.swiftpm
.claude
diff --git a/extensions/mlx-extension/settings.json b/extensions/mlx-extension/settings.json
index f8b83511c..b330668a3 100644
--- a/extensions/mlx-extension/settings.json
+++ b/extensions/mlx-extension/settings.json
@@ -1,23 +1,4 @@
[
- {
- "key": "batch_size",
- "title": "Batch Size",
- "description": "Maximum number of concurrent requests to batch (0 = disabled)",
- "controllerType": "input",
- "controllerProps": {
- "value": 4,
- "placeholder": "4",
- "type": "number",
- "textAlign": "right"
- }
- },
- {
- "key": "enable_continuous_batching",
- "title": "Continuous Batching",
- "description": "Enable continuous batching for higher throughput",
- "controllerType": "checkbox",
- "controllerProps": { "value": false }
- },
{
"key": "auto_unload",
"title": "Auto unload model",
diff --git a/extensions/mlx-extension/src/index.ts b/extensions/mlx-extension/src/index.ts
index e39c3c079..13541e011 100644
--- a/extensions/mlx-extension/src/index.ts
+++ b/extensions/mlx-extension/src/index.ts
@@ -300,15 +300,6 @@ export default class mlx_extension extends AIEngine {
const mlxConfig: MlxConfig = {
ctx_size: cfg.ctx_size ?? 4096,
- n_predict: cfg.n_predict ?? 0,
- threads: cfg.threads ?? 0,
- chat_template: cfg.chat_template ?? '',
- // Batching configuration
- batch_size: cfg.batch_size ?? 4,
- batch_timeout_ms: cfg.batch_timeout_ms ?? 100,
- enable_continuous_batching: cfg.enable_continuous_batching ?? false,
- kv_block_size: cfg.kv_block_size ?? 16,
- enable_prefix_caching: cfg.enable_prefix_caching ?? true,
}
logger.info(
diff --git a/mlx-server/.gitignore b/mlx-server/.gitignore
new file mode 100644
index 000000000..f2654ee15
--- /dev/null
+++ b/mlx-server/.gitignore
@@ -0,0 +1,2 @@
+.build
+.swiftpm
diff --git a/mlx-server/Package.swift b/mlx-server/Package.swift
index 63c3b876b..047310d10 100644
--- a/mlx-server/Package.swift
+++ b/mlx-server/Package.swift
@@ -1,4 +1,4 @@
-// swift-tools-version: 5.9
+// swift-tools-version: 5.12
import PackageDescription
@@ -11,8 +11,8 @@ let package = Package(
.executable(name: "mlx-server", targets: ["MLXServer"])
],
dependencies: [
- .package(url: "https://github.com/ml-explore/mlx-swift", from: "0.30.3"),
- .package(url: "https://github.com/ml-explore/mlx-swift-lm", revision: "2c70054"),
+ .package(url: "https://github.com/ml-explore/mlx-swift", .upToNextMinor(from: "0.30.6")),
+ .package(url: "https://github.com/ml-explore/mlx-swift-lm", branch: "main"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"),
.package(url: "https://github.com/hummingbird-project/hummingbird", from: "2.19.0"),
],
diff --git a/mlx-server/README.md b/mlx-server/README.md
index 91ce49fdc..4161a7a48 100644
--- a/mlx-server/README.md
+++ b/mlx-server/README.md
@@ -6,14 +6,12 @@ A high-performance inference server for MLX models, providing an OpenAI-compatib
- **OpenAI-Compatible API** - Drop-in replacement for OpenAI API calls
- **Streaming Support** - Server-Sent Events for real-time token streaming
-- **Batching** - Configurable batch processing for improved throughput
-- **Prefix Caching** - KV cache optimization for repeated prompts
- **Tool Calling** - Support for function calls (OpenAI-compatible format)
- **Multi-Model Support** - LLM and VLM model support
## Requirements
-- macOS 14.0+ ( Sonoma or later)
+- macOS 14.0+ (Sonoma or later)
- Apple Silicon (M1, M2, M3, M4)
- Xcode 15+ for building
- At least 8GB of unified memory
@@ -27,49 +25,18 @@ A high-performance inference server for MLX models, providing an OpenAI-compatib
cd mlx-server
# Build in release mode
-swift build -c release
+xcodebuild -scheme mlx-server -configuration Release
-# The binary will be at:
-# .build/arm64-apple-macosx/release/mlx-server
-```
-
-### Metallib Setup
-
-MLX requires a compiled metallib for GPU operations. The metallib is automatically built when using Xcode. For Swift Package Manager builds, copy the metallib:
-
-```bash
-# Find the metallib from Xcode build products
-METALLIB_PATH=$(find ~/Library/Developer/Xcode/DerivedData -name "default.metallib" | head -1)
-
-# Copy to the release build directory
-cp "$METALLIB_PATH" .build/arm64-apple-macosx/release/
+# The binary and metallib will be in the Xcode derived data build products
```
## Quick Start
-### Basic Usage
-
```bash
# Run with a local MLX model
./.build/arm64-apple-macosx/release/mlx-server \
--model "/path/to/your/model" \
--port 8080
-
-# Or with a HuggingFace model ID
-./.build/arm64-apple-macosx/release/mlx-server \
- --model "mlx-community/Qwen3-0.6B-4bit" \
- --port 8080
-```
-
-### With Performance Optimizations
-
-```bash
-# Enable continuous batching for better throughput
-./.build/arm64-apple-macosx/release/mlx-server \
- --model "/path/to/model" \
- --port 8080 \
- --max-batch-size 8 \
- --enable-continuous-batching
```
## Command-Line Options
@@ -79,13 +46,7 @@ cp "$METALLIB_PATH" .build/arm64-apple-macosx/release/
| `-m, --model` | Required | Path to model directory or HuggingFace model ID |
| `--port` | 8080 | HTTP server port |
| `--ctx-size` | 4096 | Context window size |
-| `--api-key` | "" | API key for authentication |
-| `--chat-template` | "" | Path to custom chat template file (for thinking models) |
-| `--max-batch-size` | 0 | Maximum batch size (0 = disabled) |
-| `--batch-timeout-ms` | 100 | Batch timeout in milliseconds |
-| `--enable-continuous-batching` | false | Enable continuous batching |
-| `--kv-block-size` | 16 | KV cache block size in tokens |
-| `--enable-prefix-caching` | false | Enable prefix caching (requires max-batch-size > 0) |
+| `--api-key` | `""` | API key for authentication (optional) |
## API Endpoints
@@ -117,68 +78,22 @@ curl -X POST http://localhost:8080/v1/chat/completions \
}'
```
-### List Models
-
-```bash
-curl http://localhost:8080/v1/models
-```
-
-### Health Check
+### Cancel Active Generation
```bash
-curl http://localhost:8080/health
+curl -X POST http://localhost:8080/v1/cancel
```
-### Metrics
-
-```bash
-curl http://localhost:8080/metrics
-```
-
-## Benchmarking
-
-### Using the Benchmark Script
+### List Models
```bash
-cd scripts
-
-# Install dependencies
-pip install requests
-
-# Run benchmarks
-python3 performance_bench.py
+curl http://localhost:8080/v1/models
```
-### Sample Benchmark Results (Jan-v3-4B-base-instruct-8bit)
-
-Sequential performance:
-| Configuration | Avg Latency | Throughput |
-|--------------|-------------|------------|
-| temp=0.7, 50 tokens | 1569ms | **32 tokens/sec** |
-| temp=0.7, 100 tokens | 3235ms | 31 tokens/sec |
-| temp=0.1, 50 tokens | 1618ms | 31 tokens/sec |
-
-Parallel performance (batch processing with max-batch-size=8):
-| Concurrency | Wall Time | Throughput |
-|-------------|-----------|------------|
-| 2 | ~79s | 13 tokens/sec |
-| 4 | ~159s | 6 tokens/sec |
-| 8 | ~302s | 3 tokens/sec |
-
-**Note:** For MLX on Apple Silicon, sequential processing is often optimal due to efficient utilization of unified memory. Parallel batching adds overhead but can improve throughput under high load.
-
-### Simple Test Request
+### Health Check
```bash
-# Test single request
-curl -X POST http://localhost:8080/v1/chat/completions \
- -H "Content-Type: application/json" \
- -d '{
- "model": "model",
- "messages": [{"role": "user", "content": "Hello"}],
- "max_tokens": 20,
- "temperature": 0.7
- }'
+curl http://localhost:8080/health
```
## Project Structure
@@ -190,13 +105,8 @@ mlx-server/
│ ├── MLXServerCommand.swift # CLI entry point
│ ├── ModelRunner.swift # Core inference engine
│ ├── Server.swift # HTTP server & API handlers
-│ ├── PromptCache.swift # KV cache management
-│ ├── BatchScheduler.swift # Request batching
-│ └── OpenAITypes.swift # API type definitions
-├── scripts/
-│ ├── performance_bench.py # Comprehensive benchmark with parallel tests
-│ ├── simple_bench.py # Simple request/response test
-│ └── quick_bench.sh # Quick shell benchmark
+│ ├── OpenAITypes.swift # API type definitions
+│ └── Logger.swift # Logging utilities
├── Package.swift # Swift package manifest
└── README.md # This file
```
@@ -205,33 +115,18 @@ mlx-server/
### Core Components
-1. **ModelRunner** - Manages model loading, warm-up, and inference
+1. **ModelRunner** - Manages model loading and inference (streaming and non-streaming)
2. **MLXHTTPServer** - HTTP server with OpenAI-compatible endpoints
-3. **PromptCache** - KV cache optimization for repeated prefixes
-4. **BatchScheduler** - Request queuing and batch processing
+3. **ActiveGenerations** - Tracks and manages cancellable generation tasks
-### Performance Optimizations
+### Notes
-- **Parallel Batch Execution** - Concurrent request processing using Swift structured concurrency
-- **String Building** - Array-based accumulation to reduce allocations
-- **Improved Hash Function** - FNV-1a hash for better cache hit rates
-- **Continuous Batching** - Better GPU utilization under varying load
-- **Priority Queue** - Request prioritization and adaptive sleep
+- The server binds to `127.0.0.1` (localhost only) for security
+- Client disconnects automatically cancel the active generation
+- VLM (vision-language models) are supported via image/video URL inputs
## Troubleshooting
-### Metal Library Not Found
-
-```
-MLX error: Failed to load the default metallib
-```
-
-Solution: Copy the metallib from Xcode build products:
-```bash
-METALLIB=$(find ~/Library/Developer/Xcode/DerivedData -name "default.metallib" | head -1)
-cp "$METALLIB" .build/arm64-apple-macosx/release/
-```
-
### Model Loading Fails
Ensure the model directory contains:
@@ -247,6 +142,14 @@ Change the port:
--port 8081
```
+## Benchmarking
+
+Use the [mlx-lm server benchmark script](https://github.com/ml-explore/mlx-lm/blob/main/benchmarks/server_benchmark.py) to measure throughput and latency:
+
+```bash
+python server_benchmark.py --url http://localhost:8080/v1/chat/completions --model model
+```
+
## License
This project is part of Jan - an open-source desktop AI application.
diff --git a/mlx-server/Sources/MLXServer/BatchScheduler.swift b/mlx-server/Sources/MLXServer/BatchScheduler.swift
deleted file mode 100644
index b7b733257..000000000
--- a/mlx-server/Sources/MLXServer/BatchScheduler.swift
+++ /dev/null
@@ -1,312 +0,0 @@
-import Foundation
-import MLX
-import MLXLLM
-import MLXLMCommon
-import Hummingbird
-
-// MARK: - Batching Configuration
-
-/// Configuration for batch processing
-public struct BatchingConfig: Sendable {
- public var maxBatchSize: Int
- public var maxModelTokens: Int
- public var enableContinuousBatching: Bool
-
-
- public static let `default` = BatchingConfig(
- maxBatchSize: 8,
- maxModelTokens: 4096,
- enableContinuousBatching: true,
- )
-}
-
-// MARK: - Batch Request
-
-/// A request waiting in the queue for batch processing
-struct BatchRequest: Identifiable, Sendable {
- let id: String
- let chatRequest: ChatCompletionRequest
- let createdAt: Date
- var priority: Int
-
- init(
- id: String = UUID().uuidString,
- chatRequest: ChatCompletionRequest,
- createdAt: Date = Date(),
- priority: Int = 0
- ) {
- self.id = id
- self.chatRequest = chatRequest
- self.createdAt = createdAt
- self.priority = priority
- }
-}
-
-// MARK: - Active Request
-
-/// Tracks a request currently being processed
-struct ActiveRequest: Identifiable, Sendable {
- let id: String
- let request: BatchRequest
- var startTime: Date
- var tokensGenerated: Int = 0
-
- var latencyMs: TimeInterval {
- Date().timeIntervalSince(startTime) * 1000
- }
-}
-
-// MARK: - Batch Context
-
-/// Holds the prepared input and cache for a batch item
-struct BatchContext: Sendable {
- let requestId: String
- var lmInput: LMInput
- var cache: [KVCache]
- var parameters: GenerateParameters
- var originalRequest: ChatCompletionRequest
-}
-
-// MARK: - Batching Metrics
-
-/// Tracks batch processing statistics
-struct BatchingMetrics: Sendable {
- var totalRequestsProcessed: Int = 0
- var totalBatchesProcessed: Int = 0
- var totalTokensGenerated: Int = 0
- var totalLatencyMs: Double = 0
- var cacheHits: Int = 0
- var cacheMisses: Int = 0
-
- var avgLatencyMs: Double {
- guard totalRequestsProcessed > 0 else { return 0 }
- return totalLatencyMs / Double(totalRequestsProcessed)
- }
-
- var avgBatchSize: Double {
- guard totalBatchesProcessed > 0 else { return 0 }
- return Double(totalRequestsProcessed) / Double(totalBatchesProcessed)
- }
-
- var cacheHitRate: Double {
- let total = cacheHits + cacheMisses
- guard total > 0 else { return 0 }
- return Double(cacheHits) / Double(total)
- }
-
- mutating func recordRequest(latencyMs: Double, tokens: Int, cacheHit: Bool) {
- totalRequestsProcessed += 1
- totalLatencyMs += latencyMs
- totalTokensGenerated += tokens
- if cacheHit {
- cacheHits += 1
- } else {
- cacheMisses += 1
- }
- }
-
- mutating func recordBatch(size: Int) {
- totalBatchesProcessed += 1
- }
-}
-
-// MARK: - Request Scheduler
-
-/// Manages the queue of requests waiting for batch processing
-actor RequestScheduler {
- private var waitingQueue: [BatchRequest] = []
- private var runningRequests: [String: ActiveRequest] = [:]
- private let config: BatchingConfig
- private var metrics = BatchingMetrics()
- private var isProcessing = false
- private var batchProcessor: BatchProcessor?
-
- init(config: BatchingConfig) {
- self.config = config
- log("RequestScheduler initialized with config: \(config)")
- }
-
- func setBatchProcessor(_ processor: BatchProcessor) {
- self.batchProcessor = processor
- }
-
- var status: (waitingCount: Int, runningCount: Int, maxBatchSize: Int, metrics: BatchingMetrics) {
- (waitingQueue.count, runningRequests.count, config.maxBatchSize, metrics)
- }
-
- /// Enqueue a request for batch processing
- func enqueue(_ request: BatchRequest) {
- waitingQueue.append(request)
- }
-
- /// Get the next batch of requests to process
- func getNextBatch() -> [BatchRequest] {
- // For continuous batching, add slots from finished requests
- let availableSlots = config.maxBatchSize - runningRequests.count
-
- // For static batching, wait until we have enough requests
- if !config.enableContinuousBatching && waitingQueue.count < config.maxBatchSize {
- return []
- }
-
- guard waitingQueue.count > 0 else { return [] }
-
- // Sort by priority (higher first) then by creation time (older first)
- waitingQueue.sort { lhs, rhs in
- if lhs.priority != rhs.priority {
- return lhs.priority > rhs.priority
- }
- return lhs.createdAt < rhs.createdAt
- }
-
- // Fill batch
- let batchSize = min(waitingQueue.count, max(availableSlots, config.maxBatchSize))
- let batch = Array(waitingQueue.prefix(batchSize))
-
- // Remove from waiting queue
- waitingQueue.removeFirst(batchSize)
-
- return batch
- }
-
- /// Mark requests as started
- func markRequestsStarted(_ requests: [BatchRequest]) {
- for request in requests {
- runningRequests[request.id] = ActiveRequest(
- id: request.id,
- request: request,
- startTime: Date()
- )
- }
- }
-
- /// Mark a request as completed
- func markRequestCompleted(id: String, latencyMs: Double, tokensGenerated: Int, cacheHit: Bool) {
- runningRequests.removeValue(forKey: id)
- metrics.recordRequest(latencyMs: latencyMs, tokens: tokensGenerated, cacheHit: cacheHit)
- }
-
- /// Mark a batch as processed
- func markBatchProcessed(size: Int) {
- metrics.recordBatch(size: size)
- }
-
- /// Process batches continuously
- /// Uses adaptive waiting for better throughput under varying load
- func processBatches() async throws {
- guard !isProcessing else { return }
- isProcessing = true
- defer { isProcessing = false }
-
- // Adaptive sleep duration based on queue state
- var baseSleepNs: UInt64 = 10_000_000 // 10ms baseline
-
- while !Task.isCancelled {
- let batch = getNextBatch()
- if !batch.isEmpty {
- do {
- _ = try await executeBatch(batch)
- // After successful batch, use shorter sleep (high utilization)
- baseSleepNs = 5_000_000 // 5ms
- } catch {
- log("[mlx] Batch execution error: \(error.localizedDescription)")
- // On error, back off slightly
- baseSleepNs = 20_000_000 // 20ms
- }
- } else {
- // No batch - use longer sleep when queue is empty
- let queueEmpty = waitingQueue.isEmpty
- baseSleepNs = queueEmpty ? 10_000_000 : 2_000_000 // 10ms empty, 2ms waiting
-
- try? await Task.sleep(nanoseconds: baseSleepNs)
- }
- }
- }
-
- private func executeBatch(_ batch: [BatchRequest]) async throws -> [BatchResult] {
- guard let processor = batchProcessor else {
- log("[mlx] No batch processor available")
- return []
- }
-
- return try await processor.executeBatch(batch, batchingConfig: config)
- }
-}
-
-// MARK: - Queue Status
-
-struct QueueStatus: Sendable {
- let waitingCount: Int
- let runningCount: Int
- let maxBatchSize: Int
- let metrics: BatchingMetrics
-}
-
-// MARK: - Batch Result
-
-/// Result of a batched inference request
-struct BatchResult: Sendable {
- let requestId: String
- let text: String
- let toolCalls: [ToolCallInfo]
- let usage: UsageInfo
- let latencyMs: Double
-}
-
-// MARK: - Batch Processor
-
-/// Handles actual batch processing of requests
-actor BatchProcessor {
- private let modelRunner: ModelRunner
- private let config: BatchingConfig
-
- init(modelRunner: ModelRunner, config: BatchingConfig) {
- self.modelRunner = modelRunner
- self.config = config
- }
-
- func executeBatch(_ requests: [BatchRequest], batchingConfig: BatchingConfig) async throws -> [BatchResult] {
- log("[mlx] Processing batch of \(requests.count) requests")
-
- // Use the model's batch execution
- let chatRequests = requests.map { $0.chatRequest }
-
- do {
- let results = try await modelRunner.executeBatch(requests: chatRequests, config: batchingConfig)
- log("[mlx] Batch completed: \(results.count) results")
- return results
- } catch {
- log("[mlx] Batch execution failed: \(error.localizedDescription)")
- throw error
- }
- }
-
- func getStatus() async -> QueueStatus {
- // Return default status - actual status comes from RequestScheduler
- QueueStatus(
- waitingCount: 0,
- runningCount: 0,
- maxBatchSize: config.maxBatchSize,
- metrics: BatchingMetrics()
- )
- }
-}
-
-// MARK: - Batching Errors
-
-enum BatchingError: Error, LocalizedError {
- case queueEmpty
- case invalidRequest(String)
- case processingFailed(String)
-
- var errorDescription: String? {
- switch self {
- case .queueEmpty:
- return "Request queue is empty"
- case .invalidRequest(let reason):
- return "Invalid request: \(reason)"
- case .processingFailed(let reason):
- return "Processing failed: \(reason)"
- }
- }
-}
diff --git a/mlx-server/Sources/MLXServer/MLXServerCommand.swift b/mlx-server/Sources/MLXServer/MLXServerCommand.swift
index a56fd709e..f4f6871ff 100644
--- a/mlx-server/Sources/MLXServer/MLXServerCommand.swift
+++ b/mlx-server/Sources/MLXServer/MLXServerCommand.swift
@@ -22,20 +22,6 @@ struct MLXServerCommand: AsyncParsableCommand {
@Option(name: .long, help: "API key for authentication (optional)")
var apiKey: String = ""
- @Option(name: .long, help: "Chat template to use (optional)")
- var chatTemplate: String = ""
-
- @Flag(name: .long, help: "Run in embedding mode")
- var embedding: Bool = false
-
- // MARK: - Batching Options
-
- @Option(name: .long, help: "Maximum batch size for concurrent requests (0 to disable)")
- var maxBatchSize: Int = 0
-
- @Flag(name: .long, help: "Enable continuous batching")
- var enableContinuousBatching: Bool = false
-
func run() async throws {
// Set GPU memory limit to prevent OOM issues
Memory.cacheLimit = 20 * 1024 * 1024 // 20GB limit
@@ -47,15 +33,6 @@ struct MLXServerCommand: AsyncParsableCommand {
log("[mlx] Context size: \(ctxSize)")
log("[mlx] Memory cache limit: \(Memory.cacheLimit / (1024 * 1024))MB")
- // Print batching configuration if enabled
- if maxBatchSize > 0 {
- log("[mlx] Batching enabled:")
- log(" - Max batch size: \(maxBatchSize)")
- log(" - Continuous batching: \(enableContinuousBatching)")
- } else {
- log("[mlx] Batching disabled (sequential processing)")
- }
-
// Extract model ID from path
let modelURL = URL(fileURLWithPath: model)
let modelId = modelURL.deletingPathExtension().lastPathComponent
@@ -64,39 +41,17 @@ struct MLXServerCommand: AsyncParsableCommand {
let modelRunner = ModelRunner()
do {
- try await modelRunner.load(modelPath: model, modelId: modelId)
+ try await modelRunner.load(modelPath: model)
} catch {
log("[mlx] Failed to load model: \(error)")
throw error
}
- // Warm up the model to initialize GPU kernels and optimize performance
- log("[mlx] Warming up model...")
- do {
- try await modelRunner.warmUp()
- log("[mlx] Model warm-up complete")
- } catch {
- log("[mlx] Warning: Model warm-up failed (\(error.localizedDescription)), continuing anyway...")
- }
-
- // Create batching configuration
- let batchingConfig: BatchingConfig?
- if maxBatchSize > 0 {
- batchingConfig = BatchingConfig(
- maxBatchSize: maxBatchSize,
- maxModelTokens: ctxSize,
- enableContinuousBatching: enableContinuousBatching,
- )
- } else {
- batchingConfig = nil
- }
-
// Set up the HTTP server
let server = MLXHTTPServer(
modelRunner: modelRunner,
modelId: modelId,
- apiKey: apiKey,
- batchingConfig: batchingConfig
+ apiKey: apiKey
)
let router = server.buildRouter()
diff --git a/mlx-server/Sources/MLXServer/ModelRunner.swift b/mlx-server/Sources/MLXServer/ModelRunner.swift
index 7e718b86e..65f1d95a6 100644
--- a/mlx-server/Sources/MLXServer/ModelRunner.swift
+++ b/mlx-server/Sources/MLXServer/ModelRunner.swift
@@ -6,448 +6,216 @@ import MLXVLM
/// Manages loading and running inference with MLX models
actor ModelRunner {
- private var container: ModelContainer?
- private var modelId: String = ""
- /// Stores a prompt cache for each loaded model
- private let promptCache = NSCache<NSString, PromptCache>()
- private var isVLM: Bool = false // Track if model is VLM (has different cache structure)
-
- var isLoaded: Bool {
- container != nil
- }
-
- var currentModelId: String {
- modelId
- }
-
- /// Warm up the model by running a short generation to initialize GPU kernels
- func warmUp() async throws {
- guard let container = container else {
- throw MLXServerError.modelNotLoaded
- }
- log("[mlx] Running warm-up generation...")
-
- let warmUpMessages = [ChatMessage(role: "user", content: .string("Hello"))]
- let warmUpParameters = GenerateParameters(
- maxTokens: 1,
- temperature: 0.1,
- topP: 0.9,
- repetitionPenalty: 1.0
- )
-
- let warmUpInput = UserInput(
- chat: buildChat(from: warmUpMessages),
- processing: .init(resize: .init(width: 1024, height: 1024)),
- tools: nil
- )
-
- try await container.perform { context in
- let input = try await context.processor.prepare(input: warmUpInput)
-
- for try await _ in try MLXLMCommon.generate(
- input: input, parameters: warmUpParameters, context: context
- ) {
- // Consume the stream - we only need one token to warm up
- break
- }
- }
-
- log("[mlx] Warm-up complete")
- }
-
- /// Detect if model is a VLM from config.json
- enum ModelType {
- case llm
- case vlm
- case unknown
- }
-
- private func detectModelType(modelDir: URL) -> ModelType {
- let configURL = modelDir.appendingPathComponent("config.json")
-
- guard let configData = try? Data(contentsOf: configURL),
- let json = try? JSONSerialization.jsonObject(with: configData, options: []) as? [String: Any],
- let architectures = json["architectures"] as? [Any],
- let firstArch = architectures.first else {
- return .unknown
- }
-
- // Handle both String and [String: Any] architectures
- let firstArchString: String
- if let archString = firstArch as? String {
- firstArchString = archString
- } else if let archDict = firstArch as? [String: Any],
- let archString = archDict["architectures"] as? String {
- firstArchString = archString
- } else {
- return .unknown
- }
-
- // Check if architecture indicates VLM (ends with VL or VLM)
- let upperArch = firstArchString.uppercased()
- if upperArch.contains("VL") || upperArch.contains("VLM") || upperArch.contains("VISION") {
- log("[mlx] Detected VLM model: \(firstArchString)")
- return .vlm
- }
-
- log("[mlx] Detected LLM model: \(firstArchString)")
- return .llm
- }
+ private var model: ModelContext?
/// Load a model from the given path
/// Supports both local directories and HuggingFace model IDs
- func load(modelPath: String, modelId: String) async throws {
+ func load(modelPath: String) async throws {
log("[mlx] Loading model from: \(modelPath)")
- let modelConfiguration: ModelConfiguration
- var modelDir: URL?
-
- // Check if the path is a local directory or a HuggingFace model ID
let modelURL = URL(fileURLWithPath: modelPath)
let fileManager = FileManager.default
- // Check if path is a directory
var isDirectory: ObjCBool = false
let pathExists = fileManager.fileExists(atPath: modelPath, isDirectory: &isDirectory)
+ var modelDir: URL?
+
if pathExists && isDirectory.boolValue {
- // Local model directory
- modelDir = modelURL
- let configURL = modelDir!.appendingPathComponent("config.json")
+ let configURL = modelURL.appendingPathComponent("config.json")
if fileManager.fileExists(atPath: configURL.path) {
- modelConfiguration = ModelConfiguration(directory: modelDir!, defaultPrompt: "")
- log("[mlx] Using local model directory: \(modelDir!.path)")
+ modelDir = modelURL
+ log("[mlx] Using local model directory: \(modelURL.path)")
} else {
// Try parent directory
- let parentDir = modelDir!.deletingLastPathComponent()
+ let parentDir = modelURL.deletingLastPathComponent()
let parentConfigURL = parentDir.appendingPathComponent("config.json")
if fileManager.fileExists(atPath: parentConfigURL.path) {
modelDir = parentDir
- modelConfiguration = ModelConfiguration(directory: parentDir, defaultPrompt: "")
log("[mlx] Using parent directory: \(parentDir.path)")
- } else {
- modelConfiguration = ModelConfiguration(id: modelPath)
- log("[mlx] Falling back to HuggingFace model ID: \(modelPath)")
}
}
} else if pathExists {
// Single file - use parent directory
modelDir = modelURL.deletingLastPathComponent()
- modelConfiguration = ModelConfiguration(directory: modelDir!, defaultPrompt: "")
log("[mlx] Using parent directory: \(modelDir!.path)")
- } else if modelPath.contains("/") && !modelPath.hasPrefix("/") {
- // HuggingFace model ID
- modelConfiguration = ModelConfiguration(id: modelPath)
- log("[mlx] Using HuggingFace model ID: \(modelPath)")
- } else {
- modelConfiguration = ModelConfiguration(id: modelPath)
- log("[mlx] Treating as HuggingFace model ID: \(modelPath)")
}
- // Detect model type and select appropriate factory
- let modelType: ModelType
if let dir = modelDir {
- modelType = detectModelType(modelDir: dir)
- } else {
- // For HuggingFace IDs, try VLM first for vision models, then LLM
- modelType = .unknown
+ self.model = try await loadModel(directory: dir)
}
-
- // Load using the appropriate factory
- switch modelType {
- case .vlm:
- // Load as VLM directly
- log("[mlx] Loading as VLM model...")
- self.container = try await VLMModelFactory.shared.loadContainer(
- configuration: modelConfiguration
- ) { progress in
- log("[mlx] Loading progress: \(Int(progress.fractionCompleted * 100))%")
- }
- self.isVLM = true
- log("[mlx] Model loaded as VLM: \(modelId)")
-
- case .llm:
- // Load as LLM directly
- log("[mlx] Loading as LLM model...")
- self.container = try await LLMModelFactory.shared.loadContainer(
- configuration: modelConfiguration
- ) { progress in
- log("[mlx] Loading progress: \(Int(progress.fractionCompleted * 100))%")
- }
- log("[mlx] Model loaded as LLM: \(modelId)")
-
- case .unknown:
- // Try LLM first, fall back to VLM
- do {
- self.container = try await LLMModelFactory.shared.loadContainer(
- configuration: modelConfiguration
- ) { progress in
- log("[mlx] Loading progress: \(Int(progress.fractionCompleted * 100))%")
- }
- log("[mlx] Model loaded as LLM: \(modelId)")
- } catch {
- log("[mlx] LLM loading failed (\(error.localizedDescription)), trying VLM factory...")
- do {
- self.container = try await VLMModelFactory.shared.loadContainer(
- configuration: modelConfiguration
- ) { progress in
- log("[mlx] Loading progress: \(Int(progress.fractionCompleted * 100))%")
- }
- self.isVLM = true
- log("[mlx] Model loaded as VLM: \(modelId)")
- } catch {
- log("[mlx] Error: Failed to load model with both LLM and VLM factories: \(error.localizedDescription)")
- throw error
- }
- }
- }
-
- self.modelId = modelId
- log("[mlx] Model ready: \(modelId)")
-
- // Clear out the promptCache for new model load
- // promptCache.removeObject(forKey: modelId as NSString)
}
- /// Build Chat.Message array from ChatMessages, including images and videos
- private func buildChat(from messages: [ChatMessage]) -> [Chat.Message] {
- messages.map { message in
- let role: Chat.Message.Role =
- switch message.role {
- case "assistant":
- .assistant
- case "user":
- .user
- case "system":
- .system
- case "tool":
- .tool
- default:
- .user
- }
+ /// Parse ChatMessages into system instructions, conversation history, and the current user message
+ private func buildChat(from messages: [ChatMessage]) -> (instructions: String?, history: [Chat.Message], current: Chat.Message?) {
+ let chatMessages = messages.map { toChatMessage($0) }
+ let instructions = chatMessages.first(where: { $0.role == .system })?.content
+ let nonSystem = chatMessages.filter { $0.role != .system }
+ let history = nonSystem.dropLast()
+ let current = nonSystem.last
+ return (instructions, Array(history), current)
+ }
- // Get image URLs from both explicit images field and content array format
- var imageUrls = message.content.imageUrls
- if let legacyImages = message.images {
- imageUrls.append(contentsOf: legacyImages)
- }
+ /// Convert a single ChatMessage to Chat.Message
+ private func toChatMessage(_ message: ChatMessage) -> Chat.Message {
+ let role: Chat.Message.Role =
+ switch message.role {
+ case "assistant":
+ .assistant
+ case "user":
+ .user
+ case "system":
+ .system
+ case "tool":
+ .tool
+ default:
+ .user
+ }
- let images: [UserInput.Image] = imageUrls.compactMap { urlString in
- // Handle file:// URLs
- let cleanUrl = urlString.replacingOccurrences(of: "file://", with: "")
- guard let url = URL(string: urlString) ?? URL(string: cleanUrl) else {
- log("[mlx] Warning: Invalid image URL: \(urlString)")
- return nil
- }
- return .url(url)
- }
+ // Get image URLs from both explicit images field and content array format
+ var imageUrls = message.content.imageUrls
+ if let legacyImages = message.images {
+ imageUrls.append(contentsOf: legacyImages)
+ }
- let videos: [UserInput.Video] = (message.videos ?? []).compactMap { urlString in
- guard let url = URL(string: urlString) else {
- log("[mlx] Warning: Invalid video URL: \(urlString)")
- return nil
- }
- return .url(url)
+ let images: [UserInput.Image] = imageUrls.compactMap { urlString in
+ // Handle file:// URLs
+ let cleanUrl = urlString.replacingOccurrences(of: "file://", with: "")
+ guard let url = URL(string: urlString) ?? URL(string: cleanUrl) else {
+ log("[mlx] Warning: Invalid image URL: \(urlString)")
+ return nil
}
+ return .url(url)
+ }
- if !images.isEmpty {
- log("[mlx] Message has \(images.count) image(s)")
- }
- if !videos.isEmpty {
- log("[mlx] Message has \(videos.count) video(s)")
+ let videos: [UserInput.Video] = (message.videos ?? []).compactMap { urlString in
+ guard let url = URL(string: urlString) else {
+ log("[mlx] Warning: Invalid video URL: \(urlString)")
+ return nil
}
-
- return Chat.Message(
- role: role, content: message.content.textContent, images: images, videos: videos)
+ return .url(url)
}
- }
- /// Convert AnyCodable tools array to ToolSpec format
- private func buildToolSpecs(from tools: [AnyCodable]?) -> [[String: any Sendable]]? {
- guard let tools = tools, !tools.isEmpty else { return nil }
- let specs = tools.map { tool in
- tool.toSendable() as! [String: any Sendable]
+ if !images.isEmpty {
+ log("[mlx] Message has \(images.count) image(s)")
}
- log("[mlx] Tools provided: \(specs.count)")
- return specs
+ if !videos.isEmpty {
+ log("[mlx] Message has \(videos.count) video(s)")
+ }
+
+ return Chat.Message(
+ role: role, content: message.content.textContent, images: images, videos: videos)
}
/// Build GenerateParameters from individual parameters
private nonisolated func buildGenerateParameters(
temperature: Float,
topP: Float,
- maxTokens: Int,
+ maxTokens: Int? = nil,
repetitionPenalty: Float
) -> GenerateParameters {
GenerateParameters(
maxTokens: maxTokens,
+ kvBits: 4, // 4 or 8 bits
+ kvGroupSize: 64, // Quantization group size
+ quantizedKVStart: 0, // Start quantizing after N tokens
temperature: temperature,
topP: topP,
- repetitionPenalty: repetitionPenalty
+ repetitionPenalty: repetitionPenalty,
)
}
- func getPromptCache(
- fullPrompt: LMInput, parameters: GenerateParameters, context: ModelContext,
- modelName: String
- ) -> (PromptCache?, LMInput) {
-
- if self.isVLM {
- return (nil, fullPrompt)
- }
-
- var cache: PromptCache
- if let existingCache = promptCache.object(forKey: modelName as NSString) {
- cache = existingCache
- } else {
- // Create cache if it doesn't exist yet
- cache = PromptCache(cache: context.model.newCache(parameters: parameters))
- self.promptCache.setObject(cache, forKey: modelName as NSString)
- }
-
- let lmInput: LMInput
-
- /// Remove prefix from prompt that is already in cache
- if let suffix = cache.getUncachedSuffix(prompt: fullPrompt.text.tokens) {
- // If suffix is empty, the entire prompt is cached, but we're regenerating
- // Create a new cache to force fresh generation
- if suffix.size == 0 {
- let newCache = PromptCache(cache: context.model.newCache(parameters: parameters))
- self.promptCache.setObject(newCache, forKey: modelName as NSString)
- cache = newCache
- lmInput = fullPrompt
- } else {
- lmInput = LMInput(text: LMInput.Text(tokens: suffix))
- }
- } else {
- // If suffix is nil, the cache is inconsistent with the new prompt
- // and the cache doesn't support trimming so create a new one here.
- let newCache = PromptCache(cache: context.model.newCache(parameters: parameters))
- self.promptCache.setObject(newCache, forKey: modelName as NSString)
- cache = newCache
- lmInput = fullPrompt
- }
-
- return (cache, lmInput)
- }
-
/// Generate a chat completion (non-streaming)
func generate(
messages: [ChatMessage],
temperature: Float = 0.7,
topP: Float = 1.0,
- maxTokens: Int = 2048,
+ maxTokens: Int? = nil,
repetitionPenalty: Float = 1.0,
stop: [String] = [],
tools: [AnyCodable]? = nil
) async throws -> (String, [ToolCallInfo], UsageInfo) {
- guard let container = container else {
+
+ guard let model = self.model else {
log("[mlx] Error: generate() called but no model is loaded")
throw MLXServerError.modelNotLoaded
}
- log("[mlx] Generate: \(messages.count) messages, temp=\(temperature), topP=\(topP), maxTokens=\(maxTokens)")
+ log("[mlx] Generate: \(messages.count) messages, temp=\(temperature), topP=\(topP), maxTokens=\(maxTokens ?? -1)")
+
+ let (instructions, history, currentMessage) = buildChat(from: messages)
- let chat = buildChat(from: messages)
- let toolSpecs = buildToolSpecs(from: tools)
let generateParameters = buildGenerateParameters(
temperature: temperature, topP: topP,
maxTokens: maxTokens, repetitionPenalty: repetitionPenalty
)
- let userInput = UserInput(
- chat: chat,
- processing: .init(resize: .init(width: 1024, height: 1024)),
- tools: toolSpecs,
- additionalContext: ["enable_thinking": true]
- )
-
- let result: (String, [ToolCallInfo], UsageInfo) = try await container.perform { context in
- let fullInput = try await context.processor.prepare(input: userInput)
- let fullTokens = fullInput.text.tokens
- let promptTokenCount = fullTokens.size
-
- // Get or create prompt cache (nil for VLM models)
- // TODO: Prompt cache access isn't isolated
- // Get the prompt cache and adjust new prompt to remove
- // prefix already in cache, trim cache if cache is
- // inconsistent with new prompt.
- // let (cache, lmInput) = await getPromptCache(
- // fullPrompt: fullInput, parameters: generateParameters, context: context,
- // modelName: modelId)
-
- var output = ""
- var completionTokenCount = 0
- var collectedToolCalls: [ToolCallInfo] = []
- var completionInfo: GenerateCompletionInfo?
-
- do {
- for await generation in try MLXLMCommon.generate(
- input: fullInput, cache: nil, parameters: generateParameters, context: context
- ) {
- // Check if the task was cancelled (client disconnected)
- try Task.checkCancellation()
-
- switch generation {
- case .chunk(let chunk):
- output += chunk
- completionTokenCount += 1
-
- case .info(let info):
- completionInfo = info
- // Note: info.promptTokenCount is the tokens processed in this call (may be less due to caching)
- // We report the full promptTokenCount in usage for accurate tracking
- log("[mlx] Generation info: \(info.promptTokenCount) processed prompt tokens, \(info.generationTokenCount) generated tokens")
- log("[mlx] Prompt: \(String(format: "%.1f", info.promptTokensPerSecond)) tokens/sec")
- log("[mlx] Generation: \(String(format: "%.1f", info.tokensPerSecond)) tokens/sec")
-
- case .toolCall(let toolCall):
- let argsData = try JSONSerialization.data(
- withJSONObject: toolCall.function.arguments.mapValues { $0.anyValue },
- options: [.sortedKeys]
+ let toolSpecs = self.buildToolSpecs(from: tools)
+ let session = ChatSession(model, instructions: instructions, history: history, generateParameters: generateParameters, tools: toolSpecs)
+
+ var output = ""
+ var completionTokenCount = 0
+ var collectedToolCalls: [ToolCallInfo] = []
+ var completionInfo: GenerateCompletionInfo?
+
+ do {
+ for try await item in session.streamDetails(to: currentMessage?.content ?? "", images: currentMessage?.images ?? [], videos: []) {
+ try Task.checkCancellation()
+
+ switch item {
+ case .chunk(let chunk):
+ output += chunk
+ completionTokenCount += 1
+
+ case .info(let info):
+ completionInfo = info
+ log("[mlx] Generation info: \(info.promptTokenCount) processed prompt tokens, \(info.generationTokenCount) generated tokens")
+ log("[mlx] Prompt: \(String(format: "%.1f", info.promptTokensPerSecond)) tokens/sec")
+ log("[mlx] Generation: \(String(format: "%.1f", info.tokensPerSecond)) tokens/sec")
+
+ case .toolCall(let toolCall):
+ let argsData = try JSONSerialization.data(
+ withJSONObject: toolCall.function.arguments.mapValues { $0.anyValue },
+ options: [.sortedKeys]
+ )
+ let argsString = String(data: argsData, encoding: .utf8) ?? "{}"
+ let info = ToolCallInfo(
+ id: generateToolCallId(),
+ type: "function",
+ function: FunctionCall(
+ name: toolCall.function.name,
+ arguments: argsString
)
- let argsString = String(data: argsData, encoding: .utf8) ?? "{}"
- let info = ToolCallInfo(
- id: generateToolCallId(),
- type: "function",
- function: FunctionCall(
- name: toolCall.function.name,
- arguments: argsString
- )
- )
- collectedToolCalls.append(info)
- log("[mlx] Tool call: \(toolCall.function.name)(\(argsString))")
- }
+ )
+ collectedToolCalls.append(info)
+ log("[mlx] Tool call: \(toolCall.function.name)(\(argsString))")
}
- } catch is CancellationError {
- log("[mlx] Generation cancelled by client")
- throw CancellationError()
- } catch {
- log("[mlx] Error during generation: \(error.localizedDescription)")
- throw error
- }
-
- let usage: UsageInfo
- if let info = completionInfo {
- // Use full prompt token count for accurate usage tracking (info.promptTokenCount may be smaller due to caching)
- usage = UsageInfo(
- prompt_tokens: promptTokenCount,
- completion_tokens: info.generationTokenCount,
- total_tokens: promptTokenCount + info.generationTokenCount
- )
- } else {
- usage = UsageInfo(
- prompt_tokens: promptTokenCount,
- completion_tokens: completionTokenCount,
- total_tokens: promptTokenCount + completionTokenCount
- )
}
+ } catch is CancellationError {
+ log("[mlx] Generation cancelled by client")
+ throw CancellationError()
+ } catch {
+ log("[mlx] Error during generation: \(error.localizedDescription)")
+ throw error
+ }
- log("[mlx] Generate complete: \(output.count) chars, \(collectedToolCalls.count) tool call(s)")
- return (output, collectedToolCalls, usage)
+ let usage: UsageInfo
+ if let info = completionInfo {
+ usage = UsageInfo(
+ prompt_tokens: info.promptTokenCount,
+ completion_tokens: info.generationTokenCount,
+ total_tokens: info.promptTokenCount + info.generationTokenCount
+ )
+ } else {
+ usage = UsageInfo(
+ prompt_tokens: completionTokenCount,
+ completion_tokens: completionTokenCount,
+ total_tokens: completionTokenCount + completionTokenCount
+ )
}
- return result
+ log("[mlx] Generate complete: \(output.count) chars, \(collectedToolCalls.count) tool call(s)")
+ return (output, collectedToolCalls, usage)
}
/// Generate a streaming chat completion
@@ -455,128 +223,93 @@ actor ModelRunner {
messages: [ChatMessage],
temperature: Float = 0.7,
topP: Float = 1.0,
- maxTokens: Int = 2048,
+ maxTokens: Int? = nil,
repetitionPenalty: Float = 1.0,
stop: [String] = [], // Skipped for now, later should pass thru model load where container preparation - context.configuration.extraEOSTokens
tools: [AnyCodable]? = nil
) -> AsyncThrowingStream<StreamEvent, Error> {
AsyncThrowingStream { continuation in
let task = Task {
- guard let container = self.container else {
- log("[mlx] Error: generateStream() called but no model is loaded")
- continuation.finish(throwing: MLXServerError.modelNotLoaded)
- return
+ guard let model = model else {
+ log("[mlx] Error: generate() called but no model is loaded")
+ throw MLXServerError.modelNotLoaded
}
- log("[mlx] Stream generate: \(messages.count) messages, temp=\(temperature), topP=\(topP), maxTokens=\(maxTokens)")
-
- let chat = self.buildChat(from: messages)
- let toolSpecs = self.buildToolSpecs(from: tools)
+ log("[mlx] Generate: \(messages.count) messages, temp=\(temperature), topP=\(topP), maxTokens=\(maxTokens ?? -1)")
+ let (instructions, history, currentMessage) = buildChat(from: messages)
- let userInput = UserInput(
- chat: chat,
- processing: .init(resize: .init(width: 1024, height: 1024)),
- tools: toolSpecs,
- additionalContext: ["enable_thinking": true]
+ let generateParameters = self.buildGenerateParameters(
+ temperature: temperature, topP: topP,
+ maxTokens: maxTokens, repetitionPenalty: repetitionPenalty
)
+ let toolSpecs = self.buildToolSpecs(from: tools)
+ let session = ChatSession(model, instructions: instructions, history: history, generateParameters: generateParameters, tools: toolSpecs)
+
+ var completionTokenCount = 0
+ var hasToolCalls = false
do {
- try await container.perform { context in
- let generateParameters = self.buildGenerateParameters(
- temperature: temperature, topP: topP,
- maxTokens: maxTokens, repetitionPenalty: repetitionPenalty
- )
+ for try await item in session.streamDetails(to: currentMessage?.content ?? "", images: currentMessage?.images ?? [], videos: []) {
- let fullInput = try await context.processor.prepare(input: userInput)
- let fullTokens = fullInput.text.tokens
-
- // Get or create prompt cache (nil for VLM models)
- // TODO: Prompt cache access isn't isolated
- // Get the prompt cache and adjust new prompt to remove
- // prefix already in cache, trim cache if cache is
- // inconsistent with new prompt.
- // let (cache, lmInput) = await getPromptCache(
- // fullPrompt: fullInput, parameters: generateParameters, context: context,
- // modelName: modelId)
-
- var completionTokenCount = 0
- var accumulated = ""
- var hasToolCalls = false
-
- do {
- for await generation in try MLXLMCommon.generate(
- input: fullInput, cache: nil, parameters: generateParameters, context: context
- ) {
- // Check if the task was cancelled (client disconnected)
- if Task.isCancelled {
- log("[mlx] Stream generation cancelled by client")
- break
- }
-
- switch generation {
- case .chunk(let chunk):
- accumulated += chunk
- completionTokenCount += 1
-
- continuation.yield(.chunk(chunk))
-
- case .info(let info):
- log("[mlx] Stream generation info: \(info.promptTokenCount) processed prompt tokens, \(info.generationTokenCount) generated tokens")
- log("[mlx] Prompt: \(String(format: "%.1f", info.promptTokensPerSecond)) tokens/sec")
- log("[mlx] Generation: \(String(format: "%.1f", info.tokensPerSecond)) tokens/sec")
-
- // Use full prompt token count for accurate usage tracking
- let promptTokenCount = fullTokens.size
- let usage = UsageInfo(
- prompt_tokens: promptTokenCount,
- completion_tokens: info.generationTokenCount,
- total_tokens: promptTokenCount + info.generationTokenCount
- )
- let timings = TimingsInfo(
- prompt_n: promptTokenCount,
- predicted_n: info.generationTokenCount,
- predicted_per_second: info.tokensPerSecond,
- prompt_per_second: info.promptTokensPerSecond
- )
- continuation.yield(.done(usage: usage, timings: timings, hasToolCalls: hasToolCalls))
-
- case .toolCall(let toolCall):
- hasToolCalls = true
- let argsData = try JSONSerialization.data(
- withJSONObject: toolCall.function.arguments.mapValues { $0.anyValue },
- options: [.sortedKeys]
- )
- let argsString = String(data: argsData, encoding: .utf8) ?? "{}"
- let info = ToolCallInfo(
- id: generateToolCallId(),
- type: "function",
- function: FunctionCall(
- name: toolCall.function.name,
- arguments: argsString
- )
- )
- log("[mlx] Stream tool call: \(toolCall.function.name)(\(argsString))")
- continuation.yield(.toolCall(info))
- }
- }
- } catch {
- if Task.isCancelled {
- log("[mlx] Stream generation cancelled by client")
- } else {
- log("[mlx] Error during stream generation: \(error.localizedDescription)")
- throw error
- }
+ if Task.isCancelled {
+ log("[mlx] Stream generation cancelled by client")
+ break
}
- log("[mlx] Stream complete: \(accumulated.count) chars")
- continuation.finish()
+ switch item {
+ case .chunk(let chunk):
+ completionTokenCount += 1
+
+ continuation.yield(.chunk(chunk))
+
+ case .info(let info):
+ log("[mlx] Stream generation info: \(info.promptTokenCount) processed prompt tokens, \(info.generationTokenCount) generated tokens")
+ log("[mlx] Prompt: \(String(format: "%.1f", info.promptTokensPerSecond)) tokens/sec")
+ log("[mlx] Generation: \(String(format: "%.1f", info.tokensPerSecond)) tokens/sec")
+
+ // Use full prompt token count for accurate usage tracking
+ // let promptTokenCount = fullTokens.size
+ let usage = UsageInfo(
+ prompt_tokens: nil,
+ // prompt_tokens: promptTokenCount,
+ completion_tokens: info.generationTokenCount,
+ total_tokens: nil
+ // total_tokens: promptTokenCount + info.generationTokenCount
+ )
+ let timings = TimingsInfo(
+ // prompt_n: promptTokenCount,
+ predicted_n: info.generationTokenCount,
+ predicted_per_second: info.tokensPerSecond,
+ prompt_per_second: info.promptTokensPerSecond
+ )
+ continuation.yield(.done(usage: usage, timings: timings, hasToolCalls: hasToolCalls))
+
+ case .toolCall(let toolCall):
+ hasToolCalls = true
+ let argsData = try JSONSerialization.data(
+ withJSONObject: toolCall.function.arguments.mapValues { $0.anyValue },
+ options: [.sortedKeys]
+ )
+ let argsString = String(data: argsData, encoding: .utf8) ?? "{}"
+ let info = ToolCallInfo(
+ id: generateToolCallId(),
+ type: "function",
+ function: FunctionCall(
+ name: toolCall.function.name,
+ arguments: argsString
+ )
+ )
+ log("[mlx] Stream tool call: \(toolCall.function.name)(\(argsString))")
+ continuation.yield(.toolCall(info))
+ }
}
+ continuation.finish()
} catch {
if Task.isCancelled {
- log("[mlx] Stream cancelled by client")
+ log("[mlx] Stream generation cancelled by client")
continuation.finish()
} else {
- log("[mlx] Error in stream: \(error.localizedDescription)")
+ log("[mlx] Error during stream generation: \(error.localizedDescription)")
continuation.finish(throwing: error)
}
}
@@ -588,8 +321,16 @@ actor ModelRunner {
}
}
}
+ /// Convert AnyCodable tools array to ToolSpec format
+ private func buildToolSpecs(from tools: [AnyCodable]?) -> [[String: any Sendable]]? {
+ guard let tools = tools, !tools.isEmpty else { return nil }
+ let specs = tools.map { tool in
+ tool.toSendable() as! [String: any Sendable]
+ }
+ log("[mlx] Tools provided: \(specs.count)")
+ return specs
+ }
}
-
/// Events emitted during streaming generation
enum StreamEvent {
/// A text chunk
@@ -600,58 +341,9 @@ enum StreamEvent {
case done(usage: UsageInfo, timings: TimingsInfo?, hasToolCalls: Bool)
}
-// MARK: - Batching Support
-
-extension ModelRunner {
- /// Execute a batch of requests concurrently
- /// This is a simplified batch execution - for full batching, implement continuous batching
- func executeBatch(
- requests: [ChatCompletionRequest],
- config: BatchingConfig
- ) async throws -> [BatchResult] {
- guard let container = container else {
- throw MLXServerError.modelNotLoaded
- }
-
- log("[mlx] Batch execute: \(requests.count) requests")
-
- var results: [BatchResult] = []
-
- // Process all requests
- for chatRequest in requests {
- let startTime = Date()
-
- let (text, toolCalls, usage) = try await generate(
- messages: chatRequest.messages,
- temperature: chatRequest.temperature ?? 0.7,
- topP: chatRequest.top_p ?? 1.0,
- maxTokens: chatRequest.max_tokens ?? chatRequest.n_predict ?? 2048,
- repetitionPenalty: chatRequest.repetition_penalty ?? 1.0,
- stop: chatRequest.stop ?? [],
- tools: chatRequest.tools
- )
-
- let latencyMs = Date().timeIntervalSince(startTime) * 1000
-
- let result = BatchResult(
- requestId: chatRequest.model, // Use model as request ID for now
- text: text,
- toolCalls: toolCalls,
- usage: usage,
- latencyMs: latencyMs
- )
- results.append(result)
- }
-
- return results
- }
-}
-
enum MLXServerError: Error, LocalizedError {
case modelNotLoaded
case invalidRequest(String)
- case batchingNotEnabled
- case speculativeDecodingNotSupported
var errorDescription: String? {
switch self {
@@ -659,10 +351,6 @@ enum MLXServerError: Error, LocalizedError {
return "No model is currently loaded"
case .invalidRequest(let msg):
return "Invalid request: \(msg)"
- case .batchingNotEnabled:
- return "Batching is not enabled"
- case .speculativeDecodingNotSupported:
- return "Speculative decoding is not supported for this model"
}
}
}
diff --git a/mlx-server/Sources/MLXServer/OpenAITypes.swift b/mlx-server/Sources/MLXServer/OpenAITypes.swift
index 11e1b90b5..21cafff54 100644
--- a/mlx-server/Sources/MLXServer/OpenAITypes.swift
+++ b/mlx-server/Sources/MLXServer/OpenAITypes.swift
@@ -239,9 +239,9 @@ struct ChatChoice: Codable {
}
struct UsageInfo: Codable {
- let prompt_tokens: Int
+ let prompt_tokens: Int?
let completion_tokens: Int
- let total_tokens: Int
+ let total_tokens: Int?
}
// MARK: - Chat Completion Chunk (streaming)
@@ -294,7 +294,6 @@ struct ModelInfo: Codable {
struct HealthResponse: Codable {
let status: String
- let batching: String?
}
// MARK: - Error Response
diff --git a/mlx-server/Sources/MLXServer/PromptCache.swift b/mlx-server/Sources/MLXServer/PromptCache.swift
deleted file mode 100644
index ad4d2c9c4..000000000
--- a/mlx-server/Sources/MLXServer/PromptCache.swift
+++ /dev/null
@@ -1,136 +0,0 @@
-//
-// PromptCache.swift
-// mlx-swift-examples
-//
-// Created by Jolon Faichney on 3/5/2025.
-//
-
-import MLX
-import MLXLMCommon
-
-/// Stores the KV Cache between calls to ``generate`` and maintains
-/// the token ids reflected in the cache.
-///
-/// ``PromptCache`` is ``@unchecked Sendable`` which allows it
-/// to be used within the ``ModelContainer`` context.
-///
-/// TODO: cache isolation
-public class PromptCache: @unchecked Sendable {
- private(set) var cache: [KVCache]
- private(set) var tokens: MLXArray
-
- public init(cache: [KVCache]) {
- log("[PromptCache.init]")
- self.cache = cache
- self.tokens = []
- }
-
- /// Returns the suffix of the prompt not already in cache, so that only
- /// the new part is processed. The tokens of the cache are adjusted here
- /// to reflect the new full prompt (i.e. the suffix tokens are added to the
- /// cache tokens array), assuming that the prompt suffix will
- /// be processed after the call to this function.
- ///
- /// Trims cache if necessary if part of the cache doesn't match the new
- /// prompt. If the model doesn't support trimming and the cache needs to be
- /// trimmed, will return nil for the caller to create a new cache.
- ///
- /// - Returns:
- /// - If entirety of cache is in the new prompt:
- /// - Return suffix of new prompt, less what is in the cache
- /// - If only a portion of the cache is in the new prompt:
- /// - Attempt to trim the cache to the common prefix
- /// - Return suffix of prompt not in cache
- /// - If the cache is not trimmable return nil for the caller
- /// to create a new cache.
- public func getUncachedSuffix(prompt: MLXArray) -> MLXArray? {
-
- let comPrefixLength = commonPrefixLength(newPromptTokens: prompt)
-
- if comPrefixLength == self.tokens.size {
- let suffix = prompt[comPrefixLength ..< prompt.size]
-
- // If suffix is empty (prompt == cached tokens), nothing to add
- if suffix.size == 0 {
- return suffix
- }
-
- // Avoid concatenating with empty array - MLX can't infer shape for reshape
- if self.tokens.size == 0 {
- self.tokens = suffix
- } else {
- self.tokens = concatenated([self.tokens, suffix], axis: 0)
- }
- return suffix
- } else if comPrefixLength < self.tokens.size {
- if isTrimmable() {
- let trimmedLen = self.trim(self.tokens.size - comPrefixLength)
- if trimmedLen != self.tokens.size - comPrefixLength {
- log("Warning: request trimmed amount and actual trimmed amount are different")
- }
- self.tokens = self.tokens[0 ..< comPrefixLength]
- let suffix = prompt[comPrefixLength ..< prompt.size]
-
- // If suffix is empty, we've just trimmed to match
- if suffix.size == 0 {
- return suffix
- }
-
- // Avoid concatenating with empty array - MLX can't infer shape for reshape
- if self.tokens.size == 0 {
- self.tokens = suffix
- } else {
- self.tokens = concatenated([self.tokens, suffix], axis: 0)
- }
- return suffix
- } else {
- // Caller must create a new cache
- return nil
- }
- }
-
- return nil
- }
-
- /// - Returns: true if all KV caches are trimmable
- public func isTrimmable() -> Bool {
- return cache.allSatisfy { $0.isTrimmable }
- }
-
- /// Trims all KV caches.
- /// - Parameters:
- /// - n: Amount to trim.
- /// - Returns: Amount KV Caches were trimmed (may be less than ``n``).
- public func trim(_ n: Int) -> Int {
- if !self.isTrimmable() {
- return 0
- }
- return cache.map { $0.trim(n) }.max() ?? 0
- }
-
- /// Finds the common prefix between the cached prompt and
- /// the new prompt.
- /// - Parameters:
- /// - newPromptTokens: Tokens to compare with cached tokens.
- /// - Returns: Length of the common prefix
- public func commonPrefixLength(newPromptTokens: MLXArray) -> Int {
- return commonPrefixLength(self.tokens, newPromptTokens)
- }
-
- /// Finds the common prefix between ``MLXArray``s.
- /// - Parameters:
- /// - array1: First array
- /// - array2: Second array
- /// - Returns: Length of the common prefix
- public func commonPrefixLength(_ array1: MLXArray, _ array2: MLXArray) -> Int {
- // TODO: Add test cases
- let minLength = min(array1.size, array2.size)
- for i in 0 ..< minLength {
- if all(array1[i] .!= array2[i]).item(Bool.self) {
- return i
- }
- }
- return minLength
- }
-
-}
diff --git a/mlx-server/Sources/MLXServer/Server.swift b/mlx-server/Sources/MLXServer/Server.swift
index 35d16c1af..9f8c4001f 100644
--- a/mlx-server/Sources/MLXServer/Server.swift
+++ b/mlx-server/Sources/MLXServer/Server.swift
@@ -32,20 +32,12 @@ struct MLXHTTPServer {
let modelRunner: ModelRunner
let modelId: String
let apiKey: String
- let batchingConfig: BatchingConfig?
let activeGenerations = ActiveGenerations()
- private var batchProcessor: BatchProcessor?
- init(modelRunner: ModelRunner, modelId: String, apiKey: String, batchingConfig: BatchingConfig? = nil) {
+ init(modelRunner: ModelRunner, modelId: String, apiKey: String) {
self.modelRunner = modelRunner
self.modelId = modelId
self.apiKey = apiKey
- self.batchingConfig = batchingConfig
-
- // Initialize batch processor if batching is enabled
- if let config = batchingConfig, config.maxBatchSize > 0 {
- self.batchProcessor = BatchProcessor(modelRunner: modelRunner, config: config)
- }
}
func buildRouter() -> Router<BasicRequestContext> {
@@ -53,59 +45,10 @@ struct MLXHTTPServer {
// Health check
router.get("/health") { _, _ in
- let batchingStatus: String
- if let config = batchingConfig {
- batchingStatus = "enabled (max batch: \(config.maxBatchSize), continuous: \(config.enableContinuousBatching))"
- } else {
- batchingStatus = "disabled"
- }
- let response = HealthResponse(
- status: "ok",
- batching: batchingStatus
- )
+ let response = HealthResponse(status: "ok")
return try encodeJSON(response)
}
- // Metrics endpoint
- router.get("/metrics") { _, _ in
- let metrics: [String: Any]
- if let processor = batchProcessor {
- let status = await processor.getStatus()
- metrics = [
- "waiting_requests": status.waitingCount,
- "running_requests": status.runningCount,
- "max_batch_size": status.maxBatchSize,
- "total_requests_processed": status.metrics.totalRequestsProcessed,
- "total_batches_processed": status.metrics.totalBatchesProcessed,
- "avg_batch_size": String(format: "%.2f", status.metrics.avgBatchSize),
- "avg_latency_ms": String(format: "%.2f", status.metrics.avgLatencyMs),
- "cache_hit_rate": String(format: "%.2f%%", status.metrics.cacheHitRate * 100),
- "total_tokens_generated": status.metrics.totalTokensGenerated,
- ]
- } else {
- metrics = [
- "mode": "sequential",
- "batching": "disabled",
- ]
- }
-
- // Build JSON response
- var jsonString = "{\n"
- for (key, value) in metrics {
- jsonString += " \"\(key)\": \(value),\n"
- }
- jsonString += "}"
-
- var buffer = ByteBufferAllocator().buffer(capacity: jsonString.count)
- buffer.writeString(jsonString)
-
- return Response(
- status: .ok,
- headers: [.contentType: "application/json"],
- body: .init(byteBuffer: buffer)
- )
- }
-
// List models
router.get("/v1/models") { _, _ in
let response = ModelsResponse(
@@ -153,7 +96,7 @@ struct MLXHTTPServer {
let temperature = chatRequest.temperature ?? 0.7
let topP = chatRequest.top_p ?? 1.0
- let maxTokens = chatRequest.max_tokens ?? chatRequest.n_predict ?? 2048
+ let maxTokens = chatRequest.max_tokens ?? chatRequest.n_predict
let repetitionPenalty = chatRequest.repetition_penalty ?? 1.0
let stop = chatRequest.stop ?? []
let isStreaming = chatRequest.stream ?? false
@@ -231,7 +174,7 @@ struct MLXHTTPServer {
chatRequest: ChatCompletionRequest,
temperature: Float,
topP: Float,
- maxTokens: Int,
+ maxTokens: Int? = nil,
repetitionPenalty: Float,
stop: [String],
tools: [AnyCodable]? = nil
@@ -281,7 +224,7 @@ struct MLXHTTPServer {
chatRequest: ChatCompletionRequest,
temperature: Float,
topP: Float,
- maxTokens: Int,
+ maxTokens: Int?,
repetitionPenalty: Float,
stop: [String],
tools: [AnyCodable]? = nil
diff --git a/mlx-server/scripts/benchmark.py b/mlx-server/scripts/benchmark.py
deleted file mode 100755
index 03bac8597..000000000
--- a/mlx-server/scripts/benchmark.py
+++ /dev/null
@@ -1,458 +0,0 @@
-#!/usr/bin/env python3
-"""
-MLX Server Benchmark Script
-
-Evaluates token generation speed over multiple iterations with various configurations.
-
-Usage:
- python3 benchmark.py --port 8080 --model llama-2-7b --iterations 10 --max-tokens 100
- python3 benchmark.py --port 8080 --batch-sizes 1,2,4,8 --compare-batching
-"""
-
-import asyncio
-import aiohttp
-import argparse
-import json
-import statistics
-import time
-from datetime import datetime
-from typing import List, Dict, Any, Optional
-from dataclasses import dataclass, field
-from tabulate import tabulate
-
-
-@dataclass
-class BenchmarkConfig:
- """Configuration for benchmark run."""
- host: str = "127.0.0.1"
- port: int = 8080
- model: str = "model"
- api_key: Optional[str] = None
- iterations: int = 10
- max_tokens: int = 100
- warmup_iterations: int = 2
- prompt: str = "Hello, I am a large language model. Tell me a short story about AI."
- batch_sizes: List[int] = field(default_factory=lambda: [1])
- compare_batching: bool = False
- output_format: str = "table" # table, json, csv
-
-
-@dataclass
-class BenchmarkResult:
- """Result of a single benchmark run."""
- iteration: int
- prompt_tokens: int
- completion_tokens: int
- total_tokens: int
- latency_ms: float
- tokens_per_second: float
- ttft_ms: float # Time to first token
-
-
-@dataclass
-class BatchBenchmarkResult:
- """Result of a batch benchmark run."""
- batch_size: int
- iterations: int
- results: List[BenchmarkResult]
- avg_latency_ms: float
- avg_tokens_per_second: float
- avg_ttft_ms: float
- p50_latency_ms: float
- p90_latency_ms: float
- p99_latency_ms: float
- cache_hit_rate: float
- total_requests: int
- total_tokens: int
- overall_tokens_per_second: float
-
-
-class MLXBenchmark:
- """Benchmark client for MLX server."""
-
- def __init__(self, config: BenchmarkConfig):
- self.config = config
- self.base_url = f"http://{config.host}:{config.port}/v1"
- self.health_url = f"http://{config.host}:{config.port}/health"
- self.metrics_url = f"http://{config.host}:{config.port}/metrics"
- self.headers = {
- "Content-Type": "application/json",
- }
- if config.api_key:
- self.headers["Authorization"] = f"Bearer {config.api_key}"
-
- async def check_health(self) -> bool:
- """Check if server is healthy."""
- try:
- async with aiohttp.ClientSession() as session:
- async with session.get(self.health_url) as resp:
- return resp.status == 200
- except Exception as e:
- print(f"Health check failed: {e}")
- return False
-
- async def get_metrics(self) -> Dict[str, Any]:
- """Get server metrics."""
- try:
- async with aiohttp.ClientSession() as session:
- async with session.get(self.metrics_url) as resp:
- if resp.status == 200:
- text = await resp.text()
- return json.loads(text)
- except Exception:
- pass
- return {}
-
- async def make_request(
- self,
- session: aiohttp.ClientSession,
- stream: bool = False
- ) -> Dict[str, Any]:
- """Make a chat completion request."""
- payload = {
- "model": self.config.model,
- "messages": [{"role": "user", "content": self.config.prompt}],
- "max_tokens": self.config.max_tokens,
- "stream": stream,
- }
-
- start_time = time.perf_counter()
- ttft = None
-
- async with session.post(
- f"{self.base_url}/chat/completions",
- json=payload,
- headers=self.headers
- ) as resp:
- if stream:
- # For streaming, measure TTFT
- async for line in resp.content:
- if ttft is None:
- ttft = (time.perf_counter() - start_time) * 1000
- if line.strip() == b"data: [DONE]":
- break
- return {"ttft_ms": ttft}
- else:
- data = await resp.json()
- latency_ms = (time.perf_counter() - start_time) * 1000
- return {
- "latency_ms": latency_ms,
- "ttft_ms": latency_ms * 0.1, # Estimate TTFT as 10% of latency
- "data": data
- }
-
- def parse_result(self, response: Dict[str, Any], iteration: int) -> BenchmarkResult:
- """Parse response into benchmark result."""
- data = response.get("data", {})
-
- try:
- usage = data.get("usage", {})
- prompt_tokens = usage.get("prompt_tokens", 50)
- completion_tokens = usage.get("completion_tokens", self.config.max_tokens)
- except (TypeError, AttributeError):
- prompt_tokens = 50
- completion_tokens = self.config.max_tokens
-
- latency_ms = response.get("latency_ms", 100)
- ttft_ms = response.get("ttft_ms", latency_ms * 0.1)
- total_tokens = prompt_tokens + completion_tokens
- tokens_per_second = (total_tokens / latency_ms) * 1000 if latency_ms > 0 else 0
-
- return BenchmarkResult(
- iteration=iteration,
- prompt_tokens=prompt_tokens,
- completion_tokens=completion_tokens,
- total_tokens=total_tokens,
- latency_ms=latency_ms,
- tokens_per_second=tokens_per_second,
- ttft_ms=ttft_ms
- )
-
- async def run_single_benchmark(self, batch_size: int = 1) -> BatchBenchmarkResult:
- """Run benchmark with specified batch size."""
- print(f"\n{'='*60}")
- print(f"Benchmarking batch size: {batch_size}")
- print(f"{'='*60}")
-
- results: List[BenchmarkResult] = []
-
- async with aiohttp.ClientSession() as session:
- # Warmup
- print(f" Warming up ({self.config.warmup_iterations} iterations)...", end=" ", flush=True)
- for i in range(self.config.warmup_iterations):
- await self.make_request(session)
- print("done")
-
- # Run iterations
- print(f" Running {self.config.iterations} iterations...", end=" ", flush=True)
- for i in range(self.config.iterations):
- # For batch > 1, make concurrent requests
- if batch_size > 1:
- tasks = [self.make_request(session) for _ in range(batch_size)]
- responses = await asyncio.gather(*tasks)
- for response in responses:
- result = self.parse_result(response, i)
- results.append(result)
- else:
- response = await self.make_request(session)
- result = self.parse_result(response, i)
- results.append(result)
-
- if (i + 1) % 5 == 0:
- print(f"{i+1}...", end="", flush=True)
- print("done")
-
- # Calculate statistics
- latencies = [r.latency_ms for r in results]
- tps_values = [r.tokens_per_second for r in results]
- ttft_values = [r.ttft_ms for r in results]
-
- avg_latency = statistics.mean(latencies)
- avg_tps = statistics.mean(tps_values)
- avg_ttft = statistics.mean(ttft_values)
-
- p50 = statistics.median(latencies)
- p90 = sorted(latencies)[int(len(latencies) * 0.9)]
- p99 = sorted(latencies)[int(len(latencies) * 0.99)]
-
- # Get cache metrics
- metrics = await self.get_metrics()
- cache_hit_rate = 0.0
- try:
- cache_hit_rate = float(metrics.get("cache_hit_rate", "0").replace("%", ""))
- except (ValueError, TypeError):
- pass
-
- return BatchBenchmarkResult(
- batch_size=batch_size,
- iterations=self.config.iterations,
- results=results,
- avg_latency_ms=avg_latency,
- avg_tokens_per_second=avg_tps,
- avg_ttft_ms=avg_ttft,
- p50_latency_ms=p50,
- p90_latency_ms=p90,
- p99_latency_ms=p99,
- cache_hit_rate=cache_hit_rate,
- total_requests=len(results),
- total_tokens=sum(r.total_tokens for r in results),
- overall_tokens_per_second=sum(r.total_tokens for r in results) / (sum(latencies) / 1000)
- )
-
-
-def format_table(results: List[BatchBenchmarkResult], config: BenchmarkConfig) -> str:
- """Format results as a table."""
- table_data = []
- headers = [
- "Batch Size",
- "Requests",
- "Avg Latency",
- "P50 Latency",
- "P90 Latency",
- "Tokens/sec",
- "TTFT",
- "Cache Hit%"
- ]
-
- for r in results:
- table_data.append([
- r.batch_size,
- r.total_requests,
- f"{r.avg_latency_ms:.1f}ms",
- f"{r.p50_latency_ms:.1f}ms",
- f"{r.p90_latency_ms:.1f}ms",
- f"{r.avg_tokens_per_second:.1f}",
- f"{r.avg_ttft_ms:.1f}ms",
- f"{r.cache_hit_rate:.1f}%"
- ])
-
- return tabulate(table_data, headers=headers, tablefmt="github")
-
-
-def format_json(results: List[BatchBenchmarkResult], config: BenchmarkConfig) -> str:
- """Format results as JSON."""
- output = {
- "timestamp": datetime.now().isoformat(),
- "config": {
- "host": config.host,
- "port": config.port,
- "model": config.model,
- "iterations": config.iterations,
- "max_tokens": config.max_tokens,
- "prompt_length": len(config.prompt),
- },
- "results": []
- }
-
- for r in results:
- output["results"].append({
- "batch_size": r.batch_size,
- "total_requests": r.total_requests,
- "total_tokens": r.total_tokens,
- "latency": {
- "avg_ms": r.avg_latency_ms,
- "p50_ms": r.p50_latency_ms,
- "p90_ms": r.p90_latency_ms,
- "p99_ms": r.p99_latency_ms,
- },
- "throughput": {
- "tokens_per_second": r.avg_tokens_per_second,
- "overall_tokens_per_second": r.overall_tokens_per_second
- },
- "ttft_ms": r.avg_ttft_ms,
- "cache_hit_rate": r.cache_hit_rate
- })
-
- return json.dumps(output, indent=2)
-
-
-def format_csv(results: List[BatchBenchmarkResult], config: BenchmarkConfig) -> str:
- """Format results as CSV."""
- lines = [
- "batch_size,total_requests,total_tokens,avg_latency_ms,p50_latency_ms,p90_latency_ms,tokens_per_second,ttft_ms,cache_hit_rate"
- ]
-
- for r in results:
- lines.append(
- f"{r.batch_size},{r.total_requests},{r.total_tokens},"
- f"{r.avg_latency_ms:.2f},{r.p50_latency_ms:.2f},{r.p90_latency_ms:.2f},"
- f"{r.avg_tokens_per_second:.2f},{r.avg_ttft_ms:.2f},{r.cache_hit_rate:.2f}"
- )
-
- return "\n".join(lines)
-
-
-async def run_benchmark(config: BenchmarkConfig) -> List[BatchBenchmarkResult]:
- """Run the complete benchmark suite."""
- print("\n" + "="*60)
- print("MLX Server Benchmark")
- print("="*60)
- print(f" Host: {config.host}:{config.port}")
- print(f" Model: {config.model}")
- print(f" Iterations: {config.iterations}")
- print(f" Max tokens: {config.max_tokens}")
- print(f" Prompt length: {len(config.prompt)} chars")
-
- client = MLXBenchmark(config)
-
- # Check health
- print("\nChecking server health...", end=" ")
- healthy = await client.check_health()
- if healthy:
- print("OK")
- else:
- print("FAILED - Server may not be running")
- print(f" URL: {client.health_url}")
- return []
-
- results: List[BatchBenchmarkResult] = []
-
- if config.compare_batching:
- # Test multiple batch sizes
- for batch_size in config.batch_sizes:
- result = await client.run_single_benchmark(batch_size)
- results.append(result)
- else:
- # Single benchmark
- result = await client.run_single_benchmark(config.batch_sizes[0])
- results.append(result)
-
- return results
-
-
-def print_summary(results: List[BatchBenchmarkResult], config: BenchmarkConfig):
- """Print summary of results."""
- print("\n" + "="*60)
- print("Results Summary")
- print("="*60)
-
- if config.output_format == "table":
- print(format_table(results, config))
- elif config.output_format == "json":
- print(format_json(results, config))
- else:
- print(format_csv(results, config))
-
- # Comparison summary
- if len(results) > 1:
- baseline = results[0]
- print("\nComparison vs Baseline (batch_size=1):")
- print("-" * 40)
- for r in results[1:]:
- if r.batch_size > 1:
- latency_change = ((r.avg_latency_ms - baseline.avg_latency_ms) / baseline.avg_latency_ms) * 100
- tps_change = ((r.avg_tokens_per_second - baseline.avg_tokens_per_second) / baseline.avg_tokens_per_second) * 100
- print(f" Batch {r.batch_size}:")
- print(f" Latency: {latency_change:+.1f}%")
- print(f" Throughput: {tps_change:+.1f}%")
- print(f" Cache hit rate: {r.cache_hit_rate:.1f}%")
-
-
-def main():
- parser = argparse.ArgumentParser(
- description="Benchmark MLX server token generation speed",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""
-Examples:
- # Basic benchmark with 10 iterations
- python3 benchmark.py --port 8080 --model llama-2-7b --iterations 10
-
- # Compare different batch sizes
- python3 benchmark.py --port 8080 --model llama-2-7b --compare-batching --batch-sizes 1,2,4,8
-
- # JSON output for CI/CD
- python3 benchmark.py --port 8080 --model llama-2-7b --output-format json
-
- # Custom prompt and max tokens
- python3 benchmark.py --port 8080 --model llama-2-7b --prompt "Your prompt here" --max-tokens 200
-"""
- )
-
- parser.add_argument("--host", default="127.0.0.1", help="Server host")
- parser.add_argument("--port", type=int, default=8080, help="Server port")
- parser.add_argument("--model", default="model", help="Model ID")
- parser.add_argument("--api-key", default=None, help="API key for authentication")
- parser.add_argument("--iterations", type=int, default=10, help="Number of iterations")
- parser.add_argument("--warmup-iterations", type=int, default=2, help="Warmup iterations")
- parser.add_argument("--max-tokens", type=int, default=100, help="Max tokens to generate")
- parser.add_argument("--prompt", type=str,
- default="Hello, I am a large language model. Tell me a short story about AI.",
- help="Prompt for generation")
-
- # Batching options
- parser.add_argument("--compare-batching", action="store_true",
- help="Compare different batch sizes")
- parser.add_argument("--batch-sizes", type=str, default="1",
- help="Comma-separated list of batch sizes to test")
-
- # Output options
- parser.add_argument("--output-format", choices=["table", "json", "csv"],
- default="table", help="Output format")
-
- args = parser.parse_args()
-
- # Parse batch sizes
- batch_sizes = [int(x) for x in args.batch_sizes.split(",")]
-
- config = BenchmarkConfig(
- host=args.host,
- port=args.port,
- model=args.model,
- api_key=args.api_key,
- iterations=args.iterations,
- warmup_iterations=args.warmup_iterations,
- max_tokens=args.max_tokens,
- prompt=args.prompt,
- batch_sizes=batch_sizes,
- compare_batching=args.compare_batching,
- output_format=args.output_format
- )
-
- results = asyncio.run(run_benchmark(config))
-
- if results:
- print_summary(results, config)
-
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/mlx-server/scripts/performance_bench.py b/mlx-server/scripts/performance_bench.py
deleted file mode 100644
index cdecfe020..000000000
--- a/mlx-server/scripts/performance_bench.py
+++ /dev/null
@@ -1,200 +0,0 @@
-#!/usr/bin/env python3
-"""
-MLX Server Performance Benchmark - Enhanced
-Tests batch processing, caching, and concurrency optimizations
-"""
-import requests
-import time
-import json
-import threading
-from concurrent.futures import ThreadPoolExecutor, as_completed
-
-URL = "http://127.0.0.1:8081/v1/chat/completions"
-METRICS_URL = "http://127.0.0.1:8081/metrics"
-
-def get_metrics():
- """Get server metrics"""
- try:
- resp = requests.get(METRICS_URL, timeout=5)
- return resp.json()
- except:
- return {}
-
-def warmup(iterations=3):
- """Warmup the model"""
- print(f" Warming up ({iterations} requests)...", end=" ", flush=True)
- for _ in range(iterations):
- requests.post(URL, json={
- "model": "model",
- "messages": [{"role": "user", "content": "hi"}],
- "max_tokens": 10,
- "temperature": 0.1
- })
- print("done")
-
-def sequential_benchmark(name, iterations, max_tokens, temperature):
- """Sequential request benchmark"""
- times = []
- tokens = []
-
- for i in range(iterations):
- start = time.perf_counter()
- resp = requests.post(URL, json={
- "model": "model",
- "messages": [{"role": "user", "content": "Tell me a short story about AI."}],
- "max_tokens": max_tokens,
- "temperature": temperature
- })
- elapsed = time.perf_counter() - start
-
- try:
- data = resp.json()
- completion_tokens = data.get("usage", {}).get("completion_tokens", max_tokens)
- except:
- completion_tokens = max_tokens
-
- times.append(elapsed)
- tokens.append(completion_tokens)
-
- return times, tokens
-
-def parallel_benchmark(name, iterations, max_tokens, temperature, concurrency):
- """Parallel request benchmark - tests batch processing"""
- def make_request(i):
- start = time.perf_counter()
- resp = requests.post(URL, json={
- "model": "model",
- "messages": [{"role": "user", "content": f"Tell me about topic {i} briefly."}],
- "max_tokens": max_tokens,
- "temperature": temperature
- })
- elapsed = time.perf_counter() - start
-
- try:
- data = resp.json()
- completion_tokens = data.get("usage", {}).get("completion_tokens", max_tokens)
- except:
- completion_tokens = max_tokens
-
- return elapsed, completion_tokens
-
- times = []
- total_tokens = 0
-
- with ThreadPoolExecutor(max_workers=concurrency) as executor:
- futures = [executor.submit(make_request, i) for i in range(iterations)]
- for future in as_completed(futures):
- elapsed, tokens = future.result()
- times.append(elapsed)
- total_tokens += tokens
-
- return times, total_tokens
-
-def print_stats(name, times, total_tokens, parallel=False):
- """Print benchmark statistics"""
- avg_time = sum(times) / len(times)
- total_time = sum(times)
- tps = total_tokens / total_time if total_time > 0 else 0
- sorted_times = sorted(times)
-
- print(f"\n Results:")
- print(f" Total requests: {len(times)}")
- if parallel:
- print(f" Wall clock time: {total_time*1000:.0f}ms")
- print(f" Avg latency: {avg_time*1000:.0f}ms")
- print(f" Total tokens: {total_tokens}")
- print(f" Throughput: {tps:.1f} tokens/sec")
- print(f" P50 latency: {sorted_times[len(times)//2]*1000:.0f}ms")
- print(f" P90 latency: {sorted_times[int(len(times)*0.9)]*1000:.0f}ms")
- print(f" P99 latency: {sorted_times[int(len(times)*0.99)]*1000:.0f}ms")
-
- return tps
-
-def main():
- print("="*60)
- print("MLX Server Performance Benchmark")
- print("="*60)
-
- # Get initial metrics
- metrics = get_metrics()
- if metrics:
- print(f"\nInitial metrics: {json.dumps(metrics, indent=2)}")
-
- print("\n" + "="*60)
- print("SEQUENTIAL BENCHMARKS")
- print("="*60)
-
- warmup()
-
- configs = [
- ("Baseline (temp=0.7, 50 tokens)", 0.7, 50),
- ("Temp=0.1, 50 tokens", 0.1, 50),
- ("Temp=0.7, 100 tokens", 0.7, 100),
- ("Temp=0.1, 100 tokens", 0.1, 100),
- ]
-
- seq_results = []
- for name, temp, tokens in configs:
- print(f"\n{'='*50}")
- print(f"{name}")
- print(f"{'='*50}")
-
- times, tkns = sequential_benchmark(name, iterations=10, max_tokens=tokens, temperature=temp)
- tps = print_stats(name, times, sum(tkns))
- seq_results.append((name, tps))
-
- print("\n" + "="*60)
- print("PARALLEL BENCHMARKS (Batch Processing Test)")
- print("="*60)
-
- # Test with different concurrency levels
- concurrency_levels = [2, 4, 8]
-
- parallel_results = []
- for concurrency in concurrency_levels:
- print(f"\n{'='*50}")
- print(f"Parallel Benchmark (concurrency={concurrency})")
- print(f"{'='*50}")
-
- warmup()
-
- start = time.perf_counter()
- times, total_tokens = parallel_benchmark(
- "parallel", iterations=20, max_tokens=50, temperature=0.7, concurrency=concurrency
- )
- wall_time = time.perf_counter() - start
-
- tps = print_stats(f"parallel_{concurrency}", times, total_tokens, parallel=True)
- parallel_results.append((f"concurrency={concurrency}", tps, wall_time))
-
- # Check metrics
- metrics = get_metrics()
- if metrics:
- print(f"\n Metrics after test: {json.dumps(metrics, indent=4)}")
-
- print("\n" + "="*60)
- print("SUMMARY")
- print("="*60)
-
- print("\nSequential benchmarks (tokens/sec):")
- for name, tps in sorted(seq_results, key=lambda x: -x[1]):
- print(f" {name}: {tps:.1f}")
-
- print("\nParallel benchmarks (throughput):")
- for name, tps, wall_time in sorted(parallel_results, key=lambda x: -x[1]):
- print(f" {name}: {tps:.1f} tokens/sec (wall: {wall_time*1000:.0f}ms)")
-
- print("\n" + "="*60)
- print("OPTIMIZATION VERIFICATION")
- print("="*60)
- print("""
- Expected improvements from optimizations:
- 1. Parallel batch execution: Higher throughput with concurrent requests
- 2. String building optimization: Lower latency for long generations
- 3. Continuous batching: Better GPU utilization
- 4. Improved hash function: Better cache hit rates
- 5. Priority queue: Better QoS for high-priority requests
- """)
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/mlx-server/scripts/quick_bench.sh b/mlx-server/scripts/quick_bench.sh
deleted file mode 100755
index 24cdfaec6..000000000
--- a/mlx-server/scripts/quick_bench.sh
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/bin/bash
-# Quick benchmark script for MLX server
-# Usage: ./quick_bench.sh <port> <iterations> <max_tokens>
-
-PORT=${1:-8080}
-ITERATIONS=${2:-10}
-MAX_TOKENS=${3:-100}
-MODEL=${4:-model}
-
-echo "MLX Quick Benchmark"
-echo "==================="
-echo "Port: $PORT"
-echo "Iterations: $ITERATIONS"
-echo "Max tokens: $MAX_TOKENS"
-echo ""
-
-# Check if server is running
-if ! curl -s "http://127.0.0.1:$PORT/health" > /dev/null 2>&1; then
- echo "Error: Server not running on port $PORT"
- exit 1
-fi
-
-# Run benchmark using Python script
-python3 scripts/benchmark.py \
- --port "$PORT" \
- --model "$MODEL" \
- --iterations "$ITERATIONS" \
- --max-tokens "$MAX_TOKENS" \
- --output-format table
\ No newline at end of file
diff --git a/mlx-server/scripts/simple_bench.py b/mlx-server/scripts/simple_bench.py
deleted file mode 100644
index addb8a3b5..000000000
--- a/mlx-server/scripts/simple_bench.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/env python3
-"""
-Simple MLX benchmark with warmup
-"""
-import requests
-import time
-import json
-
-URL = "http://127.0.0.1:8081/v1/chat/completions"
-
-def benchmark(name, iterations=10, max_tokens=100, temperature=0.7):
- # Warmup
- print(f" Warming up (3 requests)...", end=" ")
- for _ in range(3):
- requests.post(URL, json={"model":"model","messages":[{"role":"user","content":"hi"}],"max_tokens":10,"temperature":temperature})
- print("done")
-
- times = []
- tokens = []
-
- print(f" Running {iterations} iterations...", end=" ")
- for i in range(iterations):
- start = time.perf_counter()
- resp = requests.post(URL, json={
- "model": "model",
- "messages": [{"role": "user", "content": "Tell me a short story about AI."}],
- "max_tokens": max_tokens,
- "temperature": temperature
- })
- elapsed = time.perf_counter() - start
-
- try:
- data = resp.json()
- completion_tokens = data.get("usage", {}).get("completion_tokens", max_tokens)
- except:
- completion_tokens = max_tokens
-
- times.append(elapsed)
- tokens.append(completion_tokens)
- if (i + 1) % 5 == 0:
- print(f"{i+1}...", end="")
- print("done")
-
- avg_time = sum(times) / len(times)
- total_tokens = sum(tokens)
- avg_tps = total_tokens / sum(times)
-
- print(f"\n Results:")
- print(f" Avg latency: {avg_time*1000:.0f}ms")
- print(f" Total tokens: {total_tokens}")
- print(f" Avg tokens/sec: {avg_tps:.1f}")
- print(f" P50 latency: {sorted(times)[len(times)//2]*1000:.0f}ms")
- print(f" P90 latency: {sorted(times)[int(len(times)*0.9)]*1000:.0f}ms")
-
- return avg_tps, avg_time
-
-if __name__ == "__main__":
- print("="*50)
- print("MLX Server Performance Benchmark")
- print("="*50)
- print()
-
- # Test different configurations
- configs = [
- ("Baseline (temp=0.7, 100 tokens)", 0.7, 100),
- ("Temp=0.1, 100 tokens", 0.1, 100),
- ("Temp=0.7, 50 tokens", 0.7, 50),
- ("Temp=0.9, 100 tokens", 0.9, 100),
- ("High temp=1.0, 100 tokens", 1.0, 100),
- ]
-
- results = []
- for name, temp, tokens in configs:
- print(f"\n{'='*50}")
- print(f"{name}")
- print(f"{'='*50}")
- tps, latency = benchmark(name, iterations=10, max_tokens=tokens, temperature=temp)
- results.append((name, tps))
-
- print("\n" + "="*50)
- print("SUMMARY")
- print("="*50)
- for name, tps in sorted(results, key=lambda x: -x[1]):
- print(f" {name}: {tps:.1f} tokens/sec")
\ No newline at end of file
diff --git a/src-tauri/plugins/tauri-plugin-mlx/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-mlx/guest-js/index.ts
index 6e0401812..8ab9b9f7b 100644
--- a/src-tauri/plugins/tauri-plugin-mlx/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-mlx/guest-js/index.ts
@@ -9,17 +9,9 @@ function asNumber(v: any, defaultValue = 0): number {
return isFinite(n) ? n : defaultValue
}
-function asString(v: any, defaultValue = ''): string {
- if (v === '' || v === null || v === undefined) return defaultValue
- return String(v)
-}
-
export function normalizeMlxConfig(config: any): MlxConfig {
return {
ctx_size: asNumber(config.ctx_size),
- n_predict: asNumber(config.n_predict),
- threads: asNumber(config.threads),
- chat_template: asString(config.chat_template),
}
}
diff --git a/src-tauri/plugins/tauri-plugin-mlx/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-mlx/guest-js/types.ts
index d2a615ff6..7702d4c79 100644
--- a/src-tauri/plugins/tauri-plugin-mlx/guest-js/types.ts
+++ b/src-tauri/plugins/tauri-plugin-mlx/guest-js/types.ts
@@ -14,12 +14,4 @@ export interface UnloadResult {
export type MlxConfig = {
ctx_size: number
- n_predict: number
- threads: number
- chat_template: string
- batch_size: number
- batch_timeout_ms: number
- enable_continuous_batching: boolean
- kv_block_size: number
- enable_prefix_caching: boolean
}
diff --git a/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs b/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs
index 62a4ac233..c99299bea 100644
--- a/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs
@@ -29,23 +29,6 @@ pub struct UnloadResult {
pub struct MlxConfig {
#[serde(default)]
pub ctx_size: i32,
- #[serde(default)]
- pub n_predict: i32,
- #[serde(default)]
- pub threads: i32,
- #[serde(default)]
- pub chat_template: String,
- // Batching configuration
- #[serde(default)]
- pub batch_size: i32,
- #[serde(default)]
- pub batch_timeout_ms: i32,
- #[serde(default)]
- pub enable_continuous_batching: bool,
- #[serde(default)]
- pub kv_block_size: i32,
- #[serde(default)]
- pub enable_prefix_caching: bool,
}
/// Load a model using the MLX server binary
@@ -121,39 +104,6 @@ pub async fn load_mlx_model<R: Runtime>(
args.push(api_key.clone());
}
- if !config.chat_template.is_empty() {
- args.push("--chat-template".to_string());
- args.push(config.chat_template.clone());
- }
-
- if is_embedding {
- args.push("--embedding".to_string());
- }
-
- // Batching options
- if config.batch_size > 0 {
- args.push("--max-batch-size".to_string());
- args.push(config.batch_size.to_string());
- }
-
- if config.batch_timeout_ms > 0 {
- args.push("--batch-timeout-ms".to_string());
- args.push(config.batch_timeout_ms.to_string());
- }
-
- if config.enable_continuous_batching {
- args.push("--enable-continuous-batching".to_string());
- }
-
- if config.kv_block_size > 0 {
- args.push("--kv-block-size".to_string());
- args.push(config.kv_block_size.to_string());
- }
-
- if config.enable_prefix_caching {
- args.push("--enable-prefix-caching".to_string());
- }
-
log::info!("MLX server arguments: {:?}", args);
// Configure the command