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(mlx): show the context a model was loaded with in the token counter (#9437) (#9574)

Thinh Led2a5ba3a9841
diff --git a/extensions/mlx-extension/src/index.test.ts b/extensions/mlx-extension/src/index.test.ts
index d7863badf..c88674c7a 100644
--- a/extensions/mlx-extension/src/index.test.ts
+++ b/extensions/mlx-extension/src/index.test.ts
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import mlx_extension from './index'
import { fs, getJanDataFolderPath, events } from '@janhq/core'
import { invoke } from '@tauri-apps/api/core'
-import { unloadMlxModel } from '@janhq/tauri-plugin-mlx-api'
+import { loadMlxModel, unloadMlxModel } from '@janhq/tauri-plugin-mlx-api'
import { readGgufMetadata } from '@janhq/tauri-plugin-llamacpp-api'
const mockInvoke = vi.mocked(invoke)
@@ -11,6 +11,7 @@ const mockRm = vi.mocked(fs.rm)
const mockFileStat = vi.mocked(fs.fileStat)
const mockJanData = vi.mocked(getJanDataFolderPath)
const mockUnload = vi.mocked(unloadMlxModel)
+const mockLoad = vi.mocked(loadMlxModel)
const mockReadGguf = vi.mocked(readGgufMetadata)
function newExt(): any {
@@ -71,6 +72,47 @@ describe('getModelProps', () => {
})
})
+// A model's context window is chosen per model at load time (the web app maps
+// its `ctx_len` setting to the `ctx_size` load override). The token counter
+// must report that window, not the engine-wide default.
+describe('getModelProps after a load', () => {
+ async function loadWith(ext: any, id: string, settings?: object) {
+ ext.getLoadedModels = vi.fn().mockResolvedValue([])
+ ext.getRandomPort = vi.fn().mockResolvedValue(5000)
+ ext.generateApiKey = vi.fn().mockResolvedValue('key')
+ mockInvoke.mockImplementation(async (cmd: string) =>
+ cmd === 'read_yaml' ? { model_path: 'models/m' } : undefined
+ )
+ mockLoad.mockResolvedValue({ pid: 1, model_id: id } as any)
+ await ext.load(id, settings)
+ }
+
+ it('reports the context the model was loaded with, not the engine default', async () => {
+ const ext = newExt()
+ ext.onSettingUpdate('ctx_size', 8192)
+ await loadWith(ext, 'big', { ctx_size: 125000 })
+ expect((await ext.getModelProps('big')).nCtx).toBe(125000)
+ })
+
+ it('keeps each loaded model on its own context', async () => {
+ const ext = newExt()
+ await loadWith(ext, 'a', { ctx_size: 32768 })
+ await loadWith(ext, 'b', { ctx_size: 16384 })
+ expect((await ext.getModelProps('a')).nCtx).toBe(32768)
+ expect((await ext.getModelProps('b')).nCtx).toBe(16384)
+ })
+
+ it('falls back to the engine default once the model is unloaded', async () => {
+ const ext = newExt()
+ ext.onSettingUpdate('ctx_size', 8192)
+ await loadWith(ext, 'big', { ctx_size: 125000 })
+ mockInvoke.mockResolvedValue({ pid: 1, model_id: 'big' })
+ mockUnload.mockResolvedValue({ success: true })
+ await ext.unload('big')
+ expect((await ext.getModelProps('big')).nCtx).toBe(8192)
+ })
+})
+
describe('getModelContextLimit', () => {
it('uses the text model limit from a multimodal config', async () => {
const ext = new mlx_extension()
diff --git a/extensions/mlx-extension/src/index.ts b/extensions/mlx-extension/src/index.ts
index 682cc570d..f37f7536e 100644
--- a/extensions/mlx-extension/src/index.ts
+++ b/extensions/mlx-extension/src/index.ts
@@ -64,6 +64,10 @@ export default class mlx_extension extends AIEngine {
private providerPath!: string
private apiSecret: string = 'JanMLX'
private loadingModels = new Map<string, Promise<SessionInfo>>()
+ // Context window each loaded model's server was launched with. The window
+ // is chosen per model at load time, so the engine-wide `config.ctx_size`
+ // only describes models loaded without an override.
+ private loadedCtxSize = new Map<string, number>()
override async onLoad(): Promise<void> {
super.onLoad()
@@ -342,6 +346,7 @@ export default class mlx_extension extends AIEngine {
isEmbedding,
Number(this.timeout)
)
+ this.loadedCtxSize.set(modelId, mlxConfig.ctx_size)
return sInfo
} catch (error) {
logger.error(`Error loading MLX model: ${JSON.stringify(error)}`)
@@ -358,6 +363,7 @@ export default class mlx_extension extends AIEngine {
try {
const result = await unloadMlxModel(sInfo.pid)
if (result.success) {
+ this.loadedCtxSize.delete(modelId)
logger.info(`Successfully unloaded MLX model with PID ${sInfo.pid}`)
} else {
logger.warn(`Failed to unload MLX model: ${result.error}`)
@@ -856,12 +862,16 @@ export default class mlx_extension extends AIEngine {
}
}
- // The MLX server is launched with a fixed context window (cfg.ctx_size),
- // so the token counter can show a real percentage instead of a bare count.
+ // The MLX server is launched with a fixed context window, so the token
+ // counter can show a real percentage instead of a bare count. Report the
+ // window this model was loaded with; fall back to the engine default.
async getModelProps(
modelId: string
): Promise<{ nCtx: number; modelAlias?: string }> {
- return { nCtx: this.config.ctx_size ?? 4096, modelAlias: modelId }
+ return {
+ nCtx: this.loadedCtxSize.get(modelId) ?? this.config.ctx_size ?? 4096,
+ modelAlias: modelId,
+ }
}
async isVisionSupported(modelPath: string): Promise<boolean> {