diff --git a/sdk/python/feast/context/__init__.py b/sdk/python/feast/context/__init__.py index 62de13ebead..71a23b5d7e7 100644 --- a/sdk/python/feast/context/__init__.py +++ b/sdk/python/feast/context/__init__.py @@ -6,10 +6,21 @@ from feast.context.errors import ( ContextError, + RequiredSectionError, TokenBudgetExceededError, TokenizerNotFoundError, TokenizerUnavailableError, ) +from feast.context.priority_select import ( + DEFAULT_SEPARATOR, + Priority, + PrioritySpec, + Section, + SectionOrder, + SectionSpec, + Selection, + priority_select, +) from feast.context.token_budget import TokenBudget from feast.context.tokenizer import ( ApproximateTokenizer, @@ -26,7 +37,15 @@ "ApproximateTokenizer", "Cl100kBaseTokenizer", "ContextError", + "DEFAULT_SEPARATOR", "O200kBaseTokenizer", + "Priority", + "PrioritySpec", + "RequiredSectionError", + "Section", + "SectionOrder", + "SectionSpec", + "Selection", "TiktokenTokenizer", "TokenBudget", "TokenBudgetExceededError", @@ -36,4 +55,5 @@ "TokenizerSpec", "TokenizerUnavailableError", "get_tokenizer", + "priority_select", ] diff --git a/sdk/python/feast/context/errors.py b/sdk/python/feast/context/errors.py index 2504eabebd9..b96ff24c82e 100644 --- a/sdk/python/feast/context/errors.py +++ b/sdk/python/feast/context/errors.py @@ -40,10 +40,20 @@ def http_status_code(self) -> int: class TokenBudgetExceededError(ContextError): - def __init__(self, requested: int, remaining: int, max_tokens: int): + def __init__( + self, + requested: int, + remaining: int, + max_tokens: int, + *, + message: str = "", + ): super().__init__( - f"Cannot consume {requested} tokens: only {remaining} of " - f"{max_tokens} tokens remain in the budget." + message + or ( + f"Cannot consume {requested} tokens: only {remaining} of " + f"{max_tokens} tokens remain in the budget." + ) ) self.requested = requested self.remaining = remaining @@ -51,3 +61,24 @@ def __init__(self, requested: int, remaining: int, max_tokens: int): def http_status_code(self) -> int: return HttpStatusCode.HTTP_400_BAD_REQUEST + + +class RequiredSectionError(TokenBudgetExceededError): + """A section that must not be dropped does not fit the budget. + + Raised instead of quietly returning a prompt missing its instructions: + the caller has to widen the budget or shorten the section. + """ + + def __init__(self, section: str, requested: int, remaining: int, max_tokens: int): + super().__init__( + requested, + remaining, + max_tokens, + message=( + f"Section {section} is critical and cannot be dropped, but it " + f"needs {requested} tokens with only {remaining} of " + f"{max_tokens} left in the budget." + ), + ) + self.section = section diff --git a/sdk/python/feast/context/priority_select.py b/sdk/python/feast/context/priority_select.py new file mode 100644 index 00000000000..fd24da76e2d --- /dev/null +++ b/sdk/python/feast/context/priority_select.py @@ -0,0 +1,315 @@ +"""Choosing what survives when a prompt does not fit its 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 something +has to give. :func:`priority_select` decides what, keeping sections from the +most important down until the budget is spent:: + + selection = priority_select( + [ + ("critical", system_instructions), + ("high", f"User profile: {profile}"), + ("medium", f"Recent history: {history}"), + ("low", f"Device: {device}"), + ], + TokenBudget.of(4096), + ) + prompt = selection.render() + +The decision is deterministic in the sections and the budget alone, so an +OnDemandFeatureView that calls it drops the same sections during training as it +does at serving time. +""" + +from dataclasses import dataclass +from enum import Enum, IntEnum +from typing import Iterable, Iterator, Optional, Union + +from feast.context.errors import RequiredSectionError +from feast.context.token_budget import TokenBudget + +#: Placed between kept sections when a selection is rendered. +DEFAULT_SEPARATOR = "\n\n" + +#: Characters of content quoted in messages about an unnamed section. +_LABEL_PREVIEW_CHARS = 40 + + +class Priority(IntEnum): + """How readily a section may be dropped to make room for another. + + Ordered, so ``Priority.HIGH > Priority.LOW``. Only these four levels are + accepted: a plain number such as ``Priority.HIGH - 1`` is rejected. + """ + + #: Nice to have: dropped first. + LOW = 10 + #: Useful context, expendable under pressure. + MEDIUM = 20 + #: Kept unless the budget is genuinely tight. + HIGH = 30 + #: Never dropped; the selection fails instead. + CRITICAL = 40 + + @classmethod + def parse(cls, spec: "PrioritySpec") -> "Priority": + """Resolve a priority or its case-insensitive name.""" + if isinstance(spec, Priority): + return spec + if isinstance(spec, str): + try: + return cls[spec.strip().upper()] + except KeyError: + pass + raise ValueError( + f"Unknown priority {spec!r}. Use one of: " + f"{', '.join(level.name.lower() for level in sorted(cls, reverse=True))}." + ) + + def __str__(self) -> str: + return self.name.lower() + + +#: What callers may pass wherever a priority is expected. +PrioritySpec = Union[str, Priority] + + +@dataclass(frozen=True) +class Section: + """A candidate piece of a prompt, and how hard it is to lose. + + Attributes: + content: The text itself. Blank content is ignored by selection. + priority: How readily the section is dropped. + name: Optional identifier, quoted in error messages and useful for + asserting on what a selection kept. + """ + + content: str + priority: Priority = Priority.MEDIUM + name: Optional[str] = None + + def __post_init__(self) -> None: + if not isinstance(self.content, str): + raise TypeError(f"Section content must be a string, got {self.content!r}.") + if not isinstance(self.priority, Priority): + # A name from config lands here; resolve it once, so comparisons + # and sorting see a Priority. + object.__setattr__(self, "priority", Priority.parse(self.priority)) + + @classmethod + def of(cls, spec: "SectionSpec") -> "Section": + """Normalize a section or a ``(priority, content[, name])`` tuple.""" + if isinstance(spec, Section): + return spec + if isinstance(spec, tuple) and len(spec) in (2, 3): + priority, content, *rest = spec + return cls( + content=content, + priority=Priority.parse(priority), + name=rest[0] if rest else None, + ) + raise TypeError( + f"Expected a Section or a (priority, content) tuple, got {spec!r}." + ) + + @property + def is_required(self) -> bool: + """Whether the section must be kept, budget notwithstanding.""" + return self.priority is Priority.CRITICAL + + @property + def label(self) -> str: + """Quoted identifier for messages: the name, else a content preview.""" + if self.name: + return repr(self.name) + flattened = " ".join(self.content.split()) + if len(flattened) > _LABEL_PREVIEW_CHARS: + return repr(f"{flattened[: _LABEL_PREVIEW_CHARS - 3]}...") + return repr(flattened) + + +#: A section, or the tuple shorthand for one. +SectionSpec = Union[ + Section, + tuple[PrioritySpec, str], + tuple[PrioritySpec, str, Optional[str]], +] + + +class SectionOrder(str, Enum): + """The order kept sections come back in.""" + + #: As the caller listed them, so the prompt reads as it was written. + DECLARED = "declared" + #: Most important first, ties broken by declaration order. + PRIORITY = "priority" + + +@dataclass(frozen=True) +class Selection: + """The outcome of a :func:`priority_select`: what fit and what did not. + + Iterating yields the kept content, so a selection drops straight into a + join or a template:: + + for text in selection: ... + prompt = selection.render() + + Attributes: + budget: The budget after charging the rendered prompt. + kept: Sections that made it in, ordered as requested. + dropped: Sections left out, in declaration order. + separator: What :meth:`render` joins kept sections with. + """ + + budget: TokenBudget + kept: tuple[Section, ...] = () + dropped: tuple[Section, ...] = () + separator: str = DEFAULT_SEPARATOR + + @property + def contents(self) -> tuple[str, ...]: + """The text of each kept section.""" + return tuple(section.content for section in self.kept) + + @property + def names(self) -> tuple[Optional[str], ...]: + """The name of each kept section, None where unnamed.""" + return tuple(section.name for section in self.kept) + + @property + def is_complete(self) -> bool: + """Whether everything offered was kept.""" + return not self.dropped + + def render(self) -> str: + """The kept sections joined by :attr:`separator`.""" + return self.separator.join(self.contents) + + def __iter__(self) -> Iterator[str]: + return iter(self.contents) + + def __len__(self) -> int: + return len(self.kept) + + def __str__(self) -> str: + return self.render() + + +def priority_select( + sections: Iterable[SectionSpec], + budget: TokenBudget, + *, + separator: str = DEFAULT_SEPARATOR, + order: SectionOrder = SectionOrder.DECLARED, +) -> Selection: + """Keep as much of ``sections`` as ``budget`` allows, least important out first. + + Sections are considered from the highest priority down, ties in declaration + order, and each is kept if what remains of the budget covers it. A section + too large to fit is dropped and the scan continues, so a small low-priority + section can still be kept after a large high-priority one was refused. + + Sections whose content is blank are ignored: they would only double a + separator. ``critical`` sections are never dropped. + + Each section is charged on its own, plus ``separator`` between each pair + kept. Joined, the sections can still cost more than that, because a + tokenizer may split text differently across a boundary. So the rendered + prompt is then measured as a whole, the least important section kept is + dropped while it overflows, and the budget is charged for exactly what + :meth:`Selection.render` returns. + + Args: + sections: Sections, or ``(priority, content[, name])`` tuples. + budget: The allowance to fill. Anything already consumed on it stays + consumed; only what remains is available here. + separator: Placed between kept sections by + :meth:`Selection.render`, and charged against the budget. + order: Whether kept sections come back in declaration or priority + order. + + Returns: + A :class:`Selection` holding the kept sections, the dropped ones, and + the budget left over. + + Raises: + RequiredSectionError: A ``critical`` section does not fit. + TypeError: A section is neither a :class:`Section` nor a tuple. + ValueError: A priority or an order is not a known name. + """ + if not isinstance(separator, str): + raise TypeError(f"separator must be a string, got {separator!r}.") + order = SectionOrder(order) + + candidates = [ + section + for section in (Section.of(spec) for spec in sections) + if section.content.strip() + ] + separator_tokens = budget.count_tokens(separator) + + remaining = budget + kept: list[tuple[int, Section]] = [] + dropped: list[tuple[int, Section]] = [] + # Most important first, and among equals whoever was listed first. + by_importance = sorted( + enumerate(candidates), key=lambda pair: (-pair[1].priority, pair[0]) + ) + + 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)) + elif section.is_required: + # Counted apart, the pieces can also cost more than the prompt they + # make: each rounds up on its own. Measure the prompt with this + # section in, against what the caller had left, before refusing it. + trial = [*kept, (position, section)] + cost = budget.count_tokens(_render(trial, order, separator)) + if not budget.fits_tokens(cost): + raise RequiredSectionError( + section.label, cost, budget.remaining, budget.max_tokens + ) + remaining = budget.consume_tokens(cost) + kept.append((position, section)) + else: + dropped.append((position, section)) + + # Counted one at a time, the sections can cost less than the prompt they + # make: cl100k_base counts "Hello!\r\n", "\n\n" and "World" as four tokens + # apart but five joined. Measure the prompt as it renders, and give up the + # least important section kept until it fits. + cost = budget.count_tokens(_render(kept, order, separator)) + while not budget.fits_tokens(cost): + position, section = kept.pop() + if section.is_required: + raise RequiredSectionError( + section.label, cost, budget.remaining, budget.max_tokens + ) + dropped.append((position, section)) + cost = budget.count_tokens(_render(kept, order, separator)) + + if order is SectionOrder.DECLARED: + kept.sort(key=lambda pair: pair[0]) + dropped.sort(key=lambda pair: pair[0]) + + return Selection( + budget=budget.consume_tokens(cost), + kept=tuple(section for _, section in kept), + dropped=tuple(section for _, section in dropped), + separator=separator, + ) + + +def _render( + kept: list[tuple[int, Section]], order: SectionOrder, separator: str +) -> str: + """Join kept sections as :meth:`Selection.render` will.""" + if order is SectionOrder.DECLARED: + kept = sorted(kept, key=lambda pair: pair[0]) + return separator.join(section.content for _, section in kept) diff --git a/sdk/python/tests/unit/context/test_priority_select.py b/sdk/python/tests/unit/context/test_priority_select.py new file mode 100644 index 00000000000..01a54d53e11 --- /dev/null +++ b/sdk/python/tests/unit/context/test_priority_select.py @@ -0,0 +1,350 @@ +import dataclasses + +import pytest + +from feast.context import ( + Priority, + Section, + SectionOrder, + TokenBudget, + priority_select, +) +from feast.context.errors import RequiredSectionError, TokenBudgetExceededError +from feast.context.tokenizer import ApproximateTokenizer, Tokenizer + +# Four characters per token: "abcd" is one token under the estimate. +ESTIMATING = ApproximateTokenizer() + + +class JoinSensitiveTokenizer(Tokenizer): + """A token per character, plus one wherever "!" meets a line break. + + Like cl100k_base with "Hello!\\r\\n" and "\\n\\n", it charges a joined + prompt more than its pieces. + """ + + @property + def name(self) -> str: + return "join-sensitive" + + def count_tokens(self, text: str) -> int: + return len(text) + text.count("!\n") + + +def budget(max_tokens: int = 100, consumed: int = 0) -> TokenBudget: + """A budget on the deterministic estimate, so counts need no tiktoken.""" + return TokenBudget(max_tokens=max_tokens, tokenizer=ESTIMATING, consumed=consumed) + + +def text(tokens: int, letter: str = "a") -> str: + """Content costing exactly ``tokens`` tokens under the estimate.""" + return letter * (tokens * 4) + + +class TestPriority: + def test_orders_from_critical_down(self): + assert Priority.CRITICAL > Priority.HIGH > Priority.MEDIUM > Priority.LOW + + def test_parses_a_name_whatever_its_case(self): + assert Priority.parse("critical") is Priority.CRITICAL + assert Priority.parse(" High ") is Priority.HIGH + + def test_passes_a_priority_through(self): + assert Priority.parse(Priority.LOW) is Priority.LOW + + def test_unknown_priority_lists_the_known_ones(self): + with pytest.raises(ValueError, match="critical, high, medium, low"): + Priority.parse("urgent") + + def test_reads_as_its_lowercase_name(self): + assert f"{Priority.MEDIUM}" == "medium" + + def test_rejects_a_number_between_levels(self): + with pytest.raises(ValueError, match="Unknown priority 29"): + Section("body", Priority.HIGH - 1) # type: ignore[arg-type] + + +class TestSection: + def test_defaults_to_medium(self): + assert Section("body").priority is Priority.MEDIUM + + def test_resolves_a_priority_name(self): + assert Section("body", "high").priority is Priority.HIGH # type: ignore[arg-type] + + def test_rejects_non_string_content(self): + with pytest.raises(TypeError, match="content must be a string"): + Section(42) # type: ignore[arg-type] + + def test_is_immutable(self): + with pytest.raises(dataclasses.FrozenInstanceError): + Section("body").content = "other" # type: ignore[misc] + + def test_of_builds_from_a_priority_and_content(self): + assert Section.of(("low", "body")) == Section("body", Priority.LOW) + + def test_of_builds_from_a_named_triple(self): + section = Section.of(("high", "body", "profile")) + assert section == Section("body", Priority.HIGH, "profile") + + def test_of_passes_a_section_through(self): + section = Section("body") + assert Section.of(section) is section + + def test_of_rejects_anything_else(self): + with pytest.raises(TypeError, match="Section or a"): + Section.of("body") # type: ignore[arg-type] + + def test_only_critical_sections_are_required(self): + assert Section("body", Priority.CRITICAL).is_required is True + assert Section("body", Priority.HIGH).is_required is False + + def test_label_prefers_the_name(self): + assert Section("body", name="profile").label == "'profile'" + + def test_label_falls_back_to_a_flattened_preview(self): + assert Section("two\n words").label == "'two words'" + + def test_label_truncates_a_long_preview(self): + label = Section("word " * 20).label + assert label.endswith("...'") + assert len(label) == len("''") + 40 + + +class TestSelects: + def test_keeps_everything_that_fits(self): + selection = priority_select([("high", text(2)), ("low", text(2))], budget(10)) + assert selection.contents == (text(2), text(2)) + assert selection.is_complete is True + assert selection.dropped == () + + def test_keeps_declaration_order_by_default(self): + selection = priority_select( + [("low", "third"), ("critical", "first"), ("medium", "second")], + budget(100), + ) + assert selection.contents == ("third", "first", "second") + + def test_orders_by_priority_when_asked(self): + selection = priority_select( + [("low", "third"), ("critical", "first"), ("medium", "second")], + budget(100), + order=SectionOrder.PRIORITY, + ) + assert selection.contents == ("first", "second", "third") + + def test_accepts_an_order_by_name(self): + selection = priority_select( + [("low", "second"), ("high", "first")], budget(100), order="priority" + ) + assert selection.contents == ("first", "second") + + def test_rejects_an_unknown_order(self): + with pytest.raises(ValueError, match="alphabetical"): + priority_select([], budget(), order="alphabetical") + + def test_drops_the_least_important_first(self): + selection = priority_select( + [ + ("high", text(2, "h")), + ("medium", text(2, "m")), + ("low", text(2, "l")), + ], + budget(4), + separator="", + ) + assert selection.contents == (text(2, "h"), text(2, "m")) + assert selection.dropped == (Section(text(2, "l"), Priority.LOW),) + assert selection.is_complete is False + + def test_keeps_a_critical_section_listed_last(self): + selection = priority_select( + [("high", text(2, "h")), ("critical", text(2, "c"))], + budget(2), + separator="", + ) + assert selection.contents == (text(2, "c"),) + assert selection.dropped == (Section(text(2, "h"), Priority.HIGH),) + + def test_breaks_ties_by_declaration_order(self): + selection = priority_select( + [("medium", text(2, "a")), ("medium", text(2, "b"))], + budget(2), + separator="", + ) + assert selection.contents == (text(2, "a"),) + + def test_keeps_a_smaller_section_after_refusing_a_larger_one(self): + selection = priority_select( + [("high", text(5, "h")), ("medium", text(2, "m")), ("low", text(1, "l"))], + budget(3), + separator="", + ) + assert selection.contents == (text(2, "m"), text(1, "l")) + assert selection.budget.is_exhausted is True + + def test_ignores_blank_sections(self): + selection = priority_select( + [("critical", " \n "), ("high", "body"), ("low", "")], budget(100) + ) + assert selection.contents == ("body",) + assert selection.dropped == () + + def test_selects_nothing_from_nothing(self): + selection = priority_select([], budget(10)) + assert selection.contents == () + assert selection.is_complete is True + assert selection.budget == budget(10) + + def test_accepts_sections_as_well_as_tuples(self): + selection = priority_select( + [Section("body", Priority.HIGH, "profile"), ("low", "extra")], budget(100) + ) + assert selection.names == ("profile", None) + + def test_leaves_the_original_budget_untouched(self): + original = budget(10) + priority_select([("high", text(4))], original, separator="") + assert original.consumed == 0 + + +class TestBudgetAccounting: + def test_charges_the_kept_sections(self): + selection = priority_select( + [("high", text(3)), ("low", text(2))], budget(10), separator="" + ) + assert selection.budget.consumed == 5 + assert selection.budget.remaining == 5 + + def test_spends_only_what_is_left_of_a_used_budget(self): + selection = priority_select( + [("high", text(3)), ("low", text(3))], + budget(10, consumed=6), + separator="", + ) + assert selection.contents == (text(3),) + assert selection.budget.remaining == 1 + + def test_charges_the_prompt_as_rendered(self): + # Joined by "\n\n", three 3-token sections are 40 characters: ten + # tokens under the estimate, one fewer than the pieces counted apart. + selection = priority_select( + [("high", text(3)), ("high", text(3)), ("high", text(3))], budget(100) + ) + assert selection.budget.consumed == 10 + + def test_drops_a_section_when_joining_costs_more_than_the_pieces(self): + # Apart, "a!", "\n" and "b" cost 2 + 1 + 1 = 4 tokens; "a!\nb" costs 5. + tight = TokenBudget(max_tokens=4, tokenizer=JoinSensitiveTokenizer()) + selection = priority_select( + [("high", "a!"), ("low", "b")], tight, separator="\n" + ) + assert selection.contents == ("a!",) + assert selection.dropped == (Section("b", Priority.LOW),) + assert selection.budget.consumed == 2 + with pytest.raises(RequiredSectionError, match="'b' is critical"): + priority_select( + [("critical", "a!"), ("critical", "b")], tight, separator="\n" + ) + + def test_charges_nothing_for_an_empty_separator(self): + selection = priority_select( + [("high", text(3)), ("high", text(3))], budget(100), separator="" + ) + assert selection.budget.consumed == 6 + + def test_the_rendered_prompt_fits_the_budget(self): + selection = priority_select( + [("high", text(3, "h")), ("medium", text(3, "m")), ("low", text(3, "l"))], + budget(10), + ) + rendered = selection.render() + assert selection.contents == (text(3, "h"), text(3, "m")) + assert rendered == f"{text(3, 'h')}\n\n{text(3, 'm')}" + assert ESTIMATING.count_tokens(rendered) <= 10 + assert selection.budget.consumed == ESTIMATING.count_tokens(rendered) + + def test_rejects_a_non_string_separator(self): + with pytest.raises(TypeError, match="separator must be a string"): + priority_select([], budget(), separator=None) # type: ignore[arg-type] + + +class TestRequiredSections: + def test_raises_when_a_critical_section_does_not_fit(self): + with pytest.raises(RequiredSectionError, match="'rules' is critical"): + priority_select([("critical", text(5), "rules")], budget(4), separator="") + + def test_raises_when_critical_sections_together_overflow(self): + with pytest.raises(RequiredSectionError, match="'second'"): + priority_select( + [("critical", text(3), "first"), ("critical", text(3), "second")], + budget(5), + separator="", + ) + + def test_reports_the_shortfall(self): + with pytest.raises(RequiredSectionError) as excinfo: + priority_select([("critical", text(5))], budget(4), separator="") + error = excinfo.value + assert error.requested == 5 + assert error.remaining == 4 + assert error.max_tokens == 4 + assert error.section == f"'{text(5)}'" + + def test_keeps_critical_sections_whose_joined_prompt_fits(self): + # Apart, "a", "\n\n" and "b" round up to 1 + 1 + 1 tokens under the + # estimate; joined, "a\n\nb" is four characters: one token. + sections = [("critical", "a"), ("critical", "b")] + selection = priority_select(sections, budget(1)) + assert selection.contents == ("a", "b") + assert selection.budget.consumed == 1 + # Only what is left of an already-used budget counts. + selection = priority_select(sections, budget(3, consumed=2)) + assert selection.contents == ("a", "b") + assert selection.budget.remaining == 0 + + def test_is_a_token_budget_error(self): + # Callers already guarding prompt assembly keep catching one type. + assert issubclass(RequiredSectionError, TokenBudgetExceededError) + + +class TestSelection: + @pytest.fixture + def selection(self): + return priority_select( + [("high", "first", "profile"), ("low", "second")], budget(100) + ) + + def test_renders_sections_joined_by_the_separator(self, selection): + assert selection.render() == "first\n\nsecond" + + def test_renders_as_its_string(self, selection): + assert f"{selection}" == "first\n\nsecond" + + def test_iterates_over_the_kept_content(self, selection): + assert list(selection) == ["first", "second"] + assert " | ".join(selection) == "first | second" + + def test_counts_the_kept_sections(self, selection): + assert len(selection) == 2 + + def test_exposes_the_kept_names(self, selection): + assert selection.names == ("profile", None) + + def test_is_immutable(self, selection): + with pytest.raises(dataclasses.FrozenInstanceError): + selection.kept = () + + +class TestTiktokenSelection: + def test_the_rendered_prompt_fits_an_exact_budget(self): + pytest.importorskip("tiktoken") + sections = [ + ("critical", "You are a helpful recommendation assistant."), + ("high", "The user enjoys slow cinema and long documentaries."), + ("medium", "Recently watched: " + "an eight part nature series, " * 20), + ("low", "Device: living room television. Time: Sunday evening."), + ] + selection = priority_select(sections, TokenBudget.of(64)) + assert selection.is_complete is False + assert selection.budget.count_tokens(selection.render()) <= 64 + assert selection.contents[0] == sections[0][1]