MainViewModel.kt 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package com.example.llama
  2. import android.llama.cpp.LLamaAndroid
  3. import android.util.Log
  4. import androidx.compose.runtime.getValue
  5. import androidx.compose.runtime.mutableStateOf
  6. import androidx.compose.runtime.setValue
  7. import androidx.lifecycle.ViewModel
  8. import androidx.lifecycle.viewModelScope
  9. import kotlinx.coroutines.flow.catch
  10. import kotlinx.coroutines.launch
  11. class MainViewModel(private val llamaAndroid: LLamaAndroid = LLamaAndroid.instance()): ViewModel() {
  12. companion object {
  13. @JvmStatic
  14. private val NanosPerSecond = 1_000_000_000.0
  15. }
  16. private val tag: String? = this::class.simpleName
  17. var messages by mutableStateOf(listOf("Initializing..."))
  18. private set
  19. var message by mutableStateOf("")
  20. private set
  21. override fun onCleared() {
  22. super.onCleared()
  23. viewModelScope.launch {
  24. try {
  25. llamaAndroid.unload()
  26. } catch (exc: IllegalStateException) {
  27. messages += exc.message!!
  28. }
  29. }
  30. }
  31. fun send() {
  32. val text = message
  33. message = ""
  34. // Add to messages console.
  35. messages += text
  36. messages += ""
  37. viewModelScope.launch {
  38. llamaAndroid.send(text)
  39. .catch {
  40. Log.e(tag, "send() failed", it)
  41. messages += it.message!!
  42. }
  43. .collect { messages = messages.dropLast(1) + (messages.last() + it) }
  44. }
  45. }
  46. fun bench(pp: Int, tg: Int, pl: Int, nr: Int = 1) {
  47. viewModelScope.launch {
  48. try {
  49. val start = System.nanoTime()
  50. val warmupResult = llamaAndroid.bench(pp, tg, pl, nr)
  51. val end = System.nanoTime()
  52. messages += warmupResult
  53. val warmup = (end - start).toDouble() / NanosPerSecond
  54. messages += "Warm up time: $warmup seconds, please wait..."
  55. if (warmup > 5.0) {
  56. messages += "Warm up took too long, aborting benchmark"
  57. return@launch
  58. }
  59. messages += llamaAndroid.bench(512, 128, 1, 3)
  60. } catch (exc: IllegalStateException) {
  61. Log.e(tag, "bench() failed", exc)
  62. messages += exc.message!!
  63. }
  64. }
  65. }
  66. fun load(pathToModel: String) {
  67. viewModelScope.launch {
  68. try {
  69. llamaAndroid.load(pathToModel)
  70. messages += "Loaded $pathToModel"
  71. } catch (exc: IllegalStateException) {
  72. Log.e(tag, "load() failed", exc)
  73. messages += exc.message!!
  74. }
  75. }
  76. }
  77. fun updateMessage(newMessage: String) {
  78. message = newMessage
  79. }
  80. fun clear() {
  81. messages = listOf()
  82. }
  83. fun log(message: String) {
  84. messages += message
  85. }
  86. }