Skip to content

feat(sampling): apply no_repeat_ngram_size and ngram_window instead of dropping them - #4510

Merged
jundot merged 2 commits into
jundot:mainfrom
Cassian433:no-repeat-ngram
Oct 14, 2026
Merged

jundot merged 2 commits into
jundot:mainfrom
Cassian433:no-repeat-ngram

Conversation

@Cassian433

Copy link
Copy Markdown
Contributor

Summary

no_repeat_ngram_size and ngram_window on /v1/chat/completions were accepted and then thrown away. ChatCompletionRequest and CompletionRequest in omlx/api/openai_models.py didn't declare them, so pydantic drops them, and the per-request processor list in Scheduler._build_sampler_and_processors had nothing that bans n-grams. On main (f3ad34d) with mlx-community/Unlimited-OCR-4bit, every page I tried came back byte-identical with no knob, with no_repeat_ngram_size: 35, and with 35 plus ngram_window: 128. That's what #3741 shows for the bf16 model.

This adds make_no_repeat_ngram_processor(ngram_size, window) to omlx/utils/sampling.py. It does what SlidingWindowNoRepeatNgramProcessor in Baidu's modeling_unlimitedocr.py does: take the last n-1 tokens as the tail, look at every n-gram that starts inside the last window tokens, and ban the last token of each one whose first n-1 tokens match the tail. With no window it searches the whole history, which is transformers' no_repeat_ngram_size. The history is what mlx-lm passes every processor, prompt plus generated tokens. That's the same as HF's input_ids for a decoder-only model and the same context the repetition penalty reads. The reference also takes an optional whitelist_token_ids, but Baidu's pipeline never passes one, so I left it out.

Nothing is read back from the GPU. The n-gram prefixes are an as_strided view over the window, one compare against the tail finds the matches, and their last tokens are scattered into a vocab mask, the same unfold-and-scatter transformers 5.17 uses in NoRepeatNGramLogitsProcessor. Unmatched rows go to a spare slot, so there is no boolean indexing. Only shapes are read on the host, which keeps the one-step lookahead in GenerationBatch._step intact. It is a pure function of the history, so the Lightning MTP path can run it on draft prefixes without a snapshot.

The fields follow #3012's route for repetition_context_size through the two OpenAI request models (both >= 0; a size of 0 is off, a window of 0 means the whole history, and a window shorter than the n-gram is a 422), the chat and both completion call sites in server.py, SamplingParams in the batched and VLM engines, and _build_sampler_and_processors, which only adds the processor when the size is set. /v1/responses and /v1/messages still drop both fields: ResponsesRequest keeps unknown keys untyped and MessagesRequest throws them away, so they need typed fields first, and #3741 is about chat completions.

On DFlash: dflash-mlx samples inside its own loop and has no logits processor hook, so a request that would run on the DFlash lane now gets a 400 from preflight_chat instead of having the field ignored. That's the explicit rejection you asked for on #3012. Requests that fall back to the batched or VLM engine (long context, images) still get the ban. Distributed inference and the diffusion lane reject it in preflight too: the ranks run mlx-lm's server, and the denoising loop takes no processors. In distributed.py the check sits next to plain ValueErrors, but those come back as a 500 that says "Internal server error", so I used InvalidRequestError to get a 400 naming the field.

Fixes #3741

#4221 (DRY) is a different tool: a soft penalty that grows with the match length. This is the hard ban the Unlimited-OCR authors ship. Both touch the same plumbing, so whichever lands second needs a rebase.

Validation

Apple M5, 24 GB, macOS 26.6.2, Python 3.12.15, no native kernels. One venv with the dev extras; main and the branch ran from separate checkouts on PYTHONPATH, each as omlx serve --no-cache with its own --base-path, side by side for the speed runs.

Unlimited-OCR-4bit, prompt document parsing., temperature 0, max_tokens 1024, synthetic A4 pages:

page main, all three requests branch, no knob branch, 35 / 128
addressee line + page number 1024 tokens, length same bytes as main 81 tokens, stop
page number only 1024, length same bytes 111, stop
addressee line + signature rule 1024, length same bytes 40, stop
four short lines 385, stop same bytes same bytes

The 4-bit model loops inside a single line rather than line by line as in the issue, so distinct lines are 1/1 either way and I counted words instead. On main the first page is 14 - 14 - 14 ... for all 1024 tokens: 683 words, 2 distinct. With the ban it breaks off after about a dozen repeats, then emits both real detections, To: The Registrar, High Court and the page_number box for - 14 -. The window doesn't matter on these pages: 35 alone and 35/128 gave the same bytes.

One loop it can't stop: when four copies of the four-line page run as a batch, one row drifts into lines whose box coordinates change every time, so exact 35-grams rarely come back. The whole-history ban changed that row's text, but it still ran to 1024.

Requests without the knob are byte-identical to main at batch 1, for Qwen3.5-2B-MLX-8bit text and all four OCR pages. At batch 4 main isn't deterministic run to run either; my guess is that arrival order changes the batch. For OCR both sides produced the same four texts, seven times each. For text, main produced 7 different texts across 28 rows, and 27 of the 28 branch rows matched one of them.

Speed: with the main and branch servers up together and the arms rotated every round, end-to-end decode tok/s didn't move beyond the noise. This M5 throttles hard (OCR batch 1 drifted from about 210 to 125 tok/s over one run), so I also timed the processor next to an LM-head matmul and argmax at Unlimited-OCR's shape (hidden 1280, vocab 129280), alternating with and without it. With a synchronous eval, which overstates it, it adds 129 µs per step at window 128, 216 µs at window 1024, 254 µs over a whole 8k history and 378 µs over 32k. Building the graph takes 59 to 82 µs on the host.

Tests:

  • tests/test_sampling.py: the processor against a port of Baidu's processor on 800 random histories (n of 1, 2, 3 and 5, windows shorter and longer than the history, no window, int32 and uint32 ids), plus the window cases and a lazy TokenBuffer history.
  • tests/test_scheduler.py: a tiny llama through Scheduler.step(), greedy, two rows of different lengths. Without the knob the short row's 43 tokens hold 38 repeated trigrams. With no_repeat_ngram_size=3 they hold none, and the other row decodes the same tokens either way.
  • Request validation in test_openai_models.py, forwarding in test_server.py, test_batched_engine.py and test_vlm_engine.py, and the DFlash, distributed and diffusion rejections. One of them streams a chat request to a DFlash engine through TestClient and expects a 400 before the stream starts.

19 of the 22 new tests fail on main. The 3 that pass there are guards: chat requests that leave the knob unset or at 0 forward nothing, and DFlash's fallback engine gets the fields.

The eight touched test files pass, 1061 tests on the M5. After rebasing onto 64bf5d1 they pass on Linux too, 1063 tests against 1041 on main. I also ran the default suite on a Linux box with mlx-cpu 0.32.3: about 740 Metal-kernel and Playwright tests fail there on main too, and nothing new fails on the branch. The macOS run is CI's.

Not tested on hardware: DFlash, distributed and the diffusion lane (unit tests only), MTP decode with the knob on, streaming, the prefix cache (every server ran with --no-cache), and a real multi-page PDF with window 1024.

Checklist

  • I read CONTRIBUTING.md.
  • I understand every change in this PR and can explain it in review.
  • For UI or UX changes, I attached before and after screenshots.

Cassian433 and others added 2 commits October 13, 2026 15:50
…f dropping them

ChatCompletionRequest and CompletionRequest dropped both fields and the scheduler had no n-gram processor, so a request ran exactly as if they were unset. The processor follows Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor (window 0 is transformers' no_repeat_ngram_size) and is built from lazy MLX ops. DFlash's own lane, distributed inference and the diffusion lane reject the field instead of ignoring it.

@jundot jundot left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

#4508 removed DFlashEngine while this PR was open, so I pushed a merge commit that drops the DFlash changes. DFlash now runs inside the batched engines and applies logits processors, so the ban works there too and the 400 isn't needed. I tested it on Qwen3-4B with DFlash and Qwen3.6-35B-A3B with MTP. With the knob there were no repeated n-grams, and without it the output didn't change. LGTM, merging.

@jundot
jundot merged commit ec13b9e into jundot:main Oct 14, 2026
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.

no_repeat_ngram_size is accepted on /v1/chat/completions and then silently ignored

2 participants