Repository navigation
feat(sampling): apply no_repeat_ngram_size and ngram_window instead of dropping them - #4510
Merged
Merged
Conversation
…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
approved these changes
Oct 14, 2026
jundot
left a comment
Owner
There was a problem hiding this comment.
#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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
no_repeat_ngram_sizeandngram_windowon/v1/chat/completionswere accepted and then thrown away.ChatCompletionRequestandCompletionRequestinomlx/api/openai_models.pydidn't declare them, so pydantic drops them, and the per-request processor list inScheduler._build_sampler_and_processorshad 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, withno_repeat_ngram_size: 35, and with 35 plusngram_window: 128. That's what #3741 shows for the bf16 model.This adds
make_no_repeat_ngram_processor(ngram_size, window)toomlx/utils/sampling.py. It does whatSlidingWindowNoRepeatNgramProcessorin Baidu'smodeling_unlimitedocr.pydoes: take the last n-1 tokens as the tail, look at every n-gram that starts inside the lastwindowtokens, 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'sinput_idsfor a decoder-only model and the same context the repetition penalty reads. The reference also takes an optionalwhitelist_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_stridedview 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 inNoRepeatNGramLogitsProcessor. 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 inGenerationBatch._stepintact. 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_sizethrough 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 inserver.py,SamplingParamsin the batched and VLM engines, and_build_sampler_and_processors, which only adds the processor when the size is set./v1/responsesand/v1/messagesstill drop both fields:ResponsesRequestkeeps unknown keys untyped andMessagesRequestthrows 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_chatinstead 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. Indistributed.pythe check sits next to plainValueErrors, but those come back as a 500 that says "Internal server error", so I usedInvalidRequestErrorto 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 asomlx serve --no-cachewith its own--base-path, side by side for the speed runs.Unlimited-OCR-4bit, prompt
document parsing., temperature 0,max_tokens1024, synthetic A4 pages:lengthstoplengthstoplengthstopstopThe 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 Courtand thepage_numberbox 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 lazyTokenBufferhistory.tests/test_scheduler.py: a tiny llama throughScheduler.step(), greedy, two rows of different lengths. Without the knob the short row's 43 tokens hold 38 repeated trigrams. Withno_repeat_ngram_size=3they hold none, and the other row decodes the same tokens either way.test_openai_models.py, forwarding intest_server.py,test_batched_engine.pyandtest_vlm_engine.py, and the DFlash, distributed and diffusion rejections. One of them streams a chat request to a DFlash engine throughTestClientand 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