108 public static string LlamaLibReleaseURL = $
"https://github.com/undreamai/LlamaLib/releases/download/{LlamaLibVersion}";
114 public static string LlamaLibURL = $
"{LlamaLibReleaseURL}/{libraryName}.zip";
118 public static string LLMUnityStore = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"LLMUnity");
125 [HideInInspector]
public static readonly Dictionary<string, (string, string, string)[]>
modelOptions =
new Dictionary<
string, (
string,
string,
string)[]>()
127 {
"Medium models",
new(string, string, string)[]
129 (
"Llama 3.1 8B",
"https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf?download=true",
"https://huggingface.co/meta-llama/Meta-Llama-3.1-8B/blob/main/LICENSE"),
130 (
"Mistral 7B Instruct v0.2",
"https://huggingface.co/TheBloke/Mistral-7B-Instruct-v0.2-GGUF/resolve/main/mistral-7b-instruct-v0.2.Q4_K_M.gguf?download=true",
null),
131 (
"Gemma 2 9B it",
"https://huggingface.co/bartowski/gemma-2-9b-it-GGUF/resolve/main/gemma-2-9b-it-Q4_K_M.gguf?download=true",
"https://ai.google.dev/gemma/terms"),
132 (
"OpenHermes 2.5 7B",
"https://huggingface.co/TheBloke/OpenHermes-2.5-Mistral-7B-GGUF/resolve/main/openhermes-2.5-mistral-7b.Q4_K_M.gguf?download=true",
null),
134 {
"Small models",
new(string, string, string)[]
136 (
"Llama 3.2 3B",
"https://huggingface.co/hugging-quants/Llama-3.2-3B-Instruct-Q4_K_M-GGUF/resolve/main/llama-3.2-3b-instruct-q4_k_m.gguf",
null),
137 (
"Phi 3.5 4B",
"https://huggingface.co/bartowski/Phi-3.5-mini-instruct-GGUF/resolve/main/Phi-3.5-mini-instruct-Q4_K_M.gguf",
null),
139 {
"Tiny models",
new(string, string, string)[]
141 (
"Llama 3.2 1B",
"https://huggingface.co/hugging-quants/Llama-3.2-1B-Instruct-Q4_K_M-GGUF/resolve/main/llama-3.2-1b-instruct-q4_k_m.gguf",
null),
142 (
"Qwen 2 0.5B",
"https://huggingface.co/Qwen/Qwen2-0.5B-Instruct-GGUF/resolve/main/qwen2-0_5b-instruct-q4_k_m.gguf?download=true",
null),
144 {
"RAG models",
new(string, string, string)[]
146 (
"All MiniLM L12 v2",
"https://huggingface.co/leliuga/all-MiniLM-L12-v2-GGUF/resolve/main/all-MiniLM-L12-v2.Q4_K_M.gguf",
null),
147 (
"BGE large en v1.5",
"https://huggingface.co/CompendiumLabs/bge-large-en-v1.5-gguf/resolve/main/bge-large-en-v1.5-q4_k_m.gguf",
null),
148 (
"BGE base en v1.5",
"https://huggingface.co/CompendiumLabs/bge-base-en-v1.5-gguf/resolve/main/bge-base-en-v1.5-q4_k_m.gguf",
null),
149 (
"BGE small en v1.5",
"https://huggingface.co/CompendiumLabs/bge-small-en-v1.5-gguf/resolve/main/bge-small-en-v1.5-q4_k_m.gguf",
null),
154 [
LLMUnity]
public static DebugModeType DebugMode = DebugModeType.All;
155 static string DebugModeKey =
"DebugMode";
156 public static bool FullLlamaLib =
false;
157 static string FullLlamaLibKey =
"FullLlamaLib";
158 static List<Callback<string>> errorCallbacks =
new List<Callback<string>>();
159 static readonly
object lockObject =
new object();
160 static Dictionary<string, Task> androidExtractTasks =
new Dictionary<string, Task>();
162 public enum DebugModeType
170 public static void Log(
string message)
172 if ((
int)DebugMode > (
int)DebugModeType.All)
return;
176 public static void LogWarning(
string message)
178 if ((
int)DebugMode > (
int)DebugModeType.Warning)
return;
179 Debug.LogWarning(message);
182 public static void LogError(
string message)
184 if ((
int)DebugMode > (
int)DebugModeType.Error)
return;
185 Debug.LogError(message);
186 foreach (Callback<string> errorCallback
in errorCallbacks) errorCallback(message);
189 static void LoadPlayerPrefs()
191 DebugMode = (DebugModeType)PlayerPrefs.GetInt(DebugModeKey, (
int)DebugModeType.All);
192 FullLlamaLib = PlayerPrefs.GetInt(FullLlamaLibKey, 0) == 1;
195 public static void SetDebugMode(DebugModeType newDebugMode)
197 if (DebugMode == newDebugMode)
return;
198 DebugMode = newDebugMode;
199 PlayerPrefs.SetInt(DebugModeKey, (
int)DebugMode);
204 public static void SetFullLlamaLib(
bool value)
206 if (FullLlamaLib == value)
return;
207 FullLlamaLib = value;
208 PlayerPrefs.SetInt(FullLlamaLibKey, value ? 1 : 0);
210 _ = DownloadLibrary();
215 public static string GetLibraryName(
string version)
217 return $
"undreamai-{version}-llamacpp";
220 public static string GetAssetPath(
string relPath =
"")
222 string assetsDir = Application.platform == RuntimePlatform.Android? Application.persistentDataPath : Application.streamingAssetsPath;
223 return Path.Combine(assetsDir, relPath).Replace(
'\\',
'/');
226 public static string GetDownloadAssetPath(
string relPath =
"")
228 string assetsDir = (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)? Application.persistentDataPath : Application.streamingAssetsPath;
229 return Path.Combine(assetsDir, relPath).Replace(
'\\',
'/');
233 [InitializeOnLoadMethod]
234 static async Task InitializeOnLoad()
237 await DownloadLibrary();
241 [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
242 void InitializeOnLoad()
249 static Dictionary<string, ResumingWebClient> downloadClients =
new Dictionary<string, ResumingWebClient>();
251 public static void CancelDownload(
string savePath)
253 if (!downloadClients.ContainsKey(savePath))
return;
254 downloadClients[savePath].CancelDownloadAsync();
255 downloadClients.Remove(savePath);
258 public static async Task DownloadFile(
259 string fileUrl,
string savePath,
bool overwrite =
false,
260 Callback<string> callback =
null, Callback<float> progressCallback =
null
263 if (File.Exists(savePath) && !overwrite)
265 Log($
"File already exists at: {savePath}");
269 Log($
"Downloading {fileUrl} to {savePath}...");
270 string tmpPath = Path.Combine(Application.temporaryCachePath, Path.GetFileName(savePath));
272 ResumingWebClient client =
new ResumingWebClient();
273 downloadClients[savePath] = client;
274 await client.DownloadFileTaskAsyncResume(
new Uri(fileUrl), tmpPath, !overwrite, progressCallback);
275 downloadClients.Remove(savePath);
277 AssetDatabase.StartAssetEditing();
279 Directory.CreateDirectory(Path.GetDirectoryName(savePath));
280 File.Move(tmpPath, savePath);
282 AssetDatabase.StopAssetEditing();
284 Log($
"Download complete!");
287 progressCallback?.Invoke(1f);
288 callback?.Invoke(savePath);
291 public static async Task AndroidExtractFile(
string assetName,
bool overwrite =
false,
bool log =
true,
int chunkSize = 1024*1024)
296 if (!androidExtractTasks.TryGetValue(assetName, out extractionTask))
299 extractionTask = AndroidExtractFileOnce(assetName, overwrite, log, chunkSize);
301 extractionTask = Task.CompletedTask;
303 androidExtractTasks[assetName] = extractionTask;
306 await extractionTask;
309 public static async Task AndroidExtractFileOnce(
string assetName,
bool overwrite =
false,
bool log =
true,
int chunkSize = 1024*1024)
311 string source =
"jar:file://" + Application.dataPath +
"!/assets/" + assetName;
312 string target = GetAssetPath(assetName);
313 if (!overwrite && File.Exists(target))
315 if (log) Log($
"File {target} already exists");
319 Log($
"Extracting {source} to {target}");
322 UnityWebRequest www = UnityWebRequest.Get(source);
324 var operation = www.SendWebRequest();
326 while (!operation.isDone) await Task.Delay(1);
327 if (www.result != UnityWebRequest.Result.Success)
329 LogError(
"Failed to load file from StreamingAssets: " + www.error);
333 byte[] buffer =
new byte[chunkSize];
334 using (Stream responseStream =
new MemoryStream(www.downloadHandler.data))
335 using (FileStream fileStream =
new FileStream(target, FileMode.Create, FileAccess.Write))
338 while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
340 await fileStream.WriteAsync(buffer, 0, bytesRead);
346 public static async Task AndroidExtractAsset(
string path,
bool overwrite =
false)
348 if (Application.platform != RuntimePlatform.Android)
return;
349 await AndroidExtractFile(Path.GetFileName(path), overwrite);
352 public static string GetFullPath(
string path)
354 return Path.GetFullPath(path).Replace(
'\\',
'/');
357 public static bool IsSubPath(
string childPath,
string parentPath)
359 return GetFullPath(childPath).StartsWith(GetFullPath(parentPath), StringComparison.OrdinalIgnoreCase);
362 public static string RelativePath(
string fullPath,
string basePath)
365 string fullParentPath = GetFullPath(basePath).TrimEnd(
'/');
366 string fullChildPath = GetFullPath(fullPath);
368 string relativePath = fullChildPath;
369 if (fullChildPath.StartsWith(fullParentPath, StringComparison.OrdinalIgnoreCase))
371 relativePath = fullChildPath.Substring(fullParentPath.Length);
372 while (relativePath.StartsWith(
"/")) relativePath = relativePath.Substring(1);
379 [HideInInspector]
public static float libraryProgress = 1;
381 public static void CreateEmptyFile(
string path)
383 File.Create(path).Dispose();
386 static void ExtractInsideDirectory(
string zipPath,
string extractPath,
bool overwrite =
true)
388 using (ZipArchive archive = ZipFile.OpenRead(zipPath))
390 foreach (ZipArchiveEntry entry
in archive.Entries)
392 if (
string.IsNullOrEmpty(entry.Name))
continue;
393 string destinationPath = Path.Combine(extractPath, entry.FullName);
394 Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
395 entry.ExtractToFile(destinationPath, overwrite);
400 static async Task DownloadAndExtractInsideDirectory(
string url,
string path,
string setupDir)
402 string urlName = Path.GetFileName(url);
403 string setupFile = Path.Combine(setupDir, urlName +
".complete");
404 if (File.Exists(setupFile))
return;
406 string zipPath = Path.Combine(Application.temporaryCachePath, urlName);
407 await DownloadFile(url, zipPath,
true,
null, SetLibraryProgress);
409 AssetDatabase.StartAssetEditing();
410 ExtractInsideDirectory(zipPath, path);
411 CreateEmptyFile(setupFile);
412 AssetDatabase.StopAssetEditing();
414 File.Delete(zipPath);
418 static void DeleteEarlierVersions()
420 List<string> assetPathSubDirs =
new List<string>();
421 foreach (
string dir
in new string[]{GetAssetPath(), Path.Combine(Application.dataPath,
"Plugins",
"Android")})
423 if(Directory.Exists(dir)) assetPathSubDirs.AddRange(Directory.GetDirectories(dir));
426 Regex regex =
new Regex(GetLibraryName(
"(.+)"));
427 foreach (
string assetPathSubDir
in assetPathSubDirs)
429 Match match = regex.Match(Path.GetFileName(assetPathSubDir));
432 string version = match.Groups[1].Value;
435 Debug.Log($
"Deleting other LLMUnity version folder: {assetPathSubDir}");
436 Directory.Delete(assetPathSubDir,
true);
437 if (File.Exists(assetPathSubDir +
".meta")) File.Delete(assetPathSubDir +
".meta");
443 static async Task DownloadLibrary()
445 if (libraryProgress < 1)
return;
450 DeleteEarlierVersions();
452 string setupDir = Path.Combine(
libraryPath,
"setup");
453 Directory.CreateDirectory(setupDir);
469 private static void SetLibraryProgress(
float progress)
471 libraryProgress = Math.Min(0.99f, progress);
474 public static string AddAsset(
string assetPath)
476 if (!File.Exists(assetPath))
478 LogError($
"{assetPath} does not exist!");
481 string assetDir = GetAssetPath();
482 if (IsSubPath(assetPath, assetDir))
return RelativePath(assetPath, assetDir);
484 string filename = Path.GetFileName(assetPath);
485 string fullPath = GetAssetPath(filename);
486 AssetDatabase.StartAssetEditing();
487 foreach (
string path
in new string[] {fullPath, fullPath +
".meta"})
489 if (File.Exists(path)) File.Delete(path);
491 File.Copy(assetPath, fullPath);
492 AssetDatabase.StopAssetEditing();
502 errorCallbacks.Add(callback);
508 errorCallbacks.Remove(callback);
514 errorCallbacks.Clear();
517 public static int GetMaxFreqKHz(
int cpuId)
519 string[] paths =
new string[]
521 $
"/sys/devices/system/cpu/cpufreq/stats/cpu{cpuId}/time_in_state",
522 $
"/sys/devices/system/cpu/cpu{cpuId}/cpufreq/stats/time_in_state",
523 $
"/sys/devices/system/cpu/cpu{cpuId}/cpufreq/cpuinfo_max_freq"
526 foreach (var path
in paths)
528 if (!File.Exists(path))
continue;
531 using (StreamReader sr =
new StreamReader(path))
534 while ((line = sr.ReadLine()) !=
null)
536 string[] parts = line.Split(
' ');
537 if (parts.Length > 0 &&
int.TryParse(parts[0], out
int freqKHz))
539 if (freqKHz > maxFreqKHz)
541 maxFreqKHz = freqKHz;
546 if (maxFreqKHz != 0)
return maxFreqKHz;
551 public static bool IsSmtCpu(
int cpuId)
553 string[] paths =
new string[]
555 $
"/sys/devices/system/cpu/cpu{cpuId}/topology/core_cpus_list",
556 $
"/sys/devices/system/cpu/cpu{cpuId}/topology/thread_siblings_list"
559 foreach (var path
in paths)
561 if (!File.Exists(path))
continue;
562 using (StreamReader sr =
new StreamReader(path))
565 while ((line = sr.ReadLine()) !=
null)
567 if (line.Contains(
",") || line.Contains(
"-"))
583 int maxFreqKHzMin =
int.MaxValue;
584 int maxFreqKHzMax = 0;
585 List<int> cpuMaxFreqKHz =
new List<int>();
586 List<bool> cpuIsSmtCpu =
new List<bool>();
590 string cpuPath =
"/sys/devices/system/cpu/";
592 if (Directory.Exists(cpuPath))
594 foreach (
string cpuDir
in Directory.GetDirectories(cpuPath))
596 string dirName = Path.GetFileName(cpuDir);
597 if (!dirName.StartsWith(
"cpu"))
continue;
598 if (!
int.TryParse(dirName.Substring(3), out coreIndex))
continue;
600 int maxFreqKHz = GetMaxFreqKHz(coreIndex);
601 cpuMaxFreqKHz.Add(maxFreqKHz);
602 if (maxFreqKHz > maxFreqKHzMax) maxFreqKHzMax = maxFreqKHz;
603 if (maxFreqKHz < maxFreqKHzMin) maxFreqKHzMin = maxFreqKHz;
604 cpuIsSmtCpu.Add(IsSmtCpu(coreIndex));
614 int numCores = SystemInfo.processorCount;
615 int maxFreqKHzMedium = (maxFreqKHzMin + maxFreqKHzMax) / 2;
616 if (maxFreqKHzMedium == maxFreqKHzMax) numBigCores = numCores;
619 for (
int i = 0; i < cpuMaxFreqKHz.Count; i++)
621 if (cpuIsSmtCpu[i] || cpuMaxFreqKHz[i] >= maxFreqKHzMedium) numBigCores++;
625 if (numBigCores == 0) numBigCores = SystemInfo.processorCount / 2;
626 else numBigCores = Math.Min(numBigCores, SystemInfo.processorCount);
637 List<int> capacities =
new List<int>();
638 int minCapacity =
int.MaxValue;
641 string cpuPath =
"/sys/devices/system/cpu/";
643 if (Directory.Exists(cpuPath))
645 foreach (
string cpuDir
in Directory.GetDirectories(cpuPath))
647 string dirName = Path.GetFileName(cpuDir);
648 if (!dirName.StartsWith(
"cpu"))
continue;
649 if (!
int.TryParse(dirName.Substring(3), out coreIndex))
continue;
651 string capacityPath = Path.Combine(cpuDir,
"cpu_capacity");
652 if (!File.Exists(capacityPath))
break;
654 int capacity =
int.Parse(File.ReadAllText(capacityPath).Trim());
655 capacities.Add(capacity);
656 if (minCapacity > capacity) minCapacity = capacity;
666 foreach (
int capacity
in capacities)
668 if (capacity >= 2 * minCapacity) numBigCores++;
671 if (numBigCores == 0 || numBigCores > SystemInfo.processorCount) numBigCores = SystemInfo.processorCount;