Skip to content

fix(rag): unblock the release retrieval eval (image chunks, pypdf labels) - #5490

Merged
kovtcharov-amd merged 3 commits into
mainfrom
fix/rag-eval-vlm-chunks
Oct 21, 2026
Merged

kovtcharov-amd merged 3 commits into
mainfrom
fix/rag-eval-vlm-chunks

Conversation

@kovtcharov-amd

@kovtcharov-amd kovtcharov-amd commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

The release RAG retrieval eval fails on v0.25.1-rc1 and rc2, and has never completed a real run. The v0.25.0-rc17–19 "passes" were [skip eval] tags. Three latent defects were stacked, each found only after the one before it was fixed:

  • Image text fused onto the next marker (product bug, since v0.14.0). On a PDF page with two or more images, the chunker glued the last word of each image's text onto the next image or page marker (battery.[Page 2]). The benchmark correctly reported "4/59 chunks could not be located". This PR fixes the chunker, not the check. Page citations were never affected.
  • Two labels tied to one pypdf release. Two Attention-paper quotes ended in math that pypdf spaces differently between releases (df f = 2048 vs df f= 2048), so each matched only one version. Both now end before the math.
  • Repeated passages derailed the locator (harness bug). SEC filings repeat whole passages. After a chunk split for the embedder, the locator took a repeat hundreds of pages later, and every chunk after it in that filing counted as unlocated (644 chunks across four FinanceBench filings). The nearby copy now wins. Placements in every other filing are unchanged.

A fourth problem, filings dense with no-break spaces overflowing the embedder, is a separate product bug tracked in #5547. The eval records it as a refusal rather than stopping.

Test plan

  • Reproduced each failure locally on the same documents: CI's image-heavy PDF (VLM stubbed), the Attention paper under pypdf 6.10.2 and 6.21.1, and the four FinanceBench filings. Each goes to 0 unlocated / 0 label errors after its fix
  • New tests fail without each fix: image text on several pages (both chunking paths), mixed image and body chunks, a fused or invented chunk still unlocated and still stopping the benchmark, and an overlap through a split tail beating a later repeat while a chunk only the repeat explains stays there
  • pytest tests/unit/rag tests/unit/eval tests/test_rag.py, python util/lint.py --all
  • "Eval — RAG retrieval" dispatched on this branch passes
🔍 Technical details
  • Chunker: _split_text_into_chunks replaced each [Page N] ### 🖼️ IMAGE k match (which includes its trailing whitespace) with a bare placeholder. The whitespace is now kept after the placeholder. The cache fingerprint is unchanged, so previously cached VLM documents keep their fused chunks until re-indexed. The defect is cosmetic, so forcing everyone to re-index isn't worth it.
  • Locator: locate_chunks now checks for a copy that starts after the chunk before the previous one and runs past the previous chunk's start, and prefers it over a forward match. Old vs new placements on six filings: only the chunks that had jumped to a far-later duplicate moved.

Indexing a PDF page with two or more images fused the last word of each
image's text onto the next image or page marker ("battery.[Page 2]").
The chunks no longer matched the document's own text, which is why the
release retrieval benchmark stops with "4/59 chunks could not be
located" on every run where the vision model loads. The chunker now
keeps the whitespace that followed each image block when it swaps the
block out and back in.

Page citations were never affected: page lookup does not need a space
before the marker. Documents already in the RAG cache keep their old
chunks until they are re-indexed.
@github-actions github-actions Bot added rag RAG system changes tests Test changes performance Performance-critical changes labels Oct 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve

This fixes the RAG chunker that glued the last word of each image's text onto the next image or page marker (battery.[Page 2]) on PDF pages with two or more images. That is what made the release retrieval eval report unlocatable chunks. The fix is small: the chunker now keeps the whitespace after each image block. The new tests cover both chunking paths, and they also check that a fused or invented chunk is still rejected, so the benchmark's check stays strict.

Nothing blocks merge. One thing to know: documents already in the index keep their fused chunks until someone re-indexes them. The PR description says this is deliberate, and it's a reasonable call since page citations were never affected.

Real-world evidence

N/A: this PR doesn't change a CLI, API or MCP surface (the evidence bundle says the same). The verdict rests on reading the code. I couldn't run the new tests here because pytest isn't installed on this runner. The PR reports 397 tests passing, and its test plan still has an open item: dispatching "Eval — RAG retrieval" on this branch. Running that before merge would confirm the fix end to end.

🔍 Technical details

Issues found

🟢 Redundant .strip() (src/gaia/rag/sdk.py:2294). vlm_pattern always starts at the [Page N] literal, so block has no leading whitespace and content.strip() gives the same result as content. Not a bug. Dropping the extra strip makes it clearer that the stored content and the kept suffix add up exactly to block:

            vlm_blocks.append({"placeholder": placeholder, "content": content})

Correctness check

  • The lookahead in vlm_pattern lets the match take in trailing \n\n before the next [Page …] marker. The old code swapped all of it for a bare placeholder, so neighbouring placeholders ended up touching. The new code keeps block[len(content):] after the placeholder, so the line and paragraph splitting in STEP 2–3 still sees the real gap, and STEP 4's restore puts back text that matches the source.
  • replace(..., 1) has the same first-occurrence behaviour as before, so blocks with identical text behave no differently than they did.

Strengths

  • The fix is in the chunker itself, not in the benchmark's locate check. A negative test (test_a_chunk_absent_from_the_source_is_still_unlocated, plus the IndexingError test) makes sure the check can't quietly get looser later.
  • The test fixture builds the document through _merge_page_texts, the same path indexing uses, so the tests run on the real input shape and not on hand-written strings.
  • Both the section-based and paragraph-based splitting paths are parametrized.

Two evidence quotes from the Attention paper ended in math that pypdf
spaces differently between releases ("df f = 2048" vs "df f= 2048",
"0.1" vs "0 .1"). Each matched only one release, so the benchmark
stopped with a LabelError on whichever one CI installed. The quotes now
end before the math, which still pins the same passage.
@kovtcharov-amd kovtcharov-amd changed the title fix(rag): keep the space after image text when chunking PDFs fix(rag): unblock the release retrieval eval (image chunks, pypdf labels) Oct 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Skill audit

Skill Verdict Claimed tier Cleared tiers Findings Rules
.claude/skills/agent-hub-release ✅ ALLOW experimental experimental, community none —

✅ All audited skills cleared the tier they claim.

Per-finding detail is withheld here on purpose. Read it in the Security > Code scanning tab, or download the skill-audit-reports artifact from this run. Offending source text is withheld from CI everywhere — reproduce it locally with gaia skill audit <dir> --show-snippets.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 21, 2026
Merged via the queue into main with commit 3f07cee Oct 21, 2026
39 of 41 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the fix/rag-eval-vlm-chunks branch October 21, 2026 18:34
grtninja pushed a commit to grtninja/gaia that referenced this pull request Oct 22, 2026
…md#5548)

The release retrieval eval still stops on FinanceBench after amd#5490. SEC
filings repeat whole passages. When a chunk followed the short tail of a
chunk split for the embedder, the benchmark's locator matched a repeat
hundreds of pages later, and every chunk after it in that filing counted
as unlocated (644 chunks across four filings, over the 1% limit). The
nearby copy now wins. Placements in every other filing are unchanged.
This follows amd#5490, which merged before this commit landed on its
branch. Benchmark code only; no user-facing behavior changes.

## Test plan
- [x] The four failing filings (American Water 2022 10-K, JPMorgan 2021
Q1 10-Q and 2022 10-K, PepsiCo 2023 8-K): 644 unlocated chunks before, 0
after
- [x] Old vs new placements on six filings: only chunks that had jumped
to a far-later duplicate moved; 3M and AMD 10-Ks are identical
- [x] New test fails on the old locator: an overlap through a split tail
beats a later repeat, a chunk only the repeat explains stays there, and
absent text stays unlocated
- [x] `pytest tests/unit/eval/test_retrieval_bench.py
tests/unit/rag/test_retrieval_bench_harness.py` (87 passed), `python
util/lint.py --all`
kovtcharov-amd pushed a commit that referenced this pull request Nov 21, 2026
## Summary
Two quotes in `technical_docs.json` stopped matching the text GAIA
indexes from the PDFs, which is what killed the release RAG benchmark.
This re-points them at the same answers. Questions, answers and pages
are unchanged.

## Why
The benchmark checks that every labelled quote can be found on its page,
and it stops at the first one it can't. That's the `LabelError` on
tech-012 in the issue.

- **tech-012:** the old quote (`MAX POWER 550W or 760W 750W 1000W`) is
the table cells in plain order. Since #8116 (`39606a8a4`) GAIA indexes
table rows as `Header: value | ...`, so it no longer matches. I bisected
with pypdf 7.1.0: it resolves at `39606a8a4~1` and fails at `39606a8a4`.
- **tech-023:** the run stops at the first failure, so it never got this
far. The old quote (`SR-IOV , up to 8 partitions`) has a space before
the comma. The PDF doesn't (I checked page 1), and pypdf 7.1.0 extracts
it without one, but pypdf 6.21.1 (the version #5490 names as CI's) does
add the space. So the quote matches on one pypdf version and not the
other. It fails under 7.1.0 even before #8116, so #8116 isn't the cause.
The new quote starts after the comma, so it resolves under both.

I checked both against the PDFs: the Max Power row on page 25 of the
CDNA 3 white paper, and the SR-IOV row on page 1 of the MI300X
datasheet.

One thing I noticed but didn't touch: on the tech-012 page the extractor
treats the FORM FACTOR row (`SH5 Socket | OAM | OAM`) as the header, so
rows read `FORM FACTOR: MAX POWER | SH5 Socket: ...`. The values still
sit next to their labels, so I don't think it breaks retrieval, but it
reads oddly. I can open a separate issue if you'd consider it a bug.

## Linked issue

Refs #8407

The issue also asks for a fast, no-model check that runs on PRs, so a
stale quote fails where it's edited. I'd like to do that in a second PR,
but I'm happy to fold it into this one if you'd rather.

## Changes

- tech-012: the quote now matches the current table-row text: `MAX POWER
| SH5 Socket: 550W or 760W | OAM: 750W | OAM: 1000W`
- tech-023: the quote is now `up to 8 partitions *The MI200 Series`. It
starts after the comma, so pypdf's spacing doesn't matter, and it still
contains the answer. It runs on into the footnote under that row because
the dataset test requires quotes of at least 20 characters, and `up to 8
partitions` alone is 18.

## Test plan

- [x] Ran a script (below) that resolves every evidence quote against
the extracted text: all 55 in `technical_docs.json` (including the
table-tagged items from the bot's list) and the 8 PDF-backed labels in
`repo_docs.json` (repo-001 and repo-007 among them). Before: 2 of 55
failed. After: 0 of 55 under pypdf 6.21.1 and 7.1.0, and 0 of 8 for
`repo_docs` under 7.1.0. VLM off, pypdfium2 5.15.2. repo-028 is a
`.txt`, which the PDF table rewrite doesn't touch, so I didn't scan it.
- [x] `python -m pytest tests/unit/eval/test_retrieval_bench.py -q`
after the final edit: 77 passed, including the dataset well-formedness
test
- [x] `python -m pytest tests/unit/eval -q`: 2096 passed, 34 skipped
(run before the tech-023 quote changed)
- [x] `python util/lint.py --all --fix`: only two Pylint `os.getuid`
errors, which are Windows-only and in files this PR doesn't touch. I
didn't run the full `tests/unit/` locally since this is a data-only
change; CI covers it.
- [ ] Not run: the full `gaia eval retrieval --suite full` benchmark. It
needs Lemonade and the VLM, which my machine can't run. Could someone
confirm it on the release runner? It would also help to know which pypdf
version that runner uses.

## Evidence

The script isn't a `gaia` subcommand: it's `python scan_labels.py` from
the repo root, and the source is in the details block below.
Before, on `main` with pypdf 7.1.0:
```text
2 of 55 evidence labels do not resolve

tech-012  doc=amd_cdna3_whitepaper  page=25  tags=['pdf', 'table', 'spec']
  quote : 'MAX POWER 550W or 760W 750W 1000W'
  page  : ...FORM FACTOR | SH5 Socket | OAM | OAM FORM FACTOR: THERMAL | SH5 Socket: Passive and Liquid | OAM: Passive and Liquid | OAM: Passive and Liquid FORM FACTOR: MAX POWER | SH5 Socket: 550W or 760W | OAM: 750W | OAM: 1000W ...

tech-023  doc=amd_mi300x_datasheet  page=1  tags=['pdf', 'table', 'spec', 'numeric']
  quote : 'SR-IOV , up to 8 partitions'
  page  : ...AND VIRTUALIZATION Decoders† JPEG/MJPEG CODEC Virtualization support 4 groups for HEVC/H.265, AVC/H.264, V1, or AV1 32 cores, 8 cores per group SR-IOV, up to 8 partitions *The MI200 Series does not support TF32, FP8, or sparsity* †Video codec acceleration (including at least the HEVC (H.265), H.264, VP9, and AV1 codecs...
```
After, under pypdf 6.21.1 and 7.1.0:
```text
0 of 55 evidence labels do not resolve
```
Other surfaces: N/A, eval data change only.

<details><summary>scan_labels.py</summary>

```python
"""Lists every answer-key quote that no longer matches the indexed PDF text.

Run from the root of a gaia checkout, after `gaia eval retrieval --fetch-only`:

    python scan_labels.py                          # technical_docs, all PDFs
    python scan_labels.py --doc amd_cdna3_whitepaper
    python scan_labels.py --dump scan_out          # also write extracted text per doc

Does not need Lemonade, an embedder or a VLM (it logs a health-check warning 
if Lemonade isn't running).. Text comes from the same RAGSDK._extract_text_from_pdf 
the benchmark indexes with, VLM off, so a quote that lives only in an image shows up 
here too; check those by hand.
"""

from __future__ import annotations

import argparse
import re
from pathlib import Path

from gaia.eval.retrieval import corpus, sources
from gaia.eval.retrieval.locate import DocText, Evidence, LabelError, norm, resolve_evidence


def window(doc: DocText, page, quote: str, radius: int = 160) -> str:
    """Text on the labelled page around the quote's longest word, to compare by eye."""
    try:
        text = doc.page_text(page) if page is not None else doc.text
    except LabelError as e:
        return f"(no such page: {e})"
    for word in sorted(set(re.findall(r"\w{4,}", quote)), key=len, reverse=True):
        at = text.find(word)
        if at >= 0:
            return text[max(at - radius, 0) : at + radius]
    return text[: 2 * radius]


def scan(dataset, texts: dict) -> list:
    """Resolve every evidence label; return one record per failure (never stops early)."""
    failures, total = [], 0
    for q in dataset.questions:
        for ev in q.evidence:
            doc = texts.get(ev["doc"])
            if doc is None:
                continue  # not a PDF, or filtered out
            total += 1
            page, quote = ev.get("page"), ev.get("quote")
            try:
                hint = 0
                if ev.get("near"):
                    hint = doc.text.find(norm(ev["near"]))
                    if hint < 0:
                        raise LabelError("'near' text is not in the document as indexed")
                resolve_evidence(Evidence(ev["doc"], page, quote), doc, hint)
            except LabelError as e:
                failures.append(
                    {"q": q.id, "tags": q.tags, "doc": ev["doc"], "page": page,
                     "quote": quote, "why": str(e), "window": window(doc, page, quote or "")}
                )
    return failures, total


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--dataset", default="technical_docs")
    ap.add_argument("--doc", action="append", help="only this document id (repeatable)")
    ap.add_argument("--dump", help="directory to write each document's extracted text to")
    args = ap.parse_args()

    sources.set_repo_root(Path.cwd())
    dataset = corpus.load_labelled(args.dataset, offline=True)

    from gaia.rag.sdk import RAGConfig, RAGSDK  # imported late: heavy

    rag = RAGSDK(RAGConfig(use_vlm=False, show_stats=False))
    texts = {}
    for d in dataset.documents:
        if args.doc and d.id not in args.doc:
            continue
        if d.path.suffix.lower() != ".pdf":
            print(f"[skip] {d.id}: not a PDF ({d.path.suffix})")
            continue
        print(f"[extract] {d.id} ...", flush=True)
        full_text = rag._extract_text_from_pdf(str(d.path))[0]
        texts[d.id] = DocText.from_full_text(str(d.path), full_text)
        if args.dump:
            Path(args.dump).mkdir(parents=True, exist_ok=True)
            (Path(args.dump) / f"{d.id}.txt").write_text(full_text, encoding="utf-8")

    failures, total = scan(dataset, texts)
    print(f"\n{len(failures)} of {total} evidence labels do not resolve\n")
    for f in failures:
        print(f"{f['q']}  doc={f['doc']}  page={f['page']}  tags={f['tags']}")
        print(f"  quote : {(f['quote'] or '')[:140]!r}")
        print(f"  page  : ...{f['window']}...\n")


if __name__ == "__main__":
    main()
```
</details>

## 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 ran linting and tests locally (lint, tests/unit/eval; full
tests/unit/ left to CI)
- [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)). N/A: eval data only
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Performance-critical changes rag RAG system changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant