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.

LLamaEmbedder.cs 2.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using LLama.Native;
  2. using System;
  3. using LLama.Exceptions;
  4. #pragma warning disable
  5. // ReSharper disable all
  6. namespace LLama.OldVersion
  7. {
  8. [Obsolete("The entire LLama.OldVersion namespace will be removed")]
  9. public class LLamaEmbedder
  10. : IDisposable
  11. {
  12. SafeLLamaContextHandle _ctx;
  13. /// <summary>
  14. /// Warning: must ensure the original model has params.embedding = true;
  15. /// </summary>
  16. /// <param name="ctx"></param>
  17. internal LLamaEmbedder(SafeLLamaContextHandle ctx)
  18. {
  19. _ctx = ctx;
  20. }
  21. public LLamaEmbedder(LLamaParams @params)
  22. {
  23. @params.embedding = true;
  24. _ctx = Utils.llama_init_from_gpt_params(ref @params);
  25. }
  26. public unsafe float[] GetEmbeddings(string text, int n_thread = -1, bool add_bos = true, string encoding = "UTF-8")
  27. {
  28. if (n_thread == -1)
  29. {
  30. n_thread = Math.Max(Environment.ProcessorCount / 2, 1);
  31. }
  32. int n_past = 0;
  33. if (add_bos)
  34. {
  35. text = text.Insert(0, " ");
  36. }
  37. var embed_inp = Utils.llama_tokenize(_ctx, text, add_bos, encoding);
  38. // TODO(Rinne): deal with log of prompt
  39. if (embed_inp.Count > 0)
  40. {
  41. var embed_inp_array = embed_inp.ToArray();
  42. if (NativeApi.llama_eval(_ctx, embed_inp_array, embed_inp_array.Length, n_past, n_thread) != 0)
  43. {
  44. throw new RuntimeError("Failed to eval.");
  45. }
  46. }
  47. int n_embed = NativeApi.llama_n_embd(_ctx);
  48. var embeddings = NativeApi.llama_get_embeddings(_ctx);
  49. if (embeddings == null)
  50. {
  51. return new float[0];
  52. }
  53. var span = new Span<float>(embeddings, n_embed);
  54. float[] res = new float[n_embed];
  55. span.CopyTo(res.AsSpan());
  56. return res;
  57. }
  58. public void Dispose()
  59. {
  60. _ctx.Dispose();
  61. }
  62. }
  63. }