Repository navigation
perf: true batched inference for TransformerDetector (fixes #23) - #113
Conversation
) TransformerDetector.predict_prompt_batch now performs padded batch tokenization and a single model forward pass per configured batch_size, preserving input order and correctly trimming prompt/padding per sample for both tokens and spans. Add strict len(prompts) == len(answers) validation (no silent zip truncation), including in the LLM detector request path. Tests cover uneven sequence lengths, batch_size 1 and >1, output order, tokens, spans, min_confidence filtering, empty input, and mismatch errors; a spy/stub verifies one forward call per transformer batch without downloading a model.
adaamko
left a comment
There was a problem hiding this comment.
Thanks for this, @c71qu3. This is the first implementation for #23 and it's the one we'd like to merge. I checked it against the real model: KRLabsOrg/lettucedect-base-modernbert-en-v1 on CPU, 7 prompt/answer pairs from 67 to ~3,200 tokens, batch sizes 1/2/3/7. Batched and one-by-one spans match exactly, and token probabilities agree within 2e-6 (exactly with attn_implementation="eager"). The mmBERT + taxonomy-head cascade also gives identical typed spans, and the truncation path matches too. Using sequence_ids for the per-row answer start and attention_mask for the real length is the right call. A few things before merge:
-
Lint/format (merge gate).
ruff format --check lettucedetect/ lettucedetect_api/ tests/wants to reformatlettucedetect/detectors/transformer.pyandtests/test_inference_pytest.py.ruff check lettucedetect/ lettucedetect_api/ tests/ --extend-exclude lettucedetect/integrations/reports 12 errors:- D205/D209 docstring layout at transformer.py:273 and tests/test_inference_pytest.py:804, 833, 876, 910
- D107/D102 on
CountingClientin tests/test_llm_detector_pytest.py:35,39 - S105 at tests/test_inference_pytest.py:819, a false positive on the
"[PAD]"token string; a# noqa: S105is fine
Running
ruff formatand thenruff check --fixhandles most of it. -
Bounded default batch size. Before this change
predict_prompt_batchused constant memory whatever the list length. Withbatch_size=Nonemeaning "whole list" (transformer.py:560), existing callers that pass a few thousand pairs now get one huge forward pass and can run out of memory. Please default to a fixed size (for examplebatch_size: int = 16in__init__) and keep the per-call override. -
Validate
batch_size. A negative value currently returns[]silently (range(0, n, -2)is empty), and0falls back to the default viaor. RaiseValueErrorfor anything below 1. -
PR description. Please fill in the Summary section, add
Closes #23under "Related issue", and tick the ruff boxes once they pass.
Non-blocking nits:
- tests/test_inference_pytest.py:526-527: delete the commented-out
tokenizer.return_valueline and the stale comment above it. - transformer.py:282: instead of rejecting left-padding tokenizers, you could pass
padding_side="right"to the tokenizer call in_predict_batch, which is supported at ourtransformers>=4.48.3floor. If you keep the check, the message reads better as "...requires a right-padding tokenizer". - transformer.py:319-323: this warning fires whenever
seq_len == max_length, even for inputs that fit exactly, and it uses an f-string where the rest of the module uses%-style logger args. Measuring the untruncated length, likepredict_promptdoes, would match the single-path warning. - Typos in test docstrings: "modal" → "model", "everthing" → "everything".
- Optional follow-up: sorting pairs by length before micro-batching (restoring order afterwards) would cut padding waste on mixed-length inputs.
Once 1–4 are in and CI is green, we'll merge. Thanks again!
a1dd2b7 to
3d2a380
Compare
|
Thanks for the detailed review! I’ve pushed updates to address the requested changes. |
adaamko
left a comment
There was a problem hiding this comment.
Thanks @c71qu3, all four points are addressed. Re-verified on the new head: ruff format --check and ruff check are clean, the full suite passes (207), and against KRLabsOrg/lettucedect-base-modernbert-en-v1 on CPU the batched output matches one-by-one at batch sizes 1, 2, 3, 7 and the whole list: identical spans, token probabilities within 6e-6. The default of 16 keeps memory bounded, and batch_size below 1 now raises. Merging, closes #23.
Add BaseDetector._validate_batch_lengths(prompts, answers). It raises ValueError when the two lengths differ. The message shows both lengths. TransformerDetector, LLMDetector and RAGFactCheckerDetector now call the helper instead of an inline check. The old message text stays as a prefix, so the #113 tests pass without edits. RAGFactCheckerDetector.predict_prompt_batch now zips the answers and the backend results with strict=True. Before this change, a short backend result dropped answers with no error. Add tests for the helper and a new test file for the RAG detector. Follow-up to #113, refs #114. Signed-off-by: yassinnouh21 <yassinnouh21@gmail.com>
TransformerDetector.predict_prompt_batch now performs padded batch tokenization and a single model forward pass per configured batch_size, preserving input order and correctly trimming prompt/padding per sample for both tokens and spans. Add strict len(prompts) == len(answers) validation (no silent zip truncation), including in the LLM detector request path.
Tests cover uneven sequence lengths, batch_size 1 and >1, output order, tokens, spans, min_confidence filtering, empty input, and mismatch errors; a spy/stub verifies one forward call per transformer batch without downloading a model.
Summary
TransformerDetector.predict_prompt_batch: padded batch tokenization + one model forward pass per batch (configurablebatch_size), preserving input order and trimming prompt/padding per sample correctly for bothtokensandspans.ValueErrorwhenlen(prompts) != len(answers)(no silent truncation) and rejects invalidbatch_size < 1; keeps the LLM detector’s concurrent-request path but applies the same length validation.predict_promptper sample (within tolerance), includingmin_confidencefiltering and taxonomy typing when configured.Related issue
Closes #23.
Type of change
Testing
ruff format --check lettucedetect/ lettucedetect_api/ tests/ruff check lettucedetect/ lettucedetect_api/ tests/ --extend-exclude lettucedetect/integrations/python -m pytestChecklist
Rights & sign-off (required)
distributed under the repository's MIT license
(see CONTRIBUTING).