Skip to content

Commit 1f3b811

Browse files
Add function to reset LLM instance
1 parent 74d63d5 commit 1f3b811

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

app/src/main/java/org/vonderheidt/hips/ui/screens/HomeScreen.kt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ import kotlinx.coroutines.launch
5757
import org.vonderheidt.hips.navigation.Screen
5858
import org.vonderheidt.hips.ui.theme.HiPSTheme
5959
import org.vonderheidt.hips.utils.LLM
60+
import org.vonderheidt.hips.utils.LlamaCpp
6061
import org.vonderheidt.hips.utils.Steganography
6162

6263
/**
@@ -254,6 +255,11 @@ fun HomeScreen(navController: NavController, modifier: Modifier) {
254255
// Use Dispatchers.Default since LLM inference is CPU-bound
255256
// Keep encapsulation of coroutine vs if-else like this so the loading animation works
256257
CoroutineScope(Dispatchers.Default).launch {
258+
// Reset LLM instance on every button press to ensure reproducibility, otherwise ctx before encode and decode would not be the same
259+
// Works when called before this coroutine or inside it, but crashes when called inside its own coroutine before this one
260+
// Might be desirable to use it with Dispatchers.IO as it is presumably I/O-bound, but seems negligible
261+
LlamaCpp.resetInstance()
262+
257263
if (selectedMode == 0) {
258264
coverText = Steganography.encode(context, secretMessage)
259265
}

app/src/main/java/org/vonderheidt/hips/utils/LlamaCpp.kt

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,27 @@ object LlamaCpp {
7474
}
7575
}
7676

77+
/**
78+
* Function to reset the instance of the LLM in a thread-safe manner.
79+
*
80+
* Needed to ensure reproducible results when switching between encode/decode mode or when encoding/decoding multiple times sequentially.
81+
*/
82+
fun resetInstance() {
83+
// Mirrors startInstance
84+
if (ctx == 0L) {
85+
return
86+
}
87+
88+
synchronized(this) {
89+
if (ctx != 0L) {
90+
unloadCtx()
91+
ctx = 0L
92+
93+
ctx = loadCtx()
94+
}
95+
}
96+
}
97+
7798
/**
7899
* Function to check if a token is the end of a sentence. Needed to complete the last sentence of the cover text.
79100
*

0 commit comments

Comments
 (0)