Repository navigation
feat(context): Add priority_select for budget-aware section selection - #7216
patelchaitany wants to merge 3 commits into
Conversation
Decides which parts of a prompt survive a token budget. Sections carry a priority; selection keeps them from critical down until the allowance is spent, dropping the least important first and never dropping a critical one. The result carries the kept sections, the dropped ones and the budget left over, and renders to the assembled text. The budget is charged for the separator between kept sections, so the rendered prompt fits the allowance rather than overshooting it once the pieces are joined. Selection is a pure function of the sections and the budget, so an OnDemandFeatureView drops the same sections offline and online. Part of RHOAIENG-80116. Stacked on the TokenBudget PR. Signed-off-by: Chaitany Patel <patelchaitany93@gmail.com>
There was a problem hiding this comment.
Devin Review found 1 potential issue.
2 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)
| for position, section in by_importance: | ||
| cost = remaining.count_tokens(section.content) | ||
| if kept: | ||
| cost += separator_tokens | ||
| if remaining.fits_tokens(cost): | ||
| remaining = remaining.consume_tokens(cost) | ||
| kept.append((position, section)) |
There was a problem hiding this comment.
🔴 Rendered prompts exceed their token budget
priority_select can accept sections that fit separately but exceed the budget when joined. cl100k_base can split a section’s trailing punctuation and line break into more tokens after the default separator is appended. A model request built from the returned prompt can be rejected for exceeding its limit.
Learn more
TokenBudget.count_tokens counts the text passed to it using the configured tokenizer. With Cl100kBaseTokenizer, joining pieces can change which tokens the tokenizer chooses, and the total can increase. Selection.render returns the joined text without checking its token count. The returned budget therefore can report that the prompt fits even when it does not.
Example: Call priority_select([("critical", "Hello.\r\n"), ("high", "World")], TokenBudget.of(4, fallback=False)). With the default separator, the selector charges 2 + 1 + 1 = 4 and keeps both sections. The rendered "Hello.\r\n\n\nWorld" takes five cl100k_base tokens.
Recommended fix: Count each tentative joined prompt in the requested render order and compare that count with the original budget’s remaining allowance. Keep scanning candidates in priority order, then charge the final rendered count against the original budget so any prior consumption is preserved. Add a regression test with fallback=False using the default separator and the CRLF boundary.
Was this helpful? React with 👍 or 👎 to provide feedback.
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #7216 +/- ##
==========================================
+ Coverage 54.10% 54.20% +0.09%
==========================================
Files 467 468 +1
Lines 58940 59065 +125
Branches 8688 8706 +18
==========================================
+ Hits 31890 32015 +125
Misses 24892 24892
Partials 2158 2158
Continue to review full report in Codecov by Harness.
🚀 New features to boost your workflow:
|
Counted one at a time, sections can cost less than the prompt they make: a tokenizer may split a section's tail differently once a separator follows it. Under cl100k_base, "Hello!\r\n", "\n\n" and "World" cost four tokens apart but five joined, so a selection could render over budget. After the per-section pass, measure the rendered prompt as a whole, drop the least important kept section while it overflows (raising RequiredSectionError if only critical sections remain), and charge the budget for exactly what Selection.render() returns. Signed-off-by: Chaitany Patel <patelchaitany93@gmail.com>
franciscojavierarceo
left a comment
There was a problem hiding this comment.
we need to check the rendered prompt before rejecting critical sections that can fit together.
| if remaining.fits_tokens(cost): | ||
| remaining = remaining.consume_tokens(cost) | ||
| kept.append((position, section)) | ||
| elif section.is_required: |
There was a problem hiding this comment.
this raises before checking the rendered cost when separately counted sections overestimate it. for example, priority_select([('critical', 'a'), ('critical', 'b')], TokenBudget(max_tokens=1, tokenizer=ApproximateTokenizer())) rejects the second section, although the rendered a\n\nb is four characters and costs one token with that tokenizer. valid critical prompts therefore fail with RequiredSectionError. we should measure the tentative joined prompt in the requested order against the original remaining allowance before rejecting a critical section, and cover this case with a tight, already-consumed budget too.
…ection Counted apart, sections can cost more than the prompt they make, since each rounds up on its own. With the four-characters-a-token estimate and a one-token budget, "a", "\n\n" and "b" count as three tokens, yet "a\n\nb" costs one, so two critical sections that fit were refused with RequiredSectionError. Before refusing a critical section, render the sections kept so far with it in the requested order and measure that against what remains of the budget the caller passed in. Raise only if the joined prompt does not fit. Signed-off-by: Chaitany Patel <patelchaitany93@gmail.com>
What this PR does / why we need it:
Adds
priority_select(), the second piece offeast.context(afterTokenBudget, #6824): it decides which parts of a prompt survive a token budget. Prompt assembly is a packing problem — a user profile, a watch history and a catalogue of candidates rarely fit together in a context window — and this is the mechanism that chooses what gives.Sections are considered most important first, and dropped least important first.
Priorityis anIntEnumwith four levels (critical > high > medium > low); a section accepts one of them or its case-insensitive name. Ties keep declaration order. A section too large to fit is dropped and the scan continues, so a small low-priority section is still kept after a large high-priority one was refused. Acriticalsection is never dropped: if it does not fit,RequiredSectionErroris raised rather than quietly returning a prompt with its instructions missing. That error subclassesTokenBudgetExceededError, so callers already guarding prompt assembly keep catching one type.The rendered prompt is what gets charged. Counting sections alone and then joining them with
"\n\n"overshoots the allowance, which is exactly the sort of drift that turns into a 400 from a model server. Charging a separator per joint is not enough on its own either: a tokenizer can split a section's tail differently once a separator follows it. Undercl100k_base,"Hello!\r\n","\n\n"and"World"cost four tokens apart but five joined. Sopriority_selectfirst weighs each section plus one separator per joint, then measures the rendered prompt as a whole and drops the least important kept section while it overflows. The budget is charged for exactly whatSelection.render()returns.The result is a value, not a list of strings.
Selectionreports what was kept, what was dropped, and the budget left over — the last of which matters when a caller wants to spend the remainder elsewhere. It iterates over the kept content and stringifies to the rendered prompt, so it still drops straight into a join or a template:Kept sections come back in declaration order by default, so the prompt reads as it was written;
order=SectionOrder.PRIORITYreturns them most important first instead. Sections given blank content are ignored rather than rendered as a doubled separator.Determinism. Selection is a pure function of the sections and the budget — no clocks, no iteration over unordered collections, no mutation of the budget passed in. The same OnDemandFeatureView therefore drops the same sections during training as it does at serving time.
One change outside the new file:
TokenBudgetExceededErrorgained a keyword-onlymessageoverride soRequiredSectionErrorcan name the offending section while keeping the same type and attributes. It is additive and backwards compatible. Nothing in Feast importsfeast.contextyet, so the change remains inert.Which issue(s) this PR fixes:
No GitHub issue. Tracked internally as RHOAIENG-80116.
Checks
git commit -s)Testing Strategy
sdk/python/tests/unit/context/test_priority_select.py— 50 tests with tiktoken installed, 49 passing and 1 skipped without it. Covers priority parsing and ordering (including rejection of a bare number between levels), section normalization from tuples, dropping order, critical sections listed last, keeping a smaller section after refusing a larger one, budget accounting (the charge equals the rendered prompt's cost, and a section is dropped when the joined prompt costs more than its pieces), an already-consumed budget, blank and empty input, and the error's shortfall reporting. One exact-tokenizer test asserts a rendered prompt fits a 64-tokencl100k_basebudget.ruff check,ruff format --checkandmypyare clean.