Skip to content

Studio: move the GGUF chat requests and chat compaction out of llama_cpp.py - #15596

Open
oobabooga wants to merge 6 commits into
unslothai:mainfrom
oobabooga:llama-cpp-chat-split
Open

oobabooga wants to merge 6 commits into
unslothai:mainfrom
oobabooga:llama-cpp-chat-split

Conversation

@oobabooga

@oobabooga oobabooga commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

core/inference/llama_cpp.py is 42,440 lines and holds the whole GGUF backend. Two parts of it change mostly on their own: the chat request path (generate_chat_completion, the 4,037-line tool loop generate_chat_completion_with_tools, count_chat_tokens) and chat compaction. The safetensors orchestrator and the routes also import the compaction helpers from this module.

This PR moves those two parts, verbatim, into llama_chat.py and chat_compaction.py. llama_cpp.py drops to 35,930 lines. Unlike #13990, which splits the whole file into 45 files and 21 mixins, it moves only code that the history shows changing on its own. Thanks to #13990 for making the case for the split and for its approach to verifying the move: checking every moved definition by AST against the original, which this PR also does.

Why this cut

I counted the 302 commits that touched llama_cpp.py since the 2026-08-10 history squash, excluding merges and commits touching more than 50 files:

Code Lines Commits Touched nothing else in the file Also touched load_model
Chat request path (moved) 4,926 80 50 9
Chat compaction (moved) 901 17 9 1
GGUF cache and download helpers 2,032 40 12 16
Launch-argument helpers 2,968 56 0 53
load_model 9,584 142 11 n/a
  • The tool loop moves together with generate_chat_completion: 25 of that method's 27 commits also changed the tool loop.
  • The other helpers mostly change together with load_model, so splitting them off would turn one-file changes into two-file ones. load_model itself shares its state with __init__ and unload_model, so splitting it is a redesign, not a move.

Changes

  • chat_compaction.py holds the 47 compaction, archive and recall definitions. It depends only on context_window. The orchestrator and the routes import from it.
  • llama_chat.py holds LlamaChatMixin with the three chat methods, plus the 76 module-level definitions they use. Six small helpers that llama_cpp also reads move too (for example _LlamaStreamCancelled and _local_ssl_context). That keeps imports one way: llama_cpp → llama_chat → chat_compaction.
  • LlamaCppBackend inherits LlamaChatMixin. The methods keep their indentation byte for byte, so git diff --color-moved and git blame -C follow them. They stay methods of the backend, so callers, class patches and instance fakes work unchanged.
  • No re-exports. A test that still patches a moved name on llama_cpp now fails with AttributeError instead of silently patching nothing.
  • Each new module logs under its own name (get_logger(__name__)), so log records from the moved code carry the new module name.
  • safetensors_agentic.py no longer imports llama_cpp.
  • refactor_guard covers the new modules, and local-agent-guides-ci.yml triggers on them. test_llama_chat_module.py fails if a chat module imports llama_cpp, or if a copy of a mixin method reappears in LlamaCppBackend, where it would silently win.

Test changes

44 test files change, mostly to patch where the name is looked up:

  • Tests that drive the routes or the orchestrator patch chat_compaction; tests that drive the GGUF chat methods patch llama_chat.
  • Source-text tests read llama_chat.py. The two that assert text is absent from the backend (t_max_predict_ms, _request_branch) read all three files, so they keep their scope.

Validation

  • Moved code is unchanged: all 1,430 top-level statements and backend members of main's llama_cpp.py appear once with an equal AST, apart from the 5 import lists that are split between the modules, and all 624 global-name reads in the moved functions (counted once per function) resolve to the same definition or import as before. 6,518 of the 6,521 lines removed from llama_cpp.py reappear verbatim.
  • Backend tests (Linux, Python 3.13, CPU, the 457 files that reference these modules): 21 failed and 33,184 passed. The same 20 fail when the same files run on main; the extra one passes when its file runs alone and does not touch the moved code.
  • Root tests (45 files touching these modules) and the 3 frontend parity tests that read llama_cpp.py: same results as main.
  • ruff check and the repo's lint scripts pass.
  • Not run: the whole backend suite, and anything on a GPU.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T19:14:28.511757Z ab6294e Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@oobabooga

Copy link
Copy Markdown
Member Author

Reached Codex review convergence at oobabooga#421.

@NilayYadav NilayYadav self-assigned this Oct 27, 2026
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…, and name any test that still does (#15626)

## Summary

Backend CI (`(Python 3.13, a-f)`) and `Repo tests (CPU, rest)` have been
failing intermittently with dozens of errors like

```
AttributeError: torch._dynamo.config.recompile_limit does not exist
AttributeError: torch._dynamo.config.suppress_errors does not exist
AttributeError: torch._inductor.config.emulate_precision_casts does not exist
```

Seen on #15586, #15589, #15590, #15592, #15593, #15596 and #15601.
Locally, on pytest 9.1.1, it never reproduced.

### Root cause

CI resolves pytest 9.2.0, which changed `MonkeyPatch.setattr`
(pytest-dev/pytest#10644).
- For a non-class target it now records the old value from the instance
`__dict__`. Before, it used `getattr`.
- A torch `ConfigModule` (`torch._dynamo.config`,
`torch._inductor.config`, and its `SubConfigProxy` children such as
`torch._inductor.config.triton`) serves its entries from `__getattr__`.
They are never in `__dict__`, so pytest records "not set".
- On undo it therefore calls `delattr`. `ConfigModule.__delattr__` marks
the entry hidden, and every later read in that process raises `... does
not exist`.

So every `monkeypatch.setattr(torch._dynamo.config, ...)` in the suite
now deletes the entry it patched. Which shard fails depends on which
xdist worker such a test lands on.

Minimal reproduction:

```python
def test_patch(monkeypatch):
    monkeypatch.setattr(torch._dynamo.config, "suppress_errors", True)

def test_after():
    assert torch._dynamo.config.suppress_errors is False
```

On pytest 9.1.1 both pass. On 9.2.0 `test_after` fails with
`torch._dynamo.config.suppress_errors does not exist`.

## Change

`tests/_shared/torch_config_guard.py`, installed from
`tests/conftest.py` and `studio/backend/tests/conftest.py`:
- **`install_monkeypatch_fix()`:** wraps `pytest.MonkeyPatch.setattr`.
When the target is a torch `ConfigModule` or `SubConfigProxy`, including
the dotted-string form, it records the real value that was replaced, so
`undo()` restores it with `setattr` instead of deleting the entry. Every
other target goes through pytest unchanged. The fix is a no-op until
torch is imported, and it never imports torch itself.
- **`_no_deleted_torch_config_entries` autouse fixture:** any test that
still leaves a config entry deleted, by any route, errors at its own
teardown with the stack of the delete. The entry is then restored with
its previous value, so the rest of the worker is not poisoned. Cost is
about 24 us per test.

The guard is what found the cause. On the first push (guard only),
staging CI named 15 deletes, and every recorded stack ended in
`_pytest/monkeypatch.py, line 437, in undo: delattr(obj, name)`.

## Testing

**Under pytest 9.2.0** (CI's version):
- `tests/test_torch_config_guard.py`: 10 passed. Two tests pin the fix:
- `test_monkeypatch_undo_restores_a_config_entry_instead_of_deleting_it`
covers `torch._dynamo.config`, `torch._inductor.config` and
`torch._inductor.config.triton`.
- `test_monkeypatch_undo_restores_a_config_entry_named_by_import_path`
covers the dotted-string form.
- **Sabotage:** with `install_monkeypatch_fix` turned into a no-op,
those 4 cases fail and the guard errors at teardown.
- `tests/test_block_compile.py`: 13 failed on main (`suppress_errors` /
`recompile_limit does not exist`, the CI signature), 42 passed with this
change.

**Under pytest 9.1.1:**
- `tests/test_torch_config_guard.py`: 10 passed, and
`tests/test_block_compile.py`: 42 passed, on both trees.
- `studio/backend/tests/test_diffusion_*.py` (about 17,400 tests, run in
parallel with main on one loaded host): the guard fired 0 times. The
branch had 67 failed / 14 errors against 79 / 26 on main. The 3 failures
seen only on the branch pass when rerun alone, so they are load flakes.
- Meta-tests that read conftests and `tests/_shared`, plus
`test_ci_backend_pytest_shards.py`: 604 passed.
danielhanchen added a commit that referenced this pull request Oct 28, 2026
… moved is not a clash (#15622)

`Source lint` blocks refactors that move helpers into a new module,
because `scripts/verify_import_hoist.py` reads every re-pointed
function-local import as a rename clash. Two open PRs are stuck on it
today:

- #15596 (moves the GGUF chat and compaction helpers out of
`llama_cpp.py`): 63 `TARGET-CHANGED` blockers, e.g. `'_can_reset_epoch'
... ['from:core.inference.llama_cpp:_can_reset_epoch'] ->
['from:core.inference.chat_compaction:_can_reset_epoch']`.
- #15587 (moves `resolve_local_single_file` into
`diffusion_local_files.py`): 2 of the same.

## Cause

`TARGET-CHANGED` exists to catch a same-name load that now resolves to a
different object. Its only exemption is a module-level import removed
and re-added in the same file. A refactor that moves a definition and
updates `from old import N` inside a function to `from new import N`
binds the same object, but neither import is module-level, so it is
reported as a clash.

## Change

`compare()` takes an optional `moved(old_target, new_target)` predicate.
`main()` builds it from git: modules are resolved to files at the before
and after refs, the same way the importing file would see them (relative
imports against its package, absolute ones against its ancestor
directories). A `TARGET-CHANGED` is downgraded to an INFO `MOVED` line
only when every lost `from:old:N` pairs with exactly one gained
`from:new:N` of the same name, and either:

- both imports reach one definition, following top-level `from ...
import` re-exports at their own ref (the old and new module re-export
it); or
- `N` was defined at the top level of the old module before, is defined
at the top level of the new module after, and the old module no longer
defines it, at most re-importing it from the new module.

Anything else stays a blocker: a re-point to a different `N`, the old
module keeping its own definition, or an alias rename across modules.
The module-level relocation rule, the `HOISTED-IMPORT-UNUSED` check and
its `__init__.py`-only `__all__` exemption are unchanged.

### When a re-point does not count as a move

A re-pointed import keeps its TARGET-CHANGED blocker unless every one of
the following holds:
- the old and new targets name the same symbol, and each lost import
pairs one-to-one with a gained import;
- both modules resolve to exactly one file, meaning an absolute import
is not ambiguous between roots, and a relative import does not climb to
or past the repo root;
- the destination did not bind the name before the change, and binds it
exactly once now, unconditionally at module level.

The last point treats a binding as ambiguous when any of these appears
for the name:
- a second binding site;
- a binding inside an `if` / `try` / `with` / loop / `match` block,
including `TYPE_CHECKING`;
- a bare annotation;
- `del`, `global`, `:=` (including in a lambda default), `except ...
as`, or a match capture;
- `import *`.

## Verification

- `--self-test`: all cases pass, including three new ones (a re-point
after a move, the same re-point when nothing moved, an alias rename
across modules).
- #15596 at its head against its merge base: main's verifier 63
blockers; this branch 0 blockers, 63 `MOVED`.
- #15587: main's verifier 3 blockers; this branch 1, the
`HOISTED-IMPORT-UNUSED` re-export in `diffusion.py`, which the existing
rule keeps on purpose.
- End to end through git refs in a scratch repo: a genuine move and a
re-point through a shared re-export pass; a re-point to a different
function of the same name, a move where the old module keeps its own
definition, and an alias rename across modules all still fail.
@danielhanchen

Copy link
Copy Markdown
Member

The Source lint failure here (63 TARGET-CHANGED blockers from verify_import_hoist.py) was the verifier not recognising a function-local import that follows its definition into a new module. #15622 is now on main and reports all 63 as moved with no blockers on this head, so merging main into this branch should clear that check.

Lyxot added a commit that referenced this pull request Nov 4, 2026
…runs (#16608)

After a tool call in a GGUF chat, the reply shows nothing until the
model's next pass starts writing. In that gap Studio fits the context
window, compacts it if needed, and processes the prompt again, which
took 26 to 40 s per tool call in the CPU test below. [A user on
r/unsloth](https://www.reddit.com/r/unsloth/comments/1xkbkem/is_compaction_super_slow_for_you_too_or_just_me/)
could not tell whether the model had frozen, the tool had failed, or
compaction was running. Their slowdown went away after updating Studio,
but the missing status still reproduces on current main, as measured
below.

Two things cause the gap:

- `GeneratingIndicator` in `thread.tsx` only renders while the reply is
empty, so after the first tool call neither "Working..." nor "Processing
prompt N%" comes back. The server keeps sending prefill progress during
this time, but nothing displays it.
- Compaction has no running signal. Its only event, `context_truncated`,
is sent after the fit finishes.

## Changes

- **Status between tool calls.** `NextRoundIndicator` renders the
existing `GeneratingStatus` under a finished tool call while the reply
is still running, until the next pass streams something. A tool result
clears the previous pass's live figures on the client and server, so a
stale "Processing prompt 100%" cannot carry over.
- **"Compacting context..." label.** The rolling and checkpoint fits now
call an `on_evict` hook at the point where they decide to drop turns,
including a manual `/compact`. That reaches
`_PrefillProgressSignal.compacting()`, and the stall loop sends
`{"type": "generation_progress", "phase": "compacting"}` while the fit
is still blocked. Replaying a cut from an earlier request never reaches
the hook. This matters because once a chat has compacted, its full
history is over budget on every later request, so a token-count check
would show the label on every turn.
- **Frontend.** The new phase sets a flag in the runtime store.
`context_truncated`, or the next prefill or decode sample, clears it.
Both the live stream and the reconnect path (`runtime-provider.tsx`)
handle it.

## Notes

- No new frame type: the label reuses `generation_progress`, which is
only sent on Studio UI streams. A plain streaming `/v1/chat/completions`
request that compacts still gets only chat chunks, `context_truncated`
and `[DONE]`. Older frontends ignore the unknown phase.
- The compaction label is llama.cpp only. MLX and managed engines
compact through `Orchestrator.compact_chat_context` and still report
only afterwards, but the between-calls status applies to them too.
- #15596 moves the same `llama_cpp.py` call sites. Whichever merges
second needs to carry the `on_compacting` argument across.

## Screenshots

Main (`3d4aa8685f`) vs this PR, on a fresh Studio home, third turn of
the test below.

While compaction runs:

![Compacting context... under the tool call while compaction
runs](https://raw.githubusercontent.com/oobabooga/unsloth/pr-media/pr/compaction-status/compaction_status_01_compacting-b64d3b7636be.png)

While the prompt is processed again after compaction:

![Processing prompt progress under the tool call after
compaction](https://raw.githubusercontent.com/oobabooga/unsloth/pr-media/pr/compaction-status/compaction_status_02_prompt_progress-53667dc72d42.png)

## Testing

Live A/B in the browser: Qwen3-8B Q4_K_M on a CPU-only llama-server,
8192 context, auto-compact on. Three turns, each asking for one `python`
call that prints 1200 items; the third turn compacts. Seconds from the
tool result to the first token with no status line shown (measured at
`47dab66e99`):

| Turn | main | this PR |
| --- | --- | --- |
| 1 | 36.4 | 0.3 |
| 2 | 26.4 | 0.3 |
| 3 (compacts) | 39.9 | 0.3 |

The 0.3 s left on this PR is between the first token arriving and the
run finishing. On the compacting turn the line goes "Working...",
"Compacting context..." (about 1 s after the tool result, until
`context_truncated`), "Working...", then "Processing prompt 60% · 16s
left". A fourth turn that only replays the earlier cut shows no
compaction label.

- Backend: 16 new cases in `test_live_generation_progress.py`. They
cover the hook in both fit policies, replay staying silent, a new
checkpoint past an earlier cut, a forced reset, frame ordering in the
stall loop, and dropping a previous pass's unsent figures. The related
fit, compaction, tool-loop and refactor-guard suites pass (721 tests).
- Frontend: 4 new tests in `generation-details.test.ts`. The typecheck
and `i18n:check:strict` pass. In the full node suite, 14738 pass and 15
fail; the same 15 fail on `3d4aa8685f`.

---------

Co-authored-by: Lyxot <[email protected]>
@oobabooga

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: ab6294e290

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants