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.

GrammarTest.cs 2.5 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using LLama.Common;
  2. using LLama.Grammars;
  3. using LLama.Native;
  4. namespace LLama.Unittest
  5. {
  6. public sealed class GrammarTest
  7. : IDisposable
  8. {
  9. private readonly ModelParams _params;
  10. private readonly LLamaWeights _model;
  11. public GrammarTest()
  12. {
  13. _params = new ModelParams("Models/llama-2-7b-chat.ggmlv3.q3_K_S.bin")
  14. {
  15. ContextSize = 2048,
  16. };
  17. _model = LLamaWeights.LoadFromFile(_params);
  18. }
  19. public void Dispose()
  20. {
  21. _model.Dispose();
  22. }
  23. [Fact]
  24. public void CreateBasicGrammar()
  25. {
  26. var rules = new List<GrammarRule>
  27. {
  28. new GrammarRule("alpha", new[]
  29. {
  30. new LLamaGrammarElement(LLamaGrammarElementType.CHAR, 'a'),
  31. new LLamaGrammarElement(LLamaGrammarElementType.CHAR_RNG_UPPER, 'z'),
  32. new LLamaGrammarElement(LLamaGrammarElementType.END, 0),
  33. }),
  34. };
  35. using var handle = SafeLLamaGrammarHandle.Create(rules, 0);
  36. }
  37. [Fact]
  38. public void SampleWithTrivialGrammar()
  39. {
  40. // Create a grammar that constrains the output to be "cat" and nothing else. This is a nonsense answer, so
  41. // we can be confident it's not what the LLM would say if not constrained by the grammar!
  42. var rules = new List<GrammarRule>
  43. {
  44. new GrammarRule("feline", new []
  45. {
  46. new LLamaGrammarElement(LLamaGrammarElementType.CHAR, 'c'),
  47. new LLamaGrammarElement(LLamaGrammarElementType.CHAR, 'a'),
  48. new LLamaGrammarElement(LLamaGrammarElementType.CHAR, 't'),
  49. new LLamaGrammarElement(LLamaGrammarElementType.END, 0),
  50. }),
  51. };
  52. using var grammar = SafeLLamaGrammarHandle.Create(rules, 0);
  53. var executor = new StatelessExecutor(_model, _params);
  54. var inferenceParams = new InferenceParams
  55. {
  56. MaxTokens = 3,
  57. AntiPrompts = new [] { ".", "Input:", "\n" },
  58. Grammar = grammar,
  59. };
  60. var result = executor.Infer("Question: What is your favourite number?\nAnswer: ", inferenceParams).ToList();
  61. Assert.Equal("cat", result[0]);
  62. }
  63. }
  64. }