Skip to content

fix(vlm): load the vision model once, at the right context, and surface load errors - #4290

Merged
kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/vlm-ctx-aware-load
Sep 25, 2026
Merged

kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/vlm-ctx-aware-load

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Before this change, the first image extraction loaded the vision model at Lemonade's default context and then reloaded it straight away at the size GAIA requires. That meant two cold loads, and it evicted the chat model when both are the same Gemma. The pre-load also gave up after 60 s, which is shorter than a cold iGPU load, and any failure (timeout, out of memory) turned into a generic "model is not available". Now each extraction loads the model once, at the right context, inside the request. The real load error reaches the caller, and a model evicted mid-batch reloads on the next page instead of failing.

The only overlap with open PRs is #3122, which edits a different line of tests/test_vlm_integration.py.

Test plan

  • New tests fail on main (5 failed) and pass with the fix: python -m pytest tests/unit/test_vlm_extraction_failures.py -q (15 passed)
  • Neighbouring tests: python -m pytest tests/unit/test_structured_vlm_extraction.py tests/unit/test_ingest_helpers.py tests/unit/test_lemonade_base_url_passthrough.py tests/unit/test_llm.py tests/unit/test_testing_utilities.py tests/unit/rag/ -q (all pass)
  • black --check, isort --check-only, and the CI pylint command on src/gaia/llm src/gaia/vlm src/gaia/rag are clean
  • With Lemonade running, index a PDF with images from a cold state (vision model not loaded) and confirm one /load at the model's required ctx

Fixes #4215

…ce load errors

The first image extraction loaded the vision model at Lemonade's default context and then immediately reloaded it at the size GAIA requires: two cold loads, evicting the chat model when it is the same Gemma. The pre-load's 60 s timeout was shorter than a cold iGPU load, and any failure (timeout, OOM) was replaced with a generic "model is not available". A cached "loaded" flag meant an eviction mid-batch went unnoticed.

The separate pre-load is gone. Each extraction request now asks LemonadeClient.chat_completions to do its context-aware load under the model-slot lease (auto_download follows auto_load), so the model loads once at the right size, the client's own load timeout applies, and the real load error reaches VLMExtractionError with its cause attached.

Fixes amd#4215
@github-actions github-actions Bot added documentation Documentation changes llm LLM backend changes tests Test changes performance Performance-critical changes labels Sep 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This removes the redundant pre-load in the vision client so a PDF page's first image loads the model once — at the context size GAIA requires, under the model-slot lease — instead of loading it twice and reporting any failure as a generic "model not available". The dead vlm_loaded flag is gone with no stragglers left anywhere in the tree, and the docs, spec and tests were updated in the same change. Nothing here blocks merge.

Two things worth a follow-up:

  • Turning auto-load off no longer stops a load. Previously, constructing the client with auto-loading disabled made extraction fail immediately without contacting the server. Now the request goes out anyway, and Lemonade will happily load the model itself at its default context — the exact silent context cap this PR set out to remove. No shipped code takes that path today, so it isn't blocking, but it's a documented public option whose meaning quietly changed; either keep the explicit guard or say in the docstring what "off" now means.
  • The headline claim is mock-verified only. The unit tests prove the client asks for a context-aware load; they can't prove the server performs exactly one. Your own test plan has the cold-state check still unchecked, and that's the item that matters — on a machine where the vision model is already resident, the old double-load is invisible and the run looks clean either way.

Smaller items (wrong default model named in a docstring, a stale code sample in the spec, and two pre-existing broken constructor calls in the integration script) are in the details below.

Real-world evidence

N/A — no evidence-bundle.md was produced for this PR, and this reviewer environment has no pytest available, so I could not re-run the suite myself. The verdict rests on static review plus the results reported in the PR description. The one surface that could have been exercised here (a cold-state PDF ingest showing a single /load at the required context) is the unchecked test-plan item above; that gap is the second finding, not a separate concern.

🔍 Technical details

🟡 auto_load=False no longer suppresses the load (src/gaia/llm/vlm_client.py:247)

Before this change, _ensure_vlm_loaded() returned False under auto_load=False and extract_from_image raised VLMExtractionError without ever issuing a request. Now the only effect is auto_download=False on chat_completions, which skips GAIA's _ensure_model_loaded but still POSTs to /chat/completions. Lemonade auto-loads a non-resident model on request at its own default ctx — that behaviour is what the #1030 comment in lemonade_client.py:2212-2216 documents. So the flag that used to mean "never load" now means "load, but at the wrong context size", which is a silent-degradation shape rather than a loud failure.

No production caller is affected — rag/sdk.py:781, rag/sdk.py:1159, vlm/mixin.py:74, vlm/structured_extraction.py:77, messaging/ingest.py:28 and providers/lemonade.py:620 all take the default. Only tests/test_vlm_integration.py:30 and tests/unit/test_llm.py:317,327 pass False, and neither extracts.

Either restore an explicit guard for the auto_load=False case, or make the docstring state the new contract — the current text (src/gaia/llm/vlm_client.py:100-101) and docs/spec/vlm-client.mdx:133-134 describe only the True path.

tests/unit/test_vlm_extraction_failures.py:560 (test_auto_load_false_tells_the_request_not_to_load) asserts the kwarg is forwarded, which is true, but it doesn't assert what the caller actually gets when the model isn't resident.

🟡 No cold-state verification of the single ctx-aware load

tests/unit/test_vlm_extraction_failures.py::TestModelLoading is a good contract test of the client — it pins auto_download, proves every request re-checks, and proves a LemonadeClientError from the load reaches VLMExtractionError with __cause__ attached. The boundary it can't reach is Lemonade itself: test_the_real_load_failure_reaches_the_error synthesizes the inner load_model call from a MagicMock, so it asserts VLMClient's error handling, not that the real server performs one load at resolve_ctx_size(model).

That's the "mocks prove we called it, not that the call is valid" case in CLAUDE.md, compounded by the warm-cache trap from #1655: on a box where the vision model is already loaded at the right ctx, both the old double-load and the new single load look identical. The unchecked box in the test plan is the right check — worth running before merge and pasting the /load lines.

🟢 Class docstring names the wrong default model (src/gaia/llm/vlm_client.py:83)

The constructor defaults to Gemma-4-E4B-it-GGUF (line 88), and docs/spec/vlm-client.mdx agrees. The docstring block edited by this PR still says Qwen3-VL.

    - Model loading (default: Gemma-4-E4B-it-GGUF)

🟢 Spec code sample contradicts the real call and the spec's own text (docs/spec/vlm-client.mdx:354)

The PR adds auto_download=self.auto_load to this snippet but leaves the two args above it stale: the implementation uses max_completion_tokens=4096 and timeout=300 (src/gaia/llm/vlm_client.py:245-246), and the spec's own Performance section at line 67 already says 300 seconds. Line 70 ("Up to 2048 tokens per extraction") needs the same bump to 4096.

            max_completion_tokens=4096,  # Increased for complex extractions
            timeout=300,  # VLM needs more time for complex forms (5 min)

🟢 Two remaining fallback_model= calls will raise TypeError (tests/test_vlm_integration.py:122, tests/test_vlm_integration.py:189)

Pre-existing, not introduced here — but this PR deletes the third instance of the same dead kwarg from the same file, so it's cheap to finish the sweep. VLMClient.__init__ accepts only vlm_model, base_url, auto_load, api_key, so both call sites fail on construction whenever a Lemonade server is present to run them against.

    vlm = VLMClient(
        vlm_model="Qwen3-VL-4B-Instruct-GGUF",
        auto_load=True,
    )

Line 153's "Cleaning up (reloading fallback model)" print is stale for the same reason.

Strengths

  • The dead state is genuinely gone. vlm_loaded and _ensure_vlm_loaded have zero remaining references across Python, MDX and TS — including src/gaia/testing/mocks.py, which is where this kind of removal usually leaves a broken double.
  • The error path got better, not just shorter. Collapsing the pre-load into chat_completions means a load failure arrives as the real Lemonade message with __cause__ preserved, instead of being flattened into "not available at <url>" — and tests/unit/test_vlm_extraction_failures.py:579 pins exactly that, including the cause chain.
  • Docs moved with the code. docs/spec/vlm-client.mdx had its lifecycle description, its _ensure_vlm_loaded reference block and its test listing all updated in the same change, which is what CLAUDE.md asks for when a behaviour is described in more than one place.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 25, 2026
Merged via the queue into amd:main with commit 212ffb2 Sep 25, 2026
39 checks passed
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
…free box

Both files this PR repairs still failed in the offline lane, so the "534
passed" claim held only on the author's machine.

The memory test built its URL by interpolating a local-timezone stamp. At
a negative UTC offset the "-" is URL-safe and it passes; on a UTC runner
the "+00:00" decodes to a space, fromisoformat rejects it, and the
endpoint correctly 422s. Passing the stamp through the client's params
lets it percent-encode, and a second pinned +00:00 case means the test
now catches this from any timezone rather than only from UTC.

The TUI test set TERM to get color, but termenv treats any environment
with CI set as "not a TTY" before it looks at TERM or the pty, so
lipgloss dropped to the Ascii profile and rendered no escapes at all for
format=ansi to return. CLICOLOR_FORCE is the documented override, and
NO_COLOR outranks it, so both it and CLICOLOR are cleared.

Also resolves the merge with main: amd#4290 removed only one of this file's
three fallback_model uses, and VLMClient no longer takes that argument,
so the deletion stands.
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
Nine test files that no CI lane runs had been failing for weeks without
anyone seeing it. `tests/test_sdk.py` alone had 17 failures against APIs
that were renamed or removed. This PR gets every one of them passing
against current main, so amd#4205's follow-up can put them in a lane. Where
a test covered something that no longer exists, it's deleted and the
commit says why, rather than rebuilt.

Overlaps (small, easy to resolve, all by the same author):
- amd#4033 bumps the same schema-version assertion from 4 to 5. Whichever
lands second takes its own number.
- amd#4290 and amd#3122 edit `tests/test_vlm_integration.py`, which this PR
deletes. That file returned booleans instead of asserting, so it could
never fail, and it passed a constructor argument that no longer exists.

## Test plan
- [x] Before, on `origin/main`: the repaired files fail offline
(`test_sdk.py` 17, `test_multi_caller_equivalence.py` 2,
`test_memory_integration.py` 1, `test_memory_api_integration.py` 1,
`test_documents_router.py` 3, `test_tui_control_e2e.py` 6,
`test_ui_email_scope_consent.py` 5,
`test_lemonade_embedded_lifecycle.py` 1 on macOS)
- [x] After, with homes isolated and Lemonade pointed at a dead port:
the offline set passes. That's 534 passed and 12 skipped across the 23
files amd#4205 wires in, in a clean py3.12 venv with `-e ".[api,mcp]"` plus
the unit job's test deps, with Go on PATH
- [x] `tests/test_ui_email_scope_consent.py` passes inside the email
unit lane's full pytest command (4971 passed), in a clean venv with
`.[dev,api,publish,mcp]` and the email package installed
- [x] `black --check`, `isort --check-only`, `flake8`, and `pylint
--errors-only` are clean on every changed file

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

- `test_sdk.py`: `Agent.execute_tool` was never public; the replacement
follows `docs/sdk/testing.mdx` (registry lookup). `openai_server`
exposes a module-level `app`, not `create_app()`. `STATE_*` constants
live on `Agent`. `_register_tools` is now the only abstract method.
Removed the xfail `DatabaseMixin` block, since it ships as
`gaia.database.mixin` and has its own wired tests. The MCP tests in this
file need the `[mcp]` extra, which the lane installs.
- `test_multi_caller_equivalence.py`: mutating `/api/*` calls need
`X-Gaia-UI: 1` (`gaia.ui.security`), and `/api/connectors` returns
`{"connectors": [...]}` keyed by `id`.
- `test_memory_api_integration.py`: consolidation returns 503 until a
chat session registers `_consolidate_fn`. That is intended behavior, not
a side effect of the environment. Both branches are now pinned.
- `test_documents_router.py`: the `failed_doc` fixture and one test
uploaded without `mock_index_document`, so they indexed for real and
needed Lemonade.
- `test_tui_control_e2e.py`: a fresh pty is 0x0, so `resize` refused;
runners leave `TERM` unset, so the ANSI screen had no escapes.
- `test_ui_email_scope_consent.py`: `EmailTriageAgent` also declares
`microsoft_work` now. The three deleted tests hit an in-process
`/v1/email` mount that the UI dropped in the amd#1767 sidecar cutover;
`tests/unit/test_email_sidecar_*` cover the forwarder.
</details>

Refs amd#4205

---------

Co-authored-by: Kalin Ovtcharov <[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 tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(vlm): VLM loads without ctx_size, reloads, and hides the real load failure

2 participants