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.

reactor: clean up settings

Louisb501b402f718
diff --git a/extensions/mlx-extension/settings.json b/extensions/mlx-extension/settings.json
index b3b643ce0..f8b83511c 100644
--- a/extensions/mlx-extension/settings.json
+++ b/extensions/mlx-extension/settings.json
@@ -11,18 +11,6 @@
"textAlign": "right"
}
},
- {
- "key": "batch_timeout_ms",
- "title": "Batch Timeout (ms)",
- "description": "Maximum time to wait for batch to fill (milliseconds)",
- "controllerType": "input",
- "controllerProps": {
- "value": 100,
- "placeholder": "100",
- "type": "number",
- "textAlign": "right"
- }
- },
{
"key": "enable_continuous_batching",
"title": "Continuous Batching",
@@ -30,30 +18,11 @@
"controllerType": "checkbox",
"controllerProps": { "value": false }
},
- {
- "key": "enable_prefix_caching",
- "title": "Prefix Caching",
- "description": "Enable KV cache reuse for repeated prefixes",
- "controllerType": "checkbox",
- "controllerProps": { "value": true }
- },
{
"key": "auto_unload",
"title": "Auto unload model",
"description": "Automatically unload other models when loading a new one",
"controllerType": "checkbox",
"controllerProps": { "value": true }
- },
- {
- "key": "timeout",
- "title": "Timeout (seconds)",
- "description": "Maximum time to wait for model to load",
- "controllerType": "input",
- "controllerProps": {
- "value": 600,
- "placeholder": "600",
- "type": "number",
- "textAlign": "right"
- }
}
]
diff --git a/mlx-server/Sources/MLXServer/BatchScheduler.swift b/mlx-server/Sources/MLXServer/BatchScheduler.swift
index 0ea52c9f4..b7b733257 100644
--- a/mlx-server/Sources/MLXServer/BatchScheduler.swift
+++ b/mlx-server/Sources/MLXServer/BatchScheduler.swift
@@ -9,23 +9,14 @@ import Hummingbird
/// Configuration for batch processing
public struct BatchingConfig: Sendable {
public var maxBatchSize: Int
- public var batchTimeoutMs: Int
public var maxModelTokens: Int
public var enableContinuousBatching: Bool
- public var kvBlockSize: Int
- public var enablePrefixCatching: Bool
- public var batchTimeout: TimeInterval {
- TimeInterval(batchTimeoutMs) / 1000.0
- }
public static let `default` = BatchingConfig(
maxBatchSize: 8,
- batchTimeoutMs: 50,
maxModelTokens: 4096,
enableContinuousBatching: true,
- kvBlockSize: 16,
- enablePrefixCatching: true
)
}
@@ -37,7 +28,6 @@ struct BatchRequest: Identifiable, Sendable {
let chatRequest: ChatCompletionRequest
let createdAt: Date
var priority: Int
- var timeoutTimer: Task<Void, Never>?
init(
id: String = UUID().uuidString,
@@ -50,13 +40,6 @@ struct BatchRequest: Identifiable, Sendable {
self.createdAt = createdAt
self.priority = priority
}
-
- /// Create a copy with a modified timeout timer
- func withTimeout(_ timer: Task<Void, Never>?) -> BatchRequest {
- var copy = self
- copy.timeoutTimer = timer
- return copy
- }
}
// MARK: - Active Request
@@ -140,6 +123,7 @@ actor RequestScheduler {
init(config: BatchingConfig) {
self.config = config
+ log("RequestScheduler initialized with config: \(config)")
}
func setBatchProcessor(_ processor: BatchProcessor) {
@@ -151,41 +135,12 @@ actor RequestScheduler {
}
/// Enqueue a request for batch processing
- func enqueue(_ request: BatchRequest, timeout: TimeInterval = 30.0) {
- // Cancel any existing timeout
- request.timeoutTimer?.cancel()
-
- let requestId = request.id // Capture for timeout closure
-
- // Set up timeout timer
- let timer = Task { [weak self] in
- try? await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))
-
- guard let self = self else { return }
-
- // Check if request is still waiting (actor-isolated access)
- await self.checkAndRemoveTimedOutRequest(id: requestId, timeout: timeout)
- }
-
- let updatedRequest = request.withTimeout(timer)
- waitingQueue.append(updatedRequest)
- }
-
- /// Check and remove timed out requests (actor-isolated)
- private func checkAndRemoveTimedOutRequest(id: String, timeout: TimeInterval) {
- if let index = waitingQueue.firstIndex(where: { $0.id == id }) {
- waitingQueue.remove(at: index)
- log("[mlx] Request \(id) timed out after \(timeout)s")
- }
+ func enqueue(_ request: BatchRequest) {
+ waitingQueue.append(request)
}
/// Get the next batch of requests to process
func getNextBatch() -> [BatchRequest] {
- let now = Date()
-
- // Remove timed out requests
- waitingQueue.removeAll { now.timeIntervalSince($0.createdAt) > config.batchTimeout }
-
// For continuous batching, add slots from finished requests
let availableSlots = config.maxBatchSize - runningRequests.count
@@ -341,7 +296,6 @@ actor BatchProcessor {
enum BatchingError: Error, LocalizedError {
case queueEmpty
- case batchTimeout
case invalidRequest(String)
case processingFailed(String)
@@ -349,12 +303,10 @@ enum BatchingError: Error, LocalizedError {
switch self {
case .queueEmpty:
return "Request queue is empty"
- case .batchTimeout:
- return "Batch processing timed out"
case .invalidRequest(let reason):
return "Invalid request: \(reason)"
case .processingFailed(let reason):
return "Processing failed: \(reason)"
}
}
-}
\ No newline at end of file
+}
diff --git a/mlx-server/Sources/MLXServer/MLXServerCommand.swift b/mlx-server/Sources/MLXServer/MLXServerCommand.swift
index f276cd297..a56fd709e 100644
--- a/mlx-server/Sources/MLXServer/MLXServerCommand.swift
+++ b/mlx-server/Sources/MLXServer/MLXServerCommand.swift
@@ -33,18 +33,9 @@ struct MLXServerCommand: AsyncParsableCommand {
@Option(name: .long, help: "Maximum batch size for concurrent requests (0 to disable)")
var maxBatchSize: Int = 0
- @Option(name: .long, help: "Batch timeout in milliseconds")
- var batchTimeoutMs: Int = 100
-
@Flag(name: .long, help: "Enable continuous batching")
var enableContinuousBatching: Bool = false
- @Option(name: .long, help: "KV cache block size in tokens")
- var kvBlockSize: Int = 16
-
- @Flag(name: .long, help: "Enable prefix caching")
- var enablePrefixCaching: Bool = false
-
func run() async throws {
// Set GPU memory limit to prevent OOM issues
Memory.cacheLimit = 20 * 1024 * 1024 // 20GB limit
@@ -60,9 +51,7 @@ struct MLXServerCommand: AsyncParsableCommand {
if maxBatchSize > 0 {
log("[mlx] Batching enabled:")
log(" - Max batch size: \(maxBatchSize)")
- log(" - Batch timeout: \(batchTimeoutMs)ms")
log(" - Continuous batching: \(enableContinuousBatching)")
- log(" - Prefix caching: \(enablePrefixCaching)")
} else {
log("[mlx] Batching disabled (sequential processing)")
}
@@ -95,11 +84,8 @@ struct MLXServerCommand: AsyncParsableCommand {
if maxBatchSize > 0 {
batchingConfig = BatchingConfig(
maxBatchSize: maxBatchSize,
- batchTimeoutMs: batchTimeoutMs,
maxModelTokens: ctxSize,
enableContinuousBatching: enableContinuousBatching,
- kvBlockSize: kvBlockSize,
- enablePrefixCatching: enablePrefixCaching
)
} else {
batchingConfig = nil
diff --git a/mlx-server/Sources/MLXServer/PromptCache.swift b/mlx-server/Sources/MLXServer/PromptCache.swift
index bb77a7e69..8e315905b 100644
--- a/mlx-server/Sources/MLXServer/PromptCache.swift
+++ b/mlx-server/Sources/MLXServer/PromptCache.swift
@@ -45,24 +45,15 @@ public class PromptCache: @unchecked Sendable {
/// to create a new cache.
public func getUncachedSuffix(prompt: MLXArray) -> MLXArray? {
- log("[getUncachedSuffix] self.tokens.size = \(self.tokens.size)")
-
- log("cache[\(self.tokens.size)]: \(self.tokens)")
- log("prompt[\(prompt.size)]: \(prompt)")
-
let comPrefixLength = commonPrefixLength(newPromptTokens: prompt)
- log("[getUncachedSuffix] comPrefixLength: \(comPrefixLength)")
if comPrefixLength == self.tokens.size {
let suffix = prompt[comPrefixLength ..< prompt.size]
- log("Concating...")
self.tokens = concatenated([self.tokens, suffix], axis: 0)
return suffix
} else if comPrefixLength < self.tokens.size {
if isTrimmable() {
- log("trimming: \(self.tokens.size - comPrefixLength)")
let trimmedLen = self.trim(self.tokens.size - comPrefixLength)
- log("trimmed: \(trimmedLen)")
if trimmedLen != self.tokens.size - comPrefixLength {
log("Warning: request trimmed amount and actual trimmed amount are different")
}
@@ -111,7 +102,6 @@ public class PromptCache: @unchecked Sendable {
/// - Returns: Length of the common prefix
public func commonPrefixLength(_ array1: MLXArray, _ array2: MLXArray) -> Int {
// TODO: Add test cases
- log("Calculating common prefix: array1[\(array1.size)] array2[\(array2.size)]")
let minLength = min(array1.size, array2.size)
for i in 0 ..< minLength {
if all(array1[i] .!= array2[i]).item(Bool.self) {
diff --git a/web-app/src/services/models/default.ts b/web-app/src/services/models/default.ts
index 55e62488e..22627107e 100644
--- a/web-app/src/services/models/default.ts
+++ b/web-app/src/services/models/default.ts
@@ -333,8 +333,14 @@ export class DefaultModelsService implements ModelsService {
}
async stopAllModels(): Promise<void> {
- const models = await this.getActiveModels()
- if (models) await Promise.all(models.map((model) => this.stopModel(model)))
+ const llamaCppModels = await this.getActiveModels('llamacpp')
+ if (llamaCppModels)
+ await Promise.all(
+ llamaCppModels.map((model) => this.stopModel(model, 'llamacpp'))
+ )
+ const mlxModels = await this.getActiveModels('mlx')
+ if (mlxModels)
+ await Promise.all(mlxModels.map((model) => this.stopModel(model, 'mlx')))
}
async startModel(