Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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
6 changes: 3 additions & 3 deletions _si_article_/benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ DeepTrack checkout are never modified by these operations.
## Gold annotations and comparability

- `gold/dogfood_kilin_code.json` contains 22 questions, including five
deliberate abstention cases, verified for source-chunk overlap against the
**23 October 2026** KíLín archive. Citation paths and line numbers describe
that snapshot; review them whenever code or notebooks change. An overlapping
deliberate abstention cases. Citation paths and line numbers were checked
by hand against commit **6cb105d20 (3 December 2026)** and describe that
revision; review them whenever code or notebooks change. An overlapping
chunk does not, by itself, establish that the written reference answer is
scientifically or technically correct.
- `gold/dogfood_deeptrack_code.json` retains the historical DeepTrack2
Expand Down
129 changes: 128 additions & 1 deletion _si_article_/benchmarks/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@

Heuristic answer checks that require human interpretation.

- ``bootstrap_interval`` and ``wilson_interval``

95% intervals for mean scores and for counts.

Examples
--------
>>> from benchmarks.common import citation_validity, format_query
Expand All @@ -65,8 +69,10 @@
from difflib import SequenceMatcher
import json
from pathlib import Path
import random
import re
import shutil
from statistics import NormalDist
from zoneinfo import ZoneInfo

from kilin.query_formats import format_qwen3_query
Expand All @@ -88,10 +94,17 @@
"citation_coverage",
"abstains",
"verbatim_overlap_chars",
"bootstrap_interval",
"wilson_interval",
]

LOCAL_TIMEZONE = ZoneInfo("Europe/Rome")

# Resamples and seed of the bootstrap intervals; the fixed seed makes the
# intervals of a run reproducible.
BOOTSTRAP_RESAMPLES = 10_000
BOOTSTRAP_SEED = 0


CODE_RETRIEVAL_INSTRUCTION = (
"Given a coding problem description, retrieve the source code that "
Expand Down Expand Up @@ -167,7 +180,9 @@ def evaluate_retrieval(
Returns
-------
dict[str, dict[str, float]]
Mean NDCG, MAP, recall, precision and MRR at each cutoff.
Mean NDCG, MAP, recall, precision and MRR at each cutoff, and under
``ndcg_interval`` the 95% bootstrap interval of NDCG@10 over the
queries (when 10 is a cutoff).

Notes
-----
Expand Down Expand Up @@ -222,6 +237,13 @@ def evaluate_retrieval(
mrr[f"MRR@{k}"] += 1.0 / (rank + 1)
break

ndcg_interval: dict[str, list[float]] = {}
if 10 in k_values and scores:
low, high = bootstrap_interval(
[query_scores["ndcg_cut_10"] for query_scores in scores.values()]
)
ndcg_interval["NDCG@10"] = [round(low, 5), round(high, 5)]

query_count = len(scores) or 1
qrel_count = len(qrels) or 1
for k in k_values:
Expand All @@ -237,9 +259,114 @@ def evaluate_retrieval(
"recall": recall,
"precision": precision,
"mrr": mrr,
"ndcg_interval": ndcg_interval,
}


def bootstrap_interval(
values,
level: float = 0.95,
resamples: int = BOOTSTRAP_RESAMPLES,
seed: int = BOOTSTRAP_SEED,
) -> tuple[float, float]:
"""Return a percentile bootstrap interval for the mean of values.

Parameters
----------
values: Sequence[float]
Per-item scores, for example the NDCG@10 of each query or the
citation coverage of each answer.
level: float, optional
Coverage of the interval. Defaults to 0.95.
resamples: int, optional
Number of resamples. Defaults to ``BOOTSTRAP_RESAMPLES``.
seed: int, optional
Seed of the resampling, so that a run gives the same interval.
Defaults to ``BOOTSTRAP_SEED``.

Returns
-------
tuple[float, float]
Lower and upper bound of the mean.

Raises
------
ValueError
If values is empty or level is not between 0 and 1.

"""

values = [float(value) for value in values]
if not values:
raise ValueError("values must not be empty.")
if not 0.0 < level < 1.0:
raise ValueError("level must be between 0 and 1.")
generator = random.Random(seed)
count = len(values)
means = sorted(
sum(generator.choices(values, k=count)) / count
for _ in range(resamples)
)
tail = (1.0 - level) / 2.0
low = means[int(tail * (resamples - 1))]
high = means[int(round((1.0 - tail) * (resamples - 1)))]
return low, high


def wilson_interval(
successes: int, total: int, level: float = 0.95
) -> tuple[float, float]:
"""Return the Wilson score interval of a proportion.

Parameters
----------
successes: int
Number of items with the property, for example answers citing only
supplied evidence.
total: int
Number of items.
level: float, optional
Coverage of the interval. Defaults to 0.95.

Returns
-------
tuple[float, float]
Lower and upper bound of the proportion, between 0 and 1.

Raises
------
ValueError
If the counts or level are invalid.

Notes
-----
Unlike the normal approximation, the Wilson interval stays inside
[0, 1] and is informative when every item succeeds (for example, 42 of
42 gives 0.92--1.00).

"""

if total < 1 or not 0 <= successes <= total:
raise ValueError("Need 0 <= successes <= total and total >= 1.")
if not 0.0 < level < 1.0:
raise ValueError("level must be between 0 and 1.")
z = NormalDist().inv_cdf(0.5 + level / 2.0)
proportion = successes / total
denominator = 1.0 + z * z / total
centre = (proportion + z * z / (2.0 * total)) / denominator
half_width = (
z
* ((proportion * (1.0 - proportion) + z * z / (4.0 * total)) / total)
** 0.5
/ denominator
)
# The bounds are exactly 0 or 1 when no item or every item succeeds;
# set them directly, as rounding can otherwise give 0.9999999999999999.
low = 0.0 if successes == 0 else max(0.0, centre - half_width)
high = 1.0 if successes == total else min(1.0, centre + half_width)
return low, high


def corpus_already_written(directory: Path) -> bool:
"""Return whether a project's corpus folder is already populated.

Expand Down
47 changes: 25 additions & 22 deletions _si_article_/benchmarks/gold/dogfood_kilin_code.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{
"corpus": "kilin-code",
"corpus_description": "KíLín kilin/ package and tutorials/ notebooks from KiLin_source(3).zip (2026-10-23). The source includes the packaged JSON defaults and project types. Citation positions must be rechecked when the KíLín source changes.",
"corpus_description": "KíLín kilin/ package and tutorials/ notebooks at commit 6cb105d20 (2026-12-03). The source includes the packaged JSON defaults and project types. Citation positions must be rechecked when the KíLín source changes.",
"tasks": [
{
"task_id": "A1",
"question": "Why does chunk_source_units skip source units and chunks whose text is only whitespace?",
"gold_citations": [
"kilin/chunking.py:356",
"kilin/chunking.py:356-357",
"kilin/chunking.py:861"
],
"fact_checklist": [
Expand All @@ -21,7 +21,7 @@
"task_id": "A2",
"question": "How does code_search match named code entities and rank the corresponding chunks?",
"gold_citations": [
"kilin/retrievals/strategies/retrieval_code.py:227-335"
"kilin/retrievals/strategies/retrieval_code.py:305-420"
],
"fact_checklist": [
"It resolves entities explicitly named in a nonblank query.",
Expand All @@ -37,7 +37,8 @@
"task_id": "A3",
"question": "What is KíLín's default RAG system prompt, word for word?",
"gold_citations": [
"kilin/rag.py:307-313"
"kilin/rag.py:436-441",
"kilin/project_types/code.json:16"
],
"fact_checklist": [
"It instructs grounding in supplied project evidence.",
Expand All @@ -52,7 +53,8 @@
"task_id": "A4",
"question": "How does RAGSession format numbered evidence for a chat answer?",
"gold_citations": [
"kilin/rag.py:4476-4530"
"kilin/retrievals/evidence_budget.py:190-216",
"kilin/rag.py:7350-7485"
],
"fact_checklist": [
"Each item starts with [n] and a path plus line range.",
Expand All @@ -67,7 +69,7 @@
"task_id": "A5",
"question": "Does hybrid_search use Reciprocal Rank Fusion, and what are its default rank constant and count?",
"gold_citations": [
"kilin/retrievals/strategies/retrieval_hybrid.py:106-178"
"kilin/retrievals/strategies/retrieval_hybrid.py:106-190"
],
"fact_checklist": [
"Hybrid search uses Reciprocal Rank Fusion (RRF).",
Expand All @@ -81,8 +83,8 @@
"task_id": "A6",
"question": "What happens when scan_repository encounters more than its max_entries limit?",
"gold_citations": [
"kilin/repository.py:437-480",
"kilin/repository.py:550-578"
"kilin/repository.py:437-500",
"kilin/repository.py:566-575"
],
"fact_checklist": [
"The default max_entries limit is 10,000.",
Expand All @@ -96,8 +98,8 @@
"task_id": "A7",
"question": "Does EmbeddingSession configure embedding batch_size, or is that specified for build_semantic_index?",
"gold_citations": [
"kilin/retrievals/strategies/retrieval_semantic.py:133-193",
"kilin/embeddings.py:144-165"
"kilin/retrievals/strategies/retrieval_semantic.py:133-202",
"kilin/embeddings.py:144-152"
],
"fact_checklist": [
"EmbeddingSession does not take a batch_size constructor argument.",
Expand All @@ -110,8 +112,8 @@
"task_id": "A8",
"question": "What retrieval_count and max_new_tokens defaults does KíLín ship for a new project profile?",
"gold_citations": [
"kilin/kilin_defaults.json:184-193",
"kilin/project.py:214-241"
"kilin/kilin_defaults.json:221-231",
"kilin/project.py:212-239"
],
"fact_checklist": [
"Project-profile retrieval_count defaults to 5.",
Expand All @@ -126,8 +128,8 @@
"question": "What distinguishes KíLín's built-in code and literature project types?",
"gold_citations": [
"kilin/project_type.py:1-45",
"kilin/project_types/code.json:1-15",
"kilin/project_types/literature.json:1-15"
"kilin/project_types/code.json:1-16",
"kilin/project_types/literature.json:1-17"
],
"fact_checklist": [
"Different project type JSON files select extension lists and source folder names.",
Expand All @@ -141,8 +143,8 @@
"task_id": "A10",
"question": "What data does indexes_are_current compare to determine whether a persisted index can be reused?",
"gold_citations": [
"kilin/retrievals/persistence.py:366-405",
"kilin/retrievals/persistence.py:473-498"
"kilin/retrievals/persistence.py:366-409",
"kilin/retrievals/persistence.py:473-506"
],
"fact_checklist": [
"It compares a deterministic SHA-256 fingerprint of chunks and the code graph.",
Expand All @@ -168,7 +170,7 @@
"task_id": "A12",
"question": "Does KíLín use a configurable registry of fourth-party retrieval channels inside RAGSession._retrieve, or explicit search calls?",
"gold_citations": [
"kilin/rag.py:2920-3160"
"kilin/rag.py:4584-4682"
],
"fact_checklist": [
"The reviewed retrieval path directly calls semantic_search, lexical_search, and code_search before hybrid fusion.",
Expand Down Expand Up @@ -230,7 +232,8 @@
"task_id": "A17",
"question": "Does KíLín's deterministic context expansion replace or reorder the initial RRF ranking?",
"gold_citations": [
"kilin/retrievals/context_expansion.py:139-255"
"kilin/retrievals/context_expansion.py:260-300",
"kilin/retrievals/context_expansion.py:455-586"
],
"fact_checklist": [
"plan_context_expansion identifies explicitly requested context.",
Expand All @@ -244,7 +247,7 @@
"task_id": "A18",
"question": "Which model presets does the KíLín GUI offer, and for which roles and backends?",
"gold_citations": [
"kilin/gui/model_catalog.py:90-166"
"kilin/gui/model_catalog.py:154-175"
],
"fact_checklist": [
"The catalog lists six presets in MODEL_CHOICES.",
Expand All @@ -259,7 +262,7 @@
"task_id": "A19",
"question": "How does choose_backend resolve auto, and what happens if MLX is explicitly selected off Apple Silicon?",
"gold_citations": [
"kilin/runtime.py:84-112"
"kilin/runtime.py:84-117"
],
"fact_checklist": [
"auto chooses MLX on native Apple Silicon and Torch otherwise.",
Expand All @@ -273,8 +276,8 @@
"task_id": "A20",
"question": "Does the GUI restrict model downloads to MODEL_CHOICES, or does it accept validated custom model identifiers?",
"gold_citations": [
"kilin/gui/engine.py:1157-1190",
"kilin/gui/model_catalog.py:136-155"
"kilin/gui/engine.py:1522-1559",
"kilin/gui/model_catalog.py:1-7"
],
"fact_checklist": [
"The GUI catalog lists suggested presets, not an allowlist.",
Expand Down
Loading
Loading