Skip to content

server: add penalize_prompt to keep prompt tokens out of the penalty history - #283

Open
danielhanchen wants to merge 2 commits into
masterfrom
server-penalize-prompt
Open

danielhanchen wants to merge 2 commits into
masterfrom
server-penalize-prompt

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

server: add penalize_prompt to keep prompt tokens out of the penalty history

Base: base/upstream-ceefd16da (ggml-org b11696, the upstream commit under the current b11696-mix-7baeb9a prebuilt). The diff is only this change: 7 files, +51/-1.

Why

Unsloth Studio is about to run the FLUX.3 prompt upsampler (unsloth/flux-3-image-klein-pup-GGUF, a Qwen3.5-9B fine-tune) through llama-server. Its reference sampling (ComfyUI comfy/text_encoders/qwen35.py, and BFL's own vLLM path) applies presence_penalty and repetition_penalty over every token generated so far, never over prompt tokens, and with no window.

llama-server cannot express that today. init_sampler() feeds every prompt token into the sampler chain, so the penalties sampler sees the last repeat_last_n tokens of prompt plus output, and repeat_last_n: -1 is rejected with HTTP 400. With a long system prompt the penalty mostly lands on prompt words. On 16 prompts against an exact ComfyUI-semantics transformers reference, every repeat_last_n setting (64, 256, 1024, 4096, 8192) scored 0.47 to 0.50 word similarity, no better than no penalty at all (0.50).

What changes

  • New per-request field penalize_prompt (bool, default true) in the completion schema, plus --penalize-prompt / --no-penalize-prompt (env LLAMA_ARG_PENALIZE_PROMPT) for the server default.
  • With false, init_sampler() skips the prompt accept loop. That loop only ever fed the penalty and DRY history: grammar and the reasoning budget already ignore non-generated tokens (is_generated = false), and the dist and adaptive-p samplers do nothing on them after a reset. So grammar, reasoning budget and the other samplers behave exactly as before, and repeat_last_n / dry_penalty_last_n now count generated tokens only. With repeat_last_n = 4096 the window covers the whole of a 3584-token generation.
  • The field is echoed in generation_settings, /props default_generation_settings and /slots, and documented in the server README (request table and CLI table).
  • test_penalize_prompt in tools/server/tests/unit/test_completion.py: on stories260K, a presence penalty of 100 moves a greedy token that is already in the prompt by default, and does not move it with penalize_prompt: false; generated tokens are still penalized over the whole window.

Default true keeps today's behaviour exactly.

Results (B200, BF16 GGUF, -c 8192 -np 1 --jinja, mmproj F16 loaded)

check result
field absent, 4 prompts, base and distilled rows, vs stock b11696-mix-7baeb9a 8/8 captions byte-identical
penalize_prompt: false, repeat_last_n 4096, presence 1.5, repeat 1.0, top_k 1, vs the per-token logit_bias emulation of the exact semantics 15/16 byte-identical; the 16th diverges at word 58 on a near-tie
same, word similarity vs the transformers ComfyUI-semantics reference 0.675 mean (emulation 0.702; native repeat_last_n 64 0.499, 4096 0.467)
distilled row (repeat 1.05, presence 1.5) with the field 16/16 finish on stop, 218 to 332 words
i2i edit request with an image and the field works, 192 words, finish on stop
test-sampling pass
test_penalize_prompt pass on this branch, fails on plain b11696 (field ignored)

The emulation runs one /completion request per token, so its batch shapes differ from a single streamed generation. The one divergent caption picks "faded blue jeans" over "dark green cotton trousers" at a near-tie and stays coherent after that.

Request fields for the FLUX.3 upsampler

{
  "temperature": 1.0, "top_k": 1, "top_p": 0.95, "min_p": 0.0, "seed": 0,
  "presence_penalty": 1.5, "repeat_penalty": 1.0,
  "repeat_last_n": 4096, "penalize_prompt": false
}

Use repeat_penalty: 1.05 for the distilled row.

How this ships

The unslothai/llama.cpp prebuilt is upstream ggml-org at an aged b#### tag plus the pins in scripts/unsloth/pr-set.json, merged in order. There is no fork carry: if upstream takes an equivalent change, this pin gets deleted. The pin is added in a separate pr-set PR.

…y history

With penalize_prompt = false (request field, or --no-penalize-prompt for the
server default) the slot sampler is not fed the prompt tokens, so the repeat,
presence, frequency and DRY penalties only see generated tokens and the
repeat_last_n / dry_penalty_last_n windows count generated tokens only.
Grammar and reasoning budget never consumed prompt tokens, so nothing else
changes. Default true keeps the current behaviour.
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-18T15:17:15.550541Z 644ca7d Manual request
🔒 Security Review ✅ Completed 2026-10-18T15:19:23.073001Z 644ca7d 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.

@danielhanchen
danielhanchen changed the base branch from master to base/upstream-ceefd16da October 17, 2026 22:12

@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: 4f26c61748

ℹ️ 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 thread tools/server/server-context.cpp Outdated
Comment on lines +429 to +430
// prompt tokens feed only the penalty and DRY history here (grammar and reasoning budget skip
// non-generated tokens), so penalize_prompt = false starts that history at the first generated token

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep the comment sentence on one line

Join this comment instead of splitting one sentence across two lines; the repository explicitly prohibits mid-sentence line wrapping, so the current formatting violates the required code-comment convention.

AGENTS.md reference: AGENTS.md:L84-L84

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.

Fixed in 644ca7d: this comment and the one in test_completion.py are now single lines.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 644ca7d817

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

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 644ca7d817

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

danielhanchen added a commit that referenced this pull request Oct 18, 2026
… upstream (#284)

* pr-set: pin server penalize_prompt (#283), add its feature check

penalize_prompt = false keeps prompt tokens out of the repeat, presence,
frequency and DRY history in llama-server, which the FLUX.3 prompt upsampler
needs to match its reference sampling. feature_matrix.py gets a
penalize-prompt probe: a synthetic llama GGUF from test-llama-archs -o, a
context whose greedy next token is already in it, and a presence penalty
that must move that token by default and must not with the field false.
It is deferred when the build has no llama-server (the CPU gate).

* pr-set: drop ggml-org#30670, Beam is in the base since b11712

Upstream squash-merged it as 01fc3aa, so the pin no longer merges onto any
tag from b11712 on (REFUSED in common/parsers and src/llama-arch*, the
2026-10-17 nightly failure). pin_contract already reports 513/513 of its
lines in the base. The beam feature check stays, owned by the base.

* feature_matrix: a --gpu run without llama-server is unproven, not deferred

Only the CPU gate builds without llama-server; a full build that lacks it has not
demonstrated the penalize_prompt pin.

* pr-set: repin #283 to its head (comment-only change)
danielhanchen added a commit to unslothai/unsloth that referenced this pull request Oct 18, 2026
… sidecar (#14137)

Follows #13933 (FLUX.3 Image Klein, merged).

## Why

FLUX.3 Image Klein is trained on long, explicit captions. Sent a short
prompt as typed, it often draws broken bodies on unusual poses
(backflips, handstands, tangled arms) and generic scenes. BFL ships a
prompt upsampler for exactly this
(`black-forest-labs/flux-3-image-klein-pup`, a Qwen3.5-9B fine-tune,
Apache-2.0), and its model card says FLUX.3 "is not meant to run without
a prompt upsampler in front of it". ComfyUI's official FLUX.3 templates
run it by default. Studio currently drops that step and encodes the
prompt as typed.

Same 16 prompts, same seeds and reference noise, 32 images per arm:

| Arm | Broken bodies |
|---|---|
| distilled, prompt as typed | 3 (backflip on both seeds, one handstand)
|
| distilled, upsampled caption | 0 |
| base (50 steps), prompt as typed | 4 (headless handstand, tangled
arms, two odd violin grips) |
| base (50 steps), upsampled caption | 1 (odd violin angle) |

As typed, "a gymnast doing a backflip" mostly renders a back-bend or
walkover; upsampled, it renders a tucked backflip. Ordinary scenes
(groups, walking, dinner) were already fine and stay fine.

## What this adds

**Backend** (`core/inference/flux3_prompt_upsampler.py`)
- The upsampler runs as a llama.cpp `llama-server` sidecar, modelled on
the dictation (mtmd STT) sidecar: started on demand on an ephemeral
loopback port, five minute keep-alive, unloaded early when VRAM is
tight, and stopped at every training start, llama.cpp update, image
unload and GPU handover to chat or video. Stop during a cold start
cancels the server start. On a multi-account host it never starts beside
another account's run. CUDA, ROCm, Metal and CPU all work through the
same binary Studio already installs.
- Weights come only from `unsloth/flux-3-image-klein-pup-GGUF` (Q4_K_M
plus `mmproj-F16.gguf` for edits, 6.5 GB).
`UNSLOTH_FLUX3_UPSAMPLER_GGUF` / `_MMPROJ` point at local files instead.
- Prompts and sampling follow the ComfyUI FLUX.3 templates: BFL's `t2i`
/ `i2i` system prompts verbatim (sha256 pinned in a test, identical to
diffusers' `SYSTEM_PROMPTS`), greedy decoding, thinking off, 3584 max
tokens, presence penalty 1.5 for text-to-image and 0 for edits, repeat
penalty 1.05 for distilled and 1.0 for base. Edits send the reference
images (prepared as diffusers' `prepare_reference`) and the edit
scaffold.
- When the server supports `penalize_prompt` (unslothai/llama.cpp#283),
the penalties cover only generated tokens over the whole caption, which
is what ComfyUI and BFL's reference do. Against an exact-semantics
reference on 8 prompts this moves word similarity from 0.49 to 0.69 (the
cross-runtime floor is about 0.7 to 0.8). Older servers keep their
default window.
- `DiffusionGenerateRequest.enhance_prompt` (default: on for FLUX.3
Klein, ignored elsewhere). Records keep `prompt` as typed and add
`enhanced_prompt` (the caption encoded) and `prompt_enhancement`
(`applied` / `off` / `unavailable` / `failed`). Generation never fails
because of the upsampler: a missing download, missing binary or server
error falls back to the prompt as typed, and a multi-GB download is
never started implicitly.
- Routes: `GET /api/inference/images/prompt-upsampler/status`, `POST
.../download`, `POST .../cancel`, `POST .../preview`. `/images/status`
gains `supports_prompt_upsampler` and `prompt_upsampler_default`;
generate-progress reports an `enhance` phase.
- Captions are cached per (prompt, variant, references), so a batch
upsamples each distinct prompt once and a repeat costs nothing.
- Fix in the shared sidecar download progress: huggingface_hub 1.18+
writes `<etag>.<8 hex>.incomplete`, which the byte counter missed, so
the bar sat at 0% until the end. This also fixes the dictation model
download bar.

**Frontend** (Images page)
- "Enhance prompt" toggle under the prompt for FLUX.3 families only, on
by default, remembered per family.
- Download notice with size, progress and cancel when the upsampler is
missing.
- Preview: shows the caption with Copy and "Use as prompt" (puts the
caption in the prompt and turns the toggle off, so it can be edited).
- The Recipe popover shows the enhanced prompt and offers "Restore with
the enhanced prompt", which reproduces the image exactly.

## Evidence

End to end on a fresh install from this branch (B200,
`unsloth/flux-3-image-klein-FP8`):

| Check | Result |
|---|---|
| status before download | `downloaded: false`; generate falls back,
`prompt_enhancement: "unavailable"` |
| download through the route | 6,547,275,232 bytes in 44 s into the HF
cache |
| preview | 231-word caption, 12.2 s cold (includes llama-server start),
4.8 s for a new prompt warm |
| generate | 1.0 to 1.5 s warm without enhancement, about 8 s with a new
caption, 1.2 s with a cached one |
| restore (caption as prompt, enhance off, same seed) | max abs pixel
difference 0 |
| edit (reference workflow, "make it night time") | caption describes
the actual source image |
| VRAM | about 23 GB combined peak (DiT 13 to 16 GB, sidecar 6.2 GB
text-only, 7.5 GB with the vision projector) |
| non-FLUX.3 family (Z-Image Turbo) | no toggle; `enhance_prompt: true`
passes through untouched |

GGUF fidelity (llama.cpp `b11696-mix-7baeb9a`): the BF16 GGUF matches
transformers' chat template token for token and only diverges at
near-tie tokens (probability gaps 0.0015 to 0.041). Captions from Q4_K_M
and Q8_0 rendered the hard poses with no anatomy difference from the
BF16 captions.

Tests: `tests/test_flux3_prompt_upsampler.py` 73 passed; with the
training VRAM, multi-model serving, managed engine, STT, GPU selection,
GPU arbiter and diffusion route suites 777 passed. Frontend
`tests/image-*.test.ts` 144 passed, `tsc` clean.

## Not covered

- Clicking Download in the UI (the download was driven through the
route), cancel mid-download, the base variant end to end, edits with
several reference images, and the unload-when-tight path (the card never
ran tight).
- macOS, Windows and AMD were not run; the sidecar uses the same
llama-server binary and launch helpers as dictation.
- Exact ComfyUI caption parity needs the `penalize_prompt` pin in the
llama.cpp prebuilt; until then captions are valid but not word-for-word
ComfyUI's.

## UI

Images composer with `unsloth/flux-3-image-klein-FP8` loaded, before
(`studio-flux3-klein`, this PR's base) and after, with Preview clicked.
After this PR there is an Enhance prompt switch (on by default for
FLUX.3) and Preview opens the caption the upsampler wrote (237 words
here) with Copy and Use as prompt. `GET
/api/inference/images/prompt-upsampler/status` returns 404 before and
200 after.

![Images composer before and after: Enhance prompt switch and the
enhanced
caption](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14137/pr14137_composer_q-df214a7289c6.png)

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
@danielhanchen
danielhanchen changed the base branch from base/upstream-ceefd16da to master October 25, 2026 23:31
@danielhanchen danielhanchen self-assigned this Oct 27, 2026

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant