Skip to content

Studio: give local thinking a window budget, and compact after a thought the window still cuts - #18925

Merged
danielhanchen merged 21 commits into
mainfrom
studio-plain-thought-length
Nov 23, 2026
Merged

danielhanchen merged 21 commits into
mainfrom
studio-plain-thought-length

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

A local GGUF chat whose thinking runs past the context window ends with only the thought and no answer. Studio runs llama-server with --no-context-shift, so the server stops with finish_reason: length as soon as the window is full; the model never closed its thought, so there is no EOS and no answer. The chat then shows "Response ran out of tokens", or its automatic continuation is refused because the cut thought already fills the window.

The fix

1. Close the thought before the window does. Every local thinking request now sends llama-server a thinking_budget_tokens sized from what the window leaves after the prompt: the answer keeps a quarter of that room (at least 1,024 tokens, or half the room when it is smaller), the thought gets the rest. When the budget runs out llama-server ends the thought itself with the model's own end tag (</think>, Gemma 4's <channel|>, Inkling's end-of-message, and so on) and the model answers in the same request. It applies to the plain generator and to each round of the tool loop. A smaller budget the caller or the load settings asked for still wins, nothing is sent with thinking off, and a Max Tokens below the window's room is left alone since it stops the reply first. On a large window the budget only matters near the end of it.

2. If a thought is still cut, compact instead of resuming it. A thought can still be cut (an estimate that ran short, a resumed thought). Then the reply ends there and the thread's next request (the automatic continuation, or the next message the user types):

  • keeps the thought, cut back 8 tokens since the window can stop it mid-word, as a finished thought in the conversation; the model's chat template writes its own closing marker, read once per load with /apply-template (Qwen3.8 \n</think>\n\n, Gemma 4 \n<channel|>, Inkling-2-Mini <|end_message|><|message_model|><|content_text|>);
  • is compacted the way /compact is;
  • archives the thought, so search_conversation can find it, and offers search_conversation even with tools off;
  • starts with: "The previous model stopped thinking, so re-check via search_conversation or read the transcript at <path> and continue work."

3. Every compaction writes a transcript. Automatic compaction and /compact both write the chat's whole branch to transcript-<thread>.md in the chat's sandbox folder and name it in the <carried_forward> block next to search_conversation. The line is not one of the block's carried items, so the next reset does not re-read it as an instruction, and linking twice changes nothing.

Only threads Studio stores get step 2; an API client's next request is left as it is. Errors are still returned to a caller that asked for context_overflow: "error".

Real llama.cpp runs

Studio's plain generator against llama-server --no-context-shift (the build Studio installs), Qwen3-4B Q4_K_M, thinking on, two prompts (a 40-step planning task and a word problem that asks to check every case), one request each:

-c 1024 -c 2048
main thought only, 0 answer chars (both prompts) thought only, 0 answer chars (both prompts)
this PR 2,089 and 1,751 answer chars 3,960 and 2,443 answer chars

The answer then fills the rest of these tiny windows, as any long answer does. The step 2 path alone (no budget) answered at 2,048 after compacting (3,591 chars), but at 1,024 the recovery's own thinking plus a search call overflowed again, which is why the budget comes first.

Tests

  • tests/test_cut_thought_compaction.py: the window budget (small and large windows, a smaller requested budget wins, a smaller Max Tokens and no window send nothing); a thinking request carries the budget and thinking off carries none; the cut reply ends with the thought closed and nothing more; the cut is cut back and held only for a thread Studio keeps, and only for a thought the window cut (not Max Tokens, a cancel or a clean stop); the next request keeps the thought finished, compacts and gets the note, for both the automatic continuation and a typed message; a caller that asked for errors keeps them; the closing marker is read from Qwen3, Gemma 4 and Inkling templates; search_conversation finds the archived thought while an answer off the branch is still filtered.
  • tests/test_compaction_transcript.py: the transcript holds the branch without the system prompt, the block names it beside the search, it is not carried into the next epoch, linking is idempotent, a cut thought is labelled once with its marker, and a real compacted request writes and links it.
  • Every backend test file that drives the llama.cpp generators, base against head: no test fails on head that passes on base.

Not covered here

  • External connections (Ollama, llama.cpp or vLLM servers, cloud providers) relay their stream as it arrives; a reply cut inside its reasoning there still ends with no answer.
  • The budget uses Studio's token estimate of the prompt, not an exact count; when it runs short, step 2 takes over.

Studio before and after

Qwen3-0.6B Q4_K_M on CPU, Context 512, tools off, thinking on, greedy, the same planning prompt on both sides. Before: the turn ends with only the thought, and its automatic continuation is refused because the cut thought already fills the window. After: the thought closes in time and the plan follows in the same turn. In a window this small the answer then fills it too, and continuing that answer is refused the same way a cut answer's continuation is today.

Before and after: a thought that fills the window

…out tools

A local GGUF chat without tools (tools off, or a model with no tool support) whose thinking
ran past the context window ended the turn with only the thought and no answer: llama-server
runs with --no-context-shift, stops with finish_reason length, and the plain generator closed
the thought and returned. The tool loop already recovers this case; the plain path did not.

Now the plain path retries once with thinking off: the original messages, a short note with the
tail of the thought, and a request for the answer. The retry continues the same snapshot, so
the thought stays in the turn ahead of the answer. It is skipped when the caller's Max Tokens is
spent, when the model cannot turn thinking off, or after a cancel; if the server refuses it
before streaming, the turn ends as before.
@danielhanchen danielhanchen self-assigned this Nov 22, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 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-23T14:17:47.281006Z 7e3cc42 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 58c4bef6fa

ℹ️ 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".

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

The (Python 3.13, m-r) shard of the cross-platform run fails both tests in studio/backend/tests/test_refactor_guard.py, because this PR changes the pinned tool_call_parser surface:

runtime.core.inference.tool_call_parser.functions.continue_after_length_message: "... -> 'str'" -> "..."
ast.core.inference.tool_call_parser.symbols.continue_after_length_message.signature: '' -> 'tools: bool=True'

The new tools: bool = True parameter is intentional, so only the two pinned entries need updating:

  • studio/backend/tests/data/refactor_guard/runtime_inventory.json: continue_after_length_message() -> 'str' becomes continue_after_length_message(tools: 'bool' = True) -> 'str'
  • studio/backend/tests/data/refactor_guard/ast_inventory.json: under tool_call_parser, continue_after_length_message's "signature": "" becomes "signature": "tools: bool=True"

With just those two lines changed on the PR head, test_refactor_guard.py passes locally (12 passed). A full refactor_guard.py snapshot also rewrites a few thousand unrelated lines, so the two-line edit is the cleaner change.

@danielhanchen

Copy link
Copy Markdown
Member Author

Both entries are updated in f59c77f, the two-line edit described above; test_refactor_guard.py passes (12 passed).

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 4c5a0157ce

ℹ️ 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".

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 22, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen danielhanchen changed the title Studio: answer once more when a thought fills the window in chat without tools Studio: give local thinking a window budget, and compact after a thought the window still cuts Nov 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2f07cff9ed

ℹ️ 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".

Comment on lines +2202 to +2205
if row is not None and row["filename"] == _CUT_THOUGHT_DOCUMENT:
# A cut thought is never in the branch text, which drops reasoning; it is this thread's own.
cache[document_id] = True
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep archived cut thoughts scoped to their originating branch

After a cut thought is archived, editing an earlier user message or selecting a sibling reply in the same thread leaves that thought eligible for recall forever: this filename exemption returns true without checking the supplied live branch. Thread ownership does not establish branch membership—the existing tool loop explicitly maintains a separate live branch because stored threads contain the whole retry DAG. As a result, search_conversation can inject reasoning based on abandoned instructions into the current answer, even though ordinary archived turns are correctly filtered. Store enough originating-turn or branch provenance to validate these thought documents rather than bypassing the branch check.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this: it needs a cut thought, then an edit of an earlier message, then a search that lands on that thought, and the result is a recalled snippet labelled as an earlier thought, not a wrong or lost call. Tracking branch provenance through recall for that case is more than it is worth here.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

The latest staging run of this branch (on top of current main) has two reds that are specific to it; both pass on main:

  • (Python 3.13, a-f): studio/backend/tests/test_conversation_recall_injection.py::test_archive_and_recall_skips_recall_once_already_done fails at assert result["conversation"] is after. With recall_done = True, _archive_and_recall now hands back a new list with the same messages instead of the conversation it was given, which follows from the core/rag/conversation_archive.py change here. Either keep returning the same object when nothing is recalled, or relax the test to equality if the copy is intended.
  • Uploads (windows-latest): tests/studio/rag_upload_ci.py ends with browsers: exit 1 although every case it prints is passed, so the failing case is not in the step output; the uploaded artifact for that job should name it.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 0b1f674b38

ℹ️ 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".

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 23, 2026
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…er teardown (#19070)

## Summary

`(Python 3.13, diffusion)` still occasionally fails
`studio/backend/tests/test_diffusion_ddp_effective_precision.py::test_real_gloo_two_ranks`.
With the diagnostics from #19044, the latest occurrence (the staging run
for #18925, on a base that has #19044) says where it hangs:

```
Failed: the two Gloo ranks did not finish within 180 s:
rank 0 rc=0
stdout:
[Gloo] Rank 0 is connected to 1 peer ranks. Expected number of connected peer ranks is : 1
REFUSED Multi-GPU training stopped: the GPUs ended up training different base precisions after conversion (rank 0: fp8, rank 1: bf16). ...
rank 1 rc=-9
stdout:
[Gloo] Rank 1 is connected to 1 peer ranks. Expected number of connected peer ranks is : 1
REFUSED Multi-GPU training stopped: the GPUs ended up training different base precisions after conversion (rank 0: fp8, rank 1: bf16). ...
```

## Root cause

The test's child script, not `diffusion_ddp`. Both ranks run the
precision check and print the correct verdict; rank 0 then exits, and
rank 1 never does: it hangs at interpreter exit, in the teardown of a
Gloo process group whose peer has already gone. The child never leaves
the group itself. The trainer does not have this problem:
`DistContext.close()` destroys the group on a bounded thread for exactly
this reason ("a communicator whose peers already exited must not hold up
the trainer child").

## Fix

`studio/backend/tests/test_diffusion_ddp_effective_precision.py` only.
After printing its verdict, each rank:

- waits at `dist.barrier()` (bounded by the 60 s group timeout from
#19044), so neither rank leaves while the other is still in the group,
- calls `dist.destroy_process_group()`,
- flushes and leaves with `os._exit(0)`, skipping interpreter teardown.

An exception anywhere before that still propagates and gives a nonzero
exit, which the parent reports with both ranks' output.

## Testing

- The file: 17 passed, three runs in a row, and under `-n 2`.
- The hang does not reproduce on a quiet host (each case takes about 1.5
s here), so the evidence for the cause is the rank report above.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7e3cc42802

ℹ️ 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".

Comment on lines +2202 to +2205
if row is not None and row["filename"] == _CUT_THOUGHT_DOCUMENT:
# A cut thought is never in the branch text, which drops reasoning; it is this thread's own.
cache[document_id] = True
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep archived cut thoughts scoped to their originating branch

When a user edits an earlier message or switches to a sibling response within the same thread, this unconditional acceptance makes thoughts from the abandoned branch eligible for search_conversation and automatic recall. Thread ownership does not establish branch membership: unlike ordinary archived turns, these documents now bypass the live transcript check permanently, so discarded reasoning can influence answers on the corrected branch. Store an originating turn or branch anchor with each cut thought and validate that anchor against the requested branch before accepting the document.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Same as before: this needs a cut thought, an edit of an earlier message, and then a search that lands on that thought, and the outcome is one recalled snippet labelled as an earlier thought. It does not run a wrong tool or drop or change a call, so it stays out of this PR.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 7e3cc42802

ℹ️ 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".

@danielhanchen
danielhanchen merged commit bf48fd9 into main Nov 23, 2026
@danielhanchen
danielhanchen deleted the studio-plain-thought-length branch November 23, 2026 14:48
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.

1 participant