Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Objectify the llm model and context

Manav Rathid23bc9ac7d1c
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/RustLlmProvider.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/RustLlmProvider.kt
index a608bef146..8a7a91ef6c 100644
--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/RustLlmProvider.kt
+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/RustLlmProvider.kt
@@ -12,7 +12,7 @@ import io.ente.ensu.llm.GenerationSummary
import io.ente.ensu.llm.LlmMessage
import io.ente.ensu.llm.LlmModelTarget
import io.ente.ensu.format.formatBytes
-import io.ente.ensu.bindings.LlmContextHandle
+import io.ente.ensu.bindings.LlmContext
import io.ente.ensu.bindings.LlmContextParams
import io.ente.ensu.bindings.LlmException
import io.ente.ensu.bindings.LlmChatRequest
@@ -21,15 +21,11 @@ import io.ente.ensu.bindings.LlmGenerationEventCallback
import io.ente.ensu.bindings.LlmModelDownloadCallback
import io.ente.ensu.bindings.LlmModelDownloadProgress
import io.ente.ensu.bindings.LlmModelDownloadTarget
-import io.ente.ensu.bindings.LlmModelHandle
+import io.ente.ensu.bindings.LlmModel
import io.ente.ensu.bindings.LlmModelLoadParams
import io.ente.ensu.bindings.llmCancel
-import io.ente.ensu.bindings.llmCreateContext
import io.ente.ensu.bindings.llmDownloadModelFiles
-import io.ente.ensu.bindings.llmGenerateChatStream
import io.ente.ensu.bindings.llmInitBackend
-import io.ente.ensu.bindings.llmLoadModel
-import io.ente.ensu.bindings.llmPrewarmMultimodalContext
import io.ente.ensu.bindings.uniffiEnsureInitialized
import io.ente.ensu.bindings.Transcriber
import io.ente.ensu.bindings.LlmChatMessage as NativeChatMessage
@@ -89,8 +85,8 @@ class RustLlmProvider(
appContext.getSharedPreferences("ensu.system.downloads", Context.MODE_PRIVATE)
private val json = Json { ignoreUnknownKeys = true }
- @Volatile private var modelHandle: LlmModelHandle? = null
- @Volatile private var contextHandle: LlmContextHandle? = null
+ @Volatile private var loadedModel: LlmModel? = null
+ @Volatile private var loadedContext: LlmContext? = null
@Volatile private var currentModelKey: LoadedModelKey? = null
@Volatile private var currentContextLength: Int? = null
@Volatile private var currentJobId: Long? = null
@@ -126,7 +122,7 @@ class RustLlmProvider(
onToken: (String) -> Unit
): GenerationSummary = withContext(ioDispatcher) {
deviceCapabilityProvider.chatCapability().requireChatSupported()
- val context = contextHandle ?: throw IllegalStateException("Model context not loaded")
+ val context = loadedContext ?: throw IllegalStateException("Model context not loaded")
currentJobId = null
val mmprojPath = if (imageFiles.isEmpty()) {
null
@@ -171,9 +167,9 @@ class RustLlmProvider(
?.absolutePath
?: return@withLock
ensureModelReadyLocked(target) { }
- val context = contextHandle ?: return@withLock
+ val context = loadedContext ?: return@withLock
unloadTranscriptionModelIfLoaded()
- llmPrewarmMultimodalContext(context, mmprojPath, null)
+ context.prewarmMultimodal(mmprojPath, null)
}
}.onFailure { error ->
Log.d("RustLlmProvider", "Image inference prewarm skipped", error)
@@ -302,7 +298,7 @@ class RustLlmProvider(
fun loadedContextLength(target: LlmModelTarget): Int? {
val modelKey = LoadedModelKey(target.id, target.contextLength)
- return if (currentModelKey == modelKey && contextHandle != null && modelHandle != null) {
+ return if (currentModelKey == modelKey && loadedContext != null && loadedModel != null) {
currentContextLength
} else {
null
@@ -319,14 +315,14 @@ class RustLlmProvider(
}
fun resetContext() {
- val model = modelHandle ?: return
+ val model = loadedModel ?: return
val contextParams = LlmContextParams(
contextSize = currentContextLength,
nThreads = null,
nBatch = null
)
- contextHandle?.destroy()
- contextHandle = llmCreateContext(model, contextParams)
+ loadedContext?.destroy()
+ loadedContext = model.newContext(contextParams)
}
fun cancelDownload() {
@@ -347,10 +343,10 @@ class RustLlmProvider(
}
private fun unloadModel() {
- contextHandle?.destroy()
- contextHandle = null
- modelHandle?.destroy()
- modelHandle = null
+ loadedContext?.destroy()
+ loadedContext = null
+ loadedModel?.destroy()
+ loadedModel = null
currentModelKey = null
currentContextLength = null
}
@@ -374,7 +370,7 @@ class RustLlmProvider(
backendInitialized = true
}
- if (currentModelKey == modelKey && contextHandle != null && modelHandle != null) {
+ if (currentModelKey == modelKey && loadedContext != null && loadedModel != null) {
return
}
@@ -404,8 +400,8 @@ class RustLlmProvider(
useMlock = false
)
- val model = llmLoadModel(modelParams)
- modelHandle = model
+ val model = LlmModel.load(modelParams)
+ loadedModel = model
var lastError: Throwable? = null
for (ctx in contexts) {
@@ -415,7 +411,7 @@ class RustLlmProvider(
nThreads = threads,
nBatch = batch
)
- contextHandle = llmCreateContext(model, contextParams)
+ loadedContext = model.newContext(contextParams)
currentModelKey = LoadedModelKey(target.id, target.contextLength)
currentContextLength = ctx
return
@@ -784,7 +780,7 @@ class RustLlmProvider(
}
private fun generateStreamWithCallback(
- context: LlmContextHandle,
+ context: LlmContext,
request: LlmChatRequest,
onToken: (String) -> Unit
): NativeSummary {
@@ -810,7 +806,7 @@ class RustLlmProvider(
}
}
- val summary = llmGenerateChatStream(context, request, callback)
+ val summary = context.generateChatStream(request, callback)
error?.let { throw it }
return summary
diff --git a/mobile/native/apple/apps/ensu/Ensu/Services/InferenceRsProvider.swift b/mobile/native/apple/apps/ensu/Ensu/Services/InferenceRsProvider.swift
index 44a224e9cc..fd08f8e1c6 100644
--- a/mobile/native/apple/apps/ensu/Ensu/Services/InferenceRsProvider.swift
+++ b/mobile/native/apple/apps/ensu/Ensu/Services/InferenceRsProvider.swift
@@ -91,8 +91,8 @@ final class InferenceRsProvider {
private let modelDir: URL
private let transcriber: Transcriber
private let downloadManager = ModelDownloadManager.shared
- private var modelHandle: LlmModelHandle?
- private var contextHandle: LlmContextHandle?
+ private var loadedModel: LlmModel?
+ private var loadedContext: LlmContext?
private var currentModelKey: LoadedModelKey?
private var currentContextLength: Int?
private var backendInitialized = false
@@ -127,7 +127,7 @@ final class InferenceRsProvider {
throw UnsupportedDeviceMemoryError(capability: capability)
}
let modelKey = LoadedModelKey(id: target.id, requestedContextLength: target.contextLength)
- if currentModelKey == modelKey, modelHandle != nil, contextHandle != nil {
+ if currentModelKey == modelKey, loadedModel != nil, loadedContext != nil {
return
}
@@ -182,7 +182,7 @@ final class InferenceRsProvider {
onProgress(InferenceDownloadProgress(percent: 100, status: "Loading model..."))
do {
- try loadModelHandle(target: target, modelPath: modelPath)
+ try loadModel(target: target, modelPath: modelPath)
} catch {
if allowRecovery, downloads.isEmpty,
recoverFromCachedModelLoadFailure(modelPath: modelPath, mmprojPath: mmprojPath) {
@@ -207,7 +207,7 @@ final class InferenceRsProvider {
if !capability.isChatSupported {
throw UnsupportedDeviceMemoryError(capability: capability)
}
- guard let context = contextHandle else {
+ guard let context = loadedContext else {
throw NSError(domain: "InferenceRsProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "Model not loaded"])
}
currentJobId = nil
@@ -260,7 +260,7 @@ final class InferenceRsProvider {
Task.detached {
do {
self.unloadTranscriptionModelIfLoaded()
- let summary = try llmGenerateChatStream(context: context, request: request, callback: sink)
+ let summary = try context.generateChatStream(request: request, callback: sink)
lock.lock()
let localError = error
lock.unlock()
@@ -304,16 +304,15 @@ final class InferenceRsProvider {
}
try await self.ensureModelReadyLocked(target: target, onProgress: { _ in }, allowRecovery: true)
- guard let context = self.contextHandle else {
+ guard let context = self.loadedContext else {
return
}
self.unloadTranscriptionModelIfLoaded()
- try llmPrewarmMultimodalContext(
- context: context,
+ try context.prewarmMultimodal(
mmprojPath: mmprojPath.path,
mediaMarker: nil
- )
+ )
}
}.value
} catch {
@@ -322,10 +321,10 @@ final class InferenceRsProvider {
}
func resetContext() {
- guard let model = modelHandle else { return }
+ guard let model = loadedModel else { return }
let contextParams = LlmContextParams(contextSize: currentContextLength.map(Int32.init), nThreads: nil, nBatch: nil)
- contextHandle = nil
- contextHandle = try? llmCreateContext(model: model, params: contextParams)
+ loadedContext = nil
+ loadedContext = try? model.newContext(params: contextParams)
}
func cancelDownload() {
@@ -390,15 +389,15 @@ final class InferenceRsProvider {
func loadedContextLength(target: InferenceModelTarget) -> Int? {
let modelKey = LoadedModelKey(id: target.id, requestedContextLength: target.contextLength)
- guard currentModelKey == modelKey, modelHandle != nil, contextHandle != nil else {
+ guard currentModelKey == modelKey, loadedModel != nil, loadedContext != nil else {
return nil
}
return currentContextLength
}
private func unloadModel() {
- contextHandle = nil
- modelHandle = nil
+ loadedContext = nil
+ loadedModel = nil
currentModelKey = nil
currentContextLength = nil
}
@@ -407,10 +406,10 @@ final class InferenceRsProvider {
transcriber.unloadModel()
}
- private func loadModelHandle(target: InferenceModelTarget, modelPath: URL) throws {
+ private func loadModel(target: InferenceModelTarget, modelPath: URL) throws {
let params = LlmModelLoadParams(modelPath: modelPath.path, nGpuLayers: 0, useMmap: true, useMlock: false)
- let model = try llmLoadModel(params: params)
- modelHandle = model
+ let model = try LlmModel.load(params: params)
+ loadedModel = model
let desiredContext = target.contextLength ?? 12000
let candidates = [desiredContext, 12000, 8192, 4096, 2048, 1024]
@@ -421,7 +420,7 @@ final class InferenceRsProvider {
for contextSize in candidates {
do {
let contextParams = LlmContextParams(contextSize: Int32(contextSize), nThreads: Int32(threadCount), nBatch: Int32(512))
- contextHandle = try llmCreateContext(model: model, params: contextParams)
+ loadedContext = try model.newContext(params: contextParams)
currentModelKey = LoadedModelKey(id: target.id, requestedContextLength: target.contextLength)
currentContextLength = contextSize
return
diff --git a/mobile/native/apple/apps/ensu/EnsuTests/InferenceIntegrationTests.swift b/mobile/native/apple/apps/ensu/EnsuTests/InferenceIntegrationTests.swift
index 7f6a1e3d3e..41f2873784 100644
--- a/mobile/native/apple/apps/ensu/EnsuTests/InferenceIntegrationTests.swift
+++ b/mobile/native/apple/apps/ensu/EnsuTests/InferenceIntegrationTests.swift
@@ -40,7 +40,7 @@ final class InferenceIntegrationTests: XCTestCase {
try llmInitBackend()
- let model = try llmLoadModel(
+ let model = try LlmModel.load(
params: LlmModelLoadParams(
modelPath: modelPath,
nGpuLayers: nil,
@@ -49,8 +49,7 @@ final class InferenceIntegrationTests: XCTestCase {
)
)
- let context = try llmCreateContext(
- model: model,
+ let context = try model.newContext(
params: LlmContextParams(contextSize: 2048, nThreads: nil, nBatch: nil)
)
@@ -77,7 +76,7 @@ final class InferenceIntegrationTests: XCTestCase {
)
let collector = GenerateEventCollector()
- let summary = try llmGenerateChatStream(context: context, request: request, callback: collector)
+ let summary = try context.generateChatStream(request: request, callback: collector)
XCTAssertGreaterThan(summary.jobId, 0)
XCTAssertTrue(collector.hasDone)
@@ -92,7 +91,7 @@ final class InferenceIntegrationTests: XCTestCase {
try llmInitBackend()
- let model = try llmLoadModel(
+ let model = try LlmModel.load(
params: LlmModelLoadParams(
modelPath: modelPath,
nGpuLayers: nil,
@@ -101,8 +100,7 @@ final class InferenceIntegrationTests: XCTestCase {
)
)
- let context = try llmCreateContext(
- model: model,
+ let context = try model.newContext(
params: LlmContextParams(contextSize: 2048, nThreads: nil, nBatch: nil)
)
@@ -129,7 +127,7 @@ final class InferenceIntegrationTests: XCTestCase {
)
let collector = GenerateEventCollector()
- let summary = try llmGenerateChatStream(context: context, request: request, callback: collector)
+ let summary = try context.generateChatStream(request: request, callback: collector)
XCTAssertGreaterThan(summary.jobId, 0)
XCTAssertTrue(collector.hasDone)
diff --git a/rust/apps/ensu/src-tauri/src/commands/llm.rs b/rust/apps/ensu/src-tauri/src/commands/llm.rs
index ca88d7a194..d43c78b277 100644
--- a/rust/apps/ensu/src-tauri/src/commands/llm.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/llm.rs
@@ -14,8 +14,8 @@ use crate::logging;
#[derive(Default)]
pub struct State {
- model: Mutex<Option<llm::ModelHandleRef>>,
- context: Mutex<Option<llm::ContextHandleRef>>,
+ model: Mutex<Option<llm::ModelRef>>,
+ context: Mutex<Option<llm::ContextRef>>,
}
pub struct ModelDownloadState {
@@ -66,8 +66,8 @@ fn fs_thread_error() -> ApiError {
pub(crate) fn replace_state(
state: &State,
- model: Option<llm::ModelHandleRef>,
- context: Option<llm::ContextHandleRef>,
+ model: Option<llm::ModelRef>,
+ context: Option<llm::ContextRef>,
) -> Result<(), ApiError> {
let mut model_guard = state
.model
@@ -383,7 +383,7 @@ pub async fn llm_load_model(
format!("load model requested model_path={}", params.model_path),
);
let model = async_runtime::spawn_blocking(move || {
- match catch_unwind(AssertUnwindSafe(|| llm::load_model(params))) {
+ match catch_unwind(AssertUnwindSafe(|| llm::Model::load(params))) {
Ok(result) => result.map_err(llm_error),
Err(payload) => {
let message = panic_message(payload);
@@ -431,7 +431,7 @@ pub async fn llm_create_context(
);
let context = async_runtime::spawn_blocking(move || {
- match catch_unwind(AssertUnwindSafe(|| llm::create_context(model, params))) {
+ match catch_unwind(AssertUnwindSafe(|| llm::Context::new(&model, params))) {
Ok(result) => result.map_err(llm_error),
Err(payload) => {
let message = panic_message(payload);
@@ -493,7 +493,7 @@ pub async fn llm_prewarm_multimodal_context(
);
async_runtime::spawn_blocking(move || {
match catch_unwind(AssertUnwindSafe(|| {
- llm::prewarm_multimodal_context(context.as_ref(), mmproj_path, media_marker)
+ context.prewarm_multimodal(mmproj_path, media_marker)
})) {
Ok(result) => result.map_err(llm_error),
Err(payload) => {
@@ -531,7 +531,7 @@ pub fn llm_generate_chat_stream(
async_runtime::spawn_blocking(move || {
match catch_unwind(AssertUnwindSafe(|| {
let mut sink = EventSink::new(window.clone());
- let _ = llm::generate_chat_stream(context.as_ref(), request, &mut sink);
+ let _ = context.generate_chat_stream(request, &mut sink);
})) {
Ok(()) => {}
Err(payload) => {
diff --git a/rust/bindings/uniffi/ensu/src/llm.rs b/rust/bindings/uniffi/ensu/src/llm.rs
index 48192d7f63..cced8c864a 100644
--- a/rust/bindings/uniffi/ensu/src/llm.rs
+++ b/rust/bindings/uniffi/ensu/src/llm.rs
@@ -106,13 +106,52 @@ pub enum LlmGenerationEvent {
}
#[derive(uniffi::Object)]
-pub struct LlmModelHandle {
- handle: core::ModelHandleRef,
+pub struct LlmModel {
+ handle: core::ModelRef,
+}
+
+#[uniffi::export]
+impl LlmModel {
+ #[uniffi::constructor]
+ pub fn load(params: LlmModelLoadParams) -> Result<Arc<Self>, LlmError> {
+ let handle = core::Model::load(params.into()).map_err(LlmError::from)?;
+ Ok(Arc::new(Self { handle }))
+ }
+
+ pub fn new_context(&self, params: LlmContextParams) -> Result<Arc<LlmContext>, LlmError> {
+ let handle = core::Context::new(&self.handle, params.into()).map_err(LlmError::from)?;
+ Ok(Arc::new(LlmContext { handle }))
+ }
}
#[derive(uniffi::Object)]
-pub struct LlmContextHandle {
- handle: core::ContextHandleRef,
+pub struct LlmContext {
+ handle: core::ContextRef,
+}
+
+#[uniffi::export]
+impl LlmContext {
+ pub fn generate_chat_stream(
+ &self,
+ request: LlmChatRequest,
+ callback: Box<dyn LlmGenerationEventCallback>,
+ ) -> Result<LlmGenerationSummary, LlmError> {
+ let mut sink = CallbackSink { callback };
+ self.handle
+ .generate_chat_stream(request.into(), &mut sink)
+ .map(Into::into)
+ .map_err(LlmError::from)
+ }
+
+ pub fn prewarm_multimodal(
+ &self,
+ mmproj_path: String,
+ media_marker: Option<String>,
+ ) -> Result<(), LlmError> {
+ self.handle
+ .prewarm_multimodal(mmproj_path, media_marker)
+ .map_err(LlmError::from)
+ }
}
#[uniffi::export(callback_interface)]
@@ -264,22 +303,6 @@ pub fn llm_init_backend() -> Result<(), LlmError> {
core::init_backend().map_err(LlmError::from)
}
-#[uniffi::export]
-pub fn llm_load_model(params: LlmModelLoadParams) -> Result<Arc<LlmModelHandle>, LlmError> {
- let model = core::load_model(params.into()).map_err(LlmError::from)?;
- Ok(Arc::new(LlmModelHandle { handle: model }))
-}
-
-#[uniffi::export]
-pub fn llm_create_context(
- model: Arc<LlmModelHandle>,
- params: LlmContextParams,
-) -> Result<Arc<LlmContextHandle>, LlmError> {
- let context =
- core::create_context(model.handle.clone(), params.into()).map_err(LlmError::from)?;
- Ok(Arc::new(LlmContextHandle { handle: context }))
-}
-
#[uniffi::export]
pub fn llm_download_model_files(
targets: Vec<LlmModelDownloadTarget>,
@@ -297,28 +320,6 @@ pub fn llm_download_model_files(
.map_err(LlmError::from)
}
-#[uniffi::export]
-pub fn llm_prewarm_multimodal_context(
- context: Arc<LlmContextHandle>,
- mmproj_path: String,
- media_marker: Option<String>,
-) -> Result<(), LlmError> {
- core::prewarm_multimodal_context(context.handle.as_ref(), mmproj_path, media_marker)
- .map_err(LlmError::from)
-}
-
-#[uniffi::export]
-pub fn llm_generate_chat_stream(
- context: Arc<LlmContextHandle>,
- request: LlmChatRequest,
- callback: Box<dyn LlmGenerationEventCallback>,
-) -> Result<LlmGenerationSummary, LlmError> {
- let mut sink = CallbackSink { callback };
- core::generate_chat_stream(context.handle.as_ref(), request.into(), &mut sink)
- .map(Into::into)
- .map_err(LlmError::from)
-}
-
#[uniffi::export]
pub fn llm_cancel(job_id: i64) {
let _ = core::cancel(job_id);
diff --git a/rust/crates/ensu/src/llm/context.rs b/rust/crates/ensu/src/llm/context.rs
index d4186d6ce0..5b732fd284 100644
--- a/rust/crates/ensu/src/llm/context.rs
+++ b/rust/crates/ensu/src/llm/context.rs
@@ -10,7 +10,7 @@ use std::num::NonZeroU32;
use std::path::Path;
use std::sync::Arc;
-use super::model::ModelHandleRef;
+use super::model::ModelRef;
use super::{backend, format_error};
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -21,8 +21,8 @@ pub struct ContextParams {
}
self_cell!(
- struct ContextHandleCell {
- owner: ModelHandleRef,
+ struct ContextCell {
+ owner: ModelRef,
#[covariant]
dependent: LlamaContext,
@@ -43,22 +43,22 @@ struct CachedMtmdContext {
context: Arc<MtmdContext>,
}
-pub struct ContextHandle {
- cell: Mutex<ContextHandleCell>,
+pub struct Context {
+ cell: Mutex<ContextCell>,
mtmd_context: Mutex<Option<CachedMtmdContext>>,
}
-pub type ContextHandleRef = Arc<ContextHandle>;
+pub type ContextRef = Arc<Context>;
-unsafe impl Send for ContextHandle {}
-unsafe impl Sync for ContextHandle {}
+unsafe impl Send for Context {}
+unsafe impl Sync for Context {}
-impl ContextHandle {
+impl Context {
fn try_new(
- owner: ModelHandleRef,
- builder: impl for<'a> FnOnce(&'a ModelHandleRef) -> Result<LlamaContext<'a>, String>,
+ owner: ModelRef,
+ builder: impl for<'a> FnOnce(&'a ModelRef) -> Result<LlamaContext<'a>, String>,
) -> Result<Self, String> {
- ContextHandleCell::try_new(owner, builder).map(|cell| ContextHandle {
+ ContextCell::try_new(owner, builder).map(|cell| Context {
cell: Mutex::new(cell),
mtmd_context: Mutex::new(None),
})
@@ -135,54 +135,52 @@ fn mtmd_cache_key_and_params(
Ok((key, params))
}
-pub fn create_context(
- model: ModelHandleRef,
- params: ContextParams,
-) -> Result<ContextHandleRef, String> {
- let mut context_params = LlamaContextParams::default();
-
- if let Some(context_size) = params.context_size {
- let context_size =
- u32::try_from(context_size).map_err(|_| "context_size must be > 0".to_string())?;
- let context_size =
- NonZeroU32::new(context_size).ok_or_else(|| "context_size must be > 0".to_string())?;
- context_params = context_params.with_n_ctx(Some(context_size));
- }
+impl Context {
+ pub fn new(model: &ModelRef, params: ContextParams) -> Result<ContextRef, String> {
+ let mut context_params = LlamaContextParams::default();
- if let Some(n_threads) = params.n_threads {
- if n_threads <= 0 {
- return Err("n_threads must be > 0".to_string());
+ if let Some(context_size) = params.context_size {
+ let context_size =
+ u32::try_from(context_size).map_err(|_| "context_size must be > 0".to_string())?;
+ let context_size = NonZeroU32::new(context_size)
+ .ok_or_else(|| "context_size must be > 0".to_string())?;
+ context_params = context_params.with_n_ctx(Some(context_size));
}
- context_params = context_params
- .with_n_threads(n_threads)
- .with_n_threads_batch(n_threads);
- }
- if let Some(n_batch) = params.n_batch {
- let n_batch = u32::try_from(n_batch).map_err(|_| "n_batch must be > 0".to_string())?;
- context_params = context_params.with_n_batch(n_batch);
- }
+ if let Some(n_threads) = params.n_threads {
+ if n_threads <= 0 {
+ return Err("n_threads must be > 0".to_string());
+ }
+ context_params = context_params
+ .with_n_threads(n_threads)
+ .with_n_threads_batch(n_threads);
+ }
- let context = ContextHandle::try_new(model, |model| {
- let backend = backend()?;
- model
- .model()
- .new_context(backend, context_params)
- .map_err(|err| format_error("Failed to create context", err))
- })?;
+ if let Some(n_batch) = params.n_batch {
+ let n_batch = u32::try_from(n_batch).map_err(|_| "n_batch must be > 0".to_string())?;
+ context_params = context_params.with_n_batch(n_batch);
+ }
- Ok(Arc::new(context))
-}
+ let context = Context::try_new(Arc::clone(model), |model| {
+ let backend = backend()?;
+ model
+ .model()
+ .new_context(backend, context_params)
+ .map_err(|err| format_error("Failed to create context", err))
+ })?;
-pub fn prewarm_multimodal_context(
- context: &ContextHandle,
- mmproj_path: String,
- media_marker: Option<String>,
-) -> Result<(), String> {
- let marker = media_marker.unwrap_or_else(|| mtmd_default_marker().to_string());
- context.with_context_mut(|ctx| {
- context
- .cached_mtmd_context(ctx.model, &mmproj_path, &marker)
- .map(|_| ())
- })
+ Ok(Arc::new(context))
+ }
+
+ pub fn prewarm_multimodal(
+ &self,
+ mmproj_path: String,
+ media_marker: Option<String>,
+ ) -> Result<(), String> {
+ let marker = media_marker.unwrap_or_else(|| mtmd_default_marker().to_string());
+ self.with_context_mut(|ctx| {
+ self.cached_mtmd_context(ctx.model, &mmproj_path, &marker)
+ .map(|_| ())
+ })
+ }
}
diff --git a/rust/crates/ensu/src/llm/generate.rs b/rust/crates/ensu/src/llm/generate.rs
index a73f5d9ecd..995f7f1364 100644
--- a/rust/crates/ensu/src/llm/generate.rs
+++ b/rust/crates/ensu/src/llm/generate.rs
@@ -15,7 +15,7 @@ use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::Instant;
-use super::context::ContextHandle;
+use super::context::Context;
use super::event::{EventSink, GenerationEvent, GenerationSummary, JobId};
use super::format_error;
@@ -447,8 +447,18 @@ fn build_sampler(model: &LlamaModel, request: &SamplingParams) -> Result<LlamaSa
Ok(LlamaSampler::chain_simple(samplers))
}
-pub fn generate_chat_stream(
- context: &ContextHandle,
+impl Context {
+ pub fn generate_chat_stream(
+ &self,
+ request: ChatRequest,
+ sink: &mut dyn EventSink,
+ ) -> Result<GenerationSummary, String> {
+ generate_chat_stream(self, request, sink)
+ }
+}
+
+fn generate_chat_stream(
+ context: &Context,
request: ChatRequest,
sink: &mut dyn EventSink,
) -> Result<GenerationSummary, String> {
diff --git a/rust/crates/ensu/src/llm/model.rs b/rust/crates/ensu/src/llm/model.rs
index 44c54c824b..5b30975e3a 100644
--- a/rust/crates/ensu/src/llm/model.rs
+++ b/rust/crates/ensu/src/llm/model.rs
@@ -13,38 +13,39 @@ pub struct ModelLoadParams {
pub use_mlock: Option<bool>,
}
-pub struct ModelHandle {
+pub struct Model {
model: LlamaModel,
}
-pub type ModelHandleRef = Arc<ModelHandle>;
+pub type ModelRef = Arc<Model>;
-impl ModelHandle {
- pub(super) fn model(&self) -> &LlamaModel {
- &self.model
- }
-}
+impl Model {
+ pub fn load(params: ModelLoadParams) -> Result<ModelRef, String> {
+ let backend = backend()?;
+ let mut model_params = llama_cpp_2::model::params::LlamaModelParams::default();
-pub fn init_backend() -> Result<(), String> {
- backend().map(|_| ())
-}
+ if let Some(n_gpu_layers) = params.n_gpu_layers {
+ let layers =
+ u32::try_from(n_gpu_layers).map_err(|_| "n_gpu_layers must be >= 0".to_string())?;
+ model_params = model_params.with_n_gpu_layers(layers);
+ }
-pub fn load_model(params: ModelLoadParams) -> Result<ModelHandleRef, String> {
- let backend = backend()?;
- let mut model_params = llama_cpp_2::model::params::LlamaModelParams::default();
+ if let Some(use_mlock) = params.use_mlock {
+ model_params = model_params.with_use_mlock(use_mlock);
+ }
- if let Some(n_gpu_layers) = params.n_gpu_layers {
- let layers =
- u32::try_from(n_gpu_layers).map_err(|_| "n_gpu_layers must be >= 0".to_string())?;
- model_params = model_params.with_n_gpu_layers(layers);
- }
+ let model =
+ LlamaModel::load_from_file(backend, Path::new(&params.model_path), &model_params)
+ .map_err(|err| format_error("Failed to load model", err))?;
- if let Some(use_mlock) = params.use_mlock {
- model_params = model_params.with_use_mlock(use_mlock);
+ Ok(Arc::new(Model { model }))
}
- let model = LlamaModel::load_from_file(backend, Path::new(&params.model_path), &model_params)
- .map_err(|err| format_error("Failed to load model", err))?;
+ pub(super) fn model(&self) -> &LlamaModel {
+ &self.model
+ }
+}
- Ok(Arc::new(ModelHandle { model }))
+pub fn init_backend() -> Result<(), String> {
+ backend().map(|_| ())
}