Skip to content

Commit cf769c4

Browse files
committed
Merge remote-tracking branch 'origin/master' into feat/soul-identity-every-path
2 parents a0d6f14 + a71bb95 commit cf769c4

6 files changed

Lines changed: 836 additions & 48 deletions

File tree

‎docs/text/RERANKING.md‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -64,18 +64,22 @@ new LocalCrossEncoderReranker({
6464
modelFileName: 'model', // onnx/model.onnx; unset: the model's default file
6565
cacheDir: '/var/cache/agentos-models', // Transformers.js's own cache when unset
6666
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
6769
});
6870
```
6971

7072
- 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.
7173
- `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.
7680
- 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'`.
7983
- 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.
8084
- It reads no `timeoutMs` and no `params`.
8185

@@ -180,15 +184,26 @@ const { results } = await service.rerank(
180184

181185
| Where | What happens |
182186
|---|---|
183-
| `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 |
185189
| `CohereReranker` | Throws without an `apiKey`, on a status that is not 2xx and when no response arrives within the timeout |
186190
| `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 |
187191
| `rerankChain()` | Skips the stage and keeps the order it was given |
188192
| `RetrievalAugmentor` | Returns the chunks without reranking and adds the error to `diagnostics.messages` |
189193
| `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 |
190194
| `WebSearchService` | Keeps the fused order |
191195

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.
197+
198+
```typescript
199+
const ranked = await service.rerankChunks(query, chunks).catch((error) => {
200+
logger.warn('rerank failed; keeping the retrieved order', { error: String(error) });
201+
return chunks;
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+
192207
## Where a reranker plugs in
193208

194209
- `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)).

‎src/cognition/rag/reranking/RerankerService.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,10 @@ export class RerankerService {
206206
* @param chunks - Retrieved chunks to rerank
207207
* @param config - Request configuration
208208
* @returns Reranked chunks sorted by relevance
209+
* @throws The provider's error, after logging it to the service's logger when the service has one, as
210+
* `rerank()` does; also an error of its own, which it does not log: no provider named and no default, a
211+
* provider not registered, or a result id that is not among the chunks. A caller that wants its order on a
212+
* failure catches the error, records it and returns `chunks`; `rerankChain()` does this for each stage.
209213
*/
210214
public async rerankChunks(
211215
query: string,
@@ -259,7 +263,9 @@ export class RerankerService {
259263
/**
260264
* Run chunks through a multi-stage reranker pipeline.
261265
* Each stage's output feeds into the next, narrowing the result set.
262-
* Unavailable providers are silently skipped.
266+
* A stage whose provider is not registered or not available is skipped. A stage whose provider throws
267+
* (a local model that fails to load included) is skipped with a warning to the logger, and the chunks keep
268+
* the order and scores they had; it never throws for a stage's failure.
263269
*
264270
* @param query - The search query.
265271
* @param chunks - Input chunks to rerank.

0 commit comments

Comments
 (0)