Skip to content

feat(models): support OpenAI Privacy Filter PII tagger in mlxcel tag - #2460

Merged
inureyes merged 6 commits into
mainfrom
feature/issue-2387-openai-privacy-filter
Oct 19, 2026
Merged

inureyes merged 6 commits into
mainfrom
feature/issue-2387-openai-privacy-filter

Conversation

@inureyes

@inureyes inureyes commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Summary

openai_privacy_filter (openai/privacy-filter, mlx-community/openai-privacy-filter-*) now runs through mlxcel tag: a bidirectional sparse-MoE BIOES PII tagger with a calibrated constrained Viterbi decoder by default, --argmax for per-token decoding, and the new --operating-point NAME for viterbi_calibration.json operating points. The flag is refused by kind for argmax-only families, and an unknown point, a missing bias or a non-finite bias fails before any weight loads. mlxcel generate refuses the checkpoint with openai_privacy_filter is a token classifier; use \mlxcel tag``, and embedding detection does not claim it.

  • Encoder src/models/openai_privacy_filter.rs + _layers.rs: banded bidirectional attention with sinks in query chunks of attention_chunk_size, interleaved YaRN (truncate: false, factor 1 + 0.1 ln 32, head_dim^-0.25 on q and k, SDPA at scale 1), f32 router and experts in moe_chunk_size token chunks, Hugging Face fused gate_up_proj / down_proj split at load. Config sizes that become i32 shapes or loop bounds are refused past i32::MAX (a chunk size of 2^32 used to wrap to 0 and loop forever), and the router's output width must equal the expert planes' leading dimension and num_local_experts.
  • Shared helpers src/models/gpt_oss_common.rs (Used by: GptOss, OpenAIPrivacyFilter): yarn_rope_freqs with a truncate flag, ExpertLinear, gpt_oss_swiglu, moved out of gpt_oss.rs unchanged in arithmetic.
  • src/token_classification/viterbi.rs ports ViterbiDecoder (start / end sets, >= ties, -1e9 sentinel, closed and end ties to the first candidate in upstream's gathered order); privacy_filter.rs implements TokenClassifierModel plus calibration loading; TokenModelKind::PrivacyFilter is detected on model_type alone. No trait signature changed; load_token_classifier_with(path, &TokenClassifierLoadOptions) is additive and load_token_classifier wraps it.
  • Docs: docs/token-classification.md (model, decoding, operating points, load errors), docs/supported-models.md row, CHANGELOG.

GPT-OSS gate (helpers moved)

Teacher-forced trace (examples/logit_trace, docs/benchmarks.md#judging-a-change-that-moves-the-numbers) on models/mlx/gpt-oss-20b-mxfp4, docs/architecture.md 5 60 8 512, MLX_ENABLE_TF32=0, both arms under gpu-lock on GB10. Reverted arm = the warm logit_trace built from main cb9f2deb; fixed arm = this branch. scripts/compare_logit_traces.py: top-1 disagreement 0 / 300, decided positions (gap >= 2.0) 0 / 100, logit delta p50 = p99 = max = 0.0000, perplexity 19.9517 both; the data rows of the two TSVs are byte-identical (only the # model path header differs).

Dense experts gather unsorted (finding)

On CUDA, gather_mm with sorted_indices = true over f32 activations and bf16 weights (the overlay's gather_mm_rhs branch, M == 1 && right_sorted_) returned allocation-history-dependent results: the bf16 forward was bit-exact in a fresh process and in the pipeline order "bf16 then 8-bit then bf16", but after the 8-bit model's workload had run first in the same process the 2024-05-17 tokens drifted from private_date (-0.003) toward private_phone (top label -0.36 / -0.53), flipping spans. Forcing the unsorted gather, or sorted gathers over bf16 operands, stayed exact in every order, and gather_qmm's sorted path (8-bit, what GPT-OSS runs) matched the oracle in every order. Dense planes therefore gather unsorted (same sum, only the sorted kernel's locality lost; measured about 1.5x the 8-bit forward time on a 7.5k-token text); the kernel itself is left for a follow-up issue.

Validation (GB10, CUDA sm_121, --profile test-fast --features cuda, MLX_ENABLE_TF32=0)

Oracle: mlx-vlm 0.7.8 (git 73d366ecf9233b3fc6549531a7f2386726d09ff6) on mlx CPU, tests/fixtures/token_classification/generate_privacy_filter_fixture.py, fixture records the revision.

  • Log-probabilities of the acceptance sentence (10 tokens x 33 labels): max |dp| 6e-5, max |dlogp| 0.19 on labels above -10 nats, max |dlogp| 5.4 on tail labels below -18 nats. The tail is not gated: the oracle's own f32 forward differs from its bf16 run by 4.5 nats there and by 0.14 on labels above -10, so a 2e-2 log-domain bound over all labels measures bf16 rounding of near-zero probabilities; the test gates probabilities within 2e-2 and labels above -10 nats within 0.5.
  • Spans: identical to mlx-vlm for six sentences (incl. CJK and umlaut text, one where Viterbi and argmax disagree) plus --replacement "[REDACTED]" and --keep private_email, under Viterbi and argmax, on bf16; the 8-bit build prints the same spans for all eight cases. Fixture cases must clear a 0.5-nat top-1 / top-2 margin at every token (bf16 CUDA vs bf16 CPU flipped an argmax at 0.19 on a sentence the first draft used).
  • 4536-token text (past the 4096 attention chunk and 2048 routing chunk) on real bf16 weights: chunked vs unchunked forward max |dp| 0.00000, max |dlogp| 0.03 above -10 nats, 0 argmax flips. An oracle span comparison on long repeated text is not meaningful: the model itself sits at 50/50 on 144 of 6816 tokens there (6 exact ties).
  • Tiny random model: attention chunk 7 / 1 and MoE chunk 16 / 1 equal the unchunked forward; banded attention over 300 tokens equals the full-mask SDPA for chunks 64 / 128 / 1024; a router wider than the expert planes is refused at load.
  • Real binary: mlxcel tag -m models/mlx/openai-privacy-filter-bf16 "Alice Smith can be reached at [email protected]." prints private_person, private_email and <PRIVATE_PERSON> can be reached at <PRIVATE_EMAIL>.; --argmax, --replacement "[REDACTED]", --keep private_email, --operating-point default behave as upstream; --operating-point nope fails with Unknown Privacy Filter operating point 'nope' (... defines 'default'); Rampart with --operating-point default is refused before weights; the 8-bit build prints the same spans; mlxcel generate fails with the token-classifier message.

Changes during review

  • Implementation review: no CRITICAL or HIGH; the docs and the viterbi.rs module comment now state closed and end ties as upstream's candidate order (every E, then every S), not label output order.
  • Security review: no CRITICAL or HIGH; its MEDIUM findings are fixed (config sizes bounded to i32, router width checked against the expert planes, calibration biases must be finite), each with a test. Left as noted: the f32 copies gather_mm makes of the dense planes per forward (upstream pays the same), the per-chunk key window of upstream's attention_chunk_size, and that malformed tensor shapes abort inside MLX rather than erroring at load.

Test plan

  • cargo test --profile test-fast --features cuda -p mlxcel --lib --no-run, then under gpu-lock --test-threads=1: privacy_filter 20 passed, token_classification 64 passed, gpt_oss 11 passed (incl. the new gpt_oss_common YaRN tests against mlx-lm and mlx-vlm values), viterbi 13 passed, models::openai_privacy_filter 10 passed; the previously order-dependent pairs (privacy_filter_8bit_matches + spans, privacy_filter_acceptance + spans) pass twice each.
  • cargo test --profile test-fast --features cuda -p mlxcel --bin mlxcel --no-run: extract_tests 5 passed (--operating-point in mlxcel tag --help), tag 4 passed.
  • cargo fmt --check; cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests --no-deps -- -D warnings clean.
  • Not verifiable here: -4bit / -5bit / -6bit / -mxfp4 / -mxfp8 / -nvfp4 mlx-community variants (not on this host; an -nvfp4 export carrying a per-expert global scale would be refused by ExpertLinear as GPT-OSS is), Apple Silicon (where load_text_weights runs the dense build in f16), and the fused Hugging Face layout on a real openai/privacy-filter download (unit-tested on synthetic tensors; the local checkpoints are already split).

Closes #2387

@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata labels Oct 19, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Run openai_privacy_filter through mlxcel tag with the calibrated BIOES Viterbi decoder, --operating-point, and a token-classifier refusal from mlxcel generate (#2387).

Findings Addressed

  • None needed: no CRITICAL or HIGH finding at 24cecbbd.

Remaining Items

  • Docs say Viterbi ties go to "the first label in output order"; the closed-state candidates are ordered all E then all S (as upstream), so a tie between E-b and S-a picks E-b. Wording only, code matches upstream (LOW).
  • Viterbi transition sums are f32 throughout; upstream adds the f64 bias in Python float before storing f32. Identical for the shipped all-zero calibrations; only a near-tie under non-zero biases could differ by one ulp (LOW, informational).
  • Apple Silicon not exercised: load_text_weights converts dense bf16 to f16 on Metal, so the parity tolerances (tuned on CUDA bf16 vs CPU bf16) need one macOS run of the checkpoint tests (LOW, not verifiable on this host).
  • -nvfp4 variant: ExpertLinear refuses per-expert global_scale (fix(moe): load mlx-lm NVFP4 per-expert global_scale natively and stack ModelOpt expert scales #2351); if that export carries one it will not load "through the same path" as the docs say. Disclosed as unvalidated (LOW).
  • --operating-point default on Rampart is refused, where upstream accepts default silently. Matches the issue wording ("rejected for models without Viterbi") (LOW, intentional).

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow (mlxcel tag -> load_token_classifier_with -> PrivacyFilterTagger::load)
  • Project conventions followed
  • Existing modules reused where applicable (gpt_oss_common.rs, switch_layers gather helpers, the feat: Add token-classification and span-extraction output (mlxcel tag, mlxcel extract) #2383 pipeline)
  • No unintended structural changes (trait contract unchanged; one TokenModelKind variant, one detector; GPT-OSS helpers moved with arithmetic unchanged)
  • Tests pass: under gpu-lock with --test-threads=1, MLX_ENABLE_TF32=0: privacy_filter 19, viterbi 13, gpt_oss 11, token_classification 64, all passing; scoped clippy clean; real binary prints the acceptance spans and redaction, --operating-point nope and Rampart --operating-point default fail before weights, mlxcel generate gives the token-classifier message.

inureyes added a commit that referenced this pull request Oct 19, 2026
…rder

Closed-state and end-state ties go to the first candidate in upstream's gathered order (every entity's `E`, then every `S`; `O` first among end states), which is what the decoder does and what `ties_resolve_as_upstream` pins; the docs and the module comment said label output order. Review finding on PR #2460.
@inureyes

Copy link
Copy Markdown
Member Author

Security and Performance Review

No CRITICAL or HIGH finding at cf5afe26; nothing committed. The sinks / mask raw pointers into fast_scaled_dot_product_attention_with_sinks are sound (the bridge copies both arrays by value during the call and both locals outlive it). The moved GPT-OSS helpers are arithmetically identical for GPT-OSS (truncate: true gives the same integer low / high as the old usize path), and the PR's logit trace (0 / 300 disagreement, byte-identical rows) gates it.

Remaining Items

  • MEDIUM: validate() checks attention_chunk_size, moe_chunk_size and sliding_window as usize, then the layers cast them with as i32. A config value of 4294967296 passes validation and becomes a chunk of 0, so the banded_attention and PrivacyFilterMoe::forward loops never advance and push lazy arrays until the host runs out of memory; values in 2^31..2^32 go negative (a reversed key range, or query_start - radius overflowing). Fix: i32::try_from on each, plus num_attention_heads * head_dim and num_experts_per_tok, inside validate().
  • MEDIUM (inherited from GPT-OSS): the router's output width is never checked against the expert planes' leading dimension, and routed indices go unchecked into gather_mm / gather_qmm / take. A router with more rows than planes reads past the expert buffers on the device. Fix: one equality check in PrivacyFilterMoe::from_weights.
  • MEDIUM: on dense checkpoints MLX gather_mm runs astype(b, float32) on the whole [128, 640, 640] plane, so every forward copies 3 x 8 planes (about 5 GB written) per 2048-token MoE chunk. Upstream pays the same cost. Measured on GB10 for about 7.5k tokens: bf16 forward about 1.8 s against about 1.2 s for 8-bit. Casting the Regular planes to f32 once at load would trade 2.5 GB of resident memory for this.
  • LOW: a bias like 1e300 passes as_f64 and becomes inf in f32, and an inf meeting a -inf gives NaN Viterbi scores; add is_finite() in TransitionBiases::from_json. viterbi_calibration.json is read with no size cap.
  • LOW: band_mask is rebuilt per chunk per layer; interior chunks share one band.

inureyes added a commit that referenced this pull request Oct 19, 2026
… or index out of bounds

Security review findings on PR #2460. Every config size that becomes an i32 shape or loop bound (`attention_chunk_size`, `moe_chunk_size`, `sliding_window`, `hidden_size`, `intermediate_size`, `vocab_size`, `num_local_experts`, `num_experts_per_tok`, `num_attention_heads * head_dim`) is now rejected past `i32::MAX`; a chunk size of 2^32 used to wrap to 0 and leave the chunk loop pushing lazy arrays until memory ran out. The MoE block checks that the router's output width equals the expert planes' leading dimension and the config's `num_local_experts`, so a mismatched checkpoint fails at load instead of gathering past the planes on the GPU. Calibration biases must be finite; `1e300` used to become infinity and NaN the lattice.

Tests cover each refusal; the privacy_filter, viterbi, gpt_oss, token_classification and models::openai_privacy_filter selectors pass on the rebuilt lib tests.
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 19, 2026
`openai_privacy_filter` (openai/privacy-filter and the mlx-community exports) is a bidirectional sparse-MoE token classifier that tags PII with BIOES labels and decodes them with a calibrated constrained Viterbi pass. It now loads through `mlxcel tag`: Viterbi by default, `--argmax` for per-token decoding, and the new `--operating-point NAME` for the `viterbi_calibration.json` operating points (refused by kind for argmax-only families; an unknown point or missing bias fails before any weight loads). `mlxcel generate` refuses the checkpoint with a pointer to `mlxcel tag`.

The encoder in `src/models/openai_privacy_filter.rs` is a GPT-OSS stack without the cache: banded bidirectional attention with sinks in query chunks, interleaved YaRN (`truncate: false`) with the `1 + 0.1 ln(factor)` factor and `head_dim^-0.25` on q and k, f32 router and experts in token chunks. YaRN, the clipped SwiGLU and the biased expert projections move from `gpt_oss.rs` into `src/models/gpt_oss_common.rs`; a teacher-forced trace of gpt-oss-20b-mxfp4 (300 positions) is byte-identical before and after. Dense expert planes gather unsorted because CUDA `gather_mm` with `sorted_indices` over f32 activations returned allocation-history-dependent results.

Validated on GB10 against mlx-vlm 0.7.8 (git 73d366ec): label probabilities within 6e-5, identical spans for six sentences plus `--replacement` and `--keep` under both decoders on bf16 and 8-bit, and a 4536-token text invariant to chunking.

Closes #2387
Shorten the f32 reference frequencies in the YaRN tests to their round-trip literals, use `is_multiple_of` in the config checks, iterate the Viterbi emissions directly instead of indexing by step, and take `slice::from_ref` where a one-row argmax was built from a clone. No behavior change; the privacy_filter, viterbi, gpt_oss, token_classification and models::openai_privacy_filter selectors pass on the rebuilt lib tests.
…rder

Closed-state and end-state ties go to the first candidate in upstream's gathered order (every entity's `E`, then every `S`; `O` first among end states), which is what the decoder does and what `ties_resolve_as_upstream` pins; the docs and the module comment said label output order. Review finding on PR #2460.
… or index out of bounds

Security review findings on PR #2460. Every config size that becomes an i32 shape or loop bound (`attention_chunk_size`, `moe_chunk_size`, `sliding_window`, `hidden_size`, `intermediate_size`, `vocab_size`, `num_local_experts`, `num_experts_per_tok`, `num_attention_heads * head_dim`) is now rejected past `i32::MAX`; a chunk size of 2^32 used to wrap to 0 and leave the chunk loop pushing lazy arrays until memory ran out. The MoE block checks that the router's output width equals the expert planes' leading dimension and the config's `num_local_experts`, so a mismatched checkpoint fails at load instead of gathering past the planes on the GPU. Calibration biases must be finite; `1e300` used to become infinity and NaN the lattice.

Tests cover each refusal; the privacy_filter, viterbi, gpt_oss, token_classification and models::openai_privacy_filter selectors pass on the rebuilt lib tests.
…ther

Add doc comments to the public fields and accessors in the new Privacy Filter files that had none (YaRN beta_fast and beta_slow, the six TransitionBiases fields, ViterbiDecoder and PrivacyFilter accessors), rewrap an over-long viterbi module doc line, and note in docs/token-classification.md that dense expert planes gather unsorted while quantized planes keep the sorted gather_qmm path.

Validation:
- cargo fmt --check clean
- cargo check --lib --tests (test-fast, cuda) passes

Refs #2387
@inureyes
inureyes force-pushed the feature/issue-2387-openai-privacy-filter branch from a6c10c0 to 3d0c90c Compare October 19, 2026 08:31
@inureyes
inureyes merged commit 4928d79 into main Oct 19, 2026
52 of 53 checks passed
@inureyes
inureyes deleted the feature/issue-2387-openai-privacy-filter branch October 19, 2026 08:50
inureyes pushed a commit that referenced this pull request Oct 20, 2026
## Summary

`fast_scaled_dot_product_attention_with_sinks` carried `Used by: GptOss` at all three of its declaration sites, but five families call it: GPT-OSS, Laguna, DeepSeek-V4, Falcon-OCR and, since #2460 landed, OpenAI Privacy Filter. The same comment called a sink a "per-head attention bias for first position"; a sink is an extra per-head logit that joins the softmax denominator and has no value row. All three comments now describe the sink that way and list the five families. Comment-only; no code changes.

- `src/lib/mlxcel-core/src/lib.rs` (`///` in the cxx bridge block), `src/lib/mlxcel-core/cpp/mlx_cxx_bridge.h` and `src/lib/mlxcel-core/cpp/mlx_cxx_bridge.cpp` (`//`): the two comment lines replaced with the text from the issue, plus `OpenAIPrivacyFilter`, which was not a caller when the issue was filed. The spelling follows the existing `Used by:` lines in `src/models/gpt_oss_common.rs`.
- The three `Used by: GptOss` lines on the GPT-OSS SwiGLU activation are correct and are left as they are, as the issue asks.

## Related issues

Closes #1786

## Type of change

- [x] `chore` — build, CI, dependencies, release infrastructure

## Test plan

- [x] `cargo fmt --all -- --check` passes.
- [x] `grep -rn 'fast_scaled_dot_product_attention_with_sinks(' src/models` lists `gpt_oss.rs`, `laguna_layers.rs`, `deepseek_v4_attention.rs`, `falcon_ocr.rs`, `openai_privacy_filter_layers.rs` and the privacy filter's test file, and nothing else in `src/`, `examples/`, `tests/` or `benches/`.
- [x] `git diff -U0` shows only the six comment lines changed.
- [ ] `cargo build --release --features metal,accelerate` was not run for this comment-only change; the C++ edits are inside `//` comments, so the bridge compiles as before.
inureyes added a commit that referenced this pull request Oct 20, 2026
…arriers (#2477)

## Summary

Two CUDA overlay fixes for silently wrong values on GB10, each with tests that fail on the unfixed overlay, and both model-level workarounds removed: the OpenAI Privacy Filter sorts its dense expert planes again and the DeBERTa-v2 encoder (GLiNER2.5) no longer ends a CUDA graph after every layer.

## A1: sorted `gather_mm` read the stride of a size-1 axis as its leading dimension

`gather_mm_rhs` (`matmul.cpp`, the `M == 1 && right_sorted_` branch every sorted MoE expert gather takes) passed `a.strides(-2)` to the grouped GEMM as the stride between consecutive gathered rows. There `a` is `[rows, 1, K]`, so that is the stride of a size-1 axis, which MLX ignores when it flags an array row-contiguous (`check_contiguity`) and leaves at whatever the producer wrote. The branch now makes `a` row-contiguous and uses `lda = K`, the batch stride, as `GatherQMM`'s grouped path already did.

The producer in the Privacy Filter is the per-expert bias add in `ExpertLinear::forward`, `out + expand_dims(take(bias, ids), -2)`: `expand_dims` inserts a stride of 1, and a binary op inherits its second operand's layout when it donates that operand, which happens only when the first operand's cached buffer is more than 16 KiB over size (the cache hands out buffers up to two pages larger). So gate and up carried strides `[N, 1, 1]` or not depending on what the allocator had handed out, the compiled SwiGLU and the bf16 cast inherited them, and the down projection's sorted gather read `lda = 1`: the first row of every expert group right, every later row shifted by one element. That is PR #2460's drift (`2024-05-17` sliding from `private_date` to `private_phone` after the 8-bit model had run). A deferred per-plane capture showed exactly that signature (gate and up off by one bf16 ulp, `down` rows 1.. of each group off by up to 7.7e2). Also recorded: the overlay promotes `bf16 + f32` to bf16 (`overlays/cuda/mlx/dtype.cpp`), so "f32 activations" never reach this kernel as f32; the stride bug is dtype-independent.

Exposure: every `SwitchLinear::forward(.., sorted = true)` caller with non-quantized planes reaches the branch (deepseek, exaone_moe, glm4_moe, glm4_moe_lite, gpt_oss, hunyuan_moe, ernie4_5_moe, llama4, qwen3_next, gemma4, phixtral, the SwitchGLU families, openai_privacy_filter). Their `sorted_x` is a `take` output with natural strides; the producers that reach the branch with a unit stride today are the biased `ExpertLinear` planes of GPT-OSS and the Privacy Filter, so a dense (bf16) GPT-OSS checkpoint was exposed the same way (quantized ones take `gather_qmm`).

## A2: captured child graphs race with concurrent kernel nodes

The first `encode` of a fresh process returned wrong hidden states in about 40% of processes (7 of 20 on main with the split forced off), from a random layer each time, every replay correct. Allocation poisoning (0xFF on every allocation) changed nothing and produced no NaN. Bisection, 20 fresh processes each: graphs off 0, one op per graph 0, the whole encode in one graph 0, graph exec cache of 1 (fresh instantiation per graph) 10 of 10, program-order chaining of every node 0, chaining only edges that touch a stream-captured child graph (the cuBLASLt matmuls) 0, chaining only kernel-kernel edges 18, zeroing the whole cuBLASLt workspace inside the capture 0, workspace ceiling 0 (no split-K) 10. The child graphs hold `cutlass_80_simt_sgemm_*` with `cublasLt::splitKreduce_kernel` and a 240-byte workspace memset; their declared buffers and the dumped edges are correct. The resource that makes a cuBLASLt child graph wrong when an unrelated kernel node of the same graph runs alongside it is not identified.

Fix (`device.cpp` overlay, new): a captured child graph is a barrier inside a graph. It joins every open branch added before it and every node added after it depends on it, on top of upstream's buffer-derived edges; kernel nodes between two child graphs stay concurrent. 0 of 30 fresh processes with the barrier, 5 of 10 with `MLXCEL_CUDA_GRAPH_CAPTURE_BARRIER=0` on the same binary. `MLXCEL_CUDA_GRAPHS_DOT_VERBOSE=1` adds node parameters to `MLX_SAVE_CUDA_GRAPHS_DOT_FILE` dumps. Both are in `docs/environment-variables.md`.

Review pass (`5e29de95`): the two switches parse with the docs grammar (trimmed, case-insensitive, `0`/`false`/`off`/`no` and `1`/`true`/`on`/`yes`) via a new `mlxcel_env_flag` helper, since MLX's `atoi` env reader reads `on` as 0 and would have disabled the barrier by default; a `ConcurrentContext` batch whose nodes include a captured child graph makes its join node the barrier and clears the open-branch state afterwards, so cuBLASLt matmuls grouped under a concurrent section gate later nodes the same way single nodes do; and the per-encoder barrier map is leaked on purpose (`~CommandEncoder` runs `commit` and `clear_graph_state` during thread exit, after a `thread_local` with a destructor may be gone).

Perf A/B (same binary, barrier on vs off, 3 rounds interleaved, `mlxcel generate --profile` on a 1767-token prompt): prefill qwen2.5-0.5b-bf16 on 3274 / 3415 / 3413 tok/s vs off 3421 / 3277 / 3260; llama-3.2-1b-4bit on 3896 / 4094 / 3847 vs off 3879 / 3929 / 3947, both within the run-to-run spread. Decode of 64 tokens after the same prompt, qwen2.5-0.5b-bf16 on 151.6 / 156.9 tok/s vs off 155.1 / 154.2 / 157.1 (the first "on" run, 97.5, was the cold process); llama-3.2-1b-4bit on 165.1 / 167.0 vs off 164.9 / 163.4 / 166.8. Decode runs gemv kernels, so no child graph is captured and the barrier is inert. The f32 encoder (`mlxcel extract`, gliner2.5-small-v1, 1400-character text, wall including load): on 1.25 / 1.26 / 1.25 s vs off 1.19 / 1.19 / 1.25 s, about +4%, the prefill GEMMs no longer overlap their neighbours. `mlxcel tag` on openai-privacy-filter-bf16: on 2.27 / 2.34 s vs off 2.31 / 2.19 / 2.35 s. MoE decode A/B (bench-decode, same binary, barrier on vs off, 4 interleaved rounds per arm): qwen3-moe-4bit on 76.46 vs off 75.96 tok/s, phi-3.5-moe-4bit on 43.21 vs off 42.61, paired deltas alternate sign and sit inside the ~1.5% host noise floor, so the barrier costs nothing measurable on MoE decode either.

## Tests and code

- `src/models/switch_layers_sorted_gather_layout_tests.rs` and `_history_tests.rs` (new, helpers in `_test_support.rs`): `sorted_gather_mm_with_a_unit_stride_on_the_singleton_axis` and `sorted_gather_mm_after_a_biased_expert_add` (the Privacy Filter's op chain, donation forced) fail on the unfixed overlay (max |err| 1.19 and 5e-1 against an f64 reference, versus one bf16 ulp) and pass on the fix; `sorted_gather_mm_with_a_transposed_layout_plane` covers the row-major B instantiation; three history tests run the sorted gather before and after an 8-bit `gather_qmm` MoE, allocator churn and other sorted shapes and compare byte for byte (they pass before and after: allocation history alone never triggered it).
- `src/models/deberta_v2_tests.rs::real_encoder_first_run_equals_replay` (new): the whole trunk on the 306-token fixture, first encode equals replay bit for bit, run in N fresh processes.
- `openai_privacy_filter_layers.rs` drops `sort_routed` (every plane sorts at 64 or more rows, upstream's threshold); `moe_block_runs_both_gather_paths_identically` now compares the sorted and unsorted paths for real. `deberta_v2.rs` drops `graph_break_per_layer`. `mlxcel_core::array_strides` is new (post-eval strides only; before eval they are the shape's defaults).

## Verification (GB10 sm_121, `--profile test-fast --features cuda`, `MLX_ENABLE_TF32=0`, test binary under gpu-lock with `--test-threads=1`)

- A1: `sorted_gather` 6 passed; on a control build with the unfixed `matmul.cpp` the unit-stride and biased-add tests fail and the other four pass. `privacy_filter_8bit` then `privacy_filter_spans` in one process (PR #2460's failing order): 3 of 3 fail on the control build, 3 of 3 pass on the fix. `privacy_filter_checkpoint_tests` 5 passed on the sorted dense path (the acceptance sentence in the bf16, 8-bit, bf16 order; the 4536-token chunk-invariance check; the log-prob and span fixtures).
- A2: `real_encoder_first_run_equals_replay` 0 failures in 20 fresh processes; the same binary with the barrier disabled fails 5 of 10, and 13 of 20 with `CUDA_MODULE_LOADING=EAGER` and the barrier disabled, so lazy module loading is not the trigger. Revalidated after the review fixes: 20 fresh processes with the barrier, 0 failures. `deberta_v2` 8, `gliner2_5` 22, `token_classification` 86, `openai_privacy_filter` 10 passed.
- `cargo fmt --all -- --check` and `cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests --no-deps -- -D warnings` clean. Full lib suite with `--test-threads=1`: 9373 passed, 0 failed, 166 ignored.
- Full workspace gate on `5e29de95` (161 test binaries run in place under gpu-lock with `--test-threads=1`): build 0, clippy 0, doctests 0, contract set 0; 160/161 bins pass, `mllama_parity` failed once with the known 1-ulp `ragged_multi_image_states_concatenate_real_rows` flake and passes on rerun (8/8); issue #2467. After merging main (PRs #2469 to #2476, one overlay README conflict resolved with both additions), the same gate on the merged head `3ae5e2c1` gives the same result: build 0, clippy 0, doctests 0, contract set 0, 160/161 with the same mllama flake passing on rerun.
- Not covered here: Metal (untouched) and other CUDA parts.

## Upstream report drafts (not filed)

A1, `[CUDA] gather_mm with sorted indices reads the stride of a size-1 axis as lda`: `GatherMM::eval_gpu` routes `M == 1 && right_sorted_` to `gather_mm_rhs`, which passes `ensure_batch_contiguous(a)`'s `strides(-2)` as `lda` to `cutlass_grouped_gemm_unaligned`; `a` is `[..., 1, K]` there, so that is a size-1 axis stride that `check_contiguity` ignores and `expand_dims` or a donating binary op leaves at 1, and every gathered row after the first of a group then reads shifted memory. Repro: `a = mx.swapaxes(mx.random.normal((96, 640, 1)), 1, 2)` (strides `(640, 1, 1)`), `w` bf16 `(128, 640, 640)`, sorted expert ids, `mx.gather_mm(a.astype(mx.bfloat16), mx.swapaxes(w, -1, -2), rhs_indices=idx, sorted_indices=True)` versus `sorted_indices=False`: rows that are first in their group agree, every other row differs by O(1). Fix: make `a` row-contiguous and use `lda = a.shape(-1)`, as `GatherQMM` already does.

A2, `[CUDA] stream-captured child graph nodes (cuBLASLt matmuls) race with concurrent kernel nodes of the same graph`: GB10 sm_121, driver 580.178.04, CUDA 13, MLX 243bdf09c, `MLX_ENABLE_TF32=0`, f32 weights (fastino/gliner2.5-small-v1, 12 DeBERTa-v2 layers, hidden 384, 306 tokens). About 40% of fresh processes return a first forward that differs from every later one by 0.1 to 0.6, from a random layer; the bisection is the list in the A2 section above. Each cuBLASLt call has its own workspace, registered inputs and outputs, and correct edges in the dumped graphs. Workaround: captured child graphs as barriers inside a graph. Repro: lablup/mlxcel `src/models/deberta_v2_tests.rs::real_encoder_first_run_equals_replay` in 20 fresh processes with `MLXCEL_CUDA_GRAPH_CAPTURE_BARRIER=0`.

Technical report: `TECHNICAL_REPORTS/pr-2477-cuda-gather-mm-graph-barrier.en.md` (Korean `.ko.md`).

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

Labels

area:models Model architectures, weights, loading, metadata 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(models): Support OpenAI Privacy Filter (openai_privacy_filter) PII tagger

1 participant