Skip to content

feat(sampling): add top-n-sigma logit filtering with a row-filter hook - #1479

Merged
inureyes merged 3 commits into
mainfrom
feature/issue-1375-top-n-sigma
Aug 28, 2026
Merged

inureyes merged 3 commits into
mainfrom
feature/issue-1375-top-n-sigma

Conversation

@inureyes

@inureyes inureyes commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds top-n-sigma logit filtering: a new SamplingConfig::top_n_sigma field (default 0.0, disabled) that keeps only the tokens whose raw logit lies within n standard deviations of the row maximum and masks the rest to -inf, plus the batch-safe row-filter hook (apply_row_filters) that #1377 (typical_p) and #1373 (p_less) will reuse. Because the filter thresholds logits rather than probabilities it is invariant to temperature, which is what makes it the standard "stable at high temperature" sampler.

Rust versus C++ placement

The filter is implemented entirely in Rust as a pre-filter ahead of the single ffi::fused_sample dispatch, not inside the C++ chain. It is row-wise, history-free and RNG-free, so it needs neither the RNG plumbing that pushed XTC into the C++ chain (#1379) nor a bridge signature change; it composes MLX graph ops (astype/isfinite/sum/sqrt/where) that lazily fuse into the same evaluation, and requests stay on the single-dispatch fused batch path. No cxx::bridge or MLX pin change.

What changed

  • src/lib/mlxcel-core/src/generate.rs: SamplingConfig::top_n_sigma (0.0 in Default and greedy()).
  • src/lib/mlxcel-core/src/sampling.rs: top_n_sigma_filter (float32 statistics over the finite entries of each row, so an f16 sum over a 150k vocabulary cannot overflow and -inf/NaN entries neither perturb the threshold nor come back); apply_row_filters hook pinning the order top_n_sigma -> p_less (#1373) -> typical_p (#1377), returning the input pointer unchanged (zero graph nodes) when disabled or greedy (temperature == 0.0 || top_k == 1) and treating non-positive or non-finite values as disabled so the b10621 -1.0 sentinel is inert; hook wired into preprocess_logits_for_sampling (after the history penalties, before the fused C++ temperature/top_k/top_p/min_p/XTC chain) and batched_fused_sample; FusedSampleParams gains top_n_sigma, populated in from_config and compared bitwise in matches; config_supports_fused_batch stays true for the filter, with the rationale documented.
  • src/server/batch/scheduler.rs: the pipelined lookahead prime (prime_lookahead_with_input) applies the same apply_row_filters before its fused_sample, so the pipelined decode path samples the identical distribution as the synchronous fused path.
  • src/server/batch/speculative_burst.rs: sampling_config_eq compares top_n_sigma, keeping rows with different values out of one shared batched speculative window.
  • Request plumbing (mirrors XTC: request-only, no server default): SamplingParams::top_n_sigma, RequestOptionOverrides::top_n_sigma resolved unwrap_or(0.0), ResolvedSamplingParams::top_n_sigma threaded through both build_sampling_config branches, validate_top_n_sigma (finite and >= 0.0, else 400 invalid_request_error) called on /v1/chat/completions, /v1/completions and /v1/responses (the responses translator forwards the field through its flattened SamplingParams clone).
  • src/distributed/kv_cache_serde/types.rs + serving_protocol.rs: SerializableSamplingState::top_n_sigma with #[serde(default)] so a frame from an older prefill node deserializes to the disabled baseline; round-trip and legacy-frame tests added.
  • CLI: --top-n-sigma (alias --top-nsigma) on SamplingOptions (used by mlxcel generate and the chat REPL via resolved_cli_sampling_params), rejected at parse time when negative or non-finite.
  • Docs: docs/python-client.md sampling-parameters paragraph.

Deliberate scope deviation: native /completion

The issue asks for a top_n_sigma field on NativeCompletionRequest. That field is NOT added here, deliberately: src/server/llama_compat_tests.rs enforces that a native_request_field manifest entry with no mlxcel claim must not be declared on the struct, and the field:top_n_sigma entry (with the --top-nsigma option entry) in compat/llama-server/b10621/sampling-and-grammar.json is owned by #1436 under the epic's shard-ownership rule, so the field and its manifest flip must land together in #1436, two issues later in this chain. No manifest shard is touched by this PR. The core semantics for that wiring are already in place: apply_row_filters treats the upstream -1.0 "disabled" sentinel as inert rather than a mask-everything threshold.

Numerical validation (Qwen3-4B-4bit, real checkpoint)

  • High-temperature stability: --temp 2.0 --top-n-sigma 1.0 --seed 1 produces fluent English; the identical command without the filter degenerates (the documented property of the filter). Outputs quoted in the test plan below.
  • Control arm: greedy output (--temp 0) is token-identical with and without --top-n-sigma 1.0, and the disabled value adds zero graph nodes (pointer-equality asserted in apply_row_filters_disabled_returns_input_pointer_unchanged), so every existing token stream stays byte-identical.

Review follow-up (second commit)

A review pass surfaced three MEDIUM findings, fixed in the second commit: (1) FusedSampleParams::from_config and the speculative-window sampling_config_eq now compare SamplingConfig::effective_top_n_sigma() (greedy / non-positive / non-finite normalize to 0.0), so greedy rows differing only in an inert top_n_sigma no longer fall off the fused batch, pipelined lookahead, or shared speculative window despite sampling identically; (2) the filter's mask fill now carries the original logits dtype, since MLX's where promotion was silently returning f32 for f16/bf16 logits (precision change in the fused chain plus a doubled [B, V] tensor while active), with the f16 test asserting the output dtype; (3) the row maximum is taken over the finite-masked row so a single NaN entry can no longer drive the threshold to NaN and collapse the row to -inf. Known LOW observations left as-is: the CLI value parser intentionally rejects the llama-server -1.0 sentinel at parse time (the native endpoint mapping in #1436 will accept it as disabled), filtered-out tokens serialize logprobs as null exactly like the existing top-k/min-p masking, and the drafter-internal greedy fused_sample call sites (DFlash round loop, MTP heads) bypass all samplers by design, affecting acceptance rate only, with rejection sampling staying self-consistent through sample_token_with_distribution.

Test plan

  • cargo test -p mlxcel-core --profile test-fast --features metal,accelerate --lib sampling::tests (includes the 12 new top-n-sigma tests: worked-example kept sets, row independence, -inf transparency, f16 152k-vocab overflow guard, greedy skip, fused-batch eligibility and bitwise matches, 64-row fused batch honoring the filter, Distribution-preserving speculative-decoding acceptance (chain speculative sampling) #902 distribution zero mass outside the kept set)
  • cargo test --profile test-fast --features metal,accelerate --lib top_n_sigma plus the request_options, build_sampling_config, sampling_config_eq, serving_protocol and route-validation filters on the root crate
  • cargo clippy -p mlxcel-core --lib --tests --features metal,accelerate -- -D warnings, cargo clippy --lib --tests --bins --features metal,accelerate -- -D warnings, cargo fmt --all -- --check
  • python3 scripts/ci/check_llama_compat_manifest.py (manifest untouched, still canonical), scripts/ci/check_cross_repo_refs.py, scripts/ci/check_kernel_dtype_keys.py
  • Real-checkpoint validation on models/mlx/qwen3-4b-4bit as above

Closes #1375

Add the top-n-sigma sampler (#1375): keep only tokens whose raw logit lies within n standard deviations of the row maximum, masking the rest to -inf. The filter thresholds logits rather than probabilities, so it is invariant to temperature and is the standard way to keep sampling stable at high temperature.

Core: `SamplingConfig::top_n_sigma` (default 0.0, disabled) and `top_n_sigma_filter` in mlxcel-core, computed in float32 over the finite entries of each row so an f16 sum over a 150k vocabulary cannot overflow and already-masked entries neither perturb the statistics nor come back. The new batch-safe hook `apply_row_filters` applies the enabled RNG-free row filters in the fixed order top_n_sigma -> p_less (#1373) -> typical_p (#1377), returns the input pointer unchanged (zero graph nodes) when disabled or greedy, and treats a non-positive or non-finite value as disabled so the b10621 `-1.0` sentinel is inert. It runs at the end of `preprocess_logits_for_sampling` (after the history penalties, before the fused C++ temperature/top_k/top_p/min_p/XTC chain), inside `batched_fused_sample`, and in the scheduler's pipelined lookahead prime, so the per-row, batched, and pipelined paths all sample the same distribution; `effective_token_distribution` and `sample_token_with_distribution` pick it up through the shared preprocess, keeping #902 speculative acceptance consistent.

Fused batch path: `FusedSampleParams` gains `top_n_sigma`, compared bitwise in `matches`, so uniform batches stay on the single-dispatch fused path and mixed values fall back per row; `config_supports_fused_batch` deliberately keeps returning true. `sampling_config_eq` in the speculative burst gate also compares the field so rows with different values never share one batched speculative window.

Server: `top_n_sigma` accepted on /v1/chat/completions, /v1/completions and /v1/responses (request-only, no server default, absent resolves to 0.0), validated by the new `validate_top_n_sigma` (finite and >= 0.0, else 400 invalid_request_error), threaded through `RequestOptionOverrides`, `ResolvedSamplingParams` and both `build_sampling_config` branches, and carried on the disaggregated wire struct with `#[serde(default)]` so an older prefill peer still deserializes. The native /completion spelling is deliberately NOT added here: the llama-compat gate requires the `field:top_n_sigma` manifest entry (owned by #1436) to flip in the same change that adds the field, so that pair lands together in #1436.

CLI: `--top-n-sigma` (alias `--top-nsigma`) on `mlxcel generate` and the chat REPL, rejected at parse time when negative or non-finite.

Validated with the new unit tests across sampling.rs, request_options_tests.rs, sampling_tests.rs, serving_protocol_tests.rs and speculative_burst_tests.rs, plus a real-checkpoint check on Qwen3-4B-4bit: fluent output at temperature 2.0 with the filter versus degeneration without it, and token-identical greedy output with and without the flag.
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) area:cli Command-line interface / CLI flags modeltype:text Text-only language model labels Aug 28, 2026
Three review findings on the top-n-sigma filter, none observable in the disabled baseline:

- Batch-gate uniformity: `FusedSampleParams::from_config` and the speculative-window `sampling_config_eq` now compare `SamplingConfig::effective_top_n_sigma()`, which normalizes greedy, non-positive, and non-finite values to 0.0. Before this, two greedy rows differing only in an inert `top_n_sigma` produced byte-identical tokens yet failed `matches`, dropping the whole co-resident batch to the per-row loop, disabling the pipelined lookahead, and splitting batched speculative windows.

- Dtype preservation: the final mask fill now carries the original logits dtype instead of f32. MLX's `where` promotes to `promote_types(x, y)`, so the f32 fill silently promoted f16/bf16 logits to f32, changing the precision the fused C++ chain runs in and doubling the `[B, V]` tensor while the filter was active. The f16 test now asserts the output dtype.

- NaN containment: the row maximum is now taken over the finite-masked row. MLX's Max reducer propagates NaN, so a single NaN entry drove the threshold to NaN and collapsed the entire row to -inf; the NaN entry itself stays masked either way. New regression test covers the NaN row.

Refs #1375.
@inureyes inureyes added status:done Completed and removed status:review Under review labels Aug 28, 2026
@inureyes
inureyes merged commit 407fc13 into main Aug 28, 2026
5 checks passed
@inureyes
inureyes deleted the feature/issue-1375-top-n-sigma branch August 28, 2026 01:20
inureyes added a commit that referenced this pull request Aug 28, 2026
## Summary

Adds locally typical sampling (`typical_p`, default `1.0` disabled) on the row-filter hook introduced by #1375: tokens whose surprisal `-log p` is closest to the row entropy are kept, in typicality order, until `typical_p` probability mass accumulates; the rest are masked to `-inf`. Also flips this issue's two llama-compat manifest entries (`--typical`, `field:typical_p`) from `deferred` to `supported`, which required the server-wide flag and the native `/completion` field to land here.

## Rust versus C++ placement

Like top-n-sigma (#1479), the filter is a Rust-side graph transformation applied through `apply_row_filters` before the single `ffi::fused_sample` dispatch: it is row-wise, history-free and RNG-free, so it needs no bridge signature change, no MLX pin change, and requests stay on the single-dispatch fused batch path. The bracketed order pinned by #1375 (`top_n_sigma -> p_less (#1373) -> typical_p`) is preserved; the `p_less` slot remains a documented placeholder.

## What changed

- `src/lib/mlxcel-core/src/generate.rs`: `SamplingConfig::typical_p` (`1.0` in `Default` and `greedy()`), plus `effective_typical_p()` folding greedy and out-of-domain values to the disabled `1.0` for the batch-uniformity gates, mirroring `effective_top_n_sigma`.
- `src/lib/mlxcel-core/src/sampling.rs`: `typical_p_filter` (float32 log-softmax arithmetic; non-finite input entries sanitized to `-inf` before the softmax so `-inf` masking is transparent and a NaN cannot poison the entropy; exclusive-cumulative-mass keep rule so at least one token always survives; mask fill in the original logits dtype); the `typical_p` arm of `apply_row_filters`; `FusedSampleParams::typical_p` populated via the effective value and compared bitwise in `matches`.
- `src/server/batch/speculative_burst.rs`: `sampling_config_eq` compares `effective_typical_p()`, so greedy rows differing only in an inert value still share a batched window.
- Request plumbing: `SamplingParams::typical_p` on the three OpenAI-shaped endpoints with `validate_typical_p` (finite, in `(0.0, 1.0]`, else 400 `invalid_request_error`); `RequestOptionOverrides::typical_p`; `ResolvedSamplingParams::typical_p` threaded through both `build_sampling_config` branches.
- Server-wide default (this is where typical_p deliberately differs from XTC and top-n-sigma): a `--typical` / `--typical-p` flag on BOTH `mlxcel serve` (`src/main.rs`) and `mlxcel-server` (`src/bin/mlx_server.rs`), default `1.0` = disabled matching b10621, resolved through `ServerConfig::default_typical_p` (`cli_input.rs` -> `startup.rs` -> `config.rs`) when a request omits the field. The `--typical` manifest entry is owned by this issue, and a `supported` option claim must hold on both server binaries, so the flag could not be deferred.
- Native `/completion`: `NativeCompletionRequest::typical_p`. b10621 declares the field with NO schema limits (its source comments out the range with "what's the valid range?"), so the route sanitizes instead of rejecting: a present value outside the enabled range `(0.0, 1.0)` resolves to the explicit disabled form `1.0`, which still overrides the server-wide default exactly like an upstream request value replaces the server default; only an absent field lets the default apply. The resolved value is echoed in `generation_settings`.
- Disaggregated wire struct: `SerializableSamplingState::typical_p` with `#[serde(default = "default_typical_p_disabled")]` returning `1.0`, because the f32 zero default would deserialize an older peer's frame into an invalid always-on cutoff; round-trip and legacy-frame tests added.
- Manifest: `compat/llama-server/b10621/sampling-and-grammar.json` flips `--typical` (claim: both spellings accepted on both binaries, default `1`) and `field:typical_p` (claim: `typical_p`) to `supported`, with conformance tests `tests/llama_compat_manifest.rs` and `src/server/llama_compat_tests.rs`. These are the only manifest entries touched, both owned by #1377, and `check_llama_compat_manifest.py` passes; #1377 now has zero deferred entries, so closing it cannot redden the validator.
- CLI: `--typical-p` (alias `--typical`) on `mlxcel generate` and the chat REPL, rejected at parse time outside `(0.0, 1.0]`.
- Docs: `docs/python-client.md`.

## Numerical validation (Qwen3-4B-4bit, real checkpoint)

- `--temp 1.0 --typical-p 0.5 --seed 1` produces fluent, on-topic output with finite logits.
- Control arm: greedy output (`--temp 0`) is token-identical with and without `--typical-p 0.5`, and `typical_p = 1.0` returns the input pointer unchanged (zero graph nodes, asserted by `typical_p_one_disables_via_hook`), so every existing token stream stays byte-identical.
- A 40-case host-reference test reimplements the formula in f64 on the host and requires kept-set equality for every token whose exclusive cumulative mass is more than `1e-4` from the cutoff boundary.

## Review follow-up (second commit)

A review pass caught that the filter's chain position diverged from b10621: upstream runs `top_k -> typ_p`, re-softmaxing the surviving candidates, so the entropy and typicality ranking come from the renormalized top-k distribution, while the hook ran typical_p before the C++ chain's top_k and computed both over the full vocabulary. The fix applies an idempotent Rust-side top-k mask ahead of the typical filter whenever `1 < top_k < vocab`; the C++ chain's own top_k then re-selects the same set, so no stage runs out of order and the single fused dispatch is unchanged. A regression test uses a row where the two orders provably disagree and asserts the b10621 outcome, and the manifest notes now document the ordering guarantee. Also from review: `/props` reports `typical_p` (key-set contract updated), the server flag value is sanitized at startup (out-of-domain folds to disabled with a warning instead of a silently inert setting), the disabled-value test now discriminates against an active sibling filter, stale comments were refreshed, and the `+inf` handling difference versus top_n_sigma is documented rather than silent.

## Test plan

- [x] `cargo test -p mlxcel-core --profile test-fast --features metal,accelerate --lib sampling::tests` (89 passed; includes the 12 new typical_p tests: host reference, disable-is-pointer-equal, monotone kept counts, argmax drop, `-inf` and NaN transparency, dtype preservation, greedy skip, fused batch, params normalization and bitwise `matches`, #902 distribution)
- [x] Root-crate filters `typical_p`, `validate_typical`, `sampling_config_eq`, `request_options`, `serving_protocol`, `native_completion`, `top_n_sigma`, `build_sampling_config`, `llama_compat`: all green
- [x] `cargo test --profile test-fast --features metal,accelerate --test llama_compat_manifest` (validates the flipped `--typical` claim against both freshly built server binaries)
- [x] `cargo clippy -p mlxcel-core --lib --tests --features metal,accelerate -- -D warnings`, `cargo clippy --lib --tests --bins --features metal,accelerate -- -D warnings`, `cargo fmt --all -- --check`
- [x] `python3 scripts/ci/check_llama_compat_manifest.py`, `scripts/ci/check_cross_repo_refs.py`
- [x] Real-checkpoint validation as above

Closes #1377
@inureyes inureyes self-assigned this Aug 31, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
lablup#1479)

## Summary

Adds top-n-sigma logit filtering: a new `SamplingConfig::top_n_sigma` field (default `0.0`, disabled) that keeps only the tokens whose raw logit lies within `n` standard deviations of the row maximum and masks the rest to `-inf`, plus the batch-safe row-filter hook (`apply_row_filters`) that lablup#1377 (`typical_p`) and lablup#1373 (`p_less`) will reuse. Because the filter thresholds logits rather than probabilities it is invariant to temperature, which is what makes it the standard "stable at high temperature" sampler.

## Rust versus C++ placement

The filter is implemented entirely in Rust as a pre-filter ahead of the single `ffi::fused_sample` dispatch, not inside the C++ chain. It is row-wise, history-free and RNG-free, so it needs neither the RNG plumbing that pushed XTC into the C++ chain (lablup#1379) nor a bridge signature change; it composes MLX graph ops (`astype`/`isfinite`/`sum`/`sqrt`/`where`) that lazily fuse into the same evaluation, and requests stay on the single-dispatch fused batch path. No `cxx::bridge` or MLX pin change.

## What changed

- `src/lib/mlxcel-core/src/generate.rs`: `SamplingConfig::top_n_sigma` (`0.0` in `Default` and `greedy()`).
- `src/lib/mlxcel-core/src/sampling.rs`: `top_n_sigma_filter` (float32 statistics over the finite entries of each row, so an f16 sum over a 150k vocabulary cannot overflow and `-inf`/NaN entries neither perturb the threshold nor come back); `apply_row_filters` hook pinning the order `top_n_sigma -> p_less (lablup#1373) -> typical_p (lablup#1377)`, returning the input pointer unchanged (zero graph nodes) when disabled or greedy (`temperature == 0.0 || top_k == 1`) and treating non-positive or non-finite values as disabled so the b10621 `-1.0` sentinel is inert; hook wired into `preprocess_logits_for_sampling` (after the history penalties, before the fused C++ temperature/top_k/top_p/min_p/XTC chain) and `batched_fused_sample`; `FusedSampleParams` gains `top_n_sigma`, populated in `from_config` and compared bitwise in `matches`; `config_supports_fused_batch` stays `true` for the filter, with the rationale documented.
- `src/server/batch/scheduler.rs`: the pipelined lookahead prime (`prime_lookahead_with_input`) applies the same `apply_row_filters` before its `fused_sample`, so the pipelined decode path samples the identical distribution as the synchronous fused path.
- `src/server/batch/speculative_burst.rs`: `sampling_config_eq` compares `top_n_sigma`, keeping rows with different values out of one shared batched speculative window.
- Request plumbing (mirrors XTC: request-only, no server default): `SamplingParams::top_n_sigma`, `RequestOptionOverrides::top_n_sigma` resolved `unwrap_or(0.0)`, `ResolvedSamplingParams::top_n_sigma` threaded through both `build_sampling_config` branches, `validate_top_n_sigma` (finite and `>= 0.0`, else 400 `invalid_request_error`) called on `/v1/chat/completions`, `/v1/completions` and `/v1/responses` (the responses translator forwards the field through its flattened `SamplingParams` clone).
- `src/distributed/kv_cache_serde/types.rs` + `serving_protocol.rs`: `SerializableSamplingState::top_n_sigma` with `#[serde(default)]` so a frame from an older prefill node deserializes to the disabled baseline; round-trip and legacy-frame tests added.
- CLI: `--top-n-sigma` (alias `--top-nsigma`) on `SamplingOptions` (used by `mlxcel generate` and the chat REPL via `resolved_cli_sampling_params`), rejected at parse time when negative or non-finite.
- Docs: `docs/python-client.md` sampling-parameters paragraph.

## Deliberate scope deviation: native `/completion`

The issue asks for a `top_n_sigma` field on `NativeCompletionRequest`. That field is NOT added here, deliberately: `src/server/llama_compat_tests.rs` enforces that a `native_request_field` manifest entry with no mlxcel claim must not be declared on the struct, and the `field:top_n_sigma` entry (with the `--top-nsigma` option entry) in `compat/llama-server/b10621/sampling-and-grammar.json` is owned by lablup#1436 under the epic's shard-ownership rule, so the field and its manifest flip must land together in lablup#1436, two issues later in this chain. No manifest shard is touched by this PR. The core semantics for that wiring are already in place: `apply_row_filters` treats the upstream `-1.0` "disabled" sentinel as inert rather than a mask-everything threshold.

## Numerical validation (Qwen3-4B-4bit, real checkpoint)

- High-temperature stability: `--temp 2.0 --top-n-sigma 1.0 --seed 1` produces fluent English; the identical command without the filter degenerates (the documented property of the filter). Outputs quoted in the test plan below.
- Control arm: greedy output (`--temp 0`) is token-identical with and without `--top-n-sigma 1.0`, and the disabled value adds zero graph nodes (pointer-equality asserted in `apply_row_filters_disabled_returns_input_pointer_unchanged`), so every existing token stream stays byte-identical.

## Review follow-up (second commit)

A review pass surfaced three MEDIUM findings, fixed in the second commit: (1) `FusedSampleParams::from_config` and the speculative-window `sampling_config_eq` now compare `SamplingConfig::effective_top_n_sigma()` (greedy / non-positive / non-finite normalize to `0.0`), so greedy rows differing only in an inert `top_n_sigma` no longer fall off the fused batch, pipelined lookahead, or shared speculative window despite sampling identically; (2) the filter's mask fill now carries the original logits dtype, since MLX's `where` promotion was silently returning f32 for f16/bf16 logits (precision change in the fused chain plus a doubled `[B, V]` tensor while active), with the f16 test asserting the output dtype; (3) the row maximum is taken over the finite-masked row so a single NaN entry can no longer drive the threshold to NaN and collapse the row to `-inf`. Known LOW observations left as-is: the CLI value parser intentionally rejects the llama-server `-1.0` sentinel at parse time (the native endpoint mapping in lablup#1436 will accept it as disabled), filtered-out tokens serialize logprobs as `null` exactly like the existing top-k/min-p masking, and the drafter-internal greedy `fused_sample` call sites (DFlash round loop, MTP heads) bypass all samplers by design, affecting acceptance rate only, with rejection sampling staying self-consistent through `sample_token_with_distribution`.

## Test plan

- [x] `cargo test -p mlxcel-core --profile test-fast --features metal,accelerate --lib sampling::tests` (includes the 12 new top-n-sigma tests: worked-example kept sets, row independence, `-inf` transparency, f16 152k-vocab overflow guard, greedy skip, fused-batch eligibility and bitwise `matches`, 64-row fused batch honoring the filter, lablup#902 distribution zero mass outside the kept set)
- [x] `cargo test --profile test-fast --features metal,accelerate --lib top_n_sigma` plus the `request_options`, `build_sampling_config`, `sampling_config_eq`, `serving_protocol` and route-validation filters on the root crate
- [x] `cargo clippy -p mlxcel-core --lib --tests --features metal,accelerate -- -D warnings`, `cargo clippy --lib --tests --bins --features metal,accelerate -- -D warnings`, `cargo fmt --all -- --check`
- [x] `python3 scripts/ci/check_llama_compat_manifest.py` (manifest untouched, still canonical), `scripts/ci/check_cross_repo_refs.py`, `scripts/ci/check_kernel_dtype_keys.py`
- [x] Real-checkpoint validation on `models/mlx/qwen3-4b-4bit` as above

Closes lablup#1375
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
## Summary

Adds locally typical sampling (`typical_p`, default `1.0` disabled) on the row-filter hook introduced by lablup#1375: tokens whose surprisal `-log p` is closest to the row entropy are kept, in typicality order, until `typical_p` probability mass accumulates; the rest are masked to `-inf`. Also flips this issue's two llama-compat manifest entries (`--typical`, `field:typical_p`) from `deferred` to `supported`, which required the server-wide flag and the native `/completion` field to land here.

## Rust versus C++ placement

Like top-n-sigma (lablup#1479), the filter is a Rust-side graph transformation applied through `apply_row_filters` before the single `ffi::fused_sample` dispatch: it is row-wise, history-free and RNG-free, so it needs no bridge signature change, no MLX pin change, and requests stay on the single-dispatch fused batch path. The bracketed order pinned by lablup#1375 (`top_n_sigma -> p_less (lablup#1373) -> typical_p`) is preserved; the `p_less` slot remains a documented placeholder.

## What changed

- `src/lib/mlxcel-core/src/generate.rs`: `SamplingConfig::typical_p` (`1.0` in `Default` and `greedy()`), plus `effective_typical_p()` folding greedy and out-of-domain values to the disabled `1.0` for the batch-uniformity gates, mirroring `effective_top_n_sigma`.
- `src/lib/mlxcel-core/src/sampling.rs`: `typical_p_filter` (float32 log-softmax arithmetic; non-finite input entries sanitized to `-inf` before the softmax so `-inf` masking is transparent and a NaN cannot poison the entropy; exclusive-cumulative-mass keep rule so at least one token always survives; mask fill in the original logits dtype); the `typical_p` arm of `apply_row_filters`; `FusedSampleParams::typical_p` populated via the effective value and compared bitwise in `matches`.
- `src/server/batch/speculative_burst.rs`: `sampling_config_eq` compares `effective_typical_p()`, so greedy rows differing only in an inert value still share a batched window.
- Request plumbing: `SamplingParams::typical_p` on the three OpenAI-shaped endpoints with `validate_typical_p` (finite, in `(0.0, 1.0]`, else 400 `invalid_request_error`); `RequestOptionOverrides::typical_p`; `ResolvedSamplingParams::typical_p` threaded through both `build_sampling_config` branches.
- Server-wide default (this is where typical_p deliberately differs from XTC and top-n-sigma): a `--typical` / `--typical-p` flag on BOTH `mlxcel serve` (`src/main.rs`) and `mlxcel-server` (`src/bin/mlx_server.rs`), default `1.0` = disabled matching b10621, resolved through `ServerConfig::default_typical_p` (`cli_input.rs` -> `startup.rs` -> `config.rs`) when a request omits the field. The `--typical` manifest entry is owned by this issue, and a `supported` option claim must hold on both server binaries, so the flag could not be deferred.
- Native `/completion`: `NativeCompletionRequest::typical_p`. b10621 declares the field with NO schema limits (its source comments out the range with "what's the valid range?"), so the route sanitizes instead of rejecting: a present value outside the enabled range `(0.0, 1.0)` resolves to the explicit disabled form `1.0`, which still overrides the server-wide default exactly like an upstream request value replaces the server default; only an absent field lets the default apply. The resolved value is echoed in `generation_settings`.
- Disaggregated wire struct: `SerializableSamplingState::typical_p` with `#[serde(default = "default_typical_p_disabled")]` returning `1.0`, because the f32 zero default would deserialize an older peer's frame into an invalid always-on cutoff; round-trip and legacy-frame tests added.
- Manifest: `compat/llama-server/b10621/sampling-and-grammar.json` flips `--typical` (claim: both spellings accepted on both binaries, default `1`) and `field:typical_p` (claim: `typical_p`) to `supported`, with conformance tests `tests/llama_compat_manifest.rs` and `src/server/llama_compat_tests.rs`. These are the only manifest entries touched, both owned by lablup#1377, and `check_llama_compat_manifest.py` passes; lablup#1377 now has zero deferred entries, so closing it cannot redden the validator.
- CLI: `--typical-p` (alias `--typical`) on `mlxcel generate` and the chat REPL, rejected at parse time outside `(0.0, 1.0]`.
- Docs: `docs/python-client.md`.

## Numerical validation (Qwen3-4B-4bit, real checkpoint)

- `--temp 1.0 --typical-p 0.5 --seed 1` produces fluent, on-topic output with finite logits.
- Control arm: greedy output (`--temp 0`) is token-identical with and without `--typical-p 0.5`, and `typical_p = 1.0` returns the input pointer unchanged (zero graph nodes, asserted by `typical_p_one_disables_via_hook`), so every existing token stream stays byte-identical.
- A 40-case host-reference test reimplements the formula in f64 on the host and requires kept-set equality for every token whose exclusive cumulative mass is more than `1e-4` from the cutoff boundary.

## Review follow-up (second commit)

A review pass caught that the filter's chain position diverged from b10621: upstream runs `top_k -> typ_p`, re-softmaxing the surviving candidates, so the entropy and typicality ranking come from the renormalized top-k distribution, while the hook ran typical_p before the C++ chain's top_k and computed both over the full vocabulary. The fix applies an idempotent Rust-side top-k mask ahead of the typical filter whenever `1 < top_k < vocab`; the C++ chain's own top_k then re-selects the same set, so no stage runs out of order and the single fused dispatch is unchanged. A regression test uses a row where the two orders provably disagree and asserts the b10621 outcome, and the manifest notes now document the ordering guarantee. Also from review: `/props` reports `typical_p` (key-set contract updated), the server flag value is sanitized at startup (out-of-domain folds to disabled with a warning instead of a silently inert setting), the disabled-value test now discriminates against an active sibling filter, stale comments were refreshed, and the `+inf` handling difference versus top_n_sigma is documented rather than silent.

## Test plan

- [x] `cargo test -p mlxcel-core --profile test-fast --features metal,accelerate --lib sampling::tests` (89 passed; includes the 12 new typical_p tests: host reference, disable-is-pointer-equal, monotone kept counts, argmax drop, `-inf` and NaN transparency, dtype preservation, greedy skip, fused batch, params normalization and bitwise `matches`, lablup#902 distribution)
- [x] Root-crate filters `typical_p`, `validate_typical`, `sampling_config_eq`, `request_options`, `serving_protocol`, `native_completion`, `top_n_sigma`, `build_sampling_config`, `llama_compat`: all green
- [x] `cargo test --profile test-fast --features metal,accelerate --test llama_compat_manifest` (validates the flipped `--typical` claim against both freshly built server binaries)
- [x] `cargo clippy -p mlxcel-core --lib --tests --features metal,accelerate -- -D warnings`, `cargo clippy --lib --tests --bins --features metal,accelerate -- -D warnings`, `cargo fmt --all -- --check`
- [x] `python3 scripts/ci/check_llama_compat_manifest.py`, `scripts/ci/check_cross_repo_refs.py`
- [x] Real-checkpoint validation as above

Closes lablup#1377
@inureyes inureyes added this to the 0.7 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Command-line interface / CLI flags area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) modeltype:text Text-only language model priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(sampling): add top-n-sigma logit filtering (top_n_sigma) with a batch-safe row-filter hook

1 participant