Skip to content

Native llama.cpp path allocates a fixed 32K context at load time; Ollama's per-request negotiation avoids the same OOM - #1643

Merged
malibio merged 2 commits into
mainfrom
worktree-issue-1638-adaptive-nctx
Jul 13, 2026
Merged

malibio merged 2 commits into
mainfrom
worktree-issue-1638-adaptive-nctx

Conversation

@malibio

@malibio malibio commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator

Closes #1638

…2K (closes #1638)

The native llama.cpp path allocated a fixed 32K-token KV cache at model load
regardless of free memory, so any model whose weights + full KV cache didn't
comfortably fit hard-OOM'd on the second conversational turn
(kIOGPUCommandBufferCallbackErrorOutOfMemory). Gemma 4 12B reproduced this on a
16GB machine; the same model over Ollama never OOM'd because Ollama negotiates
context per request rather than reserving the full window up front.

The catalog context_window is now a ceiling, not a fixed allocation. When the
chat context is created we compute the GQA-aware KV-cache cost per token from
model geometry, probe memory free after weights are resident (sysinfo), and cap
the KV cache at the smaller of (available − 2GiB headroom) and 40% of available
memory — the fraction reserve leaves proportional room for the batch compute
buffer, which scales with the window and is what tipped the fixed-headroom-only
budget back into OOM at a 27K window during testing. The result is clamped to
[4096, configured] and the effective window feeds the overflow/stop guards so
they measure the real allocation.

Verified end-to-end on a 16GB machine: gemma-4-12b-unsloth-q4km now survives
multiple turns without OOM (window reduced to fit; warns on reduction), while
Gemma 4 E4B keeps the full 32K ("context fits configured window"). Unit tests
cover the sizing arithmetic (tight-memory reduction, roomy no-op, floor clamp,
degenerate-geometry fallback).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DMPgbnyNk6bDFnpqtTPbKr
@malibio

malibio commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1643

Review Type: Initial review (no prior reviews on the PR)
Scope: Cargo.lock, packages/nlp-engine/Cargo.toml, packages/nlp-engine/src/chat/mod.rs (+308/−23)
Verification run locally: cargo test -p nodespace-nlp-engine --lib → 93 passed; cargo build -p nodespace-nlp-engine --lib → clean.

Summary

This is a well-executed, tightly-scoped fix. It converts the hardcoded 32K KV-cache allocation into a memory-fitted n_ctx sized from actual GQA geometry and free memory, with the configured window as a ceiling. The core arithmetic (fit_n_ctx_to_budget) is pure, thoroughly unit-tested, and correctly models the GQA-reduced KV footprint — I verified the math against real Gemma 3/4 12B geometry (48 layers, n_embd 3840, 16/8 heads → ~180 KB/token Q8_0 → ~5.6 GB for a full 32K cache, which correctly exceeds the ~1 GB budget in the repro and forces a reduction). The borrow-checker restructure in generate_blocking is clean and the two ctx bindings are sound. No lint suppression, no println!, no back-compat cruft — standards are met.

It is a clear net improvement and directly resolves the OOM. My one substantive finding is a cross-module consistency gap (the agent's history budget doesn't learn about the reduced window), which is arguably out of this PR's declared scope but materially affects acceptance criterion 4 for large models in long conversations.

Requirements Check (issue #1638)

  • ✅ AC1 — Root cause confirmed & contrasted vs Ollama: Documented in the issue and PR; the fix directly targets the fixed-allocation-at-load-time root cause.
  • ✅ AC2 — Decide on an approach: Memory-check-before-context-creation with adaptive sizing. Reasonable, well-documented choice.
  • ✅ AC3 — Verify against repro (gemma-4-12b-unsloth-q4km, >1 turn, 16GB): E2E evidence reported ("configured=32768 effective=8960", 2 turns no OOM). The fit_leaves_compute_headroom_at_real_repro_memory test encodes the real repro geometry/memory as a regression guard.
  • ⚠️ AC4 — No regression to models that already fit (E4B, Ministral): Held for the allocation path — fit_keeps_full_window_for_small_model_with_headroom guards it and E2E showed E4B keeps 32768. But see Finding 1: a large model in a long conversation now surfaces a hard ContextOverflow error where it previously (theoretically) fit, because the agent-loop summarization threshold is hardcoded to 32K and never learns the reduced window. This isn't a regression to small models, but it's an incomplete corner of "the fix works end-to-end for the large model."

Findings

🟡 1. Effective window is invisible to the agent's history-budgeting layer — long conversations on a shrunk window fail hard instead of summarizing

packages/nlp-engine/src/chat/mod.rs:123 stores the reduced window into self.context_size, but LlamaChatInferenceEngine::model_info() (packages/agent/src/local_agent/inference.rs:139) still reports the configured context_window (captured at load, inference.rs:39), never the effective value. The agent loop's summarization gate (packages/agent/src/local_agent/agent_loop.rs:50,56,1092) uses a compile-time TOTAL_TOKEN_BUDGET = 32_000 and does not consult model_info() at all.

Consequence: when the 12B model is capped to ~8960 tokens, the agent will still assemble up to ~32K tokens of history before summarizing, then generate_blocking rejects it at the prompt_tokens >= effective_n_ctx guard (mod.rs:380) → ChatError::ContextOverflow → InferenceError::Engine (inference.rs:123) → hard turn failure. The very model this PR unblocks will hit this on any moderately long conversation.

This is the flip side of the PR's own note that model_info().context_window is out of sync — it is a real problem, but only for the budgeting consumer, not the allocation consumers (the daemon at local_agent_service.rs:1160 correctly uses context_window as the ceiling, which is right). Two honest options:

  • Preferred (small): Make model_info() report the effective window and have the agent loop derive its TOTAL_TOKEN_BUDGET from model_info().context_window rather than a constant. This closes the loop so summarization kicks in at the real ceiling. Wiring the effective value out of ChatEngine requires exposing it (it lives in state.context_size after first context creation, so it's only known post-first-inference — a caveat worth noting).
  • Acceptable for this PR: Explicitly scope this out with a tracked follow-up issue, and note in the PR that large-model long-conversation robustness is deferred. Given the PR's declared scope is the OOM allocation fix, this is defensible — but it should be a conscious, documented decision, not a silent gap, because AC4 gestures at "no regression" end-to-end.

I would not block merge on this if it's captured as a follow-up, but it should not be left implicit.

🟢 2. KV_BUDGET_PERCENT = 40 is an empirical constant with a real robustness envelope — document its assumption

The 40% cap plus 2 GiB fixed headroom is empirically tuned to one machine class (16 GB, Metal, one specific OOM signature). The rationale comment (mod.rs) is excellent and honest about why the fraction cap exists (the batch compute buffer scales with the window). My only concern is durability: the compute-buffer overhead is roughly proportional to n_batch (== n_ctx here), so a fixed 40% fraction is a proxy for a term that actually scales with the very quantity being solved for. On a machine with much more free memory but a very large model, 40% could be needlessly conservative; on an even tighter machine it may still be optimistic. This is fine as a pragmatic heuristic for the current hardware target and is well-guarded by the floor/clamp, but consider a brief note (or a follow-up) that these two constants are the tuning knobs if a new hardware class or a much larger batch/window regime is introduced. No change required now.

🟢 3. n_head_kv is a single per-model value; per-layer variance is inherent to the upstream API (not a defect here)

The GQA computation uses model.n_head() / model.n_head_kv(), each of which returns a single per-model scalar from llama_model_n_head[_kv] (confirmed in llama-cpp-2 0.1.146/0.1.151 source). Models with per-layer head-count variance (rare) would not be captured, but that's an upstream API limitation, and because kv_bytes_per_element rounds up (Q4_0→1) and the budget is deliberately a conservative upper bound, the estimate errs toward under-allocating context (safe) rather than OOMing. Correct call. No action.

🟢 4. context_size is overwritten in place — theoretical ratchet if context recreation is ever added

get_or_create_context overwrites self.context_size with the reduced value (mod.rs:123). Today the context is created exactly once and never reset to None (verified — no context = None / .take() path exists), so compute_effective_n_ctx runs once and this is fine. But the reduced value now is the ceiling: if a future change ever drops and recreates the context under different memory pressure, sizing would ratchet against the already-reduced value, not the original configured ceiling. Cheap insurance: keep the original configured ceiling in a separate immutable field and always fit against that, or add a comment at mod.rs:123 pinning the "created once" invariant. Optional.

🟢 5. Integer-arithmetic edge cases are handled correctly

Verified the math is panic-free: n_head/n_layer/n_embd == 0 short-circuit to configured; bytes_per_token == 0 guarded; the fraction uses u128 intermediate to avoid overflow (available * 40 can't overflow u64 in practice but the widening is correct defensive style); saturating_sub on the headroom prevents underflow; the clamp(N_CTX_FLOOR, configured) handles the zero-budget case (test fit_clamps_to_floor_when_memory_below_headroom proves it). The test suite covers tight-memory reduction, roomy no-op, floor clamp, degenerate geometry, real-repro headroom, and quant mapping — genuinely good coverage for a pure function.

🟢 6. expect in generate_blocking is sound

llama.context.as_mut().expect(...) (mod.rs:387) is safe: get_or_create_context()? on the prior line guarantees context is Some and nothing between them can null it. The borrow split (call as a statement, read context_size, then re-borrow context) is the idiomatic way to end the &mut self borrow before reading the field. Clean.

Recommendation

APPROVE — with a strong recommendation to address Finding 1 either in this PR (wire the effective window into the agent's history budget) or via an explicitly-linked follow-up issue before this lands, so the large-model long-conversation path degrades gracefully (summarize) rather than erroring (ContextOverflow). Findings 2–6 are informational/optional. The allocation fix itself is correct, well-tested, standards-compliant, and a clear net improvement to code health.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pragmatic code review posted as a PR comment. Verdict: APPROVE with one recommended follow-up (agent history budget doesn't learn the reduced effective window — long conversations on a shrunk 12B window fail hard with ContextOverflow instead of summarizing). Allocation fix itself is correct, well-tested, and standards-compliant. See the review comment for full detail.

…d 32K

Addresses the code-review finding on the adaptive-n_ctx change: sizing the KV
cache down to fit memory only prevents the OOM if the agent's history-budgeting
layer also respects the reduced window. It didn't — model_info() reported the
configured ceiling and the summarization gate used a hardcoded 32K budget, so a
12B model capped at ~7K tokens would pack up to 32K of history and then be
rejected with ContextOverflow. That trades an OOM crash for a different crash on
any moderately long conversation with the very model this unblocks.

- Decide the effective n_ctx eagerly at model load (geometry + free memory are
  both known then) instead of lazily at first generation, so model_info()
  reports the real window immediately. Context creation stays lazy but reuses
  the stored value.
- LlamaChatInferenceEngine::model_info() now reports the engine's effective
  context_size rather than the cached configured value.
- The agent loop derives its total/history token budgets from
  model_info().context_window (reserving MAX_RESPONSE_TOKENS so summarization
  fires before the prompt fills the window), falling back to the static 32K
  budget only when the window is unknown (model not loaded / remote backend).
- MockEngine gains a configurable window; new test
  summarization_triggers_on_reduced_effective_window pins the closed gap
  (10K-token history under the old 32K constant but over a 4096 window now
  summarizes instead of erroring).

Re-verified E2E: gemma-4-12b-unsloth-q4km reduces at load (effective=6912,
logged) and runs multiple turns with no OOM; the reduced window is now the
budget the agent plans against.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DMPgbnyNk6bDFnpqtTPbKr
@malibio

malibio commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1643 (Re-Review)

Review Type: Re-Review — of the new commit 09cd301e "Budget agent history against the effective context window, not a fixed 32K", which addresses the one 🟡 finding from my initial review (68c3e4e2, COMMENTED).
Scope of this pass: packages/nlp-engine/src/chat/mod.rs, packages/agent/src/local_agent/inference.rs, packages/agent/src/local_agent/agent_loop.rs (+144/−17).
Verification run locally: cargo build -p nodespace-agent --lib clean; cargo test -p nodespace-agent --lib summarization → 5 passed (incl. the new summarization_triggers_on_reduced_effective_window); cargo clippy on both nodespace-agent and nodespace-nlp-engine → zero warnings.

Previous Review Summary

Count Status
🔴 Critical 0 —
🟡 Recommended (Finding 1) 1 ✅ Addressed
🟢 Informational (Findings 2–6) 5 Optional; not required for merge

Finding 1 was: the effective (memory-reduced) window was invisible to the agent's history-budgeting layer — model_info() reported the configured 32K and the summarization gate used a hardcoded TOTAL_TOKEN_BUDGET = 32_000, so a 12B model capped at ~7K would pack 32K of history then hit a hard ContextOverflow, trading the OOM for a different crash. This is now resolved.

Verification of the fix

1. Finding 1 fully resolved — yes. The effective window now flows end-to-end on the native path:

  • chat/mod.rs:216 computes effective_n_ctx eagerly at load_model (after weights are resident, so free-memory measurement reflects them) and stores it via ChatLlamaState::new(..., effective_n_ctx, ...). get_or_create_context (mod.rs:117) no longer recomputes — it allocates from the stored value, and ChatEngine::model_info() (mod.rs:1066) reports it immediately after load, before any generation.
  • inference.rs:137-141 reports self.engine.model_info().context_size (effective), falling back to the cached configured self.context_window only when the model is not loaded.
  • agent_loop.rs:1094-1103 derives total_budget/history_budget from model_info().context_window, reserving MAX_RESPONSE_TOKENS so summarization fires before the prompt fills the window; falls back to the static constants when the window is unknown.
  • New test summarization_triggers_on_reduced_effective_window (agent_loop.rs:2331) pins the exact closed gap: ~10K history — under the old 32K constant, over a 4096 effective window — now summarizes instead of erroring.

2. Eager-at-load sizing move — no regression found.

  • Lazy-context path: get_or_create_context is reachable only from generate_blocking, which first does state_guard.as_mut().ok_or(ChatError::ModelNotLoaded)? (mod.rs:313). A loaded state exists only via load_model, which always populates context_size with the effective value. There is no path to create a context without load_model having sized it. The borrow split in generate_blocking is unchanged and remains sound.
  • model_info() before first generation: now returns the correct effective window (the whole point of moving the computation to load time). Previously it would have returned the configured ceiling until first inference — the move strictly improves this.
  • Unload/reload: unload_model does .take(); a subsequent load_model recomputes effective_n_ctx fresh against self.config.n_ctx (the configured ceiling), not the previously-reduced value. This also incidentally closes my prior 🟢 Finding 4 (the "ratchet" concern) — sizing always fits against the immutable configured ceiling, so repeated reloads never compound the reduction.

3. Budget arithmetic at very small windows — degenerate-but-safe, no thrash. At the N_CTX_FLOOR = 4096 floor: total = max(4096−2048, 4001) = 4001, history_budget = 4001−4000 = 1. That collapses the second gate (history_tokens <= 1) to "effectively always summarize when over total_budget," which is the intended behavior for a tiny window. maybe_summarize_history is called once per ReAct iteration (agent_loop.rs:359), not in an inner loop, and each call drains-and-summarizes at most once — so no re-summarize thrash or infinite loop is introduced. The one residual edge (the 3 kept-verbatim messages could themselves exceed a 4096 window and still overflow) is a pre-existing structural property of the keep-last-3 design, not introduced here, and this commit makes it strictly less likely by summarizing at ~2K instead of 32K on a reduced window. Out of scope; no action.

4. Blast radius correctly contained. The model_info() behavior change is limited to the native LlamaChatInferenceEngine. Other context_window consumers are unaffected: model_manager.rs builds specs from the static catalog (metadata, not the runtime engine); ollama_inference.rs uses its own /api/show-derived window on a separate backend. The only budget-consumer that reads the runtime effective window is exactly the agent loop that needed it.

Findings (this pass)

No new findings. No standards violations (no lint suppression, no println!, no back-compat cruft, comments explain why). No dead code introduced — the cached context_window field (inference.rs:25) and the static TOTAL_TOKEN_BUDGET/HISTORY_TOKEN_BUDGET constants remain live and justified as the not-loaded / remote-backend fallback. MockEngine gained a configurable window with a sensible default (8192) and a with_context_window constructor; the two prior summarization tests that use the default still pass against the now-smaller derived budget, confirming consistency.

🟢 (Informational, optional — carried context, not a blocker): my prior 🟢 Findings 2 (KV_BUDGET_PERCENT/headroom are single-hardware-class tuning knobs) and 3 (per-layer GQA variance) still stand as documented, unchanged, and remain acceptable pragmatic heuristics. Nothing in this commit touches them.

Recommendation

APPROVE. The one recommended finding from the initial review is fully and correctly addressed, with a targeted regression test pinning the closed gap and E2E confirmation (gemma-4-12b-unsloth-q4km, effective=6912 logged at load, multiple turns, zero OOM). The eager-at-load restructure is sound across the lazy-context, unload/reload, and pre-first-generation paths, and even closes a prior informational finding as a side effect. No new issues introduced. This is a clean net improvement and is ready to merge.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of commit 09cd301 (addresses the one 🟡 finding from the initial review). Verdict: APPROVE (recorded as a comment — GitHub blocks self-approval on an own PR). The effective context window now flows end-to-end into the agent's history budget; sizing is moved to load time and is sound across lazy-context / unload-reload / pre-first-generation paths; the new regression test pins the closed gap; no new issues. Full re-review posted as a PR comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Native llama.cpp path allocates a fixed 32K context at load time; Ollama's per-request negotiation avoids the same OOM

1 participant