You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit cf769c4
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: docs/text/RERANKING.md
+23-8Lines changed: 23 additions & 8 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -64,18 +64,22 @@ new LocalCrossEncoderReranker({
64
64
modelFileName: 'model', // onnx/model.onnx; unset: the model's default file
65
65
cacheDir: '/var/cache/agentos-models', // Transformers.js's own cache when unset
66
66
device: 'cpu', // the default
67
+
intraOpNumThreads: 2, // threads per operator; unset: onnxruntime sizes its pool for the machine
68
+
pieceMaxChars: 300, // score long passages by their best piece; unset: one pair per passage
67
69
});
68
70
```
69
71
70
72
- Needs Transformers.js: `@huggingface/transformers` 3.x, an optional dependency of the package, else `@xenova/transformers` 2.x. `isAvailable()` answers whether one of them imports; `rerank()` throws when neither does.
71
73
-`LOCAL_RERANKER_MODELS` lists five Hugging Face model ids: `cross-encoder/ms-marco-MiniLM-L-6-v2`, `cross-encoder/ms-marco-MiniLM-L-12-v2`, `BAAI/bge-reranker-base`, `BAAI/bge-reranker-large` and `sentence-transformers/ce-ms-marco-TinyBERT-L-4`.
72
-
- The model loads on the first `rerank()` (or `initialize(modelId)`) as a tokenizer (`AutoTokenizer`) and a sequence-classification model (`AutoModelForSequenceClassification`), and serves every later request. A request's `modelId` picks the model only on that first load; `initialize(otherModelId)` loads another. `dispose()` unloads it. Loads and unloads run one at a time in the order asked, so concurrent `initialize()` calls never load two models at once and the last one asked for stays loaded. A `rerank()` already running scores all its batches with the model it started with; a model replaced or unloaded meanwhile is disposed when the last rerank using it ends.
73
-
- What loads: the model's `config.json`, `tokenizer.json` and `tokenizer_config.json`, and one ONNX file from its `onnx/` folder, `onnx/<modelFileName><dtype suffix>.onnx`. With neither `modelFileName` nor `dtype` set, a model listed in `LOCAL_RERANKER_DEFAULT_WEIGHTS` loads the file named there and any other model loads `onnx/model.onnx` (full precision). The default model loads `onnx/model_quint8_avx2.onnx`, the repository's 8-bit dynamically quantized file (22 MB, against 87 MB for `onnx/model.onnx`): it ranks as the full-precision file does and scores a batch in about half the time on a 2-vCPU x86 host. On an ARM host, name `model_qint8_arm64`; for full precision, name `model`.
74
-
-`dtype` (Transformers.js 3.x) adds a suffix to the file name: `'fp32'` (the default) none, `'q8'``_quantized`, `'fp16'``_fp16`, `'int8'``_int8`, `'uint8'``_uint8`, `'q4'``_q4`, `'bnb4'``_bnb4`, `'q4f16'``_q4f16`. The `cross-encoder/*` repositories hold no `onnx/model_quantized.onnx`, so `dtype: 'q8'` fails to load there; name their quantized files with `modelFileName`.
75
-
- Each batch of up to `batchSize` passages is tokenized as (query, passage) pairs, padded and cut to `maxSequenceLength` tokens (a long pair loses the end of its passage), and scored in one forward pass: 20 passages at the default `batchSize` are one pass.
74
+
- The model loads on the first `rerank()` (or `initialize(modelId)`) as a tokenizer (`AutoTokenizer`) and a sequence-classification model (`AutoModelForSequenceClassification`), and serves every later request. A request's `modelId` picks the model only on that first load; `initialize(otherModelId)` loads another, and `initialize()` with no id loads `defaultModelId` in place of any other model loaded. `dispose()` unloads it. Loads and unloads run one at a time in the order asked, so concurrent `initialize()` calls never load two models at once and the last one asked for stays loaded. A `rerank()` already running scores all its batches with the model it started with; a model replaced or unloaded meanwhile is disposed when the last rerank using it ends.
75
+
- What loads: the model's `config.json`, `tokenizer.json` and `tokenizer_config.json`, and one ONNX file from its `onnx/` folder, `onnx/<modelFileName><dtype suffix>.onnx`. `modelFileName` takes the bare name (`'model_quint8_avx2'`), a path in that folder (`'onnx/model_quint8_avx2.onnx'`) or the name with `.onnx`; all three load `onnx/model_quint8_avx2.onnx`. With neither `modelFileName` nor `dtype` set, a model listed in `LOCAL_RERANKER_DEFAULT_WEIGHTS` loads the file named there and any other model loads `onnx/model.onnx` (full precision). The default model loads `onnx/model_quint8_avx2.onnx`, the repository's 8-bit dynamically quantized file (22 MB, against 87 MB for `onnx/model.onnx`): it ranks as the full-precision file does and scores a batch in about half the time on a 2-vCPU x86 host. It loads and runs on ARM hosts too; the repository also holds `onnx/model_qint8_arm64.onnx`, the file quantized for ARM, which `modelFileName: 'model_qint8_arm64'` names. For full precision, name `model`.
76
+
-`dtype` (Transformers.js 3.x) adds a suffix to the file name: `'fp32'` (the default) none, `'q8'``_quantized`, `'fp16'``_fp16`, `'int8'``_int8`, `'uint8'``_uint8`, `'q4'``_q4`, `'bnb4'``_bnb4`, `'q4f16'``_q4f16`. The `cross-encoder/*` repositories hold no `onnx/model_quantized.onnx`, so `dtype: 'q8'` fails to load there; name their quantized files with `modelFileName`. The provider always passes a dtype (`'fp32'` when unset), and an explicit dtype overrides Transformers.js's browser default: in a browser, where Transformers.js 3.x would load a model on its WASM backend at `'q8'` when given none ([`DEFAULT_DEVICE_DTYPE_MAPPING`](https://github.com/huggingface/transformers.js/blob/3.8.1/src/utils/dtypes.js#L48-L51)), the file is still `onnx/<modelFileName>.onnx`. Transformers.js 2.x reads `quantized` and no dtype, so there `'q8'` loads `onnx/<modelFileName>_quantized.onnx` and every other value loads `onnx/<modelFileName>.onnx`.
77
+
- Each batch of up to `batchSize` passages is tokenized as (query, passage) pairs, padded and cut to `maxSequenceLength` tokens, and scored in one forward pass: 20 passages at the default `batchSize` are one pass. A pair longer than `maxSequenceLength` loses the end of its passage and its closing separator token, since Transformers.js truncates the pair's token arrays at the limit ([`truncateHelper`](https://github.com/huggingface/transformers.js/blob/3.8.1/src/tokenizers.js#L2580-L2586)); an answer late in a long passage is never read.
78
+
- `pieceMaxChars` scores long passages by their best piece, and is off unless set. A passage longer than it is split into pieces of at most that many characters (UTF-16 units, as `String.length` counts them; a character outside the Basic Multilingual Plane is never split, so at 1 it is a piece of 2): its sentences in order (a sentence ends at `.`, `!` or `?` before a space, and at a line break), packed together while they fit and joined by one space; a sentence longer than a piece is split between words, and only a word longer than a piece is cut. Every piece of every passage is a (query, piece) pair in the same batches of `batchSize`, and a passage scores its best piece's score; its `content` in the answer is the whole passage. Pick a length at which a piece and the query fit in `maxSequenceLength` tokens. Each piece is a pair, so the pairs grow with the passages' length: 20 passages of 1,024 characters at `pieceMaxChars: 300` are at least 80 pairs, at least three forward passes at the default `batchSize`, against one pass for 20 whole passages, and one passage of 100,000 characters is at least 334 pairs. Cut passages that can run that long before reranking them.
79
+
- `intraOpNumThreads` sets the threads onnxruntime runs one operator on, passed to the ONNX session as `session_options.intraOpNumThreads`. Unset, the session gets no thread count and onnxruntime sizes its pool itself: onnxruntime-node 1.21 sizes it to the physical cores of the whole machine and, on Linux, pins a thread to each core ([`CreateThreadPoolHelper`](https://github.com/microsoft/onnxruntime/blob/v1.21.0/onnxruntime/core/util/thread_utils.cc#L92-L125)), whatever CPU limit the process runs under. Inside a container's cpuset or CPU quota, or on a host other processes share, those threads contend for the cores the process has, so a host on a CPU limit sets `intraOpNumThreads` to the cores it may use (`1` runs each operator on the calling thread). `interOpNumThreads` reaches the session too, but onnxruntime creates that pool only in its parallel execution mode ([`inference_session.cc`](https://github.com/microsoft/onnxruntime/blob/v1.21.0/onnxruntime/core/session/inference_session.cc#L457)) and Transformers.js runs sessions in the default sequential mode. onnxruntime-node reads both (Transformers.js 3.x on Node); onnxruntime-web and Transformers.js 2.x do not. A value that is not a whole number from 1 leaves the count unset, and a fraction is rounded down.
76
80
- Scores: a model with one logit (the `cross-encoder/*` and `BAAI/bge-reranker-*` models) scores a passage with the sigmoid of its raw logit; a model with two or more logits, with the softmax probability of its relevant class (a `LABEL_1`, `POSITIVE`, `relevant` or similar label in the model's `id2label`, else class 1). Scores sit between 0 and 1 and keep the logits' order; they compare passages within one model, not across models.
77
-
- A failed load or forward pass, or a NaN or infinite logit, throws, so `rerankChain()` and `RetrievalAugmentor` keep the order they had.
78
-
-`diagnostics.providerMetrics` reports `batchSize`, `forwardPasses`, `modelFile` (the ONNX file loaded) and `device`.
81
+
- A failed load or forward pass, or a NaN or infinite logit, throws, so `rerankChain()` and `RetrievalAugmentor` keep the order they had; a `rerankChunks()` caller keeps its order only if it catches ([When a provider fails](#when-a-provider-fails)). A load throws as soon as the tokenizer or the model fails. A model that loads after its tokenizer failed finishes in the background, and the provider then calls its `dispose()` and drops any error the disposal throws; the next load, unload or retry waits for that, so two loads never overlap. A failed load is not remembered. With no model loaded, the next `rerank()` tries the load once more and fetches any file the cache lacks. When `initialize(otherModelId)` fails while a model is loaded, reranks go on with the loaded model; call `initialize(otherModelId)` again to retry the replacement.
82
+
-`diagnostics.providerMetrics` reports `batchSize`, `forwardPasses`, `pairsScored` (the (query, text) pairs scored: one per passage, or one per piece with `pieceMaxChars`), `pieceMaxChars` when it is set, `modelFile`and `device`. `modelFile` is the file the installed Transformers.js loads by its naming rule: under 3.x `onnx/<modelFileName><dtype suffix>.onnx`, under 2.x `onnx/<modelFileName>.onnx`, or `onnx/<modelFileName>_quantized.onnx` for `dtype: 'q8'`.
79
83
- No `device` value selects a GPU: the model is loaded without a device option, so Transformers.js picks the backend. `'gpu'` sets Transformers.js's ONNX WASM backend to one thread, a process-wide setting every Transformers.js model in the process shares; `'cpu'` and `'auto'` change nothing.
|`RerankerService.rerank()`, `rerankChunks()`|Throws: no provider named and no default, a provider not registered, or the provider's own error|
184
-
|`LocalCrossEncoderReranker`| Throws when Transformers.js or the model cannot be loaded, and when a forward pass fails |
187
+
|`RerankerService.rerank()`, `rerankChunks()`|Logs the provider's error to the service's `logger` when it has one, then throws it; it also throws when no provider is named and none is the default, or the provider is not registered. The caller keeps its order only if it catches|
188
+
|`LocalCrossEncoderReranker`| Throws when Transformers.js or the model cannot be loaded, and when a forward pass fails. After a failed load, the next call loads again only when no model is loaded; a model loaded before keeps serving|
185
189
|`CohereReranker`| Throws without an `apiKey`, on a status that is not 2xx and when no response arrives within the timeout |
186
190
|`LlmJudgeReranker`| Does not throw for a model's failure: a failed scoring batch scores 0, a failed ranking call leaves the order to the scores |
187
191
|`rerankChain()`| Skips the stage and keeps the order it was given |
188
192
|`RetrievalAugmentor`| Returns the chunks without reranking and adds the error to `diagnostics.messages`|
189
193
|`CognitiveMemoryManager`, `HybridRetriever`, `SessionRetriever`| Keep the scores they had before reranking and write no log line of their own; the service logs a provider's error to its `logger`. They call the service's default provider, so a service without `defaultProviderId` fails every call this way, logged nowhere |
190
194
|`WebSearchService`| Keeps the fused order |
191
195
196
+
A host that calls `rerankChunks()` keeps its order on a failure by catching, and records the error there. The service logs a provider's error only when it was built with a `logger`, and never logs its own errors: no provider named and no default, a provider not registered, a result id that is not among the chunks.
logger.warn('rerank failed; keeping the retrieved order', { error: String(error) });
201
+
returnchunks;
202
+
});
203
+
```
204
+
205
+
`rerankChain()` does the same for every stage: a stage that throws, a local model that fails to load included, leaves the chunks in the order it was given, with their scores, and its id is missing from `_rerankerChainStages`.
206
+
192
207
## Where a reranker plugs in
193
208
194
209
-`RetrievalAugmentor` builds a `RerankerService` from `rerankerServiceConfig`. It registers the `cohere` provider (when its entry has an `apiKey`) and the `local` one for the entries that config names; register `llm-judge` and providers of your own with `registerRerankerProvider()`. It reranks a request that sets `rerankerConfig.enabled`, with `rerankerConfig.providerId` (else `defaultRerankerProviderId`) picking the provider, or one with no `rerankerConfig` whose retrieval `policy` sets `reranker: 'always'` ([RAG Memory Configuration](../memory/RAG_MEMORY_CONFIGURATION.md#reranker-chain)).
0 commit comments