Skip to content

feat(eval): RAG retrieval, answer-accuracy and scale benchmark - #4733

Merged
kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:kalin/festive-goodall-31a3ec
Oct 5, 2026
Merged

kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:kalin/festive-goodall-31a3ec

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Document Q&A had no way to tell whether a wrong answer came from retrieval or from the model: the only quality signal was LLM-judged scenarios over ~10 small files. This adds gaia eval retrieval --component rag, which scores retrieval (recall@k, MRR) against labelled evidence pages on real documents, grades answers by numeric/exact match, and marks each wrong answer as a retrieval miss or a generation miss. It also measures indexing time, memory and query latency as the library grows from 10 to 1,000 documents. Runs on this branch already found real bugs: half of public SEC filings are refused as "password-protected" (#4735), RAGSDK.query leaks earlier questions' context into later answers (#4736), and the agent's document search ranks keyword hits above every semantic match (#4737); also #4738–#4741.

  • PR gate: --suite pr is offline and deterministic: identical ranks across runs, about 30 s. It runs in test_rag.yml against tests/fixtures/eval_baselines/rag-retrieval/pr.json, an unedited result from a real run on a Strix Halo box. Replace it with this job's first retrieval-pr artifact from the strix-point pool.
  • Nightly: --suite full (FinanceBench, AMD Instinct docs, a two-column arXiv paper, XQuAD in 7 languages, scale tiers, hard cases) runs from the new eval_retrieval.yml. It is report-only until a full baseline from that workflow is committed.
  • Corpora: downloaded on demand from pinned URLs with sha256 checks and license notes; nothing downloaded is committed.
  • Product change: RAGConfig.use_vlm (default on) lets the gate run without the image model, so whether it is installed doesn't change PR scores.

Refs #868

Test plan

  • pytest tests/unit/eval/test_retrieval_bench.py tests/unit/rag/ passes
  • python util/lint.py --all passes apart from the two existing Windows-only pylint false positives (security.py, eval/bench/harness.py)
  • With Lemonade and the RAG embedder running: gaia eval retrieval --suite pr --gate tests/fixtures/eval_baselines/rag-retrieval/pr.json prints the gate as passed
  • The test_rag.yml integration job runs the gate step green on the strix-point runner
  • Dispatch eval_retrieval.yml once and check that report.md lands in the job summary
🔍 Technical details
  • Scoring maps every retrieved chunk back to the extracted text (whitespace-normalized) and to pages via [Page N] markers. Hand-labelled quotes are re-verified against GAIA's extraction on every run, and a missing quote raises.
  • Two retrieval pipelines are scored: sdk (RAGSDK._search_chunks) and agent (the query_documents tool as the chat agents run it).
  • Hard cases: a file replaced after indexing, identical copies, near-duplicate filings, scanned and truncated PDFs, corrupted caches, the document cap, planted prompt injection, and chat-history leakage.
  • A refused document is recorded and its questions score as misses. The gate fails if more labelled documents fail to index, if a gated metric drops by more than one question's worth, or if a passing hard case fails.
  • Full runs make the VLM read a test image first and stop on failure; --no-vlm measures text-only extraction. On the authoring machine the Qwen3-VL backend crashes on every image.

…l documents

Document Q&A had no measurement of whether retrieval found the evidence, only
LLM-judged scenarios over ~10 small files, so a retrieval miss could not be told
apart from a generation miss. `gaia eval retrieval --component rag` scores
recall@k/MRR against labelled evidence pages and quotes, grades answers by
numeric/exact match (judge only for free-form, opt-in), classifies each wrong
answer as a retrieval or generation miss, and measures indexing time, memory,
index size and query latency from 10 to 1,000+ documents.

- Corpora download on demand from pinned URLs with sha256 checks and license
  notes (FinanceBench, AMD Instinct docs, a two-column arXiv paper, XQuAD,
  Simple English Wikipedia); nothing downloaded is committed. Hand-written
  labels for repo documents and the AMD docs are verified against GAIA's own
  extraction on every run.
- Hard cases: a file replaced after indexing, duplicate and near-duplicate
  documents, scanned and truncated PDFs, corrupted caches, the document cap,
  planted prompt injection, and chat history leaking between queries.
- `--suite pr` is offline and deterministic and gates RAG pull requests against
  a committed baseline from a real run; `--suite full` runs nightly.
- RAGConfig gains `use_vlm` (default on) so the gate does not depend on whether
  a VLM is installed.

Refs amd#868
@github-actions github-actions Bot added documentation Documentation changes dependencies Dependency updates devops DevOps/infrastructure changes rag RAG system changes cli CLI changes eval Evaluation framework changes tests Test changes performance Performance-critical changes labels Oct 5, 2026
@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Verdict: Request changes

This adds gaia eval retrieval, a benchmark that scores document Q&A in separate pieces: did search find the evidence, was the answer right, and what indexing and queries cost as the library grows. It also adds an offline gate to the RAG CI job. The design is careful: labels are checked against real extraction, and refused documents are recorded instead of skipped. Two gaps should be fixed before it becomes a gate and a nightly:

  • The nightly will crash in its scale phase on a clean install. The Wikipedia distractor loader needs pyarrow, which no extra installs. Your machine had it, so the problem never showed up. On a fresh runner the full run dies after hours of dataset scoring. Add pyarrow to the extra the workflow installs, or fail on it before the run starts.
  • The PR gate can break with no warning. Its labelled questions point into eval/corpus/** and data/pdf/**, but neither path triggers test_rag.yml. A docs or corpus edit then merges green, and the next unrelated RAG PR fails on a label error it didn't cause. Add both paths to the workflow's path filters.

Real-world evidence

N/A: no evidence bundle was produced for this run. The PR description lists the gaia eval retrieval --suite pr --gate … command as an unchecked test-plan item but shows none of its output. The committed pr.json baseline is a real run from a Strix Halo machine, which shows the command completed there. This verdict rests on static review for the CLI and both workflows. Paste the --suite pr --gate output (the [GATE] lines) into the PR once the strix-point job has run it.

🔍 Technical details

🟡 Undeclared pyarrow dependency (src/gaia/eval/retrieval/corpus.py:~310, wikipedia_distractors)
import pyarrow.parquet as pq is the only use of pyarrow in the repo, and nothing in setup.py declares it: not rag, not dev, and not the chat hub package. eval_retrieval.yml installs .[dev,rag] ./hub/agents/chat/python, and _run_scale runs only after every dataset is scored, so a nightly with the default scale_tiers=(10,100,1000) hits an ImportError late in its 480-minute budget. This is the "hidden-state masking" case from CLAUDE.md. Either add "pyarrow" to an extra the workflow installs (a new eval extra is cleanest), or import it at run() start when tiers is non-empty, so the failure comes first:

if tiers:
    import pyarrow.parquet  # noqa: F401  — fail before hours of indexing, not after

🟡 Gate inputs aren't in test_rag.yml path filters (.github/workflows/test_rag.yml:15-40)
repo_docs.json labels quotes in data/pdf/Oil-and-Gas-…pdf and 20 files under eval/corpus/. resolve_evidence correctly raises LabelError when a quote moves, but an edit to those files doesn't run this workflow. Add both paths to the push and pull_request filters:

      - 'eval/retrieval/**'
      - 'eval/corpus/**'
      - 'data/pdf/**'

🟢 compare() ignores baseline hard cases that the current run didn't run (runner.py:~7126)
--gate … --no-hard-cases passes even though the baseline has six cases. Iterating the baseline's case ids and failing any pass case that's missing from the current run would close this.

🟢 run() overwrites caller-supplied rag_overrides (runner.py:~6851)
opts.rag_overrides = {"use_vlm": vlm} discards whatever the caller passed in. Merge instead: opts.rag_overrides = {**opts.rag_overrides, "use_vlm": vlm}.

🟢 Docs and PR disagree on the gate tolerance and runtime
eval.mdx says the tolerance is "widened to one question", but compare() allows 1.5 / n, which tolerates one flip and fails at two. That works as intended, but the doc should say so. The doc also says the pr suite takes "~1 min", while the PR says about 30 s.

Strengths

  • The use_vlm switch in RAGSDK only changes the cache key when it's off, so existing users' caches stay valid. It's covered by test_use_vlm.py.
  • The benchmark fails loudly throughout. It raises on labels that can't be found, on corpus checksum mismatches (and never silently re-downloads), on a VLM that fails its probe, and when more than 1% of chunks can't be located.
  • Retrieval misses and generation misses are counted separately, and both the SDK path and the agent's query_documents path are scored, so the numbers show which part of the pipeline failed.

…n its inputs

The nightly would have died hours in, at the scale phase, because the Wikipedia
distractor loader needs pyarrow and no extra installed it. pyarrow is now in the
`eval` extra (which the nightly installs), and a run with scale tiers checks for
it before indexing anything.

- test_rag.yml now triggers on eval/corpus/** and data/pdf/**, the documents the
  PR gate's labels point into, so an edit there can't break the next RAG PR.
- The gate fails when a hard case that passed in the baseline was not run.
- Caller-supplied rag_overrides are merged, not replaced.
- Docs state the real tolerance (1.5 questions) and the pr suite's runtime.
…run in the chat lane

The corpus cache was built from a hard-coded home path, which the GAIA_HOME
ratchet rejects. Four harness tests call the chat agent's real
query_documents tool, so they failed in every lane without the chat wheel;
they now skip there and run in test_chat_agent.yml, which installs it.
…install

The RAG retrieval gate could not start on CI: it looked for its labelled
questions next to the installed package, and the runner installs gaia as a
wheel, so eval/retrieval/datasets/ was never there.

The labels, the corpus manifest and the pr suite's documents live in the
repository, not in the package. They are now read from --repo-root, else the
current directory, else the checkout the module runs from; with none of those
the command stops and names the flag. Both workflows pass the checkout.

main gained `gaia eval retrieval --component code` (amd#4742) under the same
subcommand. The two parsers are now one: --component picks rag (default) or
code, and a suite or flag that belongs to the other component is rejected with
a message instead of being ignored.

Conflicts: src/gaia/cli.py, setup.py, docs/reference/eval.mdx.
The retrieval gate stopped with "1/54 chunks could not be located" on the oil
and gas PDF. The chunk is in the document; the benchmark looked for it in the
wrong place.

Since amd#4723 a chunk longer than the embedder's input is split in two after
chunking. The next chunk's overlap is cut from the unsplit chunk, so when the
split leaves a short tail the next chunk starts before that tail. The locator
only searched forward from the previous chunk's start and reported it missing.

It now also accepts a chunk that starts before the previous one when it runs
through it and does not reach past the chunk before that. Repeated text
elsewhere in the document still counts as unlocated.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 5, 2026
Merged via the queue into amd:main with commit 30f257f Oct 5, 2026
@kovtcharov-amd
kovtcharov-amd deleted the kalin/festive-goodall-31a3ec branch October 5, 2026 17:29
kovtcharov-amd pushed a commit to Drchennnn/gaia that referenced this pull request Nov 10, 2026
…amd#7131)

## Summary

A document indexed twice under different names no longer fills the
model's context with copies of itself. Identical chunks now count once
in a search, so the model gets k different chunks. Each collapsed chunk
lists every file that holds it, and the agent cites all of them instead
of whichever copy was indexed first.

## Why

The `exact_duplicate` hard case in amd#4733 found duplicates taking 40% of
the top 5 chunks given to the model. As the bot noted on the issue,
collapsing after FAISS's top-k cut would only trade crowding for a short
context, so the search fetches more candidates until it has k distinct
ones.

## Linked issue

Closes amd#4740

## Changes

- **The SDK search collapses identical chunks before cutting to k.** It
asks FAISS for more results until it has k distinct chunks or has seen
the whole index, and records where each chunk's copies sit.
`chunk_metadata` gains `source_files` / `source_paths` (every file
holding the text), and `query_metadata["source_files"]` includes them.
`source_file` / `source_path` stay as they were.
- **`query_documents` cites every file holding the text:** `source_file`
is the first, and `also_in` lists the rest. It resolves positions in one
pass instead of `rag.chunks.index()` per chunk.
- **`query_specific_file` looks a chunk up only in the requested file,**
so a twin in another document can't supply the page number.
- **The RAG SDK guide** says identical chunks count once, and fixes its
example's `meta['source']`, a key that doesn't exist.

## Test plan

Run in a `python:3.12` container:

- [x] `pytest tests/unit/rag/test_duplicate_chunks.py`: 7 passed. All 7
fail on `main` (a copy takes a place, a missing source, a citation from
the wrong file).
- [x] `pytest tests/unit/rag tests/test_rag.py
tests/unit/test_chat_rag_budget.py
tests/unit/chat/ui/test_sse_handler.py`: 1,341 passed, 35 skipped.
- [x] Full `pytest tests/unit`: 38,405 passed, 584 skipped, 15 failed,
of 38,908 collected, with no crashed workers. The 15 fail the same way
on `main` in this container: 14 shell-guardrail and skill-grant tests
refuse `gh` and `npm` because neither is installed there, and one
expects a folder it can't create, but the container runs as root. 44
tests have `::` inside their parameters, so they were rerun by file to
account for them.
- [x] `python util/lint.py --all`: passes. Pylint crashed in its
parallel workers, so it was rerun alone with `--jobs 1`, which exits 0.

The tool result the agent reads gains `also_in`, so `rag_quality` is the
eval category to watch on the next RC.

## Evidence

The new tests index one policy under `policy.txt` and `policy
(copy).txt` beside three other documents, in a real FAISS index:

```
# main
AssertionError: a copy took one of the 3 places
AssertionError: assert '.../policy.txt' == '.../policy (copy).txt'   # page lookup used the other file

# this PR
7 passed
```

- [ ] **Agent exposed in the Agent UI**: N/A, no visible change.
- [ ] **MCP tools / servers**: N/A
- [ ] **CLI**: N/A
- [ ] **HTTP API / REST**: N/A

## Checklist

- [x] I have linked a GitHub issue above (`Closes #N` / `Fixes #N` /
`Refs #N`).
- [x] I have described **why** this change is being made, not just what
changed.
- [x] I have run linting and tests locally (`python util/lint.py --all`,
`pytest tests/unit/`).
- [x] I have attached **real-world evidence matched to the surface I
changed** (see Evidence above), or marked each surface N/A.
- [x] I have updated documentation if user-visible behavior changed (see
[CONTRIBUTING.md](../CONTRIBUTING.md)).
kovtcharov-amd pushed a commit that referenced this pull request Nov 21, 2026
…ntic match, and slows down at scale (#8737)

## Summary

Fixed amd/gaia #4737 in both `query_documents` and
`query_specific_file`. The fixed 0.6-0.8 keyword boost (which outranked
every dense score, typically 0.3-0.6) is replaced by reciprocal rank
fusion (k=60) in shared helpers `_fuse_dense_and_keyword` /
`_fuse_extra_scores` / `_adaptive_max`: each ranking contributes
1/(k+rank), so the top dense and top keyword matches compete on equal
terms and a chunk both rankings like wins outright.

## Why

A keyword hit ranked above every semantic match, so retrieval returned
lexically matching but semantically weaker chunks first, and the ranking
slowed down at scale.

## Linked issue

Fixes #4737

## Changes

- Reciprocal rank fusion (k=60) replaces the fixed 0.6-0.8 keyword boost
in shared helpers `_fuse_dense_and_keyword` / `_fuse_extra_scores` /
`_adaptive_max`.
- The keyword pool now covers every slot (limit=`_adaptive_max`, up to
25) instead of stopping at 5.
- The per-document best passages are scored on the same fused scale
while still being added after the top, preserving the multi-document
spread guarantee.
- The remaining O(n) `rag.chunks.index()` calls (debug-only paths) are
replaced with a one-pass first-index dict; the O(n) regex scan was
already gone via the KeywordIndex inverted index (#6393), whose `rank()`
scoring is unchanged.
- Follow-up: fused scores are rescaled to a 0-1 scale in both fusion
helpers (a chunk ranked first by both lists scores 1.0; ordering
unchanged), the RAG tools spec now documents rank fusion instead of the
old fixed keyword boost, and `chunks_before_dedup_indices` now lists the
keyword chunks too so it matches `total_chunks_before_dedup`.
- Collision check clean: body search for PRs mentioning 4737 returned
only merged #4733 (the eval benchmark PR that found the issue); timeline
cross-refs were #4733 and merged #6275 (test-only PR for #4796/#6260,
not a fix). Claimed the issue with a `.take` comment (id 7067087685).
Pushed to SIDDARTHAREDDY8/gaia branch oss-bhai-2026-11-21-p1, commit
fce6ccf, base main bc3d152, verified on the fork. No PR opened
(reviewer gates that).

## Test plan

- New `tests/unit/rag/test_query_keyword_fusion.py`: 10 passed (incl. a
new test that `relevance_score` stays in 0-1) (fusion order, keyword hit
no longer outranks top dense match in both tools, chunk both rankings
like wins, keyword pool covers all slots, debug indices).
- Related suites pass: `test_keyword_search.py`,
`test_keyword_search_tools.py`, `test_query_balances_documents.py`
(incl. multi-document spread/budget), `test_retrieval_bench_harness.py`,
`test_lemonade_reranking.py` (47 passed).
- Full `tests/unit/rag/`: 791 passed, 58 failed, 52 skipped; the 58
failures are all pre-existing in untouched epub/html/image extraction
modules (verified: failure list with the fix was identical to pristine
main before dep installs; remaining are env/library issues, e.g.
pixel-value assertion in image extraction).
- Black + isort pass on both changed files (repo pyproject config).
- Eval category to watch on the next RC: `rag_quality` (this change
alters which passages fill the context).
- The rag_quality eval and `gaia eval retrieval --suite full` could NOT
be run here: they need the Lemonade embedding server/models, unavailable
in this VM. Closest runnable proxies passed: the retrieval bench harness
(both pipelines find labelled evidence) and the new tests, which
directly assert the reported failure mode (keyword hit above every
semantic match) is gone.

## Evidence

- [ ] **Agent exposed in the Agent UI** (Chat, Email, ...) — N/A: this
change touches internal RAG ranking logic only, no Agent UI surface.
- [ ] **MCP tools / servers** — N/A: no MCP surface changed.
- [ ] **CLI** — N/A: no CLI surface changed; the `gaia eval retrieval`
CLI could not run here (needs the Lemonade embedding server/models,
unavailable in this VM).
- [ ] **HTTP API / REST** — N/A: no HTTP API surface changed.
- Evidence for this internal change: the new fusion tests directly
assert the reported failure mode is gone, and the retrieval bench
harness passes (both pipelines find labelled evidence).

## Checklist

- [x] I have linked a GitHub issue above (`Closes #N` / `Fixes #N` /
`Refs #N`).
- [x] I have described **why** this change is being made, not just what
changed.
- [x] I have run linting and tests locally (`python util/lint.py --all`,
`pytest tests/unit/`).
- [x] I have attached **real-world evidence matched to the surface I
changed** (see Evidence above), or marked each surface N/A.
- [x] I have updated documentation if user-visible behavior changed (see
[CONTRIBUTING.md](../CONTRIBUTING.md)).

---------

Signed-off-by: SIDDARTHA REDDY <[email protected]>
Signed-off-by: Siddartha Reddy Chinthala <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI changes dependencies Dependency updates devops DevOps/infrastructure changes documentation Documentation changes eval Evaluation framework changes performance Performance-critical changes rag RAG system changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants