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.4 kB

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