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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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", contextSize: 2048);
  13. _model = LLamaWeights.LoadFromFile(_params);
  14. }
  15. public void Dispose()
  16. {
  17. _model.Dispose();
  18. }
  19. [Fact]
  20. public void CreateBasicGrammar()
  21. {
  22. var rules = new List<List<LLamaGrammarElement>>
  23. {
  24. new()
  25. {
  26. new LLamaGrammarElement(LLamaGrammarElementType.CHAR, 'a'),
  27. new LLamaGrammarElement(LLamaGrammarElementType.CHAR_RNG_UPPER, 'z'),
  28. new LLamaGrammarElement(LLamaGrammarElementType.END, 0),
  29. },
  30. };
  31. using var handle = SafeLLamaGrammarHandle.Create(rules, 0);
  32. }
  33. [Fact]
  34. public void SampleWithTrivialGrammar()
  35. {
  36. // Create a grammar that constrains the output to be "cat" and nothing else. This is a nonsense answer, so
  37. // we can be confident it's not what the LLM would say if not constrained by the grammar!
  38. var rules = new List<List<LLamaGrammarElement>>
  39. {
  40. new()
  41. {
  42. new LLamaGrammarElement(LLamaGrammarElementType.CHAR, 'c'),
  43. new LLamaGrammarElement(LLamaGrammarElementType.CHAR, 'a'),
  44. new LLamaGrammarElement(LLamaGrammarElementType.CHAR, 't'),
  45. new LLamaGrammarElement(LLamaGrammarElementType.END, 0),
  46. },
  47. };
  48. using var grammar = SafeLLamaGrammarHandle.Create(rules, 0);
  49. var executor = new StatelessExecutor(_model, _params);
  50. var inferenceParams = new InferenceParams
  51. {
  52. MaxTokens = 3,
  53. AntiPrompts = new [] { ".", "Input:", "\n" },
  54. Grammar = grammar,
  55. };
  56. var result = executor.Infer("Question: What is your favourite number?\nAnswer: ", inferenceParams).ToList();
  57. Assert.Equal("cat", result[0]);
  58. }
  59. }
  60. }