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>", "|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 @@
{{ t('modal.model_settings.deepseek_v41_engram_ssd_offload_hint') }}
+{{ t('modal.model_settings.deepseek_v41_engram_ssd_offload_forced') }}
+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 = "|DSML| calls>" + + +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|DSML| parameter>\n|DSML| invoke>\n|DSML| calls>' + 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 = "|DSML| calls>" + tool_parser = staticmethod(parse_tool_call) + + +CALL = ( + '<|DSML| calls>\n<|DSML| invoke name="get">\n' + '<|DSML| parameter name="city" string="true">서울|DSML| parameter>\n' + "|DSML| invoke>\n|DSML| calls>" +) + + +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: