Skip to content

feat: openai/privacy-filter port — PII detection & redaction - #60

Merged
Brooooooklyn merged 45 commits into
mainfrom
worktree-privacy-filter
May 14, 2026
Merged

Brooooooklyn merged 45 commits into
mainfrom
worktree-privacy-filter

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Brings openai/privacy-filter — a 1.5B / ~50M-active gpt-oss-style MoE token classifier for PII — to MLX-Node on Apple Silicon. End-to-end token classification matches HuggingFace transformers 5.8.1 exactly on the canonical test (`Hi I am Alice Smith, email [email protected]` → `[O O O B-private_person E-private_person O O B-private_email I-private_email E-private_email]`).

Three user-facing surfaces ship together:

  • `@mlx-node/privacy` TS package: `PrivacyFilter.load() / classify() / redact()` with per-call threshold, Viterbi calibration override, and label-allowlist redaction.
  • Native binding (`@mlx-node/core`): synchronous `PrivacyFilterModel` for low-level use.
  • CLI: `mlx redact --model --input --output ` with `--replacement`, `--labels`, `--threshold`, `--json`.

Highlights

Architecture (gpt-oss-derived):

  • 8 transformer blocks, GQA (14 q / 2 kv), 128-expert top-4 sparse MoE
  • Banded attention with attention sinks (per-head learned scalars in softmax denominator), bidirectional, `sliding_window=128`, alternating sliding/full per the gpt-oss config
  • YaRN RoPE (factor=32, theta=150000) with `mscale ≈ 1.347` pre-scaling of Q and K
  • Interleaved RoPE layout (not neox split-halves) and concatenated gate/up MLP split (not gpt-oss's alternating) — both privacy-filter-specific overrides verified against HF `modeling_opf.py`
  • BIOES Viterbi decoder with 6 configurable calibration biases (per-call override merged onto checkpoint default)

Reusable infrastructure that other models benefit from:

  • Shared `moe::TopKRouter` (gpt-oss + Qwen3.5 routing modes). Qwen3.5 MoE migrated as part of this PR — parity preserved by the existing test suite.
  • Reference + Metal banded-attention kernel at `crates/mlx-core/src/array/banded_attention.rs` (SDPA + K/V augmentation trick for sinks).

Performance (M3 Max, bf16): 17000 tok/s @ 512 tokens, 6373 tok/s @ 8K tokens.

Memory: `classify()` drops GPU intermediates + clears the MLX buffer cache before returning, so steady-state `phys_footprint` stays bounded (~3.3 GB) across thousands of calls.

Findings worth flagging

While benchmarking against a real corpus (Claude Code session history) I uncovered two operational issues, both fixed in this branch and documented in `docs/privacy-filter.md`:

  1. Long-context recall ceiling — the checkpoint is trained on short documents and recall drops sharply past ~2000 tokens. At 5000 chars it misses ~half the entities; at 8000 chars it typically returns nothing. Users should chunk at ~1500 chars (~500 tokens). Documented.
  2. Apple Silicon memory accounting — `process.memoryUsage().rss` undercounts Metal buffer use because unified memory charges GPU allocations to `phys_footprint`, not the resident set. Documented with the right tools (`vmmap`, `footprint`).

Test plan

  • `cargo test -p mlx-core --release` — 1327 passed, 0 failed
  • `cargo test -p mlx-paged-attn --release` — 7 passed
  • `vp test run` — 1202 passed, 0 failed (with model weights present: 8 additional privacy / cli tests also pass)
  • `cargo clippy --all-targets -- -D warnings` — clean
  • `cargo fmt --check` — clean
  • `vp lint --type-aware --type-check` — 0 errors (6 pre-existing warnings outside scope)
  • `vp fmt` — clean
  • End-to-end against HF reference: `cargo test --release --lib privacy_filter::forward::tests::forward_classify_alice_smith_email -- --include-ignored` — passes
  • HF parity test (5 fixtures, `PRIVACY_FILTER_PARITY=1`) — passes with documented bf16 boundary-noise budget
  • Memory bounded across 200-file / 7M-token real-corpus run

🤖 Generated with Claude Code


Note

Medium Risk
Large feature addition that introduces a new model implementation (attention/MoE/Viterbi) and a new attention primitive, plus expands quantization modes and conversion logic; correctness and numeric stability regressions are the main risk areas.

Overview
Adds an end-to-end Rust/NAPI port of openai/privacy-filter, including checkpoint loading (config.json + model.safetensors + tokenizer + optional viterbi_calibration.json), a full forward pass (YaRN RoPE, GQA, sliding/full banded attention with per-head sinks, sparse MoE FFN), BIOES Viterbi decoding, and span extraction for returned entities/tokens.

Introduces array::banded_attention (fast SDPA-backed path plus a reference oracle) and wires it into the new model, with extensive unit tests for masking/sink semantics and fast-vs-reference parity.

Extends mlx convert quantization support to additional modes (mxfp4, nvfp4) with mode-specific defaults, adds a privacy-filter-specific quantization predicate/metadata handling, and includes viterbi_calibration.json in the copied model artifacts.

Reviewed by Cursor Bugbot for commit 9f1fdf3. Bugbot is set up for automated code reviews on this repo. Configure here.

@coderabbitai

coderabbitai Bot commented May 14, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d56bd336-3a53-4775-ad67-aabeaf7585d8

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch worktree-privacy-filter

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2c7900a124

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/privacy/src/redactor.ts Resolved
@Brooooooklyn

Copy link
Copy Markdown
Contributor Author

Follow-up: quantization (Phases A-D)

Six new commits push the convert pipeline + inference path through to support all four MLX-native quantization modes for privacy-filter (and incidentally, mxfp4 and nvfp4 for every other model that uses the convert pipeline).

Commits

7134c15 register `privacy-filter` as a known convert model type
368d703 enable mxfp4 + nvfp4 quant modes in convert pipeline
1399314 mirror loosened `--q-mode` validation in CLI
db2504e privacy-filter quantize sanitizer (skips embeds/score/norms/biases/sinks; router goes to 8-bit affine only in affine mode)
77df90c quantized inference path — loader auto-detects, attention + MoE branch on `LoadedProj::{Plain,Quantized}`
62d548e cross-mode parity test (5 fixtures × 5 modes) + docs

Perf (M3 Max, 3-run median, vmmap-polled phys_footprint @ 1Hz)

Mode Load (ms) 512-tok (ms) tok/s 2K-tok (ms) tok/s Peak footprint
`bf16` 234 25 21,219 112 18,768 4.30 GB
`mxfp8` 234 26 20,805 117 17,888 3.10 GB
`mxfp4` 234 26 20,807 114 18,358 1.40 GB
`nvfp4` 240 27 19,993 114 18,382 1.40 GB
`affine` 236 26 20,701 111 18,874 1.40 GB

The win is footprint (4.3 → 1.4 GB, ~3× reduction on 4-bit modes). Throughput is essentially flat — the matmul sizes in a 1.5B / 50M-active MoE aren't bandwidth-bound enough for quantization to deliver a speed win on top of the memory win. This matches the prior estimate that quantization on this checkpoint trades quality for memory, not memory for speed.

Parity findings (5-fixture cross-mode test)

The single-input canonical NER test passes on all four quantized modes (forward_classify_alice_smith_email_{mxfp8,mxfp4,nvfp4,affine}). The 5-fixture cross-mode parity test (parity_across_quantized_modes, #[ignore]-gated) intentionally fails, documenting real divergences:

Per the brief's "don't loosen the test to make it pass" rule, the test stays strict. It serves as executable documentation; a future investigation can use it as the gate when fixing nvfp4's stability.

Recommendation

For production use, mxfp8 is the right default — 28% footprint reduction with no parity drops on the canonical test and minimal divergences (1 token short on one fixture). 4-bit modes deliver bigger memory savings but with real (if subtle) quality regressions on this 1.5B checkpoint.

How to use

mlx convert -m privacy-filter -q --q-mode mxfp8 \
  -i .cache/models/privacy-filter \
  -o .cache/models/privacy-filter-mxfp8

# Then load as usual — the loader auto-detects quantization
const pf = await PrivacyFilter.load('.cache/models/privacy-filter-mxfp8');

🤖 Generated with Claude Code

Brooooooklyn and others added 25 commits May 14, 2026 15:32
Design for porting openai/privacy-filter (1.5B/50M-active gpt-oss-style
MoE token classifier with banded bidirectional attention + attention
sinks) to MLX-Node. Covers shared MoE refactor with Qwen3.5 parity gate,
new banded-attn Metal kernel, BIOES Viterbi decoder, @mlx-node/privacy
package, and mlx redact CLI.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Empty submodules for TopKRouter and dispatch helpers; implementations
land in subsequent commits.
Implement the shared TopKRouter for MoE blocks, with the
softmax-then-top-k-then-renormalize convention used by gpt-oss
and Qwen3.5 MoE. The router owns a [num_experts, hidden] weight
and [num_experts] bias, projects [B, T, H] -> [B, T, E] logits,
softmaxes over experts, takes top-k via argpartition, and
renormalizes the kept weights to sum to 1 along axis=-1.

Re-exports RouterConfig and TopKRouter from moe::mod for
unqualified-path access.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
- RouterConfig now carries RoutingMode { GptOss, Qwen35 { renormalize_topk } }
- GptOss path: topk-then-softmax — cheaper for large E
- Qwen35 path: softmax-then-topk, with conditional renormalization mirroring
  the model's norm_topk_prob config field
- Cache transposed weight at construction; use addmm in the matmul + bias step
- New tests for both modes including the no-renormalize Qwen35 sub-mode

Addresses code-review findings on 6907fa5.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Pull the topk + softmax + (optional) renormalize math out of
TopKRouter::route into a free function topk_from_logits that operates
on 2D [N, num_experts] logits. TopKRouter::route now flattens the
input, computes logits via addmm, and delegates to the helper.

This prepares Qwen3.5 MoE to share the routing math without giving up
its LinearProj gate (which it needs to host a quantized router
matmul). Behaviour for both RoutingMode variants is unchanged; new
unit tests cover the helper's public contract directly.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Replace the inline softmax + argpartition + slice_axis + take_along_axis
+ optional-renorm block in SparseMoeBlock::forward with a single call
to moe::topk_from_logits(RoutingMode::Qwen35 { renormalize_topk: ... }).

The math is bit-identical — same operations, same axis, same dtype
casts — so this is a pure refactor. Importantly, the gate matmul
stays here as a LinearProj so the quantized MXFP8 router path
(mixed_4_6 recipe and friends) keeps working; the shared TopKRouter
only handles plain MxArray gate weights and would have regressed
that codepath.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
… sinks

Slow but correct. Implements |q-k|<=band masking and per-head sink
contribution to the softmax denominator using existing MLX ops. Serves as
the correctness oracle for the Metal kernel (Task B2).

Placed under crates/mlx-core/src/array/banded_attention.rs (Option B from
the task plan) instead of mlx-paged-attn, because mlx-core already
depends on mlx-paged-attn and adding the reverse edge would cycle. The
B2 kernel-backed implementation can pick this up via dev-dependency for
its parity tests.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adds banded_attention() — the production-path implementation.
Reuses MLX's fused scaled_dot_product_attention kernel (Apple's
optimized Metal shader) with a K/V augmentation trick: append a
zero column for the sink slot, encode the sink logit in the mask's
last column. Output is identical to the reference within bf16
tolerance because the sink's V contribution is zero.

A hand-rolled .metal shader for this primitive is a future perf
optimization; banded_attention_reference remains the correctness
oracle.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adds PrivacyFilterConfig + RopeParameters serde structs for parsing
config.json from openai/privacy-filter checkpoints. Internal type
(no NAPI export); the @mlx-node/privacy package exposes the user
API, not raw config.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
include_str! required the model dir at compile time, which would break
cargo test on hosts/CI that don't have .cache/models/privacy-filter.
Switching to runtime read_to_string + #[ignore] matches the existing
"requires checkpoint" test convention (kv_scale_calibration.rs).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Pure-Rust Viterbi over a 33-class transition matrix encoding BIOES
legality (O → {O,B,S}; B-X → {I-X,E-X}; same-class enforcement; etc).
Six configurable transition biases mirror viterbi_calibration.json
operating points for runtime precision/recall tuning.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ring

Walks a Viterbi-decoded tag sequence into coherent privacy entities.
Spans use the tokenizer's byte offsets; score is the mean of per-token
probabilities; entities below the threshold are filtered out. Malformed
fragments (B-X followed by O, I-X without B-X) are dropped silently —
caller relies on the Viterbi decoder for legality.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Loads model.safetensors via the existing lazy safetensors reader,
builds the 8-layer ModelWeights struct (including per-layer
TopKRouter in GptOss mode), wraps the gpt-oss tokenizer via
Qwen3Tokenizer, and extracts the default operating point from
viterbi_calibration.json.

Tested against the real .cache/models/privacy-filter checkpoint
(--ignored gated; 140 tensors, 2.6 GB).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
AttentionLayer composes Q/K/V projections (bias=true), YaRN-scaled
RoPE applied to Q and K, and banded_attention with per-head sinks.
YaRN frequencies computed once at model load and shared across layers.
Output projection has bias.

Sanity tests cover shape, finiteness, and YaRN frequency math at
both ends of the spectrum. End-to-end numerical parity is deferred
to C7 (full forward) and E2 (HF reference fixture).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
YaRN extrapolation in mlx-lm and HF transformers multiplies Q and K by
an `attention_factor` (= mscale) before the rotation. For
factor=32 (privacy-filter default), this is ~1.347. Without it,
rotated Q/K are ~1.35x smaller than reference, attention logits are
~1.83x smaller, and softmax becomes flatter. End-to-end logits drift
correspondingly.

Adds mscale + mscale_all_dim to RopeParameters with sensible defaults
(1.0 and 0.0 - matches HF when fields absent) and applies the
attention_factor in AttentionLayer::forward.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
GptOssMlp routes through the per-layer TopKRouter (GptOss mode),
gather_sort + gather_mm with the [E, in, out]-shaped fused gate_up_proj
and down_proj weights, applies per-expert biases, and combines weighted
expert outputs. Mirrors Qwen3.5 MoE's SwitchGLU dispatch flow without
the per-projection transpose (privacy-filter weights ship pre-transposed).

The gate/up split is alternating (gate = gate_up[..., ::2],
up = gate_up[..., 1::2]) per both the mlx-lm and HF transformers gpt-oss
references — implemented via reshape `[..., 2*I]` → `[..., I, 2]` plus
slice + squeeze since MxArray lacks strided slicing. The activation is
gpt-oss's clamped SwiGLU variant: gate clamped at +limit, up clamped at
±limit, output = (up + 1) * (gate * sigmoid(alpha * gate)) with
alpha=1.702 and limit=7.0 (hard-coded gpt-oss constants, not in config).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Block (norm -> attn -> norm -> MoE -> residual), final RMSNorm, and
classifier head wired into PrivacyFilterModel::forward_logits.
8-layer transformer end-to-end producing [B, T, 33] logits.

The end-to-end correctness test
`forward_classify_alice_smith_email` is added but currently fails:
the model predicts garbage tags (no B-* tags emitted) on the canonical
"Hi I am Alice Smith, email [email protected]" probe. The shape /
finiteness test passes, so the orchestration itself is sound -- the
bug lives upstream in C1-C6. See the report for the printed Tokens /
Tags trace.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ault

gpt-oss config defaults layer_types to alternating sliding_attention /
full_attention starting with sliding. privacy-filter inherits this
without override. Previously we applied band=128 to ALL 8 layers,
crippling the 4 layers that should run full bidirectional attention.

Adds:
- layer_types: Option<Vec<String>> to PrivacyFilterConfig.
- attention_type_for_layer(idx) and band_for_layer(idx) helpers.
- band parameter on AttentionLayer::forward; Block computes per-layer.
- 3 config tests.

Note: end-to-end forward_classify_alice_smith_email test still fails
with the same tag sequence — for a 10-token input, band=128 is already
unbounded relative to the sequence, so this fix doesn't move the
prediction on this short example. The fix is nonetheless architecturally
correct (verified via eprintln that layers 0,2,4,6 now use band=128 and
layers 1,3,5,7 use band≈i32::MAX/2). A separate bug is causing
mis-classification on this short sequence.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Two bugs prevented end-to-end token classification from matching the HF
reference. RoPE used neox split-halves layout, but privacy-filter expects
the interleaved layout (HF _apply_rotary_emb). The fused gate_up MLP
projection used gpt-oss's alternating split, but privacy-filter overrides
to a concatenated [:I]/[I:2I] split (HF _apply_gate). With both fixes,
forward_classify_alice_smith_email matches HF transformers 5.8.1 output
exactly.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Expose PrivacyFilterModel as a NAPI class with synchronous load() and
classify(text, opts?). classify() tokenizes with byte offsets, runs
forward_logits, log-softmaxes, decodes with per-call calibration on top
of the checkpoint default, extracts BIOES spans, and returns
{entities, tokens?}. Adds Qwen3Tokenizer::encode_with_offsets_sync as a
small helper.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adds the `@mlx-node/privacy` workspace package with public types
(`PrivacyLabel`, `Entity`, `ClassifyOptions`, `RedactOptions`,
`ViterbiCalibration`, etc.) layered on top of the native
`PrivacyFilterModel` NAPI class shipped in ce00e03.

Field names mirror the camelCase casing emitted by napi-rs so the
wrapper can pass user options through to the native binding without
re-keying.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adds the `PrivacyFilter` class with `load()` and `classify()` methods,
wrapping the native `PrivacyFilterModel`. The public surface is async
so future work can move loading to a worker thread without breaking the
API; the body just calls the synchronous native binding.

Wires `@mlx-node/privacy` into the Vite test alias map alongside
lm/trl/server. Tests use `.toContain()` rather than exact-match string
assertions because the tokenizer can include a leading space in entity
spans (HF byte-offset convention).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adds `PrivacyFilter.redact()` which classifies the input and replaces
each detected entity span. Supports three replacement modes:
- `'label'` (default) → `[<label>]`
- a literal string → inserted verbatim
- a function `(entity) => string` → per-entity custom rendering

`labels[]` opt narrows redaction to a subset of PII categories; the
returned `entities` array reflects what was actually redacted.

Redacted-output assertions use `.toContain()` rather than exact-match
because the tokenizer can include a leading space in entity spans (HF
byte-offset convention).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adds `mlx redact --model <path> --input <file> --output <file>
[--replacement label|<str>] [--labels csv] [--threshold f] [--json]`
wrapping @mlx-node/privacy. Reads from stdin and writes to stdout
when --input/--output are omitted. With --json, writes entities to
${output}.entities.json or stderr.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…Y=1)

Adds 5 fixture inputs comparing PrivacyFilter.classify output to HF
transformers' per-token argmax tag sequence. The HF checkpoint ships
only a logits head (no Viterbi decoder, no calibration application),
so the well-defined cross-implementation invariant is the argmax tag
per token — exposed via classify(..., { returnTokens: true }). Test
gated on PRIVACY_FILTER_PARITY=1; skips cleanly in regular CI.
Fixtures committed for reproducibility — regen via
scripts/dump-privacy-filter-parity.py.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Brooooooklyn and others added 12 commits May 14, 2026 15:32
Adds docs/privacy-filter.md covering @mlx-node/privacy API, native
PrivacyFilterModel binding, mlx redact CLI, and Viterbi calibration
tuning. Links from CLAUDE.md Topic guides.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
PrivacyFilterModel.classify held GPU intermediates (8 layers of hidden
states + K/V + MLP gate/up/down, plus [1, T, 33] logits and the softmax
/ log-softmax tensors) across calls. The MxArray wrappers dropped at
function-end, but the underlying Metal buffers stayed in MLX's caching
allocator. Across thousands of calls the cache grew unboundedly — a
real-corpus scan over Claude Code session history saw phys_footprint
climb past 100 GB on long inputs before any clear fired.

Drop the GPU-side arrays explicitly after extracting their CPU views,
then call synchronize_and_clear_cache(). Steady-state phys_footprint
now stays at ~3.3 GB for the shipped 1.5B checkpoint; transient peaks
still scale with input length but get reclaimed before the next call.
Throughput improves as a side effect (less allocator pressure):
~11k → ~21k tok/s on short chunks in local measurement.

Correctness unchanged — forward_classify_alice_smith_email still
matches the HF transformers reference exactly.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…con memory accounting

Two operational findings from a real-corpus sweep:

1. The checkpoint is trained on short documents and recall drops
   sharply past ~2000 tokens — at 5000 chars it misses ~half the
   entities, at 8000 chars it typically returns nothing. Document
   the ~1500 char chunking guidance so users don't silently lose
   detections on long inputs.

2. process.memoryUsage().rss undercounts MLX's Metal buffer use
   because Apple Silicon's unified memory charges GPU buffers to
   phys_footprint, not the resident set. Point readers at vmmap /
   footprint for accurate measurement.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adds 'privacy-filter' to the convert pipeline's model-type dispatch
as an identity sanitizer — the checkpoint ships safetensors with
MLX-native dtypes and layout, so no rearrangement is needed for
correctness. Wires auto-detection from config.json's
"model_type": "openai_privacy_filter" and lists it in CLI help.

This is the foundation for a follow-up quantization sanitizer that
will plug into the same arm.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
MLX upstream supports four quantization modes (affine, mxfp4, mxfp8,
nvfp4) end-to-end — kernels are instantiated in fp_quantized.metal
and the C++ string-to-mode parser accepts all four. Only Rust-side
validation in convert_model() blocked mxfp4 and nvfp4. Loosen the
validation, set per-mode bits/group_size defaults to match MLX C++
kernel instantiations (affine=4b/64, mxfp4=4b/32, mxfp8=8b/32,
nvfp4=4b/16), and update CLI help. FFI doc comment now lists all
four modes.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The Rust convert_model() now accepts all four MLX quant modes
(affine, mxfp4, mxfp8, nvfp4), but the CLI layer was still
rejecting --q-mode mxfp4 and --q-mode nvfp4 before they reached
the FFI. Mirror the Rust validation and broaden the recipe
compatibility check from "incompatible with mxfp8" to
"incompatible with any non-affine mode" since recipes are
affine-only by design.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Replaces the no-op privacy-filter arm with a real quantization pass.
When --q-mode is mxfp4 / mxfp8 / nvfp4, quantizes attention projections
(q/k/v/o) and MoE experts (fused gate_up_proj, down_proj); leaves
embeddings, classifier head, norms, biases, attention sinks, and the
router at bf16. When --q-mode is affine, additionally quantizes the
router at 8-bit (Qwen3.5 convention). Emits per-tensor quantization
overrides into config.json so a downstream loader can pick the right
variant per tensor.

Inference path is not touched yet — Phase C makes the loader and
forward consume the quantized weights.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ffine)

Extends the loader and forward pass to consume the per-tensor
quantization metadata emitted by `mlx convert -m privacy-filter -q`.
Persistence detects quantized projections (q/k/v/o + MoE
gate_up_proj/down_proj + optional 8-bit affine router) by the
`quantization` block in config.json and the companion .scales /
.biases tensors. Attention and MoE forward paths thread through a
single `project_2d` / `project_moe` helper so the bf16 branch and the
quantized branches share one bias-add / shape contract.

MoE expert weights ship in `[E, in, out]` orientation (the layout
gather_mm already expects) — packing the OUT axis means
`mlx_gather_qmm` runs with `transpose = false`. A thin
PrivacyFilterQuantizedSwitchLinear wraps the FFI call with the
transpose flag exposed; the existing Qwen3.5 path (which uses
`[E, out, in]` + transpose=true) is untouched.

The bf16 path is unchanged: forward_classify_alice_smith_email
still produces the same per-token tag sequence as before. New
mxfp4 / mxfp8 / nvfp4 / affine tests load the corresponding
`.cache/models/privacy-filter-<mode>` checkpoint and assert the
NER-position tags match the bf16 reference exactly. All four
quantized variants currently match the reference byte-for-byte on
the canonical "Hi I am Alice Smith, email [email protected]" input.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adds a Rust test that validates all four quantization modes (affine,
mxfp4, mxfp8, nvfp4) against the bf16 baseline on the 5-fixture
parity set (5 inputs spanning all 8 PII label classes). Asserts
exact agreement on named-entity tag positions — boundary-token
confidence noise tolerated, label flips not.

Documents the four modes, the convert invocation, and the measured
perf table in docs/privacy-filter.md.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Brings in upstream Transformer cross-attention fix (#3382). No
quantization code changes between b98831ad and a8776b7b.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Verified that nvfp4 is deterministic in our setting (per-group scales,
no global_scale). The prior 'non-deterministic' framing was wrong — the
mode is argmax-fragile on a small number of boundary tokens, but
Viterbi BIOES decoding rescues entity-level output so pf.classify() is
stable run-to-run. Per-tensor cosine similarity vs bf16 weights is in
fact higher for nvfp4 than mxfp4; the issue is error direction, not
magnitude.

While auditing this, found that Metal's QQMatmul::eval_gpu gemv path
silently drops global_scale_x/global_scale_w for nvfp4 (general path
correctly throws NYI). Doesn't affect privacy-filter (we don't use
qqmm), but filed upstream as ml-explore/mlx#3550 and noted in the docs.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the worktree-privacy-filter branch from 62d548e to 5ad8e6b Compare May 14, 2026 07:32

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5ad8e6b647

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Brooooooklyn and others added 4 commits May 14, 2026 15:43
The Rust classifier emits Entity.start/end as UTF-8 byte offsets (HF
tokenizer convention), but redactImpl was slicing the JS string with
those offsets directly. String.prototype.slice indexes UTF-16 code
units, so any non-ASCII character before an entity (emoji, CJK,
accented Latin) shifted the slice and either leaked or corrupted PII
in the output.

Now redactImpl encodes the source to a Buffer once and decodes each
[start, end) byte range with toString('utf8', a, b). Added unit tests
covering leading emoji, CJK preamble, accented Latin, multiple
non-ASCII entities, and the empty-entity fast path.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…::dispatch

Both privacy_filter::experts and qwen3_5_moe::switch_glu had local
copies of the same two MoE dispatch helpers. The privacy-filter copy
used Result for empty-input checks; the qwen3.5 copy could panic via
.unwrap() on x_shape.last().

Move the canonical (Result-based) implementation into the existing
moe::dispatch placeholder, expose as pub(crate), and update both call
sites to import from there. Field names (x_sorted, idx_sorted,
inv_order) were identical, so call sites needed no other changes.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The Viterbi decoder hardcodes O_ID = 0 as both the virtual initial
state at the first timestep and as the backtrace fallback. The label
loader in persistence.rs built label_strs from config.id2label without
ever validating that index 0 was actually "O". A checkpoint with
different label ordering would silently mis-decode tag sequences.

Add a load-time guard that errors out if "O" is missing or not at
index 0, converting silent decoder corruption into a clear failure.
The canonical openai/privacy-filter checkpoint is unaffected (O is at
id 0 there); the guard protects against community forks or retrained
variants.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
classify() was filling a per-token argmax Vec on every call and then
discarding it with `let _ = argmax_tag`. The companion per_token_probs
Vec is genuinely used downstream by extract_spans and the tokens
output, but argmax_tag was write-only. The inner loop now computes
just `best_val` via a fold and skips the unused index tracking.

The cost was small (microseconds per call vs. a multi-millisecond
forward pass) but it's pure dead work, so removing it is straight
cleanup.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
classify() was reporting score = max softmax (argmax-class probability)
while tag = Viterbi decode, so when Viterbi disagreed with local argmax
at boundary tokens, the returned score didn't belong to the returned
tag. Fixed by deferring the per-token confidence computation until
after Viterbi runs and indexing probs[t][tag_id] with the emitted tag.
The same probability vector now feeds extract_spans, so span scores
become consistent too.

Updated PrivacyEntity / PrivacyToken doc comments and the matching
JSDoc in packages/privacy/src/types.ts to describe the score as
"softmax probability of the emitted tag" instead of "argmax class".

Co-Authored-By: Claude Opus 4.7 <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 7f34cb9. Configure here.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7f34cb9e59

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/mlx-core/src/convert.rs Resolved
Comment thread packages/cli/src/commands/convert.ts Resolved
Brooooooklyn and others added 2 commits May 14, 2026 16:20
The convert pipeline whitelists the config files it carries across
from -i to -o, and viterbi_calibration.json was missing. When the file
is absent in the converted output, persistence::load_from_directory
falls back to Calibration::default() (all biases 0.0). Today's
upstream checkpoint happens to ship all-zero default biases, so there
is no observable regression on the canonical model — but any future
checkpoint with nonzero calibration values would silently lose them
through conversion. One-line fix.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The privacy-filter SafeTensors arm in convert.rs already had a 4-mode
default table for (bits, group_size). The GGUF→SafeTensors path in
utils/gguf.rs and the CLI display log in packages/cli still used the
old binary "mxfp8 ? (8,32) : (4,64)" rule, so leaving --q-bits and
--q-group-size unset for mxfp4 or nvfp4 produced wrong defaults (group
64 instead of 32/16). Replicate the canonical 4-mode table in both
spots so the GGUF path and the CLI summary stay consistent with the
SafeTensors arm and the documented matrix in docs/privacy-filter.md.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7c40a23c11

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

viterbi.rs's parse_tag() panics on labels that don't match the
B-X / I-X / E-X / S-X / O pattern. The existing validate_o_at_index_zero
guard only checked the position of "O", so a community or converted
checkpoint with a malformed entry like {"1": "garbage"} or {"1": "B"}
passed load and then panicked on the first classify() call —
process-terminating in server contexts.

Add a sibling validate_bioes_labels() that walks every non-"O" label
at load time, enforces the BIOES syntax via splitn('-'), and returns a
clear "label at index N is not a valid BIOES tag" error. viterbi.rs's
parse_tag() now sees its panics as load-time-enforced invariants
rather than reachable runtime states.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@Brooooooklyn
Brooooooklyn merged commit 025e5af into main May 14, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the worktree-privacy-filter branch May 14, 2026 10:00
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.

1 participant