|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.IO; |
| 4 | +using System.Linq; |
| 5 | +using System.Text; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using System.Xml.Linq; |
| 9 | +using LLama.Abstractions; |
| 10 | +using LLama.Exceptions; |
| 11 | +using LLama.Native; |
| 12 | +using Microsoft.Extensions.Logging; |
| 13 | + |
| 14 | +namespace LLama; |
| 15 | + |
| 16 | +/// <summary> |
| 17 | +/// Get rank scores between prompt and documents |
| 18 | +/// </summary> |
| 19 | +public sealed partial class LLamaReranker |
| 20 | + : IDisposable |
| 21 | +{ |
| 22 | + /// <summary> |
| 23 | + /// Dimension of embedding vectors |
| 24 | + /// </summary> |
| 25 | + public int EmbeddingSize => Context.EmbeddingSize; |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// LLama Context |
| 29 | + /// </summary> |
| 30 | + public LLamaContext Context { get; } |
| 31 | + |
| 32 | + /// <summary> |
| 33 | + /// Create a new reranker, using the given LLamaWeights |
| 34 | + /// </summary> |
| 35 | + /// <param name="weights"></param> |
| 36 | + /// <param name="params"></param> |
| 37 | + /// <param name="logger"></param> |
| 38 | + public LLamaReranker(LLamaWeights weights, IContextParams @params, ILogger? logger = null) |
| 39 | + { |
| 40 | + if (@params.UBatchSize != @params.BatchSize) |
| 41 | + throw new ArgumentException("For non-causal models, batch size must be equal to ubatch size", nameof(@params)); |
| 42 | + if (weights.NativeHandle is { HasEncoder: true, HasDecoder: true }) |
| 43 | + throw new NotSupportedException("Computing rank in encoder-decoder models is not supported"); |
| 44 | + if (@params.PoolingType != LLamaPoolingType.Rank) |
| 45 | + throw new NotSupportedException("Computing rank score, PoolingType must be equal to LLamaPoolingType.Rank"); |
| 46 | + Context = weights.CreateContext(@params, logger); |
| 47 | + NativeApi.llama_set_embeddings(Context.NativeHandle, true); |
| 48 | + } |
| 49 | + |
| 50 | + /// <inheritdoc /> |
| 51 | + public void Dispose() |
| 52 | + { |
| 53 | + Context.Dispose(); |
| 54 | + } |
| 55 | + |
| 56 | + /// <summary> |
| 57 | + /// Retrieve relevance scores for input and documents by reranking, execute once. |
| 58 | + /// </summary> |
| 59 | + /// <param name="input"></param> |
| 60 | + /// <param name="documents"></param> |
| 61 | + /// <param name="normalize">Whether to normalize the score to the range (0, 1)</param> |
| 62 | + /// <param name="cancellationToken"></param> |
| 63 | + /// <returns></returns> |
| 64 | + /// <exception cref="RuntimeError"></exception> |
| 65 | + /// <exception cref="NotSupportedException"></exception> |
| 66 | + public async Task<IReadOnlyList<float>> GetRelevanceScores(string input, IReadOnlyList<string> documents, bool normalize = false, CancellationToken cancellationToken = default) |
| 67 | + { |
| 68 | + List<float> scores = new List<float>(documents.Count); |
| 69 | + var inputTokens = Context.Tokenize(input); |
| 70 | + var batch = new LLamaBatch(); |
| 71 | + var clearFlag = 0; |
| 72 | + |
| 73 | + for(var idx = 0; idx < documents.Count; idx++) |
| 74 | + { |
| 75 | + var docTokens = Context.Tokenize(documents[idx] ?? ""); |
| 76 | + LLamaToken[] tokens = [.. inputTokens, .. docTokens]; |
| 77 | + |
| 78 | + if (batch.TokenCount + tokens.Length > Context.ContextSize) |
| 79 | + { |
| 80 | + scores.AddRange(await CalcRelevanceScores(batch, normalize, cancellationToken)); |
| 81 | + batch.Clear(); |
| 82 | + clearFlag = idx; |
| 83 | + } |
| 84 | + |
| 85 | + for (var i = 0; i < tokens.Length; i++) |
| 86 | + batch.Add(tokens[i], i, (LLamaSeqId)(idx - clearFlag), true); |
| 87 | + } |
| 88 | + if (batch.LogitPositionCount > 0) |
| 89 | + { |
| 90 | + scores.AddRange(await CalcRelevanceScores(batch, normalize, cancellationToken)); |
| 91 | + batch.Clear(); |
| 92 | + } |
| 93 | + |
| 94 | + return scores; |
| 95 | + } |
| 96 | + |
| 97 | + /// <summary> |
| 98 | + /// Retrieve relevance score for input and document by reranking |
| 99 | + /// </summary> |
| 100 | + /// <param name="input"></param> |
| 101 | + /// <param name="document"></param> |
| 102 | + /// <param name="cancellationToken"></param> |
| 103 | + /// <param name="normalize">Whether to normalize the score to the range (0, 1)</param> |
| 104 | + /// <returns></returns> |
| 105 | + /// <exception cref="RuntimeError"></exception> |
| 106 | + /// <exception cref="NotSupportedException"></exception> |
| 107 | + public async Task<(float Score, int Tokens)> GetRelevanceScoreWithTokenCount(string input, string document, bool normalize = false, CancellationToken cancellationToken = default) |
| 108 | + { |
| 109 | + var inputTokens = Context.Tokenize(input); |
| 110 | + var docTokens = Context.Tokenize(document); |
| 111 | + LLamaToken[] tokens = [..inputTokens, ..docTokens]; |
| 112 | + var batch = new LLamaBatch(); |
| 113 | + for (var i = 0; i < tokens.Length; i++) |
| 114 | + batch.Add(tokens[i], i, LLamaSeqId.Zero, true); |
| 115 | + |
| 116 | + // clear previous kv_cache values |
| 117 | + Context.NativeHandle.KvCacheClear(); |
| 118 | + |
| 119 | + // Check if we should cancel the work, just before doing anything expensive (encode/decode) |
| 120 | + cancellationToken.ThrowIfCancellationRequested(); |
| 121 | + |
| 122 | + // Run model |
| 123 | + switch (Context.NativeHandle.ModelHandle.HasEncoder, Context.NativeHandle.ModelHandle.HasDecoder) |
| 124 | + { |
| 125 | + case (true, false): |
| 126 | + { |
| 127 | + var result = await Context.EncodeAsync(batch, cancellationToken); |
| 128 | + if (result != EncodeResult.Ok) |
| 129 | + throw new RuntimeError($"Failed to encode: {result}"); |
| 130 | + break; |
| 131 | + } |
| 132 | + |
| 133 | + case (false, true): |
| 134 | + { |
| 135 | + var result = await Context.DecodeAsync(batch, cancellationToken); |
| 136 | + if (result != DecodeResult.Ok) |
| 137 | + throw new RuntimeError($"Failed to decode: {result}"); |
| 138 | + break; |
| 139 | + } |
| 140 | + |
| 141 | + default: |
| 142 | + throw new NotSupportedException("Unsupported model type"); |
| 143 | + } |
| 144 | + |
| 145 | + var score = Context.NativeHandle.GetEmbeddingsSeq(LLamaSeqId.Zero)[0]; |
| 146 | + |
| 147 | + Context.NativeHandle.KvCacheClear(); |
| 148 | + |
| 149 | + return (normalize ? Sigmoid(score) : score, tokens.Length); |
| 150 | + } |
| 151 | + |
| 152 | + private async Task<IReadOnlyList<float>> CalcRelevanceScores(LLamaBatch batch, bool normalize = false, CancellationToken cancellationToken = default) |
| 153 | + { |
| 154 | + var (logicCap, _) = batch.GetLogitPositions()[batch.LogitPositionCount - 1]; |
| 155 | + var seqNum = logicCap.Value + 1; |
| 156 | + List<float> scores = new List<float>(seqNum); |
| 157 | + // clear previous kv_cache values |
| 158 | + Context.NativeHandle.KvCacheClear(); |
| 159 | + |
| 160 | + // Check if we should cancel the work, just before doing anything expensive (encode/decode) |
| 161 | + cancellationToken.ThrowIfCancellationRequested(); |
| 162 | + |
| 163 | + // Run model |
| 164 | + switch (Context.NativeHandle.ModelHandle.HasEncoder, Context.NativeHandle.ModelHandle.HasDecoder) |
| 165 | + { |
| 166 | + case (true, false): |
| 167 | + { |
| 168 | + var result = await Context.EncodeAsync(batch, cancellationToken); |
| 169 | + if (result != EncodeResult.Ok) |
| 170 | + throw new RuntimeError($"Failed to encode: {result}"); |
| 171 | + break; |
| 172 | + } |
| 173 | + |
| 174 | + case (false, true): |
| 175 | + { |
| 176 | + var result = await Context.DecodeAsync(batch, cancellationToken); |
| 177 | + if (result != DecodeResult.Ok) |
| 178 | + throw new RuntimeError($"Failed to decode: {result}"); |
| 179 | + break; |
| 180 | + } |
| 181 | + |
| 182 | + default: |
| 183 | + throw new NotSupportedException("Unsupported model type"); |
| 184 | + } |
| 185 | + |
| 186 | + for (var seq = 0; seq < seqNum; seq++) |
| 187 | + { |
| 188 | + var score = Context.NativeHandle.GetEmbeddingsSeq((LLamaSeqId)seq)[0]; |
| 189 | + scores.Add(normalize ? Sigmoid(score) : score); |
| 190 | + } |
| 191 | + |
| 192 | + Context.NativeHandle.KvCacheClear(); |
| 193 | + |
| 194 | + return scores; |
| 195 | + } |
| 196 | + |
| 197 | + private float Sigmoid(float x) |
| 198 | + { |
| 199 | + return (float)(1 / (1 + Math.Exp(-x))); |
| 200 | + } |
| 201 | +} |
0 commit comments