-
-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathLlamaRankingContext.ts
269 lines (224 loc) · 9.93 KB
/
LlamaRankingContext.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import {AsyncDisposeAggregator, EventRelay, withLock} from "lifecycle-utils";
import {Token} from "../types.js";
import {LlamaText} from "../utils/LlamaText.js";
import {tokenizeInput} from "../utils/tokenizeInput.js";
import type {LlamaModel} from "./LlamaModel/LlamaModel.js";
import type {LlamaContext, LlamaContextSequence} from "./LlamaContext/LlamaContext.js";
import type {GgufTensorInfo} from "../gguf/types/GgufTensorInfoTypes.js";
export type LlamaRankingContextOptions = {
/**
* The number of tokens the model can see at once.
* - **`"auto"`** - adapt to the current VRAM state and attemp to set the context size as high as possible up to the size
* the model was trained on.
* - **`number`** - set the context size to a specific number of tokens.
* If there's not enough VRAM, an error will be thrown.
* Use with caution.
* - **`{min?: number, max?: number}`** - adapt to the current VRAM state and attemp to set the context size as high as possible
* up to the size the model was trained on, but at least `min` and at most `max`.
*
* Defaults to `"auto"`.
*/
contextSize?: "auto" | number | {
min?: number,
max?: number
},
/** prompt processing batch size */
batchSize?: number,
/**
* number of threads to use to evaluate tokens.
* set to 0 to use the maximum threads supported by the current machine hardware
*/
threads?: number,
/** An abort signal to abort the context creation */
createSignal?: AbortSignal,
/**
* Ignore insufficient memory errors and continue with the context creation.
* Can cause the process to crash if there's not enough VRAM for the new context.
*
* Defaults to `false`.
*/
ignoreMemorySafetyChecks?: boolean
};
/**
* @see [Reranking Documents](https://node-llama-cpp.withcat.ai/guide/embedding#reranking) tutorial
*/
export class LlamaRankingContext {
/** @internal */ private readonly _llamaContext: LlamaContext;
/** @internal */ private readonly _sequence: LlamaContextSequence;
/** @internal */ private readonly _disposeAggregator = new AsyncDisposeAggregator();
public readonly onDispose = new EventRelay<void>();
private constructor({
_llamaContext
}: {
_llamaContext: LlamaContext
}) {
this._llamaContext = _llamaContext;
this._sequence = this._llamaContext.getSequence();
this._disposeAggregator.add(
this._llamaContext.onDispose.createListener(() => {
void this._disposeAggregator.dispose();
})
);
this._disposeAggregator.add(this.onDispose.dispatchEvent);
this._disposeAggregator.add(async () => {
await this._llamaContext.dispose();
});
}
/**
* Get the ranking score for a document for a query.
*
* A ranking score is a number between 0 and 1 representing the probability that the document is relevant to the query.
* @returns a ranking score between 0 and 1 representing the probability that the document is relevant to the query.
*/
public async rank(query: Token[] | string | LlamaText, document: Token[] | string | LlamaText) {
if (this.model.tokens.bos == null || this.model.tokens.eos == null || this.model.tokens.sep == null)
throw new Error("Computing rankings is not supported for this model.");
const resolvedInput = this._getEvaluationInput(query, document);
if (resolvedInput.length > this._llamaContext.contextSize)
throw new Error(
"The input length exceed the context size. " +
`Try to increase the context size to at least ${resolvedInput.length + 1} ` +
"or use another model that supports longer contexts."
);
return this._evaluateRankingForInput(resolvedInput);
}
/**
* Get the ranking scores for all the given documents for a query.
*
* A ranking score is a number between 0 and 1 representing the probability that the document is relevant to the query.
* @returns an array of ranking scores between 0 and 1 representing the probability that the document is relevant to the query.
*/
public async rankAll(query: Token[] | string | LlamaText, documents: Array<Token[] | string | LlamaText>): Promise<number[]> {
const resolvedTokens = documents.map((document) => this._getEvaluationInput(query, document));
const maxInputTokensLength = resolvedTokens.reduce((max, tokens) => Math.max(max, tokens.length), 0);
if (maxInputTokensLength > this._llamaContext.contextSize)
throw new Error(
"The input lengths of some of the given documents exceed the context size. " +
`Try to increase the context size to at least ${maxInputTokensLength + 1} ` +
"or use another model that supports longer contexts."
);
else if (resolvedTokens.length === 0)
return [];
return await Promise.all(
resolvedTokens.map((tokens) => this._evaluateRankingForInput(tokens))
);
}
/**
* Get the ranking scores for all the given documents for a query and sort them by score from highest to lowest.
*
* A ranking score is a number between 0 and 1 representing the probability that the document is relevant to the query.
*/
public async rankAndSort<const T extends string>(query: Token[] | string | LlamaText, documents: T[]): Promise<Array<{
document: T,
/**
* A ranking score is a number between 0 and 1 representing the probability that the document is relevant to the query.
*/
score: number
}>> {
const scores = await this.rankAll(query, documents);
return documents
.map((document, index) => ({document: document as T, score: scores[index]!}))
.sort((a, b) => b.score - a.score);
}
public async dispose() {
await this._disposeAggregator.dispose();
}
/** @hidden */
public [Symbol.asyncDispose]() {
return this.dispose();
}
public get disposed() {
return this._llamaContext.disposed;
}
public get model() {
return this._llamaContext.model;
}
/** @internal */
private _getEvaluationInput(query: Token[] | string | LlamaText, document: Token[] | string | LlamaText) {
if (this.model.tokens.bos == null || this.model.tokens.eos == null || this.model.tokens.sep == null)
throw new Error("Computing rankings is not supported for this model.");
const resolvedQuery = tokenizeInput(query, this._llamaContext.model.tokenizer, "trimLeadingSpace", false);
const resolvedDocument = tokenizeInput(document, this._llamaContext.model.tokenizer, "trimLeadingSpace", false);
if (resolvedQuery.length === 0 && resolvedDocument.length === 0)
return [];
const resolvedInput = [
this.model.tokens.bos,
...resolvedQuery,
this.model.tokens.eos,
this.model.tokens.sep,
...resolvedDocument,
this.model.tokens.eos
];
return resolvedInput;
}
/** @internal */
private _evaluateRankingForInput(input: Token[]): Promise<number> {
if (input.length === 0)
return Promise.resolve(0);
return withLock(this, "evaluate", async () => {
await this._sequence.eraseContextTokenRanges([{
start: 0,
end: this._sequence.nextTokenIndex
}]);
const iterator = this._sequence.evaluate(input, {_noSampling: true});
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for await (const token of iterator) {
break; // only generate one token to get embeddings
}
const embedding = this._llamaContext._ctx.getEmbedding(input.length, 1);
if (embedding.length === 0)
return 0;
const logit = embedding[0]!;
const probability = logitToSigmoid(logit);
return probability;
});
}
/** @internal */
public static async _create({
_model
}: {
_model: LlamaModel
}, {
contextSize,
batchSize,
threads = 6,
createSignal,
ignoreMemorySafetyChecks
}: LlamaRankingContextOptions) {
const tensorInfo = _model.fileInfo.tensorInfo;
if (_model.tokens.bos == null || _model.tokens.eos == null || _model.tokens.sep == null)
throw new Error("Computing rankings is not supported for this model.");
// source: `append_pooling` in `llama.cpp`
if (findLayer(tensorInfo, "cls", "weight") == null || findLayer(tensorInfo, "cls", "bias") == null)
throw new Error("Computing rankings is not supported for this model.");
// source: `append_pooling` in `llama.cpp`
if (findLayer(tensorInfo, "cls.output", "weight") != null && findLayer(tensorInfo, "cls.output", "bias") == null)
throw new Error("Computing rankings is not supported for this model.");
if (_model.fileInsights.hasEncoder && _model.fileInsights.hasDecoder)
throw new Error("Computing rankings is not supported for encoder-decoder models.");
const llamaContext = await _model.createContext({
contextSize,
batchSize,
threads,
createSignal,
ignoreMemorySafetyChecks,
_embeddings: true,
_ranking: true
});
return new LlamaRankingContext({
_llamaContext: llamaContext
});
}
}
function findLayer(tensorInfo: GgufTensorInfo[] | undefined, name: string, suffix: string) {
if (tensorInfo == null)
return undefined;
for (const tensor of tensorInfo) {
if (tensor.name === name + "." + suffix)
return tensor;
}
return undefined;
}
function logitToSigmoid(logit: number) {
return 1 / (1 + Math.exp(-logit));
}