diff --git a/docs/TESTING.md b/docs/TESTING.md index d05fb2fb4d..1995352d4f 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -27,3 +27,17 @@ Run `python -m pytest -q tests/test_scheduler.py tests/test_scheduler_boundary_c Run `python -m pytest -q tests/test_cluster_pairing_session.py tests/test_cluster_pairing.py tests/test_cluster_ui_integration.py tests/ui/test_cluster_v2_wizard.py` to check joining, cancellation, and approval. Session tests recreate a manager with the same base path to verify that the original code and cancellation proof survive a restart. They also cover offline cancellation, switching peers while cleanup is pending, rejected requests versus lost responses, and storage failures. Wizard tests check that delayed responses cannot restore a cancelled join and that pending cleanup leaves new pairing controls available. For a two-Mac smoke test, start isolated servers with separate base paths. Request a join, restart only the joining server, then cancel and retry; the coordinator must remove the original pending request. Repeat with the coordinator offline: cancellation must return `state: idle` with `cleanup_pending: true`, and joining a different reachable Mac must work. Restore the coordinator and poll the join endpoint to verify cleanup. Keep existing approval/cancel race and token-ownership tests in the run; never relax the coordinator's token check to make a stale request disappear. + +# DeepSeek V4.1 offline tests + +Run `python -m pytest -q tests/test_deepseek_v41.py` for the text/vision port. Synthetic weights and small recorded official outputs cover prefill/decode, DSpark, Engram and vision numerics without a checkpoint download or vendored reference implementation. See `tests/fixtures/deepseek_v41_expected.md` for provenance and reference corrections. PyTorch is optional for the independent FP8/FP4 arithmetic checks. Other cases cover BatchGenerator admission, cache restoration, DSML and VLM engine execution. + +FP8 activation boundary and layout checks: `python -m pytest tests/test_deepseek_v41_activation.py -q`. These compare fused FP8 and weighted SwiGLU kernels against reference arithmetic across rounding ties, scale transitions, clipping, intermediate casts and floating-point dtypes. + +MoE activation reuse and per-expert reference checks: `python -m pytest tests/test_deepseek_v41_moe.py -q`. These cover sorted prefill, decode, independent routed/shared activation policies, and repeated outputs with small quantized weights. + +DeepSeek V4.1 Metal arithmetic and sparse-addressing checks: `python -m pytest tests/test_deepseek_v41_kernels.py -q` (no checkpoint required). + +Packed attention rounding: `python -m pytest tests/test_deepseek_v41_attention_rounding.py -q`. An independent MLX oracle checks 64-key online maxima, FP32 denominators, BF16 PV probabilities, masking, sink placement, and growing or strided KV across the threadgroup capacity boundary. This does not execute the official CUDA kernels. + +Engram storage and prefetch lifecycle: `python -m pytest tests/test_deepseek_v41_offload.py -q`. Modal state, forced-toggle behavior, and save payload: `node --test tests/deepseek_v41_offload_ui.test.cjs`. Both use synthetic fixtures and require no checkpoint download. diff --git a/omlx/adapter/output_parser.py b/omlx/adapter/output_parser.py index 17da351d99..346325cadd 100644 --- a/omlx/adapter/output_parser.py +++ b/omlx/adapter/output_parser.py @@ -513,6 +513,12 @@ class DeepSeekV4OutputParserSession: def __init__(self, tokenizer: Any, model_path: str | None = None): self._tokenizer = tokenizer + self._tool_start = ( + getattr(tokenizer, "tool_call_start", None) or _DEEPSEEK_V4_TOOL_CALL_START + ) + self._tool_end = ( + getattr(tokenizer, "tool_call_end", None) or _DEEPSEEK_V4_TOOL_CALL_END + ) self._raw_text = "" self._stopped = False self._detokenizer = create_streaming_detokenizer(tokenizer, model_path) @@ -545,13 +551,13 @@ def _finish_filtered_text(self, tool_filter: Any) -> str: return tool_filter.finish() def _trim_at_first_tool_block_end(self, text: str) -> tuple[str, bool]: - start_idx = text.find(_DEEPSEEK_V4_TOOL_CALL_START) + start_idx = text.find(self._tool_start) if start_idx < 0: return text, False - end_idx = text.find(_DEEPSEEK_V4_TOOL_CALL_END, start_idx) + end_idx = text.find(self._tool_end, start_idx) if end_idx < 0: return text, False - cutoff = end_idx + len(_DEEPSEEK_V4_TOOL_CALL_END) + cutoff = end_idx + len(self._tool_end) return text[:cutoff], True def process_token(self, token_id: int) -> OutputParserTokenResult: @@ -1396,6 +1402,18 @@ def detect_output_parser( ), ) + if getattr(tokenizer, "tool_call_start", None) == "<|DSML| calls>": + from ..patches.deepseek_v41.output_parser import DeepSeekV41OutputParserSession + + return OutputParserFactory( + kind="deepseek_v41", + create_session=lambda session_tokenizer: DeepSeekV41OutputParserSession( + session_tokenizer, model_path=session_model_path + ), + stop_token_ids=set(), + protocol_marker_texts=("<|DSML| calls>", ""), + ) + if _is_deepseek_v4_model(model_name, tokenizer, model_config): return OutputParserFactory( kind="deepseek_v4", diff --git a/omlx/admin/i18n/en.json b/omlx/admin/i18n/en.json index ccf74ab650..7f736e6556 100644 --- a/omlx/admin/i18n/en.json +++ b/omlx/admin/i18n/en.json @@ -653,6 +653,9 @@ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)", "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.", "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", + "modal.model_settings.deepseek_v41_engram_ssd_offload": "SSD N-gram Offload (DeepSeek V4.1)", + "modal.model_settings.deepseek_v41_engram_ssd_offload_hint": "Keep Engram tables on SSD and prefetch required rows. Saves memory; speed depends on SSD reads. Changing this setting reloads the model.", + "modal.model_settings.deepseek_v41_engram_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", "modal.model_settings.thinking_budget": "Thinking Budget", "modal.model_settings.thinking_budget_hint": "Limit thinking tokens for reasoning models. Forces end of thinking when exceeded.", "modal.model_settings.thinking_budget_placeholder": "e.g. 4096", diff --git a/omlx/admin/i18n/es.json b/omlx/admin/i18n/es.json index 5c70b532bd..c801a98936 100644 --- a/omlx/admin/i18n/es.json +++ b/omlx/admin/i18n/es.json @@ -653,6 +653,9 @@ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)", "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.", "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", + "modal.model_settings.deepseek_v41_engram_ssd_offload": "SSD N-gram Offload (DeepSeek V4.1)", + "modal.model_settings.deepseek_v41_engram_ssd_offload_hint": "Keep Engram tables on SSD and prefetch required rows. Saves memory; speed depends on SSD reads. Changing this setting reloads the model.", + "modal.model_settings.deepseek_v41_engram_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", "modal.model_settings.thinking_budget": "Presupuesto de Pensamiento", "modal.model_settings.thinking_budget_hint": "Limitar tokens de pensamiento para modelos de razonamiento. Fuerza el fin del pensamiento al excederse.", "modal.model_settings.thinking_budget_placeholder": "ej. 4096", diff --git a/omlx/admin/i18n/fr.json b/omlx/admin/i18n/fr.json index 04311ef667..9e8dd62c11 100644 --- a/omlx/admin/i18n/fr.json +++ b/omlx/admin/i18n/fr.json @@ -653,6 +653,9 @@ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)", "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.", "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", + "modal.model_settings.deepseek_v41_engram_ssd_offload": "SSD N-gram Offload (DeepSeek V4.1)", + "modal.model_settings.deepseek_v41_engram_ssd_offload_hint": "Keep Engram tables on SSD and prefetch required rows. Saves memory; speed depends on SSD reads. Changing this setting reloads the model.", + "modal.model_settings.deepseek_v41_engram_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", "modal.model_settings.thinking_budget": "Budget de réflexion", "modal.model_settings.thinking_budget_hint": "Limitez les tokens de réflexion pour les modèles de raisonnement. Force la fin de la réflexion lorsque dépassé.", "modal.model_settings.thinking_budget_placeholder": "par ex. 4096", diff --git a/omlx/admin/i18n/ja.json b/omlx/admin/i18n/ja.json index f716fa8cf3..db6e5a9971 100644 --- a/omlx/admin/i18n/ja.json +++ b/omlx/admin/i18n/ja.json @@ -653,6 +653,9 @@ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)", "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.", "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", + "modal.model_settings.deepseek_v41_engram_ssd_offload": "SSD N-gram Offload (DeepSeek V4.1)", + "modal.model_settings.deepseek_v41_engram_ssd_offload_hint": "Keep Engram tables on SSD and prefetch required rows. Saves memory; speed depends on SSD reads. Changing this setting reloads the model.", + "modal.model_settings.deepseek_v41_engram_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", "modal.model_settings.thinking_budget": "思考トークン制限", "modal.model_settings.thinking_budget_hint": "推論モデルの思考トークン数を制限します。超過時に思考を強制終了します。", "modal.model_settings.thinking_budget_placeholder": "例: 4096", diff --git a/omlx/admin/i18n/ko.json b/omlx/admin/i18n/ko.json index 51cf8ac09a..4fac2ba235 100644 --- a/omlx/admin/i18n/ko.json +++ b/omlx/admin/i18n/ko.json @@ -653,6 +653,9 @@ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram 오프로딩 (Qwen4 전용)", "modal.model_settings.qwen4_ple_ssd_offload_hint": "큰 PLE N-gram 테이블을 SSD에 두고 필요한 행만 읽습니다. 메모리를 절약하지만 컨텍스트가 바뀐 뒤 prefill이 느려질 수 있습니다.", "modal.model_settings.qwen4_ple_ssd_offload_forced": "resident 로드가 설정된 모델 메모리 한도를 초과하므로 이 옵션이 필요합니다.", + "modal.model_settings.deepseek_v41_engram_ssd_offload": "SSD N-gram 오프로딩 (DeepSeek V4.1)", + "modal.model_settings.deepseek_v41_engram_ssd_offload_hint": "Engram 테이블을 SSD에 두고 필요한 행을 미리 읽습니다. 메모리를 절약하며 속도는 SSD 읽기 성능에 따라 달라집니다. 변경 시 모델을 다시 로드합니다.", + "modal.model_settings.deepseek_v41_engram_ssd_offload_forced": "메모리 상주 시 설정된 모델 메모리 한도를 초과하므로 필수로 활성화됩니다.", "modal.model_settings.thinking_budget": "Thinking 토큰 제한", "modal.model_settings.thinking_budget_hint": "추론 모델의 thinking 토큰 수를 제한합니다. 초과 시 thinking을 강제 종료합니다.", "modal.model_settings.thinking_budget_placeholder": "예: 4096", diff --git a/omlx/admin/i18n/pt-BR.json b/omlx/admin/i18n/pt-BR.json index 53c3117d2d..ebdcba1ba2 100644 --- a/omlx/admin/i18n/pt-BR.json +++ b/omlx/admin/i18n/pt-BR.json @@ -653,6 +653,9 @@ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)", "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.", "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", + "modal.model_settings.deepseek_v41_engram_ssd_offload": "SSD N-gram Offload (DeepSeek V4.1)", + "modal.model_settings.deepseek_v41_engram_ssd_offload_hint": "Keep Engram tables on SSD and prefetch required rows. Saves memory; speed depends on SSD reads. Changing this setting reloads the model.", + "modal.model_settings.deepseek_v41_engram_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", "modal.model_settings.thinking_budget": "Orçamento de Raciocínio", "modal.model_settings.thinking_budget_hint": "Limitar tokens de raciocínio para modelos de reasoning. Força o fim do raciocínio quando excedido.", "modal.model_settings.thinking_budget_placeholder": "ex: 4096", diff --git a/omlx/admin/i18n/ru.json b/omlx/admin/i18n/ru.json index f7d708106e..41ca3747da 100644 --- a/omlx/admin/i18n/ru.json +++ b/omlx/admin/i18n/ru.json @@ -653,6 +653,9 @@ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)", "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.", "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", + "modal.model_settings.deepseek_v41_engram_ssd_offload": "SSD N-gram Offload (DeepSeek V4.1)", + "modal.model_settings.deepseek_v41_engram_ssd_offload_hint": "Keep Engram tables on SSD and prefetch required rows. Saves memory; speed depends on SSD reads. Changing this setting reloads the model.", + "modal.model_settings.deepseek_v41_engram_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", "modal.model_settings.thinking_budget": "Бюджет мышления", "modal.model_settings.thinking_budget_hint": "Ограничьте число токенов мышления для моделей рассуждения. Принудительно завершает мышление при превышении лимита.", "modal.model_settings.thinking_budget_placeholder": "например, 4096", diff --git a/omlx/admin/i18n/zh-TW.json b/omlx/admin/i18n/zh-TW.json index c500d30a73..419a9e18d4 100644 --- a/omlx/admin/i18n/zh-TW.json +++ b/omlx/admin/i18n/zh-TW.json @@ -653,6 +653,9 @@ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)", "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.", "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", + "modal.model_settings.deepseek_v41_engram_ssd_offload": "SSD N-gram Offload (DeepSeek V4.1)", + "modal.model_settings.deepseek_v41_engram_ssd_offload_hint": "Keep Engram tables on SSD and prefetch required rows. Saves memory; speed depends on SSD reads. Changing this setting reloads the model.", + "modal.model_settings.deepseek_v41_engram_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", "modal.model_settings.thinking_budget": "思考 Token 限制", "modal.model_settings.thinking_budget_hint": "限制推理模型的思考 Token 數量,超出時強制結束思考", "modal.model_settings.thinking_budget_placeholder": "例如 4096", diff --git a/omlx/admin/i18n/zh.json b/omlx/admin/i18n/zh.json index 5d37e12292..ddf1a9df9f 100644 --- a/omlx/admin/i18n/zh.json +++ b/omlx/admin/i18n/zh.json @@ -653,6 +653,9 @@ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)", "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.", "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", + "modal.model_settings.deepseek_v41_engram_ssd_offload": "SSD N-gram Offload (DeepSeek V4.1)", + "modal.model_settings.deepseek_v41_engram_ssd_offload_hint": "Keep Engram tables on SSD and prefetch required rows. Saves memory; speed depends on SSD reads. Changing this setting reloads the model.", + "modal.model_settings.deepseek_v41_engram_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.", "modal.model_settings.thinking_budget": "思考 Token 限制", "modal.model_settings.thinking_budget_hint": "限制推理模型的思考 Token 数量,超出时强制结束思考", "modal.model_settings.thinking_budget_placeholder": "例如 4096", diff --git a/omlx/admin/oq_manager.py b/omlx/admin/oq_manager.py index 2f452cb17e..c5be618f2b 100644 --- a/omlx/admin/oq_manager.py +++ b/omlx/admin/oq_manager.py @@ -240,6 +240,7 @@ def _scan() -> tuple[list[dict], list[dict]]: if not mt: continue tc = config.get("text_config", {}) + is_v41 = config.get("model_type") == "deepseek_v41" has_mtp = _has_mtp_heads( config ) and _checkpoint_has_mtp_weights(path) @@ -251,7 +252,8 @@ def _scan() -> tuple[list[dict], list[dict]]: "size_formatted": _format_size(size), "model_type": config.get("model_type", "") or tc.get("model_type", ""), - "is_quantized": "quantization" in config, + "is_quantized": "quantization" in config + or "omlx_deepseek_v41" in config, # Treat vision_config / vit_config / mm_vision_tower as VLM # evidence (Molmo / Molmo2 use vit_config; FastVLM uses # mm_vision_tower). Same predicate as model_discovery. @@ -259,6 +261,7 @@ def _scan() -> tuple[list[dict], list[dict]]: "has_mtp_heads": has_mtp, "hidden_size": tc.get("hidden_size") or config.get("hidden_size") + or (tc.get("dim") if is_v41 else 0) or 0, } all_models.append(info) @@ -270,6 +273,11 @@ def _scan() -> tuple[list[dict], list[dict]]: info_full["num_experts"] = config.get( "num_local_experts", 0 ) + if is_v41: + info_full["num_layers"] = ( + info_full["num_layers"] or tc.get("n_layers", 0) + ) + info_full["num_experts"] = tc.get("n_routed_experts", 0) info_full["memory_streaming"] = estimate_memory(size) source_models.append(info_full) except Exception: diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py index 682b6e8aa5..24f516c745 100644 --- a/omlx/admin/routes.py +++ b/omlx/admin/routes.py @@ -239,6 +239,7 @@ class ModelSettingsRequest(BaseModel): # template supports it). Mirrors ModelSettings.preserve_thinking. preserve_thinking: bool | None = None qwen4_ple_ssd_offload: bool | None = None + deepseek_v41_engram_ssd_offload: bool | None = None thinking_budget_enabled: bool | None = None thinking_budget_tokens: int | None = None # MTP draft tokens per cycle for legacy MTP (None = adaptive default). @@ -2110,6 +2111,34 @@ async def list_models(is_admin: bool = Depends(require_admin)): exc_info=True, ) + deepseek_v41_engram_ssd_offload_supported = False + deepseek_v41_engram_ssd_offload_forced = False + v41_resident_bytes = 0 + v41_mmap_bytes = 0 + if (model_info.get("config_model_type") or "").replace( + "-", "_" + ).lower() == "deepseek_v41": + try: + from ..patches.deepseek_v41.residency import ( + deepseek_v41_residency_estimate, + ) + + estimate = deepseek_v41_residency_estimate( + model_info.get("model_path", "") + ) + deepseek_v41_engram_ssd_offload_supported = estimate.supported + deepseek_v41_engram_ssd_offload_forced = estimate.force_ssd_offload( + residency_ceiling + ) + v41_resident_bytes = estimate.resident_bytes + v41_mmap_bytes = estimate.mmap_bytes + except (KeyError, OSError, TypeError, ValueError): + logger.debug( + "Could not inspect DeepSeek V4.1 Engram residency for %s", + model_id, + exc_info=True, + ) + model_data = { "id": model_id, "model_path": model_info.get("model_path", ""), @@ -2165,6 +2194,10 @@ async def list_models(is_admin: bool = Depends(require_admin)): "qwen4_ple_ssd_offload_forced": qwen4_ple_ssd_offload_forced, "qwen4_ple_resident_bytes": qwen4_resident_bytes, "qwen4_ple_mmap_bytes": qwen4_mmap_bytes, + "deepseek_v41_engram_ssd_offload_supported": deepseek_v41_engram_ssd_offload_supported, + "deepseek_v41_engram_ssd_offload_forced": deepseek_v41_engram_ssd_offload_forced, + "deepseek_v41_engram_resident_bytes": v41_resident_bytes, + "deepseek_v41_engram_mmap_bytes": v41_mmap_bytes, "is_paroquant": is_paroquant, "paroquant_reason": paroquant_reason, } @@ -2498,6 +2531,13 @@ async def update_model_settings( current_settings.qwen4_ple_ssd_offload = bool( request.qwen4_ple_ssd_offload and is_qwen4_exp ) + if "deepseek_v41_engram_ssd_offload" in sent: + is_deepseek_v41 = (entry.config_model_type or "").replace( + "-", "_" + ).lower() == "deepseek_v41" + current_settings.deepseek_v41_engram_ssd_offload = bool( + request.deepseek_v41_engram_ssd_offload and is_deepseek_v41 + ) if "thinking_budget_enabled" in sent: current_settings.thinking_budget_enabled = ( request.thinking_budget_enabled or False diff --git a/omlx/admin/static/js/dashboard.js b/omlx/admin/static/js/dashboard.js index 4ca40cc583..cf683a4bf6 100644 --- a/omlx/admin/static/js/dashboard.js +++ b/omlx/admin/static/js/dashboard.js @@ -1667,6 +1667,14 @@ model?.qwen4_ple_ssd_offload_supported === true, qwen4_ple_ssd_offload_forced: model?.qwen4_ple_ssd_offload_forced === true, + deepseek_v41_engram_ssd_offload: model?.deepseek_v41_engram_ssd_offload_forced === true + || s.deepseek_v41_engram_ssd_offload === true, + deepseek_v41_engram_ssd_offload_requested: + s.deepseek_v41_engram_ssd_offload === true, + deepseek_v41_engram_ssd_offload_supported: + model?.deepseek_v41_engram_ssd_offload_supported === true, + deepseek_v41_engram_ssd_offload_forced: + model?.deepseek_v41_engram_ssd_offload_forced === true, enableThinkingBudget: !!(s.thinking_budget_tokens), thinking_budget_tokens: s.thinking_budget_tokens || null, guided_grammar_enabled: s.guided_grammar_enabled || false, @@ -2606,6 +2614,10 @@ enable_thinking: this.selectedModel?.thinking_forced ? null : this.modelSettings.enable_thinking, qwen4_ple_ssd_offload: !!this.modelSettings.qwen4_ple_ssd_offload, + deepseek_v41_engram_ssd_offload: + this.modelSettings.deepseek_v41_engram_ssd_offload_forced + ? !!this.modelSettings.deepseek_v41_engram_ssd_offload_requested + : !!this.modelSettings.deepseek_v41_engram_ssd_offload, thinking_budget_enabled: this.modelSettings.enableThinkingBudget, thinking_budget_tokens: this.modelSettings.enableThinkingBudget ? (this.modelSettings.thinking_budget_tokens || null) diff --git a/omlx/admin/templates/dashboard/_modal_model_settings.html b/omlx/admin/templates/dashboard/_modal_model_settings.html index fbe0e20912..db9e29b437 100644 --- a/omlx/admin/templates/dashboard/_modal_model_settings.html +++ b/omlx/admin/templates/dashboard/_modal_model_settings.html @@ -475,6 +475,30 @@

{{ class="text-xs text-amber-600">{{ t('modal.model_settings.qwen4_ple_ssd_offload_forced') }}

+ +
+
+
+ {{ t('modal.model_settings.deepseek_v41_engram_ssd_offload') }} +

{{ t('modal.model_settings.deepseek_v41_engram_ssd_offload_hint') }}

+
+ +
+

{{ t('modal.model_settings.deepseek_v41_engram_ssd_offload_forced') }}

+
+
diff --git a/omlx/api/openai_models.py b/omlx/api/openai_models.py index 4cfb779d32..1e7e452906 100644 --- a/omlx/api/openai_models.py +++ b/omlx/api/openai_models.py @@ -13,7 +13,7 @@ import json from typing import Any, Dict, List, Optional, Union -from pydantic import AliasChoices, BaseModel, Field, field_validator +from pydantic import AliasChoices, BaseModel, Field, field_validator, model_validator from omlx.api.shared_models import ( BaseUsage, @@ -203,6 +203,37 @@ def _validate_arguments_json(cls, v: Any) -> str: return _coerce_tool_call_arguments(v) +def _normalize_tool_namespace(value: Any) -> Any: + """Represent explicit tool namespaces in the OpenAI function name.""" + if not isinstance(value, dict) or not isinstance(value.get("function"), dict): + return value + function = value["function"] + namespace = value.get("namespace", function.get("namespace")) + if namespace is None: + return value + description = namespace.get("description") if isinstance(namespace, dict) else None + if description is not None and not isinstance(description, str): + raise ValueError("Tool namespace description must be a string") + namespace = namespace.get("name") if isinstance(namespace, dict) else namespace + if not isinstance(namespace, str) or not namespace or "::" in namespace: + raise ValueError("Tool namespace must be a nonempty name without '::'") + name = function.get("name", "") + if not isinstance(name, str) or not name: + raise ValueError("Namespaced tool requires a function name") + if "::" in name: + prefix, name = name.split("::", 1) + if prefix != namespace or not name or "::" in name: + raise ValueError("Conflicting tool namespace and qualified name") + function = {**function, "name": f"{namespace}::{name}"} + function.pop("namespace", None) + if description: + function_description = function.get("description") + if function_description is not None and not isinstance(function_description, str): + raise ValueError("Tool function description must be a string") + function["description"] = description + "\n" + (function_description or "") + return {**value, "function": function} + + class ToolCall(BaseModel): """A tool call from the model.""" @@ -210,6 +241,11 @@ class ToolCall(BaseModel): type: str = "function" function: FunctionCall + @model_validator(mode="before") + @classmethod + def _normalize_namespace(cls, value: Any) -> Any: + return _normalize_tool_namespace(value) + class ToolDefinition(BaseModel): """Definition of a tool that can be called by the model.""" @@ -217,6 +253,11 @@ class ToolDefinition(BaseModel): type: str = "function" function: dict + @model_validator(mode="before") + @classmethod + def _normalize_namespace(cls, value: Any) -> Any: + return _normalize_tool_namespace(value) + # ============================================================================= # Structured Output (JSON Schema) diff --git a/omlx/api/tool_calling.py b/omlx/api/tool_calling.py index a7460cc48c..28ac1d5fb5 100644 --- a/omlx/api/tool_calling.py +++ b/omlx/api/tool_calling.py @@ -1575,7 +1575,7 @@ def parse_tool_calls( return cleaned_text, tool_calls or None cleaned_text, tool_calls = _parse_tool_calls_impl(text, tokenizer, tools) - if tool_calls: + if tool_calls and getattr(tokenizer, "tool_call_start", None) != "<|DSML| calls>": _remap_tool_call_names(tool_calls, tools) return cleaned_text, tool_calls @@ -1768,6 +1768,9 @@ def sanitize_tool_call_markup(text: str, tokenizer: Any) -> str: """Remove tool-call control markup while preserving surrounding prose.""" if not text: return "" + if getattr(tokenizer, "tool_call_start", None) == "<|DSML| calls>": + # V4.1 requires calls after ; reasoning is opaque text. + return text.strip() # Every caller sanitizes thinking-channel text; keep it byte-identical # with the streamed reasoning deltas, which do not consume DeepSeek @@ -1816,7 +1819,11 @@ def extract_tool_calls_with_thinking( cleaned_thinking = sanitize_tool_call_markup(thinking_content, tokenizer) tool_calls_from_thinking = False - if not tool_calls and thinking_content: + if ( + not tool_calls + and thinking_content + and getattr(tokenizer, "tool_call_start", None) != "<|DSML| calls>" + ): _, tool_calls = parse_tool_calls(thinking_content, tokenizer, tools) tool_calls_from_thinking = bool(tool_calls) @@ -1933,6 +1940,9 @@ def __init__( ): marker = getattr(tokenizer, "tool_call_start", None) marker_end = getattr(tokenizer, "tool_call_end", None) + self._opaque_reasoning = ( + not consume_dsml_separator and marker == "<|DSML| calls>" + ) # Normalize None-like values but preserve empty strings. if marker is None: marker = "" @@ -2631,6 +2641,8 @@ def _unwind_withheld_at_eof( def feed(self, text: str) -> str: """Feed a content delta, return the portion safe to emit.""" + if self._opaque_reasoning: + return text if self._suppressing or not text: return "" if self._ifm_pending_parts is not None: @@ -2725,6 +2737,8 @@ def finish(self) -> str: In clean-output strict mode, unresolved marker-like suffixes are dropped so partial control markup does not leak into user-visible text. """ + if self._opaque_reasoning: + return "" if self._ifm_pending_parts is not None: raw = "".join(self._ifm_pending_parts) self._ifm_pending_parts = None diff --git a/omlx/cache/boundary_snapshot_store.py b/omlx/cache/boundary_snapshot_store.py index 86a5df602e..744383a332 100644 --- a/omlx/cache/boundary_snapshot_store.py +++ b/omlx/cache/boundary_snapshot_store.py @@ -30,6 +30,7 @@ from pathlib import Path from typing import Any +from .deepseek_v41_delta import compact_snapshot as compact_deepseek_v41_snapshot from .paged_ssd_cache import ( HAS_MLX, _encode_shape, @@ -265,6 +266,7 @@ def save( return False if block_size is not None: compact_pooling_cache_snapshot(extracted, token_count, block_size) + compact_deepseek_v41_snapshot(extracted, token_count, block_size) # 2. Flatten tensors + metadata for safetensors serialization. tensors_raw, metadata = self._serialize_extracted( @@ -1266,7 +1268,9 @@ def _serialize_extracted( info[f"sub_{j}_missing_{k}"] = "1" continue if _has_zero_dim(elem): - arrays[f"layer_{i}_sub_{j}_state_{k}"] = mx.zeros((1,)) + arrays[f"layer_{i}_sub_{j}_state_{k}"] = mx.zeros( + (1,), dtype=elem.dtype + ) info[f"sub_{j}_zero_dim_{k}"] = _encode_shape(elem.shape) else: arrays[f"layer_{i}_sub_{j}_state_{k}"] = elem @@ -1285,7 +1289,9 @@ def _serialize_extracted( info[f"missing_{k}"] = "1" continue if _has_zero_dim(elem): - arrays[f"layer_{i}_state_{k}"] = mx.zeros((1,)) + arrays[f"layer_{i}_state_{k}"] = mx.zeros( + (1,), dtype=elem.dtype + ) info[f"zero_dim_{k}"] = _encode_shape(elem.shape) else: key = f"layer_{i}_state_{k}" diff --git a/omlx/cache/deepseek_v41_delta.py b/omlx/cache/deepseek_v41_delta.py new file mode 100644 index 0000000000..78b5f12abf --- /dev/null +++ b/omlx/cache/deepseek_v41_delta.py @@ -0,0 +1,141 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Storage-only block deltas for DeepSeek V4.1's packed cumulative state.""" + +try: + import mlx.core as mx +except ImportError: + mx = None + +DELTA_CLASS = "DeepseekV41Delta" +CACHE_CLASS = "DeepseekV41Cache" + + +def _ratio(meta): + if tuple(meta) == ("deepseek_v41", "2"): + return None # Legacy full snapshots remain readable without compaction. + if tuple(meta[:2]) != ("deepseek_v41", "3") or len(meta) != 3: + raise ValueError("Unknown V4.1 cache metadata") + ratio = int(meta[2]) + if ratio < 0: + raise ValueError("Invalid V4.1 compression ratio") + return ratio + + +def compact_state(state, meta, start, end): + """Return bounded state plus one block's rows and an absolute range record.""" + ratio = _ratio(meta) + if ratio is None: + return state + if not 0 <= start < end: + raise ValueError("Invalid V4.1 snapshot token range") + row_start, row_end = (start // ratio, end // ratio) if ratio else (0, 0) + record = [1, start, end, row_start, row_end, ratio] + if len(state) == 8: + if state[7].tolist() != record: + raise ValueError("V4.1 delta belongs to another boundary") + return state + if len(state) != 7 or state[0].tolist() != [end]: + raise ValueError("V4.1 snapshot offset does not match its boundary") + result = list(state) + for slot in (2, 3): + value = state[slot] + if ( + value.ndim != 3 + or value.shape[:2] != (1, row_end) + or value.dtype != mx.uint8 + ): + raise ValueError("Invalid cumulative V4.1 packed state") + # Gather materializes only the delta; a contiguous slice may retain + # the entire cumulative allocation in an in-memory snapshot. + result[slot] = ( + mx.take(value, mx.arange(row_start, row_end), axis=1) + if row_end > row_start + else mx.zeros((1, 0, value.shape[2]), value.dtype) + ) + result.append(mx.array(record, mx.int64)) + return tuple(result) + + +def compact_snapshot(extracted, token_count, block_size): + """Compact temporary boundary files and in-memory boundary snapshots alike.""" + if token_count <= 0 or block_size <= 0: + return extracted + start = ((token_count - 1) // block_size) * block_size + for layer in extracted: + if layer.get("class_name") == CACHE_CLASS: + layer["state"] = compact_state( + layer["state"], layer.get("meta_state", ()), start, token_count + ) + return extracted + + +def restore_chain(markers, metas, token_count): + """Validate every absolute range before joining packed rows; reject gaps.""" + from ..patches.deepseek_v41.cache import DeepseekV41Cache + + parts = {2: [], 3: []} + cursor = rows = 0 + last = last_meta = None + for marker, meta in zip(markers, metas, strict=True): + if ( + not isinstance(marker, tuple) + or len(marker) != 3 + or marker[0] != "__nstate__" + ): + raise ValueError("Missing V4.1 boundary state") + name, state = marker[1:] + if name == CACHE_CLASS and len(state) == 7: + # A legacy full checkpoint can anchor a subsequent delta chain. + last, last_meta = list(state), meta + cursor = int(state[0].item()) + ratio = _ratio(meta) + if cursor <= 0 or state[0].shape != (1,): + raise ValueError("Invalid V4.1 full snapshot offset") + for slot in (2, 3): + if ( + state[slot].ndim != 3 + or state[slot].shape[0] != 1 + or state[slot].dtype != mx.uint8 + ): + raise ValueError("Invalid V4.1 full packed state") + rows = state[2].shape[1] + if state[3].shape[1] != rows or ( + ratio is not None and rows != (cursor // ratio if ratio else 0) + ): + raise ValueError("V4.1 KV/index lengths diverge") + parts = {slot: [state[slot]] for slot in (2, 3)} + continue + if name != DELTA_CLASS or len(state) != 8: + raise ValueError("Unknown V4.1 persisted state") + record = state[7] + if record.shape != (6,) or record.dtype != mx.int64: + raise ValueError("Invalid V4.1 delta range record") + version, start, end, first, stop, ratio = record.tolist() + if ( + version != 1 + or ratio != _ratio(meta) + or start != cursor + or end <= start + or first != rows + or (first, stop) != ((start // ratio, end // ratio) if ratio else (0, 0)) + or state[0].tolist() != [end] + ): + raise ValueError("Incomplete or out-of-order V4.1 delta chain") + if last_meta is not None and _ratio(last_meta) not in (None, ratio): + raise ValueError("V4.1 compression ratio changed across blocks") + for slot in (2, 3): + value = state[slot] + if ( + value.ndim != 3 + or value.shape[:2] != (1, stop - first) + or value.dtype != mx.uint8 + or (parts[slot] and value.shape[2:] != parts[slot][-1].shape[2:]) + ): + raise ValueError("V4.1 packed delta shape mismatch") + parts[slot].append(value) + cursor, rows, last, last_meta = end, stop, list(state[:7]), meta + if last is None or cursor != token_count: + raise ValueError("V4.1 restored offset does not match the cache hit") + for slot in (2, 3): + last[slot] = mx.concatenate(parts[slot], axis=1) + return DeepseekV41Cache.from_state(last, last_meta) diff --git a/omlx/cache/paged_ssd_cache.py b/omlx/cache/paged_ssd_cache.py index bb19fb52c7..1971797491 100644 --- a/omlx/cache/paged_ssd_cache.py +++ b/omlx/cache/paged_ssd_cache.py @@ -645,7 +645,7 @@ def _store_nstate_elements_flat( arrays[elem_key] = mx.zeros((1,)) cache_list_meta[f"{elem_key}_none"] = "1" elif _has_zero_dim(elem): - arrays[elem_key] = mx.zeros((1,)) + arrays[elem_key] = mx.zeros((1,), dtype=elem.dtype) cache_list_meta[f"{elem_key}_zero_dim"] = _encode_shape(elem.shape) elif ( isinstance(elem, tuple) @@ -732,7 +732,12 @@ def _load_nstate_flat( logger.error(f"Missing {elem_key} in arrays") return None if file_metadata and zd_marker in file_metadata: - elements.append(mx.zeros(_decode_shape(file_metadata[zd_marker]))) + elements.append( + mx.zeros( + _decode_shape(file_metadata[zd_marker]), + dtype=arrays[elem_key].dtype, + ) + ) else: elements.append(arrays[elem_key]) else: diff --git a/omlx/cache/prefix_cache.py b/omlx/cache/prefix_cache.py index d99805443d..c1927772ef 100644 --- a/omlx/cache/prefix_cache.py +++ b/omlx/cache/prefix_cache.py @@ -23,6 +23,9 @@ HAS_MLX = False from ._rotating_subclass import PrefillReadyRotatingKVCache +from .deepseek_v41_delta import DELTA_CLASS as V41_DELTA_CLASS +from .deepseek_v41_delta import compact_state as compact_v41_state +from .deepseek_v41_delta import restore_chain as restore_v41_chain from .hybrid_cache import ModelCacheConfig from .interface import CacheManager from .paged_cache import ( @@ -1678,6 +1681,15 @@ def _get_cache_seq_len(self, cache_data: list[dict[str, Any]]) -> int: if not cache_data: return 0 + # V4.1 stores packed rows and a bounded window rather than a 4D KV + # tensor. Its first state slot records the absolute token position, + # including any prefix restored before this request's prefill. + for layer in cache_data: + if layer.get("class_name") == "DeepseekV41Cache": + state = layer.get("state", ()) + if len(state) in (7, 8) and state[0].shape == (1,): + return int(state[0].item()) + # Non-sliceable cache types use sliding window or have no sequence dimension # RotatingKVCache: sliding window, seq_len limited to max_size # ArraysCache: no traditional sequence dimension @@ -2523,6 +2535,21 @@ def _slice_sub_elements(sub_state): if has_snapshot else layer_state["state"] ) + marker_class = cache_type_name + if cache_type_name == "DeepseekV41Cache": + source_layer = ( + snapshot_cache_data[layer_idx] + if has_snapshot + else layer_state + ) + state = compact_v41_state( + state, + source_layer.get("meta_state", ()), + start_idx, + end_idx, + ) + if len(state) == 8: + marker_class = V41_DELTA_CLASS if isinstance(state, (list, tuple)) and len(state) > 2: cloned = [ ( @@ -2532,7 +2559,7 @@ def _slice_sub_elements(sub_state): ) for elem in state ] - block_slices.append(("__nstate__", cache_type_name, cloned)) + block_slices.append(("__nstate__", marker_class, cloned)) elif isinstance(state, (list, tuple)) and len(state) >= 2: conv_state = ( state[0] if state[0] is not None else mx.array([]) @@ -4092,6 +4119,15 @@ def _is_non_sliceable_sub_class(class_name: str) -> bool: reconstructed_caches.append(cache) continue + if cache_type_name == "DeepseekV41Cache": + restored = restore_v41_chain( + [block[layer_idx] for block in all_block_data], + [metas[layer_idx] for metas in all_block_meta_states], + valid_token_count, + ) + reconstructed_caches.append(restored) + continue + # === Generic N-tuple non-sliceable cache: use latest boundary === if ( isinstance(last_block_layer_data, tuple) diff --git a/omlx/cache/type_handlers.py b/omlx/cache/type_handlers.py index a6a7f22c45..1a3617e3f2 100644 --- a/omlx/cache/type_handlers.py +++ b/omlx/cache/type_handlers.py @@ -34,6 +34,7 @@ class CacheType(Enum): BATCH_KVCACHE = "BatchKVCache" BATCH_ROTATING_KVCACHE = "BatchRotatingKVCache" ARRAYS_CACHE = "ArraysCache" + DEEPSEEK_V41 = "DeepseekV41Cache" QUANTIZED_KVCACHE = "QuantizedKVCache" CACHE_LIST = "CacheList" POOLING_CACHE = "PoolingCache" @@ -851,6 +852,10 @@ def reconstruct_cache( return None states = state.get("states", []) + if meta_state and tuple(meta_state) == ("deepseek_v41", "2"): + from ..patches.deepseek_v41.cache import DeepseekV41Cache + + return DeepseekV41Cache.from_state(states, meta_state) cache = ArraysCache(size=len(states)) for i, s in enumerate(states): cache.cache[i] = s diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/CMakeLists.txt b/omlx/custom_kernels/glm_moe_dsa/csrc/CMakeLists.txt index ad55edb8d7..fd35ad70b4 100644 --- a/omlx/custom_kernels/glm_moe_dsa/csrc/CMakeLists.txt +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/CMakeLists.txt @@ -34,6 +34,8 @@ target_sources( PRIVATE ${CMAKE_CURRENT_LIST_DIR}/dsa_indexer.cpp ${CMAKE_CURRENT_LIST_DIR}/deepseek_v4_sparse_attention.cpp + ${CMAKE_CURRENT_LIST_DIR}/deepseek_v41_packed_attention.cpp + ${CMAKE_CURRENT_LIST_DIR}/deepseek_v41_grouped_expert.cpp ${CMAKE_CURRENT_LIST_DIR}/dspark_gemm.cpp ${CMAKE_CURRENT_LIST_DIR}/dspark_qmv.cpp ${CMAKE_CURRENT_LIST_DIR}/exact_block_attention.cpp @@ -53,6 +55,7 @@ if(MLX_BUILD_METAL) set(OMLX_GLM_METAL_SOURCES ${CMAKE_CURRENT_LIST_DIR}/deepseek_moe.metal ${CMAKE_CURRENT_LIST_DIR}/deepseek_v4_sparse_attention.metal + ${CMAKE_CURRENT_LIST_DIR}/deepseek_v41_packed_attention.metal ${CMAKE_CURRENT_LIST_DIR}/dspark_gemm.metal ${CMAKE_CURRENT_LIST_DIR}/dspark_qmv.metal ${CMAKE_CURRENT_LIST_DIR}/dsa_indexer.metal diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/bindings.cpp b/omlx/custom_kernels/glm_moe_dsa/csrc/bindings.cpp index da6219a9e9..526b53410f 100644 --- a/omlx/custom_kernels/glm_moe_dsa/csrc/bindings.cpp +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/bindings.cpp @@ -5,6 +5,8 @@ #include "dsa_indexer.h" #include "deepseek_v4_sparse_attention.h" +#include "deepseek_v41_packed_attention.h" +#include "deepseek_v41_grouped_expert.h" #include "dspark_gemm.h" #include "dspark_qmv.h" #include "exact_block_attention.h" @@ -17,6 +19,9 @@ using namespace nb::literals; NB_MODULE(_ext, m) { m.doc() = "Native GLM kernels for oMLX"; + m.def("deepseek_v41_grouped_expert", + &omlx::glm_kernels::deepseek_v41_grouped_expert, + "gate"_a, "up"_a, "activation"_a, "down"_a); // ABI canary: when the extension is built with a nanobind whose ABI tag // differs from the one the mlx wheel was built with, the NB_DOMAIN is @@ -164,6 +169,19 @@ NB_MODULE(_ext, m) { "compress_ratio"_a, "local_window"_a, "stream"_a = nb::none()); + m.def( + "deepseek_v41_packed_attention", + &omlx::glm_kernels::deepseek_v41_packed_attention, + "q"_a, + "local_kv"_a, + "pooled"_a, + "topk_indices"_a, + "sinks"_a, + "scale"_a, + "q_offset"_a, + "compress_ratio"_a, + "local_window"_a, + "stream"_a = nb::none()); m.def( "glm_dsa_q8_vup_flat", &omlx::glm_kernels::glm_dsa_q8_vup_flat, diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_moe.metal b/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_moe.metal index ccf0265812..b888b1f0a3 100644 --- a/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_moe.metal +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_moe.metal @@ -21,8 +21,8 @@ inline void deepseek_affine_dequantize( U bias, threadgroup U* w_local) { static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 8, - "DeepSeek affine MoE supports bits in {2, 3, 4, 8}"); + bits == 2 || bits == 3 || bits == 4 || bits == 6 || bits == 8, + "DeepSeek affine MoE supports bits in {2, 3, 4, 6, 8}"); if (bits == 2) { U s[4] = { @@ -55,6 +55,15 @@ inline void deepseek_affine_dequantize( w_local[2 * i] = s[0] * (w[i] & 0x0f) + bias; w_local[2 * i + 1] = s[1] * (w[i] & 0xf0) + bias; } + } else if (bits == 6) { + for (int i = 0; i < N / 4; i++) { + const device uint8_t* wp = w + 3 * i; + threadgroup U* out = w_local + 4 * i; + out[0] = (wp[0] & 0x3f) * scale + bias; + out[1] = ((wp[0] >> 6) | ((wp[1] & 0xf) << 2)) * scale + bias; + out[2] = ((wp[1] >> 4) | ((wp[2] & 0x3) << 4)) * scale + bias; + out[3] = (wp[2] >> 2) * scale + bias; + } } else if (bits == 8) { for (int i = 0; i < N; i++) { w_local[i] = scale * w[i] + bias; @@ -75,8 +84,8 @@ struct DeepseekAffineBlockLoader { static_assert(BCOLS <= group_size, "group_size must cover BCOLS"); static_assert(group_size % BCOLS == 0, "group_size must divide BCOLS"); static_assert( - bits == 2 || bits == 3 || bits == 4 || bits == 8, - "DeepSeek affine MoE supports bits in {2, 3, 4, 8}"); + bits == 2 || bits == 3 || bits == 4 || bits == 6 || bits == 8, + "DeepSeek affine MoE supports bits in {2, 3, 4, 6, 8}"); static constant constexpr const short pack_factor = deepseek_affine_pack_factor(); @@ -820,12 +829,24 @@ template < instantiate_deepseek_affine_blocks(float16_t, 16, 32, 32, 1, 2, 64, 2); instantiate_deepseek_affine_blocks(float16_t, 32, 32, 32, 1, 2, 64, 2); instantiate_deepseek_affine_blocks(float16_t, 16, 32, 32, 1, 2, 64, 3); +instantiate_deepseek_affine_blocks(float16_t, 16, 32, 32, 1, 2, 64, 4); +instantiate_deepseek_affine_blocks(float16_t, 16, 32, 32, 1, 2, 64, 6); +instantiate_deepseek_affine_blocks(float16_t, 16, 32, 32, 1, 2, 64, 8); instantiate_deepseek_affine_blocks(float16_t, 32, 32, 32, 1, 2, 64, 3); +instantiate_deepseek_affine_blocks(float16_t, 32, 32, 32, 1, 2, 64, 4); +instantiate_deepseek_affine_blocks(float16_t, 32, 32, 32, 1, 2, 64, 6); +instantiate_deepseek_affine_blocks(float16_t, 32, 32, 32, 1, 2, 64, 8); instantiate_deepseek_affine_blocks(bfloat16_t, 16, 32, 32, 1, 2, 64, 2); instantiate_deepseek_affine_blocks(bfloat16_t, 32, 32, 32, 1, 2, 64, 2); instantiate_deepseek_affine_blocks(bfloat16_t, 16, 32, 32, 1, 2, 64, 3); +instantiate_deepseek_affine_blocks(bfloat16_t, 16, 32, 32, 1, 2, 64, 4); +instantiate_deepseek_affine_blocks(bfloat16_t, 16, 32, 32, 1, 2, 64, 6); +instantiate_deepseek_affine_blocks(bfloat16_t, 16, 32, 32, 1, 2, 64, 8); instantiate_deepseek_affine_blocks(bfloat16_t, 32, 32, 32, 1, 2, 64, 3); +instantiate_deepseek_affine_blocks(bfloat16_t, 32, 32, 32, 1, 2, 64, 4); +instantiate_deepseek_affine_blocks(bfloat16_t, 32, 32, 32, 1, 2, 64, 6); +instantiate_deepseek_affine_blocks(bfloat16_t, 32, 32, 32, 1, 2, 64, 8); template < typename T, @@ -995,12 +1016,24 @@ template < instantiate_deepseek_affine_pair_concat_blocks(float16_t, 16, 32, 32, 1, 2, 64, 2); instantiate_deepseek_affine_pair_concat_blocks(float16_t, 32, 32, 32, 1, 2, 64, 2); instantiate_deepseek_affine_pair_concat_blocks(float16_t, 16, 32, 32, 1, 2, 64, 3); +instantiate_deepseek_affine_pair_concat_blocks(float16_t, 16, 32, 32, 1, 2, 64, 4); +instantiate_deepseek_affine_pair_concat_blocks(float16_t, 16, 32, 32, 1, 2, 64, 6); +instantiate_deepseek_affine_pair_concat_blocks(float16_t, 16, 32, 32, 1, 2, 64, 8); instantiate_deepseek_affine_pair_concat_blocks(float16_t, 32, 32, 32, 1, 2, 64, 3); +instantiate_deepseek_affine_pair_concat_blocks(float16_t, 32, 32, 32, 1, 2, 64, 4); +instantiate_deepseek_affine_pair_concat_blocks(float16_t, 32, 32, 32, 1, 2, 64, 6); +instantiate_deepseek_affine_pair_concat_blocks(float16_t, 32, 32, 32, 1, 2, 64, 8); instantiate_deepseek_affine_pair_concat_blocks(bfloat16_t, 16, 32, 32, 1, 2, 64, 2); instantiate_deepseek_affine_pair_concat_blocks(bfloat16_t, 32, 32, 32, 1, 2, 64, 2); instantiate_deepseek_affine_pair_concat_blocks(bfloat16_t, 16, 32, 32, 1, 2, 64, 3); +instantiate_deepseek_affine_pair_concat_blocks(bfloat16_t, 16, 32, 32, 1, 2, 64, 4); +instantiate_deepseek_affine_pair_concat_blocks(bfloat16_t, 16, 32, 32, 1, 2, 64, 6); +instantiate_deepseek_affine_pair_concat_blocks(bfloat16_t, 16, 32, 32, 1, 2, 64, 8); instantiate_deepseek_affine_pair_concat_blocks(bfloat16_t, 32, 32, 32, 1, 2, 64, 3); +instantiate_deepseek_affine_pair_concat_blocks(bfloat16_t, 32, 32, 32, 1, 2, 64, 4); +instantiate_deepseek_affine_pair_concat_blocks(bfloat16_t, 32, 32, 32, 1, 2, 64, 6); +instantiate_deepseek_affine_pair_concat_blocks(bfloat16_t, 32, 32, 32, 1, 2, 64, 8); template < typename T, diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_grouped_expert.cpp b/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_grouped_expert.cpp new file mode 100644 index 0000000000..ca39d8043a --- /dev/null +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_grouped_expert.cpp @@ -0,0 +1,103 @@ +#include "deepseek_v41_grouped_expert.h" + +#include +#include +#include "mlx/backend/metal/device.h" +#include "mlx/primitives.h" + +namespace omlx::glm_kernels { +namespace { +using namespace mlx::core; + +class GroupedExpert : public Primitive { + public: + GroupedExpert(Stream s, const array& gate, const array& up, + const array& activation, const array& down) + : Primitive(s), operations_{gate.primitive_ptr(), up.primitive_ptr(), + activation.primitive_ptr(), down.primitive_ptr()}, + intermediate_shape_(gate.shape()), + gate_inputs_(gate.inputs().size()), up_inputs_(up.inputs().size()) {} + + void eval_cpu(const std::vector&, std::vector&) override { + throw std::runtime_error("DeepSeek V4.1 grouped expert requires GPU execution"); + } + + void eval_gpu(const std::vector& in, std::vector& out) override { + std::vector gate{array(intermediate_shape_, bfloat16, nullptr, {})}; + std::vector up{array(intermediate_shape_, bfloat16, nullptr, {})}; + std::vector activation{array(intermediate_shape_, bfloat16, nullptr, {})}; + auto& encoder = metal::get_command_encoder(stream()); + // Reuse MLX kernels without evaluating a nested lazy graph. Register each + // temporary before a later stage can throw or release its dependencies. + const auto up_begin = gate_inputs_; + const auto activation_begin = gate_inputs_ + up_inputs_; + const auto down_begin = activation_begin + 2; + operations_[0]->eval_gpu( + std::vector(in.begin(), in.begin() + up_begin), gate); + encoder.add_temporary(gate[0]); + operations_[1]->eval_gpu( + std::vector(in.begin() + up_begin, in.begin() + activation_begin), up); + encoder.add_temporary(up[0]); + operations_[2]->eval_gpu( + {gate[0], up[0], in[activation_begin], in[activation_begin + 1]}, activation); + encoder.add_temporary(activation[0]); + std::vector down_inputs{activation[0]}; + down_inputs.insert(down_inputs.end(), in.begin() + down_begin, in.end()); + operations_[3]->eval_gpu(down_inputs, out); + } + + DEFINE_NAME(GroupedExpert) + DEFINE_INPUT_OUTPUT_SHAPE() + bool is_equivalent(const Primitive&) const override { return false; } + + private: + std::vector> operations_; + Shape intermediate_shape_; + size_t gate_inputs_; + size_t up_inputs_; +}; +} // namespace + +mlx::core::array deepseek_v41_grouped_expert( + const mlx::core::array& gate, const mlx::core::array& up, + const mlx::core::array& activation, const mlx::core::array& down) { + using namespace mlx::core; + for (const auto* node : {&gate, &up, &down}) { + if (!node->has_primitive() || + std::string(node->primitive().name()) != "GatherQMM" || + (node->inputs().size() != 5 && node->inputs().size() != 6) || + node->dtype() != bfloat16) { + throw std::invalid_argument("Expected unevaluated BF16 MXFP or affine GatherQMM nodes"); + } + } + if (!activation.has_primitive() || + std::string(activation.primitive().name()) != "CustomKernel" || + activation.inputs().size() != 4 || activation.dtype() != bfloat16 || + activation.inputs()[0].id() != gate.id() || + activation.inputs()[1].id() != up.id() || + down.inputs()[0].id() != activation.id() || + gate.shape() != up.shape() || gate.shape() != activation.shape() || + gate.ndim() != 3 || gate.shape(0) < 1 || gate.shape(1) != 1 || + gate.shape(2) % 32 != 0 || down.ndim() != 3 || + down.shape(0) != gate.shape(0) || down.shape(1) != 1) { + throw std::invalid_argument("Unsupported DeepSeek V4.1 expert graph"); + } + auto s = gate.primitive().stream(); + if (s.device != Device::gpu) { + throw std::invalid_argument("DeepSeek V4.1 grouped expert requires a GPU stream"); + } + for (const auto* node : {&up, &activation, &down}) { + if (node->primitive().stream() != s) { + throw std::invalid_argument("Expert nodes must share a GPU stream"); + } + } + std::vector inputs = gate.inputs(); + inputs.insert(inputs.end(), up.inputs().begin(), up.inputs().end()); + inputs.push_back(activation.inputs()[2]); + inputs.push_back(activation.inputs()[3]); + inputs.insert(inputs.end(), down.inputs().begin() + 1, down.inputs().end()); + return array(down.shape(), down.dtype(), + std::make_shared(s, gate, up, activation, down), + std::move(inputs)); +} +} // namespace omlx::glm_kernels diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_grouped_expert.h b/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_grouped_expert.h new file mode 100644 index 0000000000..a560d70c66 --- /dev/null +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_grouped_expert.h @@ -0,0 +1,7 @@ +#pragma once +#include "mlx/array.h" +namespace omlx::glm_kernels { +mlx::core::array deepseek_v41_grouped_expert( + const mlx::core::array& gate, const mlx::core::array& up, + const mlx::core::array& activation, const mlx::core::array& down); +} diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_packed_attention.cpp b/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_packed_attention.cpp new file mode 100644 index 0000000000..32e6f8f18e --- /dev/null +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_packed_attention.cpp @@ -0,0 +1,312 @@ +#include "deepseek_v41_packed_attention.h" + +#include +#include +#include + +#include "mlx/backend/common/utils.h" +#include "mlx/backend/metal/device.h" +#include "mlx/backend/metal/kernels/steel/attn/params.h" +#include "mlx/backend/metal/utils.h" +#include "mlx/ops.h" +#include "mlx/utils.h" + +namespace omlx::glm_kernels { + +namespace { + +using namespace mlx::core; +using namespace mlx::steel; + +std::string current_binary_dir() { + static std::string binary_dir = []() { + Dl_info info; + if (!dladdr(reinterpret_cast(¤t_binary_dir), &info)) { + throw std::runtime_error("Unable to get omlx_glm_kernels binary dir."); + } + return std::filesystem::path(info.dli_fname).parent_path().string(); + }(); + return binary_dir; +} + +inline int64_t bcast_stride(const array& a, int axis) { + return a.shape(axis) == 1 ? 0 : a.strides(axis); +} + +bool last_dim_contiguous(const array& arr) { + return arr.strides(-1) == 1; +} + +class DeepseekV41PackedAttentionPrimitive : public Primitive { + public: + DeepseekV41PackedAttentionPrimitive( + Stream stream, + float scale, + int q_offset, + int compress_ratio, + int local_window) + : Primitive(stream), + scale_(scale), + q_offset_(q_offset), + compress_ratio_(compress_ratio), + local_window_(local_window) {} + + static bool unsupported( + const array& q, + const array& local_kv, + const array& pooled, + const array& topk_indices, + const array& sinks, + int q_offset, + int compress_ratio, + int local_window, + Stream s) { + if (s.device == Device::cpu) { + return true; + } + if (local_kv.dtype() != uint8 || pooled.dtype() != uint8 || + sinks.dtype() != float32) { + return true; + } + if (q.dtype() != bfloat16) { + return true; + } + if (q.ndim() != 4 || local_kv.ndim() != 4 || pooled.ndim() != 3 || + topk_indices.ndim() != 4 || sinks.ndim() != 1) { + return true; + } + if (!last_dim_contiguous(q) || !last_dim_contiguous(local_kv) || + !last_dim_contiguous(pooled) || !last_dim_contiguous(topk_indices) || + !last_dim_contiguous(sinks)) { + return true; + } + if (q.shape(0) != local_kv.shape(0) || q.shape(0) != pooled.shape(0) || + q.shape(0) != topk_indices.shape(0) || q.shape(1) != 64 || + q.shape(3) != 512 || local_kv.shape(1) != 1 || + local_kv.shape(3) != 528 || pooled.shape(2) != 288 || + topk_indices.shape(1) != 1 || topk_indices.shape(2) != q.shape(2) || + sinks.shape(0) != q.shape(1)) { + return true; + } + if (q.shape(2) <= 1 || local_kv.shape(2) < q.shape(2) || + topk_indices.dtype() != uint32) { + return true; + } + if (q_offset < 0 || compress_ratio <= 0 || local_window <= 0) { + return true; + } + return false; + } + + void eval_cpu( + const std::vector& /* inputs */, + std::vector& /* outputs */) override { + throw std::runtime_error( + "DeepseekV41PackedAttentionPrimitive has no CPU path."); + } + + void eval_gpu( + const std::vector& inputs, + std::vector& outputs) override { + auto& s = stream(); + auto& d = metal::device(s.device); + + const auto& q = inputs[0]; + const auto& local_kv = inputs[1]; + const auto& pooled = inputs[2]; + const auto& topk = inputs[3]; + const auto& sinks = inputs[4]; + auto& o = outputs[0]; + + constexpr int bk = 64; + constexpr int dc = 32; + constexpr int h = 64; + constexpr int dim = 512; + constexpr int wm = 8; + + const int B = q.shape(0); + const int H = q.shape(1); + const int qL = q.shape(2); + const int localL = local_kv.shape(2); + const int pooledL = pooled.shape(1); + const int topkN = topk.shape(3); + + int64_t str_oD = 1; + int64_t str_oL = o.shape(3); + int64_t str_oH = o.shape(2) * str_oL; + int64_t str_oB = o.shape(1) * str_oH; + size_t data_size = o.shape(0) * str_oB; + array::Flags flags{ + /* bool contiguous = */ 1, + /* bool row_contiguous = */ 1, + /* bool col_contiguous = */ 0, + }; + o.set_data( + allocator::malloc(o.nbytes()), + data_size, + {str_oB, str_oH, str_oL, str_oD}, + flags); + + std::string base_name; + concatenate( + base_name, + "deepseek_v41_packed_attention_", + type_to_name(q), + "_bk", + bk, + "_dc", + dc, + "_h", + h, + "_d", + dim, + "_wm", + wm); + + auto lib = d.get_library("omlx_glm_kernels", current_binary_dir()); + auto& compute_encoder = metal::get_command_encoder(s); + auto kernel = d.get_kernel(base_name, lib); + compute_encoder.set_compute_pipeline_state(kernel); + + DeepseekV4SparseAttentionParams params{ + /* int B = */ B, + /* int H = */ H, + /* int qL = */ qL, + /* int localL = */ localL, + /* int pooledL = */ pooledL, + /* int topk = */ topkN, + /* int local_window = */ local_window_, + /* int compress_ratio = */ compress_ratio_, + /* int q_offset = */ q_offset_, + + /* float scale = */ scale_, + + /* int64_t Q_strides[3] = */ { + q.strides(0), q.strides(1), q.strides(2)}, + /* int64_t Local_strides[3] = */ { + local_kv.strides(0), + bcast_stride(local_kv, 1), + local_kv.strides(2)}, + /* int64_t Pooled_strides[2] = */ { + pooled.strides(0), pooled.strides(1)}, + /* int64_t Topk_strides[3] = */ { + topk.strides(0), bcast_stride(topk, 1), topk.strides(2)}, + /* int64_t O_strides[3] = */ { + o.strides(0), o.strides(1), o.strides(2)}}; + + compute_encoder.set_input_array(q, 0); + compute_encoder.set_input_array(local_kv, 1); + compute_encoder.set_input_array(pooled, 2); + compute_encoder.set_input_array(topk, 3); + compute_encoder.set_input_array(sinks, 4); + compute_encoder.set_output_array(o, 5); + compute_encoder.set_bytes(params, 6); + + MTL::Size grid_dims = MTL::Size(qL, B, 1); + MTL::Size group_dims = MTL::Size(32, wm, 1); + compute_encoder.dispatch_threadgroups(grid_dims, group_dims); + } + + DEFINE_NAME(OMLXDeepseekV41PackedAttention) + DEFINE_INPUT_OUTPUT_SHAPE() + bool is_equivalent(const Primitive& other) const override { + const auto& rhs = + static_cast(other); + return scale_ == rhs.scale_ && q_offset_ == rhs.q_offset_ && + compress_ratio_ == rhs.compress_ratio_ && + local_window_ == rhs.local_window_; + } + auto state() const { + return std::make_tuple( + nullptr, scale_, q_offset_, compress_ratio_, local_window_); + } + + private: + float scale_; + int q_offset_; + int compress_ratio_; + int local_window_; +}; + +} // namespace + +array deepseek_v41_packed_attention( + const array& q, + const array& local_kv, + const array& pooled, + const array& topk_indices, + const array& sinks, + float scale, + int q_offset, + int compress_ratio, + int local_window, + StreamOrDevice s) { + if (q.ndim() != 4 || local_kv.ndim() != 4 || pooled.ndim() != 3 || + topk_indices.ndim() != 4 || sinks.ndim() != 1) { + std::ostringstream msg; + msg << "[omlx_glm_kernels.deepseek_v41_packed_attention] incompatible " + << "ranks: " << q.shape() << ", " << local_kv.shape() << ", " + << pooled.shape() << ", " << topk_indices.shape() << ", " + << sinks.shape() << "."; + throw std::invalid_argument(msg.str()); + } + if (q.shape(0) != local_kv.shape(0) || q.shape(0) != pooled.shape(0) || + q.shape(0) != topk_indices.shape(0) || q.shape(1) != 64 || + q.shape(3) != 512 || local_kv.shape(1) != 1 || + local_kv.shape(3) != 528 || pooled.shape(2) != 288 || + topk_indices.shape(1) != 1 || topk_indices.shape(2) != q.shape(2) || + sinks.shape(0) != q.shape(1)) { + std::ostringstream msg; + msg << "[omlx_glm_kernels.deepseek_v41_packed_attention] incompatible " + << "shapes: " << q.shape() << ", " << local_kv.shape() << ", " + << pooled.shape() << ", " << topk_indices.shape() << ", " + << sinks.shape() << "."; + throw std::invalid_argument(msg.str()); + } + if (topk_indices.dtype() != uint32) { + std::ostringstream msg; + msg << "[omlx_glm_kernels.deepseek_v41_packed_attention] topk_indices " + << "must be uint32, got " << topk_indices.dtype() << "."; + throw std::invalid_argument(msg.str()); + } + + auto final_type = q.dtype(); + if (final_type != bfloat16) { + std::ostringstream msg; + msg << "[omlx_glm_kernels.deepseek_v41_packed_attention] expected " + << "bf16 queries, got " << final_type << "."; + throw std::invalid_argument(msg.str()); + } + + auto stream = to_stream(s); + auto q_cast = astype(q, final_type, stream); + auto local_cast = local_kv; + auto pooled_cast = pooled; + auto sinks_cast = astype(sinks, float32, stream); + + if (DeepseekV41PackedAttentionPrimitive::unsupported( + q_cast, + local_cast, + pooled_cast, + topk_indices, + sinks_cast, + q_offset, + compress_ratio, + local_window, + stream)) { + throw std::invalid_argument( + "[omlx_glm_kernels.deepseek_v41_packed_attention] unsupported DeepSeek V4.1 packed attention shape."); + } + + Shape out_shape{q_cast.shape(0), q_cast.shape(1), q_cast.shape(2), q_cast.shape(3)}; + std::vector inputs = { + q_cast, local_cast, pooled_cast, topk_indices, sinks_cast}; + return array( + std::move(out_shape), + final_type, + std::make_shared( + stream, scale, q_offset, compress_ratio, local_window), + std::move(inputs)); +} + +} // namespace omlx::glm_kernels diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_packed_attention.h b/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_packed_attention.h new file mode 100644 index 0000000000..4352a4f567 --- /dev/null +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_packed_attention.h @@ -0,0 +1,23 @@ +#pragma once + +#include "mlx/array.h" +#include "mlx/stream.h" +#include "mlx/utils.h" + +namespace mx = mlx::core; + +namespace omlx::glm_kernels { + +mx::array deepseek_v41_packed_attention( + const mx::array& q, + const mx::array& local_kv, + const mx::array& pooled, + const mx::array& topk_indices, + const mx::array& sinks, + float scale, + int q_offset, + int compress_ratio, + int local_window, + mx::StreamOrDevice s = {}); + +} // namespace omlx::glm_kernels diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_packed_attention.metal b/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_packed_attention.metal new file mode 100644 index 0000000000..774848263d --- /dev/null +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/deepseek_v41_packed_attention.metal @@ -0,0 +1,19 @@ +#include "mlx/backend/metal/kernels/utils.h" +#include "mlx/backend/metal/kernels/steel/attn/kernels/steel_attention.h" +#include "kernels/steel_deepseek_v41_packed_attention.h" + +#define instantiate_deepseek_v41_packed_attention(tname, dtype, bk, dc, h, d, wm) \ + instantiate_kernel( \ + "deepseek_v41_packed_attention_" #tname "_bk" #bk "_dc" #dc "_h" #h \ + "_d" #d "_wm" #wm, \ + deepseek_v41_packed_attention, \ + dtype, \ + bk, \ + dc, \ + h, \ + d, \ + wm, \ + uint, \ + float) + +instantiate_deepseek_v41_packed_attention(bfloat16, bfloat16_t, 64, 32, 64, 512, 8); diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/fused_moe.cpp b/omlx/custom_kernels/glm_moe_dsa/csrc/fused_moe.cpp index db62caef2c..44ed011b61 100644 --- a/omlx/custom_kernels/glm_moe_dsa/csrc/fused_moe.cpp +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/fused_moe.cpp @@ -69,6 +69,8 @@ int affine_pack_factor(int bits) { return 8; case 4: return 2; + case 6: + return 4; case 8: return 1; default: @@ -84,6 +86,8 @@ int affine_bytes_per_pack(int bits) { return 3; case 4: return 1; + case 6: + return 3; case 8: return 1; default: @@ -92,7 +96,8 @@ int affine_bytes_per_pack(int bits) { } bool supported_deepseek_affine(int group_size, int bits) { - return group_size == 64 && (bits == 2 || bits == 3); + return group_size == 64 && + (bits == 2 || bits == 3 || bits == 4 || bits == 6 || bits == 8); } int affine_packed_row_bytes(int K, int bits) { diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_deepseek_v41_packed_attention.h b/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_deepseek_v41_packed_attention.h new file mode 100644 index 0000000000..72a109ef77 --- /dev/null +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_deepseek_v41_packed_attention.h @@ -0,0 +1,352 @@ +// Copyright © 2026 OpenAI + +#pragma once + +#include "mlx/backend/metal/kernels/steel/attn/attn.h" +#include "mlx/backend/metal/kernels/steel/attn/params.h" + +using namespace mlx::steel; + +struct DeepseekV41SparseMaxOp { + template + METAL_FUNC static constexpr T apply(T x, T y) { + return metal::max(x, y); + } +}; + +struct DeepseekV41SparseSumOp { + template + METAL_FUNC static constexpr T apply(T x, T y) { + return x + y; + } +}; + +struct DeepseekV41SparseMulOp { + template + METAL_FUNC static constexpr T apply(T x, T y) { + return x * y; + } +}; + +struct DeepseekV41SparseExpSubOp { + template + METAL_FUNC static constexpr T apply(T x, T y) { + return metal::exp(x - y); + } +}; + +struct DeepseekV41SparseDivOp { + template + METAL_FUNC static constexpr T apply(T x, T y) { + return x / y; + } +}; + + +// Decode only the channel tile currently consumed by QK or PV. +METAL_FUNC float deepseek_v41_fp8(uchar code) { + const uint a = code & 127, exponent = a >> 3, mantissa = a & 7; + const float value = exponent == 0 ? float(mantissa) * 0x1p-9f + : as_type(((exponent + 120u) << 23) | (mantissa << 20)); + return code & 128 ? -value : value; +} +METAL_FUNC float deepseek_v41_packed_value( + const device uchar* row, int d, bool pooled) { + if (pooled) { + constexpr float levels[8] = {0, 0.5f, 1, 1.5f, 2, 3, 4, 6}; + const uint code = (row[d / 2] >> ((d % 2) * 4)) & 15; + const float value = levels[code & 7] * ((code & 8) ? -1.0f : 1.0f); + return value * deepseek_v41_fp8(row[256 + d / 16]); + } + return ldexp(deepseek_v41_fp8(row[d]), int(row[512 + d / 32]) - 127); +} + +// clang-format off +template < + typename T, + int BK, + int DC, + int H, + int D, + int WM, + typename IndexT, + typename AccumType = float> +[[kernel, max_total_threads_per_threadgroup(WM * 32)]] void deepseek_v41_packed_attention( + const device T* Q [[buffer(0)]], + const device uchar* LocalKV [[buffer(1)]], + const device uchar* PooledKV [[buffer(2)]], + const device IndexT* Topk [[buffer(3)]], + const device float* Sinks [[buffer(4)]], + device T* O [[buffer(5)]], + const constant DeepseekV4SparseAttentionParams* params [[buffer(6)]], + uint simd_lane_id [[thread_index_in_simdgroup]], + uint simd_group_id [[simdgroup_index_in_threadgroup]], + uint3 tid [[threadgroup_position_in_grid]]) { // clang-format on + + static_assert(H == 64 && D == 512, "Packed attention requires 64 heads of width 512."); + constexpr short kFragSize = 8; + constexpr short padQ = 16 / sizeof(T); + constexpr short padK = 16 / sizeof(T); + constexpr short padV = 16 / sizeof(T); + + constexpr short LDQ = DC + padQ; + constexpr short LDK = BK + padK; + constexpr short LDV = DC + padV; + + constexpr int kNWarps = WM; + constexpr int TQ = H / (kNWarps * kFragSize); + constexpr int TK = BK / kFragSize; + constexpr int TDC = DC / kFragSize; + constexpr int D_CHUNKS = D / DC; + + static_assert(TQ >= 1, "DeepSeek sparse attention needs a head tile."); + static_assert( + H % (kNWarps * kFragSize) == 0, + "Head count must divide evenly across simdgroups."); + static_assert(BK % kFragSize == 0, "BK must be a multiple of 8."); + static_assert(DC % kFragSize == 0, "DC must be a multiple of 8."); + static_assert(D % DC == 0, "Head dimension must divide DC."); + + constexpr int tgp_size = WM * 32; + const int lane = int(simd_group_id * 32 + simd_lane_id); + + const int q_pos = int(tid.x); + const int b = int(tid.y); + + threadgroup T Qs[H * LDQ]; + threadgroup T KVs[(BK * LDV > DC * LDK) ? BK * LDV : DC * LDK]; + threadgroup int selected[BK]; + + using MMAFragAcc = BaseMMAFrag; + MMATile Qtile; + MMATile Ktile; + MMATile Stile; + MMATile Vtile; + MMATile Otile; + + Otile.clear(); + + const short2 simd_coord = MMAFragAcc::get_coord(simd_lane_id); + const short sm = simd_coord.y; + const short sn = simd_coord.x; + const short tm = kFragSize * TQ * simd_group_id; + + const short Qs_offset = (tm + sm) * LDQ + sn; + const short Ks_offset = sm * LDK + sn; + const short Vs_offset = sm * LDV + sn; + + const AccumType scale = AccumType(params->scale); + + constexpr short rows_per_thread = decltype(Stile)::kRowsPerThread; + AccumType max_score[rows_per_thread]; + AccumType sum_score[rows_per_thread] = {0}; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < rows_per_thread; ++i) { + const int head = int(tm + sm + i * kFragSize); + if (head < params->H) { + max_score[i] = AccumType(-1e30f); + } else { + max_score[i] = Limits::finite_min; + } + } + + const device T* q_base = Q + size_t(b) * params->Q_strides[0] + + size_t(q_pos) * params->Q_strides[2]; + const device uchar* local_base = + LocalKV + size_t(b) * params->Local_strides[0]; + const device uchar* pooled_base = + PooledKV + size_t(b) * params->Pooled_strides[0]; + const device IndexT* topk_base = + Topk + size_t(b) * params->Topk_strides[0] + + size_t(q_pos) * params->Topk_strides[2]; + + const int local_offset = params->localL - params->qL; + const int local_end = + metal::min(params->localL, local_offset + q_pos + 1); + const int local_start = + metal::max(0, local_end - params->local_window); + // Tile the concatenated index list, including masked window slots. + const int window_slots = params->q_offset == 0 + ? metal::min(params->local_window, params->qL) : params->local_window; + const int window_first = params->q_offset == 0 + ? local_start : local_end - window_slots; + const int pooled_valid = metal::min( + params->pooledL, + (params->q_offset + q_pos + 1) / params->compress_ratio); + const int total_tiles = (window_slots + params->topk + BK - 1) / BK; + + for (int ktile = 0; ktile < total_tiles; ++ktile) { + for (int k = lane; k < BK; k += tgp_size) { + const int slot = ktile * BK + k; + int k_pos = -1; + if (slot < window_slots) { + const int row = window_first + slot; + if (row >= 0 && row < local_end) k_pos = row; + } else if (slot < window_slots + params->topk) { + const int row = int(topk_base[slot - window_slots]); + if (row >= 0 && row < pooled_valid) k_pos = params->localL + row; + } + selected[k] = k_pos; + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + Stile.clear(); + + STEEL_PRAGMA_UNROLL + for (short dchunk = 0; dchunk < D_CHUNKS; ++dchunk) { + const int dbase = int(dchunk) * DC; + + for (int elem = lane; elem < H * DC; elem += tgp_size) { + const int h = elem / DC; + const int d = elem - h * DC; + Qs[h * LDQ + d] = + q_base[size_t(h) * params->Q_strides[1] + dbase + d]; + } + + for (int elem = lane; elem < BK * DC; elem += tgp_size) { + const int k = elem / DC; + const int d = elem - k * DC; + const int k_pos = selected[k]; + T value = T(0); + if (k_pos >= 0) { + const bool is_pooled_tile = k_pos >= params->localL; + const int source_pos = is_pooled_tile ? k_pos - params->localL : k_pos; + const device uchar* row = is_pooled_tile + ? pooled_base + size_t(source_pos) * params->Pooled_strides[1] + : local_base + size_t(source_pos) * params->Local_strides[2]; + value = T(deepseek_v41_packed_value(row, dbase + d, is_pooled_tile)); + } + KVs[k + d * LDK] = value; + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + STEEL_PRAGMA_UNROLL + for (short dd = 0; dd < TDC; ++dd) { + simdgroup_barrier(mem_flags::mem_none); + Qtile.template load(&Qs[Qs_offset + dd * kFragSize]); + Ktile.template load( + &KVs[Ks_offset + dd * kFragSize * LDK]); + simdgroup_barrier(mem_flags::mem_none); + tile_matmad(Stile, Qtile, Ktile, Stile); + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + STEEL_PRAGMA_UNROLL + for (short ii = 0; ii < decltype(Stile)::kElemsPerTile; ++ii) { + Stile.elems()[ii] *= scale; + } + + { + using stile_t = decltype(Stile); + using selem_t = typename stile_t::elem_type; + constexpr auto neg_inf = Limits::finite_min; + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < stile_t::kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < stile_t::kTileCols; ++j) { + const short col_pos = sn + j * stile_t::kFragCols; + STEEL_PRAGMA_UNROLL + for (short jj = 0; jj < stile_t::MMAFrag_t::kElemCols; ++jj) { + if (selected[col_pos + jj] < 0) { + Stile.frag_at(i, j)[jj] = neg_inf; + } + } + } + } + } + + AccumType new_max[rows_per_thread]; + AccumType factor[rows_per_thread]; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < rows_per_thread; ++i) { + new_max[i] = max_score[i]; + } + + Stile.template row_reduce(new_max); + Stile.template row_bin_op(new_max); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < rows_per_thread; ++i) { + factor[i] = metal::exp(max_score[i] - new_max[i]); + max_score[i] = new_max[i]; + } + + AccumType sum_score_tmp[rows_per_thread] = {0}; + Stile.template row_reduce(sum_score_tmp); + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < rows_per_thread; ++i) { + sum_score[i] = sum_score[i] * factor[i] + sum_score_tmp[i]; + } + + // The denominator retains FP32 probabilities; only PV rounds to BF16. + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(Stile)::kElemsPerTile; ++i) + Stile.elems()[i] = AccumType(T(Stile.elems()[i])); + + Otile.template row_bin_op(factor); + + STEEL_PRAGMA_UNROLL + for (short vchunk = 0; vchunk < D_CHUNKS; ++vchunk) { + const int dbase = int(vchunk) * DC; + + for (int elem = lane; elem < BK * DC; elem += tgp_size) { + const int k = elem / DC; + const int d = elem - k * DC; + const int k_pos = selected[k]; + T value = T(0); + if (k_pos >= 0) { + const bool is_pooled_tile = k_pos >= params->localL; + const int source_pos = is_pooled_tile ? k_pos - params->localL : k_pos; + const device uchar* row = is_pooled_tile + ? pooled_base + size_t(source_pos) * params->Pooled_strides[1] + : local_base + size_t(source_pos) * params->Local_strides[2]; + value = T(deepseek_v41_packed_value(row, dbase + d, is_pooled_tile)); + } + KVs[k * LDV + d] = value; + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + STEEL_PRAGMA_UNROLL + for (short iq = 0; iq < TQ; ++iq) { + STEEL_PRAGMA_UNROLL + for (short id = 0; id < TDC; ++id) { + STEEL_PRAGMA_UNROLL + for (short ik = 0; ik < TK; ++ik) { + const short kk = ik * kFragSize; + const short dd = id * kFragSize; + Vtile.template load( + &KVs[Vs_offset + kk * LDV + dd]); + MMAFragAcc::mma( + Otile.frag_at(iq, vchunk * TDC + id), + Stile.frag_at(iq, ik), + Vtile.frag_at(0, 0), + Otile.frag_at(iq, vchunk * TDC + id)); + } + } + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < rows_per_thread; ++i) { + const int head = int(tm + sm + i * kFragSize); + if (head < params->H) + sum_score[i] += metal::exp(AccumType(Sinks[head]) - max_score[i]); + } + Otile.template row_bin_op(sum_score); + + device T* out = O + size_t(b) * params->O_strides[0] + + size_t(q_pos) * params->O_strides[2] + + size_t(tm + sm) * params->O_strides[1] + sn; + Otile.template store(out, params->O_strides[1]); +} diff --git a/omlx/custom_kernels/glm_moe_dsa/fast.py b/omlx/custom_kernels/glm_moe_dsa/fast.py index ea4cca56df..e63a44335e 100644 --- a/omlx/custom_kernels/glm_moe_dsa/fast.py +++ b/omlx/custom_kernels/glm_moe_dsa/fast.py @@ -110,6 +110,8 @@ def _probe_mma_score(ext) -> bool: "glm_dsa_sparse_mla_attention", "glm_dsa_exact_block_attention", "deepseek_v4_sparse_attention", + "deepseek_v41_packed_attention", + "deepseek_v41_grouped_expert", "dspark_ring_gemm", "dspark_rowwise_gemm", "glm_dsa_q8_vup_flat", @@ -576,6 +578,35 @@ def deepseek_v4_sparse_attention( raise RuntimeError("deepseek_v4_sparse_attention native kernel is unavailable") +def deepseek_v41_packed_attention( + q: mx.array, + local_kv: mx.array, + pooled: mx.array, + topk_indices: mx.array, + sinks: mx.array, + scale: float, + q_offset: int, + compress_ratio: int, + local_window: int, + *, + stream=None, +) -> mx.array: + if _ext is not None and hasattr(_ext, "deepseek_v41_packed_attention"): + return _ext.deepseek_v41_packed_attention( + q, + local_kv, + pooled, + topk_indices, + sinks, + scale, + q_offset, + compress_ratio, + local_window, + **_native_stream_kwargs(stream), + ) + raise RuntimeError("deepseek_v41_packed_attention native kernel is unavailable") + + def glm_dsa_q8_vup_flat( x: mx.array, weight: mx.array, @@ -808,3 +839,10 @@ def __dir__() -> list[str]: if _ext is not None: names.update(dir(_ext)) return sorted(names) + + +def deepseek_v41_grouped_expert(gate, up, activation, down): + """Submit one routed expert pipeline using its existing MLX primitives.""" + if _ext is not None and hasattr(_ext, "deepseek_v41_grouped_expert"): + return _ext.deepseek_v41_grouped_expert(gate, up, activation, down) + raise RuntimeError("DeepSeek V4.1 grouped expert native kernel is unavailable") diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index fbc44f1ae1..060832f0fb 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -1819,6 +1819,19 @@ def _load_vlm_sync(): return model, processor model_type = _read_config_model_type(self._model_name) + if model_type == "deepseek_v41": + from ..patches.deepseek_v41.loading import load + + return load( + self._model_name, + engram_ssd_offload=bool( + getattr( + self._model_settings, + "deepseek_v41_engram_ssd_offload", + False, + ) + ), + ) if model_type == COHERE2_MOE_MODEL_TYPE: return _load_cohere2_moe_text_model( self._model_name, @@ -2581,6 +2594,13 @@ def _format_messages_for_vlm_template( if not model_type: raise ValueError("Missing VLM model_type for chat template formatting") + if model_type == "deepseek_v41": + if num_audios: + raise ValueError("DeepSeek V4.1 supports text and images, not audio") + from ..patches.deepseek_v41.processing import format_messages + + return format_messages(messages, num_images) + image_part_types = {"image", "image_url", "input_image"} audio_part_types = {"input_audio"} has_explicit_images = any( diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index eeb26963bc..5363c2bd35 100644 --- a/omlx/engine_pool.py +++ b/omlx/engine_pool.py @@ -206,7 +206,7 @@ class EngineEntry: text_only_size: int = 0 # Language-only estimate for VLM checkpoints (0 = n/a) actual_size: int | None = None # Observed process-memory delta after load settles runtime_estimated_size: int | None = None # Includes active load-time variants - runtime_settle_size: int | None = None # Excludes K2 ANE admission headroom + runtime_settle_size: int | None = None # Excludes K2 ANE storage config_model_type: str = ( "" # Raw model_type from config.json (e.g., "deepseekocr_2") ) @@ -355,7 +355,7 @@ def _entry_runtime_resident_size( base_size: int | None = None, include_ane_reservation: bool = True, ) -> int: - """Include runtime storage and optional K2 ANE admission headroom.""" + """Include Engram runtime storage and optional K2 ANE reservations.""" base = self._entry_resident_size(entry) if base_size is None else base_size if self._distributed_deployment_for_entry(entry) is not None: @@ -365,6 +365,15 @@ def _entry_runtime_resident_size( ) if qwen4_offload and qwen4_estimate is not None: base = min(base, qwen4_estimate.mmap_bytes) + v41_offload, _, v41_estimate = self._deepseek_v41_engram_offload_status( + entry, runtime_settings + ) + if v41_estimate is not None: + base = ( + v41_estimate.mmap_bytes + if v41_offload + else v41_estimate.resident_bytes + ) extra = _qwen35_cpu_share_estimated_bytes(entry.model_path, runtime_settings) if extra is None: # An enabled CPU path with unreadable geometry must not silently @@ -471,6 +480,80 @@ def _effective_qwen4_model_settings( setattr(effective, "qwen4_ple_ssd_offload", True) return effective + def _deepseek_v41_engram_offload_status( + self, + entry: EngineEntry, + settings: object | None, + *, + ceiling: int | None = None, + ) -> tuple[bool, bool, object | None]: + """Resolve requested/forced DeepSeek V4.1 Engram mmap mode for this process.""" + + model_type = (entry.config_model_type or "").replace("-", "_").lower() + if model_type != "deepseek_v41": + return False, False, None + try: + from .patches.deepseek_v41.residency import ( + deepseek_v41_residency_estimate, + ) + + estimate = deepseek_v41_residency_estimate(entry.model_path) + except (KeyError, OSError, TypeError, ValueError): + logger.debug( + "Could not inspect DeepSeek V4.1 Engram residency for %s", + entry.model_id, + exc_info=True, + ) + return False, False, None + # Normal residency calls use the stable ceiling so a post-unload + # vm_stat dip cannot pin the new engine to SSD. Pre-load admission may + # pass its earlier live ceiling explicitly when only mmap fits. + if ceiling is None: + ceiling = self._residency_ceiling() + if ceiling <= 0: + ceiling = self._fallback_admission_ceiling() + if ceiling <= 0: + ceiling = self._current_ceiling() + forced = estimate.force_ssd_offload(ceiling) + if forced: + logger.warning( + "DeepSeek V4.1 Engram forced to SSD for %s: resident %.1fGB exceeds the " + "%.1fGB memory ceiling (mmap needs %.1fGB).", + entry.model_id, + estimate.resident_bytes / 1e9, + ceiling / 1e9, + estimate.mmap_bytes / 1e9, + ) + requested = bool( + settings is not None + and getattr(settings, "deepseek_v41_engram_ssd_offload", False) + ) + return requested or forced, forced, estimate if estimate.supported else None + + def _effective_deepseek_v41_model_settings( + self, + entry: EngineEntry, + settings: object | None, + *, + ceiling: int | None = None, + ) -> object | None: + """Apply a forced mmap decision without mutating persisted settings.""" + + enabled, forced, _ = self._deepseek_v41_engram_offload_status( + entry, + settings, + ceiling=ceiling, + ) + if not enabled or not forced: + return settings + if settings is None: + from .model_settings import ModelSettings + + settings = ModelSettings() + effective = copy.copy(settings) + effective.deepseek_v41_engram_ssd_offload = True + return effective + @property def current_model_memory(self) -> int: """Current memory used by loaded models in bytes.""" @@ -662,6 +745,10 @@ def add(key: str, value: object) -> None: if entry is not None: qwen4_offload, _, _ = self._qwen4_ple_offload_status(entry, settings) add("qwen4_ple_ssd_offload", qwen4_offload) + v41_offload, _, _ = self._deepseek_v41_engram_offload_status( + entry, settings + ) + add("deepseek_v41_engram_ssd_offload", v41_offload) turboquant_active = bool(data.get("turboquant_kv_enabled", False)) add("turboquant_kv_enabled", turboquant_active) @@ -1586,16 +1673,16 @@ async def get_engine( model_id, runtime_settings, ) - qwen4_admission_ceiling = None - if ( - (entry.config_model_type or "").replace("-", "_").lower() - == "qwen4_exp" - ): + ngram_admission_ceiling = None + if (entry.config_model_type or "").replace("-", "_").lower() in { + "qwen4_exp", + "deepseek_v41", + }: candidate = self._current_ceiling() if candidate <= 0: candidate = self._fallback_admission_ceiling() if candidate > 0: - qwen4_admission_ceiling = candidate + ngram_admission_ceiling = candidate unloaded_for_admission = False # Already loaded - just update access time @@ -1686,11 +1773,14 @@ async def get_engine( load_settings = self._effective_qwen4_model_settings( entry, admission_settings, - ceiling=qwen4_admission_ceiling, + ceiling=ngram_admission_ceiling, ) - qwen4_admission_override = load_settings is not admission_settings + load_settings = self._effective_deepseek_v41_model_settings( + entry, load_settings, ceiling=ngram_admission_ceiling + ) + ngram_admission_override = load_settings is not admission_settings runtime_load_settings = ( - load_settings if qwen4_admission_override else runtime_settings + load_settings if ngram_admission_override else runtime_settings ) admission_size = self._entry_runtime_resident_size( entry, @@ -1842,7 +1932,7 @@ async def get_engine( ) loaded = self._entries[model_id] - if qwen4_admission_override and expected_signature is not None: + if ngram_admission_override and expected_signature is not None: # Automatic mmap is local to this admission attempt. Keep the # user's requested variant as the reuse key so the next request # does not reload the model merely because pressure recovered. @@ -2489,6 +2579,8 @@ async def _unload_engine(self, model_id: str) -> None: get_mlx_executor(), lambda: (mx.synchronize(), mx.clear_cache()) ) + # RAM Engram tables share MLX buffers with CPU views, so their packed + # bytes are included in both admission and Metal unload settlement. # Memory settle barrier: poll actual freed memory instead of # trusting the cumulative _current_model_memory estimate. # Scale tolerance with model size: estimated_size includes a 5% @@ -2695,6 +2787,9 @@ async def _load_engine( if model_settings is None and self._settings_manager is not None: model_settings = self._settings_manager.get_settings(model_id) model_settings = self._effective_qwen4_model_settings(entry, model_settings) + model_settings = self._effective_deepseek_v41_model_settings( + entry, model_settings + ) if getattr(model_settings, "qwen35_ane_prefill_enabled", False): validate_ane_prefill(model_settings.to_dict(), entry.config_model_type) diff --git a/omlx/memory_monitor.py b/omlx/memory_monitor.py index 5d49351acd..3d1faca7f4 100644 --- a/omlx/memory_monitor.py +++ b/omlx/memory_monitor.py @@ -1421,7 +1421,9 @@ def make_prefill_memory_profile( return _make_qwen4_exp_prefill_memory_profile( config, compute_dtype_size=compute_dtype_size ) - if not model_type.startswith("deepseek_v4"): + if not model_type.startswith("deepseek_v4") or model_type.startswith( + "deepseek_v41" + ): return None num_layers = _cfg_get(config, "num_hidden_layers") diff --git a/omlx/model_discovery.py b/omlx/model_discovery.py index 8d0c721fc8..ec7a2773d0 100644 --- a/omlx/model_discovery.py +++ b/omlx/model_discovery.py @@ -30,6 +30,7 @@ # Known VLM (Vision-Language Model) types from mlx-vlm VLM_MODEL_TYPES = { + "deepseek_v41", "qwen2_vl", "qwen2_5_vl", "qwen3_vl", diff --git a/omlx/model_profiles.py b/omlx/model_profiles.py index 49aea4e38b..1432254e78 100644 --- a/omlx/model_profiles.py +++ b/omlx/model_profiles.py @@ -108,6 +108,7 @@ "ttl_seconds", # Hardware-specific residency choice; never propagate across models. "qwen4_ple_ssd_offload", + "deepseek_v41_engram_ssd_offload", # Security flag must be explicit per model — never propagated via profiles. "trust_remote_code", } diff --git a/omlx/model_settings.py b/omlx/model_settings.py index d9b43ea8f0..fc5b91c4bc 100644 --- a/omlx/model_settings.py +++ b/omlx/model_settings.py @@ -296,6 +296,7 @@ class ModelSettings: # through mmap. The runtime may force this on when resident loading cannot # fit under the configured model-memory ceiling but mmap loading can. qwen4_ple_ssd_offload: bool = False + deepseek_v41_engram_ssd_offload: bool = False preserve_thinking: Optional[bool] = ( None # Keep blocks in historical turns (None = auto, True when template supports it) ) diff --git a/omlx/oq.py b/omlx/oq.py index 6153595534..9a41e6dc9a 100644 --- a/omlx/oq.py +++ b/omlx/oq.py @@ -12,6 +12,7 @@ import hashlib import json import logging +import math import re import shutil import struct as _struct @@ -982,6 +983,7 @@ def _build_quant_plan( target_bpw: float = 4.6, hard_cap_bpw: float = 4.7, fixed_overrides: dict[str, dict] | None = None, + supported_bits: tuple[int, ...] = _VALID_QUANT_BITS, ) -> QuantPlan: """Allocate byte-budgeted boosts using sensitivity-driven allocation. @@ -998,6 +1000,8 @@ def _build_quant_plan( boost decision. """ base_bits = _base_bits_for_level(oq_level) + if base_bits not in supported_bits: + raise ValueError("Base quantization width is not supported by this model") base_mode = _mode_for_bits(base_bits) base_group_size = _gs_for_mode(base_bits, _OQ_DEFAULT_GROUP_SIZE) boost_map: dict[str, dict] = {} @@ -1178,7 +1182,7 @@ def _build_quant_plan( candidates, key=lambda x: x[0], reverse=True ): for cand_bits in range(max_target, cur_bits, -1): - if cand_bits not in _VALID_QUANT_BITS or cand_bits <= cur_bits: + if cand_bits not in supported_bits or cand_bits <= cur_bits: continue cand_gs = _gs_for_mode(cand_bits, _OQ_DEFAULT_GROUP_SIZE) cand_mode = _mode_for_bits(cand_bits) @@ -1223,6 +1227,8 @@ def _build_quant_plan( fallback_candidates, key=lambda x: x[0], reverse=True ): for cand_bits in (8, 6, 5, 4, 3): + if cand_bits not in supported_bits: + continue if cand_bits <= cur_bits: continue cand_gs = _gs_for_mode(cand_bits, _OQ_DEFAULT_GROUP_SIZE) @@ -3157,6 +3163,8 @@ def validate_quantizable(config: dict) -> bool: quantization_config records training-time settings but whose weights are stored in full precision (bfloat16/float16). """ + if config.get("model_type") == "deepseek_v41" and "omlx_deepseek_v41" in config: + return False if "quantization" in config: return False if "quantization_config" in config: @@ -3251,6 +3259,47 @@ def estimate_bpw_and_size( if not _checkpoint_has_mtp_weights(source): preserve_mtp = False + if config.get("model_type") == "deepseek_v41": + from .patches.deepseek_v41.oq import source_budget + + if oq_level not in (3, 4) or group_size != 64: + raise ValueError("V4.1 supports oQ3/oQ4 with group size 64") + if "omlx_deepseek_v41" in config: + raise ValueError("V4.1 quantization requires the original checkpoint") + mapping = json.loads((source / "model.safetensors.index.json").read_text())[ + "weight_map" + ] + budget = source_budget( + source, config, mapping, preserve_mtp=preserve_mtp, engram_bits=oq_level + ) + remaining = budget["remaining_weights"] + # The oQ3 allocation is not known until calibration. Quote its budget + # ceiling rather than assuming original FP4 expert bytes pass through. + remaining_bytes = remaining["tensor_bytes"] + if oq_level == 3: + remaining_bytes = math.ceil( + remaining["logical_parameters"] * _OQ_BPW_TARGETS[3][1] / 8 + ) + total = remaining_bytes + budget["engram"]["tensor_bytes"] + parameters = ( + remaining["logical_parameters"] + budget["engram"]["logical_parameters"] + ) + # Retain the existing conservative workspace multiplier, but do not + # count the SSD-offloaded Engram table as resident model weights. + streaming_peak = int(remaining["tensor_bytes"] * 1.5) + 5 * 1024**3 + return { + "effective_bpw": total * 8 / max(parameters, 1), + "output_size_bytes": total, + "output_size_formatted": _format_size(total), + "estimate_basis": ( + "calibration_budget_ceiling" if oq_level == 3 else "source_precision" + ), + "engram_size_bytes": budget["engram"]["tensor_bytes"], + "remaining_size_bytes": remaining_bytes, + "memory_streaming_bytes": streaming_peak, + "memory_streaming_formatted": _format_size(streaming_peak), + } + # Header-only scan: shapes/dtypes come from the safetensors headers, so # checkpoints with dtypes mx.load rejects (F8_E8M0 block scales) still # estimate. The logical view hides .scale companions and reports @@ -4422,7 +4471,9 @@ def _get_predicate_bits( # the selected oQ level and use the group-32 layout published by existing # Qwen4-Exp quantizations. Embeddings have no input-channel imatrix entry; # the streaming loop deliberately applies ordinary affine quantization. - if _is_qwen4_exp_ngram_embedding_tensor(tensor_name, config): + if _is_qwen4_exp_ngram_embedding_tensor(tensor_name, config) or ( + config.get("model_type") == "deepseek_v41" and ".engram.embed" in tensor_name + ): return base_bits, _QWEN4_EXP_NGRAM_GROUP_SIZE, "affine" result = universal_quant_predicate(tensor_name, None, config, oq_level) @@ -5196,6 +5247,8 @@ def _source_imatrix_signature( # Invalidate caches produced by the old independent-block walk, which # captured only q_proj in the shared-KV tail of E2B/E4B. signature["layer_walk"] = "gemma4_shared_kv_v1" + elif str(config.get("model_type", "")).lower() == "deepseek_v41": + signature["layer_walk"] = "deepseek_v41_full_forward_v1" elif str(config.get("model_type", "")).lower() == "glm5_next": # GLM-5.3 needs its mHC-expanded layer walk plus the untied output-head # capture. Older caches completed without either and must not be reused. @@ -5711,7 +5764,8 @@ def quantize_oq_streaming( faster prefill on M1/M2 Apple Silicon (native fp16 support), but is unsupported for DeepSeek V4. preserve_mtp: Keep mtp.* tensors and config fields in the output so - the Lightning MTP toggle works after quantization. Stashes mtp.* + supported models retain Lightning MTP after quantization, including + V4.1 DSpark draft stages used by server verification. Stashes mtp.* keys around the model.sanitize() call (which would otherwise strip them) and re-merges. When False (default), mtp.* tensors are stripped *and* the output config's mtp_num_hidden_layers / @@ -5781,6 +5835,29 @@ def cb( normalized_model_type = str(config.get("model_type", "")).lower().replace( "-", "_" ) + if normalized_model_type == "deepseek_v41": + from .patches.deepseek_v41.oq import quantize as quantize_v41 + + return quantize_v41( + source, + output, + oq_level=oq_level, + enhanced=enhanced, + group_size=group_size, + sensitivity_model_path=sensitivity_model_path, + sensitivity_map_override=sensitivity_map_override, + imatrix_cache_path=imatrix_cache_path, + imatrix_reuse_cache=imatrix_reuse_cache, + imatrix_strict=imatrix_strict, + imatrix_num_samples=imatrix_num_samples, + imatrix_seq_length=imatrix_seq_length, + preserve_mtp=preserve_mtp, + target_bpw=target_bpw, + hard_cap_bpw=hard_cap_bpw, + text_only=text_only, + dtype=dtype, + progress_callback=progress_callback, + ) if ( normalized_model_type in MLX_LM_TEXT_ONLY_MODEL_TYPES and _has_vision_subconfig(config) @@ -6536,6 +6613,15 @@ def _imatrix_load_path() -> str: _OQE_MIN_EXPERT_COUNT = 16 _OQE_MIN_EXPERT_COUNT_PERCENTILE = 5 _OQE_SWITCH_LINEAR_CLASSES = {"SwitchLinear", "QuantizedSwitchLinear"} + + +def _is_oqe_switch_module(module) -> bool: + return ( + type(module).__name__ in _OQE_SWITCH_LINEAR_CLASSES + or (type(module).__name__ == "QuantizedProjection" + and getattr(module.weight, "ndim", 0) == 3) + ) + _OQE_MULTI_LINEAR_CLASSES = {"MultiLinear", "QuantizedMultiLinear"} _OQ_CODE_MULTILINGUAL_KEYS = ( "code", @@ -7382,7 +7468,7 @@ def __getattr__(self, key: str): def __call__(self, *args, **kwargs): if args: if ( - type(self._module).__name__ in _OQE_SWITCH_LINEAR_CLASSES + _is_oqe_switch_module(self._module) and len(args) >= 2 ): self._collector.collect_switch( @@ -7414,7 +7500,7 @@ def __init__(self): @staticmethod def _is_capture_module(module) -> bool: cls = type(module).__name__ - if cls in _OQE_SWITCH_LINEAR_CLASSES: + if _is_oqe_switch_module(module): return hasattr(module, "weight") and getattr(module.weight, "ndim", 0) == 3 if cls in _OQE_MULTI_LINEAR_CLASSES: return hasattr(module, "weight") and getattr(module.weight, "ndim", 0) == 3 @@ -7422,7 +7508,7 @@ def _is_capture_module(module) -> bool: # already-quantized checkpoints (e.g. deriving a recalibrated MTP # head from an oQ8 model when the bf16 source is gone). return ( - cls in ("Linear", "QuantizedLinear") + cls in ("Linear", "QuantizedLinear", "QuantizedProjection") and hasattr(module, "weight") and getattr(module.weight, "ndim", 0) == 2 ) @@ -7453,7 +7539,7 @@ def install(self, model) -> int: self.capture_module_classes[cls] = ( self.capture_module_classes.get(cls, 0) + 1 ) - if cls in _OQE_SWITCH_LINEAR_CLASSES: + if _is_oqe_switch_module(module): self.switch_capture_modules += 1 self._original_modules[name] = module replacements.append((name, _ImatrixCaptureWrapper(module, name, self))) @@ -8088,6 +8174,19 @@ def _collect_imatrix( progress_start: float = 13.0, progress_end: float = 18.0, ) -> tuple[dict[str, OQImatrixEntry], dict[str, Any]]: + if str(config.get("model_type", "")).replace("-", "_") == "deepseek_v41": + from .patches.deepseek_v41.calibration import collect_checkpoint_imatrix + + return collect_checkpoint_imatrix( + model_path, + calib_dataset=calib_dataset, + num_samples=num_samples, + seq_length=seq_length, + progress_callback=progress_callback, + progress_start=progress_start, + progress_end=progress_end, + ) + from omlx.utils.model_loading import ( _checkpoint_has_mtp_weights, _has_mtp_heads, @@ -8193,6 +8292,13 @@ def _oqe_cache_missing_mtp_entries( """True when the model declares MTP heads but the cache predates the MTP-head collection pass (no ``mtp.*`` entries) — force a recollect so the head gets calibrated quantization instead of landing in "missing".""" + collection = cache.metadata.get("collection") + if ( + config.get("model_type") == "deepseek_v41" + and isinstance(collection, dict) + and collection.get("uncalibrated_policy") == "preserve_source_precision" + ): + return False try: from omlx.utils.model_loading import ( _checkpoint_has_mtp_weights, @@ -8334,6 +8440,18 @@ def _measure_sensitivity_from_model( Returns: Dict of {layer_idx: relative_mse_score}. """ + if str(config.get("model_type", "")).replace("-", "_") == "deepseek_v41": + from .patches.deepseek_v41.sensitivity import measure_sensitivity + + return measure_sensitivity( + model, + tokenizer, + bits=_base_bits_for_level(oq_level), + calib_dataset=calib_dataset, + num_samples=num_samples, + seq_length=seq_length, + ) + calib_data = _load_calibration_data( tokenizer, dataset=calib_dataset, @@ -8836,9 +8954,11 @@ def _measure_sensitivity_from_quantized_model( from omlx.utils.model_loading import ( _checkpoint_has_mtp_weights, _has_mtp_heads, - lm_load_compat as lm_load, maybe_apply_pre_load_patches, ) + from omlx.utils.model_loading import ( + lm_load_compat as lm_load, + ) # Reuse the centralised pre-load dispatch (DeepSeek V4 base patch, # load_model replacement for F8_E8M0 checkpoints, MTP sanitize, ...) diff --git a/omlx/patches/deepseek_v41/LICENSE b/omlx/patches/deepseek_v41/LICENSE new file mode 100644 index 0000000000..d42fae903e --- /dev/null +++ b/omlx/patches/deepseek_v41/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 DeepSeek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/omlx/patches/deepseek_v41/__init__.py b/omlx/patches/deepseek_v41/__init__.py new file mode 100644 index 0000000000..4e6ef8c2fe --- /dev/null +++ b/omlx/patches/deepseek_v41/__init__.py @@ -0,0 +1,19 @@ +# SPDX-License-Identifier: MIT +"""DeepSeek V4.1 reference port for oMLX's pinned mlx-vlm runtime.""" + + +def apply_patch(): + import sys + + import mlx_lm.models.cache as caches + + from omlx.cache.type_handlers import CacheType + from omlx.cache.type_registry import CacheTypeRegistry + + from . import model + from .cache import DeepseekV41Cache, DeepseekV41CacheHandler + + sys.modules.setdefault("mlx_vlm.models.deepseek_v41", model) + caches.DeepseekV41Cache = DeepseekV41Cache + CacheTypeRegistry.register(DeepseekV41CacheHandler()) + CacheTypeRegistry._class_name_map["DeepseekV41Cache"] = CacheType.DEEPSEEK_V41 diff --git a/omlx/patches/deepseek_v41/activation.py b/omlx/patches/deepseek_v41/activation.py new file mode 100644 index 0000000000..cb759d7f34 --- /dev/null +++ b/omlx/patches/deepseek_v41/activation.py @@ -0,0 +1,121 @@ +# SPDX-License-Identifier: MIT +"""Single-pass FP8 activation round trips with one SIMD group per scale group.""" + +from functools import cache + +import mlx.core as mx + +_ROUND = r""" + // Clamp to 448 * 2^-126 so the power-of-two scale stays normal. + const float amax = max(simd_max(abs(v)), 0x1.cp-118f); + const int scale_exponent = max(int(ceil(log2(amax / 448.0f))), -126); + // Integer powers of two must be exact, including FP8 rounding ties. + const float scale = as_type(uint(scale_exponent + 127) << 23); + const float scaled = clamp(v / scale, -448.0f, 448.0f); + const float a = abs(scaled); + const int step_exponent = max(int(floor(log2(max(a, 0x1p-9f)))) - 3, -9); + const float step = as_type(uint(step_exponent + 127) << 23); + const float q = sign(scaled) * min(rint(a / step) * step, 448.0f); + if (i < n) y[i] = T(q * scale); +""" + +_SOURCE = r""" + const uint i = thread_position_in_grid.x; + const uint n = N; + const float v = i < n ? float(x[i]) : 0.0f; +""" + _ROUND + +_TAIL_SOURCE = r""" + const uint i = thread_position_in_grid.x; + const uint n = N; + float v = 0.0f; + if (i < n) { + float g = gate[i], u = up[i]; + if (limit[0] != 0.0f) { + g = min(g, limit[0]); + u = clamp(u, -limit[0], limit[0]); + } + // Match MLX sigmoid arithmetic before the intermediate dtype cast. + const float neg_sigmoid = 1.0f / (1.0f + exp(abs(g))); + const float sigmoid = g < 0 ? neg_sigmoid : 1.0f - neg_sigmoid; + float value = (g * sigmoid) * u; + if (WEIGHTED) value *= weights[i / D]; + v = float(T(value)); + } +""" + _ROUND + + +@cache +def _kernel(tail=False, paired=False): + if paired: + return mx.fast.metal_kernel( + name="v41_paired_swiglu_fp8_activation", + input_names=["pair", "weights", "limit"], + output_names=["y"], + source=_TAIL_SOURCE.replace( + "float g = gate[i], u = up[i];", + "const uint j = (i / D) * (2 * D) + i % D; " + "float g = pair[j], u = pair[j + D];", + ), + ) + return mx.fast.metal_kernel( + name="v41_swiglu_fp8_activation" if tail else "v41_fp8_activation", + input_names=["gate", "up", "weights", "limit"] if tail else ["x"], + output_names=["y"], + source=_TAIL_SOURCE if tail else _SOURCE, + ) + + +def quantize_fp8_activation(x): + return _kernel()( + inputs=[x], + template=[("T", x.dtype), ("N", x.size)], + grid=(x.size, 1, 1), + threadgroup=(256, 1, 1), + output_shapes=[x.shape], + output_dtypes=[x.dtype], + )[0] + + +def quantize_swiglu_activation(gate, up, weights, dtype, limit): + return _kernel(tail=True)( + inputs=[ + gate, + up, + weights if weights is not None else mx.ones((1,)), + mx.array([float(limit or 0)], mx.float32), + ], + template=[ + ("T", dtype), + ("N", gate.size), + ("D", gate.shape[-1]), + ("WEIGHTED", weights is not None), + ], + grid=(gate.size, 1, 1), + threadgroup=(256, 1, 1), + output_shapes=[gate.shape], + output_dtypes=[dtype], + )[0] + + +def quantize_paired_swiglu_activation(pair, weights, dtype, limit): + """Read concatenated gate/up rows without materializing two contiguous copies.""" + shape = (*pair.shape[:-1], pair.shape[-1] // 2) + size = pair.size // 2 + return _kernel(paired=True)( + inputs=[ + pair, + weights if weights is not None else mx.ones((1,)), + mx.array([float(limit or 0)], mx.float32), + ], + template=[ + ("T", dtype), + ("N", size), + ("D", shape[-1]), + ("WEIGHTED", weights is not None), + ], + grid=(size, 1, 1), + threadgroup=(256, 1, 1), + output_shapes=[shape], + output_dtypes=[dtype], + )[0] diff --git a/omlx/patches/deepseek_v41/cache.py b/omlx/patches/deepseek_v41/cache.py new file mode 100644 index 0000000000..454e650749 --- /dev/null +++ b/omlx/patches/deepseek_v41/cache.py @@ -0,0 +1,121 @@ +# SPDX-License-Identifier: MIT +"""Request-local CSA2 state, including compressor tails and Engram lookback.""" + +import mlx.core as mx +from mlx_lm.models.cache import ArraysCache + +from ...cache.type_handlers import ArraysCacheHandler, CacheType + + +class DeepseekV41Cache(ArraysCache): + # offset, window KV, compressed KV, index K, partial KV, partial gates, history + def __init__(self, compress_ratio=0): + super().__init__(7) + self.compress_ratio = compress_ratio + + @property + def offset(self): + return self.cache[0] if self.cache[0] is not None else 0 + + def size(self): + offsets = self.cache[0] + if offsets is None: + return 0 + # A single row already contains its maximum; avoid a GPU reduction. + return int(offsets.item() if offsets.size == 1 else mx.max(offsets).item()) + + @property + def meta_state(self): + return ( + ("deepseek_v41", "2") + if self.compress_ratio is None + else ("deepseek_v41", "3", str(self.compress_ratio)) + ) + + @meta_state.setter + def meta_state(self, value): + if tuple(value) == ("deepseek_v41", "2"): + self.compress_ratio = None + elif len(value) == 3 and tuple(value[:2]) == ("deepseek_v41", "3"): + self.compress_ratio = int(value[2]) + if self.compress_ratio < 0: + raise ValueError("Invalid DeepSeek V4.1 compression ratio") + else: + raise ValueError("Unknown DeepSeek V4.1 cache format") + + def prepare(self, lengths=None, **kwargs): + self.left_padding = None + self.lengths = mx.array(lengths) if lengths is not None else None + + def extract(self, idx): + result = type(self)(self.compress_ratio) + result.cache = [x[idx : idx + 1] if x is not None else None for x in self.cache] + return result + + @classmethod + def merge(cls, caches): + result = cls(caches[0].compress_ratio if caches else 0) + for other in caches: + if result.cache[0] is None and result.left_padding is None: + result.cache = list(other.cache) + result.left_padding = mx.zeros((other.batch_size,), mx.int32) + else: + result.extend(other) + return result + + def extend(self, other): + if self.compress_ratio != other.compress_ratio: + raise ValueError("Cannot batch different V4.1 compression ratios") + a_batch, b_batch = self.batch_size, other.batch_size + states = [] + for i, (a, b) in enumerate(zip(self.cache, other.cache)): + if a is None and b is None: + states.append(None) + continue + template = a if a is not None else b + fill = -1 if i == 6 else 0 + if a is None: + a = mx.full((a_batch, *template.shape[1:]), fill, template.dtype) + if b is None: + b = mx.full((b_batch, *template.shape[1:]), fill, template.dtype) + if a.ndim > 1 and a.shape[1] != b.shape[1]: + width = max(a.shape[1], b.shape[1]) + a = mx.pad( + a, + [(0, 0), (0, width - a.shape[1])] + [(0, 0)] * (a.ndim - 2), + constant_values=fill, + ) + b = mx.pad( + b, + [(0, 0), (0, width - b.shape[1])] + [(0, 0)] * (b.ndim - 2), + constant_values=fill, + ) + states.append(mx.concatenate([a, b], 0)) + self.cache = states + self.left_padding = mx.concatenate( + [ + ( + self.left_padding + if self.left_padding is not None + else mx.zeros((a_batch,), mx.int32) + ), + ( + other.left_padding + if other.left_padding is not None + else mx.zeros((b_batch,), mx.int32) + ), + ] + ) + self.lengths = None + + +class DeepseekV41CacheHandler(ArraysCacheHandler): + @property + def cache_type(self): + return CacheType.DEEPSEEK_V41 + + def reconstruct_cache(self, state, meta_state=None, token_count=0): + states = state.get("states", []) + if len(states) != 7: + raise ValueError("V4.1 delta requires its complete block chain") + return DeepseekV41Cache.from_state(states, meta_state) diff --git a/omlx/patches/deepseek_v41/calibration.py b/omlx/patches/deepseek_v41/calibration.py new file mode 100644 index 0000000000..916aa9366f --- /dev/null +++ b/omlx/patches/deepseek_v41/calibration.py @@ -0,0 +1,144 @@ +# SPDX-License-Identifier: MIT +"""Collect oQe statistics through V4.1's complete cache and Engram forward.""" + +import copy + +import mlx.core as mx + + +def collect_imatrix( + model, + tokenizer, + *, + num_samples=32, + seq_length=512, + progress=None, + initial=None, + calib_dataset="oqe_code_multilingual", + adaptive=False, +): + from ...oq import ( + _OQE_MAX_ADAPTIVE_SAMPLES, + _OQE_MAX_SAMPLE_MULTIPLIER, + OQImatrixCollector, + _imatrix_expert_coverage_stats, + _imatrix_expert_coverage_sufficient, + _load_calibration_data, + ) + + maximum = num_samples + if adaptive: + maximum = max( + num_samples, + min(num_samples * _OQE_MAX_SAMPLE_MULTIPLIER, _OQE_MAX_ADAPTIVE_SAMPLES), + ) + samples = _load_calibration_data(tokenizer, calib_dataset, maximum, seq_length) + if samples is None or samples.shape[0] == 0: + raise ValueError("V4.1 oQe requires nonempty calibration data") + collector = OQImatrixCollector() + start = 0 + if initial is not None: + expected = { + "model_type": "deepseek_v41", + "dataset": calib_dataset, + "seq_length": seq_length, + } + if any(initial.metadata.get(key) != value for key, value in expected.items()): + raise ValueError("V4.1 calibration resume metadata does not match") + start = int(initial.metadata.get("processed_samples", -1)) + if not 0 <= start < len(samples): + raise ValueError("V4.1 calibration resume has no remaining samples") + collector.entries = copy.deepcopy(initial.entries) + core = model.language_model + installed = collector.install(model) + processed = start + rounds = [] + try: + for index, tokens in enumerate(samples[start:], start=start): + cache = core.make_cache() + logits = core(tokens[None], cache=cache) + mx.eval(logits[:, -1], [entry.state for entry in cache]) + if progress is not None: + progress(index + 1, len(samples), collector.entries) + del logits, cache + processed = index + 1 + if adaptive and processed >= num_samples and processed % num_samples == 0: + coverage = _imatrix_expert_coverage_stats(collector.entries) + sufficient = _imatrix_expert_coverage_sufficient( + coverage, require_expert_counts=collector.switch_capture_modules > 0 + ) + rounds.append(dict(processed_samples=processed, coverage=coverage)) + if sufficient: + break + if not collector.entries: + raise ValueError("V4.1 oQe captured no projection inputs") + metadata = { + "model_type": "deepseek_v41", + "dataset": calib_dataset, + "processed_samples": processed, + "requested_samples": num_samples, + "adaptive_max_samples": len(samples), + "rounds": rounds, + "seq_length": seq_length, + "capture_modules": installed, + "captured_modules": len(collector.entries), + "expert_coverage": _imatrix_expert_coverage_stats(collector.entries), + "forward": "full_model_with_request_local_cache_and_engram", + } + return collector.entries, metadata + finally: + collector.restore(model) + + +def collect_checkpoint_imatrix( + model_path, + *, + calib_dataset, + num_samples, + seq_length, + progress_callback=None, + progress_start=13.0, + progress_end=18.0, +): + """Adapter for the official oQ collector, including cancellation cleanup.""" + from ...oq import _emit_progress, _imatrix_expert_coverage_sufficient + from .loading import load + + model, processor = load(model_path, engram_ssd_offload=True) + try: + + def progress(done, total, entries): + _emit_progress( + progress_callback, + "imatrix", + progress_start + (progress_end - progress_start) * done / total, + f"V4.1 calibration {done}/{total}", + {"entry_count": len(entries), "processed_samples": done}, + ) + + entries, metadata = collect_imatrix( + model, + processor.tokenizer, + calib_dataset=calib_dataset, + num_samples=num_samples, + seq_length=seq_length, + progress=progress, + adaptive=True, + ) + coverage = metadata["expert_coverage"] + sufficient = _imatrix_expert_coverage_sufficient( + coverage, require_expert_counts=True + ) + metadata.update( + coverage=coverage, + requires_expert_counts=True, + coverage_sufficient=sufficient, + collection_sufficient=sufficient, + uncalibrated_policy="preserve_source_precision", + ) + return entries, metadata + finally: + model.close() + del model, processor + mx.synchronize() + mx.clear_cache() diff --git a/omlx/patches/deepseek_v41/config.py b/omlx/patches/deepseek_v41/config.py new file mode 100644 index 0000000000..e9bc98093e --- /dev/null +++ b/omlx/patches/deepseek_v41/config.py @@ -0,0 +1,210 @@ +# SPDX-License-Identifier: MIT +"""DeepSeek V4.1 configuration; field defaults follow the official reference.""" + +from dataclasses import dataclass, fields +from typing import Literal + + +@dataclass +class ModelConfig: + """Field names are exactly the config JSON keys. The defaults are a small model that + `python model.py` can run, not the released shapes -- though the scale-independent + values (norm_eps, score_func, hc_*, engram_*) do match it.""" + + # runtime limits rather than model shape: they size the KV caches + max_batch_size: int = 4 + max_seq_len: int = 4096 + temperature: float = 1 + dtype: Literal["bf16", "fp8"] = "fp8" + expert_dtype: Literal["fp4"] | None = "fp4" + vocab_size: int = 129280 + dim: int = 1024 + moe_inter_dim: int = 1024 + n_layers: int = 5 + n_mtp_layers: int = ( + 1 # extra draft layers appended after the backbone, indices n_layers.. + ) + n_heads: int = 16 + # moe + n_routed_experts: int = 8 + n_shared_experts: int = 1 + n_activated_experts: int = 2 + score_func: Literal["softmax", "sigmoid", "sqrtsoftplus"] = "sqrtsoftplus" + gate_temp: float = 1.0 + norm_topk_prob: bool = True + route_scale: float = 1.0 + swiglu_limit: float = 0.0 + # attention: latent q/kv projections, plus a LoRA-factorised output projection over o_groups + q_lora_rank: int = 256 + head_dim: int = 128 + rope_head_dim: int = 32 + norm_eps: float = 1e-20 + o_groups: int = 8 + o_lora_rank: int = 256 + # sparse attention: every layer attends over a sliding window, and may add compressed KV on top + window_size: int = 128 + # one entry per layer, MTP layers included: 0 = sliding window only, r = KV compressed r-to-1 + compress_ratios: tuple[int, ...] = (0, 2, 2, 1, 1, 0) + # layers sharing a ratio also share one compressed KV and one indexer, produced by the first + kv_source_layers: tuple[int, ...] = (1, 3) + index_source_layers: tuple[int, ...] = (1, 3) + # rope, with YaRN extrapolation when original_seq_len > 0. Compressed KV rotates at its own + # theta because one latent stands for compress_ratio tokens, so its positions are further apart. + compress_rope_theta: float = 40000.0 + original_seq_len: int = 0 + rope_theta: float = 10000.0 + rope_factor: float = 40 + beta_fast: int = 32 + beta_slow: int = 1 + # the indexer: a small extra attention that scores compressed positions, so each query can keep + # just `index_topk` of them. Names match DeepSeek-V3.2-Exp, where this mechanism first appeared. + index_n_heads: int = 16 + index_head_dim: int = 64 + index_topk: int = 64 + # candidate pre-filtering: candidate_source_layer < 0 turns it off and the other two are unused + candidate_source_layer: int = -1 + candidate_topk_blocks: int = 0 + candidate_block_size: int = 0 + # hyper-connections: the residual stream is carried as hc_mult parallel copies + hc_mult: int = 4 + hc_sinkhorn_iters: int = 20 + hc_eps: float = 1e-6 + # engram: n-gram hash lookups added into the residual stream at a few layers + engram_layer_ids: tuple[int, ...] = () + engram_num_embeddings: tuple[ + int, ... + ] = () # unpadded table rows; each rank allocates ceil(rows / world_size) + engram_max_ngram_size: int = 1 + engram_vocab_size: int = ( + 0 # bucket size each (n-gram size, head) starts searching primes from + ) + engram_n_heads: int = 0 + engram_head_dim: int = 0 + engram_pad_id: int = ( + 2 # token that fills n-gram slots with no history; matches training + ) + # size of the compressed tokenizer vocab; every hash multiplier is derived from it + engram_compressed_vocab_size: int = 0 + # vision (VL); vision_n_layers == 0 disables the vision path + vision_n_layers: int = 0 + vision_dim: int = 1024 + vision_n_heads: int = 16 + vision_inter_dim: int = 2816 + vision_patch_size: int = 14 + vision_rope_theta: float = 10000.0 + vision_downsample_ratio: int = 3 + vision_max_n_token: int = 1024 + vision_min_pixels: int = 544 * 544 + vision_max_wh_ratio: int | None = None + # raw id of <|deepseek_image|>; every position of an image span carries this id in input_ids + image_token_id: int = 129264 + # Draft weights and standalone forward are separate from server verification. + preserve_mtp: bool = False + dspark_block_size: int = 0 + dspark_noise_token_id: int = 0 + dspark_target_layer_ids: tuple[int, ...] = () + dspark_markov_rank: int = 256 + dspark_n_routed_experts: int = 0 + dspark_n_activated_experts: int = 0 + + @property + def vision_enabled(self) -> bool: + return self.vision_n_layers > 0 + + def get_moe_config(self, layer_id: int) -> tuple[int, int]: + """Return the routed/activated expert counts for a given layer.""" + if layer_id < self.n_layers: + return self.n_routed_experts, self.n_activated_experts + return ( + self.dspark_n_routed_experts or self.n_routed_experts, + self.dspark_n_activated_experts or self.n_activated_experts, + ) + + model_type: str = "deepseek_v41" + + @classmethod + def from_dict(cls, config): + text = config.get("text_config") or config + aliases = { + "hidden_size": "dim", + "moe_intermediate_size": "moe_inter_dim", + "num_hidden_layers": "n_layers", + "num_attention_heads": "n_heads", + "num_experts_per_tok": "n_activated_experts", + "scoring_func": "score_func", + "routed_scaling_factor": "route_scale", + "qk_rope_head_dim": "rope_head_dim", + "rms_norm_eps": "norm_eps", + "sliding_window": "window_size", + "kv_source_layer_ids": "kv_source_layers", + "index_source_layer_ids": "index_source_layers", + "candidate_source_layer_id": "candidate_source_layer", + "engram_pad_token_id": "engram_pad_id", + "num_nextn_predict_layers": "n_mtp_layers", + "dspark_num_experts_per_tok": "dspark_n_activated_experts", + "max_position_embeddings": "max_seq_len", + } + values = {aliases.get(k, k): v for k, v in text.items()} + values["preserve_mtp"] = bool( + config.get("omlx_deepseek_v41", {}).get("preserve_mtp", False) + ) + rope = text.get("rope_scaling") or {} + values.update( + { + aliases.get(k, k): v + for k, v in config.items() + if k in ("image_token_id", "model_type") + } + ) + values.update( + { + "original_seq_len": rope.get("original_max_position_embeddings", 0), + "rope_factor": rope.get("factor", 1), + "beta_fast": rope.get("beta_fast", 32), + "beta_slow": rope.get("beta_slow", 1), + } + ) + vision = config.get("vision_config") + if vision: + va = { + "num_hidden_layers": "n_layers", + "hidden_size": "dim", + "num_attention_heads": "n_heads", + "intermediate_size": "inter_dim", + "max_image_tokens": "max_n_token", + } + values.update({"vision_" + va.get(k, k): v for k, v in vision.items()}) + fields_set = {f.name for f in fields(cls)} + result = cls(**{k: v for k, v in values.items() if k in fields_set}) + result.validate() + return result + + def validate(self): + if len(self.compress_ratios) < self.n_layers: + raise ValueError("compress_ratios must cover every backbone layer") + if self.n_heads % self.o_groups or self.head_dim % 32: + raise ValueError( + "Attention heads must divide into groups; head_dim must divide by 32" + ) + if self.rope_head_dim % 2 or self.rope_head_dim > min( + self.head_dim, self.index_head_dim + ): + raise ValueError("Invalid RoPE head dimension") + if self.index_head_dim % 32 or self.n_shared_experts != 1: + raise ValueError("Expected 32-aligned index heads and one shared expert") + if not 1 <= self.n_activated_experts <= self.n_routed_experts: + raise ValueError("Invalid routed expert count") + source = None + index = None + for i, ratio in enumerate(self.compress_ratios[: self.n_layers]): + if i in self.kv_source_layers: + source = i + index = None + if i in self.index_source_layers: + index = i + if ratio and ( + source is None or index is None or self.compress_ratios[source] != ratio + ): + raise ValueError(f"Layer {i} has no compatible KV/index source") + if len(self.engram_layer_ids) != len(self.engram_num_embeddings): + raise ValueError("Engram layer/table counts differ") diff --git a/omlx/patches/deepseek_v41/convert.py b/omlx/patches/deepseek_v41/convert.py new file mode 100644 index 0000000000..f0164e09e4 --- /dev/null +++ b/omlx/patches/deepseek_v41/convert.py @@ -0,0 +1,242 @@ +# SPDX-License-Identifier: MIT +"""Stream the official checkpoint into MLX MXFP shards plus mmap Engram tables. + +Usage: python -m omlx.patches.deepseek_v41.convert --hf-path SRC --mlx-path DST +The source stays immutable. Engram files are hardlinked when possible, copied +otherwise. Use --preserve-mtp to retain all embedded DSpark stages. +""" + +import argparse +import json +import os +import re +import shutil +from pathlib import Path + +import mlx.core as mx +import numpy as np + +from .sharding import ShardWriter +from .storage import TensorFile, decode_array + + +def repack_weight(raw, dtype, scale, scale_dtype, force_dense=False): + """Losslessly repack E4M3/E2M1 bytes and E8M0 scales for MLX QMM.""" + if dtype.startswith("F8_E4M3") or dtype in ("I8", "U8"): + if scale is None or not scale_dtype.startswith("F8_E8M0"): + raise ValueError("Quantized weights require published E8M0 scales") + if np.any(scale == 255): + raise ValueError("NaN E8M0 scale") + bits = 8 if dtype.startswith("F8_E4M3") else 4 + if raw.ndim != 2 or raw.shape[-1] % 4: + raise ValueError("Packed matrix must be rank two with 4-byte-aligned rows") + scales = scale + if bits == 8: + scales = np.repeat(scale, 32, axis=0)[: raw.shape[0]] + width = raw.shape[-1] * (8 // bits) + if scales.shape != (raw.shape[0], width // 32): + raise ValueError("Unexpected block scale shape") + weight = mx.array(raw.view(np.uint8).copy().view("bsgr", grouped, weight).flatten(-2)) + + +class MarkovHead(nn.Module): + def __init__(self, c): + super().__init__() + self.embed = nn.Embedding(c.vocab_size, c.dspark_markov_rank) + self.head = nn.Linear(c.dspark_markov_rank, c.vocab_size, bias=False) + + def __call__(self, ids): + embedding = self.embed(ids) + return ( + project_logits(embedding, self.head.weight), + embedding, + ) + + +class ConfidenceHead(nn.Module): + def __init__(self, c): + super().__init__() + self.proj = nn.Linear(c.dim + c.dspark_markov_rank, 1, bias=False) + + def __call__(self, h, markov): + joined = mx.concatenate([h, markov], axis=-1).astype(mx.float32) + return (joined @ self.proj.weight.astype(mx.float32).T).squeeze(-1) + + +class DSparkBlock(Block): + def __init__(self, c, stage): + experts, active = c.get_moe_config(c.n_layers + stage) + draft = replace( + c, + n_routed_experts=experts, + n_activated_experts=active, + engram_layer_ids=(), + engram_num_embeddings=(), + ) + super().__init__(draft, c.n_layers + stage) + self.attn = DSparkAttention(draft, c.n_layers + stage) + if stage == 0: + self.main_proj = nn.Linear( + c.dim * len(c.dspark_target_layer_ids), c.dim, bias=False + ) + self.main_norm = RMSNorm(c.dim, c.norm_eps) + if stage == c.n_mtp_layers - 1: + self.norm = RMSNorm(c.dim, c.norm_eps) + self.markov_head = MarkovHead(c) + self.confidence_head = ConfidenceHead(c) + + def __call__(self, h, pre, cache): + ap, ao, ac = hc_mixes( + h, self.hc_attn_fn, self.hc_attn_scale, self.hc_attn_base, self._config + ) + h = hc_post(self.attn(self.attn_norm(hc_pre(h, pre)), cache), h, ao, ac) + fp, fo, fc = hc_mixes( + h, self.hc_ffn_fn, self.hc_ffn_scale, self.hc_ffn_base, self._config + ) + h = hc_post(self.ffn(self.ffn_norm(hc_pre(h, ap)), None), h, fo, fc) + return h, fp + + +def make_stages(c): + if c.dspark_block_size <= 0 or c.n_mtp_layers <= 0 or not c.dspark_target_layer_ids: + raise ValueError("MTP preservation requires a complete DSpark configuration") + if any(i < 0 or i >= c.n_layers for i in c.dspark_target_layer_ids): + raise ValueError("Invalid DSpark target layer") + if len(c.compress_ratios) < c.n_layers + c.n_mtp_layers or any( + c.compress_ratios[c.n_layers : c.n_layers + c.n_mtp_layers] + ): + raise ValueError("DSpark stages require uncompressed local attention") + return [DSparkBlock(c, i) for i in range(c.n_mtp_layers)] + + +def make_cache(c): + return [DSparkContextCache(c.window_size) for _ in range(c.n_mtp_layers)] + + +def forward_spec(model, input_ids, main_hidden, cache, *, temperature=0.0): + """Seed context on the first call; subsequently propose a full draft block. + + main_hidden must contain only newly committed target positions. Calls after + priming append exactly one position, matching the published DSpark contract. + Returned proposals still require verification by the target model. + """ + c = model._config + if not c.preserve_mtp: + raise ValueError("This checkpoint was loaded without DSpark weights") + if len(cache) != len(model.mtp) or len({item.offset for item in cache}) != 1: + raise ValueError("DSpark stage cache offsets differ") + if input_ids.ndim != 2 or input_ids.shape[1] != 1: + raise ValueError("DSpark requires one initial token per batch row") + if ( + main_hidden.ndim != 3 + or main_hidden.shape[0] != input_ids.shape[0] + or main_hidden.shape[-1] != c.dim * len(c.dspark_target_layer_ids) + ): + raise ValueError("Invalid DSpark target hidden shape") + initial = cache[0].offset == 0 + if main_hidden.shape[1] < 1 or (not initial and main_hidden.shape[1] != 1): + raise ValueError("DSpark decode appends exactly one committed target position") + first = model.mtp[0] + main_x = first.main_norm(first.main_proj(main_hidden)) + for stage, item in zip(model.mtp, cache): + stage.attn.append_context(main_x, item) + if initial: + return None + logits, h = proposal_forward(model, input_ids, cache) + final = model.mtp[-1] + proposed, biases, embeddings = [input_ids[:, 0]], [], [] + for i in range(c.dspark_block_size): + bias, embedding = final.markov_head(proposed[-1]) + step = logits[:, i] + bias + token = ( + mx.argmax(step, axis=-1) + if temperature == 0 + else mx.random.categorical(step / temperature) + ) + proposed.append(token.astype(input_ids.dtype)) + biases.append(step) + embeddings.append(embedding) + return ( + mx.stack(proposed, axis=1), + mx.stack(biases, axis=1), + final.confidence_head(h, mx.stack(embeddings, axis=1)), + ) + + +def proposal_forward(model, input_ids, cache, draft_length=None): + """Compute parallel draft logits; the shared loop applies Markov biases.""" + c = model._config + width = max(1, min(draft_length or c.dspark_block_size, c.dspark_block_size)) + input_ids = input_ids.reshape(input_ids.shape[0], -1)[:, -1:] + ids = mx.concatenate( + [ + input_ids, + mx.full( + (input_ids.shape[0], width - 1), + c.dspark_noise_token_id, + dtype=input_ids.dtype, + ), + ], + axis=1, + ) + h = mx.repeat(model.embed(ids)[..., None, :], c.hc_mult, -2) + pre = mx.broadcast_to((mx.arange(c.hc_mult) == 0).astype(mx.float32), h.shape[:-1]) + for stage, item in zip(model.mtp, cache): + h, pre = stage(h, pre, item) + final = model.mtp[-1] + h = hc_pre(h, pre) + logits = project_logits(final.norm(h), model.head.weight) + return logits, h diff --git a/omlx/patches/deepseek_v41/encoding.py b/omlx/patches/deepseek_v41/encoding.py new file mode 100644 index 0000000000..359bdf528f --- /dev/null +++ b/omlx/patches/deepseek_v41/encoding.py @@ -0,0 +1,982 @@ +# ruff: noqa +# SPDX-License-Identifier: MIT +# Source: deepseek-ai/DeepSeek-V4.1-Flash @ dba1be0a40aa45a94ad051997016db3960a90277 (encoding/encoding.py). +""" +DeepSeek-V4.1 Text and Vision Encoding + +A fully self-contained implementation for encoding/decoding DeepSeek-V4.1 chat +messages with tool calling, thinking mode, quick instruction tasks, and image +content blocks. No dependency on encoding_dsv4. + +V4.1 changes relative to V4: + +1. DSML tag names: tool calls are wrapped in "<|DSML| calls>" blocks with + "<|DSML| invoke>" / "<|DSML| parameter>" tags (leading-space tag names). +2. Numeric reasoning effort: "Reasoning Effort: {budget} (range 1-100, ...)". + Accepts an int in [1, 100] or one of "low"/"high"/"max" + (mapped to 50/75/100). Defaults to "high". Only rendered in thinking mode. +3. Mid-conversation system messages are supported via the "<|System|>" token. + A mid-conversation system message behaves like a user message for the purpose + of appending the assistant generation header. +""" + +from typing import Any, Dict, List, Union, Optional, Tuple +import copy +import json +import re + +# ============================================================ +# Special Tokens +# ============================================================ + +bos_token: str = "<|begin▁of▁sentence|>" +eos_token: str = "<|end▁of▁sentence|>" +thinking_start_token: str = "" +thinking_end_token: str = "" +dsml_token: str = "|DSML|" + +USER_SP_TOKEN = "<|User|>" +ASSISTANT_SP_TOKEN = "<|Assistant|>" +LATEST_REMINDER_SP_TOKEN = "<|latest_reminder|>" + +IMAGE_PLACEHOLDER = "<|deepseek_image|>" +IMAGE_TAG_PATTERN = re.compile(r"(.*?)", re.DOTALL) + +# Task special tokens for internal classification tasks +DS_TASK_SP_TOKENS = { + "action": "<|action|>", + "query": "<|query|>", + "authority": "<|authority|>", + "domain": "<|domain|>", + "title": "<|title|>", + "read_url": "<|read_url|>", +} +VALID_TASKS = set(DS_TASK_SP_TOKENS.keys()) + +# ============================================================ +# Templates +# ============================================================ + +system_msg_template: str = "{content}" +user_msg_template: str = "{content}" +latest_reminder_msg_template: str = "{content}" +assistant_msg_template: str = "{reasoning}{content}{tool_calls}" + eos_token +assistant_msg_wo_eos_template: str = "{reasoning}{content}{tool_calls}" +thinking_template: str = "{reasoning_content}" + +response_format_template: str = ( + "## Response Format:\n\nYou MUST strictly adhere to the following schema to reply:\n{schema}" +) + +tool_output_template: str = ( + "{content}" +) + +# ============================================================ +# Utility Functions +# ============================================================ + +def to_json(value: Any) -> str: + """Serialize a value to JSON string.""" + try: + return json.dumps(value, ensure_ascii=False) + except: + return json.dumps(value, ensure_ascii=True) + + +def tools_from_openai_format(tools): + """Extract function definitions with namespace-qualified names.""" + functions = [] + for tool in tools: + function = dict(tool["function"]) + if tool.get("namespace") is not None: + function["namespace"] = tool["namespace"] + function["name"] = _tool_name_for_encoding(function) + namespace = function.pop("namespace", None) + if isinstance(namespace, dict) and namespace.get("description"): + function["description"] = ( + namespace["description"] + "\n" + (function.get("description") or "") + ) + functions.append(function) + return functions + + +def _split_tool_name(name: str, namespace: Optional[str] = None) -> Tuple[Optional[str], str]: + """Split a qualified name and validate any explicit namespace.""" + prefix, separator, bare_name = name.partition("::") + if separator: + assert namespace in (None, prefix), ( + f"Conflicting tool namespaces: {namespace} != {prefix}" + ) + namespace, name = prefix, bare_name + assert "::" not in name, f"Tool name must not contain '::': {name}" + assert namespace is None or "::" not in namespace, ( + f"Tool namespace must not contain '::': {namespace}" + ) + return namespace, name + + +def _tool_name_for_encoding(tool: Dict[str, Any]) -> str: + namespace = tool.get("namespace") + if isinstance(namespace, dict): + namespace = namespace["name"] + namespace, name = _split_tool_name(tool["name"], namespace) + return name if namespace is None else f"{namespace}::{name}" + + +def tool_calls_from_openai_format(tool_calls): + """Convert OpenAI-format tool calls to internal format.""" + calls = [] + for tool_call in tool_calls: + function = tool_call["function"] + namespace, name = _split_tool_name( + function["name"], tool_call.get("namespace") or function.get("namespace") + ) + call = {"name": name, "arguments": function["arguments"]} + if namespace is not None: + call["namespace"] = namespace + calls.append(call) + return calls + + +def tool_calls_to_openai_format(tool_calls): + """Convert internal tool calls to OpenAI format.""" + calls = [] + for tool_call in tool_calls: + call = { + "type": "function", + "function": { + "name": tool_call["name"], + "arguments": tool_call["arguments"], + } + } + if tool_call.get("namespace") is not None: + call["namespace"] = tool_call["namespace"] + calls.append(call) + return calls + + +def decode_dsml_to_arguments(tool_name: str, tool_args: Dict[str, Tuple[str, str]]) -> Dict[str, str]: + """ + Decode DSML parameters back to a tool call dict. + + Args: + tool_name: Name of the tool. + tool_args: Dict mapping param_name -> (value, is_string_flag). + + Returns: + Dict with "name", "arguments" (JSON string), and optional "namespace". + """ + def _decode_value(key: str, value: str, string: str): + if string == "true": + value = to_json(value) + return f"{to_json(key)}: {value}" + + tool_args_json = "{" + ", ".join([_decode_value(k, v, string=is_str) for k, (v, is_str) in tool_args.items()]) + "}" + namespace, name = _split_tool_name(tool_name) + tool_call = dict(name=name, arguments=tool_args_json) + if namespace is not None: + tool_call["namespace"] = namespace + return tool_call + + +# ============================================================ +# Preprocessing +# ============================================================ + +def merge_tool_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """ + Merge tool messages into the preceding user message using content_blocks format. + + DeepSeek-V4.1 does not have a standalone "tool" role; instead, tool results + are encoded as blocks within user messages. + """ + merged: List[Dict[str, Any]] = [] + + for msg in messages: + msg = copy.deepcopy(msg) + role = msg.get("role") + + if role == "tool": + # Convert tool message to a user message with tool_result block + tool_block = { + "type": "tool_result", + "tool_use_id": msg.get("tool_call_id", ""), + "content": msg.get("content", ""), + } + # Merge into previous message if it's already a user (merged tool) + if merged and merged[-1].get("role") == "user" and "content_blocks" in merged[-1]: + merged[-1]["content_blocks"].append(tool_block) + else: + merged.append({ + "role": "user", + "content_blocks": [tool_block], + }) + elif role == "user": + content_blocks = msg.get("content_blocks") + if content_blocks is None: + content_blocks = [{"type": "text", "text": msg.get("content", "")}] + if merged and merged[-1].get("role") == "user" and "content_blocks" in merged[-1] and merged[-1].get("task") is None: + merged[-1]["content_blocks"].extend(content_blocks) + else: + # Preserve structured content and all message-level metadata. + new_msg = msg + new_msg["content_blocks"] = content_blocks + merged.append(new_msg) + else: + merged.append(msg) + + return merged + + +def sort_tool_results_by_call_order(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """ + Sort tool_result blocks within user messages by the order of tool_calls + in the preceding assistant message. + """ + last_tool_call_order: Dict[str, int] = {} + + for msg in messages: + role = msg.get("role") + if role == "assistant" and msg.get("tool_calls"): + last_tool_call_order = {} + for idx, tc in enumerate(msg["tool_calls"]): + tc_id = tc.get("id") or tc.get("function", {}).get("id", "") + if tc_id: + last_tool_call_order[tc_id] = idx + + elif role == "user" and msg.get("content_blocks"): + tool_blocks = [b for b in msg["content_blocks"] if b.get("type") == "tool_result"] + if len(tool_blocks) > 1 and last_tool_call_order: + sorted_blocks = sorted( + tool_blocks, + key=lambda b: last_tool_call_order.get(b.get("tool_use_id", ""), 0) + ) + sorted_idx = 0 + new_blocks = [] + for block in msg["content_blocks"]: + if block.get("type") == "tool_result": + new_blocks.append(sorted_blocks[sorted_idx]) + sorted_idx += 1 + else: + new_blocks.append(block) + msg["content_blocks"] = new_blocks + + return messages + + +# ============================================================ +# Vision Message Preprocessing +# ============================================================ + +def parse_tagged_text(text: str) -> Union[str, List[Dict[str, Any]]]: + """Convert ``path`` text into standard content blocks.""" + matches = list(IMAGE_TAG_PATTERN.finditer(text)) + remaining = IMAGE_TAG_PATTERN.sub("", text) + if "" in remaining or "" in remaining: + raise ValueError("Malformed path tag") + if not matches: + return text + + blocks: List[Dict[str, Any]] = [] + cursor = 0 + for match in matches: + if match.start() > cursor: + blocks.append({"type": "text", "text": text[cursor:match.start()]}) + path = match.group(1) + if not path: + raise ValueError("Image path must not be empty") + blocks.append({ + "type": "image_url", + "image_url": {"url": path}, + }) + cursor = match.end() + if cursor < len(text): + blocks.append({"type": "text", "text": text[cursor:]}) + return blocks + + +def _is_image_block(block: Dict[str, Any]) -> bool: + """Return whether a content block is an OpenAI/Anthropic/internal image.""" + return isinstance(block, dict) and block.get("type") in ("image", "image_url") + + +def _extract_image(block: Dict[str, Any]) -> Dict[str, Any]: + """Normalize a supported image block into an internal image record.""" + record: Dict[str, Any] = {"type": "image"} + if block.get("type") == "image_url": + image_url = block.get("image_url") + if isinstance(image_url, str): + record["url"] = image_url + else: + record["url"] = (image_url or {}).get("url", "") + else: + for key in ("source", "url", "data"): + if key in block: + record[key] = block[key] + if not any(record.get(key) for key in ("source", "url", "data")): + raise ValueError("Image block does not contain a valid source") + return record + + +def _process_image_blocks( + blocks: List[Any], image_placeholder: str = IMAGE_PLACEHOLDER +) -> Tuple[List[Any], List[Dict[str, Any]]]: + """Replace image blocks and collect their records in one ordered traversal.""" + new_blocks: List[Any] = [] + images: List[Dict[str, Any]] = [] + for block in blocks: + if not isinstance(block, dict): + new_blocks.append(block) + continue + if _is_image_block(block): + new_blocks.append({"type": "text", "text": image_placeholder}) + images.append(_extract_image(block)) + elif block.get("type") == "tool_result" and isinstance(block.get("content"), list): + block = copy.copy(block) + block["content"], nested_images = _process_image_blocks( + block["content"], image_placeholder) + new_blocks.append(block) + images.extend(nested_images) + elif block.get("type") == "text": + text = block.get("text") or "" + if IMAGE_PLACEHOLDER in text: + raise ValueError( + f"Text block contains image placeholder '{IMAGE_PLACEHOLDER}': " + f"'{text[:100]}'. Images should be separate content blocks." + ) + new_blocks.append(block) + else: + new_blocks.append(block) + return new_blocks, images + + +def _validate_no_image_sp_tokens(msg: Dict[str, Any]) -> None: + """Reject user-supplied image placeholder tokens in textual fields.""" + content = msg.get("content") + if isinstance(content, str) and IMAGE_PLACEHOLDER in content: + raise ValueError( + f"Message content contains image special token '{IMAGE_PLACEHOLDER}'. " + "Images should be provided as image content blocks." + ) + reasoning_content = msg.get("reasoning_content") + if isinstance(reasoning_content, str) and IMAGE_PLACEHOLDER in reasoning_content: + raise ValueError( + f"reasoning_content contains image special token '{IMAGE_PLACEHOLDER}'" + ) + + +def process_image_messages( + messages: List[Dict[str, Any]], +) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: + """Normalize image blocks and return their records in prompt order.""" + processed: List[Dict[str, Any]] = [] + images: List[Dict[str, Any]] = [] + for msg in messages: + msg = copy.deepcopy(msg) + _validate_no_image_sp_tokens(msg) + + if isinstance(msg.get("content"), list) and "content_blocks" not in msg: + msg["content_blocks"] = msg.pop("content") + + if msg.get("content_blocks"): + msg["content_blocks"], message_images = _process_image_blocks( + msg["content_blocks"]) + images.extend(message_images) + if not isinstance(msg.get("content"), str): + texts = [ + block.get("text", "") + for block in msg["content_blocks"] + if isinstance(block, dict) and block.get("type") == "text" + ] + msg["content"] = "\n\n".join(texts) + + processed.append(msg) + return processed, images + + +def _read_until_stop(index: int, text: str, stop: List[str]) -> Tuple[int, str, Optional[str]]: + """ + Read text from index until one of the stop strings is found. + + Returns: + Tuple of (new_index, content_before_stop, matched_stop_string_or_None). + """ + min_pos = len(text) + matched_stop = None + + for s in stop: + pos = text.find(s, index) + if pos != -1 and pos < min_pos: + min_pos = pos + matched_stop = s + + if matched_stop: + content = text[index:min_pos] + return min_pos + len(matched_stop), content, matched_stop + else: + content = text[index:] + return len(text), content, None + +# ============================================================ +# V4.1 Special Tokens and DSML Tag Names +# ============================================================ + +SYSTEM_SP_TOKEN = "<|System|>" + +tool_calls_block_name: str = " calls" +tool_call_tag_name: str = " invoke" +tool_parameter_tag_name: str = " parameter" + +tool_call_template: str = ( + "<{dsml_token}{tool_call_tag_name} name=\"{name}\">\n{arguments}\n" +) +tool_calls_template = ( + "<{dsml_token}{tc_block_name}>\n{tool_calls}\n" +) + +# ============================================================ +# Reasoning Effort (numeric budget) +# ============================================================ + +REASONING_EFFORT_TEMPLATE = ( + "Reasoning Effort: {budget} " + "(range 1-100, the higher the value, the more thorough the reasoning)\n\n" +) + +REASONING_EFFORT_MAPPINGS: Dict[str, int] = { + "low": 50, + "high": 75, + "max": 100, +} +DEFAULT_REASONING_EFFORT = "high" + + +def render_reasoning_effort( + index: int, + thinking_mode: str, + effort: Union[str, int, None], +) -> str: + """Render the V4.1 numeric reasoning effort prefix (thinking mode, index 0 only).""" + if effort is None: + effort = DEFAULT_REASONING_EFFORT + assert ( + type(effort) is int and 1 <= effort <= 100 + ) or effort in REASONING_EFFORT_MAPPINGS, ( + "Invalid reasoning effort for deepseek_v41: " + f"{effort}, should be int within [1,100] or {list(REASONING_EFFORT_MAPPINGS)}" + ) + if type(effort) is str: + effort = REASONING_EFFORT_MAPPINGS[effort] + if index == 0 and thinking_mode == "thinking": + return REASONING_EFFORT_TEMPLATE.format(budget=effort) + return "" + + +# ============================================================ +# Tools rendering +# ============================================================ + +TOOLS_TEMPLATE = """## Tools + +You have access to a set of tools to help answer the user's question. You can invoke tools by writing a "<{dsml_token}{tc_block_name}>" block like the following: + +<{dsml_token}{tc_block_name}> +<{dsml_token}{tool_call_tag_name} name="$TOOL_NAME"> +<{dsml_token}{tool_parameter_tag_name} name="$PARAMETER_NAME" string="true|false">$PARAMETER_VALUE +... + +<{dsml_token}{tool_call_tag_name} name="$TOOL_NAME2"> +... + + + +String parameters should be specified as is and set `string="true"`. For all other types (numbers, booleans, arrays, objects), pass the value in JSON format and set `string="false"`. + +If thinking_mode is enabled (triggered by {thinking_start_token}), you MUST output your complete reasoning inside {thinking_start_token}...{thinking_end_token} BEFORE any tool calls or final response. + +Otherwise, output directly after {thinking_end_token} with tool calls or final response. + +### Available Tool Schemas + +{tool_schemas} + +You MUST strictly follow the above defined tool name and parameter schemas to invoke tool calls. +""" + + +def render_tools(tools: List[Dict[str, Union[str, Dict[str, Any]]]]) -> str: + """Render tool schemas into the V4.1 system prompt format.""" + tools_json = [to_json(t) for t in tools] + + return TOOLS_TEMPLATE.format( + tool_schemas="\n".join(tools_json), + dsml_token=dsml_token, + tc_block_name=tool_calls_block_name, + tool_call_tag_name=tool_call_tag_name, + tool_parameter_tag_name=tool_parameter_tag_name, + thinking_start_token=thinking_start_token, + thinking_end_token=thinking_end_token, + ) + + +def encode_arguments_to_dsml(tool_call: Dict[str, Any]) -> str: + """Encode tool call arguments into V4.1 DSML parameter format.""" + p_dsml_template = ( + '<{dsml_token}{tool_parameter_tag_name} name="{key}" string="{is_str}">' + '{value}' + ) + P_dsml_strs = [] + + arguments = tool_call["arguments"] + if not isinstance(arguments, dict): + # Tolerate JSON strings, including double-encoded ones. + for _ in range(2): + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except Exception: + break + else: + break + if not isinstance(arguments, dict): + arguments = {"arguments": tool_call["arguments"]} + + for k, v in arguments.items(): + P_dsml_strs.append(p_dsml_template.format( + dsml_token=dsml_token, + tool_parameter_tag_name=tool_parameter_tag_name, + key=k, + is_str="true" if isinstance(v, str) else "false", + value=v if isinstance(v, str) else to_json(v), + )) + + return "\n".join(P_dsml_strs) + + +# ============================================================ +# Message Rendering +# ============================================================ + +def find_last_user_index(messages: List[Dict[str, Any]]) -> int: + """ + Find the index of the last user message. + + V4.1 supports mid-conversation system messages, which count as user + messages for the purposes of the assistant generation header. + """ + last_user_index = -1 + for idx in range(len(messages) - 1, -1, -1): + role = messages[idx].get("role") + if role == "user" or (role == "system" and idx > 0): + last_user_index = idx + break + return last_user_index + + +def render_message( + index: int, + messages: List[Dict[str, Any]], + thinking_mode: str, + drop_thinking: bool = True, + reasoning_effort: Union[str, int, None] = None, +) -> str: + """ + Render a single message at the given index into its V4.1 encoded string form. + """ + assert 0 <= index < len(messages) + assert thinking_mode in ["chat", "thinking"], f"Invalid thinking_mode `{thinking_mode}`" + + msg = messages[index] + last_user_idx = find_last_user_index(messages) + + role = msg.get("role") + content = msg.get("content") + tools = msg.get("tools") + response_format = msg.get("response_format") + tool_calls = msg.get("tool_calls") + reasoning_content = msg.get("reasoning_content") + wo_eos = msg.get("wo_eos", False) + + if tools: + tools = tools_from_openai_format(tools) + if tool_calls: + tool_calls = tool_calls_from_openai_format(tool_calls) + + # Reasoning effort prefix (thinking mode, index 0 only) + reasoning_effort_prompt = render_reasoning_effort(index, thinking_mode, reasoning_effort) + # System token leads the conversation when there is a reasoning effort prompt + # or the first message is a system message. + prompt = SYSTEM_SP_TOKEN if index == 0 and (reasoning_effort_prompt or role == "system") else "" + prompt += reasoning_effort_prompt + + if role == "system": + if index > 0: + # Mid-conversation system message + prompt += SYSTEM_SP_TOKEN + prompt += system_msg_template.format(content=content or "") + if tools: + prompt += "\n\n" + render_tools(tools) + if response_format: + prompt += "\n\n" + response_format_template.format(schema=to_json(response_format)) + + elif role == "user": + prompt += USER_SP_TOKEN + + # Handle content blocks (tool results mixed with text) + content_blocks = msg.get("content_blocks") + if content_blocks: + parts = [] + for block in content_blocks: + block_type = block.get("type") + if block_type == "text": + parts.append(block.get("text", "")) + elif block_type == "tool_result": + tool_content = block.get("content", "") + if isinstance(tool_content, list): + text_parts = [] + for b in tool_content: + if b.get("type") == "text": + text_parts.append(b.get("text", "")) + else: + text_parts.append(f"[Unsupported {b.get('type')}]") + tool_content = "\n\n".join(text_parts) + parts.append(tool_output_template.format(content=tool_content)) + else: + parts.append(f"[Unsupported {block_type}]") + prompt += "\n\n".join(parts) + else: + prompt += content or "" + + elif role == "latest_reminder": + prompt += LATEST_REMINDER_SP_TOKEN + latest_reminder_msg_template.format(content=content) + + elif role == "tool": + raise NotImplementedError("deepseek_v41 merges tool messages into user; please preprocess with merge_tool_messages()") + + elif role == "assistant": + thinking_part = "" + tc_content = "" + + if tool_calls: + tc_list = [ + tool_call_template.format( + dsml_token=dsml_token, + tool_call_tag_name=tool_call_tag_name, + name=_tool_name_for_encoding(tc), + arguments=encode_arguments_to_dsml(tc) + ) + for tc in tool_calls + ] + tc_content += '\n\n' + tool_calls_template.format( + dsml_token=dsml_token, + tool_calls="\n".join(tc_list), + tc_block_name=tool_calls_block_name, + ) + + summary_content = content or "" + rc = reasoning_content or "" + + # Check if previous message has a task - if so, this is a task output (no thinking) + prev_has_task = index - 1 >= 0 and messages[index - 1].get("task") is not None + + if thinking_mode == "thinking" and not prev_has_task: + if not drop_thinking or index > last_user_idx: + thinking_part = thinking_template.format(reasoning_content=rc) + thinking_end_token + else: + thinking_part = "" + + if wo_eos: + prompt += assistant_msg_wo_eos_template.format( + reasoning=thinking_part, + content=summary_content, + tool_calls=tc_content, + ) + else: + prompt += assistant_msg_template.format( + reasoning=thinking_part, + content=summary_content, + tool_calls=tc_content, + ) + else: + raise NotImplementedError(f"Unknown role: {role}") + + # Append transition tokens based on what follows + if index + 1 < len(messages) and messages[index + 1].get("role") not in ["assistant", "latest_reminder"]: + return prompt + + task = messages[index].get("task") + if task is not None: + # Task special token for internal classification tasks + assert task in VALID_TASKS, f"Invalid task: '{task}'. Valid tasks are: {list(VALID_TASKS)}" + task_sp_token = DS_TASK_SP_TOKENS[task] + + if task != "action": + # Non-action tasks: append task sp token directly after the message + prompt += task_sp_token + else: + # Action task: append Assistant + thinking token + action sp token + prompt += ASSISTANT_SP_TOKEN + prompt += thinking_end_token if thinking_mode != "thinking" else thinking_start_token + prompt += task_sp_token + + elif role == "user" or (role == "system" and index > 0): + # Normal generation: append Assistant + thinking token + # (mid-conversation system messages also trigger the assistant header) + prompt += ASSISTANT_SP_TOKEN + if not drop_thinking and thinking_mode == "thinking": + prompt += thinking_start_token + elif drop_thinking and thinking_mode == "thinking" and index >= last_user_idx: + prompt += thinking_start_token + else: + prompt += thinking_end_token + + return prompt + + +# ============================================================ +# Main Encoding Function +# ============================================================ + +def _drop_thinking_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """ + Drop reasoning_content and non-essential messages before the last user message. + Same as V4, but uses the V4.1 last-user definition (mid systems count). + """ + last_user_idx = find_last_user_index(messages) + result = [] + keep_roles = {"user", "system", "tool", "latest_reminder", "direct_search_results"} + + for idx, msg in enumerate(messages): + role = msg.get("role") + if role in keep_roles or idx >= last_user_idx: + result.append(msg) + elif role == "assistant": + msg = copy.copy(msg) + msg.pop("reasoning_content", None) + result.append(msg) + + return result + + +def _encode_messages_text( + messages: List[Dict[str, Any]], + thinking_mode: str, + context: Optional[List[Dict[str, Any]]] = None, + drop_thinking: bool = True, + add_default_bos_token: bool = True, + reasoning_effort: Union[str, int, None] = None, +) -> str: + """Encode preprocessed (text-only) messages into the V4.1 prompt format.""" + context = context if context else [] + + # Preprocess: merge tool messages and sort tool results + messages = merge_tool_messages(messages) + messages = sort_tool_results_by_call_order(context + messages)[len(context):] + if context: + context = merge_tool_messages(context) + context = sort_tool_results_by_call_order(context) + + full_messages = context + messages + + prompt = bos_token if add_default_bos_token and len(context) == 0 else "" + + # Resolve drop_thinking: if any message has tools defined, don't drop thinking + effective_drop_thinking = drop_thinking + if any(m.get("tools") for m in full_messages): + effective_drop_thinking = False + + if thinking_mode == "thinking" and effective_drop_thinking: + full_messages = _drop_thinking_messages(full_messages) + num_to_render = len(full_messages) - len(_drop_thinking_messages(context)) + context_len = len(full_messages) - num_to_render + else: + num_to_render = len(messages) + context_len = len(context) + + for idx in range(num_to_render): + prompt += render_message( + idx + context_len, + full_messages, + thinking_mode=thinking_mode, + drop_thinking=effective_drop_thinking, + reasoning_effort=reasoning_effort, + ) + + return prompt + + +def encode_messages( + messages: List[Dict[str, Any]], + thinking_mode: str, + context: Optional[List[Dict[str, Any]]] = None, + drop_thinking: bool = True, + add_default_bos_token: bool = True, + reasoning_effort: Union[str, int, None] = None, + return_multi_modal_data: bool = False, +) -> Any: + """Encode text or multimodal messages into the DeepSeek-V4.1 prompt format. + + Text-only calls return the prompt string. When return_multi_modal_data is + true, the result is ``(prompt, media_data)``. + """ + context = context or [] + processed_context, _ = process_image_messages(context) if context else ([], []) + processed_messages, images = process_image_messages(messages) + prompt = _encode_messages_text( + processed_messages, + thinking_mode=thinking_mode, + context=processed_context if processed_context else None, + drop_thinking=drop_thinking, + add_default_bos_token=add_default_bos_token, + reasoning_effort=reasoning_effort, + ) + if return_multi_modal_data: + return prompt, {"images": images} + return prompt + + +def load_cases(input_file: str) -> List[Dict[str, Any]]: + """Load one or more OpenAI-format conversation cases from JSON.""" + with open(input_file) as file: + data = json.load(file) + if isinstance(data, dict): + data = [data] + elif data and isinstance(data[0], dict) and "role" in data[0]: + data = [{"messages": data}] + + cases = [] + for case in data: + messages = copy.deepcopy(case["messages"]) + if "tools" in case: + if not messages: + raise ValueError("A case with tools must contain at least one message") + messages[0]["tools"] = case["tools"] + cases.append({ + "messages": messages, + "context": case.get("context"), + "thinking_mode": case.get("thinking_mode"), + "reasoning_effort": case.get("reasoning_effort"), + }) + return cases + + +def encode_case( + case: Dict[str, Any], thinking_mode: str +) -> Tuple[str, List[Dict[str, Any]]]: + """Encode one JSON case and return its current-turn image records.""" + prompt, media_data = encode_messages( + case["messages"], + thinking_mode=case.get("thinking_mode") or thinking_mode, + context=case.get("context"), + reasoning_effort=case.get("reasoning_effort"), + return_multi_modal_data=True, + ) + return prompt, media_data["images"] + + +# ============================================================ +# Parsing (Decoding model output) +# ============================================================ + +def parse_tool_calls(index: int, text: str) -> Tuple[int, Optional[str], List[Dict[str, str]]]: + """ + Parse V4.1 DSML tool calls from text starting at the given index. + + Returns: + Tuple of (new_index, last_stop_token, list_of_tool_call_dicts). + """ + tool_calls: List[Dict[str, Any]] = [] + stop_token = None + tool_calls_end_token = f"" + tool_call_start_token = f"<{dsml_token}{tool_call_tag_name}" + tool_call_end_token = f"\n": + raise ValueError(f"Tool call format error: expected '>\\n' but got '{_}'") + + if stop_token == tool_calls_end_token: + break + + if stop_token is None: + raise ValueError("Missing special token in tool calls") + + index, tool_name_content, stop_token = _read_until_stop(index, text, [tool_parameter_start_token, tool_call_end_token]) + + p_tool_name = re.findall(r'^\s*name="(.*?)">\n$', tool_name_content, flags=re.DOTALL) + if len(p_tool_name) != 1: + raise ValueError(f"Tool name format error: '{tool_name_content}'") + tool_name = p_tool_name[0] + + tool_args: Dict[str, Tuple[str, str]] = {} + while stop_token == tool_parameter_start_token: + index, param_content, stop_token = _read_until_stop(index, text, [tool_parameter_end_token]) + + param_kv = re.findall(r'^ name="(.*?)" string="(true|false)">(.*?)<$', param_content, flags=re.DOTALL) + if len(param_kv) != 1: + raise ValueError(f"Parameter format error: '{param_content}'") + param_name, string, param_value = param_kv[0] + + if param_name in tool_args: + raise ValueError(f"Duplicate parameter name: '{param_name}'") + tool_args[param_name] = (param_value, string) + + index, content, stop_token = _read_until_stop(index, text, [tool_parameter_start_token, tool_call_end_token]) + if content != ">\n": + raise ValueError(f"Parameter format error: expected '>\\n' but got '{content}'") + + tool_call = decode_dsml_to_arguments(tool_name=tool_name, tool_args=tool_args) + tool_calls.append(tool_call) + + return index, stop_token, tool_calls + + +def parse_message_from_completion_text(text: str, thinking_mode: str) -> Dict[str, Any]: + """ + Parse a model completion text into a structured assistant message (V4.1 format). + + Returns: + Dict with keys: "role", "content", "reasoning_content", "tool_calls". + tool_calls are in OpenAI format. + """ + summary_content, reasoning_content, tool_calls = "", "", [] + index, stop_token = 0, None + tool_calls_start_token = f"\n\n<{dsml_token}{tool_calls_block_name}" + + is_thinking = thinking_mode == "thinking" + is_tool_calling = False + + if is_thinking: + index, content_delta, stop_token = _read_until_stop(index, text, [thinking_end_token, tool_calls_start_token]) + reasoning_content = content_delta + assert stop_token == thinking_end_token, "Invalid thinking format: missing " + + index, content_delta, stop_token = _read_until_stop(index, text, [eos_token, tool_calls_start_token]) + summary_content = content_delta + if stop_token == tool_calls_start_token: + is_tool_calling = True + else: + assert stop_token == eos_token, "Invalid format: missing EOS token" + + if is_tool_calling: + index, stop_token, tool_calls = parse_tool_calls(index, text) + + index, tool_ends_text, stop_token = _read_until_stop(index, text, [eos_token]) + assert not tool_ends_text, "Unexpected content after tool calls" + + assert len(text) == index and stop_token in [eos_token, None], "Unexpected content at end" + + for sp_token in [bos_token, eos_token, thinking_start_token, thinking_end_token, dsml_token]: + assert sp_token not in summary_content and sp_token not in reasoning_content, \ + f"Unexpected special token '{sp_token}' in content" + + return { + "role": "assistant", + "content": summary_content, + "reasoning_content": reasoning_content, + "tool_calls": tool_calls_to_openai_format(tool_calls) + } diff --git a/omlx/patches/deepseek_v41/engram.py b/omlx/patches/deepseek_v41/engram.py new file mode 100644 index 0000000000..d7b5fafb4f --- /dev/null +++ b/omlx/patches/deepseek_v41/engram.py @@ -0,0 +1,167 @@ +# SPDX-License-Identifier: MIT +"""Token-normalized Engram lookup with request-local lookback.""" + +import math + +import mlx.core as mx +import mlx.nn as nn +import numpy as np + + +def build_compressed_token_map(tokenizer) -> tuple[list[int], int]: + """Map every token id onto a smaller id space where tokens that normalize alike collapse together. + + N-grams are hashed over these compressed ids, so " The", "the" and "THE" all hash the same way. + Returns the lookup plus the size of the compressed vocab -- and that size matters beyond bounds + checking, because every hash multiplier is derived from it. + """ + from tokenizers import Regex, normalizers + + # a private-use char, so a token that is exactly one space survives Strip() instead of + # collapsing to the empty string and merging with unrelated tokens + sentinel = "\ue000" + normalizer = normalizers.Sequence( + [ + normalizers.NFKC(), + normalizers.NFD(), + normalizers.StripAccents(), + normalizers.Lowercase(), + normalizers.Replace(Regex(r"[ \t\r\n]+"), " "), + normalizers.Replace(Regex(r"^ $"), sentinel), + normalizers.Strip(), + normalizers.Replace(sentinel, " "), + ] + ) + + # the raw Rust tokenizer, matching what training decodes with (no clean_up_tokenization_spaces) + backend = tokenizer.backend_tokenizer + key_to_new: dict[str, int] = {} + lookup = [0] * len(tokenizer) + for token_id in range(len(tokenizer)): + text = backend.decode([token_id], skip_special_tokens=False) + if "\ufffd" in text: + # a partial UTF-8 byte token: nothing to normalize, so key it by its raw form + key = backend.id_to_token(token_id) + else: + normalized = normalizer.normalize_str(text) + key = normalized if normalized else text + + new_id = key_to_new.get(key) + if new_id is None: + new_id = len(key_to_new) + key_to_new[key] = new_id + lookup[token_id] = new_id + + return lookup, len(key_to_new) + + +def _prime(n): + return n >= 2 and all(n % d for d in range(2, math.isqrt(n) + 1)) + + +class NgramHash: + """CPU int64 hashing matches the official NumPy RNG, not Qwen's SplitMix64. + + Only the last n-1 compressed token ids live in the request cache. Image + positions stop lookback; they are not removed from the token timeline. + """ + + def __init__(self, config, token_map): + self.config = config + self.token_map = np.asarray(token_map, dtype=np.int64) + vocab = int(self.token_map.max()) + 1 + if vocab != config.engram_compressed_vocab_size: + raise ValueError(f"Engram compressed vocabulary mismatch: {vocab}") + self.pad_id = int(self.token_map[config.engram_pad_id]) + primes, multipliers, seen = [], [], set() + for layer_id in config.engram_layer_ids: + groups = [] + for _ in range(config.engram_max_ngram_size - 1): + current, group = config.engram_vocab_size - 1, [] + for _ in range(config.engram_n_heads): + current += 1 + while not _prime(current) or current in seen: + current += 1 + seen.add(current) + group.append(current) + groups.append(group) + primes.append(groups) + rng = np.random.default_rng(10007 * layer_id) + bound = max(1, (np.iinfo(np.int64).max // vocab) // 2) + multipliers.append( + rng.integers(0, bound, config.engram_max_ngram_size, dtype=np.int64) * 2 + + 1 + ) + self.primes = np.array(primes, dtype=np.int64) + self.multipliers = np.array(multipliers, dtype=np.int64) + flat = self.primes.reshape(len(primes), -1) + self.offsets = np.cumsum( + np.concatenate( + [np.zeros((len(primes), 1), dtype=np.int64), flat[:, :-1]], -1 + ), + -1, + ) + if list(flat.sum(-1)) != list(config.engram_num_embeddings): + raise ValueError("Engram table rows do not match the official prime layout") + + def __call__(self, ids, history=None, image_mask=None): + ids = np.asarray(ids, dtype=np.int64) + if ids.min() < 0 or ids.max() >= len(self.token_map): + raise ValueError("Token id outside Engram tokenizer vocabulary") + tokens = self.token_map[ids] + if image_mask is not None: + tokens = np.where(np.asarray(image_mask), -1, tokens) + depth = self.config.engram_max_ngram_size - 1 + if history is None: + history = np.full((len(ids), depth), -1, dtype=np.int64) + joined = np.concatenate([np.asarray(history), tokens], axis=1) + positions = np.arange(tokens.shape[1]) + depth + blocked = np.zeros_like(tokens, dtype=bool) + lookback = [] + for shift in range(depth + 1): + source = joined[:, positions - shift] + blocked |= source == -1 + lookback.append(np.where(blocked, self.pad_id, source)) + product = np.stack(lookback, -1)[:, :, None, :] * self.multipliers + rolling, hashes = product[..., 0], [] + for shift in range(1, depth + 1): + rolling = np.bitwise_xor(rolling, product[..., shift]) + hashes.append(rolling[..., None] % self.primes[:, shift - 1]) + return np.concatenate(hashes, -1) + self.offsets, joined[:, -depth:] + + +class Engram(nn.Module): + def __init__(self, config, table_index): + super().__init__() + self.embed = nn.Embedding( + config.engram_num_embeddings[table_index], config.engram_head_dim + ) + self.wkv = nn.Linear( + (config.engram_max_ngram_size - 1) + * config.engram_n_heads + * config.engram_head_dim, + config.dim * (config.hc_mult + 1), + bias=False, + ) + self.q_weight = mx.ones((config.hc_mult, config.dim)) + self.k_weight = mx.ones((config.hc_mult, config.dim)) + self._config = config + + def __call__(self, h, ids, image_mask=None): + c = self._config + kv = self.wkv(self.embed(mx.array(ids)).flatten(-2)) + key, value = mx.split(kv, [c.dim * c.hc_mult], axis=-1) + key = key.astype(mx.float32).reshape(*h.shape) + x = h.astype(mx.float32) + inv = mx.rsqrt(mx.mean(x * x, -1) + c.norm_eps) * mx.rsqrt( + mx.mean(key * key, -1) + c.norm_eps + ) + dot = mx.sum(x * self.q_weight * self.k_weight * key, -1) * inv * c.dim**-0.5 + gate = mx.sigmoid(mx.sign(dot) * mx.sqrt(mx.maximum(mx.abs(dot), 1e-6))) + # copysign(+sqrt, 0) is positive in the official reference. + gate = mx.where(dot == 0, mx.sigmoid(mx.array(0.001)), gate) + if image_mask is not None: + gate = mx.where(image_mask[..., None], 0, gate) + return (x + gate[..., None] * value.astype(mx.float32)[..., None, :]).astype( + h.dtype + ) diff --git a/omlx/patches/deepseek_v41/head.py b/omlx/patches/deepseek_v41/head.py new file mode 100644 index 0000000000..bff5359edf --- /dev/null +++ b/omlx/patches/deepseek_v41/head.py @@ -0,0 +1,59 @@ +# SPDX-License-Identifier: MIT +"""Vocabulary projection with BF16 storage and FP32 accumulation/output.""" + +from functools import cache + +import mlx.core as mx + +_SOURCE = r""" + const uint row = thread_position_in_grid.x / KL; + if (row >= N) return; + const uint lane = thread_index_in_simdgroup % KL; + const uint query = threadgroup_position_in_grid.y; + float sum = 0; + for (uint k = lane * 4; k < K; k += KL * 4) { + const size_t offset = size_t(row) * K + k; + const float4 a = float4(w[offset], w[offset + 1], + w[offset + 2], w[offset + 3]); + const float4 b = float4(x[query * K + k], x[query * K + k + 1], x[query * K + k + 2], x[query * K + k + 3]); + sum += dot(a, b); + } + for (uint offset = KL / 2; offset > 0; offset /= 2) { + sum += simd_shuffle_down(sum, offset); + } + if (lane == 0) y[query * N + row] = sum; +""" + + +@cache +def _kernel(): + return mx.fast.metal_kernel( + name="v41_bf16_head_fp32_output", + input_names=["x", "w"], + output_names=["y"], + source=_SOURCE, + ) + + +def project_logits(x, weight): + """Keep the full logits contract for prefill and multi-token verification.""" + rows, width = weight.shape + if ( + weight.dtype != mx.bfloat16 + or x.shape[-1] != width + or not 1 <= x.size // width <= 5 + or width % 4 + or width < 256 + or rows < 4096 + or mx.default_device() == mx.cpu + ): + return x.astype(mx.float32) @ weight.astype(mx.float32).T + lanes = 16 + return _kernel()( + inputs=[x.astype(mx.float32), weight], + template=[("N", rows), ("K", width), ("KL", lanes)], + grid=(((rows * lanes + 63) // 64) * 64, x.size // width, 1), + threadgroup=(64, 1, 1), + output_shapes=[(*x.shape[:-1], rows)], + output_dtypes=[mx.float32], + )[0] diff --git a/omlx/patches/deepseek_v41/hyper_connection.py b/omlx/patches/deepseek_v41/hyper_connection.py new file mode 100644 index 0000000000..14ae92c179 --- /dev/null +++ b/omlx/patches/deepseek_v41/hyper_connection.py @@ -0,0 +1,254 @@ +# SPDX-License-Identifier: MIT +"""mHC normalization and four-stream mixing kernels with FP32 accumulation.""" + +from functools import cache + +import mlx.core as mx + +_SOURCE = r""" + const uint row = thread_position_in_grid.x; + if (row >= ROWS) return; + float values[16]; + for (int i = 0; i < 16; ++i) values[i] = x[row * 16 + i]; + for (int iteration = 0; iteration < ITERS; ++iteration) { + if (iteration > 0) { + for (int r = 0; r < 4; ++r) { + float total = 0.0f; + for (int c = 0; c < 4; ++c) total = values[r * 4 + c] + total; + total = total + eps[0]; + for (int c = 0; c < 4; ++c) values[r * 4 + c] /= total; + } + } + for (int c = 0; c < 4; ++c) { + float total = 0.0f; + for (int r = 0; r < 4; ++r) total = values[r * 4 + c] + total; + total = total + eps[0]; + for (int r = 0; r < 4; ++r) values[r * 4 + c] /= total; + } + } + for (int i = 0; i < 16; ++i) y[row * 16 + i] = values[i]; +""" + + +@cache +def _sinkhorn_kernel(): + return mx.fast.metal_kernel( + name="deepseek_v41_sinkhorn", + input_names=["x", "eps"], + output_names=["y"], + source=_SOURCE, + header=("#pragma clang fp reassociate(off)\n#pragma clang fp contract(off)\n"), + ) + + +def sinkhorn_reference(comb, eps, iters): + comb /= mx.sum(comb, -2, keepdims=True) + eps + for _ in range(iters - 1): + comb /= mx.sum(comb, -1, keepdims=True) + eps + comb /= mx.sum(comb, -2, keepdims=True) + eps + return comb + + +def sinkhorn(comb, eps, iters): + """Fuse only normalization; preserve softmax and mHC projection arithmetic.""" + if ( + comb.shape[-2:] != (4, 4) + or comb.dtype != mx.float32 + or mx.default_device() != mx.gpu + or not comb.size + ): + return sinkhorn_reference(comb, eps, iters) + rows = comb.size // 16 + return _sinkhorn_kernel()( + inputs=[comb, mx.array([eps], mx.float32)], + template=[("ROWS", rows), ("ITERS", max(1, iters))], + grid=(rows, 1, 1), + threadgroup=(32, 1, 1), + output_shapes=[comb.shape], + output_dtypes=[mx.float32], + )[0] + + +_POST_SOURCE = r""" + const uint z = thread_position_in_grid.x; + if (z >= ROWS * D) return; + const uint row = z / D, d = z % D; + float values[4]; + for (uint i = 0; i < 4; ++i) + values[i] = float(residual[(row * 4 + i) * D + d]); + const float value = float(x[z]); + for (uint j = 0; j < 4; ++j) { + float sum = 0.0f; + for (uint i = 0; i < 4; ++i) + sum = fma(comb[row * 16 + i * 4 + j], values[i], sum); + y[(row * 4 + j) * D + d] = T(post[row * 4 + j] * value + sum); + } +""" + + +@cache +def _post_kernel(): + return mx.fast.metal_kernel( + name="deepseek_v41_hc_post", + input_names=["x", "residual", "post", "comb"], + output_names=["y"], + source=_POST_SOURCE, + header="#pragma clang fp contract(off)\n", + ) + + +def fused_hc_post(x, residual, post, comb): + """Mix four residual streams without expanding the residual to FP32.""" + return _post_kernel()( + inputs=[x, residual, post, comb], + template=[("T", x.dtype), ("ROWS", x.size // x.shape[-1]), ("D", x.shape[-1])], + grid=(x.size, 1, 1), + threadgroup=(256, 1, 1), + output_shapes=[residual.shape], + output_dtypes=[x.dtype], + )[0] + + +_PRE_NORM_SOURCE = r""" + const uint row = threadgroup_position_in_grid.x; + const uint tid = thread_position_in_threadgroup.x; + const uint lane = thread_index_in_simdgroup; + const uint simd = simdgroup_index_in_threadgroup; + threadgroup float sums[8]; + float values[(D + 255) / 256]; + float total = 0.0f; + for (uint t = 0; t < (D + 255) / 256; ++t) { + const uint d = tid + 256 * t; + float value = 0.0f; + if (d < D) { + for (uint i = 0; i < 4; ++i) + value = float(x[(row * 4 + i) * D + d]) * pre[row * 4 + i] + value; + // The separate hc_pre output is rounded before normalization. + value = float(T(value)); + } + values[t] = value; + total = total + value * value; + } + total = simd_sum(total); + if (lane == 0) sums[simd] = total; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (simd == 0) { + float sum = lane < 8 ? sums[lane] : 0.0f; + sum = simd_sum(sum); + if (lane == 0) sums[0] = rsqrt(sum / float(D) + eps[0]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint t = 0; t < (D + 255) / 256; ++t) { + const uint d = tid + 256 * t; + if (d < D) y[row * D + d] = T((values[t] * sums[0]) * float(weight[d])); + } +""" + + +@cache +def _pre_norm_kernel(): + return mx.fast.metal_kernel( + name="deepseek_v41_hc_pre_norm", + input_names=["x", "pre", "weight", "eps"], + output_names=["y"], + source=_PRE_NORM_SOURCE, + header="#pragma clang fp contract(off)\n", + ) + + +def fused_hc_pre_norm(x, pre, weight, eps): + """Preserve the intermediate dtype cast before RMS normalization.""" + width = x.shape[-1] + rows = x.size // (4 * width) + return _pre_norm_kernel()( + inputs=[x, pre, weight, mx.array([eps], mx.float32)], + template=[("T", x.dtype), ("D", width)], + grid=(rows * 256, 1, 1), + threadgroup=(256, 1, 1), + output_shapes=[(*x.shape[:-2], width)], + output_dtypes=[x.dtype], + )[0] + + +_PROJECTION_WARP_SOURCE = r""" + const uint row = threadgroup_position_in_grid.x; + const uint block = threadgroup_position_in_grid.y; + const uint lane = thread_index_in_simdgroup; + float sums[12]; + for (uint j = 0; j < 12; ++j) sums[j] = 0.0f; + float square = 0.0f; + for (uint k = lane; k < D; k += 32) { + const float value = float(x[row * D + k]); + square = fma(value, value, square); + for (uint j = 0; j < 12; ++j) + sums[j] = fma(value, fn[(block * 12 + j) * D + k], sums[j]); + } + const float inv = rsqrt(simd_sum(square) / float(D) + eps[0]); + for (uint j = 0; j < 12; ++j) { + const float value = simd_sum(sums[j]); + if (lane == 0) y[row * 24 + block * 12 + j] = value * inv; + } +""" + +_PROJECTION_SOURCE = r""" + const uint row = threadgroup_position_in_grid.x; + const uint block = threadgroup_position_in_grid.y; + const uint tid = thread_position_in_threadgroup.x; + const uint lane = thread_index_in_simdgroup; + const uint sg = simdgroup_index_in_threadgroup; + threadgroup float scratch[13 * 8]; + float sums[12]; + for (uint j = 0; j < 12; ++j) sums[j] = 0.0f; + float square = 0.0f; + for (uint k = tid; k < D; k += 256) { + const float value = float(x[row * D + k]); + square = fma(value, value, square); + for (uint j = 0; j < 12; ++j) + sums[j] = fma(value, fn[(block * 12 + j) * D + k], sums[j]); + } + for (uint j = 0; j < 12; ++j) { + const float value = simd_sum(sums[j]); + if (lane == 0) scratch[j * 8 + sg] = value; + } + const float sq = simd_sum(square); + if (lane == 0) scratch[96 + sg] = sq; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + float q = lane < 8 ? scratch[96 + lane] : 0.0f; + q = simd_sum(q); + const float inv = rsqrt(q / float(D) + eps[0]); + for (uint j = 0; j < 12; ++j) { + float value = lane < 8 ? scratch[j * 8 + lane] : 0.0f; + value = simd_sum(value); + if (lane == 0) y[row * 24 + block * 12 + j] = value * inv; + } + } +""" + + +@cache +def _projection_kernel(warp=False): + return mx.fast.metal_kernel( + name=( + "deepseek_v41_hc_projection_warp" if warp else "deepseek_v41_hc_projection" + ), + input_names=["x", "fn", "eps"], + output_names=["y"], + source=_PROJECTION_WARP_SOURCE if warp else _PROJECTION_SOURCE, + ) + + +def fused_hc_projection(x, fn, eps): + """Project BF16 residual streams with FP32 weights and accumulators.""" + width = x.shape[-1] * 4 + rows = x.size // width + # Small batches need more warps to occupy the GPU. + threads = 32 if rows >= 1024 else 256 + return _projection_kernel(warp=threads == 32)( + inputs=[x, fn, mx.array([eps], mx.float32)], + template=[("D", width)], + grid=(rows * threads, 2, 1), + threadgroup=(threads, 1, 1), + output_shapes=[(*x.shape[:-2], 24)], + output_dtypes=[mx.float32], + )[0] diff --git a/omlx/patches/deepseek_v41/kernels.py b/omlx/patches/deepseek_v41/kernels.py new file mode 100644 index 0000000000..66da845c3a --- /dev/null +++ b/omlx/patches/deepseek_v41/kernels.py @@ -0,0 +1,826 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Packed CSA2 Metal kernels, following local DSV4 WSDPA and DSA scan patterns. + +BF16 attention uses 64-key online maxima and BF16 PV probabilities. +Other floating-point inputs retain the split-K FP32 probability path. +Index scoring fuses the head reduction and optionally visits explicit candidates. +The matrix fragment layout follows MLX-derived Bonsai kernels (Apple Inc.). No checkpoint or +compiled extension is required; compilation/dispatch errors propagate. +""" + +from functools import cache + +import mlx.core as mx + +from .packed_attention import rounded_packed_attention + +_HEADER = r""" +#include +#include +using namespace metal; +inline float v41_fp8(uchar code) { + const uint a = code & 127, exponent = a >> 3, mantissa = a & 7; + const float value = exponent == 0 ? ldexp(float(mantissa), -9) + : ldexp(1.0f + float(mantissa) * 0.125f, int(exponent) - 7); + return code & 128 ? -value : value; +} +inline float v41_fp4(uchar code) { + const float table[8] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f}; + return (code & 8 ? -1.0f : 1.0f) * table[code & 7]; +} +""" + +_ATTENTION = r""" + const uint lane = thread_index_in_threadgroup % 32; + const uint head = threadgroup_position_in_grid.x * 4 + + thread_index_in_threadgroup / 32; + const uint query = threadgroup_position_in_grid.y; + const uint split = threadgroup_position_in_grid.z; + const int H = meta[0], W = meta[1], C = meta[2]; + const int NW = meta[3], NC = meta[4], NS = meta[5]; + if (head >= H) return; + // Contiguous lanes stay inside one quantization group at these widths. + constexpr bool REUSE_SCALE = D == 32 || D == 64 || D == 128 || D == 256 || D == 512; + float query_values[D / 32], acc[D / 32]; + for (int v = 0; v < D / 32; ++v) { + query_values[v] = float(q[(query * H + head) * D + (REUSE_SCALE ? lane * (D / 32) + v : lane + v * 32)]); + acc[v] = 0.0f; + } + float maximum = -INFINITY, denominator = 0.0f; + const int end = min(int((split + 1) * CHUNK), W + C); + for (int j = split * CHUNK; j < end; ++j) { + const bool compressed = j >= W; + const int row = compressed ? ci[query * C + j - W] : wi[query * W + j]; + if (row < 0 || row >= (compressed ? NC : NW)) continue; + const size_t base = size_t(row) * (compressed + ? (D / 2 + D / 16) : (D + D / 32)); + const uint first = lane * (D / 32); + const float pooled_scale = REUSE_SCALE && compressed + ? v41_fp8(pooled[base + D / 2 + first / 16]) : 0.0f; + const int window_exp = REUSE_SCALE && !compressed + ? int(window[base + D + first / 32]) - 127 : 0; + float values[D / 32], dot = 0.0f; + for (int v = 0; v < D / 32; ++v) { + const uint d = (REUSE_SCALE ? lane * (D / 32) + v : lane + v * 32); + float value; + if (compressed) { + const uchar code = (pooled[base + d / 2] >> ((d % 2) * 4)) & 15; + value = v41_fp4(code) * (REUSE_SCALE ? pooled_scale : v41_fp8(pooled[base + D / 2 + d / 16])); + } else { + value = ldexp(v41_fp8(window[base + d]), REUSE_SCALE ? window_exp : int(window[base + D + d / 32]) - 127); + } + values[v] = value; + dot += query_values[v] * value; + } + const float score = simd_sum(dot) * scalep[0]; + const float next_maximum = max(maximum, score); + const float correction = exp(maximum - next_maximum); + const float probability = exp(score - next_maximum); + denominator = denominator * correction + probability; + for (int v = 0; v < D / 32; ++v) + acc[v] = acc[v] * correction + probability * values[v]; + maximum = next_maximum; + } + const size_t base = ((size_t(query) * H + head) * NS + split) * (D + 2); + for (int v = 0; v < D / 32; ++v) partial[base + (REUSE_SCALE ? lane * (D / 32) + v : lane + v * 32)] = acc[v]; + if (lane == 0) { + partial[base + D] = maximum; + partial[base + D + 1] = denominator; + } +""" + +_ATTENTION_MMA = r""" + const uint tid = thread_index_in_threadgroup, lane = tid % 32, sg = tid / 32; + const uint query = threadgroup_position_in_grid.y, split = threadgroup_position_in_grid.z; + const uint first_head = threadgroup_position_in_grid.x * 8; + const int H = meta[0], W = meta[1], C = meta[2], NW = meta[3], NC = meta[4], NS = meta[5]; + const uint fm = ((lane >> 2) & 4) + ((lane >> 1) & 3); + const uint fn = (((lane >> 2) & 2) << 1) + ((lane & 1) << 1); + threadgroup float tile[8 * D], dots[4 * 64], probability[64]; + threadgroup float maxima[8], denominator[8], correction[8]; + threadgroup bool valid[8]; + simdgroup_matrix output[D / 32]; + for (int v = 0; v < D / 32; ++v) { + output[v].thread_elements()[0] = 0.0f; + output[v].thread_elements()[1] = 0.0f; + } + if (tid < 8) { maxima[tid] = -INFINITY; denominator[tid] = 0.0f; } + const int end = min(int((split + 1) * CHUNK), W + C); + for (int begin = split * CHUNK; begin < end; begin += 8) { + for (uint i = tid; i < 8 * D; i += 128) { + const uint r = i / D, d = i % D, j = begin + r; + const bool compressed = j >= W; + int row = -1; + if (j < end) row = compressed ? ci[query * C + j - W] : wi[query * W + j]; + const bool ok = row >= 0 && row < (compressed ? NC : NW); + float value = 0.0f; + if (ok) { + if (compressed) { + const size_t base = size_t(row) * (D / 2 + D / 16); + const uchar code = (pooled[base + d / 2] >> ((d % 2) * 4)) & 15; + value = v41_fp4(code) * v41_fp8(pooled[base + D / 2 + d / 16]); + } else { + const size_t base = size_t(row) * (D + D / 32); + value = ldexp(v41_fp8(window[base + d]), int(window[base + D + d / 32]) - 127); + } + } + tile[i] = value; + if (d == 0) valid[r] = ok; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // Four simdgroups split the QK dot product's channel dimension. + simdgroup_matrix score, a, b; + score.thread_elements()[0] = 0.0f; + score.thread_elements()[1] = 0.0f; + for (int k = sg * (D / 4); k < (sg + 1) * (D / 4); k += 8) { + const uint head = first_head + fm; + a.thread_elements()[0] = head < H ? float(q[(query * H + head) * D + k + fn]) : 0.0f; + a.thread_elements()[1] = head < H ? float(q[(query * H + head) * D + k + fn + 1]) : 0.0f; + b.thread_elements()[0] = tile[fn * D + k + fm]; + b.thread_elements()[1] = tile[(fn + 1) * D + k + fm]; + simdgroup_multiply_accumulate(score, a, b, score); + } + dots[sg * 64 + fm * 8 + fn] = score.thread_elements()[0]; + dots[sg * 64 + fm * 8 + fn + 1] = score.thread_elements()[1]; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid < 8) { + float values[8], next_max = maxima[tid]; + for (uint r = 0; r < 8; ++r) { + float sum = dots[tid * 8 + r] + dots[64 + tid * 8 + r] + + dots[128 + tid * 8 + r] + dots[192 + tid * 8 + r]; + values[r] = valid[r] ? sum * scalep[0] : -INFINITY; + next_max = max(next_max, values[r]); + } + correction[tid] = maxima[tid] == -INFINITY ? 0.0f : exp(maxima[tid] - next_max); + float total = denominator[tid] * correction[tid]; + for (uint r = 0; r < 8; ++r) { + const float prob = valid[r] ? exp(values[r] - next_max) : 0.0f; + probability[tid * 8 + r] = prob; + total += prob; + } + maxima[tid] = next_max; + denominator[tid] = total; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // PV reuses the decoded tile. Float matrices retain FP32 probabilities. + a.thread_elements()[0] = probability[fm * 8 + fn]; + a.thread_elements()[1] = probability[fm * 8 + fn + 1]; + for (int v = 0; v < D / 32; ++v) { + const uint d = sg * (D / 4) + v * 8 + fn; + b.thread_elements()[0] = tile[fm * D + d]; + b.thread_elements()[1] = tile[fm * D + d + 1]; + output[v].thread_elements()[0] *= correction[fm]; + output[v].thread_elements()[1] *= correction[fm]; + simdgroup_multiply_accumulate(output[v], a, b, output[v]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + const uint head = first_head + fm; + if (head < H) { + const size_t base = ((size_t(query) * H + head) * NS + split) * (D + 2); + for (int v = 0; v < D / 32; ++v) { + const uint d = sg * (D / 4) + v * 8 + fn; + partial[base + d] = output[v].thread_elements()[0]; + partial[base + d + 1] = output[v].thread_elements()[1]; + } + } + if (tid < 8 && first_head + tid < H) { + const size_t base = ((size_t(query) * H + first_head + tid) * NS + split) * (D + 2); + partial[base + D] = maxima[tid]; + partial[base + D + 1] = denominator[tid]; + } +""" + +_INDEX = r""" + const uint lane = thread_index_in_threadgroup % 32; + const uint position = threadgroup_position_in_grid.x * 4 + + thread_index_in_threadgroup / 32; + const uint query = threadgroup_position_in_grid.y; + const int H = HEADS, N = meta[1], M = meta[2], start = meta[3], ratio = RATIO; + if (position >= M) return; + const int row = CANDIDATES ? candidates[query * M + position] : int(position); + if (row < 0 || row >= N || row + meta[5] >= (start + int(query) + 1) / ratio) { + if (lane == 0) scores[query * M + position] = -INFINITY; + return; + } + const size_t base = size_t(row) * (D / 2 + D / 32); + float key[D / 32]; + for (int v = 0; v < D / 32; ++v) { + const uint d = lane + v * 32; + const uchar code = (keys[base + d / 2] >> ((d % 2) * 4)) & 15; + key[v] = ldexp(v41_fp4(code), int(keys[base + D / 2 + d / 32]) - 127); + } + float result = 0.0f; + for (int h = 0; h < H; ++h) { + float dot = 0.0f; + for (int v = 0; v < D / 32; ++v) + dot += float(q[(query * H + h) * D + lane + v * 32]) * key[v]; + result += max(simd_sum(dot), 0.0f) * weights[query * H + h]; + } + if (lane == 0) scores[query * M + position] = result; +""" + + +_INDEX_MMA = r""" + const uint tid = thread_index_in_threadgroup; + const uint lane = tid % 32, sg = tid / 32; + const uint query = threadgroup_position_in_grid.y; + constexpr uint COLS = HEAD_SPLIT ? 16 : 32; + const uint key_group = HEAD_SPLIT ? sg % 2 : sg; + const uint block = threadgroup_position_in_grid.x * COLS; + const int H = HEADS, N = meta[1], M = meta[2], start = meta[3], ratio = RATIO; + const uint fm = ((lane >> 2) & 4) + ((lane >> 1) & 3); + const uint fn = (((lane >> 2) & 2) << 1) + ((lane & 1) << 1); + threadgroup float tile[D * COLS]; + for (uint i = tid; i < D * COLS; i += 128) { + const uint d = i / COLS, col = i % COLS, pos = block + col; + const int row = pos < M ? (CANDIDATES ? candidates[query * M + pos] : int(pos)) : -1; + float value = 0.0f; + if (row >= 0 && row < N && row + meta[5] < (start + int(query) + 1) / ratio) { + const size_t base = size_t(row) * (D / 2 + D / 32); + const uchar code = (keys[base + d / 2] >> ((d % 2) * 4)) & 15; + value = ldexp(v41_fp4(code), int(keys[base + D / 2 + d / 32]) - 127); + } + tile[i] = value; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float total0 = 0.0f, total1 = 0.0f; + for (int h = HEAD_SPLIT ? int(sg / 2) * 8 : 0; h < H; h += HEAD_SPLIT ? 16 : 8) { + simdgroup_matrix acc, a, b; + acc.thread_elements()[0] = 0.0f; + acc.thread_elements()[1] = 0.0f; + #pragma clang loop unroll(full) + for (int d = 0; d < D; d += 8) { + a.thread_elements()[0] = h + fm < H ? float(q[(query * H + h + fm) * D + d + fn]) : 0.0f; + a.thread_elements()[1] = h + fm < H ? float(q[(query * H + h + fm) * D + d + fn + 1]) : 0.0f; + b.thread_elements()[0] = tile[(d + fm) * COLS + key_group * 8 + fn]; + b.thread_elements()[1] = tile[(d + fm) * COLS + key_group * 8 + fn + 1]; + simdgroup_multiply_accumulate(acc, a, b, acc); + } + const float weight = h + fm < H ? weights[query * H + h + fm] : 0.0f; + float v0 = max(acc.thread_elements()[0], 0.0f) * weight; + float v1 = max(acc.thread_elements()[1], 0.0f) * weight; + // Lane bits 1, 2 and 4 span the eight head rows of each column. + for (uint i = 0; i < 3; ++i) { + const uint mask = i == 0 ? 2 : (i == 1 ? 4 : 16); + v0 += simd_shuffle_xor(v0, mask); + v1 += simd_shuffle_xor(v1, mask); + } + total0 += v0; + total1 += v1; + } + threadgroup float head_totals[32]; + if (HEAD_SPLIT) { + if (fm == 0) { + head_totals[sg * 8 + fn] = total0; + head_totals[sg * 8 + fn + 1] = total1; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid < COLS && block + tid < M) { + const uint pos = block + tid; + const int row = CANDIDATES ? candidates[query * M + pos] : int(pos); + const bool valid = row >= 0 && row < N && row + meta[5] < (start + int(query) + 1) / ratio; + scores[query * M + pos] = valid ? head_totals[tid] + head_totals[tid + COLS] : -INFINITY; + } + } else if (fm == 0) { + for (uint j = 0; j < 2; ++j) { + const uint pos = block + sg * 8 + fn + j; + if (pos >= M) continue; + const int row = CANDIDATES ? candidates[query * M + pos] : int(pos); + const bool valid = row >= 0 && row < N && row + meta[5] < (start + int(query) + 1) / ratio; + scores[query * M + pos] = valid ? (j == 0 ? total0 : total1) : -INFINITY; + } + } +""" + +_MERGE = r""" + const uint lane = thread_index_in_threadgroup % 32; + const uint head = threadgroup_position_in_grid.x * 4 + + thread_index_in_threadgroup / 32; + const uint query = threadgroup_position_in_grid.y; + const int H = meta[0], NS = meta[1]; + if (head >= H) return; + const size_t base = (size_t(query) * H + head) * NS * (D + 2); + float maximum = float(sink[head]); + for (int s = 0; s < NS; ++s) + maximum = max(maximum, partial[base + s * (D + 2) + D]); + float denominator = exp(float(sink[head]) - maximum); + float acc[D / 32]; + for (int v = 0; v < D / 32; ++v) acc[v] = 0.0f; + for (int s = 0; s < NS; ++s) { + const size_t pos = base + s * (D + 2); + const float correction = exp(partial[pos + D] - maximum); + denominator += partial[pos + D + 1] * correction; + for (int v = 0; v < D / 32; ++v) + acc[v] += partial[pos + lane + v * 32] * correction; + } + for (int v = 0; v < D / 32; ++v) + out[(query * H + head) * D + lane + v * 32] = T(acc[v] / denominator); +""" + + +@cache +def _kernel(kind): + if kind in ("attention", "attention_mma"): + inputs = ["q", "window", "pooled", "wi", "ci", "meta", "scalep"] + outputs, source = ( + ["partial"], + (_ATTENTION_MMA if kind == "attention_mma" else _ATTENTION), + ) + elif kind == "merge": + inputs = ["partial", "sink", "meta"] + outputs, source = ["out"], _MERGE + else: + inputs = ["q", "keys", "weights", "candidates", "meta"] + outputs, source = ["scores"], _INDEX_MMA if kind == "index_mma" else _INDEX + return mx.fast.metal_kernel( + name="deepseek_v41_packed_" + kind, + input_names=inputs, + output_names=outputs, + source=source, + header=_HEADER, + ) + + +def packed_sparse_attention(q, window, pooled, wi, ci, sink, scale): + """Read packed rows directly; scratch scales with split count, not selected D.""" + if q.ndim != 4 or q.shape[0] != 1 or q.shape[-1] % 32: + raise ValueError("Prepare one request with 32-aligned attention heads") + _, length, heads, dim = q.shape + if not length or not heads or not dim or sink.shape != (heads,): + raise ValueError("Invalid query or attention sink shape") + if any(x.ndim != 3 or x.shape[:2] != (1, length) for x in (wi, ci)): + raise ValueError("Sparse indices must match the query sequence") + if any(x.ndim != 3 or x.shape[0] != 1 for x in (window, pooled)): + raise ValueError("Prepare one request's KV rows") + if window.dtype != mx.uint8 or pooled.dtype != mx.uint8: + raise ValueError("Expected packed uint8 KV") + if window.shape[-1] != dim + dim // 32 or pooled.shape[-1] != dim // 2 + dim // 16: + raise ValueError("Invalid packed KV row width") + if q.dtype == mx.bfloat16: + return rounded_packed_attention(q, window, pooled, wi, ci, sink, scale) + + # Short verification blocks share the decode reduction and split geometry. + # Each query owns its causal indices while all rows share one dispatch. + chunk = 32 if length <= 8 else 128 + splits = max(1, (wi.shape[-1] + ci.shape[-1] + chunk - 1) // chunk) + mma = length > 8 and dim <= 512 + head_group = 8 if mma else 4 + partial = _kernel("attention_mma" if mma else "attention")( + inputs=[ + q, + window if window.size else mx.zeros((1,), mx.uint8), + pooled if pooled.size else mx.zeros((1,), mx.uint8), + wi.astype(mx.int32) if wi.size else mx.zeros((1,), mx.int32), + ci.astype(mx.int32) if ci.size else mx.zeros((1,), mx.int32), + mx.array( + [ + heads, + wi.shape[-1], + ci.shape[-1], + window.shape[1], + pooled.shape[1], + splits, + ], + mx.int32, + ), + mx.array([scale]), + ], + template=[("D", dim), ("CHUNK", chunk)], + grid=((heads + head_group - 1) // head_group * 128, length, splits), + threadgroup=(128, 1, 1), + output_shapes=[(1, length, heads, splits, dim + 2)], + output_dtypes=[mx.float32], + )[0] + return _kernel("merge")( + inputs=[partial, sink, mx.array([heads, splits], mx.int32)], + template=[("D", dim), ("T", q.dtype)], + grid=((heads + 3) // 4 * 128, length, 1), + threadgroup=(128, 1, 1), + output_shapes=[q.shape], + output_dtypes=[q.dtype], + )[0] + + +def packed_index_scores( + q, keys, weights, start, ratio, candidates=None, *, key_start=0 +): + """Fuse dot/ReLU/weighted-head reduction without [query, head, context] scratch.""" + if q.ndim != 4 or q.shape[0] != 1 or q.shape[-1] % 32 or keys.dtype != mx.uint8: + raise ValueError("Expected one request and packed FP4 index keys") + _, length, heads, dim = q.shape + if not length or not heads or not dim or ratio <= 0 or start < 0 or key_start < 0: + raise ValueError("Invalid index query geometry or cache position") + if keys.ndim != 3 or keys.shape[0] != 1 or weights.shape != (1, length, heads): + raise ValueError("Index keys or weights do not match the query") + if candidates is not None and ( + candidates.ndim != 3 or candidates.shape[:2] != (1, length) + ): + raise ValueError("Candidate rows must match the query sequence") + width = keys.shape[1] if candidates is None else candidates.shape[-1] + if keys.shape[-1] != dim // 2 + dim // 32: + raise ValueError("Invalid packed index row width") + if not width: + return mx.zeros((1, length, 0), mx.float32) + mma = dim <= 128 and heads >= 8 + head_split = mma and heads >= 32 + cols = 16 if head_split else 32 + return _kernel("index_mma" if mma else "index")( + inputs=[ + q, + keys if keys.size else mx.zeros((1,), mx.uint8), + weights.astype(mx.float32), + ( + mx.zeros((1,), mx.int32) + if candidates is None + else candidates.astype(mx.int32) + ), + mx.array([heads, keys.shape[1], width, start, ratio, key_start], mx.int32), + ], + template=[ + ("D", dim), + ("CANDIDATES", candidates is not None), + ("HEAD_SPLIT", head_split), + ("HEADS", heads), + ("RATIO", ratio), + ], + grid=( + ((width + cols - 1) // cols if mma else (width + 3) // 4) * 128, + length, + 1, + ), + threadgroup=(128, 1, 1), + output_shapes=[(1, length, width)], + output_dtypes=[mx.float32], + )[0] + + +_TOPK = r""" + const uint tid = thread_index_in_threadgroup; + const uint query = threadgroup_position_in_grid.y; + const uint tile = threadgroup_position_in_grid.x; + const int width = meta[0], base = meta[1]; + threadgroup float exchange_values[TILE]; + threadgroup int exchange_ids[TILE]; + float values[TILE / THREADS], next_values[TILE / THREADS]; + int indices[TILE / THREADS], next_ids[TILE / THREADS]; + for (uint j = 0; j < TILE / THREADS; ++j) { + const uint i = tid + j * THREADS, pos = tile * TILE + i; + float value = -INFINITY; + if (pos < width) { + for (uint k = 0; k < BLOCK; ++k) { + const uint src = pos * BLOCK + k; + if (src < uint(meta[2])) value = max(value, scores[query * meta[2] + src]); + } + const int length = (meta[3] + int(query) + 1) / RATIO; + if (FORCE && length > 0 && int(pos) + base == (length - 1) / BLOCK) + value = INFINITY; + } + values[j] = value; + indices[j] = pos < width ? (EXPLICIT ? ids[query * width + pos] : base + int(pos)) : INT_MAX; + } + // Only cross-SIMD exchanges need threadgroup storage and barriers. + for (uint size = 2; size <= TILE; size <<= 1) { + for (uint stride = size >> 1; stride; stride >>= 1) { + const bool cross_simd = stride >= 32 && stride < THREADS; + if (cross_simd) { + for (uint j = 0; j < TILE / THREADS; ++j) { + exchange_values[tid + j * THREADS] = values[j]; + exchange_ids[tid + j * THREADS] = indices[j]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + for (uint j = 0; j < TILE / THREADS; ++j) { + const uint i = tid + j * THREADS; + float other; + int other_id; + if (stride < 32) { + other = simd_shuffle_xor(values[j], stride); + other_id = simd_shuffle_xor(indices[j], stride); + } else if (cross_simd) { + other = exchange_values[i ^ stride]; + other_id = exchange_ids[i ^ stride]; + } else { + other = values[j ^ (stride / THREADS)]; + other_id = indices[j ^ (stride / THREADS)]; + } + const bool better = other > values[j] || (other == values[j] && other_id < indices[j]); + const bool worse = other < values[j] || (other == values[j] && other_id > indices[j]); + const bool descending = ((i & size) == 0) == ((i & stride) == 0); + const bool take = descending ? better : worse; + next_values[j] = take ? other : values[j]; + next_ids[j] = take ? other_id : indices[j]; + } + if (cross_simd) threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint j = 0; j < TILE / THREADS; ++j) { + values[j] = next_values[j]; indices[j] = next_ids[j]; + } + } + } + for (uint j = 0; j < TILE / THREADS; ++j) { + const uint i = tid + j * THREADS; + if (i < K) { + const size_t out = (size_t(query) * NT + tile) * K + i; + selected_scores[out] = values[j]; + selected_ids[out] = indices[j]; + } + } + +""" + + +@cache +def _topk_kernel(): + return mx.fast.metal_kernel( + name="deepseek_v41_tile_topk", + input_names=["scores", "ids", "meta"], + output_names=["selected_scores", "selected_ids"], + source=_TOPK, + header=_HEADER, + ) + + +_TOPK_MERGE = r""" + const uint pos = thread_position_in_grid.x; + const uint query = threadgroup_position_in_grid.y; + const uint group = threadgroup_position_in_grid.z; + const uint na = meta[0], nb = meta[1], runs = meta[2]; + const uint groups = GROUPED ? (runs + FANIN - 1) / FANIN : 1; + if (GROUPED) { + const uint source = pos / K, own = pos % K; + const uint first = group * FANIN, n = min(uint(FANIN), runs - first); + if (source >= n) return; + const size_t base = (size_t(query) * runs + first) * K; + const float value = a_scores[base + source * K + own]; + const int id = a_ids[base + source * K + own]; + uint rank = own; + for (uint run = 0; run < n; ++run) { + if (run == source) continue; + uint lo = 0, hi = K - rank; + while (lo < hi) { + const uint mid = (lo + hi) / 2; + const float other = a_scores[base + run * K + mid]; + const int other_id = a_ids[base + run * K + mid]; + const bool before = other > value || (other == value && + (other_id < id || (run < source && other_id == id))); + if (before) lo = mid + 1; else hi = mid; + } + rank += lo; + // Once K entries precede this item, later runs cannot rescue it. + if (rank >= K) return; + } + const size_t out = (size_t(query) * groups + group) * K + rank; + selected_scores[out] = value; + selected_ids[out] = id; + return; + } + const uint left_n = na, right_n = nb; + if (pos >= left_n + right_n) return; + const size_t abase = size_t(query) * na, bbase = size_t(query) * nb; + const bool right = pos >= left_n; + const uint own = right ? pos - left_n : pos; + const float value = right ? b_scores[bbase + own] : a_scores[abase + own]; + const int id = right ? b_ids[bbase + own] : a_ids[abase + own]; + if (own >= K) return; + uint lo = 0, hi = min(right ? left_n : right_n, uint(K) - own); + while (lo < hi) { + const uint mid = (lo + hi) / 2; + const float other = right ? a_scores[abase + mid] : b_scores[bbase + mid]; + const int other_id = right ? a_ids[abase + mid] : b_ids[bbase + mid]; + // Identical entries in the left run precede those in the right run. + const bool before = other > value || (other == value && + (other_id < id || (right && other_id == id))); + if (before) lo = mid + 1; else hi = mid; + } + const uint rank = own + lo; + if (rank < K) { + const size_t out = (size_t(query) * groups + group) * K + rank; + selected_scores[out] = value; + selected_ids[out] = id; + } +""" + + +@cache +def _topk_merge_kernel(): + return mx.fast.metal_kernel( + name="deepseek_v41_sorted_topk_merge", + input_names=["a_scores", "a_ids", "b_scores", "b_ids", "meta"], + output_names=["selected_scores", "selected_ids"], + source=_TOPK_MERGE, + header=_HEADER, + ) + + +def _merge_topk(a, b, count, *, runs=0): + """Merge sorted winners by parallel rank search, without concatenation.""" + if not count: + return a + na, nb = a[0].shape[-1], b[0].shape[-1] + if count > 2048: + return _tile_topk( + mx.concatenate([a[0], b[0]], -1), + count, + ids=mx.concatenate([a[1], b[1]], -1), + ) + fanin = 4 if count <= 512 else 2 + groups = (runs + fanin - 1) // fanin if runs else 1 + width = fanin * count if runs else na + nb + return tuple( + _topk_merge_kernel()( + inputs=[*a, *b, mx.array([na, nb, runs], mx.int32)], + template=[("K", count), ("GROUPED", bool(runs)), ("FANIN", fanin)], + grid=((width + 255) // 256 * 256, a[0].shape[1], groups), + threadgroup=(256, 1, 1), + output_shapes=[(1, a[0].shape[1], groups * count)] * 2, + output_dtypes=[mx.float32, mx.int32], + ) + ) + + +def _tile_topk( + scores, + count, + *, + offset=0, + ids=None, + block_size=1, + force_latest=False, + start=0, + ratio=1, +): + """Sort each initial tile once, then merge sorted winners by rank.""" + score_width = scores.shape[-1] + width = (score_width + block_size - 1) // block_size + count = min(count, width) + if count <= 0: + return scores[..., :0], mx.zeros((*scores.shape[:-1], 0), mx.int32) + if count > 2048: + if block_size != 1 or force_latest: + padded = mx.pad( + scores, + [(0, 0), (0, 0), (0, -score_width % block_size)], + constant_values=-float("inf"), + ) + scores = padded.reshape(1, scores.shape[1], -1, block_size).max(-1) + lengths = (mx.arange(start + 1, start + scores.shape[1] + 1) // ratio)[ + None, :, None + ] + if force_latest: + scores = mx.where( + (lengths > 0) + & (mx.arange(width) + offset == (lengths - 1) // block_size), + float("inf"), + scores, + ) + if ids is None: + ids = mx.broadcast_to( + mx.arange(width, dtype=mx.int32) + offset, scores.shape + ) + order = mx.argpartition(-scores, kth=count - 1, axis=-1)[..., :count] + return mx.take_along_axis(scores, order, -1), mx.take_along_axis(ids, order, -1) + tile_limit = 4096 if scores.shape[1] == 1 else max(1024, 2 * count) + tile = max(32, 1 << (min(width, tile_limit) - 1).bit_length()) + tiles = (width + tile - 1) // tile + threads = min(256, tile) + winners = tuple( + _topk_kernel()( + inputs=[ + scores, + ids if ids is not None else mx.zeros((1,), mx.int32), + mx.array([width, offset, score_width, start, ratio], mx.int32), + ], + template=[ + ("TILE", tile), + ("K", count), + ("NT", tiles), + ("EXPLICIT", ids is not None), + ("BLOCK", block_size), + ("FORCE", force_latest), + ("THREADS", threads), + ("RATIO", ratio), + ], + grid=(tiles * threads, scores.shape[1], 1), + threadgroup=(threads, 1, 1), + output_shapes=[(1, scores.shape[1], tiles * count)] * 2, + output_dtypes=[mx.float32, mx.int32], + ) + ) + while tiles > 1: + winners = _merge_topk(winners, winners, count, runs=tiles) + fanin = 4 if count <= 512 else 2 + tiles = (tiles + fanin - 1) // fanin + return winners + + +def packed_index_topk( + q, + keys, + weights, + start, + ratio, + count, + *, + block_count=0, + block_size=0, + chunk_size=None, + query_chunk_size=None, +): + """Stream exact source top-k and optional block maxima with bounded scratch. + + All causally visible source keys are scanned. A single bounded tile remains + lazy so decode can submit it with the rest of the layer. Larger scans use + GPU batches that overlap CPU construction of the next batch. + The prior batch is drained before + submitting another, and the final batch is drained before returning. + Returns chronological IDs, with -1 padding. + """ + if query_chunk_size is None: + # Fill the score budget with queries when the key prefix is short. + # A fixed 16-query tile creates many unnecessary submission barriers. + query_chunk_size = min(512, max(16, 1048576 // max(1, keys.shape[1]))) + if count < 0 or block_count < 0 or query_chunk_size <= 0: + raise ValueError("Invalid index selection budget") + if chunk_size is None: + chunk_size = min( + 524288 if q.shape[1] == 1 else 262144, + 1048576 // max(1, min(q.shape[1], query_chunk_size)), + ) + if chunk_size <= 0: + raise ValueError("Invalid index selection budget") + if block_count and block_size <= 0: + raise ValueError("Candidate block size must be positive") + # Validate even an empty source through the scoring entry point. + packed_index_scores(q, keys[:, :0], weights, start, ratio) + width = keys.shape[1] + count = min(count, width) + if block_count: + block_count = min(block_count, (width + block_size - 1) // block_size) + chunk_size = max(block_size, chunk_size // block_size * block_size) + results, block_results = [], [] + batch_chunks = 1 if q.shape[1] == 1 else 2 + pending = () + single_tile = ( + q.shape[1] <= query_chunk_size + and min(width, (start + q.shape[1]) // ratio) <= chunk_size + ) + for begin in range(0, q.shape[1], query_chunk_size): + end = min(begin + query_chunk_size, q.shape[1]) + running = ( + mx.full((1, end - begin, count), -float("inf")), + mx.full((1, end - begin, count), 2147483647, mx.int32), + ) + blocks = ( + mx.full((1, end - begin, block_count), -float("inf")), + mx.full((1, end - begin, block_count), 2147483647, mx.int32), + ) + visible = min(width, (start + end) // ratio) + for first in range(0, visible, chunk_size): + stop = min(first + chunk_size, visible) + scores = packed_index_scores( + q[:, begin:end], + keys[:, first:stop], + weights[:, begin:end], + start + begin, + ratio, + key_start=first, + ) + values, ids = _tile_topk(scores, count, offset=first) + running = ( + (values, ids) + if first == 0 and values.shape[-1] == count + else _merge_topk(running, (values, ids), count) + ) + if block_count: + values, ids = _tile_topk( + scores, + block_count, + offset=first // block_size, + block_size=block_size, + force_latest=True, + start=start + begin, + ratio=ratio, + ) + blocks = ( + (values, ids) + if first == 0 and values.shape[-1] == block_count + else _merge_topk(blocks, (values, ids), block_count) + ) + if not single_tile and ( + stop == visible or (first // chunk_size + 1) % batch_chunks == 0 + ): + # Prepare this bounded graph while the previous batch runs; + # drain it before submission to keep only one GPU batch active. + if pending: + mx.eval(*pending) + pending = (*running, *blocks) + mx.async_eval(*pending) + results.append( + mx.sort(mx.where(running[0] > -float("inf"), running[1], -1), axis=-1) + ) + block_results.append( + mx.sort(mx.where(blocks[0] > -float("inf"), blocks[1], -1), axis=-1) + ) + if pending: + mx.eval(*pending) + return mx.concatenate(results, 1), mx.concatenate(block_results, 1) diff --git a/omlx/patches/deepseek_v41/language.py b/omlx/patches/deepseek_v41/language.py new file mode 100644 index 0000000000..728bc85183 --- /dev/null +++ b/omlx/patches/deepseek_v41/language.py @@ -0,0 +1,953 @@ +# SPDX-License-Identifier: MIT +"""MLX reference port of DeepSeek V4.1 CSA2 and single-pass mHC. + +The official inference code is the numerical specification. Unlike its global +shared_attn and module buffers, all persistent state belongs to request caches. +Batch rows are evaluated independently so late admission cannot share history. +""" + +import math +from contextlib import nullcontext + +import mlx.core as mx +import mlx.nn as nn +import numpy as np +from mlx_lm.models.switch_layers import SwitchLinear + +from omlx.custom_kernels.glm_moe_dsa import fast as glm_fast + +from ..deepseek_v4.switch_layers import _block_config, _build_mxfp4_blocks +from .activation import quantize_paired_swiglu_activation, quantize_swiglu_activation +from .cache import DeepseekV41Cache +from .engram import Engram, NgramHash, build_compressed_token_map +from .head import project_logits +from .hyper_connection import ( + fused_hc_post, + fused_hc_pre_norm, + fused_hc_projection, + sinkhorn, +) +from .kernels import packed_index_scores, packed_index_topk, packed_sparse_attention +from .mtp import DSparkMixin +from .quantization import QuantizedProjection, pack_activation, quantize_activation +from .routing import combine_sorted_experts + + +@mx.compile +def norm(x, weight, eps): + f = x.astype(mx.float32) + return (f * mx.rsqrt(mx.mean(f * f, -1, keepdims=True) + eps) * weight).astype( + x.dtype + ) + + +class RMSNorm(nn.Module): + def __init__(self, dim, eps): + super().__init__() + self.weight = mx.ones((dim,)) + self.eps = eps + + def __call__(self, x): + return norm(x, self.weight, self.eps) + + +@mx.compile +def _rope(x, positions, params, compressed, inverse): + d, base, original_seq_len, beta_fast, beta_slow, rope_factor = params + freq = 1 / mx.power(base, mx.arange(0, d, 2).astype(mx.float32) / d) + if compressed and original_seq_len: + + def correction(rotations): + return ( + d + * math.log(original_seq_len / (rotations * 2 * math.pi)) + / (2 * math.log(base)) + ) + + low = max(math.floor(correction(beta_fast)), 0) + high = min(math.ceil(correction(beta_slow)), d - 1) + smooth = 1 - mx.clip((mx.arange(d // 2) - low) / max(high - low, 1e-3), 0, 1) + freq = freq / rope_factor * (1 - smooth) + freq * smooth + angles = positions.astype(mx.float32)[:, None] * freq + angles = angles.reshape(1, len(positions), *([1] * (x.ndim - 3)), d // 2) + if inverse: + angles = -angles + tail = x[..., -d:].astype(mx.float32).reshape(*x.shape[:-1], d // 2, 2) + a, b = tail[..., 0], tail[..., 1] + rotated = mx.stack( + [ + a * mx.cos(angles) - b * mx.sin(angles), + a * mx.sin(angles) + b * mx.cos(angles), + ], + -1, + ) + return mx.concatenate( + [x[..., :-d], rotated.reshape(*x.shape[:-1], d).astype(x.dtype)], -1 + ) + + +def rope(x, positions, config, compressed, inverse=False): + params = ( + config.rope_head_dim, + config.compress_rope_theta if compressed else config.rope_theta, + config.original_seq_len, + config.beta_fast, + config.beta_slow, + config.rope_factor, + ) + return _rope(x, positions, params, compressed, inverse) + + +def candidate_block_ids(scores, lengths, count, block): + width = scores.shape[-1] + if not width: + return mx.zeros((*scores.shape[:-1], 0), dtype=mx.int32) + padded = mx.pad( + scores, + [(0, 0)] * (scores.ndim - 1) + [(0, -width % block)], + constant_values=-float("inf"), + ) + grouped = padded.reshape(*scores.shape[:-1], -1, block).max(-1) + n = grouped.shape[-1] + grouped = mx.where( + (lengths > 0) & (mx.arange(n) == (lengths - 1) // block), float("inf"), grouped + ) + chosen = mx.argsort(-grouped, axis=-1)[..., : min(count, n)] + chosen = mx.sort(chosen, axis=-1).astype(mx.int32) + valid = mx.take_along_axis(grouped, chosen, -1) > -float("inf") + return mx.where(valid, chosen, -1) + + +def sparse_attention(q, selected, indices, sink, scale): + scores = ( + mx.einsum("bshd,bskd->bshk", q.astype(mx.float32), selected.astype(mx.float32)) + * scale + ) + scores = mx.where(indices[:, :, None, :] >= 0, scores, -float("inf")) + sinks = mx.broadcast_to(sink[None, None, :, None], (*scores.shape[:-1], 1)) + weights = mx.softmax(mx.concatenate([scores, sinks], -1), axis=-1)[..., :-1] + return mx.einsum("bshk,bskd->bshd", weights, selected.astype(mx.float32)).astype( + q.dtype + ) + + +class Compressor(nn.Module): + def __init__(self, c, ratio): + super().__init__() + self.wkv = nn.Linear(c.dim, c.head_dim, bias=False) + self.norm = RMSNorm(c.head_dim, c.norm_eps) + self.ratio = ratio + if ratio > 1: + self.wgate = nn.Linear(c.dim, c.head_dim, bias=False) + + def __call__(self, x, cache, start): + r = self.ratio + if r == 1: + return self.norm(self.wkv(x)) + kv, gate = self.wkv(x.astype(mx.float32)), self.wgate(x.astype(mx.float32)) + rem = start % r + if rem: + kv = mx.concatenate([cache[4][:, :rem], kv], 1) + gate = mx.concatenate([cache[5][:, :rem], gate], 1) + verify_state = getattr(cache, "_mtp_verify_state", None) + if verify_state is not None: + verify_state["compressor"] = (kv, gate) + cutoff = kv.shape[1] // r * r + cache[4], cache[5] = kv[:, cutoff:], gate[:, cutoff:] + if not cutoff: + return None + pooled = mx.sum( + kv[:, :cutoff].reshape(1, -1, r, kv.shape[-1]) + * mx.softmax(gate[:, :cutoff].reshape(1, -1, r, gate.shape[-1]), axis=2), + axis=2, + ) + return self.norm(pooled.astype(x.dtype)) + + +class Indexer(nn.Module): + def __init__(self, c, layer): + super().__init__() + self.wq_b = nn.Linear( + c.q_lora_rank, c.index_n_heads * c.index_head_dim, bias=False + ) + self.weights_proj = nn.Linear(c.dim, c.index_n_heads, bias=False) + if layer in c.kv_source_layers: + self.wk = nn.Linear(c.head_dim, c.index_head_dim, bias=False) + self.k_norm = RMSNorm(c.index_head_dim, c.norm_eps) + self._config, self._layer = c, layer + + def __call__(self, x, qr, latent, cache, shared, start, ratio): + c, layer = self._config, self._layer + end = start + x.shape[1] + if layer in c.kv_source_layers: + previous = cache[3] + previous = ( + previous[:, : start // ratio] + if previous is not None + else pack_activation( + mx.zeros((1, 0, c.index_head_dim), x.dtype), bits=4 + ) + ) + if latent is not None: + pos = mx.arange(start // ratio, end // ratio) * ratio + key = pack_activation( + rope(self.k_norm(self.wk(latent)), pos, c, True), bits=4 + ) + previous = mx.concatenate([previous, key], 1) + shared["index_k"] = cache[3] = previous + key = shared["index_k"] + q = self.wq_b(qr).reshape(1, x.shape[1], c.index_n_heads, c.index_head_dim) + q = quantize_activation(rope(q, mx.arange(start, end), c, True), bits=4) + weights = self.weights_proj(x).astype(mx.float32) * ( + c.index_head_dim**-0.5 * c.index_n_heads**-0.5 + ) + candidates = None + if 0 <= c.candidate_source_layer < layer: + blocks = shared["candidates"] + candidates = blocks[..., None] * c.candidate_block_size + mx.arange( + c.candidate_block_size + ) + candidates = mx.where(blocks[..., None] >= 0, candidates, -1).reshape( + 1, x.shape[1], blocks.shape[-1] * c.candidate_block_size + ) + if candidates is None: + idx, blocks = packed_index_topk( + q, + key, + weights, + start, + ratio, + c.index_topk, + block_count=( + c.candidate_topk_blocks if layer == c.candidate_source_layer else 0 + ), + block_size=c.candidate_block_size, + ) + if layer == c.candidate_source_layer: + shared["candidates"] = blocks + return idx + scores = packed_index_scores(q, key, weights, start, ratio, candidates) + count = min(c.index_topk, scores.shape[-1]) + order = mx.argsort(-scores, axis=-1)[..., :count].astype(mx.int32) + valid = mx.take_along_axis(scores, order, axis=-1) > -float("inf") + idx = mx.take_along_axis(candidates, order, -1) + # Keep chronological order; invalid slots are masked by attention. + return mx.sort(mx.where(valid, idx, -1), axis=-1) + + +class Attention(nn.Module): + def __init__(self, c, layer): + super().__init__() + self._config, self._layer = c, layer + self.attn_sink = mx.zeros((c.n_heads,), mx.float32) + self.wq_a = nn.Linear(c.dim, c.q_lora_rank, bias=False) + self.q_norm = RMSNorm(c.q_lora_rank, c.norm_eps) + self.wq_b = nn.Linear(c.q_lora_rank, c.n_heads * c.head_dim, bias=False) + self.wkv = nn.Linear(c.dim, c.head_dim, bias=False) + self.kv_norm = RMSNorm(c.head_dim, c.norm_eps) + self.wo_a = nn.Linear( + c.n_heads * c.head_dim // c.o_groups, c.o_groups * c.o_lora_rank, bias=False + ) + self.wo_b = nn.Linear(c.o_groups * c.o_lora_rank, c.dim, bias=False) + if layer in c.kv_source_layers: + self.compressor = Compressor(c, c.compress_ratios[layer]) + if layer in c.index_source_layers: + self.indexer = Indexer(c, layer) + + def _input_projections(self, x): + if all( + isinstance(p, QuantizedProjection) and p.quantize_input + for p in (self.wq_a, self.wkv) + ): + quantized = quantize_activation(x) + return ( + self.wq_a.project_quantized(quantized), + self.wkv.project_quantized(quantized), + ) + return self.wq_a(x), self.wkv(x) + + def __call__(self, x, cache, shared, start): + c, layer = self._config, self._layer + ratio, length = c.compress_ratios[layer], x.shape[1] + positions = mx.arange(start, start + length) + query, kv_input = self._input_projections(x) + qr = self.q_norm(query) + q = rope( + self.wq_b(qr).reshape(1, length, c.n_heads, c.head_dim), + positions, + c, + bool(ratio), + ) + new = pack_activation(rope(self.kv_norm(kv_input), positions, c, bool(ratio))) + old = cache[1] + old_len = min(start, c.window_size) + kv = mx.concatenate([old[:, :old_len], new], 1) if old_len else new + verify_state = getattr(cache, "_mtp_verify_state", None) + if verify_state is not None: + verify_state["window"] = kv + cache[1] = kv[:, -c.window_size :] + # List only the causal local window, including the current token. + if start == 0: + local = mx.maximum(positions[:, None] - c.window_size + 1, 0) + local = local + mx.arange(min(length, c.window_size)) + else: + local = positions[:, None] - c.window_size + 1 + mx.arange(c.window_size) + valid = (local >= max(0, start - old_len)) & (local <= positions[:, None]) + idx = mx.where(valid, local - (start - old_len), -1)[None] + pooled = mx.zeros((1, 0, c.head_dim // 2 + c.head_dim // 16), mx.uint8) + ci = mx.zeros((1, length, 0), mx.int32) + if ratio: + latent = None + if layer in c.kv_source_layers: + latent = self.compressor(x, cache, start) + if cache[2] is None: + cache[2] = pack_activation( + mx.zeros((1, 0, c.head_dim), x.dtype), + bits=4, + group_size=16, + e4m3_scale=True, + ) + shared["kv"] = cache[2][:, : start // ratio] + if layer in c.index_source_layers: + shared["idx"] = self.indexer(x, qr, latent, cache, shared, start, ratio) + if latent is not None: + compressed = rope( + latent, + mx.arange(start // ratio, (start + length) // ratio) * ratio, + c, + True, + ) + compressed = pack_activation( + compressed, bits=4, group_size=16, e4m3_scale=True + ) + shared["kv"] = cache[2] = mx.concatenate([shared["kv"], compressed], 1) + ci, pooled = shared["idx"], shared["kv"] + if ( + length > 8 + and c.n_heads == 64 + and c.head_dim == 512 + and q.dtype == mx.bfloat16 + and glm_fast.has_symbol("deepseek_v41_packed_attention") + ): + out = glm_fast.deepseek_v41_packed_attention( + q.transpose(0, 2, 1, 3), + kv[:, None], + pooled, + ci[:, None].astype(mx.uint32), + self.attn_sink, + c.head_dim**-0.5, + start, + max(ratio, 1), + c.window_size, + ).transpose(0, 2, 1, 3) + else: + out = packed_sparse_attention( + q, kv, pooled, idx, ci, self.attn_sink, c.head_dim**-0.5 + ) + out = rope(out, positions, c, bool(ratio), inverse=True) + grouped = out.reshape(1, length, c.o_groups, -1) + weight = self.wo_a.weight.reshape(c.o_groups, c.o_lora_rank, -1) + return self.wo_b(mx.einsum("bsgd,grd->bsgr", grouped, weight).flatten(-2)) + + +class Expert(nn.Module): + def __init__(self, c, switched=False): + super().__init__() + + def linear(a, b): + return ( + SwitchLinear(a, b, c.n_routed_experts, bias=False) + if switched + else nn.Linear(a, b, bias=False) + ) + + self.w1, self.w3 = ( + linear(c.dim, c.moe_inter_dim), + linear(c.dim, c.moe_inter_dim), + ) + self.w2 = linear(c.moe_inter_dim, c.dim) + self._limit = c.swiglu_limit + + @property + def quantizes_input(self): + return all( + isinstance(p, QuantizedProjection) and p.quantize_input + for p in (self.w1, self.w3) + ) + + def __call__( + self, + x, + indices=None, + weights=None, + sorted_indices=False, + *, + input_quantized=False, + ): + if input_quantized and not self.quantizes_input: + raise ValueError( + "Prequantized input requires matching quantized projections" + ) + projections = (self.w1, self.w3, self.w2) + if ( + indices is not None + and weights is not None + and not sorted_indices + and x.dtype == mx.bfloat16 + and mx.default_device() != mx.cpu + and all( + isinstance(p, QuantizedProjection) + and ( + (p.mode in ("mxfp4", "mxfp8") and p.group_size == 32) + or ( + p.mode == "affine" + and p.bits in (2, 3, 4, 6, 8) + and p.get("biases") is not None + ) + ) + and p.quantize_input + for p in projections + ) + and 1 <= x.size // self.w1.input_dims <= 8 + and x.size // self.w1.input_dims == indices.size // indices.shape[-1] + and indices.size > 0 + and weights.size == indices.size + and glm_fast.has_symbol("deepseek_v41_grouped_expert") + ): + # Short DSpark verification blocks share the decode execution + # pipeline, retaining a distinct quantized input for each token. + inp = (x if input_quantized else quantize_activation(x)).reshape( + -1, 1, self.w1.input_dims + ) + ids = indices.reshape(-1).astype(mx.uint32) + lhs = mx.arange(ids.size, dtype=mx.uint32) // indices.shape[-1] + + def gather(value, projection, left): + return mx.gather_qmm( + value, + projection.weight, + projection.scales, + projection.get("biases"), + lhs_indices=left, + rhs_indices=ids, + transpose=True, + group_size=projection.group_size, + bits=projection.bits, + mode=projection.mode, + ) + + # Keep these nodes unevaluated for one native execution pipeline. + gate = gather(inp, self.w1, lhs) + up = gather(inp, self.w3, lhs) + y = quantize_swiglu_activation( + gate, up, weights.reshape(-1), x.dtype, self._limit + ) + down = gather(y, self.w2, mx.arange(ids.size, dtype=mx.uint32)) + return glm_fast.deepseek_v41_grouped_expert(gate, up, y, down).reshape( + *indices.shape, 1, x.shape[-1] + ) + block_plan = None + block_kind = None + if sorted_indices: + kinds = [ + ( + p._native_block_kind(x, True) + if isinstance(p, QuantizedProjection) + else None + ) + for p in projections + ] + if kinds[0] is not None and all(kind == kinds[0] for kind in kinds): + block_kind = kinds[0] + bm, variant = _block_config(indices.size, block_kind) + meta, count = _build_mxfp4_blocks(indices, self.w1.num_experts, bm) + block_plan = (meta, count, variant) + + def project(module, value): + if indices is None: + return module(value) + if isinstance(module, QuantizedProjection): + return module(value, indices, sorted_indices, block_plan) + return module(value, indices, sorted_indices=sorted_indices) + + dtype = x.dtype + pair = None + if ( + block_plan is not None + and block_kind == "mxfp4" + and self.w1.quantize_input == self.w3.quantize_input + and self.w1.output_dims == self.w3.output_dims + and glm_fast.has_symbol("deepseek_mxfp4_gather_qmm_pair_concat_blocks") + ): + inp = ( + quantize_activation(x) + if self.w1.quantize_input and not input_quantized + else x + ) + pair = glm_fast.deepseek_mxfp4_gather_qmm_pair_concat_blocks( + inp, + self.w1.weight, + self.w1.scales, + self.w3.weight, + self.w3.scales, + *block_plan, + ) + gate = pair[..., : self.w1.output_dims] + up = pair[..., self.w1.output_dims :] + elif ( + block_kind == "affine" + and self.w1.bits == self.w3.bits + and self.w1.group_size == self.w3.group_size + and self.w1.quantize_input == self.w3.quantize_input + and self.w1.output_dims == self.w3.output_dims + and glm_fast.has_symbol("deepseek_affine_gather_qmm_pair_concat_blocks") + ): + inp = ( + quantize_activation(x) + if self.w1.quantize_input and not input_quantized + else x + ) + meta, count, variant = block_plan + pair = glm_fast.deepseek_affine_gather_qmm_pair_concat_blocks( + inp, + self.w1.weight, + self.w1.scales, + self.w1.biases, + self.w3.weight, + self.w3.scales, + self.w3.biases, + meta, + count, + self.w1.group_size, + self.w1.bits, + variant, + ) + gate = pair[..., : self.w1.output_dims] + up = pair[..., self.w1.output_dims :] + elif ( + isinstance(self.w1, QuantizedProjection) + and isinstance(self.w3, QuantizedProjection) + and self.w1.quantize_input == self.w3.quantize_input + ): + inp = ( + quantize_activation(x) + if self.w1.quantize_input and not input_quantized + else x + ) + gate = self.w1.project_quantized(inp, indices, sorted_indices, block_plan) + up = self.w3.project_quantized(inp, indices, sorted_indices, block_plan) + else: + gate = project(self.w1, x) + up = project(self.w3, x) + if ( + isinstance(self.w2, QuantizedProjection) + and self.w2.quantize_input + and gate.size + and gate.shape == up.shape + and gate.shape[-1] % 32 == 0 + and dtype in (mx.float32, mx.float16, mx.bfloat16) + and mx.default_device() != mx.cpu + and (weights is None or weights.size == gate.size // gate.shape[-1]) + ): + y = ( + quantize_paired_swiglu_activation(pair, weights, dtype, self._limit) + if pair is not None + else quantize_swiglu_activation(gate, up, weights, dtype, self._limit) + ) + return self.w2.project_quantized(y, indices, sorted_indices, block_plan) + gate, up = gate.astype(mx.float32), up.astype(mx.float32) + if self._limit: + gate = mx.minimum(gate, self._limit) + up = mx.clip(up, -self._limit, self._limit) + y = nn.silu(gate) * up + if weights is not None: + y *= weights[..., None, None] + return project(self.w2, y.astype(dtype)) + + +class Gate(nn.Module): + def __init__(self, c): + super().__init__() + self.weight = mx.zeros((c.n_routed_experts, c.dim)) + self.bias = mx.zeros((c.n_routed_experts,)) + if c.vision_enabled: + self.bias_vl = mx.zeros((c.n_routed_experts,)) + self._config = c + + def __call__(self, x, image_mask): + c = self._config + raw = (x.astype(mx.float32) @ self.weight.astype(mx.float32).T) / c.gate_temp + scores = ( + mx.softmax(raw, -1) + if c.score_func == "softmax" + else ( + mx.sigmoid(raw) + if c.score_func == "sigmoid" + else mx.sqrt(mx.logaddexp(raw, 0)) + ) + ) + bias = self.bias + if image_mask is not None and "bias_vl" in self: + bias = mx.where(image_mask[..., None], self.bias_vl, bias) + idx = mx.argsort(-(scores + bias), axis=-1)[..., : c.n_activated_experts] + weights = mx.take_along_axis(scores, idx, -1) + if c.norm_topk_prob and c.n_activated_experts > 1: + weights /= mx.sum(weights, -1, keepdims=True) + 1e-20 + return idx, weights * c.route_scale + + +class MoE(nn.Module): + def __init__(self, c): + super().__init__() + self.gate, self.experts, self.shared_experts = ( + Gate(c), + Expert(c, True), + Expert(c), + ) + + def __call__(self, x, image_mask): + idx, weights = self.gate(x, image_mask) + routed_quantized = self.experts.quantizes_input + shared_quantized = self.shared_experts.quantizes_input + # Quantization is row-local; reuse it before routing duplicates token rows. + quantized = ( + quantize_activation(x) if routed_quantized or shared_quantized else x + ) + routed_input = quantized if routed_quantized else x + if x.shape[1] >= 32 and idx.size >= 64: + shape = idx.shape + flat = idx.reshape(-1) + order = mx.argsort(flat) + inverse = mx.argsort(order) + selected = routed_input.reshape(-1, x.shape[-1])[order // shape[-1]][ + :, None, : + ] + routed = self.experts( + selected, + flat[order], + weights.reshape(-1)[order], + sorted_indices=True, + input_quantized=routed_quantized, + ) + shared = self.shared_experts( + quantized if shared_quantized else x, input_quantized=shared_quantized + ) + combined = combine_sorted_experts(routed, inverse, shared) + if combined is not None: + return combined + routed = routed[inverse].reshape(*shape, x.shape[-1]) + else: + routed = self.experts( + routed_input[..., None, None, :], + idx, + weights, + input_quantized=routed_quantized, + ).squeeze(-2) + shared = self.shared_experts( + quantized if shared_quantized else x, input_quantized=shared_quantized + ) + return (routed.astype(mx.float32).sum(-2) + shared.astype(mx.float32)).astype( + x.dtype + ) + + +@mx.compile +def _hc_mix_weights(mixes, scale, base, n, hc_eps, iters): + pre = mx.sigmoid(mixes[..., :n] * scale[0] + base[:n]) + hc_eps + post = 2 * mx.sigmoid(mixes[..., n : 2 * n] * scale[1] + base[n : 2 * n]) + comb = (mixes[..., 2 * n :] * scale[2] + base[2 * n :]).reshape( + *mixes.shape[:-1], n, n + ) + comb = mx.softmax(comb, -1) + hc_eps + return pre, post, sinkhorn(comb, hc_eps, iters) + + +@mx.compile +def _hc_mixes(x, fn, scale, base, n, norm_eps, hc_eps, iters): + flat = x.flatten(-2).astype(mx.float32) + mixes = (flat @ fn.T) * mx.rsqrt(mx.mean(flat * flat, -1, keepdims=True) + norm_eps) + return _hc_mix_weights(mixes, scale, base, n, hc_eps, iters) + + +def hc_mixes(x, fn, scale, base, c): + if ( + x.ndim == 4 + and x.shape[1] >= 256 + and x.shape[-2] == c.hc_mult == 4 + and x.shape[-1] > 0 + and x.dtype == mx.bfloat16 + and fn.dtype == mx.float32 + and fn.shape == (24, 4 * x.shape[-1]) + and mx.default_device() == mx.gpu + ): + mixes = fused_hc_projection(x, fn, c.norm_eps) + return _hc_mix_weights( + mixes, scale, base, c.hc_mult, c.hc_eps, c.hc_sinkhorn_iters + ) + return _hc_mixes( + x, fn, scale, base, c.hc_mult, c.norm_eps, c.hc_eps, c.hc_sinkhorn_iters + ) + + +@mx.compile +def hc_pre(x, pre): + return mx.sum(x.astype(mx.float32) * pre[..., None], axis=-2).astype(x.dtype) + + +def hc_pre_norm(x, pre, weight, eps): + if ( + x.ndim == 4 + and x.size + and x.shape[-2] == 4 + and x.shape[-1] <= 8192 + and x.dtype in (mx.bfloat16, mx.float16, mx.float32) + and pre.dtype == mx.float32 + and pre.shape == x.shape[:-1] + and weight.shape == (x.shape[-1],) + and weight.dtype in (mx.bfloat16, mx.float16, mx.float32) + and mx.default_device() == mx.gpu + ): + return fused_hc_pre_norm(x, pre, weight, eps) + return norm(hc_pre(x, pre), weight, eps) + + +@mx.compile +def _hc_post_reference(x, residual, post, comb): + return ( + post[..., None] * x[..., None, :] + + mx.einsum("bsij,bsid->bsjd", comb, residual.astype(mx.float32)) + ).astype(x.dtype) + + +def hc_post(x, residual, post, comb): + if ( + x.ndim == 3 + and x.size + and x.dtype in (mx.bfloat16, mx.float16, mx.float32) + and residual.dtype == x.dtype + and residual.shape == (*x.shape[:-1], 4, x.shape[-1]) + and post.shape == (*x.shape[:-1], 4) + and comb.shape == (*x.shape[:-1], 4, 4) + and post.dtype == mx.float32 + and comb.dtype == mx.float32 + and mx.default_device() == mx.gpu + ): + return fused_hc_post(x, residual, post, comb) + return _hc_post_reference(x, residual, post, comb) + + +class Block(nn.Module): + def __init__(self, c, layer): + super().__init__() + self._config = c + self.attn, self.ffn = Attention(c, layer), MoE(c) + self.attn_norm, self.ffn_norm = ( + RMSNorm(c.dim, c.norm_eps), + RMSNorm(c.dim, c.norm_eps), + ) + size = (2 + c.hc_mult) * c.hc_mult + for kind in ("attn", "ffn"): + self[f"hc_{kind}_fn"] = mx.zeros((size, c.hc_mult * c.dim)) + self[f"hc_{kind}_base"] = mx.zeros((size,)) + self[f"hc_{kind}_scale"] = mx.ones((3,)) + if layer in c.engram_layer_ids: + self.engram = Engram(c, list(c.engram_layer_ids).index(layer)) + + def __call__(self, h, pre, cache, shared, start, image_mask): + ap, ao, ac = hc_mixes( + h, self.hc_attn_fn, self.hc_attn_scale, self.hc_attn_base, self._config + ) + h = hc_post( + self.attn( + hc_pre_norm(h, pre, self.attn_norm.weight, self.attn_norm.eps), + cache, + shared, + start, + ), + h, + ao, + ac, + ) + fp, fo, fc = hc_mixes( + h, self.hc_ffn_fn, self.hc_ffn_scale, self.hc_ffn_base, self._config + ) + h = hc_post( + self.ffn( + hc_pre_norm(h, ap, self.ffn_norm.weight, self.ffn_norm.eps), image_mask + ), + h, + fo, + fc, + ) + return h, fp + + +class LanguageModel(DSparkMixin, nn.Module): + def __init__(self, config): + super().__init__() + self._config = config + config.validate() + self.embed = nn.Embedding(config.vocab_size, config.dim) + self.layers = [Block(config, i) for i in range(config.n_layers)] + self.norm = RMSNorm(config.dim, config.norm_eps) + self.head = nn.Linear(config.dim, config.vocab_size, bias=False) + if config.preserve_mtp: + from .dspark import make_stages + + self.mtp = make_stages(config) + self._hasher = None + from ..mlx_lm_mtp import get_mtp_depth, is_mtp_active + + self.configure_mtp(config.preserve_mtp and is_mtp_active(), get_mtp_depth()) + + def make_dspark_cache(self): + from .dspark import make_cache + + return make_cache(self._config) + + def forward_spec(self, input_ids, main_hidden, cache, *, temperature=0.0): + from .dspark import forward_spec + + return forward_spec( + self, input_ids, main_hidden, cache, temperature=temperature + ) + + def set_tokenizer(self, tokenizer): + mapping, _ = build_compressed_token_map(tokenizer) + self.set_token_map(mapping) + + def set_token_map(self, token_map): + if self._config.engram_layer_ids: + self._hasher = NgramHash(self._config, token_map) + + def make_cache(self): + return [ + DeepseekV41Cache( + self._config.compress_ratios[i] + if i in self._config.kv_source_layers + else 0 + ) + for i in range(len(self.layers)) + ] + + def _forward( + self, input_ids, cache=None, inputs_embeds=None, token_types=None, **kwargs + ): + c = self._config + cache = self.make_cache() if cache is None else cache + if len(cache) != len(self.layers): + raise ValueError("DeepSeek V4.1 cache layer count mismatch") + for i, item in enumerate(cache): + ratio = c.compress_ratios[i] if i in c.kv_source_layers else 0 + if item.compress_ratio is None: + item.compress_ratio = ratio # Upgrade a legacy full snapshot. + elif item.compress_ratio != ratio: + raise ValueError("DeepSeek V4.1 cache compression layout mismatch") + if c.engram_layer_ids and self._hasher is None: + raise ValueError( + "DeepSeek V4.1 requires its tokenizer-derived Engram token map" + ) + masks = cache[0].make_mask(input_ids.shape[1]) + capture = bool(kwargs.get("return_dspark_hidden", False)) + if capture and input_ids.shape[0] != 1: + raise ValueError( + "DSpark target capture currently requires one unpadded row" + ) + captured = {} + results, rows = [], [[] for _ in self.layers] + for row in range(input_ids.shape[0]): + valid = ( + np.ones(input_ids.shape[1], bool) + if masks is None + else np.asarray(masks[row]) + ) + positions = np.flatnonzero(valid) + if not len(positions): + results.append(mx.zeros((1, input_ids.shape[1], c.vocab_size))) + for i, item in enumerate(cache): + rows[i].append(item.extract(row)) + continue + begin, end = int(positions[0]), int(positions[-1]) + 1 + if capture and (begin != 0 or end != input_ids.shape[1]): + raise ValueError("DSpark target capture requires an unpadded row") + if end - begin != len(positions): + raise ValueError("Prefill padding must be contiguous") + rc = [item.extract(row) for item in cache] + verify_states = kwargs.get("mtp_verify_states") + if verify_states is not None: + for item, state in zip(rc, verify_states): + item._mtp_verify_state = state + start = rc[0].size() + if any(item.size() != start for item in rc): + raise ValueError("DeepSeek V4.1 cache offsets diverged across layers") + ids = input_ids[row : row + 1, begin:end] + image_mask = ids == c.image_token_id if inputs_embeds is not None else None + h = ( + self.embed(ids) + if inputs_embeds is None + else inputs_embeds[row : row + 1, begin:end] + ) + hashes, history = (None, None) + if self._hasher is not None: + hashes, history = self._hasher(ids, rc[0][6], image_mask) + h = mx.repeat(h[..., None, :], c.hc_mult, -2) + pre = mx.broadcast_to( + (mx.arange(c.hc_mult) == 0).astype(mx.float32), h.shape[:-1] + ) + shared = {} + prefetch = getattr(self, "_engram_prefetch", None) + with prefetch.forward() if prefetch is not None else nullcontext(): + if prefetch is not None and c.engram_layer_ids: + first = self.layers[c.engram_layer_ids[0]].engram.embed + prefetch.submit(first, hashes[:, :, 0]) + for i, layer in enumerate(self.layers): + if "engram" in layer: + ix = list(c.engram_layer_ids).index(i) + if prefetch is not None: + mx.async_eval(h, pre) + h = layer.engram(h, hashes[:, :, ix], image_mask) + if prefetch is not None and ix + 1 < len(c.engram_layer_ids): + next_layer = self.layers[c.engram_layer_ids[ix + 1]] + prefetch.submit( + next_layer.engram.embed, hashes[:, :, ix + 1] + ) + if capture and i in c.dspark_target_layer_ids: + captured[i] = mx.mean(h, axis=2) + h, pre = layer(h, pre, rc[i], shared, start, image_mask) + if prefetch is not None and "engram" in layer: + mx.async_eval(h, pre) + rc[i][0] = mx.array([start + end - begin], mx.int32) + if history is not None and i == 0: + rc[i][6] = mx.array(history, mx.int64) + for slot in range(1, 7): + if rc[i][slot] is None: + width = c.index_head_dim if slot == 3 else c.head_dim + empty = mx.zeros((1, 0, width), h.dtype) + if slot == 1: + empty = pack_activation(empty) + elif slot == 2: + empty = pack_activation(empty, 4, 16, True) + elif slot == 3: + empty = pack_activation(empty, 4) + rc[i][slot] = ( + mx.zeros((1, 0), mx.int64) if slot == 6 else empty + ) + rows[i].append(rc[i]) + logits = project_logits(self.norm(hc_pre(h, pre)), self.head.weight) + results.append( + mx.pad(logits, [(0, 0), (begin, input_ids.shape[1] - end), (0, 0)]) + ) + for i, item in enumerate(cache): + merged = DeepseekV41Cache.merge(rows[i]) + item.cache = merged.cache + item.advance(input_ids.shape[1]) + logits = mx.concatenate(results, 0) + if capture: + if not c.dspark_target_layer_ids or set(captured) != set( + c.dspark_target_layer_ids + ): + raise ValueError("Incomplete DSpark target hidden capture") + return logits, mx.concatenate( + [captured[i] for i in c.dspark_target_layer_ids], axis=-1 + ) + return logits diff --git a/omlx/patches/deepseek_v41/loading.py b/omlx/patches/deepseek_v41/loading.py new file mode 100644 index 0000000000..6fca2d49cd --- /dev/null +++ b/omlx/patches/deepseek_v41/loading.py @@ -0,0 +1,270 @@ +# SPDX-License-Identifier: MIT +"""Stream original or converted V4.1 weights; Engram is resident or mmap-backed.""" + +import fcntl +import json +import logging +from contextlib import ExitStack, closing +from pathlib import Path + +import mlx.core as mx +from mlx.utils import tree_flatten +from mlx_lm.generate import wired_limit +from transformers import PreTrainedTokenizerFast + +from .config import ModelConfig +from .convert import iter_source_weights, source_engram_tables +from .model import Model +from .processing import Processor +from .quantization import QuantizedProjection +from .storage import DiskEngramEmbedding, EngramPrefetch, TensorFile, decode_array + +logger = logging.getLogger(__name__) + + +def _load_shard(path): + # The model retains a full Metal copy. Avoid filling the unified file cache + # with a second copy of hundreds of GiB of ordinary checkpoint weights. + with Path(path).open("rb") as reader: + nocache = getattr(fcntl, "F_NOCACHE", None) + if nocache is not None: + fcntl.fcntl(reader.fileno(), nocache, 1) + values = mx.load(reader) + # File-object reads must finish before the descriptor is closed. + mx.eval(values) + # CPU file reads alone do not submit GPU work. Establish Metal residency + # while shards accumulate, before loading another large host-visible buffer. + # Only a bounded slice is reduced; the checkpoint tensors remain unchanged. + value = next((value for value in values.values() if value.size), None) + if value is not None: + mx.eval(mx.sum(value.reshape(-1)[:32].astype(mx.float32))) + mx.synchronize() + return values + + +def set_module(model, path, module): + parent = model + parts = path.split(".") + for part in parts[:-1]: + parent = ( + parent[int(part)] if isinstance(parent, list) else getattr(parent, part) + ) + if isinstance(parent, list): + parent[int(parts[-1])] = module + else: + setattr(parent, parts[-1], module) + + +def load(path, *, engram_ssd_offload=False, preserve_mtp=None): + path = Path(path) + if (path / "conversion.inprogress.json").exists(): + raise ValueError("DeepSeek V4.1 checkpoint conversion is still in progress") + raw = json.loads((path / "config.json").read_text()) + mapping = json.loads((path / "model.safetensors.index.json").read_text())[ + "weight_map" + ] + format_spec = raw.get("omlx_deepseek_v41") + if format_spec is not None and format_spec.get("version") != 1: + raise ValueError("Unsupported DeepSeek V4.1 converted checkpoint version") + source_checkpoint = format_spec is None + if source_checkpoint: + if raw.get("model_type") != "deepseek_v41": + raise ValueError("Expected a DeepSeek V4.1 checkpoint") + format_spec = {"engram_tables": source_engram_tables(mapping)} + config = ModelConfig.from_dict(raw) + if source_checkpoint and preserve_mtp is None: + from ..mlx_lm_mtp import is_mtp_active + + preserve_mtp = is_mtp_active() + if preserve_mtp is not None: + if not source_checkpoint and preserve_mtp != config.preserve_mtp: + raise ValueError("Converted checkpoint MTP layout cannot be overridden") + config.preserve_mtp = bool(preserve_mtp) + model = Model(config) + if config.engram_layer_ids: + logger.info( + "DeepSeek V4.1 Engram mode: %s", + "SSD offload" if engram_ssd_offload else "host RAM", + ) + memory_scope = ExitStack() + try: + if not engram_ssd_offload and config.engram_layer_ids: + # Include packed Engram storage in the normal MLX residency budget + # during loading, before BatchGenerator takes ownership. + memory_scope.enter_context(wired_limit(model)) + engram_keys = set() + for module, spec in format_spec.get("engram_tables", {}).items(): + for key_field, file_field in ( + ("weight_key", "weight_file"), + ("scale_key", "scale_file"), + ("bias_key", "scale_file"), + ): + key = spec.get(key_field) + if key is None: + continue + engram_keys.add(key) + if format_spec.get("engram_in_index") and mapping.get(key) != ( + spec.get(file_field) or spec["weight_file"] + ): + raise ValueError( + f"Missing or misplaced indexed Engram tensor: {key}" + ) + set_module( + model, + module, + DiskEngramEmbedding( + path / spec["weight_file"], + spec["weight_key"], + spec.get("scale_key"), + path / spec["scale_file"] if spec.get("scale_file") else None, + bias_key=spec.get("bias_key"), + bits=spec.get("bits"), + group_size=spec.get("group_size", 32), + ), + ) + if format_spec.get("engram_tables"): + # Keep the GPU submission boundaries in both modes. Resident tables + # are excluded by submit(), so RAM mode schedules no disk reads. + model.language_model._engram_prefetch = EngramPrefetch() + expected_shapes = { + name: value.shape for name, value in tree_flatten(model.parameters()) + } + + def batches(): + if source_checkpoint: + yield from iter_source_weights( + path, raw, mapping, preserve_mtp=config.preserve_mtp + ) + else: + for filename in dict.fromkeys(mapping.values()): + keys = {key for key, file in mapping.items() if file == filename} + normal_keys = keys - engram_keys + if not normal_keys: + continue + if keys.intersection(engram_keys): + # Shared shards must not pull SSD-offloaded tables onto + # the GPU when loading their ordinary projections. + reader = TensorFile(path / filename) + try: + values = { + key: decode_array(*reader.read(key)) + for key in normal_keys + } + finally: + reader.close() + else: + values = _load_shard(path / filename) + for key in values: + if mapping.get(key) != filename: + raise ValueError(f"Unexpected or misplaced weight: {key}") + yield values, { + name: spec + for name, spec in format_spec.get( + "quantized_modules", {} + ).items() + if name + ".weight" in values + } + + seen, replaced, all_quantized = set(), set(), {} + loaded_bytes = 0 + with closing(batches()) as stream: + for number, (values, quantized) in enumerate(stream): + if seen.intersection(values): + raise ValueError("Duplicate V4.1 target tensors") + all_quantized.update(quantized) + for name, spec in quantized.items(): + if name + ".weight" in values: + if name + ".scales" not in values: + raise ValueError( + f"Quantized projection must be stored in one shard: {name}" + ) + logical = expected_shapes[name + ".weight"] + packed = (*logical[:-1], logical[-1] * spec["bits"] // 32) + scales = ( + *logical[:-1], + logical[-1] // spec.get("group_size", 32), + ) + if ( + values[name + ".weight"].shape != packed + or values[name + ".scales"].shape != scales + ): + raise ValueError(f"Invalid packed projection shape: {name}") + biases = values.get(name + ".biases") + if spec["mode"] == "affine" and ( + biases is None or biases.shape != scales + ): + raise ValueError( + f"Missing or invalid affine biases: {name}" + ) + if spec["mode"] != "affine" and biases is not None: + raise ValueError(f"Unexpected MXFP biases: {name}") + set_module( + model, + name, + QuantizedProjection( + values[name + ".weight"], + values[name + ".scales"], + biases=biases, + **spec, + ), + ) + replaced.add(name) + for key, value in values.items(): + module_name = key.rsplit(".", 1)[0] + if module_name not in quantized and ( + key not in expected_shapes + or value.shape != expected_shapes[key] + ): + raise ValueError(f"Unexpected target tensor shape: {key}") + model.load_weights(list(values.items()), strict=False) + mx.eval(values) + seen.update(values) + loaded_bytes += sum(value.nbytes for value in values.values()) + if number % 25 == 0: + logger.info( + "DeepSeek V4.1 loaded %d tensor groups (%.1f GiB tensors, %.1f GiB active, %.1f GiB cached)", + number + 1, + loaded_bytes / 1024**3, + mx.get_active_memory() / 1024**3, + mx.get_cache_memory() / 1024**3, + ) + expected = {name for name, _ in tree_flatten(model.parameters())} + if ( + seen != expected + or replaced != set(all_quantized) + or ( + not source_checkpoint + and ( + seen != set(mapping) - engram_keys + or replaced != set(format_spec.get("quantized_modules", {})) + ) + ) + ): + raise ValueError( + f"Incomplete V4.1 checkpoint; missing={sorted(expected-seen)[:8]}, extra={sorted(seen-expected)[:8]}" + ) + tokenizer = PreTrainedTokenizerFast.from_pretrained(path) + from .tool_parser import parse_tool_call, tool_call_end, tool_call_start + + tokenizer.has_tool_calling = True + tokenizer.tool_call_start = tool_call_start + tokenizer.tool_call_end = tool_call_end + tokenizer.tool_parser = parse_tool_call + processor = Processor(tokenizer, model.config) + if model.config.engram_layer_ids: + model.language_model.set_tokenizer(tokenizer) + # Load the backbone before reserving RAM for large Engram tables. + if not engram_ssd_offload: + for layer in model.language_model.layers: + if "engram" in layer and isinstance( + layer.engram.embed, DiskEngramEmbedding + ): + layer.engram.embed.make_resident() + mx.eval(model.parameters()) + model.eval() + return model, processor + except BaseException: + model.close() + raise + finally: + memory_scope.close() diff --git a/omlx/patches/deepseek_v41/model.py b/omlx/patches/deepseek_v41/model.py new file mode 100644 index 0000000000..ed588e05c5 --- /dev/null +++ b/omlx/patches/deepseek_v41/model.py @@ -0,0 +1,96 @@ +# SPDX-License-Identifier: MIT +"""V4.1 text/vision model exposing the mlx-vlm embedding adapter contract.""" + +import mlx.core as mx +import mlx.nn as nn +from mlx_vlm.models.base import InputEmbeddingsFeatures + +from .config import ModelConfig +from .language import LanguageModel +from .vision import Aligner, ViT + + +class Model(nn.Module): + def __init__(self, config: ModelConfig): + super().__init__() + self.config = config + self.model_type = config.model_type + self.language_model = LanguageModel(config) + if config.vision_enabled: + self.vision = ViT(config) + self.aligner = Aligner(config) + self.image_start = mx.zeros((config.dim,)) + self.image_newline = mx.zeros((config.dim,)) + self.image_end = mx.zeros((config.dim,)) + + def get_input_embeddings(self, input_ids, pixel_values=None, **kwargs): + h = self.language_model.embed(input_ids) + if pixel_values is None: + if bool(mx.any(input_ids == self.config.image_token_id).item()): + raise ValueError("Missing pixels for image tokens") + return InputEmbeddingsFeatures(inputs_embeds=h) + if not self.config.vision_enabled: + raise ValueError("No vision encoder in this configuration") + if input_ids.shape[0] != 1: + raise ValueError("Prepare image embeddings per request") + grids, spans, types = ( + kwargs[k] for k in ("image_grids", "image_spans", "image_types") + ) + if not (len(grids) == len(spans) == len(types)): + raise ValueError("Image metadata counts differ") + offset = 0 + for (height, width), (start, length), kinds in zip(grids, spans, types): + count = height * width + features = self.aligner( + self.vision(pixel_values[offset : offset + count], height, width), + height, + width, + ) + offset += count + if kinds.count(1) != len(features) or length != len(kinds): + raise ValueError("Image layout does not match aligned features") + values, index = [], 0 + delimiters = {0: self.image_start, 2: self.image_newline, 3: self.image_end} + for kind in kinds: + if kind == 1: + values.append(features[index]) + index += 1 + else: + values.append(delimiters[kind]) + if not bool( + mx.all( + input_ids[0, start : start + length] == self.config.image_token_id + ).item() + ): + raise ValueError("Image span does not cover image token ids") + h[:, start : start + length] = mx.stack(values).astype(h.dtype) + if offset != pixel_values.shape[0]: + raise ValueError("Unused image patches") + return InputEmbeddingsFeatures(inputs_embeds=h) + + def __call__(self, input_ids, pixel_values=None, cache=None, **kwargs): + embeddings = self.get_input_embeddings(input_ids, pixel_values, **kwargs) + return self.language_model( + input_ids, + cache=cache, + inputs_embeds=( + embeddings.inputs_embeds if pixel_values is not None else None + ), + **{ + k: kwargs[k] + for k in ("return_hidden", "return_dspark_hidden", "n_confirmed") + if k in kwargs + }, + ) + + def close(self): + prefetch = getattr(self.language_model, "_engram_prefetch", None) + try: + if prefetch is not None: + prefetch.close() + finally: + for layer in self.language_model.layers: + if "engram" in layer: + close = getattr(layer.engram.embed, "close", None) + if close is not None: + close() diff --git a/omlx/patches/deepseek_v41/mtp.py b/omlx/patches/deepseek_v41/mtp.py new file mode 100644 index 0000000000..bfa63bae4e --- /dev/null +++ b/omlx/patches/deepseek_v41/mtp.py @@ -0,0 +1,165 @@ +# SPDX-License-Identifier: MIT +"""DSpark integration with oMLX's shared speculative acceptance loop.""" + +import mlx.core as mx + + +class AcceptanceDepthController: + """Choose verification shapes from token acceptance, never wall-clock time. + + V4.1's quantized backbone can round differently at different row counts. + Timing-based scheduling would therefore let system load change greedy text. + A rejection retains one lookahead beyond the accepted prefix; fully accepted + blocks grow by one until the configured depth is reached. + """ + + def __init__(self, depth): + self.max_depth = max(1, int(depth)) + self.cur = self.max_depth + self._warmup = False + self.exit_streak = 0 + self.t = {} + + def observe(self, used, accepted, cycle_ms, time_sample=True): + accepted = max(0, min(int(accepted), int(used))) + self.cur = min(self.max_depth, accepted + 1) + + def should_exit(self): + # Timing-based handoff would also change the subsequent numeric path. + return False + + +class DSparkMixin: + @property + def args(self): + return self._config + + def configure_mtp(self, enabled, depth=5): + if enabled and not self._config.preserve_mtp: + raise ValueError("DSpark decoding requires preserved MTP weights") + self._omlx_mtp_decode_enabled = bool(enabled) + self._omlx_dspark_decode_enabled = bool(enabled) + self._omlx_mtp_chain = True + self._omlx_mtp_head_clone = False + self._omlx_mtp_rowwise_unsupported = True + self._omlx_mtp_depth = max(1, min(depth, self._config.dspark_block_size)) + + def make_mtp_depth_controller(self, depth): + return AcceptanceDepthController(depth) + + def make_mtp_cache(self): + return self.make_dspark_cache() + + def dspark_append_context(self, main_hidden, cache, *, start_offset=None): + first = self.mtp[0] + projected = first.main_norm(first.main_proj(main_hidden)) + for stage, item in zip(self.mtp, cache): + stage.attn.append_context(projected, item, start_offset=start_offset) + + def dspark_forward(self, main_hidden, anchor_ids, cache=None, *, draft_length=None): + from .dspark import proposal_forward + + cache = self.make_mtp_cache() if cache is None else cache + self.dspark_append_context(main_hidden, cache) + return proposal_forward(self, anchor_ids, cache, draft_length) + + def dspark_markov(self, token_ids): + return self.mtp[-1].markov_head(token_ids) + + def mtp_forward( + self, hidden, input_ids, cache=None, return_hidden=False, logits_keep=0 + ): + logits, states = self.dspark_forward(hidden, input_ids, cache) + if logits_keep: + logits, states = logits[:, -logits_keep:], states[:, -logits_keep:] + return (logits, states) if return_hidden else logits + + def mtp_take_primed(self, cache, main_token): + from ..mlx_lm_mtp.deepseek_v4_dspark import take_primed + + return take_primed(self, cache, main_token) + + def mtp_partial_rollback(self, cache, accepted, num_drafts): + if not 0 <= accepted <= num_drafts: + return False + stash = getattr(cache[0], "_mtp_draft_stash", None) + if stash is None: + return accepted == num_drafts + inputs, snapshots, before, verify_states = stash + if inputs.shape[1] != num_drafts + 1: + return False + if any(item.size() != before + inputs.shape[1] for item in cache): + return False + cache[0]._mtp_draft_stash = None + if accepted == num_drafts: + return True + # Commit the already-computed causal prefix, including projections that + # became an incomplete compression group after rejecting later tokens. + count = accepted + 1 + end = before + count + history = None + if self._hasher is not None: + _, history = self._hasher(inputs[:, :count], snapshots[0][0][6]) + for i, (item, snapshot, state) in enumerate( + zip(cache, snapshots, verify_states) + ): + _, padding, lengths = snapshot + window_end = min(before, self._config.window_size) + count + item[1] = state["window"][ + :, max(0, window_end - self._config.window_size) : window_end + ] + ratio = item.compress_ratio + if ratio: + item[2] = item[2][:, : end // ratio] + item[3] = item[3][:, : end // ratio] + if ratio > 1: + kv, gate = state["compressor"] + projected_end = before % ratio + count + cutoff = projected_end // ratio * ratio + item[4] = kv[:, cutoff:projected_end] + item[5] = gate[:, cutoff:projected_end] + item[0] = mx.array([end], mx.int32) + if i == 0 and history is not None: + item[6] = mx.array(history, mx.int64) + item.left_padding, item.lengths = padding, lengths + item.advance(count) + mx.eval([item.state for item in cache]) + return True + + def __call__( + self, input_ids, cache=None, inputs_embeds=None, token_types=None, **kwargs + ): + from ..mlx_lm_mtp.deepseek_v4_dspark import capture_prompt + + cache = self.make_cache() if cache is None else cache + return_hidden = bool(kwargs.pop("return_hidden", False)) + target_verify = kwargs.pop("target_verify", False) + n_confirmed = kwargs.pop("n_confirmed", 0) + verify = bool(target_verify or n_confirmed) + active = getattr(self, "_omlx_dspark_decode_enabled", False) + capture_dspark = kwargs.pop("return_dspark_hidden", False) + capture = return_hidden or bool(capture_dspark) + prime = active and not capture and not verify and input_ids.shape[0] == 1 + verify_states = None + if verify: + if input_ids.shape[0] != 1 or inputs_embeds is not None: + raise ValueError("DSpark verification requires one text decode row") + before = cache[0].size() + snapshots = [(list(c.cache), c.left_padding, c.lengths) for c in cache] + verify_states = [{} for _ in cache] + result = self._forward( + input_ids, + cache=cache, + inputs_embeds=inputs_embeds, + token_types=token_types, + return_dspark_hidden=capture or prime, + mtp_verify_states=verify_states, + **kwargs, + ) + if verify: + cache[0]._mtp_draft_stash = (input_ids, snapshots, before, verify_states) + if prime: + logits, hidden = result + capture_prompt(self, input_ids, hidden, cache) + return logits + return result diff --git a/omlx/patches/deepseek_v41/oq.py b/omlx/patches/deepseek_v41/oq.py new file mode 100644 index 0000000000..3db7780ed6 --- /dev/null +++ b/omlx/patches/deepseek_v41/oq.py @@ -0,0 +1,667 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Budget-checked oQ3/oQ4 export of the mixed-precision V4.1 release. + +Engram follows Qwen4-Exp's uniform affine group-32 embedding policy and is +excluded from the remaining weights' bit budget. If all other source weights +fit their independent budget at original precision, that allocation dominates +every lossy alternative: neither sensitivity ranking nor an imatrix can improve +it. oQ3 measures layer sensitivity and projection input statistics, then uses +the official mixed-bit allocator and weighted affine arithmetic for oQ3e. +""" + +import json +import logging +import math +import shutil +import struct +from contextlib import closing +from pathlib import Path + +import mlx.core as mx +import numpy as np + +from .convert import iter_source_weights, source_engram_tables, strip_draft_config +from .sharding import ShardWriter +from .storage import TensorFile, decode_array + +logger = logging.getLogger(__name__) + + +def requantize_projection( + values, name, source_spec, *, bits, importance=None, progress=None +): + """Convert one projection with bounded floating workspace and oQe arithmetic.""" + from ...oq import _quantize_chunked + + if bits not in (2, 3, 4, 6, 8): + raise ValueError("V4.1 affine projections require 2, 3, 4, 6 or 8 bits") + weight = values[name + ".weight"] + if weight.ndim not in (2, 3): + raise ValueError("Expected a dense or stacked expert projection") + width = weight.shape[-1] + if source_spec is not None: + width = width * 32 // source_spec["bits"] + if width % 64: + raise ValueError("V4.1 affine projection width must divide into 64 channels") + # Slice before dequantization. In particular, do not expand a complete + # stacked expert tensor to BF16 while its packed source is still live. + rows_per_chunk = max(1, (128 * 1024**2) // (2 * width)) + experts = weight.shape[0] if weight.ndim == 3 else 1 + packed_experts, scale_experts, bias_experts = [], [], [] + for expert in range(experts): + current = weight[expert] if weight.ndim == 3 else weight + packed_rows, scale_rows, bias_rows = [], [], [] + imp = importance + if importance is not None and importance.ndim == 2: + imp = importance[expert] + for start in range(0, current.shape[0], rows_per_chunk): + stop = min(start + rows_per_chunk, current.shape[0]) + chunk = current[start:stop] + if source_spec is not None: + + def part(suffix, expert=expert, start=start, stop=stop): + value = values.get(name + suffix) + if value is None: + return None + value = value[expert] if weight.ndim == 3 else value + return value[start:stop] + + chunk = mx.dequantize( + chunk, + part(".scales"), + part(".biases"), + group_size=source_spec.get("group_size", 32), + bits=source_spec["bits"], + mode=source_spec["mode"], + ) + q, s, b = _quantize_chunked( + chunk.astype(mx.bfloat16), 64, bits, "affine", importance=imp + ) + mx.eval(q, s, b) + packed_rows.append(q) + scale_rows.append(s) + bias_rows.append(b) + if progress is not None: + progress(expert * current.shape[0] + stop, experts * current.shape[0]) + packed_experts.append(mx.concatenate(packed_rows)) + scale_experts.append(mx.concatenate(scale_rows)) + bias_experts.append(mx.concatenate(bias_rows)) + join = mx.stack if weight.ndim == 3 else lambda arrays: arrays[0] + result = { + name + ".weight": join(packed_experts), + name + ".scales": join(scale_experts), + name + ".biases": join(bias_experts), + } + mx.eval(result) + spec = { + "bits": bits, + "group_size": 64, + "mode": "affine", + "quantize_input": ( + source_spec.get("quantize_input", True) if source_spec else False + ), + } + return result, spec + + +def source_budget( + source, config, mapping, *, preserve_mtp, text_only=False, engram_bits=4 +): + """Count actual exported bytes, including scales, norms and draft heads.""" + headers = {} + for filename in dict.fromkeys(mapping.values()): + with (source / filename).open("rb") as f: + size = struct.unpack(" target: + raise ValueError( + "Original-precision allocation exceeds the requested oQ4 budget; " + "V4.1 calibrated affine allocation is currently supported for oQ3" + ) + allocation, imatrix, preparation = {}, None, {} + if oq_level == 3: + allocation, imatrix, preparation = prepare_affine_conversion( + source, + destination, + config, + mapping, + budget, + target=target, + cap=cap, + preserve_mtp=preserve_mtp, + sensitivity_model_path=sensitivity_model_path, + sensitivity_map_override=sensitivity_map_override, + imatrix_cache_path=imatrix_cache_path, + imatrix_reuse_cache=imatrix_reuse_cache, + imatrix_strict=imatrix_strict, + imatrix_num_samples=imatrix_num_samples, + imatrix_seq_length=imatrix_seq_length, + progress_callback=progress_callback, + ) + budget["remaining_weights"].update( + {key: preparation[key] for key in ("tensor_bytes", "effective_bpw")} + ) + budget["tensor_bytes"] = ( + budget["remaining_weights"]["tensor_bytes"] + + budget["engram"]["tensor_bytes"] + ) + destination.parent.mkdir(parents=True, exist_ok=True) + if shutil.disk_usage(destination.parent).free < budget["tensor_bytes"] + 1024**3: + raise OSError("Insufficient space for V4.1 export plus 1 GiB headroom") + destination.mkdir() + report = { + **budget, + "oq_level": oq_level, + "enhanced_requested": enhanced, + "target_bpw": target, + "hard_cap_bpw": cap, + "allocation": "original_precision_fits_independent_remaining_budget", + "budget_scope": "remaining_weights_excluding_engram", + "calibration": "not_needed_no_linear_requantization", + "imatrix_applied_modules": [], + "storage_layout": "unified_safetensors_index", + } + if allocation: + report.update( + allocation="measured_layer_sensitivity_affine", calibration=preparation + ) + (destination / "conversion.inprogress.json").write_text( + json.dumps(report, indent=2) + "\n" + ) + logger.info( + "V4.1 planned non-Engram weights: %.4f bpw; total %.2f GiB", + budget["remaining_weights"]["effective_bpw"], + budget["tensor_bytes"] / 1024**3, + ) + writer = ShardWriter(destination) + tables = source_engram_tables(mapping) + exported_tables = {} + engram_start, engram_span = (20, 20) if oq_level == 3 else (0, 30) + projection_start = engram_start + engram_span + for i, (name, table) in enumerate(tables.items()): + if _get_predicate_bits(name + ".weight", config, oq_level, 64) != ( + oq_level, + 32, + "affine", + ): + raise ValueError("V4.1 Engram policy differs from Qwen4-Exp") + filename = f".model-engram-{i:02d}.safetensors" + last = [-1] + + def progress(done, total, i=i, last=last): + percent = int(100 * done / total) + if percent != last[0]: + last[0] = percent + logger.info("Engram %d/%d: %d%%", i + 1, len(tables), percent) + _emit_progress( + progress_callback, + "quantizing", + engram_start + + engram_span * (i + done / total) / max(len(tables), 1), + f"Engram {i + 1}/{len(tables)}: {percent}%", + ) + + spec = quantize_engram( + source, + destination / filename, + table, + progress=progress, + module_name=name, + bits=oq_level, + ) + writer.add_file( + filename, [spec[key] for key in ("weight_key", "scale_key", "bias_key")] + ) + exported_tables[name] = spec + quantized = {} + written_bytes = 0 + with closing( + iter_source_weights(source, config, mapping, preserve_mtp=preserve_mtp) + ) as batches: + for i, (values, specs) in enumerate(batches): + if text_only: + values = { + k: v + for k, v in values.items() + if not k.startswith(("vision.", "aligner.", "image_")) + } + specs = {k: v for k, v in specs.items() if k + ".weight" in values} + if not values: + continue + for key in list(values): + if not key.endswith(".weight"): + continue + name = key.removesuffix(".weight") + if name not in allocation: + continue + importance = None + if enhanced: + shape = tuple(values[key].shape) + if name in specs: + shape = (*shape[:-1], shape[-1] * 32 // specs[name]["bits"]) + importance = _lookup_imatrix_importance( + imatrix, + key, + shape, + config=config, + strict=True, + report=None, + ) + converted, spec = requantize_projection( + values, + name, + specs.get(name), + bits=allocation[name]["bits"], + importance=importance, + progress=lambda done, total, name=name, written=written_bytes: _emit_progress( + progress_callback, + "quantizing", + projection_start + + (99 - projection_start) + * written + / max(budget["remaining_weights"]["tensor_bytes"], 1), + f"Quantizing {name}: {done}/{total} rows", + ), + ) + values.update(converted) + specs[name] = spec + if enhanced: + report["imatrix_applied_modules"].append(name) + writer.add(values) + written_bytes += sum(value.nbytes for value in values.values()) + quantized.update(specs) + if i % 25 == 0: + logger.info( + "Exported %d projection groups (including DSpark=%s)", + i + 1, + preserve_mtp, + ) + _emit_progress( + progress_callback, + "quantizing", + projection_start + + (99 - projection_start) + * written_bytes + / max(budget["remaining_weights"]["tensor_bytes"], 1), + f"Exported {i + 1} projection groups", + ) + output_map = writer.finish() + report["shard_count"] = len(set(output_map.values())) + for spec in exported_tables.values(): + spec["weight_file"] = output_map[spec["weight_key"]] + spec["scale_file"] = output_map[spec["scale_key"]] + if written_bytes != budget["remaining_weights"]["tensor_bytes"]: + raise ValueError("Exported non-Engram bytes differ from the independent budget") + config.pop("quantization_config", None) + if not preserve_mtp: + strip_draft_config(config) + if text_only: + config.pop("vision_config", None) + config["omlx_deepseek_v41"] = { + "version": 1, + "quantized_modules": quantized, + "engram_tables": exported_tables, + "engram_in_index": True, + "preserve_mtp": preserve_mtp, + "excluded_draft_tensors": ( + 0 if preserve_mtp else sum(k.startswith("mtp.") for k in mapping) + ), + "quantization_report": report, + } + for name in ( + "tokenizer.json", + "tokenizer_config.json", + "generation_config.json", + "LICENSE", + ): + if (source / name).is_file(): + shutil.copyfile(source / name, destination / name) + (destination / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": output_map}, indent=2) + "\n" + ) + (destination / "config.json").write_text(json.dumps(config, indent=2) + "\n") + (destination / "conversion.inprogress.json").write_text( + json.dumps(report, indent=2) + "\n" + ) + (destination / "conversion.inprogress.json").rename( + destination / "quantization_report.json" + ) + _emit_progress(progress_callback, "complete", 100.0, "V4.1 export complete") + + +def prepare_affine_conversion( + source, + destination, + config, + mapping, + budget, + *, + target, + cap, + preserve_mtp, + sensitivity_model_path, + sensitivity_map_override, + imatrix_cache_path, + imatrix_reuse_cache, + imatrix_strict, + imatrix_num_samples, + imatrix_seq_length, + progress_callback, +): + from ...oq import ( + _OQE_CALIB_DATASET, + _emit_progress, + _load_or_collect_imatrix, + _normalize_sensitivity_map_override, + _source_imatrix_signature, + ) + from .loading import load + from .oq_inventory import build_affine_plan, projection_inventory + from .sensitivity import measure_sensitivity + + if imatrix_num_samples < 1 or imatrix_seq_length < 1: + raise ValueError( + "V4.1 calibration sample count and sequence length must be positive" + ) + calibration_source = ( + Path(sensitivity_model_path) if sensitivity_model_path else source + ) + signed_config = dict(config) + if calibration_source != source: + proxy_config = json.loads((calibration_source / "config.json").read_text()) + if proxy_config.get("model_type") != "deepseek_v41" or ( + proxy_config.get("text_config") != config.get("text_config") + ): + raise ValueError( + "V4.1 calibration proxy must have matching text architecture" + ) + signed_config["_oq_calibration_proxy"] = _source_imatrix_signature( + calibration_source, + proxy_config, + num_samples=imatrix_num_samples, + seq_length=imatrix_seq_length, + calib_dataset=_OQE_CALIB_DATASET, + ) + if not imatrix_cache_path: + imatrix_cache_path = str( + destination.parent + / ".oqe_imatrix" + / f"{source.name}-oQe-s{imatrix_num_samples}-l{imatrix_seq_length}.npz" + ) + imatrix = _load_or_collect_imatrix( + str(source), + signed_config, + cache_path=imatrix_cache_path, + reuse_cache=imatrix_reuse_cache, + num_samples=imatrix_num_samples, + seq_length=imatrix_seq_length, + strict=imatrix_strict, + trust_remote_code=False, + progress_callback=progress_callback, + progress_start=1, + progress_end=10, + load_path_factory=lambda: str(calibration_source), + ) + coverage = imatrix.metadata.get("expert_coverage", {}) + sensitivity_config = { + **config, + "num_hidden_layers": config.get("text_config", config).get("num_hidden_layers") + or config.get("text_config", config).get("n_layers", 0), + } + sensitivity = _normalize_sensitivity_map_override( + sensitivity_config, sensitivity_map_override + ) + if sensitivity is None: + _emit_progress( + progress_callback, "sensitivity", 10, "Measuring V4.1 layer distortion" + ) + model, processor = load(calibration_source, engram_ssd_offload=True) + try: + + def progress(phase, done, total): + start, span = (10, 3) if phase == "capture" else (13, 7) + _emit_progress( + progress_callback, + "sensitivity", + start + span * done / total, + f"V4.1 {phase} {done}/{total}", + ) + + sensitivity = measure_sensitivity( + model, processor.tokenizer, bits=3, progress=progress + ) + finally: + model.close() + del model, processor + mx.synchronize() + mx.clear_cache() + inventory = projection_inventory(source, config, mapping, preserve_mtp=preserve_mtp) + allocation, report = build_affine_plan( + inventory, + budget, + config, + imatrix, + sensitivity, + target=target, + cap=cap, + ) + report.update( + imatrix_cache_path=imatrix.path, + imatrix_cache_reused=imatrix.reused, + expert_coverage=coverage, + sensitivity=sensitivity, + calibration_model=str(calibration_source), + uncalibrated_policy="preserve_source_precision", + ) + return allocation, imatrix, report diff --git a/omlx/patches/deepseek_v41/oq_inventory.py b/omlx/patches/deepseek_v41/oq_inventory.py new file mode 100644 index 0000000000..d81bd585a0 --- /dev/null +++ b/omlx/patches/deepseek_v41/oq_inventory.py @@ -0,0 +1,148 @@ +# SPDX-License-Identifier: MIT +"""Read logical projection sizes without materializing source weights.""" + +import json +import math +import re +import struct +from pathlib import Path + +from .convert import mapped + + +def projection_inventory(source, config, mapping, *, preserve_mtp=False): + headers = {} + source = Path(source) + for filename in dict.fromkeys(mapping.values()): + with (source / filename).open("rb") as handle: + length = struct.unpack(" cap: + raise ValueError( + f"V4.1 calibrated allocation requires {effective_bpw:.4f} bpw, above {cap:.4f} cap" + ) + return specs, dict( + tensor_bytes=output_bytes, + effective_bpw=effective_bpw, + fixed_source_bytes=fixed_bytes, + preserved_modules=preserved, + unobserved_experts=unobserved, + unobserved_expert_policy="uniform_importance_at_allocated_bits", + ) diff --git a/omlx/patches/deepseek_v41/output_parser.py b/omlx/patches/deepseek_v41/output_parser.py new file mode 100644 index 0000000000..3f64d83bad --- /dev/null +++ b/omlx/patches/deepseek_v41/output_parser.py @@ -0,0 +1,105 @@ +# SPDX-License-Identifier: MIT +"""Request-local V4.1 DSML framing with opaque reasoning content.""" + +from ...adapter.output_parser import ( + OutputParserFinalizeResult, + OutputParserTokenResult, + _decode_output_token, + create_streaming_detokenizer, +) +from .tool_parser import parse_tool_call, tool_call_end, tool_call_start + + +class DeepSeekV41OutputParserSession: + def __init__(self, tokenizer, model_path=None): + self._tokenizer = tokenizer + self._detokenizer = create_streaming_detokenizer(tokenizer, model_path) + if self._detokenizer is not None: + self._detokenizer.reset() + self._buffer = "" + self._state = "content" + self._stopped = False + self._calls = [] + + def notify_prefilled_thought(self): + self._state = "reasoning" + + def _consume(self, final=False): + output = [] + while self._buffer: + if self._state == "tool": + end = self._buffer.find(tool_call_end) + if end < 0: + if final: + output.append(self._buffer) + self._buffer = "" + break + cutoff = end + len(tool_call_end) + block = self._buffer[:cutoff] + try: + calls = parse_tool_call(block[len(tool_call_start) : end]) + except (ValueError, AssertionError): + # An invalid envelope cannot terminate the assistant turn. + output.append(block) + self._buffer = self._buffer[cutoff:] + self._state = "content" + continue + self._calls = calls + self._stopped = True + self._buffer = "" + break + markers = ( + ("",) + if self._state == "reasoning" + else ("", tool_call_start) + ) + positions = [(self._buffer.find(m), m) for m in markers] + positions = [(pos, marker) for pos, marker in positions if pos >= 0] + if positions: + pos, marker = min(positions) + output.append(self._buffer[:pos]) + if marker == tool_call_start: + self._buffer = self._buffer[pos:] + self._state = "tool" + else: + output.append(marker) + self._buffer = self._buffer[pos + len(marker) :] + self._state = "content" if marker == "" else "reasoning" + continue + held = 0 + if not final: + for marker in markers: + for size in range(1, min(len(marker), len(self._buffer) + 1)): + if self._buffer.endswith(marker[:size]): + held = max(held, size) + count = len(self._buffer) - held + output.append(self._buffer[:count]) + self._buffer = self._buffer[count:] + break + return "".join(output) + + def process_token(self, token_id): + if self._stopped: + return OutputParserTokenResult(is_stop=True, record_token=False) + self._buffer += _decode_output_token( + self._tokenizer, self._detokenizer, token_id + ) + text = self._consume() + return OutputParserTokenResult( + stream_text=text, + visible_text=text, + is_stop=self._stopped, + record_token=True, + ) + + def finalize(self): + if self._detokenizer is not None and not self._stopped: + self._detokenizer.finalize() + self._buffer += self._detokenizer.last_segment + text = self._consume(final=True) + return OutputParserFinalizeResult( + stream_text=text, + visible_text=text, + tool_calls=self._calls, + finish_reason="tool_calls" if self._calls else None, + ) diff --git a/omlx/patches/deepseek_v41/packed_attention.py b/omlx/patches/deepseek_v41/packed_attention.py new file mode 100644 index 0000000000..f0dcee3e8d --- /dev/null +++ b/omlx/patches/deepseek_v41/packed_attention.py @@ -0,0 +1,502 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Packed attention with 64-key online softmax and BF16 PV probabilities.""" + +from functools import cache + +import mlx.core as mx + +_READ = r""" +#include +using namespace metal; +inline float rounded_fp4(uchar code) { + const float table[8] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f}; + return (code & 8 ? -1.0f : 1.0f) * table[code & 7]; +} +inline float rounded_fp8(uchar code) { + const uint a = code & 127, exponent = a >> 3, mantissa = a & 7; + const float value = exponent == 0 ? float(mantissa) * 0x1p-9f + : as_type(((exponent + 120u) << 23) | (mantissa << 20)); + return code & 128 ? -value : value; +} +template +inline float read_kv(W window, P pooled, + int row, int d, int dim, bool compressed, float pooled_scale, int window_exp, bool reuse) { + if (compressed) { + const size_t base = size_t(row) * (dim / 2 + dim / 16); + const uchar code = (pooled[base + d / 2] >> ((d % 2) * 4)) & 15; + return rounded_fp4(code) * (reuse ? pooled_scale : rounded_fp8(pooled[base + dim / 2 + d / 16])); + } + const size_t base = size_t(row) * (dim + dim / 32); + return ldexp(rounded_fp8(window[base + d]), reuse ? window_exp : int(window[base + dim + d / 32]) - 127); +} +""" + +_FUSED = r""" + const uint lane = thread_index_in_simdgroup, block = simdgroup_index_in_threadgroup; + const uint head = threadgroup_position_in_grid.x, query = threadgroup_position_in_grid.y; + const int H = meta[0], W = meta[1], C = meta[2], NW = meta[3], NC = meta[4]; + threadgroup float scores[NB * CHUNK], maxima[NB], probabilities[NB * CHUNK]; + float qv[D / 32]; + for (int v = 0; v < D / 32; ++v) qv[v] = float(q[(query * H + head) * D + lane * (D / 32) + v]); + float maximum = -1e30f; + for (int j = 0; j < CHUNK; ++j) { + const int slot = int(block) * CHUNK + j; + const bool compressed = slot >= W; + const int row = slot >= W + C ? -1 : compressed ? ci[query * C + slot - W] : wi[query * W + slot]; + float score = -INFINITY; + if (row >= 0 && row < (compressed ? NC : NW)) { + constexpr bool REUSE = D == 32 || D == 64 || D == 128 || D == 256 || D == 512; + const int first = lane * (D / 32); + const size_t row_base = size_t(row) * (compressed ? (D / 2 + D / 16) : (D + D / 32)); + const float pooled_scale = REUSE && compressed ? rounded_fp8(pooled[row_base + D / 2 + first / 16]) : 0.0f; + const int window_exp = REUSE && !compressed ? int(window[row_base + D + first / 32]) - 127 : 0; + float dot = 0.0f; + for (int v = 0; v < D / 32; ++v) dot = fma(qv[v], read_kv(window, pooled, row, first + v, D, compressed, pooled_scale, window_exp, REUSE), dot); + score = simd_sum(dot) * scalep[0]; + } + maximum = max(maximum, score); + if (lane == 0) scores[block * CHUNK + j] = score; + } + if (lane == 0) maxima[block] = maximum; + threadgroup_barrier(mem_flags::mem_threadgroup); + maximum = -1e30f; + for (uint b = lane; b <= min(block | uint(64 / CHUNK - 1), uint(NB - 1)); b += 32) maximum = max(maximum, maxima[b]); + maximum = simd_max(maximum); + float denominator = 0.0f; + for (uint j = lane; j < CHUNK; j += 32) { + const float p = exp(scores[block * CHUNK + j] - maximum); + denominator += p; + probabilities[block * CHUNK + j] = float(bfloat16_t(p)); + } + denominator = simd_sum(denominator); + simdgroup_barrier(mem_flags::mem_threadgroup); + float acc[D / 32]; + for (int v = 0; v < D / 32; ++v) acc[v] = 0.0f; + for (int j = 0; j < CHUNK; ++j) { + const int slot = int(block) * CHUNK + j; + const bool compressed = slot >= W; + const int row = slot >= W + C ? -1 : compressed ? ci[query * C + slot - W] : wi[query * W + slot]; + if (row < 0 || row >= (compressed ? NC : NW)) continue; + constexpr bool REUSE = D == 32 || D == 64 || D == 128 || D == 256 || D == 512; + const int first = lane * (D / 32); + const size_t row_base = size_t(row) * (compressed ? (D / 2 + D / 16) : (D + D / 32)); + const float pooled_scale = REUSE && compressed ? rounded_fp8(pooled[row_base + D / 2 + first / 16]) : 0.0f; + const int window_exp = REUSE && !compressed ? int(window[row_base + D + first / 32]) - 127 : 0; + const float p = probabilities[block * CHUNK + j]; + for (int v = 0; v < D / 32; ++v) acc[v] = fma(p, read_kv(window, pooled, row, first + v, D, compressed, pooled_scale, window_exp, REUSE), acc[v]); + } + const size_t out_base = ((size_t(query) * H + head) * NB + block) * (D + 2); + for (int v = 0; v < D / 32; ++v) partial[out_base + lane * (D / 32) + v] = acc[v]; + if (lane == 0) { partial[out_base + D] = maximum; partial[out_base + D + 1] = denominator; } +""" + +_MMA_SCORES = r""" + const uint tid = thread_index_in_threadgroup, lane = thread_index_in_simdgroup; + const uint sg = simdgroup_index_in_threadgroup; + const uint split = threadgroup_position_in_grid.z, query = threadgroup_position_in_grid.y; + const uint first_head = threadgroup_position_in_grid.x * 8; + const int H = meta[0], W = meta[1], C = meta[2], NW = meta[3], NC = meta[4], NS = meta[5]; + const uint fm = ((lane >> 2) & 4) + ((lane >> 1) & 3); + const uint fn = (((lane >> 2) & 2) << 1) + ((lane & 1) << 1); + threadgroup float tile[8 * D], dots[4 * 64], maxima_local[8]; + threadgroup bool valid[8]; + if (tid < 8) maxima_local[tid] = -1e30f; + for (int begin = split * 16; begin < int(split + 1) * 16; begin += 8) { + for (uint i = tid; i < 8 * D; i += 128) { + const uint r = i / D, d = i % D, j = begin + r; + const bool compressed = j >= W; + const int row = j >= W + C ? -1 : compressed ? ci[query * C + j - W] : wi[query * W + j]; + const bool ok = row >= 0 && row < (compressed ? NC : NW); + tile[i] = ok ? read_kv(window, pooled, row, d, D, compressed, 0.0f, 0, false) : 0.0f; + if (d == 0) valid[r] = ok; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + simdgroup_matrix score, a, b; + score.thread_elements()[0] = 0.0f; + score.thread_elements()[1] = 0.0f; + for (int k = sg * (D / 4); k < (sg + 1) * (D / 4); k += 8) { + const uint head = first_head + fm; + a.thread_elements()[0] = head < H ? float(q[(query * H + head) * D + k + fn]) : 0.0f; + a.thread_elements()[1] = head < H ? float(q[(query * H + head) * D + k + fn + 1]) : 0.0f; + b.thread_elements()[0] = tile[fn * D + k + fm]; + b.thread_elements()[1] = tile[(fn + 1) * D + k + fm]; + simdgroup_multiply_accumulate(score, a, b, score); + } + dots[sg * 64 + fm * 8 + fn] = score.thread_elements()[0]; + dots[sg * 64 + fm * 8 + fn + 1] = score.thread_elements()[1]; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid < 8 && first_head + tid < H) { + float maximum = maxima_local[tid]; + for (uint r = 0; r < 8; ++r) { + float sum = dots[tid * 8 + r] + dots[64 + tid * 8 + r] + dots[128 + tid * 8 + r] + dots[192 + tid * 8 + r]; + const float value = valid[r] ? sum * scalep[0] : -INFINITY; + maximum = max(maximum, value); + scores[(size_t(query) * H + first_head + tid) * NS * 16 + begin + r] = value; + } + maxima_local[tid] = maximum; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (tid < 8 && first_head + tid < H) + maxima[(size_t(query) * H + first_head + tid) * NS + split] = maxima_local[tid]; +""" + +_MMA_VALUES = r""" + const uint tid = thread_index_in_threadgroup, lane = thread_index_in_simdgroup; + const uint sg = simdgroup_index_in_threadgroup; + const uint block = threadgroup_position_in_grid.z, query = threadgroup_position_in_grid.y; + const uint first_head = threadgroup_position_in_grid.x * 8; + const int H = meta[0], W = meta[1], C = meta[2], NW = meta[3], NC = meta[4], NS = meta[5], NB = meta[6]; + const uint fm = ((lane >> 2) & 4) + ((lane >> 1) & 3); + const uint fn = (((lane >> 2) & 2) << 1) + ((lane & 1) << 1); + threadgroup float tile[8 * D], probability[64], maxima[8], denominator[8]; + threadgroup bool valid[8]; + simdgroup_matrix output[D / 32]; + for (int v = 0; v < D / 32; ++v) { + output[v].thread_elements()[0] = 0.0f; + output[v].thread_elements()[1] = 0.0f; + } + if (tid < 8) { + float maximum = -1e30f; + if (first_head + tid < H) + for (uint b = 0; b <= min(block * 4 + 3, uint(NS - 1)); ++b) + maximum = max(maximum, score_maxima[(size_t(query) * H + first_head + tid) * NS + b]); + maxima[tid] = maximum; + denominator[tid] = 0.0f; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int begin = int(block) * 64; begin < int(block + 1) * 64; begin += 8) { + for (uint i = tid; i < 8 * D; i += 128) { + const uint r = i / D, d = i % D, j = begin + r; + const bool compressed = j >= W; + const int row = j >= W + C ? -1 : compressed ? ci[query * C + j - W] : wi[query * W + j]; + const bool ok = row >= 0 && row < (compressed ? NC : NW); + tile[i] = ok ? read_kv(window, pooled, row, d, D, compressed, 0.0f, 0, false) : 0.0f; + if (d == 0) valid[r] = ok; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid < 8) { + const uint head = first_head + tid; + float total = denominator[tid]; + for (uint r = 0; r < 8; ++r) { + const int slot = begin + r; + const float p = head < H && valid[r] ? exp(scores[((size_t(query) * H + head) * NS * 16) + slot] - maxima[tid]) : 0.0f; + probability[tid * 8 + r] = float(bfloat16_t(p)); + total += p; + } + denominator[tid] = total; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + simdgroup_matrix a, b; + a.thread_elements()[0] = probability[fm * 8 + fn]; + a.thread_elements()[1] = probability[fm * 8 + fn + 1]; + for (int v = 0; v < D / 32; ++v) { + const uint d = sg * (D / 4) + v * 8 + fn; + b.thread_elements()[0] = tile[fm * D + d]; + b.thread_elements()[1] = tile[fm * D + d + 1]; + simdgroup_multiply_accumulate(output[v], a, b, output[v]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + const uint head = first_head + fm; + if (head < H) { + const size_t base = ((size_t(query) * H + head) * NB + block) * (D + 2); + for (int v = 0; v < D / 32; ++v) { + const uint d = sg * (D / 4) + v * 8 + fn; + partial[base + d] = output[v].thread_elements()[0]; + partial[base + d + 1] = output[v].thread_elements()[1]; + } + } + if (tid < 8 && first_head + tid < H) { + const size_t base = ((size_t(query) * H + first_head + tid) * NB + block) * (D + 2); + partial[base + D] = maxima[tid]; + partial[base + D + 1] = denominator[tid]; + } +""" + +_SCORES = r""" + const uint lane = thread_index_in_simdgroup; + const uint head = threadgroup_position_in_grid.x * 4 + simdgroup_index_in_threadgroup; + const uint query = threadgroup_position_in_grid.y, block = threadgroup_position_in_grid.z; + const int H = meta[0], W = meta[1], C = meta[2], NW = meta[3], NC = meta[4], NB = meta[5]; + if (head >= H) return; + float qv[D / 32]; + for (int v = 0; v < D / 32; ++v) + qv[v] = float(q[(query * H + head) * D + lane * (D / 32) + v]); + float maximum = -1e30f; + const size_t base = (size_t(query) * H + head) * NB + block; + for (int j = 0; j < 16; ++j) { + const int slot = int(block) * 16 + j; + const bool compressed = slot >= W; + const int row = slot >= W + C ? -1 : compressed + ? ci[query * C + slot - W] : wi[query * W + slot]; + float score = -INFINITY; + if (row >= 0 && row < (compressed ? NC : NW)) { + + constexpr bool REUSE = D == 32 || D == 64 || D == 128 || D == 256 || D == 512; + const int first = lane * (D / 32); + const size_t row_base = size_t(row) * (compressed ? (D / 2 + D / 16) : (D + D / 32)); + const float pooled_scale = REUSE && compressed ? rounded_fp8(pooled[row_base + D / 2 + first / 16]) : 0.0f; + const int window_exp = REUSE && !compressed ? int(window[row_base + D + first / 32]) - 127 : 0; + float dot = 0.0f; + for (int v = 0; v < D / 32; ++v) { + const int d = lane * (D / 32) + v; + const float value = read_kv(window, pooled, row, d, D, compressed, pooled_scale, window_exp, REUSE); + dot = fma(qv[v], value, dot); + } + score = simd_sum(dot) * scalep[0]; + } + maximum = max(maximum, score); + if (lane == 0) scores[base * 16 + j] = score; + } + if (lane == 0) maxima[base] = maximum; +""" + +_VALUES = r""" + const uint lane = thread_index_in_simdgroup, sg = simdgroup_index_in_threadgroup; + const uint head = threadgroup_position_in_grid.x * 4 + sg; + const uint query = threadgroup_position_in_grid.y, block = threadgroup_position_in_grid.z; + const int H = meta[0], W = meta[1], C = meta[2], NW = meta[3], NC = meta[4], NB = meta[5]; + if (head >= H) return; + const size_t base = (size_t(query) * H + head) * NB; + float maximum = -1e30f; + // Four 16-key subparts share the maximum through their official 64-key tile. + for (uint b = lane; b <= min(block | 3u, uint(NB - 1)); b += 32) maximum = max(maximum, maxima[base + b]); + maximum = simd_max(maximum); + threadgroup float probabilities[4 * 16]; + float denominator = 0.0f; + for (uint j = lane; j < 16; j += 32) { + const float p = exp(scores[(base + block) * 16 + j] - maximum); + denominator += p; + probabilities[sg * 16 + j] = float(bfloat16_t(p)); + } + denominator = simd_sum(denominator); + simdgroup_barrier(mem_flags::mem_threadgroup); + float acc[D / 32]; + for (int v = 0; v < D / 32; ++v) acc[v] = 0.0f; + for (int j = 0; j < 16; ++j) { + const int slot = int(block) * 16 + j; + const bool compressed = slot >= W; + const int row = slot >= W + C ? -1 : compressed + ? ci[query * C + slot - W] : wi[query * W + slot]; + if (row < 0 || row >= (compressed ? NC : NW)) continue; + + constexpr bool REUSE = D == 32 || D == 64 || D == 128 || D == 256 || D == 512; + const int first = lane * (D / 32); + const size_t row_base = size_t(row) * (compressed ? (D / 2 + D / 16) : (D + D / 32)); + const float pooled_scale = REUSE && compressed ? rounded_fp8(pooled[row_base + D / 2 + first / 16]) : 0.0f; + const int window_exp = REUSE && !compressed ? int(window[row_base + D + first / 32]) - 127 : 0; + const float p = probabilities[sg * 16 + j]; + for (int v = 0; v < D / 32; ++v) { + const int d = lane * (D / 32) + v; + acc[v] = fma(p, read_kv(window, pooled, row, d, D, compressed, pooled_scale, window_exp, REUSE), acc[v]); + } + } + const size_t out = (base + block) * (D + 2); + for (int v = 0; v < D / 32; ++v) partial[out + lane * (D / 32) + v] = acc[v]; + if (lane == 0) { + partial[out + D] = maximum; + partial[out + D + 1] = denominator; + } +""" + +_MERGE = r""" + const uint lane = thread_index_in_simdgroup; + const uint part = threadgroup_position_in_grid.x * 4 + simdgroup_index_in_threadgroup; + const uint head = part / (D / 32), d = (part % (D / 32)) * 32 + lane; + const uint query = threadgroup_position_in_grid.y; + const int H = meta[0], NB = meta[1]; + if (head >= H) return; + const size_t base = (size_t(query) * H + head) * NB * (D + 2); + float maximum = -1e30f, denominator = 0.0f, acc = 0.0f; + for (int b = 0; b < NB; ++b) { + const size_t pos = base + b * (D + 2); + const float next_maximum = partial[pos + D]; + const float correction = (b % (64 / CHUNK) == 0) ? exp(maximum - next_maximum) : 1.0f; + denominator = denominator * correction + partial[pos + D + 1]; + acc = acc * correction + partial[pos + d]; + maximum = next_maximum; + } + denominator += exp(float(sink[head]) - maximum); + out[(query * H + head) * D + d] = T(acc / denominator); +""" + + +@cache +def _kernel(stage): + inputs, outputs, source = { + "mma_scores": ( + ["q", "window", "pooled", "wi", "ci", "meta", "scalep"], + ["scores", "maxima"], + _MMA_SCORES, + ), + "mma_values": ( + ["scores", "score_maxima", "window", "pooled", "wi", "ci", "meta"], + ["partial"], + _MMA_VALUES, + ), + "fused": ( + ["q", "window", "pooled", "wi", "ci", "meta", "scalep"], + ["partial"], + _FUSED, + ), + "scores": ( + ["q", "window", "pooled", "wi", "ci", "meta", "scalep"], + ["scores", "maxima"], + _SCORES, + ), + "values": ( + ["scores", "maxima", "window", "pooled", "wi", "ci", "meta"], + ["partial"], + _VALUES, + ), + "merge": (["partial", "sink", "meta"], ["out"], _MERGE), + }[stage] + return mx.fast.metal_kernel( + name="deepseek_v41_online_" + stage, + input_names=inputs, + output_names=outputs, + source=source, + header=_READ + + ("\n#include \n" if stage.startswith("mma_") else ""), + ) + + +def rounded_packed_attention(q, window, pooled, wi, ci, sink, scale): + """Read packed KV directly with the official 64-key BF16 PV boundary. + + Matrix kernels share decoded tiles across heads for large candidate lists. + Short lists fit QK and PV in one threadgroup per head. Shapes exceeding + that capacity use separate dispatches with the same prefix maxima. + """ + _, length, heads, dim = q.shape + window_slots, pooled_slots = wi.shape[-1], ci.shape[-1] + if heads >= 8 and dim <= 512 and window_slots + pooled_slots >= 512: + return _mma_attention(q, window, pooled, wi, ci, sink, scale) + if window_slots + pooled_slots <= 2048: + return _fused_attention(q, window, pooled, wi, ci, sink, scale) + blocks = max(1, (wi.shape[-1] + ci.shape[-1] + 15) // 16) + meta = mx.array( + [heads, wi.shape[-1], ci.shape[-1], window.shape[1], pooled.shape[1], blocks], + mx.int32, + ) + window = window if window.size else mx.zeros((1,), mx.uint8) + pooled = pooled if pooled.size else mx.zeros((1,), mx.uint8) + wi = wi.astype(mx.int32) if wi.size else mx.zeros((1,), mx.int32) + ci = ci.astype(mx.int32) if ci.size else mx.zeros((1,), mx.int32) + scale = mx.array([scale]) + merge_meta = mx.array([heads, blocks], mx.int32) + # Share a single contiguous input between the score and value stages. + window, pooled = mx.contiguous(window), mx.contiguous(pooled) + wi, ci = mx.contiguous(wi), mx.contiguous(ci) + grid = ((heads + 3) // 4 * 128, length, blocks) + scores, maxima = _kernel("scores")( + inputs=[q, window, pooled, wi, ci, meta, scale], + template=[("D", dim)], + grid=grid, + threadgroup=(128, 1, 1), + output_shapes=[(1, length, heads, blocks, 16), (1, length, heads, blocks)], + output_dtypes=[mx.float32, mx.float32], + ) + partial = _kernel("values")( + inputs=[scores, maxima, window, pooled, wi, ci, meta], + template=[("D", dim)], + grid=grid, + threadgroup=(128, 1, 1), + output_shapes=[(1, length, heads, blocks, dim + 2)], + output_dtypes=[mx.float32], + )[0] + result = _kernel("merge")( + inputs=[partial, sink, merge_meta], + template=[("D", dim), ("T", q.dtype), ("CHUNK", 16)], + grid=((heads * (dim // 32) + 3) // 4 * 128, length, 1), + threadgroup=(128, 1, 1), + output_shapes=[(1, length, heads, dim)], + output_dtypes=[q.dtype], + )[0] + + return result + + +def _fused_attention(q, window, pooled, wi, ci, sink, scale): + _, length, heads, dim = q.shape + window_slots, pooled_slots = wi.shape[-1], ci.shape[-1] + count = window_slots + pooled_slots + chunk = 32 if count <= 1024 else 64 + blocks = max(1, (count + chunk - 1) // chunk) + meta = mx.array( + [heads, window_slots, pooled_slots, window.shape[1], pooled.shape[1]], mx.int32 + ) + window = window if window.size else mx.zeros((1,), mx.uint8) + pooled = pooled if pooled.size else mx.zeros((1,), mx.uint8) + wi = wi.astype(mx.int32) if wi.size else mx.zeros((1,), mx.int32) + ci = ci.astype(mx.int32) if ci.size else mx.zeros((1,), mx.int32) + scale = mx.array([scale]) + merge_meta = mx.array([heads, blocks], mx.int32) + partial = _kernel("fused")( + inputs=[q, window, pooled, wi, ci, meta, scale], + template=[("D", dim), ("NB", blocks), ("CHUNK", chunk)], + grid=(heads * blocks * 32, length, 1), + threadgroup=(blocks * 32, 1, 1), + output_shapes=[(1, length, heads, blocks, dim + 2)], + output_dtypes=[mx.float32], + )[0] + result = _kernel("merge")( + inputs=[partial, sink, merge_meta], + template=[("D", dim), ("T", q.dtype), ("CHUNK", chunk)], + grid=((heads * (dim // 32) + 3) // 4 * 128, length, 1), + threadgroup=(128, 1, 1), + output_shapes=[q.shape], + output_dtypes=[q.dtype], + )[0] + return result + + +def _mma_attention(q, window, pooled, wi, ci, sink, scale): + _, length, heads, dim = q.shape + count = wi.shape[-1] + ci.shape[-1] + score_blocks = max(1, (count + 15) // 16) + value_blocks = max(1, (count + 63) // 64) + meta = mx.array( + [ + heads, + wi.shape[-1], + ci.shape[-1], + window.shape[1], + pooled.shape[1], + score_blocks, + value_blocks, + ], + mx.int32, + ) + window = window if window.size else mx.zeros((1,), mx.uint8) + pooled = pooled if pooled.size else mx.zeros((1,), mx.uint8) + wi = wi.astype(mx.int32) if wi.size else mx.zeros((1,), mx.int32) + ci = ci.astype(mx.int32) if ci.size else mx.zeros((1,), mx.int32) + scores, maxima = _kernel("mma_scores")( + inputs=[q, window, pooled, wi, ci, meta, mx.array([scale])], + template=[("D", dim)], + grid=((heads + 7) // 8 * 128, length, score_blocks), + threadgroup=(128, 1, 1), + output_shapes=[ + (1, length, heads, score_blocks, 16), + (1, length, heads, score_blocks), + ], + output_dtypes=[mx.float32, mx.float32], + ) + partial = _kernel("mma_values")( + inputs=[scores, maxima, window, pooled, wi, ci, meta], + template=[("D", dim)], + grid=((heads + 7) // 8 * 128, length, value_blocks), + threadgroup=(128, 1, 1), + output_shapes=[(1, length, heads, value_blocks, dim + 2)], + output_dtypes=[mx.float32], + )[0] + return _kernel("merge")( + inputs=[partial, sink, mx.array([heads, value_blocks], mx.int32)], + template=[("D", dim), ("T", q.dtype), ("CHUNK", 64)], + grid=((heads * (dim // 32) + 3) // 4 * 128, length, 1), + threadgroup=(128, 1, 1), + output_shapes=[q.shape], + output_dtypes=[q.dtype], + )[0] diff --git a/omlx/patches/deepseek_v41/processing.py b/omlx/patches/deepseek_v41/processing.py new file mode 100644 index 0000000000..27f65fa6df --- /dev/null +++ b/omlx/patches/deepseek_v41/processing.py @@ -0,0 +1,240 @@ +# SPDX-License-Identifier: MIT +"""DeepSeek V4.1 image geometry, packing and prompt encoding.""" + +import math + +import mlx.core as mx +import numpy as np +from PIL import Image, ImageOps + + +def num_image_tokens(n_llm_h: int, n_llm_w: int) -> int: + return n_llm_h * (n_llm_w + 1) + 2 + + +def llm_grid(best_height: int, best_width: int, patch_size: int, downsample_ratio: int): + """Token grid the aligner produces from a patch grid of this pixel size.""" + return math.ceil((best_height // patch_size) / downsample_ratio), math.ceil( + (best_width // patch_size) / downsample_ratio + ) + + +def solve_resize_ratio(height, width, patch_size, downsample_ratio, max_n_token): + """Largest aspect-preserving pixel size whose token grid still fits in max_n_token.""" + r = height / width + max_w_float = math.sqrt((max_n_token - 2) / r + 0.25) - 0.5 + max_h_float = max_w_float * r + cell = patch_size * downsample_ratio + if max_w_float < 1.0: # very tall: collapse to a single column + return (max_n_token - 2) // 2 * cell, cell + if max_h_float < 1.0: # very wide: collapse to a single row + return cell, (max_n_token - 3) * cell + beta = min( + math.floor(max_w_float) * cell / width, math.floor(max_h_float) * cell / height + ) + return ( + math.floor(height * beta / patch_size) * patch_size, + math.floor(width * beta / patch_size) * patch_size, + ) + + +def safe_resize( + height, width, best_height, best_width, patch_size, downsample_ratio, max_n_token +): + """Shrink the pixel size until the image costs at most max_n_token LLM tokens.""" + n_llm_h, n_llm_w = llm_grid(best_height, best_width, patch_size, downsample_ratio) + if num_image_tokens(n_llm_h, n_llm_w) > max_n_token: + best_height, best_width = solve_resize_ratio( + height, width, patch_size, downsample_ratio, max_n_token + ) + n_llm_h, n_llm_w = llm_grid( + best_height, best_width, patch_size, downsample_ratio + ) + assert num_image_tokens(n_llm_h, n_llm_w) <= max_n_token + return n_llm_h, n_llm_w, best_height, best_width + + +def plan_image_grid(width: int, height: int, args): + """Resize plan for an image of the given original size; a pure function of its arguments.""" + p = args.vision_patch_size + if ( + args.vision_max_wh_ratio is not None + and width > height * args.vision_max_wh_ratio + ): + width = height * args.vision_max_wh_ratio + if 0 < width * height < args.vision_min_pixels: + ratio = (args.vision_min_pixels / (width * height)) ** 0.5 + width = int(width * ratio) + height = int(height * ratio) + best_width = math.ceil(width / p) * p + best_height = math.ceil(height / p) * p + return safe_resize( + height, + width, + best_height, + best_width, + p, + args.vision_downsample_ratio, + args.vision_max_n_token, + ) + + +def image_patches(image, config): + image = image.convert("RGB") + nh, nw, height, width = plan_image_grid(image.width, image.height, config) + if ( + config.vision_max_wh_ratio is not None + and image.width >= config.vision_max_wh_ratio * image.height + ): + image = image.resize((width, height)) + else: + scale = min(width / image.width, height / image.height) + contained = ( + max(1, round(image.width * scale)), + max(1, round(image.height * scale)), + ) + if round(image.width * scale) == 0 or round(image.height * scale) == 0: + resized = image.resize(contained, Image.Resampling.BICUBIC) + image = Image.new("RGB", (width, height), (127, 127, 127)) + image.paste( + resized, ((width - contained[0]) // 2, (height - contained[1]) // 2) + ) + else: + image = ImageOps.pad(image, (width, height), color=(127, 127, 127)) + p = config.vision_patch_size + x = (np.asarray(image, np.float32) / 255 - 0.5) / 0.5 + patches = ( + x.reshape(height // p, p, width // p, p, 3) + .transpose(0, 2, 4, 1, 3) + .reshape(-1, 3, p, p) + ) + types = [0] + ([1] * nw + [2]) * nh + [3] + return mx.array(patches).astype(mx.bfloat16), height // p, width // p, types + + +class Processor: + def __init__(self, tokenizer, config): + self.tokenizer, self.config = tokenizer, config + self.chat_template = "deepseek_v41_python_reference" + # Both oMLX's text and image paths must use the same encoder. + tokenizer.apply_chat_template = self.apply_chat_template + + def apply_chat_template( + self, + messages, + tokenize=False, + add_generation_prompt=True, + enable_thinking=True, + thinking_mode=None, + reasoning_effort=None, + tools=None, + continue_final_message=False, + **kwargs, + ): + from copy import deepcopy + + from .encoding import encode_messages + + messages = deepcopy(messages) + if tools: + if not messages or messages[0]["role"] != "system": + messages.insert(0, {"role": "system", "content": ""}) + messages[0]["tools"] = tools + mode = thinking_mode or ("thinking" if enable_thinking else "chat") + prompt = encode_messages( + messages, thinking_mode=mode, reasoning_effort=reasoning_effort + ) + header = "<|Assistant|>" + ("" if mode == "thinking" else "") + if not add_generation_prompt and prompt.endswith(header): + prompt = prompt[: -len(header)] + if continue_final_message: + raise ValueError( + "DeepSeek V4.1 partial assistant continuation is not yet supported" + ) + return ( + self.tokenizer.encode(prompt, add_special_tokens=False) + if tokenize + else prompt + ) + + def __call__(self, text=None, images=None, audio=None, videos=None, **kwargs): + if audio is not None or videos is not None: + raise ValueError("DeepSeek V4.1 processor supports text and images") + texts = [text] if isinstance(text, str) else text + if len(texts) != 1: + raise ValueError("Prepare each V4.1 prompt independently before batching") + ids = self.tokenizer.encode(texts[0], add_special_tokens=False) + images = [] if images is None else images + if ids.count(self.config.image_token_id) != len(images): + raise ValueError("Image placeholder count does not match image count") + expanded, pixels, grids, spans, types = [], [], [], [], [] + image_index = 0 + for token in ids: + if token != self.config.image_token_id: + expanded.append(token) + continue + patch, h, w, kinds = image_patches(images[image_index], self.config) + image_index += 1 + spans.append((len(expanded), len(kinds))) + expanded.extend([token] * len(kinds)) + pixels.append(patch) + grids.append((h, w)) + types.append(kinds) + result = { + "input_ids": mx.array([expanded]), + "attention_mask": mx.ones((1, len(expanded)), mx.int32), + } + if pixels: + result.update( + pixel_values=mx.concatenate(pixels), + image_grids=grids, + image_spans=spans, + image_types=types, + ) + return result + + +def format_messages(messages, num_images): + """Preserve text/image interleaving, retaining placeholders for decoded PIL inputs.""" + from copy import deepcopy + + output, ranges, seen = deepcopy(messages), [], 0 + for i, message in enumerate(output): + content = message.get("content") + if not isinstance(content, list): + continue + count = 0 + for part in content: + kind = part.get("type") + if kind in ("image", "image_url", "input_image"): + part.clear() + part.update(type="image", url="omlx-prepared-image") + count += 1 + elif kind in ("text", "input_text"): + part["type"] = "text" + else: + raise ValueError(f"Unsupported DeepSeek V4.1 content: {kind}") + if count: + ranges.append((i, count)) + seen += count + if seen == 0 and num_images: + target = next( + (i for i in range(len(output) - 1, -1, -1) if output[i]["role"] == "user"), + None, + ) + if target is None: + raise ValueError("Images require a user message") + content = output[target].get("content") or "" + parts = ( + content + if isinstance(content, list) + else [{"type": "text", "text": content}] + ) + output[target]["content"] = [ + {"type": "image", "url": "omlx-prepared-image"} for _ in range(num_images) + ] + parts + ranges = [(target, num_images)] + seen = num_images + if seen != num_images: + raise ValueError("Message image count does not match supplied images") + return output, ranges diff --git a/omlx/patches/deepseek_v41/quantization.py b/omlx/patches/deepseek_v41/quantization.py new file mode 100644 index 0000000000..700d46b3a4 --- /dev/null +++ b/omlx/patches/deepseek_v41/quantization.py @@ -0,0 +1,215 @@ +# SPDX-License-Identifier: MIT +"""Reference arithmetic for the published FP8/FP4 activation formats. + +Persistent KV uses packed FP8/FP4 bytes and one-byte scales. Activation-only +round trips remain available for projection arithmetic and numerical tests. +""" + +import mlx.core as mx +import mlx.nn as nn + +from omlx.custom_kernels.glm_moe_dsa import fast as glm_fast + +from ..deepseek_v4.switch_layers import _AFFINE_NATIVE_MIN_ROUTES, QuantizedSwitchLinear +from .activation import quantize_fp8_activation + + +def _normal_power_of_two(exponent): + """Construct normal FP32 scales exactly, including the minimum exponent.""" + return ((exponent + 127).astype(mx.uint32) << 23).view(mx.float32) + + +def round_fp8(x): + """E4M3FN, round to nearest even with finite saturation.""" + a = mx.minimum(mx.abs(x.astype(mx.float32)), 448.0) + exponent = mx.floor(mx.log2(mx.maximum(a, 2.0**-9))) + step = _normal_power_of_two(mx.maximum(exponent - 3, -9)) + return mx.sign(x) * mx.minimum(mx.round(a / step) * step, 448.0) + + +def _quantize_activation(x, bits=8, group_size=32, e4m3_scale=False): + dtype, shape = x.dtype, x.shape + if shape[-1] % group_size: + raise ValueError("Activation width must divide by quantization group size") + grouped = x.astype(mx.float32).reshape(*shape[:-1], -1, group_size) + limit = 448.0 if bits == 8 else 6.0 + minimum = limit * (2.0**-9 if e4m3_scale else 2.0**-126) + amax = mx.maximum(mx.max(mx.abs(grouped), axis=-1, keepdims=True), minimum) + scale = ( + round_fp8(amax / limit) + if e4m3_scale + else _normal_power_of_two(mx.maximum(mx.ceil(mx.log2(amax / limit)), -126)) + ) + scaled = mx.clip(grouped / scale, -limit, limit) + if bits == 8: + quantized = round_fp8(scaled) + elif bits == 4: + # E2M1 midpoint ties go to the code with an even low bit. + a = mx.abs(scaled) + q = mx.zeros_like(a) + for threshold, value, inclusive in [ + (0.25, 0.5, False), + (0.75, 1.0, True), + (1.25, 1.5, False), + (1.75, 2.0, True), + (2.5, 3.0, False), + (3.5, 4.0, True), + (5.0, 6.0, False), + ]: + q = mx.where(a >= threshold if inclusive else a > threshold, value, q) + quantized = mx.sign(scaled) * q + else: + raise ValueError("Only FP8 and FP4 are supported") + return (quantized * scale).reshape(shape).astype(dtype) + + +_compiled_quantize_activation = mx.compile(_quantize_activation) + + +def quantize_activation(x, bits=8, group_size=32, e4m3_scale=False): + if ( + bits == 8 + and group_size == 32 + and not e4m3_scale + and x.shape[-1] % 32 == 0 + and x.dtype in (mx.float32, mx.float16, mx.bfloat16) + and mx.default_device() != mx.cpu + ): + return quantize_fp8_activation(x) if x.size else x + return _compiled_quantize_activation(x, bits, group_size, e4m3_scale) + + +@mx.compile +def pack_activation(x, bits=8, group_size=32, e4m3_scale=False): + """Pack each row as value bytes followed by one scale byte per group.""" + if bits not in (4, 8) or x.shape[-1] % group_size: + raise ValueError("Invalid packed activation geometry") + grouped = x.astype(mx.float32).reshape( + *x.shape[:-1], x.shape[-1] // group_size, group_size + ) + limit = 448.0 if bits == 8 else 6.0 + minimum = limit * (2.0**-9 if e4m3_scale else 2.0**-126) + amax = mx.maximum(mx.max(mx.abs(grouped), -1), minimum) + if e4m3_scale: + scale = round_fp8(amax / limit) + scale_bytes = mx.to_fp8(scale) + else: + exponent = mx.maximum(mx.ceil(mx.log2(amax / limit)), -126) + scale = _normal_power_of_two(exponent) + scale_bytes = (exponent + 127).astype(mx.uint8) + scaled = mx.clip(grouped / scale[..., None], -limit, limit).reshape(x.shape) + if bits == 8: + values = mx.to_fp8(round_fp8(scaled)) + else: + a = mx.abs(scaled) + code = mx.zeros(a.shape, mx.uint8) + for i, (threshold, inclusive) in enumerate( + [ + (0.25, False), + (0.75, True), + (1.25, False), + (1.75, True), + (2.5, False), + (3.5, True), + (5.0, False), + ], + 1, + ): + code = mx.where(a >= threshold if inclusive else a > threshold, i, code) + code = code.astype(mx.uint8) | ((scaled < 0).astype(mx.uint8) << 3) + values = code[..., ::2] | (code[..., 1::2] << 4) + return mx.concatenate([values, scale_bytes], -1) + + +def unpack_activation( + packed, bits=8, group_size=32, e4m3_scale=False, dtype=mx.bfloat16 +): + """Decode already-selected rows; never expand a persistent KV cache.""" + groups = packed.shape[-1] // (group_size * bits // 8 + 1) + width = groups * group_size + nbytes = width * bits // 8 + values, scales = packed[..., :nbytes], packed[..., nbytes:] + if bits == 8: + values = mx.from_fp8(values, dtype=mx.float32) + else: + codes = mx.stack([values & 15, values >> 4], -1).reshape( + *packed.shape[:-1], width + ) + levels = mx.array([0, 0.5, 1, 1.5, 2, 3, 4, 6], mx.float32) + values = levels[codes & 7] * mx.where(codes & 8, -1.0, 1.0) + scales = ( + mx.from_fp8(scales, dtype=mx.float32) + if e4m3_scale + else _normal_power_of_two(scales.astype(mx.int32) - 127) + ) + return ( + (values.reshape(*packed.shape[:-1], groups, group_size) * scales[..., None]) + .reshape(*packed.shape[:-1], width) + .astype(dtype) + ) + + +class QuantizedProjection(QuantizedSwitchLinear): + """Packed MXFP or affine weights with optional official FP8 activations.""" + + def __init__( + self, + weight, + scales, + bits, + mode, + biases=None, + group_size=32, + quantize_input=True, + ): + nn.Module.__init__(self) + self.weight, self.scales = weight, scales + self.bits, self.mode = bits, mode + self.group_size = group_size + self.quantize_input = quantize_input + if biases is not None: + self.biases = biases + + @property + def input_dims(self): + return self.weight.shape[-1] * 32 // self.bits + + def _can_use_affine_blocks(self, x, sorted_indices, dtype=None): + dtype = dtype or x.dtype + return ( + sorted_indices + and x.ndim == 3 + and x.shape[-2] == 1 + and x.shape[0] >= _AFFINE_NATIVE_MIN_ROUTES + and dtype in (mx.float16, mx.bfloat16) + and self.group_size == 64 + and self.bits in (2, 3, 4, 6, 8) + and self._has_affine_metadata_dtype(dtype) + and glm_fast.has_symbol("deepseek_affine_gather_qmm_blocks") + ) + + def _native_block_kind(self, x, sorted_indices, dtype=None): + if (dtype or x.dtype) not in (mx.float16, mx.bfloat16): + return None + return super()._native_block_kind(x, sorted_indices, dtype=dtype) + + def __call__(self, x, indices=None, sorted_indices=False, block_plan=None): + if self.quantize_input: + x = quantize_activation(x) + return self.project_quantized(x, indices, sorted_indices, block_plan) + + def project_quantized(self, x, indices=None, sorted_indices=False, block_plan=None): + """Project an input whose activation quantization is already complete.""" + if indices is None: + return mx.quantized_matmul( + x, + self.weight, + self.scales, + self.get("biases"), + group_size=self.group_size, + bits=self.bits, + mode=self.mode, + ) + return super().__call__( + x, indices, sorted_indices=sorted_indices, block_plan=block_plan + ) diff --git a/omlx/patches/deepseek_v41/residency.py b/omlx/patches/deepseek_v41/residency.py new file mode 100644 index 0000000000..d131c0226b --- /dev/null +++ b/omlx/patches/deepseek_v41/residency.py @@ -0,0 +1,138 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Original and converted V4.1 residency estimates from tensor headers.""" + +import json +import struct +from dataclasses import dataclass +from functools import lru_cache +from pathlib import Path + + +@dataclass(frozen=True) +class EngramResidencyEstimate: + supported: bool + resident_bytes: int + mmap_bytes: int + engram_bytes: int + + def force_ssd_offload(self, memory_ceiling): + return ( + self.supported + and memory_ceiling > 0 + and self.resident_bytes > memory_ceiling >= self.mmap_bytes + ) + + +@lru_cache(maxsize=128) +def _header(filename, size, mtime_ns): + with open(filename, "rb") as file: + raw = file.read(8) + if len(raw) != 8: + raise ValueError("Truncated safetensors header") + length = struct.unpack(" size - 8: + raise ValueError("Invalid safetensors header length") + return json.loads(file.read(length)) + + +def deepseek_v41_residency_estimate(model_path): + path = Path(model_path).expanduser().resolve() + files = [path / "config.json", path / "model.safetensors.index.json"] + files.extend(path.glob("*.safetensors")) + files.extend((path / "engram").glob("*.safetensors")) + signature = tuple( + (str(f), st.st_size, st.st_mtime_ns) + for f in sorted(files) + for st in (f.stat(),) + ) + return _estimate(str(path), signature) + + +@lru_cache(maxsize=128) +def _estimate(model_path, signature): + path = Path(model_path) + config = json.loads((path / "config.json").read_text()) + spec = config.get("omlx_deepseek_v41") + if spec is not None and spec.get("version") != 1: + return EngramResidencyEstimate(False, 0, 0, 0) + mapping = json.loads((path / "model.safetensors.index.json").read_text())[ + "weight_map" + ] + headers = {} + stats = {name: (size, mtime) for name, size, mtime in signature} + + def entry(filename, key): + if filename not in headers: + full = str(path / filename) + headers[filename] = _header(full, *stats[full]) + return headers[filename][key] + + def tensor_bytes(filename, key): + start, end = entry(filename, key)["data_offsets"] + if start < 0 or end < start: + raise ValueError("Invalid Engram tensor offsets") + return end - start + + base, engram = 0, 0 + if spec is not None: + tables = spec.get("engram_tables", {}) + if not tables: + return EngramResidencyEstimate(False, 0, 0, 0) + engram_keys = { + table[key] + for table in tables.values() + for key in ("weight_key", "scale_key", "bias_key") + if table.get(key) + } + base = sum( + tensor_bytes(filename, key) + for key, filename in mapping.items() + if key not in engram_keys + ) + for table in tables.values(): + engram += tensor_bytes(table["weight_file"], table["weight_key"]) + if table.get("scale_key"): + engram += tensor_bytes( + table.get("scale_file") or table["weight_file"], table["scale_key"] + ) + if table.get("bias_key"): + engram += tensor_bytes( + table.get("scale_file") or table["weight_file"], table["bias_key"] + ) + else: + if config.get("model_type") != "deepseek_v41": + return EngramResidencyEstimate(False, 0, 0, 0) + for key, filename in mapping.items(): + if key.startswith("mtp."): + continue + size = tensor_bytes(filename, key) + if ".engram.embed." in key: + engram += size + continue + weight_key = ( + key.removesuffix(".scale") + ".weight" + if key.endswith(".scale") + else key + ) + dense = weight_key.endswith("wo_a.weight") or weight_key in ( + "head.weight", + "embed.weight", + ) + weight = entry(mapping[weight_key], weight_key) + if weight["dtype"].startswith("F8_E4M3"): + if key.endswith(".scale"): + # MLX MXFP8 uses one scale per row and 32 channels. + size = ( + 0 + if dense + else weight["shape"][0] * entry(filename, key)["shape"][1] + ) + elif dense: + size *= 2 + base += size + return EngramResidencyEstimate( + engram > 0, + int((base + engram) * 1.05), + int(base * 1.05) + 32 * 1024 * 1024, + engram, + ) diff --git a/omlx/patches/deepseek_v41/routing.py b/omlx/patches/deepseek_v41/routing.py new file mode 100644 index 0000000000..36bba7686b --- /dev/null +++ b/omlx/patches/deepseek_v41/routing.py @@ -0,0 +1,53 @@ +# SPDX-License-Identifier: MIT +"""Combine sorted expert outputs without a full unpermuted intermediate.""" + +from functools import cache + +import mlx.core as mx + +_SOURCE = r""" + const uint i = thread_position_in_grid.x; + if (i >= ROWS * D) return; + const uint row = i / D, d = i % D; + float sum = 0.0f; + for (uint j = 0; j < K; j++) { + sum += float(x[size_t(order[row * K + j]) * D + d]); + } + y[i] = T(sum + float(shared[i])); +""" + + +@cache +def _kernel(): + return mx.fast.metal_kernel( + name="v41_unpermute_reduce", + input_names=["x", "order", "shared"], + output_names=["y"], + source=_SOURCE, + ) + + +def combine_sorted_experts(routed, inverse, shared): + """Return the fused six-expert BF16 sum, or None for other layouts.""" + if ( + mx.default_device() != mx.gpu + or shared.ndim != 3 + or not shared.size + or routed.dtype != mx.bfloat16 + or shared.dtype != mx.bfloat16 + or inverse.ndim != 1 + or inverse.dtype != mx.uint32 + or routed.shape != (inverse.size, 1, shared.shape[-1]) + or inverse.size != 6 * shared.shape[0] * shared.shape[1] + ): + return None + width = shared.shape[-1] + rows = shared.size // width + return _kernel()( + inputs=[routed, inverse, shared], + template=[("T", shared.dtype), ("ROWS", rows), ("D", width), ("K", 6)], + grid=(shared.size, 1, 1), + threadgroup=(256, 1, 1), + output_shapes=[shared.shape], + output_dtypes=[shared.dtype], + )[0] diff --git a/omlx/patches/deepseek_v41/sensitivity.py b/omlx/patches/deepseek_v41/sensitivity.py new file mode 100644 index 0000000000..e9402f3dc6 --- /dev/null +++ b/omlx/patches/deepseek_v41/sensitivity.py @@ -0,0 +1,146 @@ +# SPDX-License-Identifier: MIT +"""Measure layer-output distortion on real V4.1 full-forward inputs.""" + +from contextlib import contextmanager + +import mlx.core as mx +import mlx.nn as nn +from mlx.utils import tree_flatten + +from .loading import set_module +from .oq import requantize_projection +from .quantization import QuantizedProjection + + +class _CaptureBlock: + def __init__(self, block, samples): + self.block = block + self.samples = samples + + def __contains__(self, name): + return name in self.block + + def __getattr__(self, name): + return getattr(self.block, name) + + def __call__(self, h, pre, cache, shared, start, image_mask): + # Cache writes replace arrays; separate containers preserve the input + # snapshot while the ordinary forward updates its own cache and KV map. + self.samples.append((h, pre, cache.extract(0), dict(shared), start, image_mask)) + return self.block(h, pre, cache, shared, start, image_mask) + + +@contextmanager +def _quantized_block(block, bits, eligible=None, progress=None): + saved = {} + try: + for path, module in tree_flatten( + block.leaf_modules(), is_leaf=nn.Module.is_module + ): + if eligible is not None and path not in eligible: + continue + if path.startswith("engram.") or path.endswith("wo_a"): + # Engram runs outside Block.__call__; wo_a is consumed directly + # as a dense weight by the attention output contraction. + continue + source_spec = None + if isinstance(module, QuantizedProjection): + source_spec = dict( + bits=module.bits, + mode=module.mode, + group_size=module.group_size, + quantize_input=module.quantize_input, + ) + elif not isinstance(module, nn.Linear) or "bias" in module: + continue + width = module.input_dims if source_spec else module.weight.shape[-1] + if width % 64: + continue + values = {path + ".weight": module.weight} + if source_spec: + values[path + ".scales"] = module.scales + if "biases" in module: + values[path + ".biases"] = module.biases + quantized, spec = requantize_projection( + values, path, source_spec, bits=bits, progress=progress + ) + replacement = QuantizedProjection( + quantized[path + ".weight"], + quantized[path + ".scales"], + biases=quantized[path + ".biases"], + **spec, + ) + saved[path] = module + set_module(block, path, replacement) + yield len(saved) + finally: + for path, module in saved.items(): + set_module(block, path, module) + + +def measure_sensitivity( + model, + tokenizer, + *, + bits=3, + num_samples=32, + seq_length=256, + calib_dataset="code_multilingual", + progress=None, +): + from ...oq import _load_calibration_data + + tokens = _load_calibration_data(tokenizer, calib_dataset, num_samples, seq_length) + if tokens is None or len(tokens) == 0: + raise ValueError("V4.1 sensitivity requires nonempty calibration data") + core = model.language_model + layers = list(core.layers) + inputs = [[] for _ in layers] + try: + core.layers = [ + _CaptureBlock(layer, rows) for layer, rows in zip(layers, inputs) + ] + for index, row in enumerate(tokens): + cache = core.make_cache() + logits = core(row[None], cache=cache) + mx.eval(logits, [item.state for item in cache]) + if progress: + progress("capture", index + 1, len(tokens)) + del logits, cache + finally: + core.layers = layers + + scores = {} + for index, (block, rows) in enumerate(zip(layers, inputs)): + if len(rows) != len(tokens): + raise RuntimeError(f"Missing full-forward samples for V4.1 layer {index}") + + def forward(row, block=block): + h, pre, cache, shared, start, mask = row + return block(h, pre, cache.extract(0), dict(shared), start, mask) + + baseline = [forward(row) for row in rows] + mx.eval(baseline) + + def quantize_progress(done, total, index=index): + if progress: + progress("measure", index, len(layers)) + + with _quantized_block(block, bits, progress=quantize_progress) as changed: + if not changed: + raise ValueError(f"No quantizable projections in V4.1 layer {index}") + error, power = 0.0, 0.0 + for row, reference in zip(rows, baseline): + actual = forward(row) + for original, converted in zip(reference, actual): + original = original.astype(mx.float32) + converted = converted.astype(mx.float32) + error += mx.sum(mx.square(original - converted)).item() + power += mx.sum(mx.square(original)).item() + scores[index] = error / max(power, 1e-10) + # Release this layer's retained inputs as soon as its measurement ends. + rows.clear() + del baseline + if progress: + progress("measure", index + 1, len(layers)) + return scores diff --git a/omlx/patches/deepseek_v41/sharding.py b/omlx/patches/deepseek_v41/sharding.py new file mode 100644 index 0000000000..f731f47280 --- /dev/null +++ b/omlx/patches/deepseek_v41/sharding.py @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Size-bounded shards that keep each quantized projection together.""" + +from pathlib import Path + +import mlx.core as mx + +MAX_SHARD_BYTES = 5_000_000_000 + + +class ShardWriter: + def __init__(self, destination, max_shard_bytes=MAX_SHARD_BYTES): + if max_shard_bytes <= 0: + raise ValueError("Shard size must be positive") + self.destination = Path(destination) + self.max_shard_bytes = max_shard_bytes + self._values = {} + self._bytes = 0 + self._shards = [] + self._seen = set() + + def add(self, values): + if self._seen.intersection(values): + raise ValueError("Duplicate tensor in shard writer") + size = sum(value.nbytes for value in values.values()) + if self._values and self._bytes + size > self.max_shard_bytes: + self._flush() + self._seen.update(values) + self._values.update(values) + self._bytes += size + # A projection larger than the target stays intact in its own shard. + if self._bytes >= self.max_shard_bytes: + self._flush() + + def _flush(self): + if not self._values: + return + name = f".model-shard-{len(self._shards) + 1:05d}.safetensors" + mx.save_safetensors(str(self.destination / name), self._values) + self._shards.append((name, tuple(self._values))) + self._values = {} + self._bytes = 0 + + def add_file(self, filename, keys): + """Adopt a streamed, indivisible tensor group without reading its data.""" + self._flush() + if self._seen.intersection(keys): + raise ValueError("Duplicate tensor in prewritten shard") + self._seen.update(keys) + self._shards.append((filename, tuple(keys))) + + def finish(self): + self._flush() + mapping = {} + count = len(self._shards) + for i, (temporary, keys) in enumerate(self._shards, 1): + name = f"model-{i:05d}-of-{count:05d}.safetensors" + target = self.destination / name + if target.exists(): + raise FileExistsError(target) + (self.destination / temporary).rename(target) + mapping.update(dict.fromkeys(keys, name)) + return mapping diff --git a/omlx/patches/deepseek_v41/storage.py b/omlx/patches/deepseek_v41/storage.py new file mode 100644 index 0000000000..3e158c5925 --- /dev/null +++ b/omlx/patches/deepseek_v41/storage.py @@ -0,0 +1,402 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Selected-row Engram I/O, following Qwen4-Exp's _SafeTensorMMap pattern. + +DeepSeek uses per-row/per-32-channel scales instead of Qwen's shared scale. +Copies leave the mapping under the lock, so close cannot invalidate a live view. +Resident tables retain their packed bytes; prefetch workers only copy CPU rows. +""" + +import fcntl +import json +import math +import mmap +import os +import struct +import time +from concurrent.futures import ThreadPoolExecutor, wait +from contextlib import contextmanager +from pathlib import Path +from threading import RLock + +import mlx.core as mx +import mlx.nn as nn +import numpy as np + +RESIDENT_READ_BYTES = 8 * 1024 * 1024 +PAGE_SIZE = os.sysconf("SC_PAGE_SIZE") +PAGE_PREFETCH_MIN_ROWS = 128 +PAGE_IO_WORKERS = 48 +_PAGE_IO_POOL = ThreadPoolExecutor( + max_workers=PAGE_IO_WORKERS, thread_name_prefix="v41-page-io" +) + + +def _resident_buffer(shape, dtype): + """Share packed Metal storage with CPU gathers, without a host copy.""" + types = { + np.dtype("= view.shape[0]): + raise IndexError("Engram row outside table") + gather_start = None + row_bytes = (end - start) // view.shape[0] if view.shape[0] else 0 + if ( + rows.size > PAGE_PREFETCH_MIN_ROWS + and 0 < row_bytes <= PAGE_SIZE + and self._prefetch_pages(rows, self._start + start, row_bytes) + ): + gather_start = time.perf_counter() + copied = view[rows] # Advanced indexing already copies the rows. + if gather_start is not None: + elapsed = time.perf_counter() - gather_start + now = time.monotonic() + # As in Qwen4-Exp, a slow warm gather can indicate eviction. + # This only changes I/O scheduling, never the selected rows. + if ( + elapsed > 0.0005 + 2e-6 * rows.size + and now - self._last_rearm >= 60 + ): + self._seen_pages = None + self._last_rearm = now + return copied, dtype + return np.array(view, copy=True), dtype + + def _prefetch_pages(self, rows, base, row_bytes): + """Read unseen pages concurrently before gathering from the mmap.""" + if self._seen_pages is None: + self._seen_pages = np.zeros( + (self._file_size + PAGE_SIZE - 1) // PAGE_SIZE, dtype=np.uint8 + ) + offsets = base + rows.reshape(-1) * row_bytes + pages = np.unique( + np.concatenate( + (offsets // PAGE_SIZE, (offsets + row_bytes - 1) // PAGE_SIZE) + ) + ) + fresh = pages[self._seen_pages[pages] == 0] + if not fresh.size: + return True + fd = self._file.fileno() + + def touch(group): + for page in group: + offset = int(page) * PAGE_SIZE + remaining = min(PAGE_SIZE, self._file_size - offset) + while remaining: + data = os.pread(fd, remaining, offset) + if not data: + raise ValueError("Truncated Engram page") + offset += len(data) + remaining -= len(data) + + # Bound the queue as well as the active reads. The caller holds _lock; + # drain every worker, including on error, before close can release fd. + futures = [] + try: + for group in np.array_split(fresh, min(PAGE_IO_WORKERS, fresh.size)): + futures.append(_PAGE_IO_POOL.submit(touch, group)) + finally: + wait(futures) + for future in futures: + future.result() + self._seen_pages[fresh] = 1 + return False + + def close(self): + with self._lock: + self._seen_pages = None + if self._mapping is not None: + self._mapping.close() + self._mapping = None + self._file.close() + + +def decode_array(raw, dtype): + if dtype == "BF16": + return mx.array((raw.astype(np.uint32) << 16).view(np.float32)).astype( + mx.bfloat16 + ) + if dtype.startswith("F8_E4M3"): + return mx.from_fp8(mx.array(raw), dtype=mx.float32) + if dtype.startswith("F8_E8M0"): + if np.any(raw == 255): + raise ValueError("NaN E8M0 scale in checkpoint") + return mx.array(np.exp2(raw.astype(np.float32) - 127)) + return mx.array(raw) + + +class DiskEngramEmbedding(nn.Module): + def __init__( + self, + path, + weight_key, + scale_key, + scale_path=None, + *, + bias_key=None, + bits=None, + group_size=32, + ): + super().__init__() + self._lock = RLock() + self._weights = TensorFile(path) + try: + self._scales = ( + self._weights + if scale_path is None or Path(scale_path) == Path(path) + else TensorFile(scale_path) + ) + except Exception: + self._weights.close() + raise + self._weight_key, self._scale_key = weight_key, scale_key + self._bias_key, self._bits, self._group_size = bias_key, bits, group_size + if (bits is None) != (bias_key is None) or ( + bits is not None and scale_key is None + ): + self._weights.close() + self._scales.close() + raise ValueError("Affine Engram requires bits, scales and biases") + self._closed = False + self._resident = None + self._prefetched = None + + def make_resident(self): + """Keep packed tensors in Metal-managed RAM with shared CPU views.""" + with self._lock: + resident = { + self._weight_key: self._weights.read( + self._weight_key, metal_backed=True + ), + } + if self._scale_key is not None: + resident[self._scale_key] = self._scales.read( + self._scale_key, metal_backed=True + ) + if self._bias_key is not None: + resident[self._bias_key] = self._scales.read( + self._bias_key, metal_backed=True + ) + self._resident = resident + self._weights.close() + if self._scales is not self._weights: + self._scales.close() + + def selected_bytes(self, rows): + total = 0 + for reader, key in ( + (self._weights, self._weight_key), + (self._scales, self._scale_key), + (self._scales, self._bias_key), + ): + if key is not None: + entry = reader.header[key] + start, end = entry["data_offsets"] + total += (end - start) // entry["shape"][0] * rows + return total + + def _read_rows(self, host): + with self._lock: + if self._closed: + raise RuntimeError("Engram embedding is closed") + result = [] + for reader, key in ( + (self._weights, self._weight_key), + (self._scales, self._scale_key), + (self._scales, self._bias_key), + ): + if key is None: + continue + if self._resident is None: + result.append(reader.read(key, host.reshape(-1))) + else: + raw, dtype = self._resident[key] + rows = host.reshape(-1) + if rows.size and (rows.min() < 0 or rows.max() >= raw.shape[0]): + raise IndexError("Engram row outside table") + result.append((raw[rows], dtype)) + return result + + def __call__(self, indices): + host = np.asarray(indices).astype(np.int64) + pending, self._prefetched = self._prefetched, None + if pending is not None: + requested, future = pending + data = future.result() + if not np.array_equal(requested, host): + data = self._read_rows(host) + else: + data = self._read_rows(host) + values = decode_array(*data[0]) + if self._bits is not None: + values = mx.dequantize( + values, + decode_array(*data[1]), + decode_array(*data[2]), + bits=self._bits, + group_size=self._group_size, + mode="affine", + ) + elif self._scale_key is not None: + scales = decode_array(*data[1]) + values = ( + values.reshape(values.shape[0], -1, 32) * scales[..., None] + ).reshape(values.shape) + return values.reshape(*host.shape, values.shape[-1]).astype(mx.bfloat16) + + def close(self): + with self._lock: + self._closed = True + self._resident = None + self._weights.close() + if self._scales is not self._weights: + self._scales.close() + + +PREFETCH_BYTES = 16 * 1024 * 1024 + + +class EngramPrefetch: + """One pending CPU read per model, drained at each forward boundary.""" + + def __init__(self): + self._executor = ThreadPoolExecutor( + max_workers=1, thread_name_prefix="v41-engram" + ) + self._pending = None + self._closed = False + + def submit(self, embed, ids): + self.drain() + if self._closed: + raise RuntimeError("Engram prefetch is closed") + if not isinstance(embed, DiskEngramEmbedding) or embed._resident is not None: + return + host = np.asarray(ids, dtype=np.int64).copy() + if embed.selected_bytes(host.size) + host.nbytes > PREFETCH_BYTES: + return + future = self._executor.submit(embed._read_rows, host) + embed._prefetched = (host, future) + self._pending = (embed, future) + + def drain(self): + pending, self._pending = self._pending, None + if pending is not None: + embed, future = pending + embed._prefetched = None + if not future.cancel(): + future.result() + + @contextmanager + def forward(self): + try: + yield self + finally: + self.drain() + + def close(self): + self._closed = True + try: + self.drain() + finally: + self._executor.shutdown(wait=True, cancel_futures=True) diff --git a/omlx/patches/deepseek_v41/tool_parser.py b/omlx/patches/deepseek_v41/tool_parser.py new file mode 100644 index 0000000000..6cebd19fd0 --- /dev/null +++ b/omlx/patches/deepseek_v41/tool_parser.py @@ -0,0 +1,40 @@ +# SPDX-License-Identifier: MIT +"""V4.1 DSML adapter around the official completion parser.""" + +import json + +from .encoding import parse_message_from_completion_text + +tool_call_start = "<|DSML| calls>" +tool_call_end = "" + + +def parse_tool_call(text, tools=None): + parsed = parse_message_from_completion_text( + "\n\n" + + tool_call_start + + "\n" + + text.strip() + + "\n" + + tool_call_end + + "<|end▁of▁sentence|>", + "chat", + ) + calls = parsed.get("tool_calls") or [] + if not calls: + raise ValueError("No complete DeepSeek V4.1 tool invocation") + for call in calls: + if not isinstance(json.loads(call["function"]["arguments"]), dict): + raise ValueError("DeepSeek V4.1 tool arguments must be a JSON object") + return [ + { + # oMLX uses the qualified name in the OpenAI function.name field. + "name": ( + f'{call["namespace"]}::{call["function"]["name"]}' + if call.get("namespace") is not None + else call["function"]["name"] + ), + "arguments": call["function"]["arguments"], + } + for call in calls + ] diff --git a/omlx/patches/deepseek_v41/vision.py b/omlx/patches/deepseek_v41/vision.py new file mode 100644 index 0000000000..ffb2256e31 --- /dev/null +++ b/omlx/patches/deepseek_v41/vision.py @@ -0,0 +1,141 @@ +# SPDX-License-Identifier: MIT +# Adapted from Blaizzy/mlx-vlm PR #2136 (7ec3d07e), MIT license. +import math + +import mlx.core as mx +import mlx.nn as nn + +from .config import ModelConfig + +VISION_NORM_EPS = 1e-6 + + +def get_vision_cos_sin( + n_h: int, n_w: int, dim: int, theta: float +) -> tuple[mx.array, mx.array]: + inv_freq = 1.0 / (theta ** (mx.arange(0, dim, 2, dtype=mx.float32) / dim)) + hpos = mx.broadcast_to(mx.arange(n_h)[:, None], (n_h, n_w)) + wpos = mx.broadcast_to(mx.arange(n_w)[None, :], (n_h, n_w)) + positions = mx.stack([hpos, wpos], axis=-1).reshape(-1, 2, 1) + freqs = (positions.astype(mx.float32) * inv_freq).reshape(n_h * n_w, -1) + return mx.cos(freqs)[:, None, :], mx.sin(freqs)[:, None, :] + + +def apply_rotary(x: mx.array, cos: mx.array, sin: mx.array) -> mx.array: + dtype = x.dtype + x1, x2 = mx.split(x.astype(mx.float32), 2, axis=-1) + return mx.concatenate([x1 * cos - x2 * sin, x2 * cos + x1 * sin], axis=-1).astype( + dtype + ) + + +class PatchEmbed(nn.Module): + def __init__(self, config: ModelConfig): + super().__init__() + patch_dim = 3 * config.vision_patch_size**2 + self.proj = nn.Linear(patch_dim, config.vision_dim) + + def __call__(self, x: mx.array) -> mx.array: + return self.proj(x.reshape(x.shape[0], -1)) + + +class Attention(nn.Module): + def __init__(self, config: ModelConfig): + super().__init__() + self.n_heads = config.vision_n_heads + self.head_dim = config.vision_dim // config.vision_n_heads + self.scale = self.head_dim**-0.5 + self.wqkv = nn.Linear(config.vision_dim, 3 * config.vision_dim) + self.wo = nn.Linear(config.vision_dim, config.vision_dim) + + def __call__(self, x: mx.array, cos: mx.array, sin: mx.array) -> mx.array: + n = x.shape[0] + q, k, v = ( + value.reshape(n, self.n_heads, self.head_dim) + for value in mx.split(self.wqkv(x), 3, axis=-1) + ) + q = apply_rotary(q, cos, sin).transpose(1, 0, 2) + k = apply_rotary(k, cos, sin).transpose(1, 0, 2) + v = v.transpose(1, 0, 2) + output = mx.fast.scaled_dot_product_attention( + q[None], k[None], v[None], scale=self.scale + )[0] + return self.wo(output.transpose(1, 0, 2).reshape(n, -1)) + + +class MLP(nn.Module): + def __init__(self, config: ModelConfig): + super().__init__() + self.w1 = nn.Linear(config.vision_dim, 2 * config.vision_inter_dim, bias=False) + self.w2 = nn.Linear(config.vision_inter_dim, config.vision_dim, bias=False) + + def __call__(self, x: mx.array) -> mx.array: + gate, up = mx.split(self.w1(x), 2, axis=-1) + return self.w2(nn.silu(gate) * up) + + +class Block(nn.Module): + def __init__(self, config: ModelConfig): + super().__init__() + self.norm1 = nn.RMSNorm(config.vision_dim, eps=VISION_NORM_EPS) + self.attn = Attention(config) + self.norm2 = nn.RMSNorm(config.vision_dim, eps=VISION_NORM_EPS) + self.ffn = MLP(config) + + def __call__(self, x: mx.array, cos: mx.array, sin: mx.array) -> mx.array: + x = x + self.attn(self.norm1(x), cos, sin) + return x + self.ffn(self.norm2(x)) + + +class ViT(nn.Module): + """DeepSeek ViT with full attention over one image and 2D RoPE.""" + + def __init__(self, config: ModelConfig): + super().__init__() + head_dim = config.vision_dim // config.vision_n_heads + if head_dim % 4: + raise ValueError("DeepSeek-V4.1 vision head dimension must divide by 4") + self.rope_dim = head_dim // 2 + self.rope_theta = config.vision_rope_theta + self.patch_embed = PatchEmbed(config) + self.blocks = [Block(config) for _ in range(config.vision_n_layers)] + self.norm = nn.RMSNorm(config.vision_dim, eps=VISION_NORM_EPS) + + def __call__(self, patches: mx.array, n_h: int, n_w: int) -> mx.array: + if patches.shape[0] != n_h * n_w: + raise ValueError( + f"Expected {n_h * n_w} vision patches, got {patches.shape[0]}" + ) + x = self.patch_embed(patches) + cos, sin = get_vision_cos_sin(n_h, n_w, self.rope_dim, self.rope_theta) + for block in self.blocks: + x = block(x, cos, sin) + return self.norm(x) + + +class Aligner(nn.Module): + def __init__(self, config: ModelConfig): + super().__init__() + self.downsample_ratio = config.vision_downsample_ratio + in_dim = config.vision_dim * self.downsample_ratio**2 + self.w1 = nn.Linear(in_dim, config.dim) + self.w2 = nn.Linear(config.dim, config.dim) + self.gelu = nn.GELU() + + def __call__(self, x: mx.array, n_h: int, n_w: int) -> mx.array: + ratio = self.downsample_ratio + dim = x.shape[-1] + pad_h = -n_h % ratio + pad_w = -n_w % ratio + x = x.reshape(n_h, n_w, dim) + if pad_h or pad_w: + x = mx.pad(x, ((0, pad_h), (0, pad_w), (0, 0))) + + out_h = math.ceil(n_h / ratio) + out_w = math.ceil(n_w / ratio) + x = x.reshape(out_h, ratio, out_w, ratio, dim) + x = x.transpose(0, 2, 4, 1, 3).reshape(out_h * out_w, dim * ratio**2) + return self.w2(self.gelu(self.w1(x))) + + +__all__ = ["Aligner", "ViT", "apply_rotary", "get_vision_cos_sin"] diff --git a/omlx/patches/mlx_lm_mtp/batch_generator.py b/omlx/patches/mlx_lm_mtp/batch_generator.py index e357f186cc..b0c84f0a0a 100644 --- a/omlx/patches/mlx_lm_mtp/batch_generator.py +++ b/omlx/patches/mlx_lm_mtp/batch_generator.py @@ -2502,13 +2502,19 @@ def _post_init_mtp(gen_batch: Any) -> None: state.depth = depth state.head_clone = head_clone if depth > 1: - state.controller = _DepthController( - depth, - marginal_ms=getattr( - gen_batch.model, "_omlx_mtp_marginal_ms", None - ), - exit_margin=_effective_loop_tax(gen_batch.model), + factory = getattr( + _dspark_host(gen_batch.model), "make_mtp_depth_controller", None ) + if factory is not None: + state.controller = factory(depth) + else: + state.controller = _DepthController( + depth, + marginal_ms=getattr( + gen_batch.model, "_omlx_mtp_marginal_ms", None + ), + exit_margin=_effective_loop_tax(gen_batch.model), + ) primed = _prompt_priming.take_primed( gen_batch.model, gen_batch.prompt_cache, main_tok ) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index ca41bc00b2..eabca6d60d 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -36,6 +36,9 @@ PromptProcessingBatch, SequenceStateMachine, ) +from mlx_lm.models.cache import ( + ArraysCache as _MLXArraysCache, +) from mlx_lm.models.cache import ( KVCache as _MLXKVCache, ) @@ -47,6 +50,7 @@ ) from mlx_lm.sample_utils import make_logits_processors +from .cache.deepseek_v41_delta import compact_snapshot as compact_deepseek_v41_snapshot from .cache.observability import BoundarySnapshotDiagnostics, CacheRateTracker from .cache.paged_cache import PagedCacheManager from .cache.pooling_delta import compact_pooling_cache_snapshot @@ -100,8 +104,14 @@ def _compact_boundary_snapshot_value( ): with mx.stream(stream): compact_pooling_cache_snapshot(value[1], token_count, block_size) + compact_deepseek_v41_snapshot(value[1], token_count, block_size) delta_arrays = [] for layer in value[1]: + if ( + layer.get("class_name") == "DeepseekV41Cache" + and len(layer.get("state", ())) == 8 + ): + delta_arrays.extend(layer["state"][i] for i in (2, 3)) for sub_idx in layer.get("pooling_delta_ranges", {}): pooled = layer["state"][int(sub_idx)][2] if isinstance(pooled, mx.array): @@ -2913,7 +2923,10 @@ def _cache_tree_has_arrays_cache(cache_obj: Any) -> bool: return any( Scheduler._cache_tree_has_arrays_cache(sub) for sub in sub_caches ) - return type(cache_obj).__name__ in ("ArraysCache", "SizedArraysCache") + return isinstance(cache_obj, _MLXArraysCache) or type(cache_obj).__name__ in ( + "ArraysCache", + "SizedArraysCache", + ) def _load_generation_config_eos(self) -> set[int] | None: """Load EOS token IDs from generation_config.json if available.""" diff --git a/omlx/utils/model_loading.py b/omlx/utils/model_loading.py index 4f6fd32b24..54124b394e 100644 --- a/omlx/utils/model_loading.py +++ b/omlx/utils/model_loading.py @@ -513,7 +513,15 @@ def maybe_apply_pre_load_patches( ) model_type = config.get("model_type") - if isinstance(model_type, str) and model_type.startswith("deepseek_v4"): + if model_type == "deepseek_v41": + from ..patches.deepseek_v41 import apply_patch + + apply_patch() + if ( + isinstance(model_type, str) + and model_type.startswith("deepseek_v4") + and not model_type.startswith("deepseek_v41") + ): from ..patches.deepseek_v4 import apply_deepseek_v4_patch if apply_deepseek_v4_patch(): diff --git a/pyproject.toml b/pyproject.toml index 937b2a5330..3822b1d8bb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -268,6 +268,7 @@ include = ["omlx*"] "bench_corpora/*", ] "omlx.eval" = ["data/*.jsonl"] +"omlx.patches.deepseek_v41" = ["LICENSE"] "omlx.custom_kernels.glm_moe_dsa" = ["*.metallib", "*.dylib", "*.so"] "omlx.custom_kernels.decode_fast" = ["*.metallib", "*.dylib", "*.so"] "omlx.custom_kernels.minimax_m3" = ["*.metallib", "*.dylib", "*.so"] diff --git a/tests/deepseek_v41_offload_ui.test.cjs b/tests/deepseek_v41_offload_ui.test.cjs new file mode 100644 index 0000000000..a7e75a56ec --- /dev/null +++ b/tests/deepseek_v41_offload_ui.test.cjs @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: Apache-2.0 +const fs = require('fs'); +const vm = require('vm'); +const assert = require('assert/strict'); +const path = require('path'); +const root = path.resolve(__dirname, '..'); +const context = { + localStorage: {getItem: () => null}, + window: {t: k => k}, + console, + alert: message => {throw Error(message)}, +}; +vm.createContext(context); +vm.runInContext(fs.readFileSync(path.join(root, 'omlx/admin/static/js/dashboard.js'), 'utf8'), context); +(async () => { + const app = context.dashboard(); + app.loadModels = async () => {}; + let payload; + context.fetch = async (url, init) => { + payload = JSON.parse(init.body); + assert.equal(init.method, 'PUT'); + return {ok: true, json: async () => ({})}; + }; + const key = 'deepseek_v41_engram_ssd_offload'; + for (const [forced, saved] of [[false,false], [false,true], [true,false], [true,true]]) { + const model = {id:'v41', config_model_type:'deepseek_v41', [key+'_supported']:true, [key+'_forced']:forced}; + app.selectedModel = model; + app.modelSettings = app.buildModelSettingsState(model, {[key]:saved}); + assert.equal(app.modelSettings[key], forced || saved); + assert.equal(app.modelSettings[key+'_forced'], forced); + const html = fs.readFileSync(path.join(root, + 'omlx/admin/templates/dashboard/_modal_model_settings.html'), 'utf8'); + const section = html.split('')[1] + .split('')[0]; + const click = section.match(/@click="([^"]+)"/)[1]; + const disabled = section.match(/:disabled="([^"]+)"/)[1]; + const scope = {modelSettings: app.modelSettings}; + assert.equal(vm.runInNewContext(disabled, scope), forced); + vm.runInNewContext(click, scope); + assert.equal(app.modelSettings[key], forced || !saved); + if (!forced) vm.runInNewContext(click, scope); + await app.saveModelSettings(); + assert.equal(payload[key], saved, 'Saving unrelated settings must preserve requested storage mode'); + } + app.selectedModel[key+'_forced'] = false; + app.modelSettings = app.buildModelSettingsState(app.selectedModel, {[key]:false}); + app.modelSettings[key] = true; + await app.saveModelSettings(); + assert.equal(payload[key], true); + const other = app.buildModelSettingsState({config_model_type:'llama'}, {}); + assert.equal(other[key+'_supported'], false); + console.log('PASS: forced/saved/toggled/other-model modal state and actual PUT payload'); +})().catch(error => {console.error(error); process.exitCode = 1}); diff --git a/tests/fixtures/deepseek_v41_expected.md b/tests/fixtures/deepseek_v41_expected.md new file mode 100644 index 0000000000..90efd605e7 --- /dev/null +++ b/tests/fixtures/deepseek_v41_expected.md @@ -0,0 +1,11 @@ +# DeepSeek V4.1 expected outputs + +`deepseek_v41_expected.npz` contains 43 small NumPy arrays (23,093 bytes), not model weights or executable reference code. They were recorded from DeepSeek's MIT-licensed [reference implementation at df42c109f1defefcbfcedbe7d905718a12266e40](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/tree/df42c109f1defefcbfcedbe7d905718a12266e40). The archive SHA-256 is `2eb45f6bd71cda9a99dd58e6efb263858d7b09e7b12c5193ccab71f096d41f31`. + +The tests reconstruct synthetic weights with `load_reference_weights`: NumPy PCG64 seeded by the case seed plus CRC32 of each original PyTorch parameter name. Expert weights are generated separately before stacking; vision `.ffn.` maps to reference `.mlp.`. Configurations, input seeds, normalization adjustments and comparison tolerances are in `test_deepseek_v41.py`. + +The archive covers prefill lengths 1/3/8/17 followed by three decode steps, Engram hashes across image boundaries, Engram gating, ViT and aligner outputs, image patch geometry/normalization, and three DSpark target/draft steps. PyTorch ran in FP32 on CPU with the small `cpu_kernels` substitutions in the test file replacing TileLang activation quantization, sparse attention and Sinkhorn operations. No MLX model output was used as an expected value. + +For prefill/decode and DSpark, the reference indexer was made to republish its own K cache before each call. The pinned source otherwise retains another layer's shared index-K pointer on an incomplete compression group. This correction is part of the recorded oracle; these vectors do not claim parity with that reference bug or evaluate real-checkpoint quality. + +To regenerate, use the linked reference revision and the configurations, parameter generator and CPU substitutions above. Record the final prefill/decode logits, target hidden states and draft tuple, and the separate vision/Engram outputs in the same assertion order. Changes to model arithmetic must be checked against that independent reference before replacing expected values. diff --git a/tests/fixtures/deepseek_v41_expected.npz b/tests/fixtures/deepseek_v41_expected.npz new file mode 100644 index 0000000000..22001a199c Binary files /dev/null and b/tests/fixtures/deepseek_v41_expected.npz differ diff --git a/tests/test_admin_api_key.py b/tests/test_admin_api_key.py index da7fac43b6..649d814447 100644 --- a/tests/test_admin_api_key.py +++ b/tests/test_admin_api_key.py @@ -133,6 +133,63 @@ def test_list_models_reports_forced_qwen4_ple_offload(self, tmp_path): assert model["qwen4_ple_resident_bytes"] == 1000 assert model["qwen4_ple_mmap_bytes"] == 400 + def test_list_models_reports_forced_deepseek_v41_engram_offload(self, tmp_path): + from omlx.patches.deepseek_v41.residency import ( + EngramResidencyEstimate, + ) + + model_path = tmp_path / "v41" + model_path.mkdir() + estimate = EngramResidencyEstimate( + supported=True, + engram_bytes=550, + resident_bytes=1000, + mmap_bytes=400, + ) + pool = MagicMock() + pool.get_status.return_value = { + "models": [ + { + "id": "v41", + "model_path": str(model_path), + "config_model_type": "deepseek_v41", + "estimated_size": 1000, + } + ] + } + pool._fallback_admission_ceiling.return_value = 500 + manager = MagicMock() + manager.get_all_settings.return_value = {} + state = MagicMock(default_model=None) + + with ( + patch.object(admin_routes, "_get_engine_pool", return_value=pool), + patch.object(admin_routes, "_get_settings_manager", return_value=manager), + patch.object(admin_routes, "_get_server_state", return_value=state), + patch.object(admin_routes, "_get_global_settings", return_value=None), + patch.object( + admin_routes, "_dflash_compat_for_model", return_value=(False, "") + ), + patch.object( + admin_routes, "_mtp_compat_for_model", return_value=(False, "") + ), + patch.object( + admin_routes, "_paroquant_compat_for_model", return_value=(False, "") + ), + patch( + "omlx.patches.deepseek_v41.residency." + "deepseek_v41_residency_estimate", + return_value=estimate, + ), + ): + result = asyncio.run(admin_routes.list_models(is_admin=True)) + + model = result["models"][0] + assert model["deepseek_v41_engram_ssd_offload_supported"] is True + assert model["deepseek_v41_engram_ssd_offload_forced"] is True + assert model["deepseek_v41_engram_resident_bytes"] == 1000 + assert model["deepseek_v41_engram_mmap_bytes"] == 400 + def test_list_models_adds_display_name_without_changing_id(self, tmp_path): """Ensure nested model paths only affect UI display names.""" model_root = tmp_path / "models" @@ -326,26 +383,31 @@ class TestVerifyAnyApiKey: def test_matches_main_key(self): from omlx.settings import SubKeyEntry + sub_keys = [SubKeyEntry(key="sub1"), SubKeyEntry(key="sub2")] assert verify_any_api_key("main-key", "main-key", sub_keys) is True def test_matches_sub_key(self): from omlx.settings import SubKeyEntry + sub_keys = [SubKeyEntry(key="sub1"), SubKeyEntry(key="sub2")] assert verify_any_api_key("sub2", "main-key", sub_keys) is True def test_no_match(self): from omlx.settings import SubKeyEntry + sub_keys = [SubKeyEntry(key="sub1")] assert verify_any_api_key("wrong", "main-key", sub_keys) is False def test_empty_api_key(self): from omlx.settings import SubKeyEntry + sub_keys = [SubKeyEntry(key="sub1")] assert verify_any_api_key("", "main-key", sub_keys) is False def test_no_main_key_matches_sub(self): from omlx.settings import SubKeyEntry + sub_keys = [SubKeyEntry(key="sub1")] assert verify_any_api_key("sub1", "", sub_keys) is True @@ -360,6 +422,7 @@ def test_none_main_key_no_sub_keys(self): def test_none_main_key_matches_sub(self): from omlx.settings import SubKeyEntry + sub_keys = [SubKeyEntry(key="sub1")] assert verify_any_api_key("sub1", None, sub_keys) is True diff --git a/tests/test_admin_model_settings.py b/tests/test_admin_model_settings.py index 75f09c5d55..257cd40124 100644 --- a/tests/test_admin_model_settings.py +++ b/tests/test_admin_model_settings.py @@ -295,6 +295,35 @@ async def test_qwen4_ple_ssd_offload_is_ignored_for_other_models(): assert settings.qwen4_ple_ssd_offload is False +@pytest.mark.asyncio +async def test_deepseek_v41_engram_ssd_offload_is_persisted_for_v41_only(): + pool, entry = _failed_pool() + entry.config_model_type = "deepseek_v41" + settings = ModelSettings() + + await _update_settings( + pool, + settings, + admin_routes.ModelSettingsRequest(deepseek_v41_engram_ssd_offload=True), + ) + + assert settings.deepseek_v41_engram_ssd_offload is True + + +@pytest.mark.asyncio +async def test_deepseek_v41_engram_ssd_offload_is_ignored_for_other_models(): + pool, _ = _failed_pool() + settings = ModelSettings() + + await _update_settings( + pool, + settings, + admin_routes.ModelSettingsRequest(deepseek_v41_engram_ssd_offload=True), + ) + + assert settings.deepseek_v41_engram_ssd_offload is False + + @pytest.mark.asyncio async def test_qwen4_mtp_setting_accepts_embedded_head(tmp_path): _write_qwen4_mtp_checkpoint(tmp_path, embedded_mtp=True) diff --git a/tests/test_deepseek_v41.py b/tests/test_deepseek_v41.py new file mode 100644 index 0000000000..c06f996c2f --- /dev/null +++ b/tests/test_deepseek_v41.py @@ -0,0 +1,913 @@ +"""Small-weight regression checks against recorded official outputs. + +Expected values come from the independent PyTorch reference with CPU kernel +substitutions. See fixtures/deepseek_v41_expected.md for provenance and limits. +""" + +import sys +import zlib +from dataclasses import asdict +from pathlib import Path + +import mlx.core as mx +import numpy as np +import pytest + +from omlx.patches.deepseek_v41.cache import DeepseekV41Cache +from omlx.patches.deepseek_v41.config import ModelConfig +from omlx.patches.deepseek_v41.language import LanguageModel + + +def tiny(**kwargs): + values = dict( + vocab_size=64, + dim=32, + moe_inter_dim=32, + n_layers=5, + n_heads=2, + q_lora_rank=32, + head_dim=32, + rope_head_dim=8, + o_groups=2, + o_lora_rank=16, + index_n_heads=8, + index_head_dim=32, + index_topk=3, + n_routed_experts=4, + n_activated_experts=2, + window_size=4, + dtype="bf16", + expert_dtype=None, + n_mtp_layers=0, + max_seq_len=64, + max_batch_size=2, + hc_sinkhorn_iters=3, + candidate_source_layer=3, + candidate_block_size=2, + candidate_topk_blocks=2, + index_source_layers=(1, 3, 4), + ) + values.update(kwargs) + return ModelConfig(**values) + + +def decode_e4m3(raw): + """Decode the E4M3FN bit fields independently of MLX.""" + raw = np.asarray(raw, dtype=np.uint8) + exponent = ((raw >> 3) & 15).astype(np.int32) + fraction = (raw & 7).astype(np.float32) + magnitude = np.where( + exponent == 0, fraction * 2.0**-9, + np.ldexp(1.0 + fraction / 8, exponent - 7), + ) + magnitude = np.where((raw & 127) == 127, np.nan, magnitude) + return np.copysign(magnitude, np.where(raw & 128, -1, 1)).astype(np.float32) + + +def reference_activation(raw, bits=8, group=32, e4m3=False): + """Nearest representable value, with even-code tie breaking.""" + def nearest(values, levels): + order = np.concatenate([np.arange(0, len(levels), 2), np.arange(1, len(levels), 2)]) + index = np.abs(np.abs(values)[..., None] - levels[order]).argmin(-1) + return np.copysign(levels[order[index]], values) + + fp8 = decode_e4m3(np.arange(127, dtype=np.uint8)) + levels = fp8 if bits == 8 else np.array([0, .5, 1, 1.5, 2, 3, 4, 6], np.float32) + rows = raw.reshape(*raw.shape[:-1], -1, group) + scale = np.maximum(np.abs(rows).max(-1, keepdims=True) / levels[-1], + 2.0**-9 if e4m3 else 2.0**-126) + scale = nearest(scale, fp8) if e4m3 else np.exp2(np.ceil(np.log2(scale))) + return (nearest(rows / scale, levels) * scale).reshape(raw.shape) + + +@pytest.fixture +def expected(): + with np.load(Path(__file__).parent / "fixtures/deepseek_v41_expected.npz") as data: + return dict(data) + + +def load_reference_weights(model, seed=341, scale=0.08, vision=False): + from mlx.utils import tree_flatten + + def values(name, shape): + rng = np.random.default_rng(seed + zlib.crc32(name.encode())) + data = rng.normal(0, scale, shape).astype(np.float32) + if ( + ("norm" in name and name.endswith("weight")) + if vision + else "norm.weight" in name + ): + data += 1 + if "weights_proj.weight" in name: + data = np.abs(data) + return data + + weights = [] + for name, parameter in tree_flatten(model.parameters()): + original = name.replace(".ffn.", ".mlp.") if vision else name + if ".experts." in original and parameter.ndim == 3: + prefix, suffix = original.split(".experts.") + data = np.stack( + [ + values(f"{prefix}.experts.{expert}.{suffix}", parameter.shape[1:]) + for expert in range(parameter.shape[0]) + ] + ) + else: + data = values(original, parameter.shape) + weights.append((name, mx.array(data))) + model.load_weights(weights, strict=True) + + +@pytest.mark.parametrize("length", [1, 3, 8, 17]) +def test_official_prefill_decode(expected, length): + model = LanguageModel(tiny()) + load_reference_weights(model) + ids = np.random.default_rng(5).integers(3, 60, (1, length + 3), dtype=np.int32) + cache = model.make_cache() + actual = np.asarray(model(mx.array(ids[:, :length]), cache=cache))[:, -1] + np.testing.assert_allclose( + actual, expected[f"prefill{length}_0"], atol=2e-5, rtol=2e-4 + ) + for index, position in enumerate(range(length, length + 3), 1): + actual = np.asarray( + model(mx.array(ids[:, position : position + 1]), cache=cache) + )[:, -1] + np.testing.assert_allclose( + actual, expected[f"prefill{length}_{index}"], atol=3e-5, rtol=3e-4 + ) + + +def test_chunk_boundaries_and_late_join(): + mx.random.seed(32) + model = LanguageModel(tiny()) + a, b = mx.array([[4, 5, 6, 7, 8, 9, 10]]), mx.array([[12, 13, 14]]) + ca, cb = model.make_cache(), model.make_cache() + expected = model(a) + actual = mx.concatenate( + [ + model(a[:, :3], cache=ca), + model(a[:, 3:5], cache=ca), + model(a[:, 5:], cache=ca), + ], + 1, + ) + np.testing.assert_allclose(actual, expected, atol=1e-5) + model(b, cache=cb) + merged = [DeepseekV41Cache.merge([x, y]) for x, y in zip(ca, cb)] + next_ids = mx.array([[15], [16]]) + result = model(next_ids, cache=merged) + solo_a = model(mx.concatenate([a, next_ids[:1]], 1))[:, -1:] + solo_b = model(mx.concatenate([b, next_ids[1:]], 1))[:, -1:] + np.testing.assert_allclose(result, mx.concatenate([solo_a, solo_b], 0), atol=1e-5) + for c in merged: + c.filter(mx.array([1])) + result = model(mx.array([[17]]), cache=merged) + np.testing.assert_allclose( + result, model(mx.array([[12, 13, 14, 16, 17]]))[:, -1:], atol=1e-5 + ) + + +def test_left_padding(): + model = LanguageModel(tiny()) + cache = model.make_cache() + for c in cache: + c.left_padding = mx.array([0, 3]) + x = mx.array([[3, 4, 5, 6, 7], [0, 0, 0, 8, 9]]) + actual = model(x, cache=cache) + np.testing.assert_allclose(actual[1:2, -1:], model(x[1:2, -2:])[:, -1:], atol=1e-5) + assert cache[0].offset.tolist() == [5, 2] + + +def test_engram_hash_history_and_image_boundary(expected): + from omlx.patches.deepseek_v41.engram import NgramHash + + c = tiny( + engram_layer_ids=(1,), + engram_num_embeddings=(72,), + engram_vocab_size=5, + engram_max_ngram_size=4, + engram_n_heads=2, + engram_head_dim=32, + engram_compressed_vocab_size=64, + ) + hasher = NgramHash(c, np.arange(64)) + ids = np.array([[3, 4, 5, 6, 7, 8, 9]]) + image = np.array([[False, False, True, True, False, False, False]]) + first, history = hasher(ids[:, :3], image_mask=image[:, :3]) + second, history = hasher(ids[:, 3:], history, image[:, 3:]) + np.testing.assert_array_equal( + np.concatenate([first, second], 1), expected["hash_0"] + ) + np.testing.assert_array_equal(history, [[7, 8, 9]]) + with pytest.raises(ValueError, match="vocabulary"): + NgramHash(c, np.arange(63)) + + +def test_vision_and_aligner_reference(expected): + from omlx.patches.deepseek_v41.vision import Aligner, ViT + + c = tiny( + vision_n_layers=2, + vision_dim=32, + vision_n_heads=4, + vision_inter_dim=32, + vision_patch_size=2, + ) + rng = np.random.default_rng(7) + for index, cls in enumerate([ViT, Aligner]): + model = cls(c) + load_reference_weights(model, seed=7, scale=0.1, vision=True) + x = rng.normal(0, 1, (20, 3, 2, 2) if cls is ViT else (20, 32)).astype( + np.float32 + ) + np.testing.assert_allclose( + model(mx.array(x), 4, 5), expected[f"vision_{index}"], atol=2e-6, rtol=1e-4 + ) + + +@pytest.mark.parametrize( + "shape", [(120, 50), (30, 190), (1, 2000), (2000, 1), (12, 12)] +) +def test_image_processor_matches_reference(expected, shape): + from PIL import Image + + from omlx.patches.deepseek_v41.processing import image_patches + + c = tiny( + vision_n_layers=1, + vision_patch_size=2, + vision_min_pixels=64, + vision_max_n_token=32, + ) + actual, ah, aw, types_ = image_patches(Image.new("RGB", shape, (19, 101, 220)), c) + if shape in ((1, 2000), (2000, 1)): + assert actual.shape[0] == ah * aw and len(types_) <= c.vision_max_n_token + return + key = f"image{shape[0]}x{shape[1]}" + np.testing.assert_array_equal([ah, aw], expected[f"{key}_grid"]) + np.testing.assert_array_equal(actual.astype(mx.float32), expected[f"{key}_patch"]) + np.testing.assert_array_equal(types_, expected[f"{key}_types"]) + + +def test_fp8_and_fp4_roundtrip(): + from omlx.patches.deepseek_v41.quantization import quantize_activation + + rng = np.random.default_rng(8) + raw = np.concatenate([rng.normal(0, 4, (4, 32)), np.zeros((1, 32))]).astype( + np.float32 + ) + np.testing.assert_array_equal( + quantize_activation(mx.array(raw)), + reference_activation(raw), + ) + for group, e4m3 in [(32, False), (16, True)]: + expected = reference_activation(raw, 4, group, e4m3) + np.testing.assert_array_equal( + quantize_activation(mx.array(raw), 4, group, e4m3), + expected, + ) + + +def test_mmap_engram_selected_rows_and_close(tmp_path): + from omlx.patches.deepseek_v41.storage import DiskEngramEmbedding + + path = tmp_path / "table.safetensors" + # Byte-compatible E4M3 data and E8M0 scales represented by source dtypes. + values = mx.arange(8 * 32, dtype=mx.float32).reshape(8, 32) / 32 + mx.save_safetensors(str(path), {"weight": values.astype(mx.bfloat16)}) + table = DiskEngramEmbedding(path, "weight", None) + actual = table(mx.array([[6, 1, 6]])) + table.close() + np.testing.assert_array_equal( + actual.astype(mx.float32), values[mx.array([[6, 1, 6]])] + ) + with pytest.raises(RuntimeError, match="closed"): + table(mx.array([0])) + + +def test_cache_handler_restores_type_and_continuation(): + from omlx.cache.type_registry import CacheTypeRegistry + from omlx.patches.deepseek_v41 import apply_patch + + apply_patch() + model = LanguageModel(tiny()) + cache = model.make_cache() + model(mx.array([[3, 4, 5, 6, 7]]), cache=cache) + restored = [] + for item in cache: + handler = CacheTypeRegistry.get_handler_by_class_name(type(item).__name__) + state = handler.serialize_state(item) + restored.append(handler.deserialize_state(state, item.meta_state)) + assert all(isinstance(c, DeepseekV41Cache) for c in restored) + np.testing.assert_allclose( + model(mx.array([[9]]), cache=restored), + model(mx.array([[3, 4, 5, 6, 7, 9]]))[:, -1:], + atol=1e-5, + ) + + +def write_checkpoint(tmp_path, vision=True, **config_overrides): + import json + import re + + from mlx.utils import tree_flatten + from tokenizers import Tokenizer, models, pre_tokenizers + from transformers import PreTrainedTokenizerFast + + from omlx.patches.deepseek_v41.model import Model + + c = tiny( + vision_n_layers=1 if vision else 0, + vision_dim=32, + vision_n_heads=4, + vision_inter_dim=32, + vision_patch_size=2, + vision_min_pixels=64, + vision_max_n_token=32, + image_token_id=63, + **config_overrides, + ) + model = Model(c) + source = tmp_path / "source" + source.mkdir() + weights = {} + for name, value in tree_flatten(model.parameters()): + name = name.removeprefix("language_model.") + match = re.match(r"((?:layers|mtp)\.\d+\.ffn\.experts)\.(w[123])\.weight", name) + if match: + for e in range(value.shape[0]): + weights[f"{match[1]}.{e}.{match[2]}.weight"] = value[e] + else: + weights[ + name.replace(".ffn.", ".mlp.") if name.startswith("vision.") else name + ] = value + mx.save_safetensors(str(source / "model.safetensors"), weights) + config = { + "model_type": "deepseek_v41", + "text_config": asdict(c), + "image_token_id": 63, + } + if vision: + config["vision_config"] = { + "num_hidden_layers": 1, + "hidden_size": 32, + "num_attention_heads": 4, + "intermediate_size": 32, + "patch_size": 2, + "max_image_tokens": 32, + "min_pixels": 64, + } + (source / "config.json").write_text(json.dumps(config)) + (source / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": {k: "model.safetensors" for k in weights}}) + ) + special = [ + "<|begin▁of▁sentence|>", + "<|end▁of▁sentence|>", + "", + "hello", + "world", + "", + "<|User|>", + "<|Assistant|>", + "<|System|>", + "", + "", + ] + vocabulary = ( + special + [f"t{i}" for i in range(len(special), 63)] + ["<|deepseek_image|>"] + ) + backend = Tokenizer( + models.WordLevel(dict(zip(vocabulary, range(64))), unk_token="") + ) + backend.pre_tokenizer = pre_tokenizers.Whitespace() + tokenizer = PreTrainedTokenizerFast( + tokenizer_object=backend, + bos_token=special[0], + eos_token=special[1], + pad_token="", + unk_token="", + additional_special_tokens=special[6:] + [vocabulary[-1]], + ) + tokenizer.save_pretrained(source) + return source, model + + +def test_dspark_matches_official_single_pass_reference(expected): + c = tiny( + preserve_mtp=True, + n_mtp_layers=3, + dspark_block_size=3, + dspark_noise_token_id=2, + dspark_target_layer_ids=(2, 3, 4), + dspark_n_routed_experts=2, + dspark_n_activated_experts=1, + dspark_markov_rank=32, + compress_ratios=(0, 2, 2, 1, 1, 0, 0, 0), + temperature=0, + ) + model = LanguageModel(c) + load_reference_weights(model) + target, draft = model.make_cache(), model.make_dspark_cache() + index = 0 + for start, ids in [(0, [3, 4, 5, 6, 7]), (5, [8]), (6, [9])]: + logits, hidden = model(mx.array([ids]), cache=target, return_dspark_hidden=True) + np.testing.assert_allclose( + hidden, expected[f"dspark_{index}"], atol=2e-5, rtol=2e-4 + ) + np.testing.assert_allclose( + logits[:, -1], expected[f"dspark_{index + 1}"], atol=2e-5, rtol=2e-4 + ) + index += 2 + actual = model.forward_spec(mx.array([[10]]), hidden, draft) + if start == 0: + assert actual is None + else: + np.testing.assert_array_equal(actual[0], expected[f"dspark_{index}"]) + for component in [1, 2]: + np.testing.assert_allclose( + actual[component], + expected[f"dspark_{index + component}"], + atol=3e-5, + rtol=3e-4, + ) + index += 3 + assert all(item.offset == start + len(ids) for item in draft) + + +@pytest.mark.parametrize("preserve", [False, True]) +def test_convert_preserves_complete_dspark(tmp_path, preserve): + import json + + from mlx.utils import tree_flatten + + from omlx.patches.deepseek_v41.convert import convert + from omlx.patches.deepseek_v41.loading import load + + source, before = write_checkpoint( + tmp_path, + preserve_mtp=True, + n_mtp_layers=3, + dspark_block_size=3, + dspark_noise_token_id=2, + dspark_target_layer_ids=(2, 3, 4), + dspark_n_routed_experts=2, + dspark_n_activated_experts=1, + dspark_markov_rank=32, + compress_ratios=(0, 2, 2, 1, 1, 0, 0, 0), + ) + target = tmp_path / "converted" + convert(source, target, preserve_mtp=preserve) + after, _ = load(target) + direct, _ = load(source, preserve_mtp=preserve) + try: + expected = dict(tree_flatten(before.parameters())) + for loaded in (after, direct): + values = dict(tree_flatten(loaded.parameters())) + assert any(".mtp." in name for name in values) == preserve + for name, value in values.items(): + np.testing.assert_array_equal(value, expected[name]) + assert loaded.config.preserve_mtp == preserve + config = json.loads((target / "config.json").read_text()) + assert config["omlx_deepseek_v41"]["preserve_mtp"] == preserve + finally: + after.close() + direct.close() + + +def test_conversion_loading_and_image_path(tmp_path): + from PIL import Image + + from omlx.models.vlm import VLMModelAdapter + from omlx.patches.deepseek_v41.convert import convert + from omlx.patches.deepseek_v41.loading import load + + source, before = write_checkpoint(tmp_path) + target = tmp_path / "converted" + convert(source, target) + model, processor = load(target) + images = [Image.new("RGB", (6, 8), "red"), Image.new("RGB", (8, 6), "blue")] + prompt = processor.apply_chat_template( + [ + { + "role": "user", + "content": [ + {"type": "text", "text": "hello"}, + {"type": "image", "url": "first"}, + {"type": "text", "text": "world"}, + {"type": "image", "url": "second"}, + ], + } + ], + enable_thinking=False, + ) + inputs = processor(text=[prompt], images=images) + features = model.get_input_embeddings(**inputs) + expected = before(**inputs) + adapter = VLMModelAdapter(model) + actual = adapter( + inputs["input_ids"], + inputs_embeds=features.inputs_embeds, + cache=adapter.make_cache(), + ) + np.testing.assert_allclose(actual, expected, atol=1e-5) + model.close() + + +def test_batch_generator_ragged_prefill_and_admission(): + from mlx_lm.generate import BatchGenerator + + model = LanguageModel(tiny()) + generator = BatchGenerator( + model, + max_tokens=3, + prefill_batch_size=2, + prefill_step_size=3, + sampler=lambda logits: mx.argmax(logits, -1), + ) + uids = generator.insert([[3, 4, 5, 6, 7], [8, 9]]) + result = {uid: [] for uid in uids} + while len(result[uids[0]]) < 1: + for response in generator.next()[1]: + result[response.uid].append(response.token) + late = generator.insert([[10, 11, 12]])[0] + result[late] = [] + for _ in range(20): + prefill, outputs = generator.next() + if not outputs and not prefill: + break + for response in outputs: + result[response.uid].append(response.token) + for uid, prompt in zip([*uids, late], [[3, 4, 5, 6, 7], [8, 9], [10, 11, 12]]): + expected = [] + for _ in range(3): + token = int(mx.argmax(model(mx.array([prompt + expected]))[0, -1]).item()) + expected.append(token) + assert result[uid] == expected + + +def test_dsml_and_reasoning_encoding(tmp_path): + from omlx.api.tool_calling import ToolCallStreamFilter, parse_tool_calls + from omlx.patches.deepseek_v41.convert import convert + from omlx.patches.deepseek_v41.loading import load + + source, _ = write_checkpoint(tmp_path, vision=False) + convert(source, tmp_path / "mlx") + model, processor = load(tmp_path / "mlx") + prompt = processor.apply_chat_template( + [{"role": "user", "content": "hello"}], reasoning_effort=33 + ) + assert "Reasoning Effort: 33" in prompt and prompt.endswith("") + text = '\n\n<|DSML| calls>\n<|DSML| invoke name="weather">\n<|DSML| parameter name="city" string="true">Seoul\n\n' + visible, calls = parse_tool_calls(text, processor.tokenizer) + assert len(calls) == 1 and calls[0].function.name == "weather" + assert "Seoul" in calls[0].function.arguments + stream_filter = ToolCallStreamFilter(processor.tokenizer) + output = "".join(stream_filter.feed(char) for char in text) + stream_filter.finish() + assert "<|DSML|" not in output + model.close() + + +def test_mxfp_repacking_has_exact_source_values(): + from omlx.patches.deepseek_v41.convert import repack_weight + + raw = np.arange(128, dtype=np.uint8).reshape(4, 32) + scale = np.full((1, 1), 125, np.uint8) + values, spec = repack_weight(raw, "F8_E4M3", scale, "F8_E8M0") + actual = mx.dequantize(values["weight"], values["scales"], group_size=32, **spec) + expected = decode_e4m3(raw) * 0.25 + # Code 127 is NaN and is outside a finite converted checkpoint. + np.testing.assert_array_equal( + np.asarray(actual.astype(mx.float32))[:3], expected[:3] + ) + raw4 = np.arange(64, dtype=np.uint8).reshape(4, 16) + values, spec = repack_weight(raw4, "I8", np.full((4, 1), 127, np.uint8), "F8_E8M0") + actual = mx.dequantize(values["weight"], values["scales"], group_size=32, **spec) + table = np.array([0, 0.5, 1, 1.5, 2, 3, 4, 6, 0, -0.5, -1, -1.5, -2, -3, -4, -6]) + expected = np.stack([table[raw4 & 15], table[raw4 >> 4]], -1).reshape(4, 32) + np.testing.assert_array_equal(actual.astype(mx.float32), expected) + + +def test_engram_gate_matches_official(expected): + from omlx.patches.deepseek_v41.engram import Engram + + c = tiny( + engram_layer_ids=(1,), + engram_num_embeddings=(72,), + engram_vocab_size=5, + engram_max_ngram_size=4, + engram_n_heads=2, + engram_head_dim=32, + ) + model = Engram(c, 0) + load_reference_weights(model, seed=41, scale=0.05) + rng = np.random.default_rng(41) + h = rng.normal(0, 1, (1, 3, 4, 32)).astype(np.float32) + ids = rng.integers(0, 72, (1, 3, 6), dtype=np.int32) + mask = np.array([[False, True, False]]) + actual = model(mx.array(h), ids, mx.array(mask)) + np.testing.assert_allclose(actual, expected["engram_0"], atol=2e-6, rtol=1e-5) + np.testing.assert_array_equal(actual[:, 1], h[:, 1]) + + +async def _run_vlm_engine(tmp_path, direct=False): + import asyncio + + from PIL import Image + + from omlx.engine.vlm import VLMBatchedEngine + from omlx.patches.deepseek_v41.convert import convert + from omlx.scheduler import SchedulerConfig + + source, _ = write_checkpoint(tmp_path) + target = source if direct else tmp_path / "mlx" + if not direct: + convert(source, target) + engine = VLMBatchedEngine( + str(target), + enable_thinking=False, + scheduler_config=SchedulerConfig(prefill_step_size=4), + ) + try: + await engine.start() + text = await asyncio.wait_for( + engine.generate("hello world", max_tokens=3, temperature=0), 30 + ) + # Random fixture weights can select EOS on the first step. EOS is + # excluded from completion_tokens by the engine contract. + assert text.finished, text + assert text.finish_reason in ("stop", "length"), text + assert 0 <= text.completion_tokens <= 3, text + assert text.completion_tokens > 0 or text.finish_reason == "stop", text + messages = [ + { + "role": "user", + "content": [ + {"type": "text", "text": "hello"}, + {"type": "image", "url": "prepared"}, + {"type": "text", "text": "world"}, + ], + } + ] + inputs = engine._prepare_vision_inputs( + messages, [Image.new("RGB", (6, 8), "red")] + ) + ids, embeds, extras = inputs[:3] + assert len(ids) == embeds.shape[1] and len(ids) > 3 + outputs = [] + async for chunk in engine.stream_generate( + ids, + max_tokens=3, + temperature=0, + vlm_inputs_embeds=embeds, + vlm_extra_kwargs=extras, + ): + outputs.append(chunk) + assert outputs and outputs[-1].finished + finally: + await engine.stop() + + +def raw_safetensors(path, tensors): + import json + import struct + + header, payload, offset = {}, [], 0 + for name, (value, dtype) in tensors.items(): + data = np.ascontiguousarray(value).tobytes() + header[name] = { + "dtype": dtype, + "shape": list(value.shape), + "data_offsets": [offset, offset + len(data)], + } + offset += len(data) + payload.append(data) + encoded = json.dumps(header).encode() + encoded += b" " * (-len(encoded) % 8) + path.write_bytes(struct.pack(" c.index_topk for state in cache) + np.testing.assert_allclose( + actual, model(mx.array([[3] * 32 + [4]]))[:, -1:], atol=1e-5 + ) + + +@pytest.mark.parametrize("dtype", [mx.float32, mx.bfloat16]) +@pytest.mark.parametrize( + "bits,group,e4m3", [(8, 32, False), (4, 32, False), (4, 16, True)] +) +def test_compiled_activation_is_exact(dtype, bits, group, e4m3): + from omlx.patches.deepseek_v41.quantization import ( + _quantize_activation, + quantize_activation, + ) + + mx.random.seed(49) + values = mx.random.normal((2, 19, 128)) * mx.power( + 2.0, mx.arange(-9, 10)[None, :, None] + ) + for x in [values, mx.zeros_like(values), values * 1e-20, values * 1e-38]: + x = x.astype(dtype) + expected = _quantize_activation(x, bits, group, e4m3) + actual = quantize_activation(x, bits, group, e4m3) + np.testing.assert_array_equal( + actual.astype(mx.float32), expected.astype(mx.float32) + ) + + +@pytest.mark.parametrize("quantized", [False, True]) +def test_sorted_prefill_preserves_weighted_expert_output(quantized): + from omlx.patches.deepseek_v41.language import MoE + from omlx.patches.deepseek_v41.quantization import QuantizedProjection + + mx.random.seed(1204) + layer = MoE(tiny()) + if quantized: + for name in ("w1", "w2", "w3"): + projection = getattr(layer.experts, name) + weight, scales = mx.quantize( + projection.weight.astype(mx.bfloat16), + bits=4, + group_size=32, + mode="mxfp4", + ) + setattr( + layer.experts, name, QuantizedProjection(weight, scales, 4, "mxfp4") + ) + for length in (1, 6, 32, 65): + x = mx.random.normal((2, length, 32)).astype( + mx.bfloat16 if quantized else mx.float32 + ) + indices, weights = layer.gate(x, None) + routed = layer.experts(x[..., None, None, :], indices, weights).squeeze(-2) + expected = ( + routed.astype(mx.float32).sum(-2) + + layer.shared_experts(x).astype(mx.float32) + ).astype(x.dtype) + actual = layer(x, None) + # Sorted GEMM may change FP32 reduction order relative to vector QMM. + np.testing.assert_allclose( + actual.astype(mx.float32), + expected.astype(mx.float32), + rtol=1e-5, + atol=2e-7, + ) + mx.eval(actual) + repeated = layer(x, None) + mx.eval(repeated) + np.testing.assert_array_equal( + actual.astype(mx.float32), repeated.astype(mx.float32) + ) + + +def test_load_preserves_bf16_head_without_changing_prefill_logits(tmp_path): + from omlx.patches.deepseek_v41.convert import convert + from omlx.patches.deepseek_v41.loading import load + + source, _ = write_checkpoint(tmp_path, vision=False) + filename = source / "model.safetensors" + weights = mx.load(str(filename)) + weights["head.weight"] = weights["head.weight"].astype(mx.bfloat16) + mx.eval(weights) + mx.save_safetensors(str(filename), weights) + expected = weights["head.weight"].astype(mx.float32) + target = tmp_path / "converted" + convert(source, target) + for path in (source, target): + model, _ = load(path) + try: + head = model.language_model.head + assert head.weight.dtype == mx.bfloat16 + np.testing.assert_array_equal(head.weight.astype(mx.float32), expected) + ids = mx.array([[3, 4, 5]]) + actual = model(ids) + mx.eval(actual) + head.weight = head.weight.astype(mx.float32) + reference = model(ids) + np.testing.assert_array_equal(actual, reference) + finally: + model.close() diff --git a/tests/test_deepseek_v41_activation.py b/tests/test_deepseek_v41_activation.py new file mode 100644 index 0000000000..beb561f0f8 --- /dev/null +++ b/tests/test_deepseek_v41_activation.py @@ -0,0 +1,167 @@ +"""FP8 activation fusion preserves quantization boundaries and input layouts.""" + +import mlx.core as mx +import mlx.nn as nn +import numpy as np +import pytest + +from omlx.patches.deepseek_v41.activation import quantize_swiglu_activation +from omlx.patches.deepseek_v41.quantization import ( + _compiled_quantize_activation, + quantize_activation, +) + + +@pytest.mark.parametrize("dtype", [mx.float32, mx.float16, mx.bfloat16]) +def test_fp8_activation_midpoints_and_scale_boundaries(dtype): + codes = mx.from_fp8(mx.arange(127, dtype=mx.uint8), dtype=mx.float32) + levels = np.asarray(codes) + mid = (levels[:-1] + levels[1:]) / 2 + values = np.concatenate( + [ + mid, + np.nextafter(mid, np.float32(-np.inf)), + np.nextafter(mid, np.float32(np.inf)), + ] + ) + rows = np.zeros((len(values) * 2, 32), np.float32) + rows[:, 0] = np.concatenate([values, -values]) + rows[:, -1] = 448 + exponents = [-10, 0, 6] if dtype == mx.float16 else [-110, -10, 0, 10, 110] + for exponent in exponents: + x = mx.array(rows * np.float32(2.0**exponent)).astype(dtype) + expected = _compiled_quantize_activation(x) + actual = quantize_activation(x) + np.testing.assert_array_equal( + actual.astype(mx.float32), expected.astype(mx.float32) + ) + # Move the group maximum across power-of-two scale transitions. + anchors = np.array( + [ + np.nextafter(np.float32(448), np.float32(0)), + 448, + np.nextafter(np.float32(448), np.float32(np.inf)), + ], + np.float32, + ) + x = mx.array(np.repeat(anchors[:, None], 32, axis=1)).astype(dtype) + np.testing.assert_array_equal( + quantize_activation(x).astype(mx.float32), + _compiled_quantize_activation(x).astype(mx.float32), + ) + + +@pytest.mark.parametrize("dtype", [mx.float32, mx.float16, mx.bfloat16]) +@pytest.mark.parametrize("length", [1, 3, 33]) +def test_fp8_activation_noncontiguous_rows_and_repeat(dtype, length): + mx.random.seed(711) + x = mx.random.normal((2, 64, length)).astype(dtype).transpose(0, 2, 1) + expected = _compiled_quantize_activation(x) + actual = quantize_activation(x) + np.testing.assert_array_equal( + actual.astype(mx.float32), expected.astype(mx.float32) + ) + np.testing.assert_array_equal( + actual.astype(mx.float32), quantize_activation(x).astype(mx.float32) + ) + + +def test_fp8_activation_empty_and_invalid_width(): + x = mx.zeros((1, 0, 64), mx.bfloat16) + assert quantize_activation(x).shape == x.shape + with pytest.raises(ValueError, match="width"): + quantize_activation(mx.zeros((1, 33))) + + +@pytest.mark.parametrize("dtype", [mx.float32, mx.float16, mx.bfloat16]) +@pytest.mark.parametrize("limit", [0.0, 3.5, 10.0]) +@pytest.mark.parametrize("weighted", [False, True]) +@pytest.mark.parametrize("input_dtype", [mx.float32, mx.bfloat16]) +def test_swiglu_fusion_preserves_weighted_intermediate_rounding( + dtype, limit, weighted, input_dtype +): + mx.random.seed(749) + gate = (mx.random.normal((17, 1, 128)) * 9).astype(input_dtype) + up = (mx.random.normal(gate.shape) * 11).astype(input_dtype) + weights = mx.linspace(0, 2, 17) if weighted else None + gate_fp32, up_fp32 = gate.astype(mx.float32), up.astype(mx.float32) + clipped_gate = mx.minimum(gate_fp32, limit) if limit else gate_fp32 + clipped_up = mx.clip(up_fp32, -limit, limit) if limit else up_fp32 + value = nn.silu(clipped_gate) * clipped_up + if weights is not None: + value *= weights[:, None, None] + expected = _compiled_quantize_activation(value.astype(dtype)) + actual = quantize_swiglu_activation(gate, up, weights, dtype, limit) + np.testing.assert_array_equal( + actual.astype(mx.float32), expected.astype(mx.float32) + ) + np.testing.assert_array_equal( + actual.astype(mx.float32), + quantize_swiglu_activation(gate, up, weights, dtype, limit).astype(mx.float32), + ) + + +@pytest.mark.parametrize("dtype", [mx.bfloat16, mx.float16, mx.float32]) +@pytest.mark.parametrize("weighted", [False, True]) +@pytest.mark.parametrize("limit", [0.0, 3.5, 10.0]) +def test_paired_swiglu_preserves_row_and_quantization_boundaries( + dtype, weighted, limit +): + from omlx.patches.deepseek_v41.activation import quantize_paired_swiglu_activation + + mx.random.seed(882) + pair = (mx.random.normal((17, 1, 256)) * 11).astype(dtype) + weights = mx.linspace(0, 2, 17) if weighted else None + expected = quantize_swiglu_activation( + pair[..., :128], pair[..., 128:], weights, dtype, limit + ) + actual = quantize_paired_swiglu_activation(pair, weights, dtype, limit) + repeated = quantize_paired_swiglu_activation(pair, weights, dtype, limit) + np.testing.assert_array_equal( + actual.astype(mx.float32), expected.astype(mx.float32) + ) + np.testing.assert_array_equal( + actual.astype(mx.float32), repeated.astype(mx.float32) + ) + + +@pytest.mark.parametrize("device", [mx.cpu, mx.gpu]) +def test_normal_scales_are_exact_and_nonzero(device): + from omlx.patches.deepseek_v41.quantization import _normal_power_of_two + + with mx.stream(device): + exponent = mx.arange(-126, 128, dtype=mx.float32) + actual = _normal_power_of_two(exponent) + compiled = mx.compile(_normal_power_of_two)(exponent) + expected = np.exp2(np.arange(-126, 128, dtype=np.float32)) + np.testing.assert_array_equal(actual, expected) + np.testing.assert_array_equal(compiled, expected) + + +@pytest.mark.parametrize("bits,group,e4m3", [(8, 32, False), (4, 32, False), (4, 16, True)]) +def test_zero_activation_groups_remain_zero(bits, group, e4m3): + from omlx.patches.deepseek_v41.quantization import ( + _quantize_activation, + pack_activation, + unpack_activation, + ) + + x = mx.zeros((3, 128), mx.float32) + for result in ( + _quantize_activation(x, bits, group, e4m3), + _compiled_quantize_activation(x, bits, group, e4m3), + quantize_activation(x, bits, group, e4m3), + unpack_activation(pack_activation(x, bits, group, e4m3), bits, group, e4m3, mx.float32), + ): + # This rejects NaNs explicitly, including matching NaNs in both paths. + assert mx.all(mx.isfinite(result)).item() + np.testing.assert_array_equal(result, np.zeros((3, 128), np.float32)) + + +def test_fp8_kernel_preserves_exact_power_of_two_scaled_values(): + # Every scale whose maximum finite FP8 value fits in a normal FP32. + # A transcendental exp2 approximation can shift these values and FP8 ties. + exponents = np.arange(-126, 119, dtype=np.int32) + rows = np.repeat(np.ldexp(np.float32(448), exponents)[:, None], 32, axis=1) + actual = quantize_activation(mx.array(rows)) + np.testing.assert_array_equal(actual, rows) diff --git a/tests/test_deepseek_v41_affine.py b/tests/test_deepseek_v41_affine.py new file mode 100644 index 0000000000..a1633410c8 --- /dev/null +++ b/tests/test_deepseek_v41_affine.py @@ -0,0 +1,114 @@ +"""All oQ affine widths use the V4.1 expert execution optimizations.""" + +import mlx.core as mx +import numpy as np +import pytest + +from omlx.custom_kernels.glm_moe_dsa import fast +from omlx.patches.deepseek_v41.config import ModelConfig +from omlx.patches.deepseek_v41.language import Expert +from omlx.patches.deepseek_v41.quantization import QuantizedProjection + + +def expert_for(bits): + expert = Expert(ModelConfig(dim=64, moe_inter_dim=64, n_routed_experts=4), True) + widths = (bits,) * 3 if isinstance(bits, int) else bits + for name, width in zip(("w1", "w3", "w2"), widths): + weight, scales, biases = mx.quantize( + (mx.random.normal((4, 64, 64)) * 0.1).astype(mx.bfloat16), + group_size=64, + bits=width, + mode="affine", + ) + setattr( + expert, + name, + QuantizedProjection( + weight, + scales, + width, + "affine", + biases, + group_size=64, + ), + ) + return expert + + +@pytest.mark.parametrize("bits", [2, 3, 4, 6, 8, (2, 3, 6)]) +@pytest.mark.skipif( + not fast.has_symbol("deepseek_v41_grouped_expert"), + reason="Requires the native extension", +) +def test_affine_decode_grouped_matches_stock(monkeypatch, bits): + mx.random.seed(948) + expert = expert_for(bits) + x = mx.random.normal((1, 1, 1, 1, 64)).astype(mx.bfloat16) + ids = mx.array([[[0, 2]]], mx.uint32) + weights = mx.array([[[0.3, 0.7]]]) + calls = [] + original = fast.deepseek_v41_grouped_expert + + def counted(*args): + calls.append(True) + return original(*args) + + monkeypatch.setattr(fast, "deepseek_v41_grouped_expert", counted) + actual = expert(x, ids, weights) + repeated = expert(x, ids, weights) + assert len(calls) == 2 + with monkeypatch.context() as patch: + patch.setattr(fast, "has_symbol", lambda _: False) + expected = expert(x, ids, weights) + np.testing.assert_array_equal( + actual.astype(mx.float32), expected.astype(mx.float32) + ) + np.testing.assert_array_equal( + actual.astype(mx.float32), repeated.astype(mx.float32) + ) + + +@pytest.mark.parametrize("bits", [2, 3, 4, 6, 8, (2, 3, 6)]) +@pytest.mark.skipif( + not fast.has_symbol("deepseek_affine_gather_qmm_blocks"), + reason="Requires the native extension", +) +def test_affine_prefill_native_blocks_and_pair(monkeypatch, bits): + mx.random.seed(714) + expert = expert_for(bits) + x = mx.random.normal((1024, 1, 64)).astype(mx.bfloat16) + ids = mx.repeat(mx.arange(4, dtype=mx.uint32), 256) + weights = mx.random.uniform(shape=(1024,)) + calls = [] + original = fast.deepseek_affine_gather_qmm_pair_concat_blocks + + def counted(*args): + calls.append(True) + return original(*args) + + monkeypatch.setattr(fast, "deepseek_affine_gather_qmm_pair_concat_blocks", counted) + actual = expert(x, ids, weights, sorted_indices=True) + assert calls == ([True] if isinstance(bits, int) else []) + with monkeypatch.context() as patch: + patch.setattr(fast, "has_symbol", lambda _: False) + expected = expert(x, ids, weights, sorted_indices=True) + np.testing.assert_allclose( + actual.astype(mx.float32), expected.astype(mx.float32), rtol=0.03, atol=0.0002 + ) + # Exercise each packed bit layout directly, independently of nonlinearities. + projection = expert.w1 + reference = mx.gather_qmm( + x, + projection.weight, + projection.scales, + projection.biases, + rhs_indices=ids, + group_size=64, + bits=projection.bits, + mode="affine", + sorted_indices=True, + ) + native = projection.project_quantized(x, ids, True) + np.testing.assert_allclose( + native.astype(mx.float32), reference.astype(mx.float32), rtol=0.03, atol=0.02 + ) diff --git a/tests/test_deepseek_v41_attention_projection.py b/tests/test_deepseek_v41_attention_projection.py new file mode 100644 index 0000000000..713d0ee39c --- /dev/null +++ b/tests/test_deepseek_v41_attention_projection.py @@ -0,0 +1,62 @@ +"""Attention input sharing preserves each projection's quantization setting.""" + +import mlx.core as mx +import numpy as np +import pytest +from test_deepseek_v41 import tiny + +from omlx.patches.deepseek_v41.cache import DeepseekV41Cache +from omlx.patches.deepseek_v41.language import Attention +from omlx.patches.deepseek_v41.quantization import QuantizedProjection + + +@pytest.mark.parametrize( + "quantize_q,quantize_kv", + [(True, True), (True, False), (False, True), (False, False)], +) +@pytest.mark.parametrize("length", [1, 33]) +@pytest.mark.parametrize( + "mode,bits", [("mxfp8", 8)] + [("affine", b) for b in (2, 3, 4, 6, 8)] +) +def test_attention_shared_inputs_match_individual_calls( + monkeypatch, quantize_q, quantize_kv, length, mode, bits +): + mx.random.seed(964) + attention = Attention(tiny(), 0) + for name, quantizes in [("wq_a", quantize_q), ("wkv", quantize_kv)]: + packed, scales, *biases = mx.quantize( + mx.random.normal((32, 32)).astype(mx.bfloat16) * 0.05, + mode=mode, + bits=bits, + group_size=32, + ) + setattr( + attention, + name, + QuantizedProjection( + packed, + scales, + bits, + mode, + biases[0] if biases else None, + quantize_input=quantizes, + ), + ) + for name in ("wq_b", "wo_a", "wo_b"): + projection = getattr(attention, name) + projection.weight = projection.weight.astype(mx.bfloat16) + x = mx.random.normal((1, length, 32)).astype(mx.bfloat16) + cache = DeepseekV41Cache() + actual = attention(x, cache, {}, 0) + with monkeypatch.context() as patch: + patch.setattr( + Attention, + "_input_projections", + lambda self, value: (self.wq_a(value), self.wkv(value)), + ) + expected_cache = DeepseekV41Cache() + expected = attention(x, expected_cache, {}, 0) + np.testing.assert_array_equal( + actual.astype(mx.float32), expected.astype(mx.float32) + ) + np.testing.assert_array_equal(cache[1], expected_cache[1]) diff --git a/tests/test_deepseek_v41_attention_rounding.py b/tests/test_deepseek_v41_attention_rounding.py new file mode 100644 index 0000000000..982ea1d64b --- /dev/null +++ b/tests/test_deepseek_v41_attention_rounding.py @@ -0,0 +1,170 @@ +"""Independent 64-key online-softmax oracle with the official BF16 PV boundary.""" + +import mlx.core as mx +import numpy as np +import pytest + +from omlx.custom_kernels.glm_moe_dsa import fast +from omlx.patches.deepseek_v41.kernels import packed_sparse_attention +from omlx.patches.deepseek_v41.quantization import pack_activation, unpack_activation + + +def reference(q, window, pooled, wi, ci, sink, scale, round_probabilities=True): + keys = [] + masks = [] + for packed, ids, bits, group, e4 in [ + (window, wi, 8, 32, False), + (pooled, ci, 4, 16, True), + ]: + if not ids.shape[-1]: + continue + valid = (ids >= 0) & (ids < packed.shape[1]) + if packed.shape[1]: + values = unpack_activation(packed, bits, group, e4, mx.bfloat16)[0] + values = values[mx.clip(ids, 0, packed.shape[1] - 1)].astype(mx.float32) + else: + values = mx.zeros((*ids.shape, q.shape[-1])) + keys.append(values) + masks.append(valid) + if not keys: + return mx.zeros_like(q) + keys, masks = mx.concatenate(keys, -2), mx.concatenate(masks, -1) + maximum = mx.full(q.shape[:-1], -1e30) + denominator = mx.zeros(q.shape[:-1]) + numerator = mx.zeros(q.shape) + for start in range(0, keys.shape[-2], 64): + kv = keys[:, :, start : start + 64] + score = q.astype(mx.float32) @ kv.swapaxes(-1, -2) * scale + score = mx.where(masks[:, :, None, start : start + 64], score, -float("inf")) + new_maximum = mx.maximum(maximum, mx.max(score, -1)) + correction = mx.exp(maximum - new_maximum) + p = mx.exp(score - new_maximum[..., None]) + denominator = denominator * correction + mx.sum(p, -1) + if round_probabilities: + p = p.astype(mx.bfloat16).astype(mx.float32) + numerator = numerator * correction[..., None] + p @ kv + maximum = new_maximum + return (numerator / (denominator + mx.exp(sink - maximum))[..., None]).astype( + q.dtype + ) + + +@pytest.mark.parametrize( + "length,window_count,pooled_count", + [(1, 128, 513), (7, 135, 129), (17, 17, 19), (65, 65, 77), (129, 129, 97)], +) +def test_packed_attention_preserves_online_bf16_probability_rounding( + length, window_count, pooled_count +): + mx.random.seed(103 + length) + q = mx.random.normal((1, length, 64, 512)).astype(mx.bfloat16) + window = pack_activation(mx.random.normal((1, window_count, 512))) + pooled = pack_activation(mx.random.normal((1, pooled_count, 512)), 4, 16, True) + start = window_count - length + pos = mx.arange(start, start + length) + width = min(length, 128) if start == 0 else 128 + first = mx.maximum(pos[:, None] - 127, 0) if start == 0 else pos[:, None] - 127 + wi = first + mx.arange(width) + wi = mx.where((wi >= 0) & (wi <= pos[:, None]), wi, -1)[None] + ci = mx.broadcast_to(mx.arange(pooled_count), (1, length, pooled_count)) + ci = mx.where(ci < (pos[None, :, None] + 1) // 4, ci, -1) + sink = mx.linspace(-2.1, 3.7, 64) + args = (q, window, pooled, wi, ci, sink, 512**-0.5) + expected = reference(*args) + unrounded = reference(*args, round_probabilities=False) + actual = packed_sparse_attention(*args) + mx.eval(expected, unrounded, actual) + + def rms(value): + return mx.sqrt( + mx.mean((value.astype(mx.float32) - expected.astype(mx.float32)) ** 2) + ).item() + + assert rms(actual) < rms(unrounded) * 0.2 + assert mx.array_equal(actual, packed_sparse_attention(*args)).item() + if length > 1 and fast.has_symbol("deepseek_v41_packed_attention"): + native = fast.deepseek_v41_packed_attention( + q.transpose(0, 2, 1, 3), + window[:, None], + pooled, + ci[:, None].astype(mx.uint32), + sink, + 512**-0.5, + start, + 4, + 128, + ).transpose(0, 2, 1, 3) + mx.eval(native) + assert rms(native) < rms(unrounded) * 0.2 + + +def test_masked_tiles_and_sink_stay_finite(): + q = mx.ones((1, 2, 5, 32), mx.bfloat16) + window = mx.zeros((1, 0, 33), mx.uint8) + pooled = mx.zeros((1, 0, 18), mx.uint8) + indices = mx.full((1, 2, 193), -1, mx.int32) + empty = mx.zeros((1, 2, 0), mx.int32) + result = packed_sparse_attention( + q, window, pooled, indices, empty, mx.array([-10000, -3, 0, 4, 10000]), 1 + ) + mx.eval(result) + np.testing.assert_array_equal(result.astype(mx.float32), 0) + + +def test_rounding_tracks_growing_and_strided_kv(): + mx.random.seed(91) + q = mx.random.normal((1, 1, 5, 64))[..., ::2].astype(mx.bfloat16) + window = pack_activation(mx.random.normal((1, 256, 32)))[:, ::2] + wi = mx.arange(128)[None, None] + ci = mx.arange(34, dtype=mx.int32)[::2][None, None] + sink = mx.linspace(-2, 2, 5) + for count in [0, 4, 7, 70, 129, 4]: + pooled = pack_activation(mx.random.normal((1, count * 2, 32)), 4, 16, True)[ + :, ::2 + ] + args = (q, window, pooled, wi, ci, sink, 32**-0.5) + actual, expected = packed_sparse_attention(*args), reference(*args) + mx.eval(actual, expected) + np.testing.assert_allclose( + actual.astype(mx.float32), + expected.astype(mx.float32), + atol=0.002, + rtol=0.002, + ) + + +@pytest.mark.parametrize("count", [1025, 2051]) +def test_rounding_across_threadgroup_capacity(count): + mx.random.seed(123) + q = mx.random.normal((1, 1, 5, 32)).astype(mx.bfloat16) + window = pack_activation(mx.random.normal((1, 128, 32))) + pooled = pack_activation(mx.random.normal((1, count, 32)), 4, 16, True) + wi = mx.arange(128)[None, None] + ci = mx.arange(count)[None, None] + args = (q, window, pooled, wi, ci, mx.linspace(-3, 3, 5), 32**-0.5) + actual, expected = packed_sparse_attention(*args), reference(*args) + mx.eval(actual, expected) + np.testing.assert_allclose( + actual.astype(mx.float32), expected.astype(mx.float32), atol=0.002, rtol=0.002 + ) + + +@pytest.mark.parametrize("heads,dim,length", [(9, 96, 1), (64, 512, 1), (8, 32, 3)]) +def test_matrix_rounding_with_full_candidate_lists(heads, dim, length): + mx.random.seed(71) + q = mx.random.normal((1, length, heads, dim)).astype(mx.bfloat16) + window = pack_activation(mx.random.normal((1, 128, dim))) + pooled = pack_activation(mx.random.normal((1, 513, dim)), 4, 16, True) + wi = mx.broadcast_to(mx.arange(128), (1, length, 128)) + ci = mx.broadcast_to(mx.arange(513), (1, length, 513)) + args = (q, window, pooled, wi, ci, mx.linspace(-2, 2, heads), dim**-0.5) + actual = packed_sparse_attention(*args) + expected = reference(*args) + unrounded = reference(*args, round_probabilities=False) + error = mx.mean((actual.astype(mx.float32) - expected.astype(mx.float32)) ** 2) + baseline = mx.mean( + (unrounded.astype(mx.float32) - expected.astype(mx.float32)) ** 2 + ) + mx.eval(error, baseline) + assert error.item() < baseline.item() * 0.04 + assert mx.array_equal(actual, packed_sparse_attention(*args)).item() diff --git a/tests/test_deepseek_v41_calibration.py b/tests/test_deepseek_v41_calibration.py new file mode 100644 index 0000000000..cda7472025 --- /dev/null +++ b/tests/test_deepseek_v41_calibration.py @@ -0,0 +1,367 @@ +"""V4.1 mixed-format projections expose their real calibration inputs.""" + +import mlx.core as mx +import mlx.nn as nn +import numpy as np +import pytest + +from omlx.oq import OQImatrixCollector +from omlx.patches.deepseek_v41.config import ModelConfig +from omlx.patches.deepseek_v41.language import Expert +from omlx.patches.deepseek_v41.quantization import QuantizedProjection + + +@pytest.mark.parametrize("length", [2, 32]) +def test_capture_dense_and_routed_quantized_projection_inputs(length): + mx.random.seed(908) + model = nn.Module() + model.dense = QuantizedProjection( + *mx.quantize( + mx.random.normal((64, 64)).astype(mx.bfloat16) * 0.1, + bits=8, + group_size=32, + mode="mxfp8", + ), + 8, + "mxfp8", + ) + model.expert = Expert( + ModelConfig(dim=64, moe_inter_dim=64, n_routed_experts=4), True + ) + for name in ("w1", "w3", "w2"): + w, s = mx.quantize( + mx.random.normal((4, 64, 64)).astype(mx.bfloat16) * 0.1, + bits=4, + group_size=32, + mode="mxfp4", + ) + setattr(model.expert, name, QuantizedProjection(w, s, 4, "mxfp4")) + x = mx.random.normal((1, length, 64)).astype(mx.bfloat16) + ids = mx.broadcast_to(mx.array([[[0, 2]]], mx.uint32), (1, length, 2)) + weights = mx.broadcast_to(mx.array([[[0.3, 0.7]]]), ids.shape) + + def forward(): + value = model.dense(x) + return model.expert(value[..., None, None, :], ids, weights) + + expected = forward() + mx.eval(expected) + original_dense = model.dense + collector = OQImatrixCollector() + try: + assert collector.install(model) == 4 + actual = forward() + mx.eval(actual) + assert set(collector.entries) == { + "dense", + "expert.w1", + "expert.w3", + "expert.w2", + } + np.testing.assert_array_equal(collector.entries["dense"].counts, [length]) + np.testing.assert_allclose( + collector.entries["dense"].in_sum2, + np.square(np.asarray(x.astype(mx.float32))).sum(axis=(0, 1)), + rtol=1e-6, + ) + for name in ("w1", "w3", "w2"): + entry = collector.entries["expert." + name] + assert entry.in_sum2.shape == (4, 64) + np.testing.assert_array_equal(entry.counts, [length, 0, length, 0]) + assert np.isfinite(entry.in_sum2).all() + np.testing.assert_allclose( + actual.astype(mx.float32), + expected.astype(mx.float32), + rtol=0.03, + atol=0.0002, + ) + finally: + collector.restore(model) + assert model.dense is original_dense + + +def test_inventory_matches_streamed_projection_shapes_and_bytes(tmp_path): + import json + + from test_deepseek_v41 import write_checkpoint + + from omlx.patches.deepseek_v41.convert import iter_source_weights + from omlx.patches.deepseek_v41.oq_inventory import projection_inventory + + source, _ = write_checkpoint(tmp_path) + config = json.loads((source / "config.json").read_text()) + mapping = json.loads((source / "model.safetensors.index.json").read_text())[ + "weight_map" + ] + inventory = projection_inventory(source, config, mapping) + visited = set() + for tensors, specs in iter_source_weights(source, config, mapping): + for key, weight in tensors.items(): + if not key.endswith(".weight"): + continue + name = key.removesuffix(".weight") + shape = list(weight.shape) + if name in specs: + shape[-1] = shape[-1] * 32 // specs[name]["bits"] + assert tuple(shape) == inventory[name]["shape"] + assert ( + sum(t.nbytes for k, t in tensors.items() if k.startswith(name + ".")) + == inventory[name]["source_bytes"] + ) + visited.add(name) + assert visited == set(inventory) + + +def test_calibration_resume_matches_single_pass(monkeypatch): + import omlx.oq as oq + from omlx.patches.deepseek_v41.calibration import collect_imatrix + + class Core(nn.Module): + def __init__(self): + super().__init__() + self.proj = nn.Linear(4, 8) + + def make_cache(self): + return [] + + def __call__(self, x, cache): + return self.proj(x.astype(mx.float32)) + + model = nn.Module() + model.language_model = Core() + samples = mx.arange(16).reshape(4, 4) + monkeypatch.setattr( + oq, "_load_calibration_data", lambda tokenizer, dataset, n, length: samples[:n] + ) + full, _ = collect_imatrix(model, None, num_samples=4, seq_length=4) + first, metadata = collect_imatrix(model, None, num_samples=2, seq_length=4) + original = first["language_model.proj"].counts.copy() + progress = [] + resumed, _ = collect_imatrix( + model, + None, + num_samples=4, + seq_length=4, + initial=oq.OQImatrixData(first, metadata, path="fixture"), + progress=lambda done, total, entries: progress.append(done), + ) + assert progress == [3, 4] + np.testing.assert_array_equal(first["language_model.proj"].counts, original) + for name in full: + np.testing.assert_array_equal(full[name].counts, resumed[name].counts) + np.testing.assert_array_equal(full[name].in_sum2, resumed[name].in_sum2) + + +def test_official_collector_routes_v41_settings(monkeypatch): + from omlx import oq + from omlx.patches.deepseek_v41 import calibration + + received = {} + + def collect(path, **kwargs): + received.update(path=path, **kwargs) + return {}, {"marker": "v41"} + + monkeypatch.setattr(calibration, "collect_checkpoint_imatrix", collect) + + def callback(*args): + pass + + assert oq._collect_imatrix( + "source", + {"model_type": "deepseek_v41"}, + calib_dataset="custom", + num_samples=37, + seq_length=256, + progress_callback=callback, + progress_start=7, + progress_end=19, + ) == ({}, {"marker": "v41"}) + assert received == dict( + path="source", + calib_dataset="custom", + num_samples=37, + seq_length=256, + progress_callback=callback, + progress_start=7, + progress_end=19, + ) + + +def test_official_v41_collector_closes_model_on_cancel(monkeypatch): + from types import SimpleNamespace + + from omlx.patches.deepseek_v41 import calibration, loading + + events = [] + model = SimpleNamespace(close=lambda: events.append("close")) + + def load(path, **kwargs): + assert kwargs == {"engram_ssd_offload": True} + return model, SimpleNamespace(tokenizer="tokenizer") + + def collect(model, tokenizer, **kwargs): + assert tokenizer == "tokenizer" + kwargs["progress"](1, 2, {}) + + def cancel(*args): + raise RuntimeError("cancelled") + + monkeypatch.setattr(loading, "load", load) + monkeypatch.setattr(calibration, "collect_imatrix", collect) + monkeypatch.setattr(calibration.mx, "synchronize", lambda: events.append("sync")) + monkeypatch.setattr(calibration.mx, "clear_cache", lambda: events.append("clear")) + with pytest.raises(RuntimeError, match="cancelled"): + calibration.collect_checkpoint_imatrix( + "source", + calib_dataset="custom", + num_samples=2, + seq_length=512, + progress_callback=cancel, + ) + assert events == ["close", "sync", "clear"] + + +@pytest.mark.parametrize("sufficient_at, expected", [(2, 2), (4, 4), (99, 6)]) +def test_adaptive_calibration_stops_on_coverage_or_available_data( + monkeypatch, sufficient_at, expected +): + import omlx.oq as oq + from omlx.patches.deepseek_v41.calibration import collect_imatrix + + class Collector: + switch_capture_modules = 1 + + def __init__(self): + self.entries = {"expert": object()} + + def install(self, model): + return 1 + + def restore(self, model): + model.restored = True + + class Core: + calls = 0 + + def make_cache(self): + return [] + + def __call__(self, x, cache): + self.calls += 1 + return x + + from types import SimpleNamespace + + model = SimpleNamespace(language_model=Core(), restored=False) + requested = [] + + def samples(tokenizer, dataset, number, length): + requested.append(number) + return np.arange(12).reshape(6, 2) + + monkeypatch.setattr(oq, "OQImatrixCollector", Collector) + monkeypatch.setattr(oq, "_load_calibration_data", samples) + monkeypatch.setattr( + oq, "_imatrix_expert_coverage_stats", lambda entries: {"fixture": True} + ) + monkeypatch.setattr( + oq, + "_imatrix_expert_coverage_sufficient", + lambda stats, **kwargs: model.language_model.calls >= sufficient_at, + ) + # This test covers the sample scheduling and restoration, not GPU arithmetic. + monkeypatch.setattr(mx, "eval", lambda *args: None) + steps = [] + _, metadata = collect_imatrix( + model, + None, + num_samples=2, + seq_length=2, + adaptive=True, + progress=lambda done, total, entries: steps.append(done), + ) + assert requested == [16] + assert steps == list(range(1, expected + 1)) + assert metadata["processed_samples"] == expected + assert metadata["adaptive_max_samples"] == 6 + assert model.restored + + +@pytest.mark.parametrize("vision", ["vision.proj", "aligner.proj", "image_projection"]) +@pytest.mark.parametrize("calibrated_vision", [False, True]) +def test_affine_plan_preserves_vision_precision(vision, calibrated_vision): + from types import SimpleNamespace + + from omlx.patches.deepseek_v41.oq_inventory import build_affine_plan + + good = "language_model.layers.0.ffn.experts.w1" + missing_expert = "language_model.layers.1.ffn.experts.w1" + inventory = { + good: dict(shape=(128, 64, 64), source_bytes=278528), + missing_expert: dict(shape=(2, 64, 64), source_bytes=4352), + vision: dict(shape=(64, 64), source_bytes=8192), + } + imatrix = SimpleNamespace( + entries={ + good: SimpleNamespace(counts=np.ones(128)), + missing_expert: SimpleNamespace(counts=np.array([10, 0])), + } + ) + if calibrated_vision: + imatrix.entries[vision] = SimpleNamespace(counts=np.ones(1)) + budget = dict( + remaining_weights=dict(logical_parameters=536576, tensor_bytes=291072) + ) + specs, report = build_affine_plan( + inventory, + budget, + {"model_type": "deepseek_v41"}, + imatrix, + {0: 0.25, 1: 0.5}, + target=3.5, + cap=3.7, + ) + assert set(specs) == {good, missing_expert} + assert specs[good]["bits"] == 3 + assert specs[missing_expert]["bits"] == 3 + assert report["fixed_source_bytes"] == 8192 + assert report["tensor_bytes"] == 8192 + (524288 + 8192) * 7 // 16 + assert report["effective_bpw"] <= 3.7 + assert report["unobserved_experts"] == {missing_expert: [1]} + assert report["unobserved_expert_policy"] == "uniform_importance_at_allocated_bits" + assert report["preserved_modules"][vision] == "precision_policy" + with pytest.raises(ValueError, match="above.*cap"): + build_affine_plan( + inventory, + budget, + {"model_type": "deepseek_v41"}, + imatrix, + {0: 0.25, 1: 0.5}, + target=3.0, + cap=3.1, + ) + + +@pytest.mark.parametrize( + "model_type,collection,missing", + [ + ("deepseek_v41", {"uncalibrated_policy": "preserve_source_precision"}, False), + ("deepseek_v41", None, True), + ("deepseek_v41", {}, True), + ("qwen4_exp", {"uncalibrated_policy": "preserve_source_precision"}, True), + ], +) +def test_mtp_cache_reuse_requires_v41_preservation_policy( + monkeypatch, model_type, collection, missing +): + from omlx import oq + from omlx.utils import model_loading + + monkeypatch.setattr(model_loading, "_has_mtp_heads", lambda config: True) + monkeypatch.setattr(model_loading, "_checkpoint_has_mtp_weights", lambda path: True) + cache = oq.OQImatrixData({}, {"collection": collection}, "fixture") + assert ( + oq._oqe_cache_missing_mtp_entries(cache, {"model_type": model_type}, "source") + is missing + ) diff --git a/tests/test_deepseek_v41_grouped_expert.py b/tests/test_deepseek_v41_grouped_expert.py new file mode 100644 index 0000000000..85d1753859 --- /dev/null +++ b/tests/test_deepseek_v41_grouped_expert.py @@ -0,0 +1,144 @@ +"""Grouped expert execution preserves quantization and stream ownership.""" + +import mlx.core as mx +import numpy as np +import pytest + +from omlx.custom_kernels.glm_moe_dsa import fast +from omlx.patches.deepseek_v41.activation import quantize_swiglu_activation +from omlx.patches.deepseek_v41.config import ModelConfig +from omlx.patches.deepseek_v41.language import Expert +from omlx.patches.deepseek_v41.quantization import QuantizedProjection + +pytestmark = pytest.mark.skipif( + not fast.has_symbol("deepseek_v41_grouped_expert"), + reason="Grouped expert extension is not built", +) + + +def make_graph(): + x = mx.ones((1, 1, 64), mx.bfloat16) + w, s = mx.quantize( + mx.ones((2, 64, 64), mx.bfloat16) * 0.03125, group_size=32, bits=4, mode="mxfp4" + ) + ids = mx.array([0, 1], mx.uint32) + + def q(value, left): + return mx.gather_qmm( + value, + w, + s, + lhs_indices=left, + rhs_indices=ids, + group_size=32, + bits=4, + mode="mxfp4", + ) + + gate = q(x, mx.zeros((2,), mx.uint32)) + up = q(x, mx.zeros((2,), mx.uint32)) + y = quantize_swiglu_activation(gate, up, mx.array([0.3, 0.7]), mx.bfloat16, 10) + return gate, up, y, q(y, ids) + + +def test_grouped_expert_async_streams_and_temporary_lifetime(): + streams = [mx.new_stream(mx.gpu), mx.new_stream(mx.gpu)] + outputs = [] + for i in range(12): + with mx.stream(streams[i % 2]): + graph = make_graph() + grouped = fast.deepseek_v41_grouped_expert(*graph) + mx.async_eval(grouped) + outputs.append((grouped, graph[-1])) + mx.clear_cache() + for actual, expected in outputs: + np.testing.assert_array_equal( + actual.astype(mx.float32), expected.astype(mx.float32) + ) + + +def test_grouped_expert_rejects_evaluated_graph(): + graph = make_graph() + mx.eval(*graph) + with pytest.raises(ValueError, match="unevaluated"): + fast.deepseek_v41_grouped_expert(*graph) + + +@pytest.mark.parametrize("length", [1, 2, 4, 6, 8]) +@pytest.mark.parametrize( + "mode,bits", + [ + ("mxfp4", 4), + ("affine", 2), + ("affine", 3), + ("affine", 4), + ("affine", 6), + ("affine", 8), + ], +) +def test_expert_dispatch_matches_unfused_and_repeats(monkeypatch, length, mode, bits): + mx.random.seed(847) + expert = Expert(ModelConfig(dim=64, moe_inter_dim=64, n_routed_experts=4), True) + for name in ("w1", "w3", "w2"): + packed = mx.quantize( + mx.random.normal((4, 64, 64)).astype(mx.bfloat16) * 0.05, + group_size=32 if mode == "mxfp4" else 64, + bits=bits, + mode=mode, + ) + setattr( + expert, + name, + QuantizedProjection( + packed[0], + packed[1], + bits, + mode, + biases=packed[2] if mode == "affine" else None, + group_size=32 if mode == "mxfp4" else 64, + ), + ) + x = mx.random.normal((1, length, 1, 1, 64)).astype(mx.bfloat16) + ids = (mx.arange(length * 2, dtype=mx.uint32) % 4).reshape(1, length, 2) + weights = mx.broadcast_to(mx.array([[[0.3, 0.7]]]), (1, length, 2)) + actual = expert(x, ids, weights) + repeated = expert(x, ids, weights) + with monkeypatch.context() as patch: + patch.setattr(fast, "has_symbol", lambda _: False) + expected = expert(x, ids, weights) + mx.eval(actual, repeated, expected) + np.testing.assert_array_equal( + actual.astype(mx.float32), expected.astype(mx.float32) + ) + np.testing.assert_array_equal( + actual.astype(mx.float32), repeated.astype(mx.float32) + ) + + +def test_grouped_expert_rejects_mixed_streams(): + first, second = mx.new_stream(mx.gpu), mx.new_stream(mx.gpu) + with mx.stream(first): + gate, up, _, old_down = make_graph() + with mx.stream(second): + activation = quantize_swiglu_activation( + gate, up, mx.array([0.3, 0.7]), mx.bfloat16, 10 + ) + w, s = mx.quantize( + mx.ones((2, 64, 64), mx.bfloat16) * 0.03125, + group_size=32, + bits=4, + mode="mxfp4", + ) + ids = mx.array([0, 1], mx.uint32) + down = mx.gather_qmm( + activation, + w, + s, + lhs_indices=ids, + rhs_indices=ids, + group_size=32, + bits=4, + mode="mxfp4", + ) + with pytest.raises(ValueError, match="share a GPU stream"): + fast.deepseek_v41_grouped_expert(gate, up, activation, down) diff --git a/tests/test_deepseek_v41_head.py b/tests/test_deepseek_v41_head.py new file mode 100644 index 0000000000..4598e5c73c --- /dev/null +++ b/tests/test_deepseek_v41_head.py @@ -0,0 +1,40 @@ +import mlx.core as mx +import numpy as np +import pytest + +from omlx.patches.deepseek_v41.head import project_logits + + +@pytest.mark.parametrize("length", [1, 3, 5]) +@pytest.mark.parametrize("width", [256, 264, 5120]) +@pytest.mark.parametrize("dtype", [mx.float32, mx.bfloat16]) +def test_bf16_head_fp32_accumulation_and_repeatability(width, dtype, length): + mx.random.seed(190) + weight = (mx.random.normal((4099, width)) * 0.05).astype(mx.bfloat16) + x = mx.random.normal((1, length, width)).astype(dtype) + actual = project_logits(x, weight) + repeated = project_logits(x, weight) + mx.eval(actual, repeated) + assert actual.dtype == mx.float32 + assert actual.shape == (1, length, 4099) + reference = ( + np.asarray(x.astype(mx.float32)).astype(np.float64) + @ np.asarray(weight.astype(mx.float32)).astype(np.float64).T + ) + np.testing.assert_allclose(actual, reference, rtol=2e-5, atol=5e-5) + np.testing.assert_array_equal(actual, repeated) + + +@pytest.mark.parametrize("shape", [(1, 3, 256), (2, 1, 256)]) +def test_multi_token_head_retains_full_logits(shape): + mx.random.seed(192) + weight = mx.random.normal((4099, 256)).astype(mx.bfloat16) + x = mx.random.normal(shape) + actual = project_logits(x, weight) + reference = x @ weight.astype(mx.float32).T + assert actual.shape == (*shape[:-1], 4099) + np.testing.assert_allclose(actual, reference, rtol=2e-5, atol=5e-5) + independent = mx.concatenate( + [project_logits(row[None], weight) for row in x.reshape(-1, 256)], axis=0 + ).reshape(actual.shape) + np.testing.assert_array_equal(actual, independent) diff --git a/tests/test_deepseek_v41_hyper_connection.py b/tests/test_deepseek_v41_hyper_connection.py new file mode 100644 index 0000000000..d369e511ed --- /dev/null +++ b/tests/test_deepseek_v41_hyper_connection.py @@ -0,0 +1,159 @@ +"""Four-stream mHC mixing preserves accumulation and batch/sequence indexing.""" + +import mlx.core as mx +import numpy as np +import pytest + +from omlx.patches.deepseek_v41.language import _hc_post_reference, hc_post + + +@pytest.mark.parametrize("dtype", [mx.bfloat16, mx.float16, mx.float32]) +@pytest.mark.parametrize("shape", [(1, 1, 64), (2, 17, 128), (1, 3, 513)]) +def test_fused_hc_post_matches_reference_and_repeats(dtype, shape): + mx.random.seed(941) + x = mx.random.normal(shape).astype(dtype) + residual = mx.random.normal((*shape[:-1], 4, shape[-1])).astype(dtype) + post = mx.random.uniform(shape=(*shape[:-1], 4)) * 2 + comb = mx.softmax(mx.random.normal((*shape[:-1], 4, 4)), axis=-1) + expected = _hc_post_reference(x, residual, post, comb) + actual = hc_post(x, residual, post, comb) + repeated = hc_post(x, residual, post, comb) + np.testing.assert_allclose( + actual.astype(mx.float32), expected.astype(mx.float32), rtol=1e-6, atol=1e-6 + ) + np.testing.assert_array_equal( + actual.astype(mx.float32), repeated.astype(mx.float32) + ) + + +def test_hc_post_noncontiguous_inputs_and_other_stream_counts(): + mx.random.seed(943) + for streams in (2, 4, 8): + x = mx.random.normal((2, 64, 3)).transpose(0, 2, 1).astype(mx.bfloat16) + residual = ( + mx.random.normal((2, streams, 3, 64)) + .transpose(0, 2, 1, 3) + .astype(mx.bfloat16) + ) + post = mx.random.normal((2, streams, 3)).transpose(0, 2, 1) + comb = mx.random.normal((2, 3, streams, streams)).swapaxes(-1, -2) + np.testing.assert_allclose( + hc_post(x, residual, post, comb).astype(mx.float32), + _hc_post_reference(x, residual, post, comb).astype(mx.float32), + rtol=0.008, + atol=0.008, + ) + + +@pytest.mark.parametrize( + "dtype,tolerance", [(mx.float32, 2e-6), (mx.float16, 0.001), (mx.bfloat16, 0.008)] +) +@pytest.mark.parametrize("width", [64, 513, 5120]) +def test_pre_norm_fusion_bounds_and_repeat(dtype, tolerance, width): + from omlx.patches.deepseek_v41.language import hc_pre, hc_pre_norm, norm + + mx.random.seed(944) + x = mx.random.normal((2, 7, 4, width)).astype(dtype) + pre = mx.random.uniform(shape=(2, 7, 4)) + weight = mx.random.uniform(shape=(width,)) + expected = norm(hc_pre(x, pre), weight, 1e-6) + actual = hc_pre_norm(x, pre, weight, 1e-6) + repeated = hc_pre_norm(x, pre, weight, 1e-6) + np.testing.assert_allclose( + actual.astype(mx.float32), + expected.astype(mx.float32), + rtol=tolerance, + atol=1e-7, + ) + np.testing.assert_array_equal( + actual.astype(mx.float32), repeated.astype(mx.float32) + ) + + +def test_pre_norm_fusion_zero_and_intermediate_cast(): + from omlx.patches.deepseek_v41.language import hc_pre, hc_pre_norm, norm + + x = mx.zeros((1, 2, 4, 5120), mx.bfloat16) + pre = mx.ones((1, 2, 4)) + weight = mx.ones((5120,)) + np.testing.assert_array_equal( + hc_pre_norm(x, pre, weight, 1e-6).astype(mx.float32), 0 + ) + mx.random.seed(948) + x = mx.random.normal(x.shape).astype(mx.bfloat16) + expected = norm(hc_pre(x, pre), weight, 1e-6) + unrounded = norm( + mx.sum(x.astype(mx.float32) * pre[..., None], -2), weight, 1e-6 + ).astype(x.dtype) + actual = hc_pre_norm(x, pre, weight, 1e-6) + assert mx.sum(actual != unrounded).item() > 100 + np.testing.assert_allclose( + actual.astype(mx.float32), expected.astype(mx.float32), rtol=0.008, atol=1e-7 + ) + + +def test_pre_norm_fusion_cancellation_preserves_pre_reduction_order(): + from omlx.patches.deepseek_v41.language import hc_pre, hc_pre_norm, norm + + small = mx.linspace(0.25, 2, 64) + large = mx.full((64,), 2**24) + x = mx.stack([small, large, -large, small[::-1]])[None, None].astype(mx.bfloat16) + pre = mx.ones((1, 1, 4)) + weight = mx.ones((64,)) + expected = norm(hc_pre(x, pre), weight, 1e-6) + actual = hc_pre_norm(x, pre, weight, 1e-6) + np.testing.assert_allclose( + actual.astype(mx.float32), expected.astype(mx.float32), rtol=0.008, atol=1e-7 + ) + + +@pytest.mark.parametrize("width", [64, 513, 5120]) +def test_hc_projection_fp32_weight_accuracy_and_repeat(width): + from omlx.patches.deepseek_v41.hyper_connection import fused_hc_projection + + mx.random.seed(952) + x = mx.random.normal((2, 3, 4, width)).astype(mx.bfloat16) + fn = mx.random.normal((24, 4 * width)) * 0.01 + actual = fused_hc_projection(x, fn, 1e-6) + repeated = fused_hc_projection(x, fn, 1e-6) + flat = np.asarray(x.astype(mx.float32)).astype(np.float64).reshape(2, 3, -1) + weights = np.asarray(fn).astype(np.float64) + expected = (flat @ weights.T) / np.sqrt( + np.mean(flat * flat, axis=-1, keepdims=True) + 1e-6 + ) + np.testing.assert_allclose(actual, expected, rtol=2e-5, atol=5e-6) + np.testing.assert_array_equal(actual, repeated) + + +def test_prefill_hc_mixes_dispatch_and_controls_match_reference(): + from types import SimpleNamespace + + from omlx.patches.deepseek_v41.language import _hc_mixes, hc_mixes + + mx.random.seed(953) + c = SimpleNamespace(hc_mult=4, norm_eps=1e-6, hc_eps=1e-6, hc_sinkhorn_iters=20) + x = mx.random.normal((2, 256, 4, 64)).astype(mx.bfloat16) + fn = mx.random.normal((24, 256)) * 0.05 + scale = mx.array([0.3, 0.7, 1.1]) + base = mx.random.normal((24,)) + expected = _hc_mixes(x, fn, scale, base, 4, 1e-6, 1e-6, 20) + actual = hc_mixes(x, fn, scale, base, c) + repeated = hc_mixes(x, fn, scale, base, c) + for a, e, r in zip(actual, expected, repeated): + np.testing.assert_allclose(a, e, rtol=2e-5, atol=1e-6) + np.testing.assert_array_equal(a, r) + + +def test_hc_projection_large_row_dispatch_matches_fp64(): + from omlx.patches.deepseek_v41.hyper_connection import fused_hc_projection + + mx.random.seed(960) + x = mx.random.normal((1, 1024, 4, 513)).astype(mx.bfloat16) + fn = mx.random.normal((24, 4 * 513)) * 0.01 + actual = fused_hc_projection(x, fn, 1e-6) + flat = np.asarray(x.astype(mx.float32)).astype(np.float64).reshape(1, 1024, -1) + expected = (flat @ np.asarray(fn).astype(np.float64).T) / np.sqrt( + np.mean(flat * flat, -1, keepdims=True) + 1e-6 + ) + np.testing.assert_allclose(actual, expected, rtol=2e-5, atol=5e-6) + np.testing.assert_array_equal(actual, fused_hc_projection(x, fn, 1e-6)) diff --git a/tests/test_deepseek_v41_kernels.py b/tests/test_deepseek_v41_kernels.py new file mode 100644 index 0000000000..b27dbfbc86 --- /dev/null +++ b/tests/test_deepseek_v41_kernels.py @@ -0,0 +1,448 @@ +"""Checkpoint-free Metal numerical and sparse-addressing gates.""" + +import mlx.core as mx +import numpy as np +import pytest + +from omlx.patches.deepseek_v41.kernels import ( + packed_index_scores, + packed_sparse_attention, +) +from omlx.patches.deepseek_v41.language import candidate_block_ids, sparse_attention +from omlx.patches.deepseek_v41.quantization import pack_activation, unpack_activation + + +@pytest.mark.parametrize("dtype", [mx.float32, mx.float16, mx.bfloat16]) +@pytest.mark.parametrize( + "dim,length,count", + [ + (32, 1, 0), + (64, 1, 17), + (128, 1, 17), + (256, 1, 17), + (512, 1, 513), + (512, 7, 129), + (96, 1, 17), + (96, 3, 37), + (1024, 1, 17), + ], +) +def test_packed_attention_split_and_mask(dtype, dim, length, count): + rng = np.random.default_rng(71) + q = mx.array(rng.normal(size=(1, length, 5, dim)).astype(np.float32)).astype(dtype) + window = pack_activation(mx.array(rng.normal(size=(1, 17, dim)).astype(np.float32))) + pooled = pack_activation( + mx.array(rng.normal(size=(1, 541, dim)).astype(np.float32)), 4, 16, True + ) + wi = mx.array(rng.integers(-3, 17, size=(1, length, 19)), mx.int32) + ci = mx.array(rng.integers(-3, 541, size=(1, length, count)), mx.int32) + sinks = mx.array([-10000, -3, 0, 4, 10000], mx.float32) + actual = packed_sparse_attention(q, window, pooled, wi, ci, sinks, dim**-0.5) + selected = mx.concatenate( + [ + unpack_activation(window, dtype=mx.float32)[0][mx.maximum(wi[0], 0)][None], + unpack_activation(pooled, 4, 16, True, mx.float32)[0][mx.maximum(ci[0], 0)][ + None + ], + ], + -2, + ) + expected = sparse_attention( + q, selected, mx.concatenate([wi, ci], -1), sinks, dim**-0.5 + ) + tolerance = ( + 3e-6 if dtype == mx.float32 else (0.002 if dtype == mx.float16 else 0.016) + ) + np.testing.assert_allclose( + actual.astype(mx.float32), + expected.astype(mx.float32), + atol=tolerance, + rtol=tolerance, + ) + assert mx.all(mx.isfinite(actual)).item() + + +def test_attention_empty_and_all_masked(): + q = mx.ones((1, 2, 3, 32)) + w, p = mx.zeros((1, 0, 33), mx.uint8), mx.zeros((1, 0, 18), mx.uint8) + empty = mx.zeros((1, 2, 0), mx.int32) + sinks = mx.array([-10000, 0, 10000], mx.float32) + np.testing.assert_array_equal( + packed_sparse_attention(q, w, p, empty, empty, sinks, 1), 0 + ) + invalid = mx.full((1, 2, 257), -1, mx.int32) + np.testing.assert_array_equal( + packed_sparse_attention(q, w, p, invalid, empty, sinks, 1), 0 + ) + + +@pytest.mark.parametrize( + "dim,heads,length", + [(32, 8, 1), (128, 128, 3), (96, 9, 2), (96, 33, 3), (128, 65, 1), (32, 32, 2)], +) +@pytest.mark.parametrize("dtype", [mx.float32, mx.float16, mx.bfloat16]) +@pytest.mark.parametrize("restricted", [False, True]) +def test_index_scores_packed_candidates_and_causal( + dim, heads, length, restricted, dtype +): + rng = np.random.default_rng(14) + n = 137 + q = mx.array(rng.normal(size=(1, length, heads, dim)).astype(np.float32)).astype( + dtype + ) + keys = pack_activation(mx.array(rng.normal(size=(1, n, dim)).astype(np.float32)), 4) + weights = mx.array(rng.normal(size=(1, length, heads)).astype(np.float32)) / heads + candidates = None + if restricted: + candidates = mx.array( + np.tile([-1, 0, 2, 70, 132, 132, 136, 137], (1, length, 1)), mx.int32 + ) + actual = packed_index_scores(q, keys, weights, 263, 2, candidates) + expanded = unpack_activation(keys, 4, dtype=mx.float32) + expected = mx.sum( + mx.maximum(mx.einsum("bshd,btd->bsht", q.astype(mx.float32), expanded), 0) + * weights[..., None], + -2, + ) + valid = mx.arange(n) < ((263 + mx.arange(length) + 1) // 2)[:, None] + expected = mx.where(valid, expected, -float("inf")) + if candidates is not None: + expected = mx.take_along_axis(expected, mx.clip(candidates, 0, n - 1), -1) + expected = mx.where( + (candidates >= 0) & (candidates < n), expected, -float("inf") + ) + np.testing.assert_allclose(actual, expected, atol=3e-5, rtol=3e-5) + + +def test_candidate_block_ids_preserve_latest_and_partial_blocks(): + scores = mx.array( + [ + [ + [9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, -float("inf")], + [9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0], + ] + ] + ) + lengths = mx.array([[[8], [9]]]) + ids = candidate_block_ids(scores, lengths, 2, 4) + np.testing.assert_array_equal(ids, [[[0, 1], [0, 2]]]) + # All unavailable blocks must remain invalid even if the budget covers all. + ids = candidate_block_ids( + mx.full((1, 1, 9), -float("inf")), mx.array([[[0]]]), 4, 4 + ) + np.testing.assert_array_equal(ids, -1) + + +def test_empty_index_cache_with_explicit_candidates(): + q = mx.ones((1, 2, 8, 32)) + keys = mx.zeros((1, 0, 17), mx.uint8) + weights = mx.ones((1, 2, 8)) + candidates = mx.array([[[-1, 0], [1, -1]]]) + actual = packed_index_scores(q, keys, weights, 0, 2, candidates) + np.testing.assert_array_equal(actual, -float("inf")) + + +def test_noncontiguous_index_inputs(): + mx.random.seed(25) + q = mx.random.normal((1, 6, 8, 32))[:, ::2] + keys = pack_activation(mx.random.normal((1, 40, 32)), 4)[:, ::2] + weights = mx.random.normal((1, 6, 8))[:, ::2] + candidates = mx.broadcast_to(mx.arange(12)[None, None], (1, 3, 12)) + actual = packed_index_scores(q, keys, weights, 40, 1, candidates) + expanded = unpack_activation(keys, 4, dtype=mx.float32) + expected = mx.sum( + mx.maximum(mx.einsum("bshd,btd->bsht", q.astype(mx.float32), expanded), 0) + * weights[..., None], + -2, + )[..., :12] + np.testing.assert_allclose(actual, expected, atol=2e-5, rtol=2e-5) + + +@pytest.mark.parametrize( + "count,width", + [(0, 33), (7, 9001), (512, 5003), (2048, 5003), (3000, 5003), (50, 17)], +) +def test_tile_topk_matches_score_order(count, width): + from omlx.patches.deepseek_v41.kernels import _tile_topk + + rng = np.random.default_rng(122) + data = rng.normal(size=(1, 3, width)).astype(np.float32) + data[0, 0, :5] = -np.inf + values, ids = _tile_topk(mx.array(data), count, offset=71) + mx.eval(values, ids) + k = min(count, width) + expected = np.sort(np.argsort(-data, axis=-1)[..., :k] + 71, axis=-1) + np.testing.assert_array_equal(np.sort(np.asarray(ids), axis=-1), expected) + np.testing.assert_array_equal( + values, np.take_along_axis(data, np.asarray(ids) - 71, -1) + ) + + +def test_tile_topk_ties_use_absolute_ids(): + from omlx.patches.deepseek_v41.kernels import _tile_topk + + ids = mx.arange(5003, dtype=mx.int32)[::-1][None, None] + scores = mx.zeros(ids.shape) + _, chosen = _tile_topk(scores, 512, ids=ids) + np.testing.assert_array_equal(mx.sort(chosen, axis=-1), np.arange(512)[None, None]) + + +@pytest.mark.parametrize( + "dim,heads,start,ratio", [(32, 3, 0, 4), (128, 8, 399, 2), (96, 9, 91, 3)] +) +@pytest.mark.parametrize("dtype", [mx.float32, mx.bfloat16]) +def test_streamed_index_and_candidate_blocks_match_full_scores( + dim, heads, start, ratio, dtype +): + from omlx.patches.deepseek_v41.kernels import packed_index_topk + + mx.random.seed(105) + length, width = 19, 203 + q = mx.random.normal((1, length, heads, dim)).astype(dtype) + keys = pack_activation(mx.random.normal((1, width, dim)), 4) + weights = mx.random.normal((1, length, heads)) + scores = packed_index_scores(q, keys, weights, start, ratio) + expected_order = mx.argsort(-scores, axis=-1)[..., :17].astype(mx.int32) + expected = mx.sort( + mx.where( + mx.take_along_axis(scores, expected_order, -1) > -float("inf"), + expected_order, + -1, + ), + axis=-1, + ) + lengths = (mx.arange(start + 1, start + length + 1) // ratio)[None, :, None] + expected_blocks = mx.sort(candidate_block_ids(scores, lengths, 7, 8), axis=-1) + actual, blocks = packed_index_topk( + q, + keys, + weights, + start, + ratio, + 17, + block_count=7, + block_size=8, + chunk_size=61, + query_chunk_size=5, + ) + np.testing.assert_array_equal(actual, expected) + np.testing.assert_array_equal(blocks, expected_blocks) + + +def test_streamed_index_empty_and_forced_recent_block(): + from omlx.patches.deepseek_v41.kernels import packed_index_topk + + q = mx.zeros((1, 5, 8, 32)) + weights = mx.ones((1, 5, 8)) + empty = mx.zeros((1, 0, 17), mx.uint8) + ids, blocks = packed_index_topk( + q, empty, weights, 0, 2, 512, block_count=2048, block_size=8 + ) + assert ids.shape == blocks.shape == (1, 5, 0) + keys = pack_activation(mx.ones((1, 53, 32)), 4) + ids, blocks = packed_index_topk( + q, + keys, + weights, + 37, + 1, + 3, + block_count=1, + block_size=8, + chunk_size=17, + query_chunk_size=2, + ) + np.testing.assert_array_equal(ids, np.broadcast_to(np.arange(3), (1, 5, 3))) + np.testing.assert_array_equal(blocks, ((np.arange(38, 43) - 1) // 8)[None, :, None]) + + +def test_streaming_bounds_scoring_and_skips_future_chunks(monkeypatch): + from omlx.patches.deepseek_v41 import kernels + + calls = [] + original = kernels.packed_index_scores + + def tracked(q, keys, weights, start, ratio, **kwargs): + if keys.shape[1]: + calls.append((q.shape[1], keys.shape[1], start, kwargs.get("key_start", 0))) + return original(q, keys, weights, start, ratio, **kwargs) + + monkeypatch.setattr(kernels, "packed_index_scores", tracked) + q = mx.ones((1, 19, 8, 32)) + keys = pack_activation(mx.ones((1, 1000, 32)), 4) + ids, _ = kernels.packed_index_topk( + q, keys, mx.ones((1, 19, 8)), 0, 2, 17, chunk_size=5, query_chunk_size=4 + ) + mx.eval(ids) + assert calls + assert all(queries <= 4 and width <= 5 for queries, width, _, _ in calls) + assert all( + first + width <= (start + queries) // 2 + for queries, width, start, first in calls + ) + # The first query has no completed compressed row; output size stays fixed. + np.testing.assert_array_equal(ids[0, 0], -1) + assert ids.shape == (1, 19, 17) + + +@pytest.mark.parametrize( + "left_size,right_size,count", + [(512, 513, 512), (5, 2, 7), (0, 33, 17), (2048, 13, 2048)], +) +def test_sorted_merge_ties_padding_and_uneven_runs(left_size, right_size, count): + from omlx.patches.deepseek_v41.kernels import _merge_topk + + rng = np.random.default_rng(577) + values = rng.integers(-3, 4, (1, 3, left_size + right_size)).astype(np.float32) + values[..., -2:] = -np.inf + ids = rng.integers(0, 17, values.shape).astype(np.int32) + order = np.lexsort((ids, -values), axis=-1) + expected = ( + np.take_along_axis(values, order, -1)[..., :count], + np.take_along_axis(ids, order, -1)[..., :count], + ) + runs = [] + for part in (slice(None, left_size), slice(left_size, None)): + v, i = values[..., part], ids[..., part] + local_order = np.lexsort((i, -v), axis=-1) + runs.append( + ( + mx.array(np.take_along_axis(v, local_order, -1)), + mx.array(np.take_along_axis(i, local_order, -1)), + ) + ) + actual = _merge_topk(*runs, count) + for a, b in zip(actual, expected, strict=True): + np.testing.assert_array_equal(a, b) + + +@pytest.mark.parametrize("block,count", [(3, 17), (8, 2048), (2, 3000), (1, 512)]) +def test_fused_candidate_selection_matches_block_maxima(block, count): + from omlx.patches.deepseek_v41.kernels import _tile_topk + + width, length, start, ratio = 10003, 3, 100, 2 + rng = np.random.default_rng(302) + data = rng.normal(size=(1, length, width)).astype(np.float32) + data[..., -3:] = -np.inf + scores = mx.array(data) + expected = candidate_block_ids( + scores, + (mx.arange(start + 1, start + length + 1) // ratio)[None, :, None], + count, + block, + ) + values, ids = _tile_topk( + scores, count, block_size=block, force_latest=True, start=start, ratio=ratio + ) + actual = mx.sort(mx.where(values > -float("inf"), ids, -1), axis=-1) + np.testing.assert_array_equal(actual, mx.sort(expected, axis=-1)) + + +@pytest.mark.parametrize("length", [1, 9]) +def test_streaming_drains_async_work_before_return(monkeypatch, length): + from omlx.patches.deepseek_v41.kernels import packed_index_topk + + pending, submissions = set(), [] + evaluate, submit = mx.eval, mx.async_eval + + def tracked_eval(*arrays): + result = evaluate(*arrays) + pending.difference_update(id(a) for a in arrays) + return result + + def tracked_submit(*arrays): + assert not pending, "Previous batch must be drained before the next submission" + result = submit(*arrays) + pending.update(id(a) for a in arrays) + submissions.append(len(arrays)) + return result + + q = mx.ones((1, length, 8, 32)) + keys = pack_activation(mx.ones((1, 137, 32)), 4) + weights = mx.ones((1, length, 8)) + mx.eval(q, keys, weights) + monkeypatch.setattr(mx, "eval", tracked_eval) + monkeypatch.setattr(mx, "async_eval", tracked_submit) + packed_index_topk( + q, + keys, + weights, + 128, + 1, + 17, + block_count=3, + block_size=8, + chunk_size=32, + query_chunk_size=4, + ) + assert len(submissions) > 1 + assert not pending + + +@pytest.mark.parametrize("count,runs", [(7, 3), (17, 5), (512, 9), (513, 5), (2048, 3)]) +def test_multiway_merge_exact_rank_with_duplicate_ids(count, runs): + from omlx.patches.deepseek_v41.kernels import _merge_topk + + rng = np.random.default_rng(779) + values = rng.integers(-2, 3, (1, 2, runs, count)).astype(np.float32) + values[:, 0, -1] = -np.inf + ids = rng.integers(0, 37, values.shape).astype(np.int32) + order = np.lexsort((ids, -values), axis=-1) + values = np.take_along_axis(values, order, -1) + ids = np.take_along_axis(ids, order, -1) + arrays = (mx.array(values.reshape(1, 2, -1)), mx.array(ids.reshape(1, 2, -1))) + actual = _merge_topk(arrays, arrays, count, runs=runs) + fanin = 4 if count <= 512 else 2 + expected_values, expected_ids = [], [] + for first in range(0, runs, fanin): + v = values[:, :, first : first + fanin].reshape(1, 2, -1) + i = ids[:, :, first : first + fanin].reshape(1, 2, -1) + chosen = np.lexsort((i, -v), axis=-1)[..., :count] + expected_values.append(np.take_along_axis(v, chosen, -1)) + expected_ids.append(np.take_along_axis(i, chosen, -1)) + np.testing.assert_array_equal(actual[0], np.concatenate(expected_values, axis=-1)) + np.testing.assert_array_equal(actual[1], np.concatenate(expected_ids, axis=-1)) + + +@pytest.mark.parametrize("length", [1, 4, 65, 512]) +def test_single_tile_index_stays_lazy_and_matches_streaming(monkeypatch, length): + from omlx.patches.deepseek_v41.kernels import packed_index_topk + + mx.random.seed(106) + q = mx.random.normal((1, length, 8, 32)) + keys = pack_activation(mx.random.normal((1, 137, 32)), 4) + weights = mx.random.normal((1, length, 8)) + args = (q, keys, weights, 128, 1, 17) + expected = packed_index_topk(*args, block_count=3, block_size=8, chunk_size=32) + mx.eval(expected) + + def unexpected_submission(*arrays): + raise AssertionError("A single bounded tile must remain lazy") + + with monkeypatch.context() as patch: + patch.setattr(mx, "eval", unexpected_submission) + patch.setattr(mx, "async_eval", unexpected_submission) + actual = packed_index_topk(*args, block_count=3, block_size=8) + for result, reference in zip(actual, expected): + np.testing.assert_array_equal(result, reference) + + +@pytest.mark.parametrize("length", [1, 16, 512]) +@pytest.mark.parametrize("iters", [1, 2, 20]) +@pytest.mark.parametrize("eps", [1e-6, 1e-3]) +def test_sinkhorn_fused_exact(length, iters, eps): + from omlx.patches.deepseek_v41.hyper_connection import ( + sinkhorn, + sinkhorn_reference, + ) + + mx.random.seed(108) + values = mx.random.normal((1, length, 4, 4)) * 20 + comb = mx.softmax(values, -1) + eps + np.testing.assert_array_equal( + sinkhorn(comb, eps, iters), sinkhorn_reference(comb, eps, iters) + ) + zeros = mx.zeros_like(comb) + np.testing.assert_array_equal( + sinkhorn(zeros, eps, iters), sinkhorn_reference(zeros, eps, iters) + ) diff --git a/tests/test_deepseek_v41_moe.py b/tests/test_deepseek_v41_moe.py new file mode 100644 index 0000000000..e5415eec4a --- /dev/null +++ b/tests/test_deepseek_v41_moe.py @@ -0,0 +1,63 @@ +"""Routing preserves row-local activation quantization and router inputs.""" + +import mlx.core as mx +import numpy as np +import pytest + +from omlx.patches.deepseek_v41 import language +from omlx.patches.deepseek_v41.config import ModelConfig +from omlx.patches.deepseek_v41.quantization import QuantizedProjection + + +@pytest.mark.parametrize("length", [1, 32]) +@pytest.mark.parametrize( + "routed,shared", [(True, True), (True, False), (False, True), (False, False)] +) +def test_moe_quantization_reuse_matches_per_expert_reference(length, routed, shared): + mx.random.seed(412) + config = ModelConfig( + dim=64, moe_inter_dim=64, n_routed_experts=4, n_activated_experts=2 + ) + moe = language.MoE(config) + moe.gate.weight = mx.random.normal((4, 64)) + for expert, switched, quantizes in [ + (moe.experts, True, routed), + (moe.shared_experts, False, shared), + ]: + for name in ("w1", "w3", "w2"): + weight = ( + mx.random.normal((4, 64, 64) if switched else (64, 64)).astype( + mx.bfloat16 + ) + * 0.05 + ) + packed, scales, biases = mx.quantize(weight, bits=4, group_size=32) + setattr( + expert, + name, + QuantizedProjection( + packed, scales, 4, "affine", biases=biases, quantize_input=quantizes + ), + ) + x = mx.random.normal((1, length, 64)).astype(mx.bfloat16) + # Route raw inputs and project each selected expert without prequantization. + indices, weights = moe.gate(x, None) + selected = moe.experts(x[..., None, None, :], indices, weights).squeeze(-2) + expected = ( + selected.astype(mx.float32).sum(-2) + moe.shared_experts(x).astype(mx.float32) + ).astype(x.dtype) + actual = moe(x, None) + repeated = moe(x, None) + mx.eval(expected, actual, repeated) + np.testing.assert_allclose( + actual.astype(mx.float32), expected.astype(mx.float32), rtol=0.01, atol=0.002 + ) + np.testing.assert_array_equal( + actual.astype(mx.float32), repeated.astype(mx.float32) + ) + + +def test_expert_rejects_prequantized_input_for_unquantized_projections(): + expert = language.Expert(ModelConfig(dim=64, moe_inter_dim=64)) + with pytest.raises(ValueError, match="matching quantized projections"): + expert(mx.zeros((1, 1, 64)), input_quantized=True) diff --git a/tests/test_deepseek_v41_mtp.py b/tests/test_deepseek_v41_mtp.py new file mode 100644 index 0000000000..cb380da614 --- /dev/null +++ b/tests/test_deepseek_v41_mtp.py @@ -0,0 +1,181 @@ +"""Exercise CSA2 rollback and the shared DSpark generation loop.""" + +from dataclasses import replace + +import mlx.core as mx +import numpy as np +import pytest +from test_deepseek_v41 import load_reference_weights, tiny + +from omlx.patches.deepseek_v41.language import LanguageModel + + +def mtp_config(**kwargs): + return tiny( + preserve_mtp=True, + n_mtp_layers=3, + dspark_block_size=3, + dspark_noise_token_id=2, + dspark_target_layer_ids=(2, 3, 4), + dspark_n_routed_experts=2, + dspark_n_activated_experts=1, + dspark_markov_rank=32, + compress_ratios=(0, 2, 2, 1, 1, 0, 0, 0), + **kwargs, + ) + + +@pytest.mark.parametrize("ratio", [2, 4, 8]) +@pytest.mark.parametrize("prefix", [1, 3, 4, 5, 7, 8]) +@pytest.mark.parametrize("accepted", [0, 1, 2, 3]) +def test_verify_rollback_restores_all_csa2_slots(prefix, accepted, ratio, monkeypatch): + config = replace(mtp_config(), compress_ratios=(0, ratio, ratio, 1, 1, 0, 0, 0)) + model = LanguageModel(config) + load_reference_weights(model) + model.configure_mtp(True, 3) + cache, expected = model.make_cache(), model.make_cache() + prompt = mx.array([[3 + i % 20 for i in range(prefix)]]) + model(prompt, cache=cache) + model(prompt, cache=expected) + block = mx.array([[21, 22, 23, 24]]) + model(block, cache=cache, return_hidden=True, n_confirmed=1) + + def fail_replay(*args, **kwargs): + raise AssertionError("Rollback must not execute the target backbone") + + with monkeypatch.context() as patch: + patch.setattr(model, "_forward", fail_replay) + assert model.mtp_partial_rollback(cache, accepted, 3) + assert cache[0]._mtp_draft_stash is None + model(block[:, : accepted + 1], cache=expected, return_hidden=True) + for actual, wanted in zip(cache, expected): + assert actual.size() == wanted.size() == prefix + accepted + 1 + np.testing.assert_array_equal(actual.left_padding, wanted.left_padding) + for a, b in zip(actual.state, wanted.state): + np.testing.assert_allclose(a, b, atol=1e-6, rtol=1e-5) + following = mx.array([[25]]) + a = model(following, cache=cache) + b = model(following, cache=expected) + np.testing.assert_allclose(a, b, atol=1e-6, rtol=1e-5) + + +def test_rollback_restores_engram_history(): + from omlx.patches.deepseek_v41.language import LanguageModel + + model = LanguageModel( + tiny( + engram_layer_ids=(1,), + engram_num_embeddings=(72,), + engram_vocab_size=5, + engram_max_ngram_size=4, + engram_n_heads=2, + engram_head_dim=32, + engram_compressed_vocab_size=64, + ) + ) + model.set_token_map(np.arange(64)) + cache, expected = model.make_cache(), model.make_cache() + for state in (cache, expected): + model(mx.array([[3, 4, 5, 6, 7]]), cache=state) + model(mx.array([[8, 9, 10, 11]]), cache=cache, n_confirmed=1) + assert model.mtp_partial_rollback(cache, 1, 3) + model(mx.array([[8, 9]]), cache=expected) + np.testing.assert_array_equal(cache[0][6], expected[0][6]) + for a, b in zip(cache, expected): + for x, y in zip(a.state, b.state): + np.testing.assert_allclose(x, y, atol=1e-5) + + +def test_shared_batch_generator_activates_and_matches_greedy(monkeypatch): + from mlx_lm.generate import BatchGenerator + + from omlx.patches.mlx_lm_mtp import batch_generator + + batch_generator.apply() + model = LanguageModel(mtp_config()) + load_reference_weights(model) + prompt = [3, 4, 5, 6, 7, 8, 9] + expected, cache = [], model.make_cache() + ids = mx.array([prompt]) + for _ in range(16): + logits = model(ids, cache=cache) + token = int(mx.argmax(logits[0, -1]).item()) + expected.append(token) + ids = mx.array([[token]]) + model.configure_mtp(True, 3) + calls = [] + original = type(model).dspark_forward + + def tracked(self, *args, **kwargs): + calls.append(1) + return original(self, *args, **kwargs) + + monkeypatch.setattr(type(model), "dspark_forward", tracked) + controllers = [] + original_factory = model.make_mtp_depth_controller + + def make_controller(depth): + controller = original_factory(depth) + controllers.append(controller) + return controller + + monkeypatch.setattr(model, "make_mtp_depth_controller", make_controller) + generator = BatchGenerator( + model, + max_tokens=16, + prefill_step_size=3, + sampler=lambda logits: mx.argmax(logits, -1), + ) + result = [] + try: + generator.insert([prompt]) + for _ in range(64): + _, responses = generator.next() + result.extend(response.token for response in responses) + if len(result) == 16: + break + finally: + generator.close() + assert controllers, "The shared loop must use the model depth policy" + assert calls, "The test must exercise actual DSpark proposal execution" + assert result == expected + + +def test_mtp_load_flag_is_instance_owned(monkeypatch): + from omlx.patches import mlx_lm_mtp + from omlx.patches.deepseek_v41.language import LanguageModel + + monkeypatch.setattr(mlx_lm_mtp, "_MTP_ACTIVE", True) + enabled = LanguageModel(mtp_config()) + monkeypatch.setattr(mlx_lm_mtp, "_MTP_ACTIVE", False) + disabled = LanguageModel(mtp_config()) + assert enabled._omlx_dspark_decode_enabled + assert not disabled._omlx_dspark_decode_enabled + assert disabled.mtp # Weight preservation is independent of execution. + assert enabled._omlx_mtp_rowwise_unsupported + + +def test_v41_dspark_config_is_eligible(): + from omlx.utils.model_loading import _is_mtp_compatible + + assert _is_mtp_compatible( + {"dspark_block_size": 5, "dspark_target_layer_ids": [37, 38, 39]}, + "deepseek_v41", + ) + assert not _is_mtp_compatible({"n_mtp_layers": 0}, "deepseek_v41") + + +def test_acceptance_depth_is_independent_of_timing(): + from omlx.patches.deepseek_v41.mtp import AcceptanceDepthController + + a, b = AcceptanceDepthController(3), AcceptanceDepthController(3) + depths = [] + for accepted in [0, 1, 2, 3, 1, 0, 1, 2, 3]: + assert a.cur == b.cur + used = a.cur + a.observe(used, accepted, 0.01) + b.observe(used, accepted, 100000, time_sample=False) + assert a.cur == b.cur + assert not a.should_exit() and not b.should_exit() + depths.append(a.cur) + assert depths == [1, 2, 3, 3, 2, 1, 2, 3, 3] diff --git a/tests/test_deepseek_v41_native_attention.py b/tests/test_deepseek_v41_native_attention.py new file mode 100644 index 0000000000..9c8ebb5aba --- /dev/null +++ b/tests/test_deepseek_v41_native_attention.py @@ -0,0 +1,145 @@ +import mlx.core as mx +import numpy as np +import pytest + +from omlx.custom_kernels.glm_moe_dsa import fast +from omlx.patches.deepseek_v41.kernels import packed_sparse_attention +from omlx.patches.deepseek_v41.quantization import pack_activation + +pytestmark = pytest.mark.skipif( + not fast.has_symbol("deepseek_v41_packed_attention"), + reason="Packed attention extension is not built", +) + + +@pytest.mark.parametrize( + "start,length,pooled_count", [(0, 7, 0), (0, 7, 3), (131, 3, 40), (4096, 7, 1024)] +) +def test_native_packed_attention_causal_window_and_fp32_sinks( + start, length, pooled_count +): + mx.random.seed(193) + q = mx.random.normal((1, length, 64, 512)).astype(mx.bfloat16) + old = min(start, 128) + window = pack_activation(mx.random.normal((1, old + length, 512))) + pooled = pack_activation(mx.random.normal((1, pooled_count, 512)), 4, 16, True) + if pooled_count: + ci = mx.broadcast_to( + mx.array( + [-1, 0, 1, pooled_count - 1, pooled_count, pooled_count + 2], mx.int32 + ), + (1, length, 6), + ) + else: + ci = mx.zeros((1, length, 0), mx.int32) + positions = mx.arange(start, start + length) + local = positions[:, None] - 127 + mx.arange(128) + wi = mx.where(local >= max(0, start - old), local - (start - old), -1)[None] + valid = ( + (ci >= 0) & (ci < pooled_count) & (ci < ((positions + 1) // 4)[None, :, None]) + ) + masked = mx.where(valid, ci, -1) + sinks = mx.linspace(-4.123456, 4.234567, 64) + expected = packed_sparse_attention(q, window, pooled, wi, masked, sinks, 512**-0.5) + args = ( + q.transpose(0, 2, 1, 3), + window[:, None], + pooled, + ci[:, None].astype(mx.uint32), + sinks, + 512**-0.5, + start, + 4, + 128, + ) + actual = fast.deepseek_v41_packed_attention(*args).transpose(0, 2, 1, 3) + repeated = fast.deepseek_v41_packed_attention(*args).transpose(0, 2, 1, 3) + np.testing.assert_allclose( + actual.astype(mx.float32), expected.astype(mx.float32), atol=0.008, rtol=0.008 + ) + assert mx.array_equal(actual, repeated).item() + assert window.dtype == pooled.dtype == mx.uint8 + assert mx.all(mx.isfinite(actual)).item() + + +def test_native_packed_attention_does_not_round_fp32_sinks(): + q = mx.zeros((1, 64, 2, 512), mx.bfloat16) + window = pack_activation(mx.ones((1, 2, 512)))[:, None] + pooled = mx.zeros((1, 0, 288), mx.uint8) + topk = mx.zeros((1, 1, 2, 0), mx.uint32) + sinks = mx.linspace(-4.123456, 4.234567, 64) + actual = fast.deepseek_v41_packed_attention( + q, window, pooled, topk, sinks, 512**-0.5, 0, 4, 128 + ) + count = mx.array([1, 2], mx.float32)[None, :] + expected = (count / (count + mx.exp(sinks[:, None]))).astype(mx.bfloat16) + rounded = ( + count / (count + mx.exp(sinks.astype(mx.bfloat16).astype(mx.float32)[:, None])) + ).astype(mx.bfloat16) + assert not mx.array_equal(expected, rounded).item() + assert mx.array_equal(actual[0, :, :, 0], expected).item() + + +@pytest.mark.parametrize("scale_byte", [64, 126, 127, 128, 192]) +def test_native_packed_attention_fp8_codes_and_power_of_two_scales(scale_byte): + codes = np.resize( + np.concatenate([np.arange(127), np.arange(128, 255)]).astype(np.uint8), 512 + ) + magnitude = (codes & 127).astype(np.int32) + exponent, mantissa = magnitude >> 3, magnitude & 7 + values = np.where( + exponent == 0, + np.ldexp(mantissa.astype(np.float32), -9), + np.ldexp(1 + mantissa.astype(np.float32) / 8, exponent - 7), + ) + values *= np.where(codes & 128, -1, 1) + values = np.ldexp(values, scale_byte - 127).astype(np.float32) + row = np.concatenate([codes, np.full(16, scale_byte, np.uint8)]) + window = mx.array(np.tile(row, (1, 1, 2, 1))) + actual = fast.deepseek_v41_packed_attention( + mx.zeros((1, 64, 2, 512), mx.bfloat16), + window, + mx.zeros((1, 0, 288), mx.uint8), + mx.zeros((1, 1, 2, 0), mx.uint32), + mx.full((64,), -100.0), + 512**-0.5, + 0, + 4, + 128, + ) + expected = mx.broadcast_to(mx.array(values).astype(mx.bfloat16), actual.shape) + assert mx.array_equal(actual, expected).item() + + +@pytest.mark.parametrize("length", [2, 4, 6, 8]) +@pytest.mark.parametrize("pooled_count", [0, 40, 1024]) +def test_short_packed_attention_matches_independent_decode(length, pooled_count): + mx.random.seed(291) + q = mx.random.normal((1, length, 64, 512)).astype(mx.bfloat16) + window = pack_activation(mx.random.normal((1, 128 + length, 512))) + pooled = pack_activation(mx.random.normal((1, pooled_count, 512)), 4, 16, True) + wi = mx.arange(1, 129)[None, None, :] + mx.arange(length)[None, :, None] + ci = mx.broadcast_to(mx.arange(pooled_count), (1, length, pooled_count)) + # Distinct per-query visibility, including invalid and entirely masked rows. + ci = mx.where(ci < mx.arange(length)[None, :, None] * 17, ci, -1) + sinks = mx.linspace(-4.123456, 4.234567, 64) + args = (q, window, pooled, wi, ci, sinks, 512**-0.5) + actual = packed_sparse_attention(*args) + expected = mx.concatenate( + [ + packed_sparse_attention( + q[:, i : i + 1], + window, + pooled, + wi[:, i : i + 1], + ci[:, i : i + 1], + sinks, + 512**-0.5, + ) + for i in range(length) + ], + axis=1, + ) + assert mx.array_equal(actual, expected).item() + assert mx.array_equal(actual, packed_sparse_attention(*args)).item() + assert mx.all(mx.isfinite(actual)).item() diff --git a/tests/test_deepseek_v41_offload.py b/tests/test_deepseek_v41_offload.py new file mode 100644 index 0000000000..fe9e2b6f0e --- /dev/null +++ b/tests/test_deepseek_v41_offload.py @@ -0,0 +1,728 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Resident/SSD equivalence and bounded Engram prefetch lifecycle.""" + +import json +from concurrent.futures import ThreadPoolExecutor +from threading import Event, current_thread + +import mlx.core as mx +import numpy as np +import pytest +from test_deepseek_v41 import raw_safetensors, write_checkpoint + +from omlx.patches.deepseek_v41 import loading, storage +from omlx.patches.deepseek_v41.convert import convert +from omlx.patches.deepseek_v41.loading import load +from omlx.patches.deepseek_v41.residency import deepseek_v41_residency_estimate +from omlx.patches.deepseek_v41.storage import DiskEngramEmbedding, EngramPrefetch + + +def table(tmp_path): + path = tmp_path / "rows.safetensors" + raw = np.arange(16 * 64, dtype=np.uint8).reshape(16, 64) % 120 + scales = np.arange(32, dtype=np.uint8).reshape(16, 2) + 110 + raw_safetensors(path, {"w": (raw, "F8_E4M3"), "s": (scales, "F8_E8M0")}) + return DiskEngramEmbedding(path, "w", "s") + + +def test_packed_resident_and_prefetched_rows_match(tmp_path, monkeypatch): + disk = table(tmp_path) + resident = table(tmp_path) + resident.make_resident() + prefetch = EngramPrefetch() + try: + assert resident._weights._mapping is None + assert resident._resident["w"][0].nbytes == 16 * 64 + ids = np.array([[5, 1, 5, 0]]) + expected = np.asarray(resident(mx.array(ids)).astype(mx.float32)) + original = disk._read_rows + threads = [] + + def read(rows): + threads.append(current_thread().name) + return original(rows) + + monkeypatch.setattr(disk, "_read_rows", read) + with prefetch.forward(): + prefetch.submit(disk, ids) + actual = disk(mx.array(ids)) + np.testing.assert_array_equal(actual.astype(mx.float32), expected) + assert len(threads) == 1 and threads[0].startswith("v41-engram") + assert disk._prefetched is None and prefetch._pending is None + with prefetch.forward(): + prefetch.submit(disk, ids) + # A mismatched request must never consume stale row data. + actual = disk(mx.array([[2, 3]])) + np.testing.assert_array_equal( + actual.astype(mx.float32), resident(mx.array([[2, 3]])).astype(mx.float32) + ) + monkeypatch.setattr(storage, "PREFETCH_BYTES", 1) + prefetch.submit(disk, ids) + assert prefetch._pending is None + prefetch.submit(resident, ids) + assert prefetch._pending is None + finally: + prefetch.close() + disk.close() + resident.close() + + +def test_prefetch_drains_before_unmap(tmp_path, monkeypatch): + disk = table(tmp_path) + prefetch = EngramPrefetch() + entered, release, closing = Event(), Event(), Event() + original = disk._read_rows + + def read(rows): + entered.set() + assert release.wait(5) + assert disk._weights._mapping is not None + return original(rows) + + monkeypatch.setattr(disk, "_read_rows", read) + prefetch.submit(disk, np.array([1])) + assert entered.wait(5) + + def close(): + closing.set() + prefetch.close() + disk.close() + + with ThreadPoolExecutor(max_workers=1) as executor: + future = executor.submit(close) + try: + assert closing.wait(5) + assert not future.done() + finally: + release.set() + future.result(timeout=5) + assert disk._weights._mapping is None + assert prefetch._pending is None + prefetch.close() + disk.close() + + +def test_prefetch_forward_error_releases_pending_rows(tmp_path): + disk = table(tmp_path) + prefetch = EngramPrefetch() + try: + with pytest.raises(ValueError, match="cancelled"), prefetch.forward(): + prefetch.submit(disk, np.array([1, 2])) + raise ValueError("cancelled") + assert prefetch._pending is None and disk._prefetched is None + # Subsequent requests remain usable. + with prefetch.forward(): + prefetch.submit(disk, np.array([3])) + mx.eval(disk(mx.array([3]))) + finally: + prefetch.close() + disk.close() + + +@pytest.fixture +def converted(tmp_path): + source, _ = write_checkpoint( + tmp_path, + vision=False, + engram_layer_ids=(1, 3), + engram_num_embeddings=(72, 204), + engram_vocab_size=5, + engram_max_ngram_size=4, + engram_n_heads=2, + engram_head_dim=32, + engram_compressed_vocab_size=64, + ) + target = tmp_path / "converted" + convert(source, target) + return target + + +def test_converted_modes_match_chunked_prefill_decode_and_cleanup(converted): + resident, _ = load(converted, engram_ssd_offload=False) + disk, _ = load(converted, engram_ssd_offload=True) + try: + caches = [model.language_model.make_cache() for model in (resident, disk)] + for ids in ([[3, 4, 5]], [[6, 7]], [[8]], [[9]], [[10]]): + outputs = [ + model(mx.array(ids), cache=cache) + for model, cache in zip((resident, disk), caches) + ] + mx.eval(outputs) + np.testing.assert_array_equal(outputs[0], outputs[1]) + assert disk.language_model._engram_prefetch._pending is None + assert resident.language_model._engram_prefetch._pending is None + assert all( + layer.engram.embed._resident is not None + for layer in resident.language_model.layers + if "engram" in layer + ) + from omlx.models.vlm import VLMModelAdapter + + VLMModelAdapter(disk).release_resources() + for layer in disk.language_model.layers: + if "engram" in layer: + assert layer.engram.embed._weights._mapping is None + assert disk.language_model._engram_prefetch._closed + finally: + resident.close() + disk.close() + + +def test_residency_counts_indexed_tensors_not_linked_shard_bytes(converted): + estimate = deepseek_v41_residency_estimate(converted) + spec = json.loads((converted / "config.json").read_text())["omlx_deepseek_v41"] + expected = (72 + 204) * 32 * 4 # Fixture uses float32 embeddings. + assert estimate.engram_bytes == expected + assert estimate.supported + assert estimate.resident_bytes > expected + # Files copied from the source contain unrelated tensors too. + assert ( + sum( + (converted / t["weight_file"]).stat().st_size + for t in spec["engram_tables"].values() + ) + > expected + ) + # Tiny fixtures cannot save enough RAM to cover the bounded I/O allowance. + assert not estimate.force_ssd_offload(estimate.resident_bytes - 1) + + +@pytest.mark.parametrize( + "ceiling,requested,expected,forced", + [ + (0, False, False, False), + (1000, False, False, False), + (500, False, True, True), + (300, False, False, False), + (1000, True, True, False), + ], +) +def test_memory_decision_and_reload_signature( + monkeypatch, ceiling, requested, expected, forced +): + from test_engine_pool import _make_pool + + from omlx.engine_pool import EngineEntry + from omlx.model_settings import ModelSettings + from omlx.patches.deepseek_v41.residency import EngramResidencyEstimate + + estimate = EngramResidencyEstimate(True, 1000, 400, 600) + monkeypatch.setattr( + "omlx.patches.deepseek_v41.residency.deepseek_v41_residency_estimate", + lambda _: estimate, + ) + pool = _make_pool(ceiling=ceiling) + entry = EngineEntry( + model_id="v41", + model_path="/fixture", + model_type="vlm", + engine_type="vlm", + config_model_type="deepseek_v41", + estimated_size=10, + ) + pool._entries["v41"] = entry + settings = ModelSettings(deepseek_v41_engram_ssd_offload=requested) + enabled, actual_forced, _ = pool._deepseek_v41_engram_offload_status( + entry, settings + ) + assert (enabled, actual_forced) == (expected, forced) + assert pool._entry_runtime_resident_size(entry, settings) == ( + 400 if expected else 1000 + ) + effective = pool._effective_deepseek_v41_model_settings(entry, settings) + assert effective.deepseek_v41_engram_ssd_offload == expected + assert settings.deepseek_v41_engram_ssd_offload == requested + if forced: + assert pool._effective_deepseek_v41_model_settings( + entry, None + ).deepseek_v41_engram_ssd_offload + if ceiling == 1000: + before = pool._engine_runtime_signature("v41", settings) + settings.deepseek_v41_engram_ssd_offload = not requested + assert before != pool._engine_runtime_signature("v41", settings) + + +def test_setting_roundtrip_excludes_shared_profile(tmp_path): + from omlx.model_settings import ModelSettingsManager + + manager = ModelSettingsManager(tmp_path) + settings = manager.get_settings("v41") + settings.deepseek_v41_engram_ssd_offload = True + manager.set_settings("v41", settings) + restored = ModelSettingsManager(tmp_path).get_settings("v41") + assert restored.deepseek_v41_engram_ssd_offload + manager.save_profile("v41", "sample", "Sample", None, restored.to_dict()) + profile = manager.list_profiles("v41")[0] + assert "deepseek_v41_engram_ssd_offload" not in profile["settings"] + + +def test_loader_failure_closes_all_tables(converted, monkeypatch): + tables = [] + original = DiskEngramEmbedding.__init__ + + def init(self, *args, **kwargs): + original(self, *args, **kwargs) + tables.append(self) + + def fail(*args, **kwargs): + raise ValueError("tokenizer failure") + + monkeypatch.setattr(DiskEngramEmbedding, "__init__", init) + monkeypatch.setattr( + "omlx.patches.deepseek_v41.loading.PreTrainedTokenizerFast.from_pretrained", + fail, + ) + with pytest.raises(ValueError, match="tokenizer failure"): + load(converted, engram_ssd_offload=True) + assert len(tables) == 2 + assert all(t._closed and t._weights._mapping is None for t in tables) + + +def test_model_close_unmaps_even_after_prefetch_failure(converted, monkeypatch): + model, _ = load(converted, engram_ssd_offload=True) + prefetch = model.language_model._engram_prefetch + embed = model.language_model.layers[1].engram.embed + entered = Event() + + def fail(rows): + entered.set() + raise OSError("read failed") + + monkeypatch.setattr(embed, "_read_rows", fail) + prefetch.submit(embed, np.array([1])) + assert entered.wait(5) + with pytest.raises(OSError, match="read failed"): + model.close() + for layer in model.language_model.layers: + if "engram" in layer: + assert layer.engram.embed._weights._mapping is None + model.close() + + +@pytest.mark.parametrize("offload", [False, True]) +def test_original_checkpoint_load_matches_export_without_writing( + converted, offload, monkeypatch +): + source = converted.parent / "source" + before = { + str(p): (p.stat().st_size, p.stat().st_mtime_ns) + for p in source.rglob("*") + if p.is_file() + } + exported, _ = load(converted, engram_ssd_offload=offload) + + def no_export(*args, **kwargs): + raise AssertionError("Direct loading must not export tensors") + + monkeypatch.setattr(mx, "save_safetensors", no_export) + original, _ = load(source, engram_ssd_offload=offload) + try: + caches = [m.language_model.make_cache() for m in (exported, original)] + for ids in ([[3, 4, 5]], [[6]], [[7]]): + actual = [ + m(mx.array(ids), cache=c) for m, c in zip((exported, original), caches) + ] + mx.eval(actual) + np.testing.assert_array_equal(*actual) + assert deepseek_v41_residency_estimate( + source + ) == deepseek_v41_residency_estimate(converted) + after = { + str(p): (p.stat().st_size, p.stat().st_mtime_ns) + for p in source.rglob("*") + if p.is_file() + } + assert before == after + finally: + exported.close() + original.close() + + +@pytest.mark.parametrize("bits", [4, 8]) +def test_direct_quantized_experts_and_dense_projection_match_export(converted, bits): + source = converted.parent / "source" + filename = source / "model.safetensors" + data = mx.load(str(filename)) + index_path = source / "model.safetensors.index.json" + index = json.loads(index_path.read_text()) + packed = {} + for key in list(data): + if not ( + (key.startswith("layers.0.ffn.experts.") and key.endswith(".w1.weight")) + or key == "layers.0.attn.wo_a.weight" + ): + continue + shape = data.pop(key).shape + width = shape[1] // 2 if bits == 4 and ".experts." in key else shape[1] + fp4 = width != shape[1] + raw = np.full((shape[0], width), 0x22, dtype=np.int8 if fp4 else np.uint8) + scale = np.full( + (shape[0] if fp4 else (shape[0] + 31) // 32, shape[1] // 32), + 124, + dtype=np.uint8, + ) + scale_key = key.removesuffix(".weight") + ".scale" + packed[key] = (raw, "I8" if fp4 else "F8_E4M3") + packed[scale_key] = (scale, "F8_E8M0") + index["weight_map"][key] = "quant.safetensors" + index["weight_map"][scale_key] = "quant.safetensors" + mx.eval(data) + mx.save_safetensors(str(filename), data) + raw_safetensors(source / "quant.safetensors", packed) + index_path.write_text(json.dumps(index)) + target = converted.parent / f"quantized-{bits}" + convert(source, target) + direct, _ = load(source, engram_ssd_offload=True) + exported, _ = load(target, engram_ssd_offload=True) + try: + assert direct.language_model.layers[0].ffn.experts.w1.bits == bits + assert deepseek_v41_residency_estimate( + source + ) == deepseek_v41_residency_estimate(target) + outputs = [m(mx.array([[3, 4, 5]])) for m in (direct, exported)] + mx.eval(outputs) + assert bool(mx.all(mx.isfinite(outputs[0])).item()) + np.testing.assert_array_equal(*outputs) + finally: + direct.close() + exported.close() + + +def test_source_iterator_releases_mappings_before_yield(converted, monkeypatch): + from omlx.patches.deepseek_v41 import convert as converter + + source = converted.parent / "source" + config = json.loads((source / "config.json").read_text()) + mapping = json.loads((source / "model.safetensors.index.json").read_text())[ + "weight_map" + ] + readers = [] + original = converter.TensorFile + + def open_reader(path): + reader = original(path) + readers.append(reader) + return reader + + monkeypatch.setattr(converter, "TensorFile", open_reader) + stream = converter.iter_source_weights(source, config, mapping) + try: + for values, _ in stream: + assert readers and all(reader._mapping is None for reader in readers) + mx.eval(values) + finally: + stream.close() + + +def test_residency_tracks_stored_head_precision(converted): + before = deepseek_v41_residency_estimate(converted) + mapping = json.loads((converted / "model.safetensors.index.json").read_text())[ + "weight_map" + ] + name = "language_model.head.weight" + filename = converted / mapping[name] + weights = mx.load(str(filename)) + assert weights[name].dtype == mx.float32 + weights[name] = weights[name].astype(mx.bfloat16) + mx.eval(weights) + mx.save_safetensors(str(filename), weights) + after = deepseek_v41_residency_estimate(converted) + assert before.resident_bytes > after.resident_bytes + assert before.mmap_bytes > after.mmap_bytes + assert before.engram_bytes == after.engram_bytes + + +@pytest.mark.parametrize("short_read", [False, True]) +def test_resident_reads_are_bounded_and_preserve_bytes( + tmp_path, monkeypatch, short_read +): + disk = table(tmp_path) + reader = disk._weights + expected, dtype = reader.read("w", np.arange(16)) + source = reader._file + requests = [] + + class TrackedFile: + def fileno(self): + return source.fileno() + + def seek(self, offset): + return source.seek(offset) + + def readinto(self, buffer): + requests.append(len(buffer)) + return source.readinto(buffer[:7] if short_read else buffer) + + def close(self): + source.close() + + reader._file = TrackedFile() + monkeypatch.setattr(storage, "RESIDENT_READ_BYTES", 31) + try: + actual, actual_dtype = reader.read("w") + assert actual_dtype == dtype + np.testing.assert_array_equal(actual, expected) + assert len(requests) > 1 and max(requests) <= 31 + assert actual.flags.owndata + finally: + disk.close() + + +@pytest.mark.parametrize("failed_key", ["w", "s"]) +def test_resident_read_rejects_unexpected_eof(tmp_path, monkeypatch, failed_key): + disk = table(tmp_path) + reader = disk._weights + source = reader._file + original = source.readinto + fail_at = reader._start + reader.header[failed_key]["data_offsets"][0] + + def readinto(buffer): + return 0 if source.tell() >= fail_at else original(buffer) + + monkeypatch.setattr(source, "readinto", readinto) + toggles = [] + original_fcntl = storage.fcntl.fcntl + + def tracked_fcntl(fd, command, value): + toggles.append(value) + return original_fcntl(fd, command, value) + + monkeypatch.setattr(storage.fcntl, "fcntl", tracked_fcntl) + try: + with pytest.raises(ValueError, match="Truncated tensor data"): + disk.make_resident() + assert disk._resident is None + if hasattr(storage.fcntl, "F_NOCACHE"): + assert toggles and toggles == [1, 0] * (len(toggles) // 2) + finally: + disk.close() + + +def test_empty_resident_tensor(tmp_path): + path = tmp_path / "empty.safetensors" + raw_safetensors(path, {"w": (np.empty((0, 32), np.uint8), "U8")}) + reader = storage.TensorFile(path) + try: + result, dtype = reader.read("w") + assert result.shape == (0, 32) and dtype == "U8" + finally: + reader.close() + + +@pytest.mark.parametrize("fail", [False, True]) +def test_resident_load_restores_wired_limit(converted, monkeypatch, fail): + def fail_tokenizer(*args, **kwargs): + raise ValueError("tokenizer failure") + + if fail: + monkeypatch.setattr( + loading.PreTrainedTokenizerFast, "from_pretrained", fail_tokenizer + ) + previous = mx.set_wired_limit(0) + model = None + try: + if fail: + with pytest.raises(ValueError, match="tokenizer failure"): + load(converted, engram_ssd_offload=False) + else: + model, _ = load(converted, engram_ssd_offload=False) + assert mx.set_wired_limit(0) == 0 + finally: + if model is not None: + model.close() + mx.synchronize() + mx.set_wired_limit(previous) + + +def test_resident_storage_counts_packed_bytes_and_releases_on_close(tmp_path): + import gc + + path = tmp_path / "packed.safetensors" + weight = np.arange(8192 * 32, dtype=np.uint32).reshape(8192, 32) + scale = np.full((8192, 8), 0x3F80, dtype=np.uint16) + raw_safetensors(path, {"w": (weight, "U32"), "s": (scale, "BF16")}) + disk = DiskEngramEmbedding(path, "w", "s") + mx.synchronize() + gc.collect() + before = mx.get_active_memory() + try: + disk.make_resident() + assert mx.get_active_memory() >= before + weight.nbytes + scale.nbytes + assert not disk._resident["w"][0].flags.owndata + np.testing.assert_array_equal(disk._resident["w"][0], weight) + np.testing.assert_array_equal(disk._resident["s"][0], scale) + assert disk._resident["s"][1] == "BF16" + assert disk._weights._mapping is None + finally: + disk.close() + mx.synchronize() + gc.collect() + assert mx.get_active_memory() <= before + + +def test_resident_engram_follows_backbone_load(converted, monkeypatch): + events = [] + original_weights = loading.Model.load_weights + original_resident = DiskEngramEmbedding.make_resident + + def weights(self, *args, **kwargs): + result = original_weights(self, *args, **kwargs) + events.append("weights") + return result + + def resident(self): + events.append("resident") + return original_resident(self) + + monkeypatch.setattr(loading.Model, "load_weights", weights) + monkeypatch.setattr(DiskEngramEmbedding, "make_resident", resident) + model, _ = load(converted, engram_ssd_offload=False) + try: + assert "weights" in events and "resident" in events + first_resident = events.index("resident") + assert all(event == "weights" for event in events[:first_resident]) + assert all(event == "resident" for event in events[first_resident:]) + logits = model.language_model(mx.array([[3, 4, 5]])) + assert mx.all(mx.isfinite(logits)).item() + finally: + model.close() + + +def test_shard_reader_preserves_packed_bytes_after_close(tmp_path, monkeypatch): + path = tmp_path / "packed.safetensors" + expected = { + "weight": mx.arange(128, dtype=mx.uint32).reshape(4, 32), + "scales": mx.array([[0.5, 1.0], [2.0, 4.0]], dtype=mx.bfloat16), + } + mx.save_safetensors(str(path), expected) + original = mx.load + readers = [] + + def tracked_load(reader): + readers.append(reader) + assert not reader.closed + return original(reader) + + monkeypatch.setattr(loading.mx, "load", tracked_load) + actual = loading._load_shard(path) + assert len(readers) == 1 and readers[0].closed + for name, value in expected.items(): + assert actual[name].dtype == value.dtype + assert actual[name].shape == value.shape + assert mx.array_equal(actual[name], value).item() + + +def test_shard_reader_closes_on_invalid_checkpoint(tmp_path, monkeypatch): + path = tmp_path / "invalid.safetensors" + path.write_bytes(b"not a checkpoint") + original = mx.load + readers = [] + + def tracked_load(reader): + readers.append(reader) + return original(reader) + + monkeypatch.setattr(loading.mx, "load", tracked_load) + with pytest.raises((ValueError, RuntimeError)): + loading._load_shard(path) + assert len(readers) == 1 and readers[0].closed + + +def page_table(tmp_path): + path = tmp_path / "pages.safetensors" + raw = np.arange(4096 * 64, dtype=np.uint8).reshape(4096, 64) + raw_safetensors(path, {"w": (raw, "U8")}) + return storage.TensorFile(path), raw + + +def test_parallel_pages_preserve_order_short_reads_and_warm_hits(tmp_path, monkeypatch): + reader, raw = page_table(tmp_path) + original = storage.os.pread + calls = [] + + def short_read(fd, count, offset): + calls.append((count, offset)) + return original(fd, min(count, 4096), offset) + + monkeypatch.setattr(storage.os, "pread", short_read) + ids = np.tile(np.array([4095, 0, 255, 256, 1023, 256]), 32) + try: + actual, dtype = reader.read("w", ids) + assert dtype == "U8" and calls + np.testing.assert_array_equal(actual, raw[ids]) + count = len(calls) + repeated, _ = reader.read("w", ids) + assert len(calls) == count + np.testing.assert_array_equal(repeated, actual) + finally: + reader.close() + # A returned row copy cannot retain or depend on the closed file mapping. + np.testing.assert_array_equal(actual, raw[ids]) + assert reader._seen_pages is None + + +def test_decode_rows_skip_page_prefetch(tmp_path, monkeypatch): + reader, raw = page_table(tmp_path) + + def unexpected(*args): + raise AssertionError("Decode rows must retain the direct mmap path") + + monkeypatch.setattr(storage.os, "pread", unexpected) + try: + ids = np.arange(24) + actual, _ = reader.read("w", ids) + np.testing.assert_array_equal(actual, raw[ids]) + assert reader._seen_pages is None + finally: + reader.close() + + +def test_page_read_failure_drains_workers_before_close(tmp_path, monkeypatch): + reader, _ = page_table(tmp_path) + original = storage.os.pread + entered, release, closing = Event(), Event(), Event() + monkeypatch.setattr(storage, "PAGE_IO_WORKERS", 2) + + def blocked_read(fd, count, offset): + if offset == 0: + raise OSError("page read failed") + entered.set() + assert release.wait(5) + assert not reader._file.closed + return original(fd, count, offset) + + def close(): + closing.set() + reader.close() + + monkeypatch.setattr(storage.os, "pread", blocked_read) + with ThreadPoolExecutor(max_workers=2) as executor: + reading = executor.submit(reader.read, "w", np.arange(4096)) + try: + assert entered.wait(5) + closed = executor.submit(close) + assert closing.wait(5) + assert not closed.done() + finally: + release.set() + with pytest.raises(OSError, match="page read failed"): + reading.result(timeout=5) + closed.result(timeout=5) + assert reader._file.closed and reader._mapping is None + + +def test_slow_warm_gather_rearms_page_prefetch(tmp_path, monkeypatch): + reader, _ = page_table(tmp_path) + ids = np.arange(256) + try: + reader.read("w", ids) + assert reader._seen_pages is not None + ticks = iter([0.0, 1.0]) + monkeypatch.setattr(storage.time, "perf_counter", lambda: next(ticks)) + monkeypatch.setattr(storage.time, "monotonic", lambda: 100.0) + reader.read("w", ids) + assert reader._seen_pages is None + reader.read("w", ids) + assert reader._seen_pages is not None + finally: + reader.close() diff --git a/tests/test_deepseek_v41_oq.py b/tests/test_deepseek_v41_oq.py new file mode 100644 index 0000000000..1d9f5b2608 --- /dev/null +++ b/tests/test_deepseek_v41_oq.py @@ -0,0 +1,586 @@ +"""Independent Engram budgets and bounded affine storage round trips.""" + +import json +import math + +import mlx.core as mx +import numpy as np +import pytest + +from omlx.patches.deepseek_v41.oq import quantize_engram, source_budget +from omlx.patches.deepseek_v41.storage import DiskEngramEmbedding, EngramPrefetch + + +def test_shards_pack_small_groups_without_splitting_quantized_projection(tmp_path): + from omlx.patches.deepseek_v41.sharding import ShardWriter + + writer = ShardWriter(tmp_path, max_shard_bytes=160) + groups = [ + {"a.weight": mx.arange(20, dtype=mx.float32)}, + { + "b.weight": mx.arange(12, dtype=mx.uint32), + "b.scales": mx.ones((4,), mx.float32), + "b.biases": mx.zeros((4,), mx.float32), + }, + {"c.weight": mx.arange(20, dtype=mx.float32)}, + ] + for group in groups: + writer.add(group) + mapping = writer.finish() + assert len(set(mapping.values())) == 2 + assert ( + mapping["a.weight"] + == mapping["b.weight"] + == mapping["b.scales"] + == mapping["b.biases"] + ) + assert len(list(tmp_path.glob("*.safetensors"))) == 2 + for group in groups: + for name, value in group.items(): + np.testing.assert_array_equal( + mx.load(str(tmp_path / mapping[name]))[name], value + ) + + +def test_shard_writer_keeps_oversized_projection_intact(tmp_path): + from omlx.patches.deepseek_v41.sharding import ShardWriter + + writer = ShardWriter(tmp_path, max_shard_bytes=16) + writer.add({"big.weight": mx.ones((16,)), "big.scales": mx.ones((2,))}) + writer.add({"small.weight": mx.ones((1,))}) + mapping = writer.finish() + assert mapping["big.weight"] == mapping["big.scales"] + assert mapping["big.weight"] != mapping["small.weight"] + + +@pytest.mark.parametrize("switched", [False, True]) +def test_affine_projection_respects_bias_and_group_size(switched): + from omlx.patches.deepseek_v41.quantization import ( + QuantizedProjection, + quantize_activation, + ) + + mx.random.seed(41) + weights = mx.random.normal((3, 16, 64) if switched else (16, 64)).astype( + mx.bfloat16 + ) + packed, scales, biases = mx.quantize(weights, bits=4, group_size=64) + projection = QuantizedProjection( + packed, scales, bits=4, mode="affine", biases=biases, group_size=64 + ) + x = mx.random.normal((2, 1, 64) if switched else (2, 64)).astype(mx.bfloat16) + restored = mx.dequantize(packed, scales, biases, bits=4, group_size=64) + if switched: + indices = mx.array([2, 0]) + actual = projection(x, indices) + expected = mx.matmul(quantize_activation(x), restored[indices].swapaxes(-1, -2)) + else: + actual = projection(x) + expected = quantize_activation(x) @ restored.T + np.testing.assert_allclose( + actual.astype(mx.float32), expected.astype(mx.float32), atol=0.125, rtol=0.02 + ) + + +def test_engram_size_does_not_change_remaining_budget(tmp_path): + reports = [] + for rows in (4, 400): + path = tmp_path / str(rows) + path.mkdir() + weights = { + "layers.0.attn.wq_a.weight": mx.ones((32, 32), mx.bfloat16), + "layers.1.engram.embed.weight": mx.ones((rows, 32), mx.bfloat16), + } + mx.save_safetensors(str(path / "model.safetensors"), weights) + reports.append( + source_budget( + path, {}, {k: "model.safetensors" for k in weights}, preserve_mtp=False + ) + ) + assert reports[0]["remaining_weights"] == reports[1]["remaining_weights"] + assert reports[0]["remaining_weights"]["effective_bpw"] == 16 + assert ( + reports[1]["engram"]["tensor_bytes"] + == reports[0]["engram"]["tensor_bytes"] * 100 + ) + assert reports[1]["engram"]["effective_bpw"] == 5 + + +@pytest.mark.parametrize("resident", [False, True]) +@pytest.mark.parametrize("bits", [2, 3, 4, 6, 8]) +def test_chunked_engram_affine_matches_mlx_with_prefetch(tmp_path, resident, bits): + mx.random.seed(341) + weight = mx.random.normal((17, 256)).astype(mx.bfloat16) + mx.save_safetensors(str(tmp_path / "source.safetensors"), {"embed.weight": weight}) + result = quantize_engram( + tmp_path, + tmp_path / "engram.safetensors", + {"weight_file": "source.safetensors", "weight_key": "embed.weight"}, + rows_per_chunk=3, + bits=bits, + ) + loaded = mx.load(str(tmp_path / "engram.safetensors")) + expected = mx.quantize(weight, bits=bits, group_size=32) + for key, value in zip(("weight", "scales", "biases"), expected): + np.testing.assert_array_equal( + loaded[key].view(mx.uint32 if key == "weight" else mx.uint16), + value.view(mx.uint32 if key == "weight" else mx.uint16), + ) + embed = DiskEngramEmbedding( + tmp_path / result["weight_file"], + result["weight_key"], + result["scale_key"], + bias_key=result["bias_key"], + bits=bits, + group_size=32, + ) + prefetch = EngramPrefetch() + try: + if resident: + embed.make_resident() + ids = mx.array([[0, 16, 7, 7]]) + with prefetch.forward(): + prefetch.submit(embed, ids) + actual = embed(ids) + np.testing.assert_array_equal( + actual.astype(mx.float32), + mx.dequantize(*expected, bits=bits, group_size=32)[ids].astype(mx.float32), + ) + assert embed.selected_bytes(4) == 4 * (256 * bits // 8 + 16 + 16) + finally: + prefetch.close() + embed.close() + + +def test_engram_does_not_hide_remaining_budget_failure(tmp_path): + from omlx.patches.deepseek_v41.oq import quantize + + source = tmp_path / "source" + source.mkdir() + weights = { + "layers.0.attn.wq_a.weight": mx.ones((32, 32), mx.bfloat16), + "layers.1.engram.embed.weight": mx.ones((400, 32), mx.bfloat16), + } + mx.save_safetensors(str(source / "model.safetensors"), weights) + (source / "config.json").write_text(json.dumps({"model_type": "deepseek_v41"})) + (source / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": {k: "model.safetensors" for k in weights}}) + ) + # The combined average is below 6 bpw, but the separate trunk is 16 bpw. + with pytest.raises(ValueError, match="exceeds"): + quantize(source, tmp_path / "output", target_bpw=6, hard_cap_bpw=6) + assert not (tmp_path / "output").exists() + + +def test_oq_entrypoint_preserves_dspark_and_separate_report(tmp_path): + from mlx.utils import tree_flatten + from test_deepseek_v41 import write_checkpoint + + from omlx.oq import quantize_oq_streaming + from omlx.patches.deepseek_v41.loading import load + + source, original = write_checkpoint( + tmp_path, + preserve_mtp=True, + n_mtp_layers=3, + dspark_block_size=3, + dspark_noise_token_id=2, + dspark_target_layer_ids=(2, 3, 4), + dspark_n_routed_experts=2, + dspark_n_activated_experts=1, + dspark_markov_rank=32, + compress_ratios=(0, 2, 2, 1, 1, 0, 0, 0), + ) + output = tmp_path / "tiny-oQ4e-mtp" + # The tiny fixture is FP32; use an explicit budget to test the lossless path. + quantize_oq_streaming( + str(source), + str(output), + 4, + enhanced=True, + preserve_mtp=True, + target_bpw=32, + hard_cap_bpw=32, + ) + model, _ = load(output) + try: + expected = dict(tree_flatten(original.parameters())) + for name, value in tree_flatten(model.parameters()): + np.testing.assert_array_equal(value, expected[name]) + assert len(model.language_model.mtp) == 3 + report = json.loads((output / "quantization_report.json").read_text()) + assert report["budget_scope"] == "remaining_weights_excluding_engram" + assert report["preserved_source_draft_tensors"] > 0 + assert report["imatrix_applied_modules"] == [] + finally: + model.close() + + +def test_unified_index_engram_and_mixed_shard_offload(tmp_path, monkeypatch): + from test_deepseek_v41 import write_checkpoint + + from omlx.patches.deepseek_v41.loading import load + from omlx.patches.deepseek_v41.oq import quantize + from omlx.patches.deepseek_v41.residency import deepseek_v41_residency_estimate + + source, _ = write_checkpoint( + tmp_path, + vision=False, + engram_layer_ids=(1, 3), + engram_num_embeddings=(72, 204), + engram_vocab_size=5, + engram_max_ngram_size=4, + engram_n_heads=2, + engram_head_dim=32, + engram_compressed_vocab_size=64, + ) + output = tmp_path / "quantized" + quantize(source, output, enhanced=True, target_bpw=32, hard_cap_bpw=32) + assert not (output / "engram").exists() + config = json.loads((output / "config.json").read_text()) + index = json.loads((output / "model.safetensors.index.json").read_text()) + mapping = index["weight_map"] + tables = config["omlx_deepseek_v41"]["engram_tables"] + table_keys = { + table[key] + for table in tables.values() + for key in ("weight_key", "scale_key", "bias_key") + } + assert table_keys <= set(mapping) + assert all("/" not in name for name in mapping.values()) + before = deepseek_v41_residency_estimate(output) + report = config["omlx_deepseek_v41"]["quantization_report"] + assert before.engram_bytes == report["engram"]["tensor_bytes"] + assert ( + before.mmap_bytes + == int(report["remaining_weights"]["tensor_bytes"] * 1.05) + 32 * 1024**2 + ) + + # Put one lookup table and normal weights in the same small fixture shard. + first = next(iter(tables.values())) + normal_file = next( + filename for key, filename in mapping.items() if key not in table_keys + ) + values = { + **mx.load(str(output / normal_file)), + **mx.load(str(output / first["weight_file"])), + } + mx.save_safetensors(str(output / "mixed.safetensors"), values) + for key in values: + mapping[key] = "mixed.safetensors" + first["weight_file"] = first["scale_file"] = "mixed.safetensors" + (output / "model.safetensors.index.json").write_text(json.dumps(index)) + (output / "config.json").write_text(json.dumps(config)) + actual_load = mx.load + + def guarded_load(path, *args, **kwargs): + assert not str(path).endswith( + "mixed.safetensors" + ), "Must not load offloaded table through mx.load" + return actual_load(path, *args, **kwargs) + + monkeypatch.setattr(mx, "load", guarded_load) + disk, _ = load(output, engram_ssd_offload=True) + resident, _ = load(output, engram_ssd_offload=False) + try: + ids = mx.array([[3, 4, 5]]) + np.testing.assert_allclose( + disk(ids).astype(mx.float32), resident(ids).astype(mx.float32), atol=1e-6 + ) + assert deepseek_v41_residency_estimate(output) == before + finally: + disk.close() + resident.close() + + +@pytest.mark.parametrize("bits", [2, 3, 4, 6, 8]) +@pytest.mark.parametrize("rank", [2, 3]) +def test_requantize_projection_uses_weighted_oq_arithmetic(bits, rank): + from omlx.oq import _quantize_chunked + from omlx.patches.deepseek_v41.oq import requantize_projection + + with mx.stream(mx.cpu): + shape = (16, 64) if rank == 2 else (2, 16, 64) + weight = mx.sin(mx.arange(math.prod(shape)).reshape(shape)).astype(mx.bfloat16) + importance = mx.linspace(0.1, 2.0, 64) + if rank == 3: + importance = mx.stack([importance, importance[::-1]]) + values, spec = requantize_projection( + {"p.weight": weight}, "p", None, bits=bits, importance=importance + ) + reference = _quantize_chunked(weight, 64, bits, "affine", importance) + for suffix, expected in zip(("weight", "scales", "biases"), reference): + assert mx.array_equal(values["p." + suffix], expected).item() + assert spec == dict( + bits=bits, group_size=64, mode="affine", quantize_input=False + ) + + +@pytest.mark.parametrize( + "source_bits,mode", [(4, "mxfp4"), (8, "mxfp8"), (6, "affine")] +) +@pytest.mark.parametrize("quantize_input", [False, True]) +def test_requantize_packed_source_preserves_activation_policy( + source_bits, mode, quantize_input +): + from omlx.patches.deepseek_v41.oq import requantize_projection + + with mx.stream(mx.cpu): + dense = mx.cos(mx.arange(2048).reshape(2, 16, 64)).astype(mx.bfloat16) + packed = mx.quantize(dense, bits=source_bits, group_size=32, mode=mode) + values = {"p." + k: v for k, v in zip(("weight", "scales", "biases"), packed)} + source_spec = dict( + bits=source_bits, group_size=32, mode=mode, quantize_input=quantize_input + ) + actual, spec = requantize_projection(values, "p", source_spec, bits=3) + restored = mx.dequantize(*packed, bits=source_bits, group_size=32, mode=mode) + expected, _ = requantize_projection({"p.weight": restored}, "p", None, bits=3) + for key in expected: + assert mx.array_equal(actual[key], expected[key]).item() + assert spec["quantize_input"] is quantize_input + + +@pytest.mark.parametrize("enhanced", [False, True]) +def test_official_oq3_streams_affine_weights_and_unified_engram( + tmp_path, monkeypatch, enhanced +): + from test_deepseek_v41 import write_checkpoint + + from omlx import oq + from omlx.patches.deepseek_v41 import oq as converter + from omlx.patches.deepseek_v41.loading import load + + with mx.stream(mx.cpu): + source, original = write_checkpoint( + tmp_path, + vision=False, + dim=64, + engram_layer_ids=(1, 3), + engram_num_embeddings=(72, 204), + engram_vocab_size=5, + engram_max_ngram_size=4, + engram_n_heads=2, + engram_head_dim=32, + engram_compressed_vocab_size=64, + ) + name = "language_model.layers.0.attn.wq_a" + weight = original.language_model.layers[0].attn.wq_a.weight + received = {} + + def prepare(source, output, config, mapping, budget, **kwargs): + received.update(kwargs) + count = weight.size + new_bytes = ( + budget["remaining_weights"]["tensor_bytes"] + - weight.nbytes + + count * 7 // 16 + ) + stats = oq.OQImatrixData( + { + name: oq.OQImatrixEntry( + np.linspace(1, 2, 64).astype(np.float32), np.array([1]) + ) + }, + {}, + "fixture", + ) + return ( + {name: dict(bits=3, group_size=64, mode="affine")}, + stats, + dict( + tensor_bytes=new_bytes, + effective_bpw=8 + * new_bytes + / budget["remaining_weights"]["logical_parameters"], + ), + ) + + monkeypatch.setattr(converter, "prepare_affine_conversion", prepare) + output = tmp_path / "oq3" + oq.quantize_oq_streaming( + str(source), + str(output), + 3, + enhanced=enhanced, + target_bpw=32, + hard_cap_bpw=32, + imatrix_num_samples=17, + imatrix_seq_length=64, + imatrix_strict=True, + imatrix_reuse_cache=False, + imatrix_cache_path="selected-cache", + sensitivity_model_path="selected-proxy", + ) + assert received["imatrix_num_samples"] == 17 + assert received["imatrix_seq_length"] == 64 + assert received["imatrix_strict"] is True + assert received["imatrix_reuse_cache"] is False + assert received["imatrix_cache_path"] == "selected-cache" + assert received["sensitivity_model_path"] == "selected-proxy" + config = json.loads((output / "config.json").read_text()) + spec = config["omlx_deepseek_v41"] + assert spec["quantized_modules"][name]["bits"] == 3 + assert spec["quantized_modules"][name]["quantize_input"] is False + assert all(table["bits"] == 3 for table in spec["engram_tables"].values()) + assert spec["engram_in_index"] + assert not (output / "conversion.inprogress.json").exists() + assert not (output / "engram").exists() + report = json.loads((output / "quantization_report.json").read_text()) + assert report["imatrix_applied_modules"] == ([name] if enhanced else []) + loaded, _ = load(output, engram_ssd_offload=True) + try: + projection = loaded.language_model.layers[0].attn.wq_a + actual = projection(mx.ones((1, 64), mx.bfloat16)) + assert mx.all(mx.isfinite(actual)).item() + finally: + loaded.close() + + +def test_ui_source_filter_excludes_converted_v41(): + from omlx.oq import validate_quantizable + + source = { + "model_type": "deepseek_v41", + "quantization_config": {"quant_method": "fp8", "expert_dtype": "fp4"}, + } + assert validate_quantizable(source) + assert not validate_quantizable( + {"model_type": "deepseek_v41", "omlx_deepseek_v41": {"version": 1}} + ) + + +@pytest.mark.parametrize("level", [3, 4]) +def test_v41_estimate_uses_independent_engram_budget(tmp_path, level): + from omlx.oq import estimate_bpw_and_size + + source = tmp_path / "source" + source.mkdir() + # Estimation reads headers only; no valid inference architecture is needed. + with mx.stream(mx.cpu): + weights = { + "layers.0.attn.wq_a.weight": mx.ones((64, 64), mx.bfloat16), + "layers.1.engram.embed.weight": mx.ones((128, 64), mx.bfloat16), + } + mx.save_safetensors(str(source / "model.safetensors"), weights) + (source / "config.json").write_text(json.dumps({"model_type": "deepseek_v41"})) + (source / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": {k: "model.safetensors" for k in weights}}) + ) + result = estimate_bpw_and_size(str(source), level) + assert result["engram_size_bytes"] == 8192 * level // 8 + 8192 // 32 * 4 + assert result["remaining_size_bytes"] == ( + math.ceil(4096 * 3.7 / 8) if level == 3 else 8192 + ) + assert ( + result["output_size_bytes"] + == result["engram_size_bytes"] + result["remaining_size_bytes"] + ) + assert result["memory_streaming_bytes"] > 0 + + +def test_official_oq3_reuses_signed_imatrix_and_applies_real_plan( + tmp_path, monkeypatch +): + from test_deepseek_v41 import write_checkpoint + + from omlx import oq + from omlx.patches.deepseek_v41 import loading + + with mx.stream(mx.cpu): + source, original = write_checkpoint(tmp_path, vision=False, dim=64) + config = json.loads((source / "config.json").read_text()) + name = "language_model.layers.0.attn.wq_a" + cache_path = tmp_path / "imatrix.npz" + metadata = oq._source_imatrix_signature( + source, + config, + num_samples=17, + seq_length=64, + calib_dataset=oq._OQE_CALIB_DATASET, + ) + metadata["collection"] = {"uncalibrated_policy": "preserve_source_precision"} + oq._save_oqe_imatrix( + cache_path, + { + name: oq.OQImatrixEntry( + np.linspace(1, 2, 64).astype(np.float32), np.array([17]) + ) + }, + metadata, + ) + + def no_model_load(*args, **kwargs): + raise AssertionError( + "Signed cache and sensitivity override must avoid calibration load" + ) + + monkeypatch.setattr(loading, "load", no_model_load) + output = tmp_path / "converted" + oq.quantize_oq_streaming( + str(source), + str(output), + 3, + enhanced=True, + target_bpw=32, + hard_cap_bpw=32, + imatrix_num_samples=17, + imatrix_seq_length=64, + imatrix_cache_path=str(cache_path), + sensitivity_map_override={0: 0.25}, + ) + report = json.loads((output / "quantization_report.json").read_text()) + assert report["calibration"]["imatrix_cache_reused"] is True + assert report["calibration"]["sensitivity"] == {"0": 0.25} + assert report["imatrix_applied_modules"] == [name] + assert ( + report["remaining_weights"]["tensor_bytes"] + == report["calibration"]["tensor_bytes"] + ) + saved = json.loads((output / "config.json").read_text())["omlx_deepseek_v41"] + assert saved["quantized_modules"][name]["bits"] in (3, 4, 6, 8) + + +def test_expert_requantization_cancellation_does_not_process_remaining_experts(): + from omlx.patches.deepseek_v41.oq import requantize_projection + + with mx.stream(mx.cpu): + weight = mx.ones((3, 16, 64), mx.bfloat16) + values = {"p.weight": weight} + calls = [] + + def cancel(done, total): + calls.append((done, total)) + raise RuntimeError("cancelled") + + with pytest.raises(RuntimeError, match="cancelled"): + requantize_projection(values, "p", None, bits=3, progress=cancel) + assert calls == [(16, 48)] + assert list(values) == ["p.weight"] + assert values["p.weight"] is weight + + +def test_unobserved_expert_uses_affine_three_bits_without_importance(): + from omlx import oq + from omlx.patches.deepseek_v41.oq import requantize_projection + + with mx.stream(mx.cpu): + weight = mx.sin(mx.arange(2048).reshape(2, 16, 64)).astype(mx.bfloat16) + entry = oq.OQImatrixEntry( + np.stack([np.linspace(0.1, 2, 64), np.zeros(64)]).astype(np.float32), + np.array([10, 0]), + ) + data = oq.OQImatrixData({"p": entry}, {}, "fixture") + importance = oq._lookup_imatrix_importance( + data, "p.weight", weight.shape, strict=True, report=None + ) + assert mx.array_equal(importance[1], mx.ones((64,))).item() + result, spec = requantize_projection( + {"p.weight": weight}, "p", None, bits=3, importance=importance + ) + plain = mx.quantize(weight[1], bits=3, group_size=64, mode="affine") + for suffix, expected in zip(("weight", "scales", "biases"), plain): + assert mx.array_equal(result["p." + suffix][1], expected).item() + observed = oq._quantize_chunked(weight[0], 64, 3, "affine", importance[0]) + for suffix, expected in zip(("weight", "scales", "biases"), observed): + assert mx.array_equal(result["p." + suffix][0], expected).item() + assert spec["bits"] == 3 and spec["mode"] == "affine" diff --git a/tests/test_deepseek_v41_routing.py b/tests/test_deepseek_v41_routing.py new file mode 100644 index 0000000000..33ac59805d --- /dev/null +++ b/tests/test_deepseek_v41_routing.py @@ -0,0 +1,82 @@ +import mlx.core as mx +import numpy as np +import pytest + +from omlx.patches.deepseek_v41.routing import combine_sorted_experts as combine + + +@pytest.mark.parametrize( + "batch,length,width", [(1, 32, 64), (2, 33, 513), (1, 256, 5120)] +) +def test_reference_repeat_and_layout(batch, length, width): + mx.random.seed(147) + n = batch * length * 6 + inverse = mx.argsort(mx.random.uniform(shape=(n,))) + # Noncontiguous storage also exercises the Metal input-copy contract. + routed = mx.random.normal((n, 1, width * 2)).astype(mx.bfloat16)[..., ::2] + shared = mx.random.normal((batch, length, width)).astype(mx.bfloat16) + expected = ( + routed[inverse].reshape(batch, length, 6, width).astype(mx.float32).sum(-2) + + shared.astype(mx.float32) + ).astype(mx.bfloat16) + actual = combine(routed, inverse, shared) + assert actual is not None and actual.dtype == mx.bfloat16 + np.testing.assert_array_equal( + actual.astype(mx.float32), expected.astype(mx.float32) + ) + np.testing.assert_array_equal( + actual.astype(mx.float32), combine(routed, inverse, shared).astype(mx.float32) + ) + + +def test_cancellation_and_shared_rounding(): + routed = mx.array([256.0, 1.0, -256.0, 0.125, -0.125, 2.0], mx.bfloat16).reshape( + 6, 1, 1 + ) + shared = mx.array([[[0.25]]], mx.bfloat16) + actual = combine(routed, mx.arange(6, dtype=mx.uint32), shared) + assert actual.item() == 3.25 + + +def test_unsupported_layouts(): + x = mx.zeros((6, 1, 4), mx.bfloat16) + order = mx.arange(6, dtype=mx.uint32) + s = mx.zeros((1, 1, 4), mx.bfloat16) + assert combine(x.astype(mx.float32), order, s) is None + assert combine(x, order.astype(mx.int32), s) is None + assert combine(x[:3], order[:3], s) is None + assert combine(x, order, s.astype(mx.float32)) is None + assert combine(x[:0], order[:0], s[:, :0]) is None + + +def test_moe_dispatch_preserves_sorted_reference(monkeypatch): + from mlx.utils import tree_flatten + from test_deepseek_v41 import tiny + + import omlx.patches.deepseek_v41.language as language + + mx.random.seed(417) + layer = language.MoE(tiny(n_routed_experts=8, n_activated_experts=6)) + layer.load_weights( + [ + (name, (mx.random.normal(weight.shape) * 0.1).astype(mx.bfloat16)) + for name, weight in tree_flatten(layer.parameters()) + ] + ) + x = mx.random.normal((2, 33, 32)).astype(mx.bfloat16) + calls = [] + + def observed(*args): + result = combine(*args) + calls.append(result is not None) + return result + + monkeypatch.setattr(language, "combine_sorted_experts", observed) + actual = layer(x, None) + mx.eval(actual) + assert calls == [True] + monkeypatch.setattr(language, "combine_sorted_experts", lambda *args: None) + expected = layer(x, None) + np.testing.assert_array_equal( + actual.astype(mx.float32), expected.astype(mx.float32) + ) diff --git a/tests/test_deepseek_v41_sensitivity.py b/tests/test_deepseek_v41_sensitivity.py new file mode 100644 index 0000000000..7d5b456cbe --- /dev/null +++ b/tests/test_deepseek_v41_sensitivity.py @@ -0,0 +1,107 @@ +"""V4.1 layer sensitivity preserves the full-forward cache and weights.""" + +from types import SimpleNamespace + +import mlx.core as mx +import mlx.nn as nn +import pytest + +from omlx.patches.deepseek_v41.cache import DeepseekV41Cache +from omlx.patches.deepseek_v41.sensitivity import measure_sensitivity + + +class Block(nn.Module): + def __init__(self): + super().__init__() + self.proj = nn.Linear(64, 64, bias=False) + self.proj.weight = mx.sin(mx.arange(4096).reshape(64, 64)).astype(mx.bfloat16) + + def __call__(self, h, pre, cache, shared, start, image_mask): + old = cache[1] + if old is not None: + h = h + old + h = h + shared.get("h", mx.zeros_like(h)) + value = self.proj(h) + cache[1] = value + shared["h"] = value + return value, pre + + +class Core(nn.Module): + def __init__(self): + super().__init__() + self.layers = [Block(), Block()] + + def make_cache(self): + return [DeepseekV41Cache(), DeepseekV41Cache()] + + def __call__(self, x, cache): + h = mx.sin(x[..., None] + mx.arange(64)).astype(mx.bfloat16) + pre = mx.ones_like(h) + shared = {} + for block, state in zip(self.layers, cache): + h, pre = block(h, pre, state, shared, 0, None) + return h + + +@pytest.mark.parametrize("cancel_phase", [None, "capture", "measure"]) +def test_measure_sensitivity_restores_layers_weights_and_snapshots( + monkeypatch, cancel_phase +): + import omlx.oq as oq + + with mx.stream(mx.cpu): + model = SimpleNamespace(language_model=Core()) + core = model.language_model + originals = list(core.layers) + projections = [layer.proj for layer in originals] + tokens = mx.array([[1, 2], [3, 4]]) + monkeypatch.setattr(oq, "_load_calibration_data", lambda *args: tokens) + expected = core(tokens, cache=core.make_cache()) + mx.eval(expected) + + def progress(phase, done, total): + if phase == cancel_phase: + raise RuntimeError("cancelled") + + if cancel_phase: + with pytest.raises(RuntimeError, match="cancelled"): + measure_sensitivity( + model, None, num_samples=2, seq_length=2, progress=progress + ) + else: + scores = measure_sensitivity(model, None, num_samples=2, seq_length=2) + repeated = measure_sensitivity(model, None, num_samples=2, seq_length=2) + assert scores == repeated + assert set(scores) == {0, 1} + assert all(0 < value < 1 for value in scores.values()) + assert all(a is b for a, b in zip(core.layers, originals)) + assert all(layer.proj is proj for layer, proj in zip(core.layers, projections)) + actual = core(tokens, cache=core.make_cache()) + assert mx.array_equal(actual, expected).item() + + +def test_cancellation_during_second_projection_restores_first(): + from omlx.patches.deepseek_v41.sensitivity import _quantized_block + + with mx.stream(mx.cpu): + block = nn.Module() + block.first = nn.Linear(64, 64, bias=False) + block.second = nn.Linear(64, 64, bias=False) + original = (block.first, block.second) + calls = [] + + def cancel(done, total): + calls.append((done, total)) + if len(calls) == 2: + assert block.first is not original[0] + raise RuntimeError("cancelled") + + with ( + pytest.raises(RuntimeError, match="cancelled"), + _quantized_block(block, 3, progress=cancel), + ): + raise AssertionError("Cancelled quantization must not enter the body") + assert block.first is original[0] + assert block.second is original[1] + assert len(calls) == 2 diff --git a/tests/test_deepseek_v41_ssd.py b/tests/test_deepseek_v41_ssd.py new file mode 100644 index 0000000000..f001989e58 --- /dev/null +++ b/tests/test_deepseek_v41_ssd.py @@ -0,0 +1,237 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Packed V4.1 block persistence and physical SSD roundtrip regressions.""" + +import time +from types import SimpleNamespace + +import mlx.core as mx +import numpy as np +import pytest +from test_deepseek_v41 import tiny + +from omlx.cache.boundary_snapshot_store import BoundarySnapshotSSDStore +from omlx.cache.deepseek_v41_delta import compact_state, restore_chain +from omlx.cache.paged_cache import BlockTable, PagedCacheManager +from omlx.cache.paged_ssd_cache import PagedSSDCacheManager +from omlx.cache.prefix_cache import BlockAwarePrefixCache +from omlx.patches.deepseek_v41 import apply_patch +from omlx.patches.deepseek_v41.language import LanguageModel +from omlx.scheduler import Scheduler + +META = ("deepseek_v41", "3", "2") + + +def _state(end): + return ( + mx.array([end]), + mx.zeros((1, 4, 8), mx.uint8), + mx.zeros((1, end // 2, 8), mx.uint8), + mx.zeros((1, end // 2, 4), mx.uint8), + mx.zeros((1, 0, 8), mx.bfloat16), + mx.zeros((1, 0, 8), mx.float32), + mx.zeros((1, 0), mx.int64), + ) + + +def _marker(start, end): + return ( + "__nstate__", + "DeepseekV41Delta", + compact_state(_state(end), META, start, end), + ) + + +def _wait_empty(pending): + deadline = time.monotonic() + 10 + while pending() and time.monotonic() < deadline: + time.sleep(0.01) + assert not pending(), "SSD writer did not finish" + + +def test_delta_growth_is_linear_and_terminal_partial_preserves_state(): + total = 0 + for end in range(3, 301, 3): + state = _state(end) + delta = compact_state(state, META, end - 3, end) + assert compact_state(delta, META, end - 3, end) is delta + for slot in (0, 1, 4, 5, 6): + assert delta[slot] is state[slot] + total += delta[2].shape[1] + assert total == 150 + markers = [_marker(0, 3), _marker(3, 6), _marker(6, 7)] + restored = restore_chain(markers, [META] * 3, 7) + assert restored.size() == 7 + assert restored.state[2].shape[1] == 3 + + +@pytest.mark.parametrize("indices", [(1,), (0, 2), (1, 0), (0, 0)]) +def test_missing_or_reordered_blocks_are_rejected(indices): + markers = [_marker(0, 3), _marker(3, 6), _marker(6, 9)] + with pytest.raises(ValueError): + restore_chain([markers[i] for i in indices], [META] * len(indices), 9) + + +def test_legacy_anchor_and_invalid_metadata(): + old = ("__nstate__", "DeepseekV41Cache", _state(3)) + restored = restore_chain([old, _marker(3, 6)], [("deepseek_v41", "2"), META], 6) + assert restored.state[2].shape[1] == 3 + with pytest.raises(ValueError): + compact_state(_state(3), ("deepseek_v41", "4"), 0, 3) + with pytest.raises(ValueError): + compact_state(_marker(0, 3)[2], META, 3, 6) + with pytest.raises(ValueError): + restore_chain([_marker(0, 3)], [("deepseek_v41", "3", "4")], 3) + + +@pytest.mark.parametrize("block_size", [3, 4]) +@pytest.mark.parametrize("engram", [False, True]) +@pytest.mark.parametrize("extend_prefix", [False, True]) +def test_real_ssd_reopen_full_and_partial_prefix( + tmp_path, block_size, engram, extend_prefix +): + apply_patch() + mx.random.seed(18) + cfg_args = ( + dict( + engram_layer_ids=(1,), + engram_num_embeddings=(72,), + engram_vocab_size=5, + engram_max_ngram_size=4, + engram_n_heads=2, + engram_head_dim=32, + engram_compressed_vocab_size=64, + ) + if engram + else {} + ) + model = LanguageModel(tiny(**cfg_args)) + if engram: + model.set_token_map(np.arange(64)) + state = model.make_cache() + tokens = list(range(3, 15)) + name = "deepseek-v41-test" + paged = PagedCacheManager( + block_size=block_size, max_blocks=100, initial_blocks=100, model_name=name + ) + + def open_ssd(): + return PagedSSDCacheManager( + cache_dir=tmp_path / "ssd", + max_size_bytes=100 * 1024**2, + hot_cache_max_bytes=0, + hot_cache_only=False, + expected_model_name=name, + ) + + def open_prefix(ssd): + return BlockAwarePrefixCache( + model=model, + paged_cache_manager=paged, + paged_ssd_cache_manager=ssd, + gdn_ssd_split_enabled=True, + ) + + def extract(cache): + return Scheduler._extract_cache_states(SimpleNamespace(model_name=name), cache) + + ssd = open_ssd() + store = BoundarySnapshotSSDStore(tmp_path / "boundary") + try: + prefix = open_prefix(ssd) + assert not prefix._gdn_split_layout_supported(["DeepseekV41Cache"] * 5) + for end in range(block_size, 13, block_size): + mx.eval(model(mx.array([tokens[end - block_size : end]]), cache=state)) + assert store.save("probe", end, state, extract, block_size=block_size) + _wait_empty(lambda: store._pending_writes) + snapshots = { + end: store.load("probe", end) for end in range(block_size, 13, block_size) + } + full, cfg = extract(state) + # Empty packed arrays must keep uint8 through the temporary SSD file. + for layers in snapshots.values(): + for layer in layers: + assert layer["state"][2].dtype == mx.uint8 + assert layer["state"][3].dtype == mx.uint8 + request_id = "probe" + if extend_prefix: + prefix.store_cache( + request_id, + tokens[: 2 * block_size], + snapshots[2 * block_size], + model_cache_config=cfg, + boundary_snapshots=snapshots, + hot_cache_write_back=False, + ) + _wait_empty(lambda: ssd._pending_write_hashes) + request_id = "extend" + matched, remaining = prefix.fetch_cache(request_id, tokens) + assert matched.num_tokens == 2 * block_size + assert remaining == tokens[2 * block_size :] + # Scheduler hands the final compact boundary to store_cache after + # a prefix hit. Only newly traversed boundaries are captured. + full = snapshots[12] + snapshots = { + end: value for end, value in snapshots.items() if end > 2 * block_size + } + table = prefix.store_cache( + request_id, + tokens, + full, + model_cache_config=cfg, + boundary_snapshots=snapshots, + hot_cache_write_back=False, + ) + assert table is not None + assert table.num_tokens == 12 + _wait_empty(lambda: ssd._pending_write_hashes) + ssd.close() + del prefix, snapshots, full, state + ssd = open_ssd() + prefix = open_prefix(ssd) + for count in (block_size, 2 * block_size, 12): + partial = BlockTable( + "restore", table.block_ids[: count // block_size], count + ) + restored = prefix.reconstruct_cache(partial) + assert restored is not None + for cache in restored: + assert cache.state[2].dtype == mx.uint8 + assert cache.state[3].dtype == mx.uint8 + actual = model(mx.array([[20, 21]]), cache=restored) + fresh = model(mx.array([tokens[:count] + [20, 21]]))[:, -2:] + np.testing.assert_allclose(actual, fresh, atol=1e-5) + finally: + store.shutdown() + ssd.close() + + +def test_in_memory_boundary_compacts_and_rejects_corrupt_record(): + from omlx.scheduler import _compact_boundary_snapshot_value + + layer = {"class_name": "DeepseekV41Cache", "state": _state(6), "meta_state": META} + value = ("__prefill_extracted__", [layer]) + assert ( + _compact_boundary_snapshot_value(value, 6, 3, mx.default_stream(mx.gpu)) + is value + ) + assert layer["state"][2].shape[1] == 2 + bad = list(layer["state"]) + bad[7] = mx.array([1, 3, 6, 0, 3, 2], mx.int64) + with pytest.raises(ValueError, match="out-of-order"): + restore_chain( + [_marker(0, 3), ("__nstate__", "DeepseekV41Delta", bad)], [META] * 2, 6 + ) + + +def test_cache_size_single_row_and_unaligned_batch(): + from omlx.patches.deepseek_v41.cache import DeepseekV41Cache + + cache = DeepseekV41Cache() + assert cache.size() == 0 + cache.cache[0] = mx.array([4096], mx.int32) + assert cache.size() == 4096 + cache.cache[0] = mx.array([4096, 17, 8192], mx.int32) + assert cache.size() == 8192 + assert cache.extract(1).size() == 17 + restored = DeepseekV41Cache.from_state(cache.state, cache.meta_state) + assert restored.size() == 8192 diff --git a/tests/test_deepseek_v41_tool_output.py b/tests/test_deepseek_v41_tool_output.py new file mode 100644 index 0000000000..607d2c3a55 --- /dev/null +++ b/tests/test_deepseek_v41_tool_output.py @@ -0,0 +1,181 @@ +# SPDX-License-Identifier: MIT +import json + +import pytest +from test_output_parser import CohereTokenizer + +from omlx.adapter.output_parser import detect_output_parser +from omlx.api.tool_calling import extract_tool_calls_with_thinking +from omlx.patches.deepseek_v41.tool_parser import parse_tool_call + + +class Tokenizer(CohereTokenizer): + has_tool_calling = True + tool_call_start = "<|DSML| calls>" + tool_call_end = "" + tool_parser = staticmethod(parse_tool_call) + + +CALL = ( + '<|DSML| calls>\n<|DSML| invoke name="get">\n' + '<|DSML| parameter name="city" string="true">서울\n' + "\n" +) + + +def replay(text, split, prefilled=False): + chunks = [text[:split], text[split:]] + tokenizer = Tokenizer(dict(enumerate(chunks))) + factory = detect_output_parser("v41", tokenizer, {"model_type": "deepseek_v41"}) + assert factory.kind == "deepseek_v41" + session = factory.create_session(tokenizer) + if prefilled: + session.notify_prefilled_thought() + output = [] + stopped = [] + for i in range(len(chunks)): + result = session.process_token(i) + output.append(result.stream_text) + stopped.append(result.is_stop) + final = session.finalize() + output.append(final.stream_text) + return "".join(output), stopped, final + + +@pytest.mark.parametrize("prefilled", [False, True]) +def test_reasoning_example_never_calls_or_stops_at_any_split(prefilled): + text = ("" if prefilled else "") + "Example: " + CALL + "Answer" + for split in range(len(text) + 1): + visible, stops, final = replay(text, split, prefilled) + assert visible == text, split + assert not any(stops), split + assert not final.tool_calls, split + + +def test_real_call_after_reasoning_at_any_split(): + reasoning = "Example: " + CALL + "" + text = reasoning + CALL + "discard trailing text" + for split in range(len(text) + 1): + visible, stops, final = replay(text, split) + assert visible == reasoning, split + assert any(stops), split + assert final.finish_reason == "tool_calls" + assert len(final.tool_calls) == 1 + assert json.loads(final.tool_calls[0]["arguments"]) == {"city": "서울"} + + +@pytest.mark.parametrize( + "text", [CALL[:-3], CALL.replace('string="true"', 'string="bad"')] +) +def test_incomplete_or_invalid_envelope_does_not_stop(text): + for split in range(len(text) + 1): + visible, stops, final = replay(text, split) + assert visible == text, split + assert not any(stops), split + assert not final.tool_calls + + +def test_http_extraction_does_not_promote_reasoning_calls(): + tools = [{"type": "function", "function": {"name": "get"}}] + result = extract_tool_calls_with_thinking(CALL, "Answer", Tokenizer({}), tools) + assert result.cleaned_thinking == CALL + assert not result.tool_calls + assert not result.tool_calls_from_thinking + + +def test_server_thinking_filter_preserves_literal_dsml(): + from omlx.api.tool_calling import ToolCallStreamFilter + + stream = ToolCallStreamFilter(Tokenizer({}), consume_dsml_separator=False) + assert "".join(stream.feed(char) for char in CALL) + stream.finish() == CALL + + +@pytest.mark.parametrize( + "namespace", ["weather", {"name": "weather", "description": "Weather tools"}] +) +def test_namespace_survives_request_encoding_completion_and_history(namespace): + from omlx.api.openai_models import ToolCall, ToolDefinition + from omlx.api.tool_calling import parse_tool_calls + from omlx.patches.deepseek_v41 import encoding + + raw = { + "type": "function", + "namespace": namespace, + "function": {"name": "get", "parameters": {"type": "object"}}, + } + tool = ToolDefinition.model_validate(raw).model_dump() + assert tool["function"]["name"] == "weather::get" + assert encoding.tools_from_openai_format( + [tool] + ) == encoding.tools_from_openai_format([raw]) + wire = CALL.replace('name="get"', 'name="weather::get"') + _, calls = parse_tool_calls(wire, Tokenizer({}), [raw]) + assert calls[0].function.name == "weather::get" + restored = ToolCall.model_validate(calls[0].model_dump()).model_dump() + assert encoding.tool_calls_from_openai_format([restored]) == [ + {"namespace": "weather", "name": "get", "arguments": '{"city": "서울"}'} + ] + official_call = { + "id": "call_1", + "type": "function", + "namespace": "weather", + "function": {"name": "get", "arguments": "{}"}, + } + assert ToolCall.model_validate(official_call).function.name == "weather::get" + assert raw["function"]["name"] == "get" + + +def test_namespace_conflict_is_rejected_without_affecting_plain_tools(): + from omlx.api.openai_models import ToolDefinition + + plain = {"type": "function", "function": {"name": "get"}} + assert ToolDefinition.model_validate(plain).model_dump() == plain + with pytest.raises(ValueError, match="Conflicting"): + ToolDefinition.model_validate( + { + "type": "function", + "namespace": "weather", + "function": {"name": "calendar::get"}, + } + ) + + +@pytest.mark.parametrize( + "namespace,function", + [ + ({"name": "weather", "description": 42}, {"name": "get"}), + ( + {"name": "weather", "description": "Weather tools"}, + {"name": "get", "description": []}, + ), + ("weather", {"name": "weather::"}), + ], +) +def test_invalid_namespace_fields_raise_validation_errors(namespace, function): + from pydantic import ValidationError + + from omlx.api.openai_models import ToolDefinition + + with pytest.raises(ValidationError): + ToolDefinition.model_validate({"namespace": namespace, "function": function}) + + +def test_same_bare_name_in_two_namespaces_stays_distinct(): + first = CALL.replace('name="get"', 'name="weather::get"') + second = CALL.replace('name="get"', 'name="calendar::get"') + wire = first.removesuffix(Tokenizer.tool_call_end) + second.removeprefix( + Tokenizer.tool_call_start + "\n" + ) + _, _, final = replay(wire, len(wire) // 2) + assert [call["name"] for call in final.tool_calls] == [ + "weather::get", + "calendar::get", + ] + + +def test_invalid_json_cannot_end_tool_turn(): + wire = CALL.replace('string="true">서울', 'string="false">[broken') + visible, stops, final = replay(wire, len(wire) // 2) + assert visible == wire + assert not any(stops) + assert not final.tool_calls diff --git a/tests/test_engine_pool.py b/tests/test_engine_pool.py index 6e79a1cbf8..e63f51c905 100644 --- a/tests/test_engine_pool.py +++ b/tests/test_engine_pool.py @@ -730,6 +730,101 @@ async def test_qwen4_live_admission_keeps_viable_mmap_fallback(self, tmp_path): signature = dict(entry.runtime_settings_signature or ()) assert signature["qwen4_ple_ssd_offload"] == "False" + def test_v41_ple_offload_reduces_resident_projection(self, tmp_path): + from omlx.model_settings import ModelSettings + from omlx.patches.deepseek_v41.residency import ( + EngramResidencyEstimate, + ) + + model = tmp_path / "v41" + model.mkdir() + settings = ModelSettings(deepseek_v41_engram_ssd_offload=False) + entry = EngineEntry( + model_id="v41", + model_path=str(model), + model_type="vlm", + engine_type="vlm", + config_model_type="deepseek_v41", + estimated_size=1000, + ) + estimate = EngramResidencyEstimate( + supported=True, + engram_bytes=550, + resident_bytes=1000, + mmap_bytes=400, + ) + pool = _make_pool(ceiling=500) + pool._entries[entry.model_id] = entry + + with patch( + "omlx.patches.deepseek_v41.residency." "deepseek_v41_residency_estimate", + return_value=estimate, + ): + projected = pool._entry_runtime_resident_size(entry, settings) + effective = pool._effective_deepseek_v41_model_settings(entry, settings) + signature = dict(pool._engine_runtime_signature("v41", settings)) + + assert projected == 400 + assert settings.deepseek_v41_engram_ssd_offload is False + assert effective.deepseek_v41_engram_ssd_offload is True + assert signature["deepseek_v41_engram_ssd_offload"] == "True" + + @pytest.mark.asyncio + async def test_v41_live_admission_keeps_viable_mmap_fallback(self, tmp_path): + """Real pressure may select mmap without making that override sticky.""" + from omlx.model_settings import ModelSettings + from omlx.patches.deepseek_v41.residency import ( + EngramResidencyEstimate, + ) + + model = tmp_path / "v41" + model.mkdir() + (model / "config.json").write_text(json.dumps({"model_type": "deepseek_v41"})) + settings = ModelSettings(deepseek_v41_engram_ssd_offload=False) + entry = EngineEntry( + model_id="v41", + model_path=str(model), + model_type="vlm", + engine_type="vlm", + config_model_type="deepseek_v41", + estimated_size=1000, + ) + estimate = EngramResidencyEstimate( + supported=True, + engram_bytes=550, + resident_bytes=1000, + mmap_bytes=400, + ) + pool = _make_pool(ceiling=500) + pool._get_admission_soft_target = lambda: 500 + pool._get_residency_ceiling = lambda: 1000 + pool._entries[entry.model_id] = entry + mock_engine = MagicMock() + mock_engine.start = AsyncMock() + + with ( + patch("omlx.engine_pool.VLMBatchedEngine", return_value=mock_engine) as cls, + patch("omlx.engine_pool.get_phys_footprint", return_value=0), + patch("omlx.engine_pool.mx.get_active_memory", return_value=0), + patch( + "omlx.patches.deepseek_v41.residency." + "deepseek_v41_residency_estimate", + return_value=estimate, + ), + ): + loaded = await pool.get_engine("v41", runtime_settings=settings) + reused = await pool.get_engine("v41", runtime_settings=settings) + + assert loaded is mock_engine + assert reused is mock_engine + cls.assert_called_once() + effective = cls.call_args.kwargs["model_settings"] + assert effective.deepseek_v41_engram_ssd_offload is True + assert settings.deepseek_v41_engram_ssd_offload is False + assert entry.runtime_estimated_size == 400 + signature = dict(entry.runtime_settings_signature or ()) + assert signature["deepseek_v41_engram_ssd_offload"] == "False" + class TestApplySettingsOverrides: """Tests for apply_settings_overrides method.""" @@ -3149,6 +3244,52 @@ def mock_get_active(): assert pool._entries["model-a"].engine is None assert pool._current_model_memory == initial_memory - est_size + @pytest.mark.asyncio + @pytest.mark.parametrize("offload", [False, True]) + async def test_v41_settle_tracks_metal_engram_and_admission( + self, pool_with_loaded_model, offload, caplog + ): + from omlx.model_settings import ModelSettings + from omlx.patches.deepseek_v41.residency import EngramResidencyEstimate + + pool = pool_with_loaded_model + entry = pool._entries["model-a"] + entry.config_model_type = "deepseek_v41" + gib = 1024**3 + estimate = EngramResidencyEstimate(True, 80 * gib, 50 * gib, 30 * gib) + settings = ModelSettings(deepseek_v41_engram_ssd_offload=offload) + with patch( + "omlx.patches.deepseek_v41.residency.deepseek_v41_residency_estimate", + return_value=estimate, + ): + entry.runtime_estimated_size = pool._entry_runtime_resident_size( + entry, settings + ) + entry.runtime_settle_size = pool._entry_runtime_resident_size( + entry, settings, include_ane_reservation=False, + ) + charge = (50 if offload else 80) * gib + assert entry.runtime_estimated_size == charge + assert entry.runtime_settle_size == charge + pool._current_model_memory = charge + + def active_memory(): + assert pool._current_model_memory == charge + return next(readings) + + readings = iter([charge + gib, gib]) + with ( + patch("omlx.engine_pool.mx") as mock_mx, + patch("omlx.engine_pool.get_mlx_executor", return_value=None), + patch("asyncio.sleep", new_callable=AsyncMock) as sleep, + ): + mock_mx.get_active_memory.side_effect = active_memory + await pool._unload_engine("model-a") + assert pool._current_model_memory == 0 + assert "Settle barrier timed out" not in caplog.text + assert mock_mx.get_active_memory.call_count == 2 + assert not any(call.args == (0.1,) for call in sleep.call_args_list) + @pytest.mark.asyncio async def test_settle_takes_multiple_rounds(self, pool_with_loaded_model): """Test settle barrier succeeds after multiple rounds of GC.""" diff --git a/tests/test_oq_manager.py b/tests/test_oq_manager.py index f2d141d9ff..c1ad414f36 100644 --- a/tests/test_oq_manager.py +++ b/tests/test_oq_manager.py @@ -788,3 +788,39 @@ async def test_hf_cache_excludes_models_without_model_type(self, tmp_path): assert len(source_models) == 0 assert len(all_models) == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("layer_key", ["n_layers", "num_hidden_layers"]) +async def test_v41_source_metadata_and_converted_filter(tmp_path, layer_key): + root = tmp_path / "models" + root.mkdir() + base = { + "model_type": "deepseek_v41", + "text_config": {layer_key: 40, "dim": 5120, "n_routed_experts": 384}, + } + for name, config in ( + ( + "original", + { + **base, + "quantization_config": {"quant_method": "fp8", "expert_dtype": "fp4"}, + }, + ), + ("converted", {**base, "omlx_deepseek_v41": {"version": 1}}), + ): + folder = root / name + folder.mkdir() + (folder / "config.json").write_text(json.dumps(config)) + (folder / "model.safetensors").write_bytes(bytes(64)) + sources, all_models = await OQManager( + model_dirs=[str(root)] + ).list_quantizable_models() + assert [row["name"] for row in sources] == ["original"] + assert sources[0]["num_layers"] == 40 + assert sources[0]["num_experts"] == 384 + assert sources[0]["hidden_size"] == 5120 + assert {row["name"]: row["is_quantized"] for row in all_models} == { + "original": False, + "converted": True, + } diff --git a/tests/test_qwen4_qsa_gather_rows.py b/tests/test_qwen4_qsa_gather_rows.py index 39968548fc..99728a9ded 100644 --- a/tests/test_qwen4_qsa_gather_rows.py +++ b/tests/test_qwen4_qsa_gather_rows.py @@ -40,28 +40,6 @@ def test_gather_kv_rows_matches_token_major_gather(batch, form): assert mx.array_equal(out.view(mx.uint16), _reference(kv, indices).view(mx.uint16)).item() -def test_gather_kv_rows_does_not_copy_the_whole_cache(): - """Cost must not scale with the cache length: gathering 4 rows from 8x the tokens takes ~the same time.""" - import time - - from mlx_vlm.models.qwen4_exp import qsa_fast - - def cost(tokens): - kv = mx.random.normal((1, 2, tokens, 256)).astype(mx.bfloat16) - idx = mx.sort(mx.random.randint(0, tokens, (1, 4)).astype(mx.int32), axis=-1) - mx.eval(kv, idx) - mx.eval(qsa_fast._gather_kv_rows(kv, idx)) - t0 = time.perf_counter() - for _ in range(20): - mx.eval(qsa_fast._gather_kv_rows(kv, idx)) - return (time.perf_counter() - t0) / 20 - - small, large = cost(16_384), cost(131_072) - # 8x more tokens. A whole-cache copy is ~8x. Shared macos-14 runners - # jitter sub-millisecond Metal evals past 2x (CI saw 2.6x on 3.11). - assert large < 4.0 * small, (small, large) - - def _dispatch(monkeypatch, per_query, tokens): """Which form the dispatcher picks for a (1, per_query, 2051) gather from a cache of ``tokens`` rows.""" from mlx_vlm.models.qwen4_exp import qsa_fast diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 1a5a3229a0..93e2d4cc73 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -24,9 +24,11 @@ import mlx.core as mx import pytest +from mlx_lm.models.cache import CacheList, KVCache import omlx.scheduler as scheduler_module from omlx.cache.stats import PrefixCacheStats +from omlx.patches.deepseek_v41.cache import DeepseekV41Cache from omlx.request import Request, RequestOutput, RequestStatus, SamplingParams from omlx.scheduler import ( Scheduler, @@ -3702,6 +3704,36 @@ def test_cleanup_finished_extends_deferred_clear_for_concurrent_completions( class TestSchedulerArraysCacheBlockAlignment: """ArraysCache boundaries must match the effective prefill chunk.""" + @pytest.mark.parametrize("nested", [False, True]) + def test_deepseek_v41_subclass_uses_2048_boundaries( + self, mock_tokenizer, tmp_path, nested + ): + model = self._hybrid_model(model_type="deepseek_v41") + model.make_cache = lambda: [ + CacheList(KVCache(), DeepseekV41Cache(4)) + if nested + else DeepseekV41Cache(4) + ] + scheduler = Scheduler( + model=model, + tokenizer=mock_tokenizer, + config=SchedulerConfig( + paged_ssd_cache_dir=str(tmp_path), + paged_cache_block_size=256, + prefill_step_size=2048, + ), + ) + try: + assert scheduler._model_has_arrays_cache() + assert scheduler._qwen35_prefill_floor == 0 + assert scheduler.config.paged_cache_block_size == 2048 + assert scheduler._prefill_step_size_for_progress(0, 9216) == 2048 + finally: + scheduler.shutdown() + + def test_plain_kv_cache_is_not_arrays_cache(self): + assert not Scheduler._cache_tree_has_arrays_cache(KVCache()) + @staticmethod def _hybrid_model(model_type="qwen3_5"): class ArraysCache: