Skip to content

fix(rag): embed every chunk whole instead of its first 1,200 chars - #4723

Merged
kovtcharov-amd merged 2 commits into
amd:mainfrom
kovtcharov:kalin/rag-embed-whole-chunk
Oct 5, 2026
Merged

kovtcharov-amd merged 2 commits into
amd:mainfrom
kovtcharov:kalin/rag-embed-whole-chunk

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Document search only ever embedded the first 1,200 characters of each chunk, so a fact further into a default (~2,000-char) chunk could never be retrieved, even though the model would have read it once found. Now every chunk is embedded whole: chunks are cut to the embedder's real input limit (2,000 chars), and every load of the embedder carries the 2,048-token batch that limit depends on. Previously any embeddings call (memory, for one) could quietly reload the embedder at llama.cpp's 512 default, which is what the old 1,200 cap was guarding against.

chunk_size above 500 now logs a startup warning and is capped, so the docs' 768/1024 presets are now 500. Documents cached under the old chunking re-chunk on next load.

Benchmark (gaia eval retrieval, before = origin/main, after = this branch): pending, added below once the runs finish.

Test plan

  • python -m pytest tests/unit/rag tests/unit/test_embedder_cpu_backend.py tests/unit/test_llamacpp_backend.py tests/test_rag.py: all pass. On origin/main's code, the new chunk-ceiling/refusal/cache-key tests fail (a numeric table indexed into an 8,889-char chunk, 87% unembedded).
  • Live embedder (EmbeddingGemma on Lemonade, ubatch 2048): 2,000-char inputs of prose, code, digits, numeric tables, random symbols, CJK and emoji all return finite 768-dim unit vectors. Worst case is 2,002 tokens (digits, emoji).
  • python util/lint.py --black --isort
  • Index a long PDF with gaia chat --index <file> and confirm no "Truncated … chunks" line and no embedding errors
🔍 Technical details
  • Cap = (EMBEDDER_UBATCH_TOKENS 2048 − 48 reserved) × 1.0 chars/token. Gemma tokenizes each digit separately, so 1.0 is the measured floor for realistic text. Only byte-fallback scripts (e.g. CJK Extension B, ~0.25 chars/token) can exceed it, and those fail loudly with a 500 rather than truncating.
  • Over-limit inputs are a hard 500 from llama-server (input (N tokens) is too large … physical batch size), not the empty vectors the old comment described.
  • Over-long chunks are split into consecutive stored chunks (one vector each), so chunk↔vector mapping stays 1:1 and no text is dropped. A long query is cut with a WARNING. _encode_texts refuses an oversized input. A batch rejected for a small physical batch reloads the embedder before its retry.
  • embed_max_chars joins the chunk-cache fingerprint (fix(rag): key the document cache on chunking settings #4624).
  • code_index keeps its own 1,200 cap; not changed here.

Fixes #3534

Document search only ever saw the first 1,200 characters of each chunk, so a
fact further into a ~2,000-char default chunk could not be retrieved even
though the model would have read it. The 1,200 cap was sized for llama.cpp's
512-token default batch, which any embeddings call could quietly reinstate by
reloading the embedder without RAG's 2048.

- The embedder's input limit now lives in one place (EMBEDDER_UBATCH_TOKENS in
  lemonade_client) and every load of the embedder carries it, including the
  backend pin on first /embeddings and the embedded Lemonade's saved options.
- The cap is 2,000 chars: 2,048 tokens at one char per token, the worst case
  measured on the live embedder (digits and emoji), with BOS/EOS headroom.
- The chunker splits anything longer into consecutive chunks, so each vector
  covers its whole chunk; an oversized input to _encode_texts is refused, and
  a long query is cut with a WARNING. A batch rejected for a too-small physical
  batch reloads the embedder before its retry.
- The cap is part of the chunk-cache key, so documents cached with the old
  oversized chunks re-chunk on next load.
- Docs: chunk_size advice now tops out at 500, the default, since larger
  values are capped.

Fixes amd#3534
@github-actions github-actions Bot added documentation Documentation changes rag RAG system changes llm LLM backend 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: Approve with suggestions

Document search used to embed only the first 1,200 characters of each chunk, so anything past that point in a chunk could never be found. This PR fixes that: chunks are cut to what the embedder can actually read, and the embedder is loaded with the larger batch size that limit needs. The logic is sound and well tested, and I found no blocking bugs.

Before merge:

  • Proof on a real document is still missing. The retrieval benchmark is marked "pending", and the gaia chat --index item is still unchecked. Since this changes what retrieval returns, please also dispatch the rag_quality eval lane and paste the before/after numbers.
  • On macOS the larger batch size isn't saved for the embedder. When Lemonade loads the embedder by itself (for example, for memory), it falls back to the 512 default. The new reload-on-retry recovers, so nothing breaks, but it costs an extra embedder reload. This contradicts the PR's claim that every load carries the 2,048 batch.

Real-world evidence

N/A: no evidence bundle was produced for this run. The verdict rests on static review plus the author's checked test-plan items (unit tests, and a live check that 2,000-char inputs embed cleanly). Real indexing through gaia chat --index and the retrieval benchmark have not been shown yet.

🔍 Technical details

🟡 Evidence / eval gap (PR description). The benchmark line says "pending", and test-plan item 4 (gaia chat --index <file>, no "Truncated" line, no embedding errors) is unchecked. Chunk boundaries now change for every document, and the doc presets drop from 768/1024 to 500. Both affect retrieval, so dispatch eval_flagship.yml for rag_quality and compare against tests/fixtures/eval_baselines/gaia-flagship/scorecard_rag_quality.json.

🟢 macOS gets no ubatch pin (src/gaia/llm/lemonade_embedded.py:637-651, src/gaia/llm/lemonade_client.py:5403). llamacpp_backend_for() returns None on Darwin. That makes _pin_llamacpp_backends hit continue before it adds --ubatch-size, and load_model never sets save_options. As a result the 2048 ubatch only applies to GAIA's explicit loads on macOS, and /embeddings auto-loads still run at 512. The physical-batch retry covers this, but if the ubatch pin is meant to be platform-independent, write it even when there's no backend to pin:

            entry = options.get(model)
            entry = dict(entry) if isinstance(entry, dict) else {}
            if backend is not None:
                entry["llamacpp_backend"] = backend

(plus dropping the continue). The same split is needed for save_options in load_model.

🟢 Over-limit inputs trigger pointless reloads (src/gaia/rag/sdk.py:704-711). A genuinely too-long input (the CJK Ext-B case the PR mentions) also fails with "physical batch size". The retry then unloads and reloads the embedder twice before re-raising the raw 500. You could reload only when the error reports current batch size below EMBEDDER_UBATCH_TOKENS, or skip the reload once one has already been done.

🟢 Stale docstring (src/gaia/rag/sdk.py:520-522). _get_cache_path still lists only chunk_size, chunk_overlap and use_llm_chunking as fingerprint inputs. The embedder's input limit now belongs in that list too.

Strengths

  • The cap is derived from one constant (EMBEDDER_UBATCH_TOKENS), which is shared by the load args, the embedded-Lemonade pin, and the chunk ceiling, so they can't drift apart.
  • Over-long chunks are split into extra stored chunks rather than truncated, which keeps chunk↔vector 1:1. _encode_texts now refuses oversized input loudly instead of silently cutting it, in line with the fail-loudly rule.
  • The tests are good: they check that the recorded embedder inputs equal the stored chunks, that cache-fingerprint invalidation works, that the LLM-chunking path is covered, and that an existing custom --ubatch-size is preserved.
  • Doc presets above 500 were updated across all six pages.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 5, 2026
Merged via the queue into amd:main with commit 5472194 Oct 5, 2026
@kovtcharov-amd
kovtcharov-amd deleted the kalin/rag-embed-whole-chunk branch October 5, 2026 06:37
kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 5, 2026
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 added a commit to kovtcharov/gaia that referenced this pull request Oct 5, 2026
The memory-cap test in the Windows unit job sometimes hit the 60 s
pytest timeout, failing unrelated PRs (for example amd#4723) on a busy
runner. It added about 925 memories one at a time, and every add saved
to disk on its own, so a slow disk made the test crawl. It now adds each
batch in one save. The checks are unchanged and the measured prompt
sizes are byte-for-byte the same.

<details>
<summary>🔍 Technical details</summary>

- `MemoryStore.store()` commits per row (one WAL fsync) and runs an FTS5
dedup query before each insert. Profiling showed commit ≈ 45% and
`execute` ≈ 50% of runtime.
- `_seed_entries` now calls `MemoryStore.seed_bulk()`: one transaction,
no dedup. The prompt builder doesn't read `source`/`last_used`, the two
fields where `seed_bulk` differs, so the rendered block is the same. I
diffed the standalone growth table before and after: identical.
- Skipping dedup is safe because `_make_entry()` produces unique entries
by construction. `test_dedup_did_not_collapse_seeded_entries` still goes
through `store()` (new `_store_entries`), so it keeps proving that.
- Local timings (`--durations`):
`test_memory_block_never_exceeds_hard_cap` 1.69 s → 0.24 s,
`test_print_growth_table` 1.61 s → 0.25 s, the two 500-entry tests 0.8 s
→ under 0.06 s. Module total: 6.5 s → 1.3 s.
</details>

## Test plan
- [x] `python -m pytest tests/unit/test_memory_prompt_growth.py -v
--durations=10` passes three runs in a row (1.2 to 1.5 s)
- [x] `python tests/unit/test_memory_prompt_growth.py` prints a growth
table identical to `main`'s
- [x] `python util/lint.py --black --isort --flake8` passes
- [ ] `Unit Tests (Windows, py3.12)` passes on this PR
@kovtcharov-amd kovtcharov-amd mentioned this pull request Oct 6, 2026
5 of 10 tasks
grtninja pushed a commit to grtninja/gaia that referenced this pull request Oct 6, 2026
# GAIA v0.25.0 Release Notes

## Breaking Changes

- **`gaia chat` runs the flagship GAIA agent**, the same agent as the
TUI and Agent UI, instead of the retired ChatAgent. `gaia chat -q "…"`
queries it once. (PR [amd#4520](amd#4520))
- **`gaia talk` transcribes and speaks through Lemonade** — it uses
Lemonade's Whisper and `kokoro-v1`, and stops with the reason if
Lemonade is down. The `[audio]` extra is gone; `pip install
amd-gaia[audio]` only warns. (PR
[amd#4665](amd#4665))
- **The Agent UI runs only the GAIA agent** — the Agent Hub home, agent
picker, and custom-agent export/import are removed from the UI. The CLI
and eval harness can still run other agents. (PR
[amd#4509](amd#4509))
- **The retired nomic embedder is removed** — memory saved with it is
re-embedded on first start. (PR
[amd#4489](amd#4489))
- **Indexed documents are re-indexed once** — the document cache is now
keyed on chunking settings, so the first query after upgrading rebuilds
it. (PR [amd#4624](amd#4624))
- **A skill that asks for more than its tier allows no longer loads** —
the permission ceiling is checked at every load, so a skill already on
disk that exceeds it is refused with the reason. (PR
[amd#4849](amd#4849))

## What's New

- **A larger local model where the GPU holds it** — `gaia init` picks
Qwen3.6-35B-A3B on a 64 GB+ Strix Halo or a 32 GB GPU and keeps
Gemma-4-E4B elsewhere, with each context window sized to available
memory. Qwen3.8 Flash Next is opt-in on 128 GB Strix Halo. (PRs
[amd#4479](amd#4479),
[amd#4670](amd#4670),
[amd#4671](amd#4671),
[amd#4658](amd#4658),
[amd#4655](amd#4655))
- **The Agent UI opens straight to a chat and sets itself up** — a fresh
install runs the same setup steps as the TUI in the window, with
provider, key and model settings, permission modes, and revocable
"always allow" grants. (PR
[amd#4509](amd#4509))
- **A much smaller install** — PyTorch, transformers and accelerate are
gone from the core, `[ui]` and `[talk]` installs; the desktop app's
Python environment drops from ~0.9 GB to ~0.1 GB on Windows. (PRs
[amd#4666](amd#4666),
[amd#4621](amd#4621),
[amd#4665](amd#4665))
- **One Windows installer for the desktop app and the terminal**, with a
GAIA Windows Terminal profile. (PRs
[amd#4720](amd#4720),
[amd#4707](amd#4707))
- **A "no" holds** — a declined action isn't retried through another
tool; the agent asks again with the exact command. The TUI gains
Shift+Tab permission modes. (PRs
[amd#4460](amd#4460),
[amd#4461](amd#4461))
- **Answers are checked against what the tools actually did** — the
agent looks at files you name before answering about them, and a short
plain-English note appears only when work isn't confirmed. (PRs
[amd#4532](amd#4532),
[amd#4501](amd#4501),
[amd#4508](amd#4508))
- **One shell session** — commands share a persistent shell, risky ones
ask instead of being refused, and "full access" is one setting
everywhere. (PR [amd#4408](amd#4408))
- **Memory surfaces what's relevant to each request, with its age**,
keeps what fixed a failure as a lesson for that workspace, and extracts
after the answer instead of before it. (PRs
[amd#4061](amd#4061),
[amd#4066](amd#4066),
[amd#4406](amd#4406))
- **`gaia.log` stays bounded** — it rotates at 10 MB with three backups
(`GAIA_LOG_MAX_MB`, `GAIA_LOG_BACKUPS`). (PRs
[amd#4668](amd#4668),
[amd#4760](amd#4760))
- **Child processes get a trimmed environment** — shell, MCP and skill
children no longer inherit GAIA's internal credentials; `GAIA_NO_DOTENV`
skips loading `.env`. (PRs
[amd#4635](amd#4635),
[amd#4659](amd#4659))
- **Every file tool checks the allowed-folders rule**, and paths inside
an inline shell script are checked one by one. (PRs
[amd#4656](amd#4656),
[amd#4758](amd#4758))

## Bug Fixes

A selection of the user-visible fixes; the full list is in the changelog
below.

- **Local Qwen models no longer loop on repeated tool calls** — they run
with their model card's sampling instead of near-greedy settings. (PR
[amd#4655](amd#4655))
- **Qwen3.6 runs on a Strix Halo with an older AMD driver** — it used to
crash on its first token, so `gaia init` failed; GAIA now turns off the
Vulkan path that crashes on those drivers only, and newer drivers keep
the faster path. (PR [amd#4674](amd#4674))
- **A long PDF no longer hangs or times out while indexing** — big
documents index in the background, and PDFs that only carry
owner-password restrictions now index. (PRs
[amd#4754](amd#4754),
[amd#4679](amd#4679),
[amd#4734](amd#4734))
- **Document answers cite the right document and page**, and every chunk
is embedded whole instead of its first 1,200 characters. (PRs
[amd#4688](amd#4688),
[amd#4723](amd#4723))
- **`gaia init` fails when model verification fails**, shows downloads
live, and no longer hangs while Lemonade hashes a large model. (PRs
[amd#4620](amd#4620),
[amd#4564](amd#4564),
[amd#4673](amd#4673))
- **`gaia init` adds a profile's extras without reinstalling GAIA**,
which failed on Windows while `gaia.exe` was running. (PR
[amd#4672](amd#4672))
- **Every SDK and CLI entry point starts GAIA's own Lemonade**, and
every call goes to the resolved URL with its API key. (PRs
[amd#4657](amd#4657),
[amd#4627](amd#4627))
- **Local chat stays cached across turns** — the system prompt is fixed
and side requests no longer evict the conversation. (PRs
[amd#4698](amd#4698),
[amd#4543](amd#4543))
- **A cloud model selection never preloads a local model**, and cloud
models no longer get llama.cpp-only fields. (PRs
[amd#4757](amd#4757),
[amd#4709](amd#4709))
- **The Agent UI stops claiming "100% local" while chat goes to a cloud
model**, and the chat header names the session's real model. (PRs
[amd#4711](amd#4711),
[amd#4550](amd#4550))
- **Enter can't approve a permission prompt**, and prompts wait 10
minutes before timing out. (PRs
[amd#4700](amd#4700),
[amd#4699](amd#4699))
- **Stopping a run keeps the turn and its steps visible.** (PR
[amd#4743](amd#4743))
- **A file edit keeps the file's line endings** — a one-line edit on
Windows used to rewrite every line ending, so a small change showed up
as the whole file changed. (PR
[amd#4864](amd#4864))
- **A broken agent install is reported as broken, not as missing** — the
error names both package versions and the real import error, and
suggests a reinstall that works. (PR
[amd#4588](amd#4588))
- **A meeting or document summary is never cut off mid-sentence** — a
thinking model used to spend the summary's output budget reasoning, so a
long meeting lost its second half. (PR
[amd#4827](amd#4827))
- **"What can you do?" gets an answer** instead of an attempt to
generate an image of the question. (PR
[amd#4809](amd#4809))
- **Writes and approved edits can't reach credential folders**
(`~/.ssh`, `~/.aws`, `~/.kube` and others), and shell option values and
script arguments get the same path check as plain paths. (PRs
[amd#4848](amd#4848),
[amd#4847](amd#4847))
- **`gaia connectors connect google --grant-agent installed:gaia`
works** — it used to fail with no sign-in link for the shipped agent; it
now asks for read-only Gmail and grants exactly that. (PR
[amd#4859](amd#4859))
- **A "no" to creating a folder also covers writing into it** — GAIA no
longer asks again to create the same folder a different way. (PR
[amd#4857](amd#4857))
- **`gaia skill import` runs the same checks as a hub install** — https
only, the audit, the permission ceiling, and an explicit opt-in for
skills that ship code. (PR
[amd#4849](amd#4849))
- **Memory off and private chats apply to scheduled and background runs
too.** (PRs [amd#4842](amd#4842),
[amd#4821](amd#4821))
- **Memory stops false apologies and reusing deleted values**, saves
"remember this" requests, and skips loading the embedder when memory is
off. (PRs [amd#4708](amd#4708),
[amd#4756](amd#4756))
- **A reply cut off by the token limit is continued** instead of ending
mid-sentence, and a tool call cut off at the output cap is retried
shorter. (PRs [amd#4054](amd#4054),
[amd#4556](amd#4556))
- **The TUI remembers the chosen model** across restarts and
agent-process restarts. (PRs
[amd#4497](amd#4497),
[amd#4710](amd#4710))
- **`gaia uninstall --purge` removes installer binaries, PATH edits and
daemon state.** (PR [amd#4413](amd#4413))

## Contributors

Thanks to the community members who contributed to this release:

- [@itomek](https://github.com/itomek) — the flagship's browser and tool
picker, one shell session, memory extraction off the answer path, stale
tool-result eviction, the TUI's sourced Fireworks rankings, and
`--purge` cleanup (PRs [amd#4407](amd#4407),
[amd#4408](amd#4408),
[amd#4406](amd#4406),
[amd#4465](amd#4465),
[amd#4414](amd#4414),
[amd#4413](amd#4413))
- [@mikemikimike](https://github.com/mikemikimike) — chained shell
command timeouts, bundled skills in frozen builds, and sidecar cleanup
reporting (PRs [amd#4463](amd#4463),
[amd#4467](amd#4467),
[amd#4419](amd#4419))
- [@Hashim1999164](https://github.com/Hashim1999164) — honoring
`GAIA_HOME` for cache, chat and index paths (PR
[amd#4381](amd#4381))
- [@krtadev](https://github.com/krtadev) — `~` expansion in file and
document tool paths (PR [amd#4576](amd#4576))
- [@aksh8b](https://github.com/aksh8b) — telling a broken agent install
apart from a missing one, with a reinstall hint that works (PR
[amd#4588](amd#4588))
- [@Dev-next-gen](https://github.com/Dev-next-gen) — numeric prerelease
ordering in the hub (PR [amd#4517](amd#4517))
- [@vianmangal](https://github.com/vianmangal) — recording denied tool
calls as unsuccessful in memory (PR
[amd#4412](amd#4412))
- [@GaetanVDB07](https://github.com/GaetanVDB07) — links to upstream
credential setup guides for connectors (PR
[amd#4669](amd#4669))
- [@rradjabi](https://github.com/rradjabi) — moving self-hosted CI jobs
to the xsj-dispatch runner pool (PR
[amd#4534](amd#4534))




## Also in this PR

- **Hub floors raised to core 0.25.0** — the chat agent imports the
allowed-folders check that only 0.25.0 ships (amd#4656), so
`gaia-agent-chat` goes to 0.2.0 with `amd-gaia>=0.25.0`, and the
flagship requires `amd-gaia>=0.25.0` and `gaia-agent-chat>=0.2.0`.
- **Two follow-ups held back until that floor could rise** —
`~/.gaia/logs/gaia-agent.log` now rotates like `gaia.log` (amd#4668), and
the chat agent's Python runners and Windows notification start their
children without GAIA's internal credentials (amd#4659).

The full changelog (300 commits) is in `docs/releases/v0.25.0.mdx`.

## Test plan

- [x] `util/validate_release_notes.py docs/releases/v0.25.0.mdx --tag
v0.25.0` passes; narrative is 590 words (cap 600)
- [x] `util/check_component_core_api.py --release-version 0.25.0` passes
- [x] `pytest tests/unit/test_docs_json_release.py
tests/unit/test_check_component_core_api.py
hub/agents/chat/python/tests/test_chat_dependency_floor.py
hub/agents/chat/python/tests/test_dependency_floor.py
hub/agents/gaia/python/tests/test_gen_binaries_lock.py` (72 passed)
- [x] `pytest hub/agents/gaia/python/tests/test_stdio.py` (91 passed,
incl. the new rotation test); `pytest
tests/unit/test_execute_python_file_cwd.py
tests/unit/test_run_python_tool.py` (42 passed)
- [ ] `mintlify validate` (docs CI job) — timed out locally, relying on
CI
- [x] Full flagship eval on main 9ce6598
(https://github.com/amd/gaia/actions/runs/37436249503): 181/308
scenarios pass vs 100/183 for the same categories in the baseline, 39
FAIL→PASS, 13 PASS→FAIL (two fixed in amd#4878, held until after rc1);
retrieval lane still finishing at merge time
- [ ] CI green

## Release checklist

- [ ] Publish `gaia-agent-chat` 0.2.0 only after core 0.25.0 is on PyPI
— it fails at import on an older core
- [ ] Build Installers on the merged SHA (pre-tag verification) before
pushing `v0.25.0`
- [ ] terminal-hub 0.25.0 published before the flagship npm release
consumes `binaries.lock.json`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Documentation changes llm LLM backend 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.

fix(rag): only the first 1200 chars of each chunk is ever embedded

2 participants