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

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