Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/apps-module-migrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@
"tests/apps/test_apps_module_migrations.py",
"tests/apps/test_campaign_record_injection.py",
"tests/apps/test_campaign_task_selection.py",
"tests/apps/test_indexer_deliveries.py",
"tests/apps/test_knowledge_navigation_browser.py",
"tests/apps/test_optimization_session.py",
"tests/apps/test_optimization_story.py",
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/dashboard-profile-review.html

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions src/inferrsi/knowledge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ Benchmark owns assessment of the results those workflows produce.
- [`knowledge_operations.py`](knowledge_operations.py) exposes
`KnowledgeReader.collect` for context, `read` for bundles, and `resource` for
files at a pinned revision.
- [`RankingPolicy`](ranking_policy.py) supplies field weights to Find and
Collect. For example, pass `ranking_policy=RankingPolicy("trial", {"applicability": 3})`
to compare results against the default on the same library. Collect records
its version and effective weights in `retrieval.selection.ranking_policy` when
it ranks matches or selects skill sections by relevance. Explicit item IDs
keep caller order even when section selection uses these weights.
Inspect `contexts` and `context_omissions` to see which material fit the budget.
- [`knowledge_store.py`](knowledge_store.py) exposes `KnowledgeStore.create` and
`update` for an authorized writable store. The packaged library is authored
in the repository.
Expand Down
5 changes: 3 additions & 2 deletions src/inferrsi/knowledge/_skill_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from ._source_snapshot import source_entry
from .catalog import _skill_search_source, packaged_skill_id
from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy

FIND_RELEVANCE = "find-lexical-v1"
TASK_STOP_WORDS = frozenset({"a", "an", "and", "for", "in", "of", "on", "the", "to", "with"})
Expand Down Expand Up @@ -152,7 +153,7 @@ def skill_procedure(path: str, raw: bytes) -> tuple[bytes, dict]:

def context_view(
index: tuple[str, list[str], list[str]], view: dict, content: dict[str, bytes],
cue: str | None, available: int,
cue: str | None, available: int, ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY,
) -> tuple[dict | None, dict | None]:
core, required, optional = index
selected = {path: skill_procedure(path, content[path]) for path in [*required, *optional]}
Expand Down Expand Up @@ -207,7 +208,7 @@ def include(path: str) -> None:
)
for path, text in candidates.items()
]
_, _, ranked = rank(cue, Corpus(documents))
_, _, ranked = rank(cue, Corpus(documents), ranking_policy)
paths = [documents[index].identity for _, _, index, _ in ranked]
matched = set(paths)
omissions.extend(
Expand Down
5 changes: 4 additions & 1 deletion src/inferrsi/knowledge/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from ..resources.repository_packs import REPO_TYPES
from . import _source_snapshot
from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy
from .retrieval import observation

if TYPE_CHECKING:
Expand Down Expand Up @@ -394,6 +395,7 @@ def search_knowledge(
scenario: str | None = None,
limit: int = 10,
explain: bool = False,
ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY,
) -> list[dict[str, Any]] | dict[str, Any]:
"""List exact package records, using Find when a text query is supplied."""
if limit < 1:
Expand All @@ -404,7 +406,7 @@ def search_knowledge(
from .knowledge_find import rank

corpus, document_records = _catalog_corpus(records)
_, _, scored = rank(query, corpus)
_, _, scored = rank(query, corpus, ranking_policy)
matches = [
(document_records[index], score, components) for score, _, index, components in scored
]
Expand Down Expand Up @@ -435,6 +437,7 @@ def search_knowledge(
selection={
"method": FIND_RELEVANCE if ranking else None, "scope": "package-records",
"ranking_applied": ranking, "state": "applied" if ranking else "not_requested",
**({"ranking_policy": ranking_policy.receipt()} if ranking else {}),
"tie_break": "state_then_id_then_ref" if ranking else None,
},
items=observed,
Expand Down
39 changes: 18 additions & 21 deletions src/inferrsi/knowledge/knowledge_find.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,7 @@
from ._knowledge_errors import MissingSkillsExtra
from ._skill_selection import TASK_STOP_WORDS, indexed_skill, named_backends
from .catalog import BACKENDS, packaged_skill_id

# Author-written intent outranks bulk prose: a term in a title is evidence the
# document is about it, the same term in a long body often is not.
FIELD_WEIGHTS = {
"title": 5.0,
"summary": 4.0,
"tags": 4.0,
"findings": 4.0,
"applicability": 2.0,
"body": 1.0,
}
from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy

# Ties break towards stronger evidence rather than alphabetical identity.
STATE_RANK = {
Expand Down Expand Up @@ -634,10 +624,7 @@ def __init__(
lengths = [fields["body"].total() if "body" in fields else 0 for fields in self._counts]
nonempty_lengths = [length for length in lengths if length]
typical_length = median(nonempty_lengths) if nonempty_lengths else 1
self._body_weights = [
FIELD_WEIGHTS["body"] / math.sqrt(max(1, length / typical_length))
for length in lengths
]
self._body_normalizers = [math.sqrt(max(1, length / typical_length)) for length in lengths]
for fields in self._counts:
appearances.update({token for counts in fields.values() for token in counts})
self._idf = {
Expand All @@ -650,7 +637,8 @@ def idf(self, token: str) -> float:
return self._idf.get(token, self._unseen)

def score(
self, index: int, query_tokens: list[str], *, query_backend: str | None = None
self, index: int, query_tokens: list[str], *, query_backend: str | None = None,
ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY,
) -> tuple[float, dict]:
"""Sum of idf x field weight x sqrt(occurrences).

Expand All @@ -661,17 +649,20 @@ def score(
"""
total = 0.0
detail: dict[str, float] = {}
body_weight = self._body_weights[index]
weights = ranking_policy.weights
body_weight = weights["body"] / self._body_normalizers[index]
backend_weight = _backend_weight(self.documents[index].backend, query_backend)
for token in query_tokens:
weight = self.idf(token) * backend_weight
for name, counts in self._counts[index].items():
hits = counts[token]
if hits:
field_weight = body_weight if name == "body" else FIELD_WEIGHTS[name]
field_weight = body_weight if name == "body" else weights[name]
gain = weight * field_weight * math.sqrt(hits)
total += gain
detail[token] = round(detail.get(token, 0.0) + gain, 2)
if not math.isfinite(total) or not all(map(math.isfinite, detail.values())):
raise ValueError(f"Ranking score overflow for policy {ranking_policy.policy_id!r}")
return total, detail


Expand Down Expand Up @@ -921,15 +912,19 @@ def link(selector: str | None = None) -> dict:
return None


def rank(query: str, corpus: Corpus) -> tuple[
def rank(
query: str, corpus: Corpus, ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY,
) -> tuple[
list[str], dict[str, tuple[str, ...]], list[tuple[float, int, int, dict]]
]:
"""Score matches without opening a Bundle or formatting a delivery."""
query_backend = _query_backend(query)
query_tokens, applied = expand(query)
scored = []
for index, document in enumerate(corpus.documents):
value, detail = corpus.score(index, query_tokens, query_backend=query_backend)
value, detail = corpus.score(
index, query_tokens, query_backend=query_backend, ranking_policy=ranking_policy,
)
if value > 0:
scored.append((value, STATE_RANK.get(document.state, 0), index, detail))
scored.sort(key=lambda row: (
Expand All @@ -956,6 +951,7 @@ def find(
limit: int = 5,
explain: bool = False,
decision_cards: bool = False,
ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY,
registry: "ChannelRegistry | None" = None,
backend: str | None = None,
platform: str | None = None,
Expand All @@ -967,7 +963,7 @@ def find(
"""Find local matches, optionally annotating them from the verified ranking source."""
if type(limit) is not int or limit < 1:
raise ValueError("limit must be a positive integer")
query_tokens, applied, scored = rank(query, corpus)
query_tokens, applied, scored = rank(query, corpus, ranking_policy)
query_backend = _query_backend(query) if decision_cards else None
index = None
if searchspace_coordinate is not None:
Expand Down Expand Up @@ -1030,6 +1026,7 @@ def find(
"query": query,
"tokens": query_tokens,
"corpus_size": len(corpus.documents),
"ranking_policy": ranking_policy.receipt(),
"matched": len(scored),
"items": items,
"no_match": not scored,
Expand Down
23 changes: 17 additions & 6 deletions src/inferrsi/knowledge/knowledge_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
validate_relevance_method,
)
from .catalog import KNOWLEDGE_SCOPES, SCENARIO_ALIASES, knowledge_records, lookup_record
from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy

if TYPE_CHECKING:
from .knowledge_find import Document
Expand Down Expand Up @@ -310,7 +311,10 @@ def _tree(


class KnowledgeReader:
def collect_service_context(self, cue, *, relevance_method, limit, context_bytes):
def collect_service_context(
self, cue, *, relevance_method, limit, context_bytes,
ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY,
):
"""Package knowledge for service campaigns; no Bundle/content identity path."""
from .catalog import _catalog_corpus, without_file_fingerprints
from .context_projection import assemble_context_text
Expand All @@ -327,7 +331,7 @@ def collect_service_context(self, cue, *, relevance_method, limit, context_bytes
):
raise ValueError("Valid cue and positive limit/context budget required")
corpus, records = _catalog_corpus(knowledge_records(file_fingerprints=False))
_, _, ranked = rank(cue, corpus)
_, _, ranked = rank(cue, corpus, ranking_policy)
package = files("inferrsi").joinpath("knowledge")
contexts, omissions, used = [], [], 0
for score, _, index, _ in ranked:
Expand Down Expand Up @@ -386,6 +390,7 @@ def collect_service_context(self, cue, *, relevance_method, limit, context_bytes
"request": {
"relevance": cue,
"relevance_method": FIND_RELEVANCE,
"ranking_policy": ranking_policy.configuration(),
"limit": limit,
"context_bytes": context_bytes,
},
Expand Down Expand Up @@ -698,7 +703,7 @@ def resource(self, identity: str, path: str, *, revision: str) -> bytes:

def _search_order(
self, cue: str, matches, *, kind: str | None, package_only: bool, backend: str | None,
store_documents: list[Document],
store_documents: list[Document], ranking_policy: RankingPolicy,
) -> tuple[dict, int, dict[str, int]]:
from .knowledge_find import (
Corpus,
Expand Down Expand Up @@ -764,7 +769,7 @@ def _search_order(
else:
excluded["filters"] += 1

_, _, scored = rank(cue, Corpus(eligible))
_, _, scored = rank(cue, Corpus(eligible), ranking_policy)
results = {
references[index]: {"score": round(score, 2), "components": components}
for score, _, index, components in scored
Expand All @@ -788,6 +793,7 @@ def collect(
material: bool = False,
relevance: str | None = None,
relevance_method: str | None = None,
ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY,
context_bytes: int | None = None,
decision_cards: dict[str, str | None] | None = None,
) -> dict:
Expand Down Expand Up @@ -932,7 +938,7 @@ def matches(metadata: dict, authority: str) -> bool:
found, considered, rank_excluded = self._search_order(
cue, matches, kind=kind, backend=backend,
package_only=package_filters or kind == "knowledge",
store_documents=store_documents,
store_documents=store_documents, ranking_policy=ranking_policy,
)
considered += len(omitted)
requested = list(found)
Expand Down Expand Up @@ -991,7 +997,9 @@ def select(reference: str, bundle: Bundle, view: dict) -> None:
if is_skill:
if index is None:
index = indexed_skill(record, view, bundle.content)
context, omission = context_view(index, view, bundle.content, cue, available)
context, omission = context_view(
index, view, bundle.content, cue, available, ranking_policy,
)
else:
context, omission = record_context(record, view, bundle.content, available)
except (ValueError, KeyError, TypeError) as exc:
Expand Down Expand Up @@ -1133,6 +1141,8 @@ def select(reference: str, bundle: Bundle, view: dict) -> None:
from .retrieval import observation

selection = result.get("selection", {})
if selection:
selection["ranking_policy"] = ranking_policy.receipt()
result["retrieval"] = observation(
entrypoint="collect", request={
"query": query, "relevance": relevance, "relevance_method": relevance_method,
Expand All @@ -1145,6 +1155,7 @@ def select(reference: str, bundle: Bundle, view: dict) -> None:
}, selection={
"method": selection.get("method"),
"scope": selection.get("scope"),
**({"ranking_policy": selection["ranking_policy"]} if selection else {}),
"ranking_applied": find_ranking,
"state": "applied" if find_ranking else "explicit_ids" if ids is not None
else "not_requested",
Expand Down
52 changes: 52 additions & 0 deletions src/inferrsi/knowledge/ranking_policy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Versioned field weights for the shared lexical Knowledge ranking."""

from __future__ import annotations

import hashlib
import json
import re
import sys
from collections.abc import Mapping
from dataclasses import dataclass, field
from types import MappingProxyType

# Bump when the scoring or tie-breaking semantics change.
RANKING_VERSION = 1
_DEFAULT_WEIGHTS = MappingProxyType({
"title": 5.0, "summary": 4.0, "tags": 4.0, "findings": 4.0,
"applicability": 2.0, "body": 1.0,
})


@dataclass(frozen=True)
class RankingPolicy:
"""A named set of overrides, expanded once into immutable effective weights."""

policy_id: str = "default"
weights: Mapping[str, float] = field(default_factory=dict)

def __post_init__(self) -> None:
if not isinstance(self.policy_id, str) or not re.fullmatch(
r"[a-zA-Z0-9][a-zA-Z0-9_.-]*", self.policy_id
):
raise ValueError("Ranking policy requires a nonempty identifier")
if not isinstance(self.weights, Mapping) or self.weights.keys() - _DEFAULT_WEIGHTS.keys():
raise ValueError("Unknown ranking weight field")
effective = dict(_DEFAULT_WEIGHTS)
for name, value in self.weights.items():
if type(value) not in (float, int) or not 0 <= value <= sys.float_info.max:
raise ValueError(f"Ranking weight for {name} must be finite and nonnegative")
effective[name] = float(value) if value else 0.0
object.__setattr__(self, "weights", MappingProxyType(effective))

def configuration(self) -> dict:
"""Return the full effective rule, also suitable for service-mode receipts."""
return {"id": self.policy_id, "version": RANKING_VERSION, "weights": dict(self.weights)}

def receipt(self) -> dict:
configuration = self.configuration()
raw = json.dumps(configuration, sort_keys=True, separators=(",", ":")).encode("utf-8")
return {**configuration, "config_sha256": hashlib.sha256(raw).hexdigest()}


DEFAULT_RANKING_POLICY = RankingPolicy()
5 changes: 4 additions & 1 deletion src/inferrsi/knowledge/research.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from .catalog import _catalog_corpus, _scoped_records
from .knowledge_find import rank
from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy

PROCEDURE = (
"data/skill_library/workflows/research/inference-engine-research/"
Expand Down Expand Up @@ -42,6 +43,7 @@ def research_knowledge(
target_backend: str | None = None,
target_device: str | None = None,
target_memory_gib: float | None = None,
ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY,
) -> dict:
"""Union separate research queries, preserving every package filter and record.
Expand Down Expand Up @@ -82,7 +84,7 @@ def research_knowledge(
continue
seen.add(term.casefold())
query = {"group": group, "query": term}
_, _, scored = rank(term, corpus)
_, _, scored = rank(term, corpus, ranking_policy)
records = [document_records[index] for _, _, index, _ in scored]
queries.append({**query, "matches": len(records)})
streams.append(records)
Expand All @@ -100,6 +102,7 @@ def research_knowledge(
break
return {
"model": model,
"ranking_policy": ranking_policy.receipt(),
"profile": profile,
"queries": queries,
"filters": filters,
Expand Down
Loading
Loading