LLamaSharp/LLama/LLamaEmbedder.cs

100 lines
2.9 KiB
C#
Raw Normal View History

using LLama.Native;
using System;
using LLama.Exceptions;
2023-08-06 06:44:54 +08:00
using LLama.Abstractions;
2023-06-11 05:44:21 +08:00
namespace LLama
{
2023-06-20 02:38:57 +08:00
/// <summary>
/// The embedder for LLama, which supports getting embeddings from text.
/// </summary>
public sealed class LLamaEmbedder
2023-08-09 08:07:42 +08:00
: IDisposable
{
private readonly LLamaContext _ctx;
2023-08-09 08:07:42 +08:00
/// <summary>
/// Dimension of embedding vectors
/// </summary>
public int EmbeddingSize => _ctx.EmbeddingSize;
2023-06-19 02:53:21 +08:00
/// <summary>
///
/// </summary>
/// <param name="params"></param>
2023-08-06 06:44:54 +08:00
public LLamaEmbedder(IModelParams @params)
{
2023-06-11 05:44:21 +08:00
@params.EmbeddingMode = true;
using var weights = LLamaWeights.LoadFromFile(@params);
_ctx = weights.CreateContext(@params);
}
2023-08-31 21:19:29 +08:00
public LLamaEmbedder(LLamaWeights weights, IModelParams @params)
2023-08-31 16:24:44 +08:00
{
2023-08-31 21:19:29 +08:00
_ctx = weights.CreateContext(@params);
2023-08-31 16:24:44 +08:00
}
2023-06-11 05:44:21 +08:00
/// <summary>
/// Get the embeddings of the text.
/// </summary>
/// <param name="text"></param>
/// <param name="threads">unused</param>
2023-06-11 05:44:21 +08:00
/// <param name="addBos">Add bos to the text.</param>
/// <param name="encoding">unused</param>
2023-06-11 05:44:21 +08:00
/// <returns></returns>
/// <exception cref="RuntimeError"></exception>
[Obsolete("'threads' and 'encoding' parameters are no longer used")]
// ReSharper disable once MethodOverloadWithOptionalParameter
public float[] GetEmbeddings(string text, int threads = -1, bool addBos = true, string encoding = "UTF-8")
{
return GetEmbeddings(text, addBos);
}
/// <summary>
/// Get the embeddings of the text.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
/// <exception cref="RuntimeError"></exception>
public float[] GetEmbeddings(string text)
{
return GetEmbeddings(text, true);
}
/// <summary>
/// Get the embeddings of the text.
/// </summary>
/// <param name="text"></param>
/// <param name="addBos">Add bos to the text.</param>
/// <returns></returns>
/// <exception cref="RuntimeError"></exception>
public float[] GetEmbeddings(string text, bool addBos)
{
var embed_inp_array = _ctx.Tokenize(text, addBos);
// TODO(Rinne): deal with log of prompt
if (embed_inp_array.Length > 0)
_ctx.Eval(embed_inp_array, 0);
unsafe
{
var embeddings = NativeApi.llama_get_embeddings(_ctx.NativeHandle);
if (embeddings == null)
return Array.Empty<float>();
return new Span<float>(embeddings, EmbeddingSize).ToArray();
}
}
2023-05-16 02:51:02 +08:00
2023-06-19 02:53:21 +08:00
/// <summary>
///
/// </summary>
2023-05-16 02:51:02 +08:00
public void Dispose()
{
_ctx.Dispose();
}
}
}