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

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