You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Utils.cs 2.9 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using LLama.Native;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using LLama.Exceptions;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. using System.IO;
  9. #pragma warning disable
  10. namespace LLama.OldVersion
  11. {
  12. using llama_token = Int32;
  13. internal static class Utils
  14. {
  15. public static SafeLLamaContextHandle llama_init_from_gpt_params(ref LLamaParams @params)
  16. {
  17. var lparams = NativeApi.llama_context_default_params();
  18. lparams.n_ctx = @params.n_ctx;
  19. lparams.n_gpu_layers = @params.n_gpu_layers;
  20. lparams.seed = @params.seed;
  21. lparams.f16_kv = @params.memory_f16;
  22. lparams.use_mmap = @params.use_mmap;
  23. lparams.use_mlock = @params.use_mlock;
  24. lparams.logits_all = @params.perplexity;
  25. lparams.embedding = @params.embedding;
  26. if (!File.Exists(@params.model))
  27. {
  28. throw new FileNotFoundException($"The model file does not exist: {@params.model}");
  29. }
  30. var model = SafeLlamaModelHandle.LoadFromFile(@params.model, lparams);
  31. var ctx = SafeLLamaContextHandle.Create(model, lparams);
  32. if (!string.IsNullOrEmpty(@params.lora_adapter))
  33. model.ApplyLoraFromFile(@params.lora_adapter, @params.lora_base, @params.n_threads);
  34. return ctx;
  35. }
  36. public static List<llama_token> llama_tokenize(SafeLLamaContextHandle ctx, string text, bool add_bos, string encodingName)
  37. {
  38. var encoding = Encoding.GetEncoding(encodingName);
  39. var cnt = encoding.GetByteCount(text);
  40. llama_token[] res = new llama_token[cnt + (add_bos ? 1 : 0)];
  41. int n = NativeApi.llama_tokenize(ctx, text, encoding, res, res.Length, add_bos);
  42. if (n < 0)
  43. {
  44. throw new RuntimeError("Error happened during tokenization. It's possibly caused by wrong encoding. Please try to " +
  45. "specify the encoding.");
  46. }
  47. return res.Take(n).ToList();
  48. }
  49. public unsafe static Span<float> llama_get_logits(SafeLLamaContextHandle ctx, int length)
  50. {
  51. var logits = NativeApi.llama_get_logits(ctx);
  52. return new Span<float>(logits, length);
  53. }
  54. public static unsafe string PtrToStringUTF8(IntPtr ptr)
  55. {
  56. #if NET6_0_OR_GREATER
  57. return Marshal.PtrToStringUTF8(ptr);
  58. #else
  59. byte* tp = (byte*)ptr.ToPointer();
  60. List<byte> bytes = new();
  61. while (true)
  62. {
  63. byte c = *tp++;
  64. if (c == '\0')
  65. {
  66. break;
  67. }
  68. else
  69. {
  70. bytes.Add(c);
  71. }
  72. }
  73. return Encoding.UTF8.GetString(bytes.ToArray());
  74. #endif
  75. }
  76. }
  77. }