Repository navigation
feat(models): add RT-DETRv2 object detection model - #80
Merged
Merged
Conversation
Add RT-DETRv2, a real-time detection transformer, to mlxcel. This is a new task type: the model emits bounding boxes (left, top, right, bottom, label, confidence) rather than a token stream, so it lives outside the LanguageModel/generate flow and is exposed through a new top-level `mlxcel detect` subcommand. Ported from the upstream mlx-vlm RT-DETRv2 model (PR #1195). Architecture: - ResNet-50-vd / ResNet-101-vd backbone (3-conv stem, stride-2 maxpool, AvgPool-based vd downsampling shortcuts), with depth read from the backbone config so both variants share one module. - Hybrid encoder: an AIFI transformer on the deepest level (2D sine position embedding), a top-down FPN, and a bottom-up PAN with RepVGG/CSPRep blocks. - Encoder query selection (top-K over the flattened position-by-label score space) feeding a six-layer deformable-attention decoder with iterative bbox refinement. - Multi-scale deformable attention via a pure-MLX bilinear grid_sample (padding zeros, align_corners false). The whole forward path runs in float32 for box-coordinate precision; weights stay in their stored dtype (bf16) so the float32-input by bf16-weight promotion matches the reference. The HF-to-MLX weight rename pipeline runs only when raw HF layout is detected, so pre-converted checkpoints load as-is. Detection is a new `mlxcel detect` subcommand (`--model`, `--image`, `--threshold`, `--format text|json`) rather than an overload of `generate` or `serve`, because the output is boxes, not tokens. The existing model-type classification module is left untouched; this model registers no new generate-flow model type. New module `src/vision/detection/rt_detr_v2/` (config, sanitize, shared layers, backbone, hybrid_encoder, transformer, model, processor, predictor) plus `src/commands/detect.rs` and the `detect` subcommand wiring in `src/main.rs`. Verified with cargo fmt, cargo clippy (metal,accelerate, all-targets, -D warnings), and 22 unit tests covering grid_sample, max and average pool, nearest upsample, anchor generation, the inverse-sigmoid round-trip, the rename pipeline, and config parsing.
inureyes
added a commit
that referenced
this pull request
May 26, 2026
Bump version to 0.0.31. Highlights: MiniCPM-V 4.6 and RT-DETRv2 model support plus an Anthropic-style /v1/messages API endpoint (#82, #80, #74); fixes for missing or null chat-message content, Gemma 3n VLM per_layer_inputs, Qwen3.5 MTP verify attention, and batched quantized KV cache mask offsets (#91, #86, #78, #76); and a pinned 1.93.1 Rust toolchain (#87, #90).
sjswerdloff
added a commit
to sjswerdloff/mlxcel
that referenced
this pull request
Jun 25, 2026
sparse_sdpa signature changes: - Drop: `l: i32, num_blocks: i32` - Add: `q_len: i32, kv_len: i32, cache_offset: i32` num_query_blocks and num_key_blocks are derived inside from q_len and kv_len respectively. Q is padded to num_query_blocks * block_size; K/V are padded (separately) to num_key_blocks * block_size. The mask is the new asymmetric form from lablup#78 with cache_offset threaded through. Shape walk for the per-(kv_head, q_block) gather is updated: the broadcast axis is num_query_blocks (outer), the gather source is num_key_blocks (axis 3). The 5D GQA expansion uses num_query_blocks for the q-block axis. Output reshape goes back to padded_q_len, sliced to q_len. Call site at line 394: kv_len read from cache_k's actual shape; cache_offset = kv_len - l. The no-cache case (cache_offset=0) makes num_query_blocks == num_key_blocks and the algebra coincides with cycle 65's symmetric form. KNOWN GAP closed by lablup#80: the `selected` indices today are computed from the indexer over CURRENT-CHUNK idx_q/idx_k only, so values are chunk-relative ([0, num_query_blocks)) while sparse_sdpa interprets them as absolute ([0, num_key_blocks)). No crash (chunk-relative values are still valid into the larger range), but attention attends to wrong blocks in the cached case. End-to-end correctness gated on lablup#80's indexer K cache. build_msa_unified_mask (symmetric) marked #[allow(dead_code)] and kept with its 7 unit tests for regression value; deletion planned post-merge. cargo build clean, 14 mask tests pass (7 symmetric + 7 asymmetric).
sjswerdloff
added a commit
to sjswerdloff/mlxcel
that referenced
this pull request
Jun 25, 2026
) Add per-layer m3_idx_k cache to KVCache for MiniMax-M3's MSA indexer projection (index_k_proj). The indexer scores key BLOCKS for top-k selection; in chunked-prefill / multi-turn it must see the FULL cached prefix idx_k, not just the current chunk's projection. Current code (pre-lablup#80) projects from x only, so top-k selection is blind to cached positions — the architectural gap behind the cycle-65 latent comment. API additions on KVCache: - m3_idx_k_update_and_fetch(new_idx_k) -> full cached idx_k Concatenates the new chunk to prior cached state, advances m3_idx_offset, returns an independently-owned slice of the full cache. - m3_idx_offset() — accessor for the indexer's accumulated length. - has_m3_idx_k_state() — defensive check for whether the indexer cache has been written. Fields added to KVCache struct (initialized to None / 0 in both new() constructors at lines 514 and 562; default state for non-M3 models): - m3_idx_k: Option<UniquePtr<MlxArray>> - m3_idx_offset: i32 5 unit tests in cache.rs covering: initial-empty state, single-chunk write, two-chunk concat along seq axis, three-chunk accumulation (precursor to task lablup#82's four-chunk gate), independence from main K/V offset. All pass. Wired into M3's forward() by task lablup#81; until then the methods exist but are unused by mlxcel-M3. KVCache rationale (cf. struct doc): the model-specific fields are documented as opt-in state with Option<> types, consistent with the Turbo/INT8 sidecar pattern. Avoids per-model branching in the trait at the cost of a small per-cache memory footprint when unused. Per-request scoping (KVCache is request-scoped) inherits naturally.
sjswerdloff
added a commit
to sjswerdloff/mlxcel
that referenced
this pull request
Jun 25, 2026
The architectural completion: SparseAttention::forward() now correctly handles chunked-prefill / cached cases. Key changes: - Compute kv_len = cache_offset + l BEFORE update_and_fetch, so the asymmetric block counts are derived from the FULL cached length, not just the current chunk's length. - num_query_blocks vs num_key_blocks throughout: Q padded to num_query_blocks*block_size, K/V padded to num_key_blocks*block_size, reshape sites updated accordingly. - cache.m3_idx_k_update_and_fetch(&idx_k) (from lablup#80) swaps the current-chunk-only idx_k for the FULL cached idx_k. This closes the architectural gap behind the cycle-65 latent comment: top-k block selection now scores ALL num_key_blocks blocks, including the cached prefix that pre-lablup#81 was invisible to the indexer. - New apply_causal_block_mask_asymmetric: per-query-block max attendable absolute key block = floor((cache_offset + (i+1)*block_size - 1) / block_size). Over-permissive at block level; sparse_sdpa's unified mask trims within-block future positions. - New ensure_local_block_score_asymmetric: forces top-k to include the cached-prefix's last few absolute blocks (the query's local neighbourhood), which sit BEFORE the current chunk in absolute coords. - Dispatch dense when num_key_blocks <= top_k (top-k saturates → no sparsity benefit, dense is at least as good). - selected has shape [b, num_kv_heads, num_query_blocks, top_k] with ABSOLUTE key block indices in [0, num_key_blocks). sparse_sdpa's asymmetric path consumes them correctly. Symmetric apply_causal_block_mask + ensure_local_block_score marked #[allow(dead_code)] for regression value; the asymmetric forms subsume them at cache_offset=0. Deletion planned after lablup#78-lablup#83 lands and the asymmetric forms have lived without regressions. Cycle 65's "Unreachable under default prefill_chunk_size=512, hence latent until now" comment in cycle 65's code is now obsolete — the cached-prefill path is exercised on every forward with non-empty cache. 14 mask tests pass (7 symmetric regression + 7 asymmetric). Integration test for the actual four-chunk forward-attention path is task lablup#82; this commit wires the path, the test in lablup#82 verifies correctness against dense single-shot.
sjswerdloff
added a commit
to sjswerdloff/mlxcel
that referenced
this pull request
Jun 26, 2026
The cycle 79 root bug, but exposed via a different path: when the scheduler adopts a cached KV entry (CacheEntry stores main K/V only), the main cache.offset is restored to the adopted length, but m3_idx_offset (the indexer K cache I added in lablup#80) stays at 0 — the CacheEntry has no awareness of the M3-specific indexer state. The next forward() then has cache.offset=23248 and m3_idx_offset=0. m3_idx_k_update_and_fetch produces just the current chunk's idx_k (315 positions). Padded to padded_k_len=23680, the buffer has only 432 positions, but the reshape expects 23680. Crash: `Cannot reshape array of size 55296 into shape (1,1,185,128,128)`. Detection: BEFORE the indexer projection, check whether the indexer offset is in lockstep with the main K/V offset: cache.m3_idx_offset() == cache.offset - l holds in the normal path (no adoption) and after every prior forward() since the indexer cache append is in lockstep with main K cache update. Adoption breaks the invariant. When broken, fall back to dense. Cost: dense attention for the first turn after a cache-adoption hit (O(q_len * kv_len) instead of MSA's selected-blocks math). Acceptable band-aid. Proper fix is to extend CacheEntry to carry the m3_idx_k state alongside main K/V so adoption preserves it — track separately.
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
Add RT-DETRv2, a real-time detection transformer, to mlxcel. This is a new task type: the model emits bounding boxes (left, top, right, bottom, label, confidence) rather than a token stream, so it lives outside the LanguageModel/generate flow and is exposed through a new top-level `mlxcel detect` subcommand. Ported from the upstream mlx-vlm RT-DETRv2 model (PR lablup#1195). Architecture: - ResNet-50-vd / ResNet-101-vd backbone (3-conv stem, stride-2 maxpool, AvgPool-based vd downsampling shortcuts), with depth read from the backbone config so both variants share one module. - Hybrid encoder: an AIFI transformer on the deepest level (2D sine position embedding), a top-down FPN, and a bottom-up PAN with RepVGG/CSPRep blocks. - Encoder query selection (top-K over the flattened position-by-label score space) feeding a six-layer deformable-attention decoder with iterative bbox refinement. - Multi-scale deformable attention via a pure-MLX bilinear grid_sample (padding zeros, align_corners false). The whole forward path runs in float32 for box-coordinate precision; weights stay in their stored dtype (bf16) so the float32-input by bf16-weight promotion matches the reference. The HF-to-MLX weight rename pipeline runs only when raw HF layout is detected, so pre-converted checkpoints load as-is. Detection is a new `mlxcel detect` subcommand (`--model`, `--image`, `--threshold`, `--format text|json`) rather than an overload of `generate` or `serve`, because the output is boxes, not tokens. The existing model-type classification module is left untouched; this model registers no new generate-flow model type. New module `src/vision/detection/rt_detr_v2/` (config, sanitize, shared layers, backbone, hybrid_encoder, transformer, model, processor, predictor) plus `src/commands/detect.rs` and the `detect` subcommand wiring in `src/main.rs`. Verified with cargo fmt, cargo clippy (metal,accelerate, all-targets, -D warnings), and 22 unit tests covering grid_sample, max and average pool, nearest upsample, anchor generation, the inverse-sigmoid round-trip, the rename pipeline, and config parsing.
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
Bump version to 0.0.31. Highlights: MiniCPM-V 4.6 and RT-DETRv2 model support plus an Anthropic-style /v1/messages API endpoint (lablup#82, lablup#80, lablup#74); fixes for missing or null chat-message content, Gemma 3n VLM per_layer_inputs, Qwen3.5 MTP verify attention, and batched quantized KV cache mask offsets (lablup#91, lablup#86, lablup#78, lablup#76); and a pinned 1.93.1 Rust toolchain (lablup#87, lablup#90).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #79
Adds RT-DETRv2, a real-time detection transformer. This is a new task type: the model emits bounding boxes
(left, top, right, bottom, label, confidence)rather than a token stream, so it lives outside the LanguageModel/generate flow and is exposed through a new top-levelmlxcel detectsubcommand. Ported from the upstream mlx-vlm RT-DETRv2 model (PR #1195).Architecture
Notes
mlxcel detect(--model,--image,--threshold,--format text|json) is a separate subcommand rather than an overload ofgenerate/serve, because the output is boxes, not tokens.Files
New
src/vision/detection/rt_detr_v2/(config, sanitize, layers, backbone, hybrid_encoder, transformer, model, processor, predictor) plussrc/commands/detect.rsand thedetectwiring insrc/main.rs.Verification
cargo fmt --checkclean.cargo clippy --features metal,accelerate --all-targets -- -D warningsclean.