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.

LLamaEmbedderTests.cs 1.9 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using LLama.Common;
  2. namespace LLama.Unittest;
  3. public class LLamaEmbedderTests
  4. : IDisposable
  5. {
  6. private readonly LLamaEmbedder _embedder = new(new ModelParams(Constants.ModelPath));
  7. public void Dispose()
  8. {
  9. _embedder.Dispose();
  10. }
  11. private static float Magnitude(float[] a)
  12. {
  13. return MathF.Sqrt(a.Zip(a, (x, y) => x * y).Sum());
  14. }
  15. private static void Normalize(float[] a)
  16. {
  17. var mag = Magnitude(a);
  18. for (var i = 0; i < a.Length; i++)
  19. a[i] /= mag;
  20. }
  21. private static float Dot(float[] a, float[] b)
  22. {
  23. Assert.Equal(a.Length, b.Length);
  24. return a.Zip(b, (x, y) => x * y).Sum();
  25. }
  26. private static void AssertApproxStartsWith(float[] expected, float[] actual, float epsilon = 0.08f)
  27. {
  28. for (int i = 0; i < expected.Length; i++)
  29. Assert.Equal(expected[i], actual[i], epsilon);
  30. }
  31. // todo: enable this one llama2 7B gguf is available
  32. //[Fact]
  33. //public void EmbedBasic()
  34. //{
  35. // var cat = _embedder.GetEmbeddings("cat");
  36. // Assert.NotNull(cat);
  37. // Assert.NotEmpty(cat);
  38. // // Expected value generate with llama.cpp embedding.exe
  39. // var expected = new float[] { -0.127304f, -0.678057f, -0.085244f, -0.956915f, -0.638633f };
  40. // AssertApproxStartsWith(expected, cat);
  41. //}
  42. [Fact]
  43. public void EmbedCompare()
  44. {
  45. var cat = _embedder.GetEmbeddings("cat");
  46. var kitten = _embedder.GetEmbeddings("kitten");
  47. var spoon = _embedder.GetEmbeddings("spoon");
  48. Normalize(cat);
  49. Normalize(kitten);
  50. Normalize(spoon);
  51. var close = Dot(cat, kitten);
  52. var far = Dot(cat, spoon);
  53. // This comparison seems backwards, but remember that with a
  54. // dot product 1.0 means **identical** and 0.0 means **completely opposite**!
  55. Assert.True(close > far);
  56. }
  57. }