perf(llm): avoid tokenizing discarded lines#12981
Conversation
|
All contributors have signed the CLA ✍️ ✅ |
|
I have read the CLA Document and I hereby sign the CLA |
|
The |
|
Re-checked this today against It still applies unchanged. On the red check, Context, in case it is useful: #4947 reported these two functions as a code-completion latency problem on large files, and #5310 removed the repeated array mutation but left the eager tokenization of every line in place. This is the remaining half of that. If it would be easier to review, I am glad to split the test un-skip into a separate PR and keep this one to the two function bodies. |
Description
Fixes #12980.
PR #5310 removed repeated array mutation from
pruneLinesFromTopandpruneLinesFromBottom, but both functions still tokenize every line before discarding most of them. This change traverses from the side that will be retained and stops as soon as the next line would exceed the token budget.The existing one-token newline accounting and returned strings are preserved. The production change is limited to the two pruning function bodies, and this PR enables their existing focused tests.
Performance
The deterministic evaluator counts real
Tiktoken.encodecalls across top and bottom pruning of a 320-line prompt:mainAll nine baseline and candidate samples were identical within each revision. A 580-case differential suite covering empty input, leading and trailing blank lines, newline boundaries, Unicode, oversized lines, random multiline prompts, and zero or negative limits produced byte-for-byte identical output.
On the 2,000-line scale described in #4947, the same metric is 4,001 calls on
mainand 86 on this branch (-97.9%).Autoresearch
The retained-side traversal was independently reproduced during a 10-step autoresearch run with Weco. The final patch was then reduced and validated in a clean worktree.
Public trajectory: https://dashboard.weco.ai/share/xWch5tqFM_tvJr2AZVT4lWugmaTnbu5b
AI Code Review
@continue-reviewChecklist
Screen recording or screenshot
Not applicable; this changes token-pruning work without changing UI behavior.
Tests
npm test -- --runInBand llm/countTokens.test.ts(25 passed, 9 unrelated skipped)npm run tsc:checkgit diff --check