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.

SafeLlamaModelHandle.cs 26 kB

April 2024 Binary Update (#662) * Updated binaries, using [this build](https://github.com/SciSharp/LLamaSharp/actions/runs/8654672719/job/23733195669) for llama.cpp commit `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7`. - Added all new functions. - Moved some functions (e.g. `SafeLlamaModelHandle` specific functions) into `SafeLlamaModelHandle.cs` - Exposed tokens on `SafeLlamaModelHandle` and `LLamaWeights` through a `Tokens` property. As new special tokens are added in the future they can be added here. - Changed all token properties to return nullable tokens, to handle some models not having some tokens. - Fixed `DefaultSamplingPipeline` to handle no newline token in some models. * Moved native methods to more specific locations. - Context specific things have been moved into `SafeLLamaContextHandle.cs` and made private - they're exposed through C# properties and methods already. - Checking that GPU layer count is zero if GPU offload is not supported. - Moved methods for creating default structs (`llama_model_quantize_default_params` and `llama_context_default_params`) into relevant structs. * Removed exception if `GpuLayerCount > 0` when GPU is not supported. * - Added low level wrapper methods for new per-sequence state load/save in `SafeLLamaContextHandle` - Added high level wrapper methods (save/load with `State` object or memory mapped file) in `LLamaContext` - Moved native methods for per-sequence state load/save into `SafeLLamaContextHandle` * Added update and defrag methods for KV cache in `SafeLLamaContextHandle` * Updated submodule to `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7` * Passing the sequence ID when saving a single sequence state
1 year ago
April 2024 Binary Update (#662) * Updated binaries, using [this build](https://github.com/SciSharp/LLamaSharp/actions/runs/8654672719/job/23733195669) for llama.cpp commit `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7`. - Added all new functions. - Moved some functions (e.g. `SafeLlamaModelHandle` specific functions) into `SafeLlamaModelHandle.cs` - Exposed tokens on `SafeLlamaModelHandle` and `LLamaWeights` through a `Tokens` property. As new special tokens are added in the future they can be added here. - Changed all token properties to return nullable tokens, to handle some models not having some tokens. - Fixed `DefaultSamplingPipeline` to handle no newline token in some models. * Moved native methods to more specific locations. - Context specific things have been moved into `SafeLLamaContextHandle.cs` and made private - they're exposed through C# properties and methods already. - Checking that GPU layer count is zero if GPU offload is not supported. - Moved methods for creating default structs (`llama_model_quantize_default_params` and `llama_context_default_params`) into relevant structs. * Removed exception if `GpuLayerCount > 0` when GPU is not supported. * - Added low level wrapper methods for new per-sequence state load/save in `SafeLLamaContextHandle` - Added high level wrapper methods (save/load with `State` object or memory mapped file) in `LLamaContext` - Moved native methods for per-sequence state load/save into `SafeLLamaContextHandle` * Added update and defrag methods for KV cache in `SafeLLamaContextHandle` * Updated submodule to `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7` * Passing the sequence ID when saving a single sequence state
1 year ago
April 2024 Binary Update (#662) * Updated binaries, using [this build](https://github.com/SciSharp/LLamaSharp/actions/runs/8654672719/job/23733195669) for llama.cpp commit `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7`. - Added all new functions. - Moved some functions (e.g. `SafeLlamaModelHandle` specific functions) into `SafeLlamaModelHandle.cs` - Exposed tokens on `SafeLlamaModelHandle` and `LLamaWeights` through a `Tokens` property. As new special tokens are added in the future they can be added here. - Changed all token properties to return nullable tokens, to handle some models not having some tokens. - Fixed `DefaultSamplingPipeline` to handle no newline token in some models. * Moved native methods to more specific locations. - Context specific things have been moved into `SafeLLamaContextHandle.cs` and made private - they're exposed through C# properties and methods already. - Checking that GPU layer count is zero if GPU offload is not supported. - Moved methods for creating default structs (`llama_model_quantize_default_params` and `llama_context_default_params`) into relevant structs. * Removed exception if `GpuLayerCount > 0` when GPU is not supported. * - Added low level wrapper methods for new per-sequence state load/save in `SafeLLamaContextHandle` - Added high level wrapper methods (save/load with `State` object or memory mapped file) in `LLamaContext` - Moved native methods for per-sequence state load/save into `SafeLLamaContextHandle` * Added update and defrag methods for KV cache in `SafeLLamaContextHandle` * Updated submodule to `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7` * Passing the sequence ID when saving a single sequence state
1 year ago
April 2024 Binary Update (#662) * Updated binaries, using [this build](https://github.com/SciSharp/LLamaSharp/actions/runs/8654672719/job/23733195669) for llama.cpp commit `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7`. - Added all new functions. - Moved some functions (e.g. `SafeLlamaModelHandle` specific functions) into `SafeLlamaModelHandle.cs` - Exposed tokens on `SafeLlamaModelHandle` and `LLamaWeights` through a `Tokens` property. As new special tokens are added in the future they can be added here. - Changed all token properties to return nullable tokens, to handle some models not having some tokens. - Fixed `DefaultSamplingPipeline` to handle no newline token in some models. * Moved native methods to more specific locations. - Context specific things have been moved into `SafeLLamaContextHandle.cs` and made private - they're exposed through C# properties and methods already. - Checking that GPU layer count is zero if GPU offload is not supported. - Moved methods for creating default structs (`llama_model_quantize_default_params` and `llama_context_default_params`) into relevant structs. * Removed exception if `GpuLayerCount > 0` when GPU is not supported. * - Added low level wrapper methods for new per-sequence state load/save in `SafeLLamaContextHandle` - Added high level wrapper methods (save/load with `State` object or memory mapped file) in `LLamaContext` - Moved native methods for per-sequence state load/save into `SafeLLamaContextHandle` * Added update and defrag methods for KV cache in `SafeLLamaContextHandle` * Updated submodule to `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7` * Passing the sequence ID when saving a single sequence state
1 year ago
April 2024 Binary Update (#662) * Updated binaries, using [this build](https://github.com/SciSharp/LLamaSharp/actions/runs/8654672719/job/23733195669) for llama.cpp commit `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7`. - Added all new functions. - Moved some functions (e.g. `SafeLlamaModelHandle` specific functions) into `SafeLlamaModelHandle.cs` - Exposed tokens on `SafeLlamaModelHandle` and `LLamaWeights` through a `Tokens` property. As new special tokens are added in the future they can be added here. - Changed all token properties to return nullable tokens, to handle some models not having some tokens. - Fixed `DefaultSamplingPipeline` to handle no newline token in some models. * Moved native methods to more specific locations. - Context specific things have been moved into `SafeLLamaContextHandle.cs` and made private - they're exposed through C# properties and methods already. - Checking that GPU layer count is zero if GPU offload is not supported. - Moved methods for creating default structs (`llama_model_quantize_default_params` and `llama_context_default_params`) into relevant structs. * Removed exception if `GpuLayerCount > 0` when GPU is not supported. * - Added low level wrapper methods for new per-sequence state load/save in `SafeLLamaContextHandle` - Added high level wrapper methods (save/load with `State` object or memory mapped file) in `LLamaContext` - Moved native methods for per-sequence state load/save into `SafeLLamaContextHandle` * Added update and defrag methods for KV cache in `SafeLLamaContextHandle` * Updated submodule to `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7` * Passing the sequence ID when saving a single sequence state
1 year ago
April 2024 Binary Update (#662) * Updated binaries, using [this build](https://github.com/SciSharp/LLamaSharp/actions/runs/8654672719/job/23733195669) for llama.cpp commit `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7`. - Added all new functions. - Moved some functions (e.g. `SafeLlamaModelHandle` specific functions) into `SafeLlamaModelHandle.cs` - Exposed tokens on `SafeLlamaModelHandle` and `LLamaWeights` through a `Tokens` property. As new special tokens are added in the future they can be added here. - Changed all token properties to return nullable tokens, to handle some models not having some tokens. - Fixed `DefaultSamplingPipeline` to handle no newline token in some models. * Moved native methods to more specific locations. - Context specific things have been moved into `SafeLLamaContextHandle.cs` and made private - they're exposed through C# properties and methods already. - Checking that GPU layer count is zero if GPU offload is not supported. - Moved methods for creating default structs (`llama_model_quantize_default_params` and `llama_context_default_params`) into relevant structs. * Removed exception if `GpuLayerCount > 0` when GPU is not supported. * - Added low level wrapper methods for new per-sequence state load/save in `SafeLLamaContextHandle` - Added high level wrapper methods (save/load with `State` object or memory mapped file) in `LLamaContext` - Moved native methods for per-sequence state load/save into `SafeLLamaContextHandle` * Added update and defrag methods for KV cache in `SafeLLamaContextHandle` * Updated submodule to `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7` * Passing the sequence ID when saving a single sequence state
1 year ago
April 2024 Binary Update (#662) * Updated binaries, using [this build](https://github.com/SciSharp/LLamaSharp/actions/runs/8654672719/job/23733195669) for llama.cpp commit `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7`. - Added all new functions. - Moved some functions (e.g. `SafeLlamaModelHandle` specific functions) into `SafeLlamaModelHandle.cs` - Exposed tokens on `SafeLlamaModelHandle` and `LLamaWeights` through a `Tokens` property. As new special tokens are added in the future they can be added here. - Changed all token properties to return nullable tokens, to handle some models not having some tokens. - Fixed `DefaultSamplingPipeline` to handle no newline token in some models. * Moved native methods to more specific locations. - Context specific things have been moved into `SafeLLamaContextHandle.cs` and made private - they're exposed through C# properties and methods already. - Checking that GPU layer count is zero if GPU offload is not supported. - Moved methods for creating default structs (`llama_model_quantize_default_params` and `llama_context_default_params`) into relevant structs. * Removed exception if `GpuLayerCount > 0` when GPU is not supported. * - Added low level wrapper methods for new per-sequence state load/save in `SafeLLamaContextHandle` - Added high level wrapper methods (save/load with `State` object or memory mapped file) in `LLamaContext` - Moved native methods for per-sequence state load/save into `SafeLLamaContextHandle` * Added update and defrag methods for KV cache in `SafeLLamaContextHandle` * Updated submodule to `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7` * Passing the sequence ID when saving a single sequence state
1 year ago
April 2024 Binary Update (#662) * Updated binaries, using [this build](https://github.com/SciSharp/LLamaSharp/actions/runs/8654672719/job/23733195669) for llama.cpp commit `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7`. - Added all new functions. - Moved some functions (e.g. `SafeLlamaModelHandle` specific functions) into `SafeLlamaModelHandle.cs` - Exposed tokens on `SafeLlamaModelHandle` and `LLamaWeights` through a `Tokens` property. As new special tokens are added in the future they can be added here. - Changed all token properties to return nullable tokens, to handle some models not having some tokens. - Fixed `DefaultSamplingPipeline` to handle no newline token in some models. * Moved native methods to more specific locations. - Context specific things have been moved into `SafeLLamaContextHandle.cs` and made private - they're exposed through C# properties and methods already. - Checking that GPU layer count is zero if GPU offload is not supported. - Moved methods for creating default structs (`llama_model_quantize_default_params` and `llama_context_default_params`) into relevant structs. * Removed exception if `GpuLayerCount > 0` when GPU is not supported. * - Added low level wrapper methods for new per-sequence state load/save in `SafeLLamaContextHandle` - Added high level wrapper methods (save/load with `State` object or memory mapped file) in `LLamaContext` - Moved native methods for per-sequence state load/save into `SafeLLamaContextHandle` * Added update and defrag methods for KV cache in `SafeLLamaContextHandle` * Updated submodule to `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7` * Passing the sequence ID when saving a single sequence state
1 year ago
April 2024 Binary Update (#662) * Updated binaries, using [this build](https://github.com/SciSharp/LLamaSharp/actions/runs/8654672719/job/23733195669) for llama.cpp commit `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7`. - Added all new functions. - Moved some functions (e.g. `SafeLlamaModelHandle` specific functions) into `SafeLlamaModelHandle.cs` - Exposed tokens on `SafeLlamaModelHandle` and `LLamaWeights` through a `Tokens` property. As new special tokens are added in the future they can be added here. - Changed all token properties to return nullable tokens, to handle some models not having some tokens. - Fixed `DefaultSamplingPipeline` to handle no newline token in some models. * Moved native methods to more specific locations. - Context specific things have been moved into `SafeLLamaContextHandle.cs` and made private - they're exposed through C# properties and methods already. - Checking that GPU layer count is zero if GPU offload is not supported. - Moved methods for creating default structs (`llama_model_quantize_default_params` and `llama_context_default_params`) into relevant structs. * Removed exception if `GpuLayerCount > 0` when GPU is not supported. * - Added low level wrapper methods for new per-sequence state load/save in `SafeLLamaContextHandle` - Added high level wrapper methods (save/load with `State` object or memory mapped file) in `LLamaContext` - Moved native methods for per-sequence state load/save into `SafeLLamaContextHandle` * Added update and defrag methods for KV cache in `SafeLLamaContextHandle` * Updated submodule to `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7` * Passing the sequence ID when saving a single sequence state
1 year ago
April 2024 Binary Update (#662) * Updated binaries, using [this build](https://github.com/SciSharp/LLamaSharp/actions/runs/8654672719/job/23733195669) for llama.cpp commit `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7`. - Added all new functions. - Moved some functions (e.g. `SafeLlamaModelHandle` specific functions) into `SafeLlamaModelHandle.cs` - Exposed tokens on `SafeLlamaModelHandle` and `LLamaWeights` through a `Tokens` property. As new special tokens are added in the future they can be added here. - Changed all token properties to return nullable tokens, to handle some models not having some tokens. - Fixed `DefaultSamplingPipeline` to handle no newline token in some models. * Moved native methods to more specific locations. - Context specific things have been moved into `SafeLLamaContextHandle.cs` and made private - they're exposed through C# properties and methods already. - Checking that GPU layer count is zero if GPU offload is not supported. - Moved methods for creating default structs (`llama_model_quantize_default_params` and `llama_context_default_params`) into relevant structs. * Removed exception if `GpuLayerCount > 0` when GPU is not supported. * - Added low level wrapper methods for new per-sequence state load/save in `SafeLLamaContextHandle` - Added high level wrapper methods (save/load with `State` object or memory mapped file) in `LLamaContext` - Moved native methods for per-sequence state load/save into `SafeLLamaContextHandle` * Added update and defrag methods for KV cache in `SafeLLamaContextHandle` * Updated submodule to `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7` * Passing the sequence ID when saving a single sequence state
1 year ago
April 2024 Binary Update (#662) * Updated binaries, using [this build](https://github.com/SciSharp/LLamaSharp/actions/runs/8654672719/job/23733195669) for llama.cpp commit `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7`. - Added all new functions. - Moved some functions (e.g. `SafeLlamaModelHandle` specific functions) into `SafeLlamaModelHandle.cs` - Exposed tokens on `SafeLlamaModelHandle` and `LLamaWeights` through a `Tokens` property. As new special tokens are added in the future they can be added here. - Changed all token properties to return nullable tokens, to handle some models not having some tokens. - Fixed `DefaultSamplingPipeline` to handle no newline token in some models. * Moved native methods to more specific locations. - Context specific things have been moved into `SafeLLamaContextHandle.cs` and made private - they're exposed through C# properties and methods already. - Checking that GPU layer count is zero if GPU offload is not supported. - Moved methods for creating default structs (`llama_model_quantize_default_params` and `llama_context_default_params`) into relevant structs. * Removed exception if `GpuLayerCount > 0` when GPU is not supported. * - Added low level wrapper methods for new per-sequence state load/save in `SafeLLamaContextHandle` - Added high level wrapper methods (save/load with `State` object or memory mapped file) in `LLamaContext` - Moved native methods for per-sequence state load/save into `SafeLLamaContextHandle` * Added update and defrag methods for KV cache in `SafeLLamaContextHandle` * Updated submodule to `f7001ccc5aa359fcf41bba19d1c99c3d25c9bcc7` * Passing the sequence ID when saving a single sequence state
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. using System;
  2. using System.Buffers;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. using LLama.Exceptions;
  9. using LLama.Extensions;
  10. namespace LLama.Native
  11. {
  12. /// <summary>
  13. /// A reference to a set of llama model weights
  14. /// </summary>
  15. // ReSharper disable once ClassNeverInstantiated.Global (used implicitly in native API)
  16. public sealed class SafeLlamaModelHandle
  17. : SafeLLamaHandleBase
  18. {
  19. /// <summary>
  20. /// Total number of tokens in vocabulary of this model
  21. /// </summary>
  22. public int VocabCount => llama_n_vocab(this);
  23. /// <summary>
  24. /// Get the vocabulary type for this model
  25. /// </summary>
  26. public LLamaVocabType VocabType => llama_vocab_type(this);
  27. /// <summary>
  28. /// Get the rope (positional embedding) type for this model
  29. /// </summary>
  30. public LLamaRopeType RopeType => llama_rope_type(this);
  31. /// <summary>
  32. /// Total number of tokens in the context
  33. /// </summary>
  34. public int ContextSize => llama_n_ctx_train(this);
  35. /// <summary>
  36. /// Get the rope frequency this model was trained with
  37. /// </summary>
  38. public float RopeFrequency => llama_rope_freq_scale_train(this);
  39. /// <summary>
  40. /// Dimension of embedding vectors
  41. /// </summary>
  42. public int EmbeddingSize => llama_n_embd(this);
  43. /// <summary>
  44. /// Get the size of this model in bytes
  45. /// </summary>
  46. public ulong SizeInBytes => llama_model_size(this);
  47. /// <summary>
  48. /// Get the number of parameters in this model
  49. /// </summary>
  50. public ulong ParameterCount => llama_model_n_params(this);
  51. /// <summary>
  52. /// Get the number of layers in this model
  53. /// </summary>
  54. public int LayerCount => llama_n_embd(this);
  55. /// <summary>
  56. /// Get a description of this model
  57. /// </summary>
  58. public string Description
  59. {
  60. get
  61. {
  62. unsafe
  63. {
  64. // Get description length
  65. var size = llama_model_desc(this, null, 0);
  66. var buf = new byte[size + 1];
  67. fixed (byte* bufPtr = buf)
  68. {
  69. size = llama_model_desc(this, bufPtr, buf.Length);
  70. return Encoding.UTF8.GetString(buf, 0, size);
  71. }
  72. }
  73. }
  74. }
  75. /// <summary>
  76. /// Get the number of metadata key/value pairs
  77. /// </summary>
  78. /// <returns></returns>
  79. public int MetadataCount => llama_model_meta_count(this);
  80. private ModelTokens? _tokens;
  81. /// <summary>
  82. /// Get the special tokens of this model
  83. /// </summary>
  84. public ModelTokens Tokens => _tokens ??= new ModelTokens(this);
  85. /// <inheritdoc />
  86. protected override bool ReleaseHandle()
  87. {
  88. llama_free_model(handle);
  89. return true;
  90. }
  91. /// <summary>
  92. /// Load a model from the given file path into memory
  93. /// </summary>
  94. /// <param name="modelPath"></param>
  95. /// <param name="lparams"></param>
  96. /// <returns></returns>
  97. /// <exception cref="RuntimeError"></exception>
  98. public static SafeLlamaModelHandle LoadFromFile(string modelPath, LLamaModelParams lparams)
  99. {
  100. // Try to open the model file, this will check:
  101. // - File exists (automatically throws FileNotFoundException)
  102. // - File is readable (explicit check)
  103. // This provides better error messages that llama.cpp, which would throw an access violation exception in both cases.
  104. using (var fs = new FileStream(modelPath, FileMode.Open))
  105. if (!fs.CanRead)
  106. throw new InvalidOperationException($"Model file '{modelPath}' is not readable");
  107. return llama_load_model_from_file(modelPath, lparams)
  108. ?? throw new LoadWeightsFailedException(modelPath);
  109. }
  110. #region native API
  111. static SafeLlamaModelHandle()
  112. {
  113. // Ensure that `NativeApi` has been loaded
  114. NativeApi.llama_empty_call();
  115. }
  116. /// <summary>
  117. /// Load all of the weights of a model into memory.
  118. /// </summary>
  119. /// <param name="path_model"></param>
  120. /// <param name="params"></param>
  121. /// <returns>The loaded model, or null on failure.</returns>
  122. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  123. private static extern SafeLlamaModelHandle llama_load_model_from_file(string path_model, LLamaModelParams @params);
  124. /// <summary>
  125. /// Apply a LoRA adapter to a loaded model
  126. /// path_base_model is the path to a higher quality model to use as a base for
  127. /// the layers modified by the adapter. Can be NULL to use the current loaded model.
  128. /// The model needs to be reloaded before applying a new adapter, otherwise the adapter
  129. /// will be applied on top of the previous one
  130. /// </summary>
  131. /// <param name="model_ptr"></param>
  132. /// <param name="path_lora"></param>
  133. /// <param name="scale"></param>
  134. /// <param name="path_base_model"></param>
  135. /// <param name="n_threads"></param>
  136. /// <returns>Returns 0 on success</returns>
  137. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  138. private static extern int llama_model_apply_lora_from_file(SafeLlamaModelHandle model_ptr, string path_lora, float scale, string? path_base_model, int n_threads);
  139. /// <summary>
  140. /// Frees all allocated memory associated with a model
  141. /// </summary>
  142. /// <param name="model"></param>
  143. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  144. private static extern void llama_free_model(IntPtr model);
  145. /// <summary>
  146. /// Get the number of metadata key/value pairs
  147. /// </summary>
  148. /// <param name="model"></param>
  149. /// <returns></returns>
  150. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  151. private static extern int llama_model_meta_count(SafeLlamaModelHandle model);
  152. /// <summary>
  153. /// Get metadata key name by index
  154. /// </summary>
  155. /// <param name="model">Model to fetch from</param>
  156. /// <param name="index">Index of key to fetch</param>
  157. /// <param name="dest">buffer to write result into</param>
  158. /// <returns>The length of the string on success (even if the buffer is too small). -1 is the key does not exist.</returns>
  159. private static int llama_model_meta_key_by_index(SafeLlamaModelHandle model, int index, Span<byte> dest)
  160. {
  161. unsafe
  162. {
  163. fixed (byte* destPtr = dest)
  164. {
  165. return llama_model_meta_key_by_index_native(model, index, destPtr, dest.Length);
  166. }
  167. }
  168. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "llama_model_meta_key_by_index")]
  169. static extern unsafe int llama_model_meta_key_by_index_native(SafeLlamaModelHandle model, int index, byte* buf, long buf_size);
  170. }
  171. /// <summary>
  172. /// Get metadata value as a string by index
  173. /// </summary>
  174. /// <param name="model">Model to fetch from</param>
  175. /// <param name="index">Index of val to fetch</param>
  176. /// <param name="dest">Buffer to write result into</param>
  177. /// <returns>The length of the string on success (even if the buffer is too small). -1 is the key does not exist.</returns>
  178. private static int llama_model_meta_val_str_by_index(SafeLlamaModelHandle model, int index, Span<byte> dest)
  179. {
  180. unsafe
  181. {
  182. fixed (byte* destPtr = dest)
  183. {
  184. return llama_model_meta_val_str_by_index_native(model, index, destPtr, dest.Length);
  185. }
  186. }
  187. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "llama_model_meta_val_str_by_index")]
  188. static extern unsafe int llama_model_meta_val_str_by_index_native(SafeLlamaModelHandle model, int index, byte* buf, long buf_size);
  189. }
  190. /// <summary>
  191. /// Get metadata value as a string by key name
  192. /// </summary>
  193. /// <param name="model"></param>
  194. /// <param name="key"></param>
  195. /// <param name="buf"></param>
  196. /// <param name="buf_size"></param>
  197. /// <returns>The length of the string on success, or -1 on failure</returns>
  198. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  199. public static extern unsafe int llama_model_meta_val_str(SafeLlamaModelHandle model, byte* key, byte* buf, long buf_size);
  200. /// <summary>
  201. /// Get the number of tokens in the model vocabulary
  202. /// </summary>
  203. /// <param name="model"></param>
  204. /// <returns></returns>
  205. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  206. private static extern int llama_n_vocab(SafeLlamaModelHandle model);
  207. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  208. private static extern LLamaVocabType llama_vocab_type(SafeLlamaModelHandle model);
  209. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  210. private static extern LLamaRopeType llama_rope_type(SafeLlamaModelHandle model);
  211. /// <summary>
  212. /// Get the size of the context window for the model
  213. /// </summary>
  214. /// <param name="model"></param>
  215. /// <returns></returns>
  216. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  217. private static extern int llama_n_ctx_train(SafeLlamaModelHandle model);
  218. /// <summary>
  219. /// Get the dimension of embedding vectors from this model
  220. /// </summary>
  221. /// <param name="model"></param>
  222. /// <returns></returns>
  223. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  224. private static extern int llama_n_embd(SafeLlamaModelHandle model);
  225. /// <summary>
  226. /// Get the number of layers in this model
  227. /// </summary>
  228. /// <param name="model"></param>
  229. /// <returns></returns>
  230. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  231. private static extern int llama_n_layers(SafeLlamaModelHandle model);
  232. /// <summary>
  233. /// Get a string describing the model type
  234. /// </summary>
  235. /// <param name="model"></param>
  236. /// <param name="buf"></param>
  237. /// <param name="buf_size"></param>
  238. /// <returns>The length of the string on success (even if the buffer is too small)., or -1 on failure</returns>
  239. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  240. private static extern unsafe int llama_model_desc(SafeLlamaModelHandle model, byte* buf, long buf_size);
  241. /// <summary>
  242. /// Get the size of the model in bytes
  243. /// </summary>
  244. /// <param name="model"></param>
  245. /// <returns>The size of the model</returns>
  246. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  247. private static extern ulong llama_model_size(SafeLlamaModelHandle model);
  248. /// <summary>
  249. /// Get the number of parameters in this model
  250. /// </summary>
  251. /// <param name="model"></param>
  252. /// <returns>The functions return the length of the string on success, or -1 on failure</returns>
  253. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  254. private static extern ulong llama_model_n_params(SafeLlamaModelHandle model);
  255. /// <summary>
  256. /// Get the model's RoPE frequency scaling factor
  257. /// </summary>
  258. /// <param name="model"></param>
  259. /// <returns></returns>
  260. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  261. private static extern float llama_rope_freq_scale_train(SafeLlamaModelHandle model);
  262. /// <summary>
  263. /// Get the "Beginning of sentence" token
  264. /// </summary>
  265. /// <returns></returns>
  266. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  267. private static extern LLamaToken llama_token_bos(SafeLlamaModelHandle model);
  268. /// <summary>
  269. /// Get the "End of sentence" token
  270. /// </summary>
  271. /// <returns></returns>
  272. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  273. private static extern LLamaToken llama_token_eos(SafeLlamaModelHandle model);
  274. /// <summary>
  275. /// Get the "classification" token
  276. /// </summary>
  277. /// <returns></returns>
  278. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  279. private static extern LLamaToken llama_token_cls(SafeLlamaModelHandle model);
  280. /// <summary>
  281. /// Get the "sentence separator" token
  282. /// </summary>
  283. /// <returns></returns>
  284. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  285. private static extern LLamaToken llama_token_sep(SafeLlamaModelHandle model);
  286. /// <summary>
  287. /// Get the "new line" token
  288. /// </summary>
  289. /// <returns></returns>
  290. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  291. private static extern LLamaToken llama_token_nl(SafeLlamaModelHandle model);
  292. /// <summary>
  293. /// codellama infill tokens, Beginning of infill prefix
  294. /// </summary>
  295. /// <returns></returns>
  296. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  297. private static extern int llama_token_prefix(SafeLlamaModelHandle model);
  298. /// <summary>
  299. /// codellama infill tokens, Beginning of infill middle
  300. /// </summary>
  301. /// <returns></returns>
  302. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  303. private static extern int llama_token_middle(SafeLlamaModelHandle model);
  304. /// <summary>
  305. /// codellama infill tokens, Beginning of infill suffix
  306. /// </summary>
  307. /// <returns></returns>
  308. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  309. private static extern int llama_token_suffix(SafeLlamaModelHandle model);
  310. /// <summary>
  311. /// codellama infill tokens, End of infill middle
  312. /// </summary>
  313. /// <returns></returns>
  314. [DllImport(NativeApi.libraryName, CallingConvention = CallingConvention.Cdecl)]
  315. private static extern int llama_token_eot(SafeLlamaModelHandle model);
  316. #endregion
  317. #region LoRA
  318. /// <summary>
  319. /// Apply a LoRA adapter to a loaded model
  320. /// </summary>
  321. /// <param name="lora"></param>
  322. /// <param name="scale"></param>
  323. /// <param name="modelBase">A path to a higher quality model to use as a base for the layers modified by the
  324. /// adapter. Can be NULL to use the current loaded model.</param>
  325. /// <param name="threads"></param>
  326. /// <exception cref="RuntimeError"></exception>
  327. public void ApplyLoraFromFile(string lora, float scale, string? modelBase = null, int? threads = null)
  328. {
  329. // Try to open the model file, this will check:
  330. // - File exists (automatically throws FileNotFoundException)
  331. // - File is readable (explicit check)
  332. // This provides better error messages that llama.cpp, which would throw an access violation exception in both cases.
  333. using (var fs = new FileStream(lora, FileMode.Open))
  334. if (!fs.CanRead)
  335. throw new InvalidOperationException($"LoRA file '{lora}' is not readable");
  336. var err = llama_model_apply_lora_from_file(
  337. this,
  338. lora,
  339. scale,
  340. string.IsNullOrEmpty(modelBase) ? null : modelBase,
  341. threads ?? Math.Max(1, Environment.ProcessorCount / 2)
  342. );
  343. if (err != 0)
  344. throw new RuntimeError($"Failed to apply lora adapter (err={err}).");
  345. }
  346. #endregion
  347. #region tokenize
  348. /// <summary>
  349. /// Convert a single llama token into bytes
  350. /// </summary>
  351. /// <param name="token">Token to decode</param>
  352. /// <param name="dest">A span to attempt to write into. If this is too small nothing will be written</param>
  353. /// <returns>The size of this token. **nothing will be written** if this is larger than `dest`</returns>
  354. public uint TokenToSpan(LLamaToken token, Span<byte> dest)
  355. {
  356. var length = NativeApi.llama_token_to_piece(this, token, dest);
  357. return (uint)Math.Abs(length);
  358. }
  359. /// <summary>
  360. /// Convert a sequence of tokens into characters.
  361. /// </summary>
  362. /// <param name="tokens"></param>
  363. /// <param name="dest"></param>
  364. /// <param name="encoding"></param>
  365. /// <returns>The section of the span which has valid data in it.
  366. /// If there was insufficient space in the output span this will be
  367. /// filled with as many characters as possible, starting from the _last_ token.
  368. /// </returns>
  369. [Obsolete("Use a StreamingTokenDecoder instead")]
  370. internal Span<char> TokensToSpan(IReadOnlyList<LLamaToken> tokens, Span<char> dest, Encoding encoding)
  371. {
  372. var decoder = new StreamingTokenDecoder(encoding, this);
  373. decoder.AddRange(tokens);
  374. var str = decoder.Read();
  375. if (str.Length < dest.Length)
  376. {
  377. str.AsSpan().CopyTo(dest);
  378. return dest.Slice(0, str.Length);
  379. }
  380. else
  381. {
  382. str.AsSpan().Slice(str.Length - dest.Length).CopyTo(dest);
  383. return dest;
  384. }
  385. }
  386. /// <summary>
  387. /// Convert a string of text into tokens
  388. /// </summary>
  389. /// <param name="text"></param>
  390. /// <param name="add_bos"></param>
  391. /// <param name="encoding"></param>
  392. /// <param name="special">Allow tokenizing special and/or control tokens which otherwise are not exposed and treated as plaintext.</param>
  393. /// <returns></returns>
  394. public LLamaToken[] Tokenize(string text, bool add_bos, bool special, Encoding encoding)
  395. {
  396. // Early exit if there's no work to do
  397. if (text == "" && !add_bos)
  398. return Array.Empty<LLamaToken>();
  399. // Convert string to bytes, adding one extra byte to the end (null terminator)
  400. var bytesCount = encoding.GetByteCount(text);
  401. var bytes = ArrayPool<byte>.Shared.Rent(bytesCount + 1);
  402. try
  403. {
  404. unsafe
  405. {
  406. fixed (char* textPtr = text)
  407. fixed (byte* bytesPtr = bytes)
  408. {
  409. // Convert text into bytes
  410. encoding.GetBytes(textPtr, text.Length, bytesPtr, bytes.Length);
  411. // Tokenize once with no output, to get the token count. Output will be negative (indicating that there was insufficient space)
  412. var count = -NativeApi.llama_tokenize(this, bytesPtr, bytesCount, (LLamaToken*)IntPtr.Zero, 0, add_bos, special);
  413. // Tokenize again, this time outputting into an array of exactly the right size
  414. var tokens = new LLamaToken[count];
  415. fixed (LLamaToken* tokensPtr = tokens)
  416. {
  417. NativeApi.llama_tokenize(this, bytesPtr, bytesCount, tokensPtr, count, add_bos, special);
  418. return tokens;
  419. }
  420. }
  421. }
  422. }
  423. finally
  424. {
  425. ArrayPool<byte>.Shared.Return(bytes, true);
  426. }
  427. }
  428. #endregion
  429. #region context
  430. /// <summary>
  431. /// Create a new context for this model
  432. /// </summary>
  433. /// <param name="params"></param>
  434. /// <returns></returns>
  435. public SafeLLamaContextHandle CreateContext(LLamaContextParams @params)
  436. {
  437. return SafeLLamaContextHandle.Create(this, @params);
  438. }
  439. #endregion
  440. #region metadata
  441. /// <summary>
  442. /// Get the metadata key for the given index
  443. /// </summary>
  444. /// <param name="index">The index to get</param>
  445. /// <returns>The key, null if there is no such key or if the buffer was too small</returns>
  446. public Memory<byte>? MetadataKeyByIndex(int index)
  447. {
  448. // Check if the key exists, without getting any bytes of data
  449. var keyLength = llama_model_meta_key_by_index(this, index, Array.Empty<byte>());
  450. if (keyLength < 0)
  451. return null;
  452. // get a buffer large enough to hold it
  453. var buffer = new byte[keyLength + 1];
  454. keyLength = llama_model_meta_key_by_index(this, index, buffer);
  455. Debug.Assert(keyLength >= 0);
  456. return buffer.AsMemory().Slice(0, keyLength);
  457. }
  458. /// <summary>
  459. /// Get the metadata value for the given index
  460. /// </summary>
  461. /// <param name="index">The index to get</param>
  462. /// <returns>The value, null if there is no such value or if the buffer was too small</returns>
  463. public Memory<byte>? MetadataValueByIndex(int index)
  464. {
  465. // Check if the key exists, without getting any bytes of data
  466. var valueLength = llama_model_meta_val_str_by_index(this, index, Array.Empty<byte>());
  467. if (valueLength < 0)
  468. return null;
  469. // get a buffer large enough to hold it
  470. var buffer = new byte[valueLength + 1];
  471. valueLength = llama_model_meta_val_str_by_index(this, index, buffer);
  472. Debug.Assert(valueLength >= 0);
  473. return buffer.AsMemory().Slice(0, valueLength);
  474. }
  475. internal IReadOnlyDictionary<string, string> ReadMetadata()
  476. {
  477. var result = new Dictionary<string, string>();
  478. for (var i = 0; i < MetadataCount; i++)
  479. {
  480. var keyBytes = MetadataKeyByIndex(i);
  481. if (keyBytes == null)
  482. continue;
  483. var key = Encoding.UTF8.GetStringFromSpan(keyBytes.Value.Span);
  484. var valBytes = MetadataValueByIndex(i);
  485. if (valBytes == null)
  486. continue;
  487. var val = Encoding.UTF8.GetStringFromSpan(valBytes.Value.Span);
  488. result[key] = val;
  489. }
  490. return result;
  491. }
  492. #endregion
  493. /// <summary>
  494. /// Get tokens for a model
  495. /// </summary>
  496. public class ModelTokens
  497. {
  498. private readonly SafeLlamaModelHandle _model;
  499. internal ModelTokens(SafeLlamaModelHandle model)
  500. {
  501. _model = model;
  502. }
  503. private static LLamaToken? Normalize(LLamaToken token)
  504. {
  505. return token == -1 ? null : token;
  506. }
  507. /// <summary>
  508. /// Get the Beginning of Sentence token for this model
  509. /// </summary>
  510. public LLamaToken? BOS => Normalize(llama_token_bos(_model));
  511. /// <summary>
  512. /// Get the End of Sentence token for this model
  513. /// </summary>
  514. public LLamaToken? EOS => Normalize(llama_token_eos(_model));
  515. /// <summary>
  516. /// Get the newline token for this model
  517. /// </summary>
  518. public LLamaToken? Newline => Normalize(llama_token_nl(_model));
  519. /// <summary>
  520. /// Get the classification token for this model
  521. /// </summary>
  522. public LLamaToken? CLS => Normalize(llama_token_cls(_model));
  523. /// <summary>
  524. /// Get the sentence separator token for this model
  525. /// </summary>
  526. public LLamaToken? SEP => Normalize(llama_token_sep(_model));
  527. /// <summary>
  528. /// Codellama beginning of infill prefix
  529. /// </summary>
  530. public LLamaToken? InfillPrefix => Normalize(llama_token_prefix(_model));
  531. /// <summary>
  532. /// Codellama beginning of infill middle
  533. /// </summary>
  534. public LLamaToken? InfillMiddle => Normalize(llama_token_middle(_model));
  535. /// <summary>
  536. /// Codellama beginning of infill suffix
  537. /// </summary>
  538. public LLamaToken? InfillSuffix => Normalize(llama_token_suffix(_model));
  539. /// <summary>
  540. /// Codellama end of infill middle
  541. /// </summary>
  542. public LLamaToken? EOT => Normalize(llama_token_eot(_model));
  543. }
  544. }
  545. }