Skip to content

Add custom LogitProcessor injection to GenerateParameters / ChatSession - #401

Merged
davidkoski merged 5 commits into
ml-explore:mainfrom
xocialize:logit-processor-injection
Aug 4, 2026
Merged

davidkoski merged 5 commits into
ml-explore:mainfrom
xocialize:logit-processor-injection

Conversation

@xocialize

Copy link
Copy Markdown
Contributor

Motivation

TokenIterator already exposes a direct init(input:model:cache:processor:sampler:prefillStepSize:maxTokens:) for callers who want to supply their own LogitProcessor. But GenerateParameters.processor() only ever produces the built-in penalty processors, and ChatSession (like the other high-level paths) drives generation exclusively through the parameters-based initializers — so a custom processor (e.g. grammar-constrained / structured decoding) cannot ride ChatSession at all.

In practice this forces downstream packages to bypass ChatSession for structured-output requests and re-implement the prompt-formatting + iterator plumbing just to inject one processor. We carry exactly that bypass in two production packages and would like to retire it.

API

var parameters = GenerateParameters(temperature: 0)
parameters.customLogitProcessorFactory = { GrammarProcessor(grammar: grammar) }

// rides ChatSession (and every other parameters-driven path) unchanged
let session = ChatSession(model, generateParameters: parameters)
  • GenerateParameters.customLogitProcessorFactory: (@Sendable () -> any LogitProcessor)? — new stored property (plus a defaulted trailing init parameter).
  • GenerateParameters.processor() composes the factory's product after the built-in PenaltyProcessor.
  • ChainedLogitProcessor — small public processor that applies multiple LogitProcessors in order; used for the composition and available for users combining several custom processors.

Design notes

  • Factory, not a stored processor. LogitProcessor is stateful (didSample), so each generation needs a fresh instance — important for multi-turn ChatSession where the same GenerateParameters drives many generations. A @Sendable closure also keeps GenerateParameters: Sendable intact, which a stored any LogitProcessor would not.
  • No plumbing changes needed. TokenIterator, SpeculativeTokenIterator, and MTPSpeculativeTokenIterator all build their processor via parameters.processor(), so ChatSession, generate(...), and the speculative paths pick this up for free.
  • Custom-after-penalty ordering matches Python mlx-lm, where user logits_processors append after the ones from make_logits_processors.
  • Purely additive — behavior is unchanged when the factory is nil (processor() returns exactly what it did before).

Testing

New tests, all passing via xcodebuild test -scheme mlx-swift-lm-Package:

  • SampleTests.testGenerateParametersCustomLogitProcessorFactory — nil/custom-only/chained composition of processor().
  • SampleTests.testGenerateParametersAppliesCustomProcessorAfterPenalties — numeric check that penalties apply before the custom processor.
  • SampleTests.testChainedLogitProcessorForwardsPromptAndDidSample — prompt/didSample forwarding through the chain.
  • ChatSessionTests.testChatSessionUsesCustomLogitProcessor — end-to-end: a masking processor on a tiny randomly-initialized Gemma3 (existing test pattern, no downloads) forces every generated token.

🤖 Generated with Claude Code

GenerateParameters.processor() only ever produced the built-in penalty
processors, so a custom LogitProcessor (e.g. grammar-constrained
decoding) could not ride ChatSession or any other parameters-driven
generation path -- only the direct TokenIterator
init(input:model:cache:processor:sampler:...) supported it.

Add GenerateParameters.customLogitProcessorFactory, a @sendable factory
closure whose product processor() composes after the PenaltyProcessor
via a new public ChainedLogitProcessor. A factory (rather than a stored
processor) keeps GenerateParameters Sendable and gives each generation a
fresh processor instance, since processors are stateful.

Because TokenIterator, SpeculativeTokenIterator and
MTPSpeculativeTokenIterator all build their processor from
parameters.processor(), ChatSession and the speculative paths pick this
up with no further plumbing. Purely additive: processor() is unchanged
when the factory is nil.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Comment thread Libraries/MLXLMCommon/Evaluate.swift Outdated
prefillStepSize: Int = 512,
seed: UInt64? = nil
seed: UInt64? = nil,
customLogitProcessorFactory: (@Sendable () -> any LogitProcessor)? = nil

@aleroot aleroot Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This constructor got telescopic, but more than that I think that placing a behavioral factory closure inside a pure data configuration struct introduces a leak. GenerateParameters is a value type meant strictly for static generation metrics (temperature, tokens, etc.). A LogitProcessor controls execution behavior. Mixing the two is not a great idea...
GenerateParameters should remain strictly focused on configuration parameters. A logitProcessorProvider should be introduced in the ChatSession, I believe...

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Even better would be having something like this in the futue:

public struct GenerationComponents: Sendable {
    public var logitProcessorProvider: (@Sendable () -> any LogitProcessor)?
    public var stoppingCriteriaProvider: (@Sendable () -> any StoppingCriteria)?
    public var onTokenSampled: (@Sendable (Int) -> Void)?
    }

Then the session:

public class ChatSession {
    private let model: any LanguageModel
    private let parameters: GenerateParameters
    private let components: GenerationComponents
public init(
        _ model: any LanguageModel,
        parameters: GenerateParameters = .init(),
        components: GenerationComponents = .init()
    ) {
        self.model = model
        self.parameters = parameters
        self.components = components
    }
    }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good point, and I agree GenerationComponents is the cleaner long-term shape — behavioral concerns (logit processor, stopping criteria, per-token callback) do belong together and separate from static config.

The reason it currently lives on GenerateParameters is that processor() is the single composition point every generation path builds from — TokenIterator, SpeculativeTokenIterator, MTPSpeculativeTokenIterator, and therefore generate(...), ChatSession, and the speculative paths all pick it up with zero plumbing. That's specifically the bypass we're trying to retire downstream: a custom (e.g. grammar-constrained) processor can currently only be injected via the direct TokenIterator.init(...processor:...), so structured-output callers have to re-implement the prompt-formatting + iterator wiring instead of riding ChatSession.

A GenerationComponents on ChatSession is nicer conceptually, but as sketched it only reaches ChatSession — generate(...) and the speculative iterators still wouldn't see the processor, since they compose off parameters.processor(). To keep parity we'd need to thread components through those iterator inits too, which is a larger, more invasive change.

(One small note on the "leak" framing: the factory is @Sendable () -> any LogitProcessor, so it keeps GenerateParameters: Sendable intact — the concern is separation of concerns rather than a Sendability break.)

I'm happy to go the GenerationComponents route if that's the preferred direction — but since the additive version here is fully behavior-preserving (processor() is unchanged when the factory is nil) and unblocks the downstream bypass today, could we keep this PR minimal and track GenerationComponents (with the iterator-path threading) as a follow-up refactor? Glad to take whichever scope the maintainers prefer.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

parameters.processor() is currently the common composition point for the parameter-driven generation paths, and I understand why adding the factory there gives broad coverage with a small diff. My concern is that this makes an implementation convenience part of the long-term API contract.

This is ultimately a call for @davidkoski to make but I think the right fix is to introduce the separate concept now, even if the first version only carries a logit processor factory:

public struct GenerationComponents: Sendable {
    public var logitProcessorFactory: (@Sendable () -> any LogitProcessor)?

    public init(
        logitProcessorFactory: (@Sendable () -> any LogitProcessor)? = nil
    ) {
        self.logitProcessorFactory = logitProcessorFactory
    }
}

Then thread that through the generation entry points that need parity:

TokenIterator(..., parameters: parameters, components: components)
SpeculativeTokenIterator(..., parameters: parameters, components: components)
MTPSpeculativeTokenIterator(..., parameters: parameters, components: components)
ChatSession(..., generateParameters: parameters, generationComponents: components)

The composition can still happen in one place, just not by storing behavioral state inside GenerateParameters:

let processor = compose(
    parameters.processor(),
    components.logitProcessorFactory?()
)

I know this is more work than the current patch, but I think it is the better direction for future maintainability and API clarity. If we add the factory to GenerateParameters now, we are accepting that shape as public API; moving it later would become a breaking change.

Sorry to be an intruder into your pull request, but this looks like an API-impacting change, and GenerateParameters has already grown quite a bit.
Refactoring now would be something easier than later, once you change the public API then it becomes a breaking change ...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That's a fair point and it changes my mind — threading components alongside parameters into the iterator/session entry points gives the same broad coverage without storing behavioral state in GenerateParameters, so my "single composition point" concern is fully addressed by your sketch. And the breaking-change argument is the decisive one: once the factory ships on GenerateParameters it's public API, and moving it later is a source break, whereas the split is essentially free right now. No intrusion at all — this is exactly the kind of API-shape call worth making before release.

So I'm on board with GenerationComponents. Before I rework the PR I'd just like a steer from @davidkoski on the shape, since it touches public API on several entry points:

  • naming (GenerationComponents, components: / generationComponents: labels)
  • whether the free generate(...) functions should also gain a components: parameter, or whether it's scoped to the iterators + ChatSession
  • default-arg placement on the existing entry points

Happy to do the full threading (TokenIterator / SpeculativeTokenIterator / MTPSpeculativeTokenIterator / ChatSession, with compose(parameters.processor(), components.logitProcessorFactory?()) as the one composition point) once the preferred shape is confirmed — I'd rather build it once to spec than guess. @davidkoski, any preference on the above?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks @davidkoski — this all makes sense, and I agree with the framing: GenerateParameters is the factory for pre-configured processor/sampler, and the only real gap is reach — a custom processor can only be injected through the low-level TokenIterator.init, so it can't ride ChatSession (or the speculative paths). Making GenerationComponents the first-class home for behavioral concerns is the right move, and I think TokenLoopHandler belongs there too — it's "how tokens are generated," same as a custom processor/sampler, so having GenerationComponents optionally vend it fits cleanly.

On the one fork I'd offer an opinion: I'd lean compose rather than make GenerateParameters a protocol. Turning a concrete, widely-used value type into a protocol is a source break for anyone constructing or copying it, pushes callers toward any GenerationComponents existentials on a hot path, and gives up the value semantics that make GenerateParameters easy to pass around and mutate. Concretely:

  • GenerateParameters stays the value type for generation config (temperature, penalties, seed) — it already knows how to vend the built-in processor/sampler.
  • GenerationComponents is a small Sendable struct for behavior: logitProcessorFactory, samplerFactory, stoppingCriteria, and (optionally) a TokenLoopHandler factory. Factories, not instances, so each generation gets a fresh stateful object and the struct stays Sendable.
  • The composition point stays single: compose(parameters.processor(), components.logitProcessorFactory?()), threaded alongside parameters into TokenIterator / the speculative iterators / ChatSession.

That's non-breaking and keeps "both," but as composition rather than a type hierarchy — which I think reads cleaner than a protocol for value types. You're right that maxTokens/prefillStepSize are really iteration knobs rather than generation; I'd keep them where they are for now and treat a generation-vs-iteration split (and ChatParameters to tame the ChatSession init proliferation, and the let/Sendable-ChatSession idea) as follow-ups so this PR can land minimal and additive.

If you'd rather go the protocol-replacement route despite the above, I'm happy to build that instead — I just didn't want to guess. We opened this, so we're glad to do the work either way: tell me which shape you want (compose vs protocol-replace, and whether TokenLoopHandler should be in scope for v1) and I'll rework the PR to match.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It may be fine if maxTokens and friends are in the same place with the rest -- they do seem separate, but if we scope this to "token generation" then they would clearly fit in (I think).

So are you thinking that GenerateParameters could produce a GenerationComponents?

I agree that source breaking wouldn't be a good path. GenerateParameters should not become a protocol, but it might implement the new protocol. I don't think existentials are too much a problem here: dynamic method dispatch to produce these values is insignificant compared to the metal kernel dispatch to actually produce a single token. That said, simple structs as you said may be the way to go.

I think we need something that can be passed down through ChatSession and generate() that can encapsulate all these pieces. We need a reasonable default implementation for temperature (like GenerateParameters). This could either produce the value or be the value.

I think folding TokenLoopHandler in would be nice but it would make it generic as it has an associated type. That might complicate things and make it necessary to keep them separate. Unless they need to be coupled to actually work.

I am not tied to any specific implementation -- protocols were what came to mind, but they are not the only way. I agree we can do the ChatSession work as a followup.

I think my ideas are still a bit hand-wavy. I can imagine the general shape but I think it needs to be tried to see how it all fits. I think we need some code to look at to decide. If you want to try your approach, go for it! If I get a chance I will try playing around a bit with this too and can post notes or a draft PR so we can see the diffs.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Sounds good — I'll take a first cut so we have a concrete diff to react to rather than staying hand-wavy. Plan for v1, matching what we landed on:

  • Keep GenerateParameters concrete/non-breaking (it stays the default and still vends .processor()/.sampler()).
  • Add a small GenerationComponents: Sendable struct of behavioral factories — logitProcessorFactory to start, with room for samplerFactory/stoppingCriteria — defaulting to empty so behavior is identical when unused.
  • Thread an optional components: through TokenIterator / the two speculative iterators / ChatSession, with a single composition point compose(parameters.processor(), components.logitProcessorFactory?()).
  • Leave TokenLoopHandler out of v1 (the associated type makes it generic, as you noted) and treat the ChatSession init cleanup / ChatParameters as the follow-up.

I'll push a commit to the PR branch so you can see how it actually fits. Please still poke at it / post notes or a draft if you get the chance — happy to converge on whichever diff reads best.

@aleroot aleroot Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Have you completed, the changes ?
I would need to add the thinking budget, for example:

public struct ThinkingBudgetConfiguration: Sendable, Equatable {
    public let maximumTokenCount: Int
    public let closingPrefix: String

    public init(
        maximumTokenCount: Int,
        closingPrefix: String = "\n"
    ) throws
}

and then plug that in like :

var components = GenerationComponents()

components = try components.applyingThinkingBudget(
    ThinkingBudgetConfiguration(maximumTokenCount: 512),
    reasoning: reasoningConfig,
    tokenizer: tokenizer
)

let session = ChatSession(
    model,
    generateParameters: parameters,
    components: components
)

If you can complete and merge this pull request then I will open mine. Thanks.
@davidkoski what do you think of the Thinking budget ?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

ThinkingBudget sounds interesting -- so it is a LogitProcessor that constrains the tokens to finish thinking as it gets to the token count?

Does this need a specific applyingThinkingBudget()? IdeallyGenerationComponents should be able to compose these generically. I guess we can answer these questions in a followup PR!

xocialize and others added 2 commits July 14, 2026 10:57
…rationComponents

Rework of the custom-LogitProcessor-injection PR per maintainer feedback:
keep GenerateParameters a pure value config type and carry behavioral
hooks in a separate struct.

- Remove GenerateParameters.customLogitProcessorFactory (stored property +
  init param). GenerateParameters.processor() returns to composing only the
  built-in PenaltyProcessor (pre-PR behavior).
- Add GenerationComponents: a small Sendable struct holding the optional
  @sendable logitProcessorFactory. Its logitProcessor(parameters:) is the
  single composition point -- it invokes the factory fresh (so each
  generation gets a new stateful processor, no leakage across turns) and
  chains penalty-then-custom via ChainedLogitProcessor, matching Python
  mlx-lm ordering.
- Keep ChainedLogitProcessor public.
- Thread an additive `components: GenerationComponents = .init()` through
  TokenIterator, SpeculativeTokenIterator, MTPSpeculativeTokenIterator,
  ChatSession, and the parameters-driven generate/generateTokens free
  functions. Every site that built its processor via parameters.processor()
  now uses components.logitProcessor(parameters:). Fully non-breaking:
  empty components reproduce prior behavior.
- Tests: rework the factory tests onto GenerationComponents; add fresh-
  instance-per-call/per-generation guards, an empty-components regression
  guard, and an end-to-end ChatSession masking-processor test.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…ection

# Conflicts:
#	Libraries/MLXLMCommon/ChatSession.swift
#	Libraries/MLXLMCommon/Evaluate.swift
@xocialize

Copy link
Copy Markdown
Contributor Author

@aleroot Yes — the rework is complete and pushed (2026-07-14). The branch is up to date with main and mergeable; there's nothing outstanding on my side.

What's on it now, per the direction you and @davidkoski landed on:

  • GenerationComponents: Sendable — behavioral hooks kept out of GenerateParameters, which is back to being a pure value type (its processor() is penalty-only again, as before this PR).
  • A single composition point, components.logitProcessor(parameters:), composing penalty-then-custom.
  • components: threaded (additive + defaulted, so non-breaking) through TokenIterator, SpeculativeTokenIterator, MTPSpeculativeTokenIterator, all six ChatSession inits, and the non-deprecated generate(...) free functions.
  • Tests covering the ChatSession path end-to-end, per-generation factory freshness (stateful processors must not leak across turns), and an empty-components regression guard.

It's waiting on two maintainer-side things, not on code: @davidkoski's call on the broader shape (he raised possibly folding this into a protocol and/or adding ChatParameters, and mentioned he might prototype it), and CI approval — the run has been sitting at action_required since the push, since fork PRs need a maintainer to start the workflow.

On the thinking budget: that's a good fit, and your snippet already reads against the current API exactly as-is (GenerationComponents() → ChatSession(model, generateParameters:, components:)). Worth noting v1 deliberately ships only logitProcessorFactory — but I think a thinking budget lands cleanly on that alone: forcing closingPrefix once the thinking-token budget is spent is logit processing, and the per-generation factory semantics give you a fresh counter each turn, which is exactly what you'd want for a budget in a multi-turn session. applyingThinkingBudget returning a modified copy also fits the value-type design nicely.

If a budget ends up wanting a stopping-criteria or sampler hook too, the struct was built to grow — those were left out of v1 only to keep the first change minimal, and your use case is a reasonable argument for adding them.

@aleroot

aleroot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

@xocialize ok, when this gets merged, I will then prepare the work for the thinking budget. thanks .

/// components.logitProcessorFactory = { GrammarProcessor(grammar: grammar) }
/// let session = ChatSession(model, components: components)
/// ```
public struct GenerationComponents: Sendable {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This isn't really new to this PR, but #508 -- it makes it easy :-)

/// invoked once per generation so each generation gets a fresh instance and
/// state cannot leak across generations. A `@Sendable` closure also keeps
/// `GenerationComponents` `Sendable`.
public var logitProcessorFactory: (@Sendable () -> any LogitProcessor)?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We may want the same for LogitSampler but now we have the mechanism to do it.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good, thank you!

xocialize and others added 2 commits August 3, 2026 15:01
This PR added a `components:` parameter (and main earlier added `state:`)
to the TokenIterator initializer and the free generate/generateTokens
functions, changing their symbol signatures. DocC symbol links elsewhere
still referenced the old parameter-label lists, so the
`Verify documentation` CI step (`swift package generate-documentation
--warnings-as-errors`) failed to resolve them. Update each link to the
current declaration's exact label list:

- generate(input:cache:parameters:context:wiredMemoryTicket:tools:)
  -> generate(input:cache:parameters:context:components:wiredMemoryTicket:tools:)
  (Evaluate.swift x7, ModelFactory.swift x1)
- generate(...draftModel:draftCache:numDraftTokens:wiredMemoryTicket:)
  -> generate(...draftModel:draftCache:numDraftTokens:components:wiredMemoryTicket:)
- generateTokens(...draftModel:draftCache:numDraftTokens:wiredMemoryTicket:)
  -> generateTokens(...draftModel:draftCache:numDraftTokens:components:wiredMemoryTicket:)
- init(input:model:cache:state:parameters:)
  -> init(input:model:cache:state:parameters:components:)

Verified with scripts/verify-docs.sh's doc build: MLXLMCommon and MLXLLM
generate documentation clean under --warnings-as-errors. swift build passes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@davidkoski
davidkoski merged commit 26f3a48 into ml-explore:main Aug 4, 2026
2 checks passed
jyauxi added a commit to jyauxi/mlx-swift-lm that referenced this pull request Aug 5, 2026
…ateParameters

Follow-up to ml-explore#401 landing, as agreed in review: GenerateParameters grows no
new fields for the sliding-window no-repeat n-gram guard.

- Remove noRepeatNgramSize / noRepeatNgramWindowSize /
  noRepeatNgramWhitelistTokenIds from GenerateParameters and revert
  GenerateParameters.processor() to upstream; Evaluate.swift now matches
  upstream main byte-for-byte.
- Drop SequentialLogitProcessor — ml-explore#401's public ChainedLogitProcessor is the
  same composition.
- SlidingWindowNoRepeatNGramProcessor is unchanged and still opt-in; attach it
  through GenerationComponents(logitProcessorFactory:), which also gives each
  generation a fresh processor instance (no state leakage across turns).
- Update UnlimitedOCR docs and both READMEs to the components-based opt-in;
  rewrite the attachment tests against GenerationComponents/
  ChainedLogitProcessor.
kklimuk added a commit to kklimuk/mlx-swift-lm that referenced this pull request Aug 7, 2026
Three issues from @davidkoski's review.

GlmOcr had no unsupportedBatchContinuation guard, unlike Qwen35 and
Qwen3VL. missingState does not cover it: that guard fires when the anchor
is absent, this one when the anchor is present but cannot describe several
rows resuming at different positions. Without it a warm batched
continuation either trapped on getRopeIndex's batchSize precondition
(image path) or silently shared one row's anchor across the batch
(text path).

The promptCache: initializers did not forward `components:`. Every other
ChatSession initializer takes it; ml-explore#401 added the parameter and touched the
cache: initializers, so those picked it up on merge while ours — which the
docs recommend over cache: — silently could not accept a logit processor.

The speculation gate refused a warm main cache with no draft cache, which
is exactly the state reusedMainCacheWithoutDraft exists to repair by
rebuilding both caches from the full input. The gate returned before that
code could run, so speculation never resumed for the rest of a session.
Admit that case explicitly. The gate still refuses a warm cache with no
transcript to rebuild from (a restored snapshot), where the iterator would
throw on mismatched caches rather than fall back.

Tests: a warm batched GlmOcr continuation throws, and speculation resumes
on the text turn after a media turn. The restart test needs
PrefixPreservingTokenizer so turn 2 renders as an exact extension of turn
1 — with an ordinary tokenizer the session rebuilds from cold and never
reaches this path. Both tests were confirmed to fail without their fixes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
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.

3 participants