Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: opt-in REAP expert pruning on the Export page (#14130)

Daniel Han61fb544b4910
diff --git a/scripts/risky_loaders_baseline.json b/scripts/risky_loaders_baseline.json
index d58d5d89e41..88a9ead6d83 100644
--- a/scripts/risky_loaders_baseline.json
+++ b/scripts/risky_loaders_baseline.json
@@ -26,6 +26,14 @@
"count": 1,
"reason": "Loads the installed torchao package file it is stubbing around, located via find_spec."
},
+ {
+ "file": "studio/backend/core/export/reap.py",
+ "rule": "dynamic-import",
+ "sink": "spec_from_file_location",
+ "digest": "9f96fe82c04e1bd3",
+ "count": 1,
+ "reason": "Loads Unsloth's own installed models/mapper.py (plain data), located via find_spec, to read its 16-bit Hub id table without importing unsloth."
+ },
{
"file": "studio/backend/core/export/worker.py",
"rule": "trust-remote-code",
diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.py
index e507e277bb0..8f64cfde099 100644
--- a/studio/backend/core/export/export.py
+++ b/studio/backend/core/export/export.py
@@ -622,10 +622,23 @@ This model was converted to GGUF format using [Unsloth](https://github.com/unslo
# export_metadata.json is local bookkeeping whose base model can be a local path; the GGUF push
# keeps it out of the repo too.
_HUB_UPLOAD_IGNORE = ["export_metadata.json", "._*"]
+# REAP's report: uploaded with a pruned export, and deleted from a reused repo by any other merged
+# or base upload (GGUF files carry one each) (upload_folder never removes remote files on its own; one it uploads in the
+# same commit is kept).
+_REAP_REPORT = "reap_report.json"
_STAGING_PREFIX = "unsloth-hub-upload-"
+def _card_base_model(model) -> str:
+ """The base a Hub card names: after REAP the config points at a staging copy, so the id the
+ pruned model came from is used instead."""
+ source = getattr(model, "_unsloth_reap_source", None)
+ if source:
+ return source
+ return getattr(getattr(model, "config", None), "_name_or_path", "unknown") or "unknown"
+
+
def _staging_dir(export_parent):
"""Stage a copy of an export where it fits: merge_and_overwrite_lora refuses a save its
destination cannot hold, and neither the temporary directory nor the export's own filesystem is
@@ -720,6 +733,7 @@ def _push_mlx_merged(
repo_id = repo_id,
repo_type = "model",
ignore_patterns = _HUB_UPLOAD_IGNORE,
+ delete_patterns = [_REAP_REPORT],
)
return repo_id
@@ -737,7 +751,7 @@ def _publish_unsloth_model_card(hf_api, repo_id, model, hf_token):
config = getattr(model, "config", None)
if config is None:
return
- base_model = getattr(config, "_name_or_path", "unknown") or "unknown"
+ base_model = _card_base_model(model)
# method/extra reproduce what upload_to_huggingface passed for this path
# ("finetuned", "trl"): the template already carries the unsloth tag, so `extra`
# is where trl goes, and the heading already reads "Uploaded finetuned ... model".
@@ -817,6 +831,14 @@ class ExportBackend:
except Exception as e:
logger.error(f"Error during memory cleanup: {e}")
return False
+ finally:
+ # Even when an unload above failed: a later load must never inherit this load's REAP
+ # settings (they would read as "already pruned" for an unpruned model).
+ try:
+ from core.export.reap import discard_reap_staging
+ discard_reap_staging(self)
+ except Exception as e:
+ logger.warning(f"Could not clear the REAP state: {e}")
def scan_checkpoints(
self, outputs_dir: Optional[str] = None
@@ -1272,6 +1294,31 @@ class ExportBackend:
def _decision_only_gguf(self) -> Tuple[bool, str, Optional[str]]:
return False, "Decision models export to GGUF only.", None
+ def _sync_gguf_reap_reports(self, folder, ggufs) -> List[str]:
+ """One report beside each GGUF this export wrote (a reused folder keeps other files);
+ returns their names, written or removed."""
+ try:
+ from core.export.reap import gguf_report_name, sync_reap_report
+
+ names = []
+ for gguf in ggufs:
+ name = gguf_report_name(gguf)
+ sync_reap_report(self, folder, name, [os.path.basename(gguf)])
+ names.append(name)
+ return names
+ except Exception as exc: # noqa: BLE001 - the report never blocks an export
+ logger.warning(f"Could not update the REAP reports in {folder}: {exc}")
+ return []
+
+ def _sync_reap_report(self, folder) -> None:
+ """reap_report.json in ``folder`` describes the weights it holds (written for a REAP pruned
+ model, a stale one removed otherwise); run before a folder is uploaded."""
+ try:
+ from core.export.reap import sync_reap_report
+ sync_reap_report(self, folder)
+ except Exception as exc: # noqa: BLE001 - the report never blocks an export
+ logger.warning(f"Could not update reap_report.json in {folder}: {exc}")
+
def _write_export_metadata(self, save_directory: str):
"""Write export_metadata.json with base model info for Chat page discovery."""
try:
@@ -1514,6 +1561,10 @@ class ExportBackend:
)
logger.info(f"Model saved successfully to {final_dir}")
output_path = str(Path(final_dir).resolve())
+ # Complete on disk even if the Hub upload below fails (the worker syncs REAP's report).
+ self._local_export_path = output_path
+ # Before any upload: the folder's REAP report must describe the weights it now holds.
+ self._sync_reap_report(output_path)
if push_to_hub:
hf_token = _hub_push_token(hf_token)
@@ -1557,6 +1608,7 @@ class ExportBackend:
**merged_token_kw,
)
self._package_drafter_merged(upload_dir, repo_id)
+ self._sync_reap_report(upload_dir)
# Whatever was built, only weights are worth a repo; without them the
# merging push below runs instead, as it did before this was uploaded.
if _holds_checkpoint_weights(upload_dir):
@@ -1572,6 +1624,7 @@ class ExportBackend:
repo_id = repo_id,
repo_type = "model",
ignore_patterns = _HUB_UPLOAD_IGNORE,
+ delete_patterns = [_REAP_REPORT],
)
uploaded = True
if uploaded:
@@ -1579,9 +1632,7 @@ class ExportBackend:
# push_to_hub_merged does.
try:
if not hf_api.file_exists(repo_id, "README.md", repo_type = "model"):
- base_model = getattr(
- self.current_model.config, "_name_or_path", "unknown"
- )
+ base_model = _card_base_model(self.current_model)
content = MODEL_CARD.format(
username = repo_id.split("/")[0],
base_model = repo_id if os.path.isdir(base_model) else base_model,
@@ -1639,7 +1690,8 @@ class ExportBackend:
if not self.current_model or not self.current_tokenizer:
return False, "No model loaded. Please select a checkpoint first.", None
- if self.is_peft:
+ # A LoRA load stays one after REAP merged its adapters in memory for a pruned export.
+ if self.is_peft or getattr(self, "_reap_merged_peft", False):
return (
False,
"This is a PEFT model. Use 'Merged Model' export type instead.",
@@ -1671,6 +1723,8 @@ class ExportBackend:
self._write_export_metadata(save_directory)
logger.info(f"Model saved successfully to {save_directory}")
output_path = str(Path(save_directory).resolve())
+ self._local_export_path = output_path
+ self._sync_reap_report(output_path)
if push_to_hub:
hf_token = _hub_push_token(hf_token)
@@ -1695,9 +1749,7 @@ class ExportBackend:
private = private,
)
else:
- base_model = (
- base_model_id or self.current_model.config._name_or_path or "unknown"
- )
+ base_model = base_model_id or _card_base_model(self.current_model)
with contextlib.ExitStack() as stack:
upload_dir = save_directory
@@ -1710,6 +1762,7 @@ class ExportBackend:
self.current_model.save_pretrained(upload_dir)
self.current_tokenizer.save_pretrained(upload_dir)
self._package_drafter_merged(upload_dir, repo_id)
+ self._sync_reap_report(upload_dir)
hf_api = HfApi(token = hf_token)
repo_url = hf_api.create_repo(repo_id, private = private, exist_ok = True)
repo_id = getattr(repo_url, "repo_id", repo_id)
@@ -1735,6 +1788,7 @@ class ExportBackend:
repo_id = repo_id,
repo_type = "model",
ignore_patterns = _HUB_UPLOAD_IGNORE,
+ delete_patterns = [_REAP_REPORT],
)
logger.info(f"Model pushed successfully to {repo_id}")
else:
@@ -1807,6 +1861,7 @@ class ExportBackend:
output_path: Optional[str] = None
exported_ggufs: List[str] = []
+ gguf_reports: List[str] = []
drafter_gguf_files: List[str] = []
exported_modelfile = False
exported_modelfile_bytes: Optional[bytes] = None
@@ -1979,6 +2034,13 @@ class ExportBackend:
# Only write metadata once an artifact is actually present.
self._write_export_metadata(abs_save_dir)
output_path = str(Path(abs_save_dir).resolve())
+ # Before the upload below, which allow-lists each file's report when there is one.
+ # The model's own GGUFs only: an EAGLE-3 drafter is converted separately, not pruned.
+ drafter_names = {os.path.basename(f) for f in drafter_gguf_files}
+ gguf_reports = self._sync_gguf_reap_reports(
+ output_path,
+ [f for f in exported_ggufs if os.path.basename(f) not in drafter_names],
+ )
if npu_q4nx:
source = q4nx.source_gguf(exported_ggufs, quant_methods)
@@ -1988,6 +2050,8 @@ class ExportBackend:
with q4nx.staged_output(Path(abs_save_dir) / "npu-q4nx") as staging:
q4nx.convert_gguf_to_q4nx(source, staging)
self._write_q4nx_companions(staging, exported_config)
+ # The NPU folder is deployed on its own, so it carries its own report.
+ self._sync_reap_report(staging)
except Exception as exception:
logger.error(f"Q4NX conversion failed: {exception}")
return (
@@ -2024,7 +2088,14 @@ class ExportBackend:
*(glob.escape(os.path.basename(f)) for f in exported_ggufs),
*(["Modelfile"] if exported_modelfile else []),
*(["drafter.json"] if drafter_gguf_files else []),
+ *(
+ glob.escape(name)
+ for name in gguf_reports
+ if (Path(output_path) / name).is_file()
+ ),
],
+ # A report an earlier pruned export pushed for these same files.
+ delete_patterns = [glob.escape(name) for name in gguf_reports] or None,
)
if exported_config is not None:
hf_api.upload_file(
@@ -2442,6 +2513,13 @@ class ExportBackend:
if refusal:
return False, refusal, None
+ if getattr(self, "_reap_merged_peft", False):
+ return (
+ False,
+ "The LoRA adapters were merged into the model for a REAP export. Load the "
+ "checkpoint again to export the adapter.",
+ None,
+ )
if not self.is_peft:
return False, "This is not a PEFT model. No adapter to export.", None
diff --git a/studio/backend/core/export/orchestrator.py b/studio/backend/core/export/orchestrator.py
index b732da99813..e732b0c670d 100644
--- a/studio/backend/core/export/orchestrator.py
+++ b/studio/backend/core/export/orchestrator.py
@@ -49,6 +49,16 @@ OP_CANCELLED = "Export cancelled"
_CLEANUP_TIMEOUT = 30.0
+def _sweep_reap_staging_of(pid: Optional[int]) -> None:
+ """A worker confirmed dead (cancelled, killed at shutdown, crashed) cannot remove its REAP
+ staging copy, a full model, itself."""
+ try:
+ from core.export.reap import sweep_reap_staging
+ sweep_reap_staging(dead_pid = pid)
+ except Exception as exc: # noqa: BLE001 - cleanup must never block a stop
+ logger.warning("Could not sweep REAP staging after the export worker stopped: %s", exc)
+
+
class ExportOrchestrator:
"""Export backend orchestrator, subprocess-based. Same API surface as ExportBackend so
routes/export.py needs minimal changes."""
@@ -248,6 +258,8 @@ class ExportOrchestrator:
proc.join(timeout = 3)
except Exception:
pass
+ if not proc.is_alive():
+ _sweep_reap_staging_of(proc.pid)
return True
def _spawn_subprocess(self, config: dict) -> None:
@@ -339,6 +351,7 @@ class ExportOrchestrator:
except Exception: # noqa: BLE001 - the reap is best-effort
logger.warning("could not reap the orphaned export worker", exc_info = True)
if _spawned_proc.exitcode is not None:
+ _sweep_reap_staging_of(_spawned_proc.pid)
forget_pid(_spawned_proc.pid)
else:
logger.warning(
@@ -357,6 +370,8 @@ class ExportOrchestrator:
pre-swap liveness guard can still observe the survivor instead of a cleared
handle and refuse the destructive sidecar swap."""
if self._proc is None or not self._proc.is_alive():
+ if self._proc is not None:
+ _sweep_reap_staging_of(self._proc.pid)
self._proc = None
return True
@@ -395,6 +410,7 @@ class ExportOrchestrator:
)
return False
+ _sweep_reap_staging_of(self._proc.pid)
self._proc = None
self._cmd_queue = None
self._resp_queue = None
@@ -665,6 +681,7 @@ class ExportOrchestrator:
install_missing_dependencies: bool = False,
expected_checkpoint: Optional[str] = None,
op_id: Optional[str] = None,
+ reap: Optional[dict] = None,
) -> Tuple[bool, str, Optional[str]]:
return self._run_export(
"merged",
@@ -679,6 +696,7 @@ class ExportOrchestrator:
"install_missing_dependencies": install_missing_dependencies,
"expected_checkpoint": expected_checkpoint,
"op_id": op_id,
+ "reap": reap,
},
)
@@ -692,6 +710,7 @@ class ExportOrchestrator:
base_model_id: Optional[str] = None,
expected_checkpoint: Optional[str] = None,
op_id: Optional[str] = None,
+ reap: Optional[dict] = None,
) -> Tuple[bool, str, Optional[str]]:
return self._run_export(
"base",
@@ -704,6 +723,7 @@ class ExportOrchestrator:
"base_model_id": base_model_id,
"expected_checkpoint": expected_checkpoint,
"op_id": op_id,
+ "reap": reap,
},
)
@@ -719,6 +739,7 @@ class ExportOrchestrator:
npu_q4nx: bool = False,
expected_checkpoint: Optional[str] = None,
op_id: Optional[str] = None,
+ reap: Optional[dict] = None,
) -> Tuple[bool, str, Optional[str]]:
"""Export model in GGUF format. `quantization_method` may be a single method or a list."""
return self._run_export(
@@ -734,6 +755,7 @@ class ExportOrchestrator:
"npu_q4nx": npu_q4nx,
"expected_checkpoint": expected_checkpoint,
"op_id": op_id,
+ "reap": reap,
},
)
@@ -838,6 +860,9 @@ class ExportOrchestrator:
def cleanup_memory(self) -> bool:
with self._lock:
if not self._ensure_subprocess_alive():
+ if self._proc is not None:
+ # The worker died on its own (CUDA crash, OOM kill) and left its staging.
+ _sweep_reap_staging_of(self._proc.pid)
self.current_checkpoint = None
self.is_vision = False
self.is_peft = False
diff --git a/studio/backend/core/export/q4nx.py b/studio/backend/core/export/q4nx.py
index fd6959cf8db..df93033307d 100644
--- a/studio/backend/core/export/q4nx.py
+++ b/studio/backend/core/export/q4nx.py
@@ -97,8 +97,9 @@ def staged_output(out_dir: Path):
out_dir.mkdir(exist_ok = True)
# Again at publish: the conversion is long enough for the folder to be swapped.
refuse_symlink()
- # The last model's companions must not survive beside the new weights.
- for name in ("model.q4nx", "config.json", *TOKENIZER_FILES):
+ # The last model's companions must not survive beside the new weights (REAP's report
+ # included: a pruned conversion stages a fresh one).
+ for name in ("model.q4nx", "config.json", "reap_report.json", *TOKENIZER_FILES):
(out_dir / name).unlink(missing_ok = True)
for path in staging.iterdir():
os.replace(path, out_dir / path.name)
diff --git a/studio/backend/core/export/reap.py b/studio/backend/core/export/reap.py
new file mode 100644
index 00000000000..c49cad6e0c5
--- /dev/null
+++ b/studio/backend/core/export/reap.py
@@ -0,0 +1,593 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+"""Opt-in REAP expert pruning before an export (Core's ``FastLanguageModel.reap_prune``)."""
+
+from __future__ import annotations
+
+import functools
+import json
+import os
+import weakref
+from pathlib import Path
+from typing import Any, List, Optional, Tuple
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+# Core's top-k keys plus the raw config.json aliases transformers maps through attribute_map.
+_NUM_EXPERTS_KEYS = ("num_experts", "num_local_experts", "n_routed_experts", "moe_num_experts")
+_TOP_K_KEYS = ("num_experts_per_tok", "top_k", "moe_top_k", "top_k_experts", "moe_topk", "moe_k")
+# Decoder layers that hand state to the next layer (prev_* arguments), which Core refuses since it
+# calibrates one layer at a time: GLM-5 / HY-V4 sparse-attention top-k indices, ZAYA router states.
+_STATEFUL_MODEL_TYPES = frozenset({"glm_moe_dsa", "glm5_next", "glm5_next_text", "hy_v4", "zaya"})
+# Hash-routed MoE (tid2eid): Core refuses it since dropped experts cannot be remapped.
+_HASH_ROUTED_MODEL_TYPES = frozenset({"deepseek_v4"})
+_N_GROUP_KEYS = ("n_group", "num_expert_group")
+_TOPK_GROUP_KEYS = ("topk_group", "top_k_group")
+REPORT_NAME = "reap_report.json"
+# The export worker's pid, so a parent only removes staging copies it can prove a dead worker made.
+_OWNER_FILE = ".unsloth_reap_owner"
+
+
+def _first_int(
+ config: dict,
+ keys,
+ per_layer = False,
+) -> Optional[int]:
+ for key in keys:
+ value = config.get(key)
+ if isinstance(value, int) and not isinstance(value, bool):
+ return value
+ if (
+ per_layer
+ and isinstance(value, list)
+ and value
+ and all(isinstance(v, int) for v in value)
+ ):
+ return max(value)
+ return None
+
+
+def _model_parallel(distributed) -> bool:
+ """A saved distributed_config Core refuses: expert / tensor / pipeline / FSDP / sequence parallel."""
+ if not isinstance(distributed, dict):
+ return False
+ if distributed.get("enable_expert_parallel") or distributed.get("enable_sequence_parallel"):
+ return True
+ return any(
+ isinstance(distributed.get(k), int) and distributed.get(k) > 1
+ for k in ("tp_size", "pp_size", "fsdp_size")
+ )
+
+
+# Quantization a 16-bit load unpacks (gpt-oss mxfp4; bitsandbytes only for Hub ids Unsloth maps to
+# 16-bit); anything else stays packed and Core refuses it only after a full load.
+_UNPACKED_QUANT_METHODS = {"mxfp4"}
+# Older ModelOpt exports declare quantization here (attach_hf_quant_config reads it too).
+_HF_QUANT_CONFIG = "hf_quant_config.json"
+
+
[email protected]_cache(maxsize = 1)
+def _int_to_float_mapper() -> dict:
+ """Unsloth's quantized-to-16-bit Hub id table, read from mapper.py (plain data) without importing
+ unsloth, which would initialize the GPU stack in the server process."""
+ import importlib.util
+
+ spec = importlib.util.find_spec("unsloth")
+ roots = list(spec.submodule_search_locations or []) if spec else []
+ for root in roots:
+ path = Path(root) / "models" / "mapper.py"
+ if path.is_file():
+ module_spec = importlib.util.spec_from_file_location("_unsloth_mapper_data", path)
+ module = importlib.util.module_from_spec(module_spec)
+ module_spec.loader.exec_module(module)
+ return dict(module.INT_TO_FLOAT_MAPPER)
+ return {}
+
+
+def _maps_to_16_bit(model: str) -> bool:
+ """A quantized Hub id Unsloth loads as its 16-bit original when asked for 16-bit."""
+ try:
+ return str(model).lower() in _int_to_float_mapper()
+ except Exception as exc:
+ logger.debug("Could not read Unsloth's model mapper: %s", exc)
+ return False
+
+
+class MoeProbeError(RuntimeError):
+ """The config could not be read (network, Hub, I/O): unknown, not a dense answer, so an export
+ with REAP on must wait or have REAP turned off rather than go out unpruned."""
+
+
+def _cached_hub_file(repo: str, filename: str, offline: bool) -> Optional[bool]:
+ """What the local Hub cache knows: True when the file is cached, False when its absence is
+ recorded (or, offline, when the repo's snapshot is cached without it, so the loader could not
+ fetch it either), else None."""
+ try:
+ from huggingface_hub import try_to_load_from_cache
+ from utils.hf_cache_settings import active_hf_hub_cache
+
+ cache_dir = active_hf_hub_cache()
+ found = try_to_load_from_cache(repo, filename, cache_dir = cache_dir)
+ if isinstance(found, str):
+ return True
+ if found is not None: # _CACHED_NO_EXIST
+ return False
+ if offline and any(
+ isinstance(try_to_load_from_cache(repo, name, cache_dir = cache_dir), str)
+ for name in ("config.json", "adapter_config.json")
+ ):
+ return False
+ except Exception as exc:
+ logger.debug("Could not read the Hub cache for '%s': %s", repo, exc)
+ return None
+
+
+def hub_file_exists(
+ repo: str,
+ filename: str,
+ hf_token = None,
+) -> bool:
+ """Whether a Hub repo has ``filename``. file_exists answers False only for a definite absence
+ (repo, file or revision not found). Offline, or when the request fails, the local cache answers
+ if it knows; anything still unknown (timeout, auth, gated) raises ``MoeProbeError``, so a file
+ that would make REAP fail after the load is never assumed away."""
+ error = None
+ try:
+ from huggingface_hub import HfApi, constants
+ offline = bool(constants.HF_HUB_OFFLINE)
+ if not offline:
+ return bool(HfApi(token = hf_token).file_exists(repo, filename))
+ except Exception as exc:
+ offline, error = False, exc
+ cached = _cached_hub_file(repo, filename, offline)
+ if cached is not None:
+ return cached
+ raise MoeProbeError(f"Could not check '{repo}' for {filename}: {error or 'offline'}") from error
+
+
+def _export_runs_transformers_4(model: str, hf_token = None) -> bool:
+ """Whether Studio would load ``model`` for export under transformers 4.x (the 4.57 tier, or the
+ default tier where the default is 4.57, e.g. Python 3.9). Core prunes only transformers 5's
+ fused experts; 4.x keeps a ModuleList, which it refuses after the full load. If the tier
+ cannot be resolved, the option stays (Core still refuses clearly, never exporting unpruned)."""
+ try:
+ from utils.transformers_version import (
+ TRANSFORMERS_DEFAULT_VERSION,
+ get_transformers_activation_tier,
+ )
+ tier = get_transformers_activation_tier(model, hf_token)
+ return tier == "457" or (
+ tier == "default" and str(TRANSFORMERS_DEFAULT_VERSION).startswith("4.")
+ )
+ except Exception as exc:
+ logger.debug("Could not resolve the transformers tier of '%s': %s", model, exc)
+ return False
+
+
+def hub_adapter_has_mtp_head(repo: str, hf_token = None) -> bool:
+ """Unsloth's loader re-attaches a Hub LoRA repo's trained MTP head, which REAP refuses."""
+ return hub_file_exists(repo, "mtp_head.safetensors", hf_token)
+
+
+def _quantization_allows_reap(holders, bnb_maps_to_16_bit: bool) -> bool:
+ for holder in holders:
+ quant = holder.get("quantization_config")
+ if not quant:
+ continue
+ if not isinstance(quant, dict):
+ return False
+ method = str(quant.get("quant_method") or "").lower()
+ if not method and (quant.get("load_in_4bit") or quant.get("load_in_8bit")):
+ method = "bitsandbytes" # configs saved before quant_method existed
+ if method in _UNPACKED_QUANT_METHODS or (method == "bitsandbytes" and bnb_maps_to_16_bit):
+ continue
+ return False
+ return True
+
+
+def moe_info_from_config(
+ config: Optional[dict], bnb_maps_to_16_bit: bool = False
+) -> Optional[dict]:
+ """``{num_experts, top_k}`` (plus ``n_group`` / ``topk_group`` for group-limited routers) for a
+ routed-MoE config dict, else None."""
+ if not isinstance(config, dict):
+ return None
+ holders = [h for h in (config.get("text_config"), config) if isinstance(h, dict)]
+
+ # Like Core's _first_attr: each field from the first level that has it, text_config first.
+ def first(keys, per_layer = False):
+ return next((v for h in holders if (v := _first_int(h, keys, per_layer)) is not None), None)
+
+ # Core refuses routers with identity (zero) experts and bidirectional / diffusion models.
+ if any(h.get("zero_expert_num") for h in holders) or any(
+ h.get("use_bidirectional_attention") == "all"
+ or str(h.get("model_type", "")).startswith("diffusion")
+ for h in holders
+ ):
+ return None
+ if any(_model_parallel(h.get("distributed_config")) for h in holders):
+ return None
+ if not _quantization_allows_reap(holders, bnb_maps_to_16_bit):
+ return None
+ if any(
+ str(h.get("model_type", "")) in _STATEFUL_MODEL_TYPES | _HASH_ROUTED_MODEL_TYPES
+ for h in holders
+ ):
+ return None
+ experts = first(_NUM_EXPERTS_KEYS)
+ top_k = first(_TOP_K_KEYS, per_layer = True)
+ if not (experts and top_k and experts > top_k):
+ return None
+ info = {"num_experts": experts, "top_k": top_k}
+ n_group, topk_group = first(_N_GROUP_KEYS), first(_TOPK_GROUP_KEYS)
+ if n_group and n_group > 1:
+ if not topk_group:
+ # Core refuses grouped routing it cannot prune per group.
+ return None
+ info.update(n_group = n_group, topk_group = topk_group)
+ return info
+
+
+def moe_export_info(
+ model: str,
+ hf_token = None,
+ local_files_only = True,
+ _depth = 0,
+ adapter_base: Optional[str] = None,
+) -> Optional[dict]:
+ """MoE info for a local checkpoint / model folder or a Hub id (a LoRA folder resolves to its
+ base, or to ``adapter_base`` when the caller already authorized it). None for a dense model, a
+ repo without config.json or a malformed one; ``MoeProbeError`` when the config could not be read."""
+ try:
+ from utils.models.diffusion_lm import _local_adapter_base
+ from utils.models.model_config import _read_raw_config_json
+ from utils.paths import is_local_path, normalize_path
+
+ if is_local_path(model):
+ local = Path(normalize_path(model)).expanduser()
+ has_config = (local / "config.json").is_file()
+ # The loader re-attaches a LoRA folder's trained MTP head, which REAP refuses.
+ if (local / "adapter_config.json").is_file() and (
+ local / "mtp_head.safetensors"
+ ).is_file():
+ return None
+ # The export loader follows adapter_config.json even beside a config.json.
+ if not has_config or (local / "adapter_config.json").is_file():
+ base = adapter_base or _local_adapter_base(str(local))
+ if base and _depth < 2 and base != model:
+ # A Hub base of a local adapter may not be cached yet: read it online.
+ return moe_export_info(base, hf_token, is_local_path(base), _depth + 1)
+ if not has_config:
+ return None
+ if not (local / "adapter_config.json").is_file():
+ from core.export.drafter_export import training_manifest
+
+ # The export attaches a full checkpoint's trained MTP head, which REAP refuses.
+ manifest = training_manifest(str(local))
+ if manifest and manifest.get("strategy") == "mtp":
+ return None
+ local = is_local_path(model)
+ if local and (Path(normalize_path(model)).expanduser() / _HF_QUANT_CONFIG).is_file():
+ return None
+ config = _read_raw_config_json(model, hf_token, local_files_only, None)
+ info = moe_info_from_config(config, bnb_maps_to_16_bit = not local and _maps_to_16_bit(model))
+ if info is not None and _export_runs_transformers_4(model, hf_token):
+ return None
+ if (
+ info is not None
+ and not local
+ and not (isinstance(config, dict) and config.get("quantization_config"))
+ and hub_file_exists(model, _HF_QUANT_CONFIG, hf_token)
+ ):
+ return None
+ return info
+ except MoeProbeError:
+ raise
+ except ValueError as exc:
+ logger.debug("MoE detection skipped for '%s': %s", model, exc)
+ return None
+ except Exception as exc:
+ raise MoeProbeError(f"Could not read the config of '{model}': {exc}") from exc
+
+
+def _options_key(options: dict) -> Tuple[float, int, Optional[str]]:
+ return (
+ float(options.get("sparsity", 0.25)),
+ int(options.get("num_calibration_samples", 512)),
+ (options.get("dataset") or "").strip() or None,
+ )
+
+
+def _loaded_in_4bit(model: Any) -> bool:
+ if getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False):
+ return True
+ config = getattr(model, "config", None)
+ quant = getattr(config, "quantization_config", None)
+ if quant is not None:
+ get = quant.get if isinstance(quant, dict) else lambda k, d = None: getattr(quant, k, d)
+ if get("load_in_4bit", False) or get("load_in_8bit", False):
+ return True
+ return False
+
+
+def _calibration_dataset(dataset: Optional[str], hf_token):
+ """A custom dataset opened with the request's token (export workers keep tokens out of their
+ environment, so Core's own load would be anonymous); the default stays Core's."""
+ if not dataset:
+ return None
+ from datasets import load_dataset
+
+ kwargs = {} if hf_token is None else {"token": hf_token}
+ # Like Core: no split forced, take `train` else the only split.
+ splits = load_dataset(dataset, streaming = True, **kwargs)
+ if not isinstance(splits, dict):
+ return splits
+ if "train" in splits:
+ return splits["train"]
+ if len(splits) == 1:
+ return next(iter(splits.values()))
+ raise ValueError(
+ f"the calibration dataset '{dataset}' has no train split but several others "
+ f"({', '.join(sorted(splits))}); use a dataset with a train split or a single split"
+ )
+
+
+def current_reap_key(backend: Any):
+ """The REAP settings the loaded model was pruned with, else None. A key whose model is no
+ longer the loaded one (an unload that failed part way before a new load) is not this model's."""
+ key = getattr(backend, "_reap_key", None)
+ ref = getattr(backend, "_reap_model", None)
+ model = getattr(backend, "current_model", None)
+ if key is None or ref is None or model is None or ref() is not model:
+ return None
+ return key
+
+
+def apply_reap(
+ backend: Any,
+ options: Optional[dict],
+ staging_parent,
+ hf_token = None,
+) -> Tuple[bool, str]:
+ """Prune the loaded model once per load; a multi-format export reuses the pruned model.
+ ``hf_token`` opens a private or gated calibration dataset."""
+ if not options:
+ return True, ""
+ key = _options_key(options)
+ applied = current_reap_key(backend)
+ if applied is None and getattr(backend, "_reap_key", None) is not None:
+ # Left by an unload that failed part way: it describes an older model, not this load.
+ discard_reap_staging(backend)
+ if applied == key:
+ return True, ""
+ if applied is not None:
+ return False, (
+ "This model was already pruned with different REAP settings. Start the export again "
+ "to load a fresh copy."
+ )
+ model, tokenizer = backend.current_model, backend.current_tokenizer
+ if model is None:
+ return False, "No model loaded. Please select a checkpoint first."
+ if _loaded_in_4bit(model):
+ return False, (
+ "REAP expert pruning needs the model loaded in 16-bit, but it was loaded in 4-bit. "
+ "Turn off 4-bit loading and export again."
+ )
+ if getattr(model, "__dict__", {}).get("_unsloth_mtp_head") is not None:
+ # Core refuses this: the attached MTP head would keep the old expert count.
+ return False, (
+ "REAP cannot prune a checkpoint with an attached MTP head. Export it without expert "
+ "pruning."
+ )
+ from core.export.export import _staging_dir
+ from unsloth import FastLanguageModel
+
+ try:
+ if getattr(backend, "is_peft", False):
+ # REAP scores the fine-tuned experts, so the adapters are merged first (16-bit, in memory).
+ logger.info("REAP: merging the LoRA adapters into the 16-bit base before pruning...")
+ model = model.merge_and_unload()
+ backend.current_model = model
+ backend.is_peft = False
+ # Kept until the next load: the base export must still refuse this LoRA checkpoint.
+ backend._reap_merged_peft = True
+ sweep_reap_staging()
+ staging = _staging_dir(staging_parent)
+ _register_staging(staging.name)
+ backend._reap_staging = staging
+ sparsity, samples, dataset = key
+ # save_directory repoints every later save / merge / GGUF at the pruned copy, named after the model.
+ source = str(getattr(model.config, "_name_or_path", "") or "")
+ name = Path(source.rstrip("/\\") or "model").name
+ FastLanguageModel.reap_prune(
+ model,
+ tokenizer,
+ sparsity = sparsity,
+ dataset = _calibration_dataset(dataset, hf_token),
+ num_calibration_samples = samples,
+ save_directory = str(Path(staging.name) / f"{name or 'model'}-REAP"),
+ )
+ except Exception as exc:
+ # A failure part way leaves the loaded model merged and partly pruned; never export it.
+ logger.warning("REAP failed, unloading the partly pruned model: %s", exc)
+ unloaded = False
+ try:
+ unloaded = backend.cleanup_memory() is not False
+ except Exception as cleanup_exc:
+ logger.warning("Could not unload after a failed REAP run: %s", cleanup_exc)
+ if not unloaded:
+ # cleanup_memory may report failure; this worker must never export the model again.
+ backend.current_model = None
+ backend.current_tokenizer = None
+ backend.current_checkpoint = None
+ discard_reap_staging(backend)
+ raise RuntimeError(
+ f"REAP expert pruning failed: {exc}. The model was unloaded since it may be partly "
+ "pruned; load it again to export."
+ ) from exc
+ model._unsloth_reap_source = source or None
+ backend._reap_key = key
+ # The settings belong to this model object only (see current_reap_key).
+ backend._reap_model = weakref.ref(model)
+ report = getattr(model, "_unsloth_reap_report", None) or {}
+ kept = len(next(iter(report.values()), []))
+ return True, f"REAP kept {kept} experts per MoE layer in {len(report)} layers."
+
+
+def gguf_report_name(gguf: str) -> str:
+ """The report beside one GGUF file (``model.Q4_K_M.gguf`` -> ``model.Q4_K_M.reap_report.json``):
+ a reused GGUF folder keeps files from other loads, so each file carries its own."""
+ name = os.path.basename(str(gguf))
+ stem = name[: -len(".gguf")] if name.lower().endswith(".gguf") else name
+ return f"{stem}.reap_report.json"
+
+
+def sync_reap_report(
+ backend: Any,
+ output_path: Optional[str],
+ name: str = REPORT_NAME,
+ files: Optional[List[str]] = None,
+) -> None:
+ """After an export: the report when the exported model is pruned, else remove one a previous
+ REAP export left in a reused folder, so the folder never describes other weights."""
+ if current_reap_key(backend) is not None:
+ write_reap_report(backend, output_path, name, files)
+ return
+ if output_path and Path(output_path).is_dir():
+ stale = Path(output_path) / name
+ try:
+ stale.unlink(missing_ok = True)
+ except OSError as exc:
+ logger.warning(f"Could not remove the stale {name}: {exc}")
+
+
+def write_reap_report(
+ backend: Any,
+ output_path: Optional[str],
+ name: str = REPORT_NAME,
+ files: Optional[List[str]] = None,
+) -> None:
+ """The report (kept expert ids per layer and the settings) next to the export; ``files`` names
+ the artifacts it describes when the folder can hold others."""
+ model = getattr(backend, "current_model", None)
+ report = getattr(model, "_unsloth_reap_report", None)
+ key = current_reap_key(backend)
+ if not report or key is None or not output_path or not Path(output_path).is_dir():
+ return
+ try:
+ payload = {
+ "method": "REAP (arXiv:2510.13999)",
+ "sparsity": key[0],
+ "num_calibration_samples": key[1],
+ "dataset": key[2] or "mlabonne/open-perfectblend",
+ "kept_experts": report,
+ }
+ if files:
+ payload["files"] = files
+ (Path(output_path) / name).write_text(json.dumps(payload, indent = 1), encoding = "utf-8")
+ except Exception as exc:
+ logger.warning(f"Could not write {name}: {exc}")
+
+
+def discard_reap_staging(backend: Any) -> None:
+ staging = getattr(backend, "_reap_staging", None)
+ backend._reap_staging = None
+ backend._reap_key = None
+ backend._reap_model = None
+ backend._reap_merged_peft = False
+ if staging is not None:
+ try:
+ staging.cleanup()
+ except Exception as exc:
+ logger.warning(f"Could not remove the REAP staging copy: {exc}")
+ sweep_reap_staging()
+
+
+def reap_staging_parent(save_directory: Optional[str]) -> Path:
+ """Where the pruned copy may stage: the chosen save folder's filesystem (an absolute path on
+ another drive is allowed), else the exports root. ``_staging_dir`` then takes whichever of
+ this and the temp dir has more room."""
+ from utils.paths.storage_roots import resolve_export_dir, resolve_export_write_dir
+
+ try:
+ target = resolve_export_write_dir(save_directory)
+ except Exception:
+ return resolve_export_dir()
+ # The save folder itself may not exist yet; its nearest existing ancestor is on the same drive.
+ for candidate in (target, *target.parents):
+ if candidate.is_dir():
+ return candidate
+ return resolve_export_dir()
+
+
+def _registry() -> Path:
+ from utils.paths.storage_roots import cache_root
+ return cache_root() / "reap_staging.json"
+
+
+def _read_registry() -> list:
+ try:
+ entries = json.loads(_registry().read_text(encoding = "utf-8"))
+ return [e for e in entries if isinstance(e, dict) and "path" in e and "pid" in e]
+ except Exception:
+ return []
+
+
+def _write_registry(entries: list) -> None:
+ try:
+ path = _registry()
+ path.parent.mkdir(parents = True, exist_ok = True)
+ tmp = path.with_suffix(".tmp")
+ tmp.write_text(json.dumps(entries), encoding = "utf-8")
+ tmp.replace(path)
+ except Exception as exc:
+ logger.debug("Could not update the REAP staging registry: %s", exc)
+
+
+def _register_staging(path: str) -> None:
+ import os
+
+ pid = os.getpid()
+ try:
+ (Path(path) / _OWNER_FILE).write_text(str(pid), encoding = "utf-8")
+ except OSError as exc:
+ logger.debug("Could not mark the REAP staging copy: %s", exc)
+ _write_registry(_read_registry() + [{"path": str(path), "pid": pid}])
+
+
+def sweep_reap_staging(dead_pid: Optional[int] = None) -> None:
+ """Remove staging copies whose worker is gone: a cancel kills the worker, so neither
+ ``cleanup_memory`` nor the TemporaryDirectory finalizer runs. ``dead_pid`` is a worker the
+ caller just killed; otherwise an owner counts as gone when its process no longer exists.
+ Only folders carrying their owner marker are touched. Never raises."""
+ import shutil
+
+ try:
+ import psutil
+ alive = psutil.pid_exists
+ except Exception:
+ alive = None
+ entries = _read_registry()
+ if not entries:
+ return
+ keep = []
+ for entry in entries:
+ path, pid = Path(entry["path"]), entry["pid"]
+ if not path.exists():
+ continue
+ gone = pid == dead_pid or (dead_pid is None and alive is not None and not alive(pid))
+ try:
+ owned = (path / _OWNER_FILE).read_text(encoding = "utf-8").strip() == str(pid)
+ except OSError:
+ owned = False
+ if gone and owned:
+ shutil.rmtree(path, ignore_errors = True)
+ if not path.exists():
+ logger.info("Removed a REAP staging copy left by a stopped export: %s", path)
+ continue
+ keep.append(entry)
+ if keep != entries:
+ _write_registry(keep)
diff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.py
index 6f54406d5cd..1d6da980203 100644
--- a/studio/backend/core/export/worker.py
+++ b/studio/backend/core/export/worker.py
@@ -592,6 +592,64 @@ def _handle_export(backend, cmd: dict, resp_queue: Any) -> None:
output_path: Any = None
try:
+ from core.export.reap import current_reap_key
+
+ reap = cmd.get("reap") if export_type in ("merged", "base", "gguf") else None
+ if (
+ not reap
+ and export_type in ("merged", "base", "gguf")
+ and current_reap_key(backend) is not None
+ ):
+ # The loaded model is the pruned one now; "no REAP" must not export it. Studio loads
+ # the checkpoint again for every export run; an API client has to do the same.
+ _send_response(
+ resp_queue,
+ {
+ "type": response_type,
+ "success": False,
+ "message": "This model was pruned with REAP for an earlier export. Load it "
+ "again to export it without pruning.",
+ "output_path": None,
+ "ts": time.time(),
+ },
+ )
+ return
+ if (
+ reap
+ and export_type == "base"
+ and (getattr(backend, "is_peft", False) or getattr(backend, "_reap_merged_peft", False))
+ ):
+ # Merging for REAP would get a LoRA past export_base_model's PEFT refusal.
+ reap = None
+ if reap:
+ from core.export.reap import apply_reap, reap_staging_parent
+
+ _send_response(
+ resp_queue,
+ {"type": "status", "message": "Pruning experts with REAP...", "ts": time.time()},
+ )
+ ok, reap_message = apply_reap(
+ backend,
+ reap,
+ reap_staging_parent(cmd.get("save_directory")),
+ # The export's token, else the one the checkpoint was loaded with.
+ hf_token = cmd.get("hf_token") or getattr(backend, "_checkpoint_token", None),
+ )
+ if not ok:
+ _send_response(
+ resp_queue,
+ {
+ "type": response_type,
+ "success": False,
+ "message": reap_message,
+ "output_path": None,
+ "ts": time.time(),
+ },
+ )
+ return
+ if reap_message:
+ logger.info(reap_message)
+ backend._local_export_path = None
if export_type == "merged":
success, message, output_path = backend.export_merged_model(
save_directory = cmd.get("save_directory", ""),
@@ -636,6 +694,12 @@ def _handle_export(backend, cmd: dict, resp_queue: Any) -> None:
)
else:
success, message = False, f"Unknown export type: {export_type}"
+ # A failed Hub upload leaves complete local files: merged / base record their folder once the
+ # local save finishes. GGUF exports keep one report per file themselves.
+ local_path = output_path or getattr(backend, "_local_export_path", None)
+ if (success or local_path) and export_type in ("merged", "base"):
+ from core.export.reap import sync_reap_report
+ sync_reap_report(backend, local_path)
_send_response(
resp_queue,
diff --git a/studio/backend/models/__init__.py b/studio/backend/models/__init__.py
index 4784b1a17c2..bb2f8567e6a 100644
--- a/studio/backend/models/__init__.py
+++ b/studio/backend/models/__init__.py
@@ -47,6 +47,8 @@ from .export import (
LlmCompressorExportProbeResponse,
DecisionExportInfo,
ExportDecisionInfoResponse,
+ MoeInfoResponse,
+ ReapOptions,
)
from .users import Token
from .inference import (
@@ -110,6 +112,8 @@ __all__ = [
"LlmCompressorExportProbeResponse",
"DecisionExportInfo",
"ExportDecisionInfoResponse",
+ "MoeInfoResponse",
+ "ReapOptions",
"Token",
"LoadRequest",
"UnloadRequest",
diff --git a/studio/backend/models/export.py b/studio/backend/models/export.py
index fdadb687edc..3524cf512a7 100644
--- a/studio/backend/models/export.py
+++ b/studio/backend/models/export.py
@@ -182,6 +182,39 @@ class ExportOperationResponse(BaseModel):
)
+class ReapOptions(BaseModel):
+ """Opt-in REAP expert pruning (arXiv:2510.13999) applied to an MoE model before it is exported."""
+
+ sparsity: float = Field(
+ 0.25,
+ gt = 0,
+ lt = 1,
+ description = "Fraction of the routed experts to remove in every MoE layer.",
+ )
+ num_calibration_samples: int = Field(
+ 512,
+ ge = 8,
+ le = 4096,
+ description = "Calibration conversations used to score the experts.",
+ )
+ dataset: Optional[str] = Field(
+ None,
+ max_length = 200,
+ pattern = r"^[A-Za-z0-9][A-Za-z0-9._-]*(/[A-Za-z0-9][A-Za-z0-9._-]*)?$",
+ description = "Hugging Face dataset id for calibration (default mlabonne/open-perfectblend).",
+ )
+
+
+class MoeInfoResponse(BaseModel):
+ """Routed-expert counts for a model, or None when it is not a routed MoE."""
+
+ model: str
+ num_experts: Optional[int] = None
+ top_k: Optional[int] = None
+ n_group: Optional[int] = Field(None, description = "Router groups (group-limited routing).")
+ topk_group: Optional[int] = Field(None, description = "Groups each token may route into.")
+
+
class ExportCommonOptions(BaseModel):
"""Common options for export operations that save locally and/or push to Hub."""
@@ -255,11 +288,18 @@ class ExportMergedModelRequest(ExportCommonOptions):
description = "User consent to install llm-compressor (or its shadow runtime) for "
"compressed-tensors export.",
)
+ reap: Optional[ReapOptions] = Field(
+ None, description = "Prune MoE experts with REAP before exporting (off when omitted)."
+ )
class ExportBaseModelRequest(ExportCommonOptions):
"""Request for exporting a non-PEFT (base) model."""
+ reap: Optional[ReapOptions] = Field(
+ None, description = "Prune MoE experts with REAP before exporting (off when omitted)."
+ )
+
class ExportGGUFRequest(BaseModel):
"""Request for exporting the current model to GGUF format."""
@@ -321,6 +361,9 @@ class ExportGGUFRequest(BaseModel):
description = "Also convert one Q4_0 / Q4_1 / Q4_K_M GGUF to FastFlowLM's Q4NX for the "
"AMD Ryzen AI NPU, written to <save_directory>/npu-q4nx.",
)
+ reap: Optional[ReapOptions] = Field(
+ None, description = "Prune MoE experts with REAP before converting (off when omitted)."
+ )
class ConvertQ4NXRequest(BaseModel):
diff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.py
index a5fd8057c5c..312fc8ccd43 100644
--- a/studio/backend/routes/export.py
+++ b/studio/backend/routes/export.py
@@ -19,7 +19,7 @@ import time
from pathlib import Path
from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple
-from fastapi import APIRouter, Depends, HTTPException, Query, Request
+from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request
from fastapi.responses import StreamingResponse
import structlog
from loggers import get_logger
@@ -56,6 +56,7 @@ from models import (
ExportDiffusionLoRARequest,
LlmCompressorExportProbeResponse,
ExportDecisionInfoResponse,
+ MoeInfoResponse,
)
router = APIRouter()
@@ -442,6 +443,86 @@ async def get_decision_export_info(
)
[email protected]("/moe-info", response_model = MoeInfoResponse)
+async def get_moe_info(
+ model: str = Query(
+ ..., max_length = 4096, description = "Local checkpoint / model folder or Hub id"
+ ),
+ hf_token: Optional[str] = Header(None, alias = "X-HF-Token"),
+ current_subject: str = Depends(get_current_subject),
+ allow_ambient: bool = Depends(allow_ambient_hf_token),
+):
+ """Routed-expert counts for the REAP option on the export page; null counts for a dense model.
+ The token (gated repos) comes in the X-HF-Token header, as for /api/models/export-size."""
+ from core.export.reap import (
+ MoeProbeError,
+ hub_adapter_has_mtp_head,
+ hub_file_exists,
+ moe_export_info,
+ )
+ from routes.models import _normalize_hf_token, _require_model_access_or_caller_token
+ from utils.paths import is_local_path
+
+ local = is_local_path(model)
+ token = _normalize_hf_token(hf_token)
+ adapter_base = None
+ if local:
+ validate_job_paths({"checkpoint_path": model})
+ # The probe follows a LoRA folder to its base, so that base is authorized as a load is.
+ adapter_base = await asyncio.to_thread(_authorized_adapter_base, model)
+ if adapter_base:
+ validate_job_paths({"base_model": adapter_base, "hf_token": token})
+ else:
+ await _require_model_access_or_caller_token(model, token)
+ probe_token = token or hf_token_arg(None, allow_ambient_token = allow_ambient)
+ # The export loader follows a Hub repo's adapter_config.json even when it also ships a
+ # config.json, so an adapter repo is probed through its base (and its MTP head) like a local one.
+ try:
+ hub_adapter = not local and await asyncio.to_thread(
+ hub_file_exists, model, "adapter_config.json", probe_token
+ )
+ # A local folder never reaches the network; a Hub id reads only its config.json.
+ info = (
+ None
+ if hub_adapter
+ else await asyncio.to_thread(
+ moe_export_info,
+ model,
+ probe_token,
+ local,
+ adapter_base = adapter_base,
+ )
+ )
+ if info is None and not local:
+ # A Hub LoRA repo publishes adapter_config.json, not config.json: probe its base, which is
+ # authorized first like the adapter.
+ from utils.models.model_config import get_base_model_from_lora_identifier
+
+ base = await asyncio.to_thread(get_base_model_from_lora_identifier, model, probe_token)
+ if hub_adapter and not base:
+ # A confirmed adapter whose base could not be read (a failed download after its
+ # retries): unknown, not dense.
+ raise MoeProbeError(f"Could not resolve the base model of the adapter '{model}'")
+ if (
+ base
+ and base != model
+ and await asyncio.to_thread(hub_adapter_has_mtp_head, model, probe_token)
+ ):
+ # Unsloth's loader re-attaches this adapter's trained MTP head, which REAP refuses.
+ base = None
+ if base and base != model:
+ base_local = is_local_path(base)
+ if base_local:
+ validate_job_paths({"base_model": base, "hf_token": token})
+ else:
+ await _require_model_access_or_caller_token(base, token)
+ info = await asyncio.to_thread(moe_export_info, base, probe_token, base_local)
+ except MoeProbeError as exc:
+ # Unknown is not dense: the page keeps a REAP export blocked and offers a retry.
+ raise HTTPException(status_code = 503, detail = str(exc)) from exc
+ return MoeInfoResponse(model = model, **(info or {}))
+
+
@router.post("/export/merged", response_model = ExportOperationResponse)
async def export_merged_model(
request: ExportMergedModelRequest,
@@ -453,6 +534,8 @@ async def export_merged_model(
Wraps ExportBackend.export_merged_model.
"""
validate_job_paths(request.model_dump())
+ if request.reap and request.reap.dataset:
+ validate_job_paths({"hf_dataset": request.reap.dataset, "hf_token": request.hf_token})
try:
await _ensure_export_supported()
backend = get_export_backend()
@@ -472,6 +555,7 @@ async def export_merged_model(
install_missing_dependencies = request.install_missing_dependencies,
expected_checkpoint = request.expected_checkpoint,
op_id = request.op_id,
+ reap = request.reap.model_dump() if request.reap else None,
)
if not success:
@@ -519,6 +603,8 @@ async def export_base_model(
Wraps ExportBackend.export_base_model.
"""
validate_job_paths(request.model_dump())
+ if request.reap and request.reap.dataset:
+ validate_job_paths({"hf_dataset": request.reap.dataset, "hf_token": request.hf_token})
try:
await _ensure_export_supported()
backend = get_export_backend()
@@ -536,6 +622,7 @@ async def export_base_model(
base_model_id = request.base_model_id,
expected_checkpoint = request.expected_checkpoint,
op_id = request.op_id,
+ reap = request.reap.model_dump() if request.reap else None,
)
if not success:
@@ -574,6 +661,8 @@ async def export_gguf(
Wraps ExportBackend.export_gguf.
"""
validate_job_paths(request.model_dump())
+ if request.reap and request.reap.dataset:
+ validate_job_paths({"hf_dataset": request.reap.dataset, "hf_token": request.hf_token})
try:
await _ensure_export_supported()
backend = get_export_backend()
@@ -595,6 +684,7 @@ async def export_gguf(
npu_q4nx = request.npu_q4nx,
expected_checkpoint = request.expected_checkpoint,
op_id = request.op_id,
+ reap = request.reap.model_dump() if request.reap else None,
)
if not success:
diff --git a/studio/backend/tests/test_export_absolute_paths.py b/studio/backend/tests/test_export_absolute_paths.py
index 9756f03e9ea..64f1bb93a46 100644
--- a/studio/backend/tests/test_export_absolute_paths.py
+++ b/studio/backend/tests/test_export_absolute_paths.py
@@ -226,6 +226,7 @@ def _install_lightweight_backend_stubs(monkeypatch):
"ExportLoRAAdapterRequest",
"LlmCompressorExportProbeResponse",
"ExportDecisionInfoResponse",
+ "MoeInfoResponse",
):
setattr(models_pkg, name, object)
models_pkg.LocalModelInfo = _LocalModelInfo
diff --git a/studio/backend/tests/test_export_gguf_discovery.py b/studio/backend/tests/test_export_gguf_discovery.py
index e09d8349258..6fb7d62e59b 100644
--- a/studio/backend/tests/test_export_gguf_discovery.py
+++ b/studio/backend/tests/test_export_gguf_discovery.py
@@ -106,6 +106,7 @@ def _hub_doubles(export_mod, monkeypatch, calls: dict):
repo_type,
allow_patterns = None,
ignore_patterns = None,
+ delete_patterns = None,
):
calls["upload"] = folder_path
diff --git a/studio/backend/tests/test_export_gguf_hub_upload.py b/studio/backend/tests/test_export_gguf_hub_upload.py
index ff819a2b76c..f5ba4f8e0eb 100644
--- a/studio/backend/tests/test_export_gguf_hub_upload.py
+++ b/studio/backend/tests/test_export_gguf_hub_upload.py
@@ -3,6 +3,8 @@
from __future__ import annotations
+import weakref
+
import importlib.util
import os
import types
@@ -99,6 +101,7 @@ def _hub_doubles(calls, seen):
repo_type,
allow_patterns = None,
ignore_patterns = None,
+ delete_patterns = None,
):
calls.append("upload_folder")
seen["folder"] = folder_path
@@ -112,6 +115,7 @@ def _hub_doubles(calls, seen):
for pattern in ignore_patterns or ():
paths = [p for p in paths if not fnmatchcase(p, pattern)]
seen["uploaded"] = sorted(paths)
+ seen["delete_patterns"] = delete_patterns
class _ModelCard:
def __init__(self, content):
@@ -603,6 +607,7 @@ def test_gguf_hub_export_reports_the_local_path_when_the_upload_fails(tmp_path,
repo_type,
allow_patterns = None,
ignore_patterns = None,
+ delete_patterns = None,
):
raise RuntimeError("504 Gateway Timeout")
@@ -964,3 +969,98 @@ def test_gguf_hub_export_publishes_a_modelfile_blocked_by_a_directory(tmp_path,
assert seen["uploaded"] == ["model.Q4_K_M.gguf"]
assert seen["Modelfile"] == b"FROM ./model.Q4_K_M.gguf\n"
assert list((Path(output_path) / "Modelfile").iterdir()) == []
+
+
+def _real_reap_module(monkeypatch):
+ # The export imports core.export.reap, which this harness's stub package lacks.
+ import sys
+
+ spec = importlib.util.spec_from_file_location(
+ "core.export.reap", Path(__file__).resolve().parents[1] / "core/export/reap.py"
+ )
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ monkeypatch.setitem(sys.modules, "core.export.reap", module)
+
+
[email protected]("pruned", [True, False])
+def test_gguf_hub_export_carries_a_current_reap_report_only(tmp_path, monkeypatch, pruned):
+ _install_export_backend_stubs(monkeypatch)
+ _real_reap_module(monkeypatch)
+ export_module = _load_module(
+ "test_export_gguf_hub_upload_reap", "core/export/export.py", monkeypatch
+ )
+ calls: list[str] = []
+ seen: dict = {}
+ export_dir = tmp_path / "export"
+ export_dir.mkdir()
+ # A reused folder: an older GGUF from another load, with its own report, stays as it is.
+ (export_dir / "older.Q8_0.gguf").write_bytes(b"GGUF")
+ (export_dir / "older.Q8_0.reap_report.json").write_text('{"kept_experts": {"older": [3]}}')
+ # And a report an earlier pruned export left for the file this export overwrites.
+ (export_dir / "model.Q4_K_M.reap_report.json").write_text('{"kept_experts": {"old": [1]}}')
+
+ class Model:
+ _unsloth_reap_report = {"model.layers.0.mlp": [0, 2]}
+
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
+ output = Path(f"{model_save_path}_gguf")
+ output.mkdir(parents = True, exist_ok = True)
+ (output / "model.Q4_K_M.gguf").write_bytes(b"GGUF")
+
+ _patch_hub(monkeypatch, export_module, calls, seen)
+ backend = _export_backend(export_module, Model)
+ backend._reap_key = (0.5, 512, None) if pruned else None
+ backend._reap_model = weakref.ref(backend.current_model) # pruned this load
+ success, message, output_path = _push_gguf(backend, str(export_dir))
+ assert success is True, message
+ report = Path(output_path, "model.Q4_K_M.reap_report.json")
+ # Synced before the upload: only this export's GGUF and its own current report go up.
+ assert seen["uploaded"] == (
+ ["model.Q4_K_M.gguf", "model.Q4_K_M.reap_report.json"] if pruned else ["model.Q4_K_M.gguf"]
+ )
+ assert report.is_file() is pruned
+ if pruned:
+ data = report.read_text()
+ assert '"old"' not in data and '"files": [\n "model.Q4_K_M.gguf"\n ]' in data
+ # The other file's report is never touched, and a stale remote one for this file is deleted.
+ assert Path(output_path, "older.Q8_0.reap_report.json").is_file()
+ assert seen["delete_patterns"] == ["model.Q4_K_M.reap_report.json"]
+
+
+def test_a_packaged_eagle3_drafter_gguf_gets_no_reap_report(tmp_path, monkeypatch):
+ # The drafter is converted on its own, not pruned: only the model's GGUFs carry a report.
+ _install_export_backend_stubs(monkeypatch)
+ _real_reap_module(monkeypatch)
+ export_module = _load_module(
+ "test_export_gguf_hub_upload_reap_drafter", "core/export/export.py", monkeypatch
+ )
+ calls: list[str] = []
+ seen: dict = {}
+
+ class Model:
+ _unsloth_reap_report = {"model.layers.0.mlp": [0, 2]}
+
+ def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
+ output = Path(f"{model_save_path}_gguf")
+ output.mkdir(parents = True, exist_ok = True)
+ (output / "model.Q4_K_M.gguf").write_bytes(b"GGUF")
+
+ _patch_hub(monkeypatch, export_module, calls, seen)
+ backend = _export_backend(export_module, Model)
+ backend._reap_key = (0.5, 512, None)
+ backend._reap_model = weakref.ref(backend.current_model)
+
+ def package(merged_dir, gguf_dir, ggufs):
+ drafter = Path(gguf_dir) / "drafter-eagle3.F16.gguf"
+ drafter.write_bytes(b"GGUF")
+ (Path(gguf_dir) / "drafter.json").write_text("{}")
+ return [str(drafter), str(Path(gguf_dir) / "drafter.json")]
+
+ backend._package_drafter_gguf = package
+ success, message, output_path = _push_gguf(backend, str(tmp_path / "export"))
+ assert success is True, message
+ assert Path(output_path, "model.Q4_K_M.reap_report.json").is_file()
+ assert not Path(output_path, "drafter-eagle3.F16.reap_report.json").exists()
+ assert "drafter-eagle3.F16.gguf" in seen["uploaded"]
+ assert "drafter-eagle3.F16.reap_report.json" not in seen["uploaded"]
diff --git a/studio/backend/tests/test_export_hub_push.py b/studio/backend/tests/test_export_hub_push.py
index f4262b6ddc1..0f845786c2c 100644
--- a/studio/backend/tests/test_export_hub_push.py
+++ b/studio/backend/tests/test_export_hub_push.py
@@ -3,6 +3,8 @@
from __future__ import annotations
+import weakref
+
import functools
import importlib.util
import sys
@@ -502,6 +504,8 @@ def test_mlx_export_push_to_a_reused_folder_does_not_upload_its_leftovers(
assert seen["uploaded"] == _MLX_MERGED_FILES
assert output_path == str(export_dir.resolve())
assert backend.current_model.merges == [_MLX_EXPORTS[export][3]] * 2
+ # A REAP report an earlier export pushed to this repo is deleted in the same commit.
+ assert seen["delete_patterns"] == ["reap_report.json"]
assert seen["folder"] != output_path
assert not Path(seen["folder"]).exists()
@@ -935,6 +939,127 @@ def test_lora_gguf_export_push_to_a_reused_folder_does_not_upload_its_leftovers(
assert seen["uploaded"] == _LORA_GGUF_FILES
+def _reap_pruned(backend, monkeypatch):
+ # As apply_reap leaves it: the pruning key and the kept experts on the loaded model. The stub
+ # core.export package of this harness gets the real reap module the export imports.
+ spec = importlib.util.spec_from_file_location(
+ "core.export.reap", Path(__file__).resolve().parents[1] / "core/export/reap.py"
+ )
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ monkeypatch.setitem(sys.modules, "core.export.reap", module)
+ backend._reap_key = (0.5, 512, None)
+ backend._reap_model = weakref.ref(backend.current_model)
+ backend.current_model._unsloth_reap_report = {"model.layers.0.mlp": [0, 2]}
+ return backend
+
+
[email protected]("reused", [False, True])
+def test_merged_push_of_a_reap_pruned_model_uploads_its_report(tmp_path, monkeypatch, reused):
+ calls: list[str] = []
+ seen: dict = {}
+ backend = _reap_pruned(
+ _non_mlx_backend(monkeypatch, "test_export_hub_push_reap_merged", calls, seen), monkeypatch
+ )
+ export_dir = tmp_path / "export"
+ if reused:
+ export_dir.mkdir()
+ (export_dir / "adapter_config.json").write_text("{}")
+ success, message, output_path = backend.export_merged_model(
+ str(export_dir), push_to_hub = True, repo_id = "model", hf_token = "hf_fake"
+ )
+ assert success is True, message
+ # Written before the upload, into whichever folder was uploaded.
+ assert "reap_report.json" in seen["uploaded"]
+ assert Path(output_path, "reap_report.json").is_file()
+
+
+def test_merged_push_into_a_folder_with_a_stale_report_uploads_none(tmp_path, monkeypatch):
+ calls: list[str] = []
+ seen: dict = {}
+ backend = _non_mlx_backend(monkeypatch, "test_export_hub_push_reap_stale", calls, seen)
+ _reap_pruned(backend, monkeypatch)
+ backend._reap_key = None # not pruned this time
+ export_dir = tmp_path / "export-torchao-fp8"
+ export_dir.mkdir(parents = True)
+ (export_dir / "reap_report.json").write_text('{"kept_experts": {}}')
+ success, message, output_path = backend.export_merged_model(
+ str(tmp_path / "export"),
+ compressed_method = "torchao_fp8",
+ push_to_hub = True,
+ repo_id = "model",
+ hf_token = "hf_fake",
+ )
+ assert success is True, message
+ assert seen["folder"] == output_path
+ assert "reap_report.json" not in seen["uploaded"]
+ assert not Path(output_path, "reap_report.json").exists()
+
+
+def test_base_push_of_a_reap_pruned_model_uploads_its_report(tmp_path, monkeypatch):
+ calls: list[str] = []
+ seen: dict = {}
+ backend = _reap_pruned(
+ _non_mlx_backend(monkeypatch, "test_export_hub_push_reap_base", calls, seen), monkeypatch
+ )
+ export_dir = tmp_path / "export"
+ export_dir.mkdir()
+ (export_dir / "old.Q4_K_M.gguf").write_bytes(b"GGUF")
+ success, message, output_path = backend.export_base_model(
+ str(export_dir), push_to_hub = True, repo_id = "model", hf_token = "hf_fake"
+ )
+ assert success is True, message
+ assert "reap_report.json" in seen["uploaded"]
+
+
+def test_base_and_adapter_exports_after_a_reap_merge_of_a_lora_load(tmp_path, monkeypatch):
+ # REAP merged the adapters in memory (is_peft is False now); the load is still a LoRA one.
+ calls: list[str] = []
+ seen: dict = {}
+ backend = _non_mlx_backend(monkeypatch, "test_export_hub_push_reap_merged_peft", calls, seen)
+ backend._reap_merged_peft = True
+ success, message, _ = backend.export_base_model(str(tmp_path / "base"))
+ assert success is False and "PEFT model" in message
+ assert not (tmp_path / "base").exists()
+ success, message, _ = backend.export_lora_adapter(str(tmp_path / "lora"))
+ assert success is False and "merged into the model for a REAP export" in message
+
+
[email protected]("method", ["merged", "base"])
+def test_hub_uploads_delete_a_reap_report_left_in_a_reused_repo(tmp_path, monkeypatch, method):
+ # upload_folder never removes remote files; one it uploads in the same commit is kept, so a
+ # pruned export keeps its new report and any other export drops an old one.
+ calls: list[str] = []
+ seen: dict = {}
+ backend = _non_mlx_backend(
+ monkeypatch, f"test_export_hub_push_reap_delete_{method}", calls, seen
+ )
+ export = backend.export_merged_model if method == "merged" else backend.export_base_model
+ success, message, _ = export(
+ str(tmp_path / "export"), push_to_hub = True, repo_id = "model", hf_token = "hf_fake"
+ )
+ assert success is True, message
+ assert seen["delete_patterns"] == ["reap_report.json"]
+
+
+def test_cleanup_clears_reap_state_even_when_an_unload_fails(tmp_path, monkeypatch):
+ calls: list[str] = []
+ seen: dict = {}
+ backend = _reap_pruned(
+ _non_mlx_backend(monkeypatch, "test_export_hub_push_reap_cleanup", calls, seen), monkeypatch
+ )
+ backend._reap_model = weakref.ref(backend.current_model)
+
+ def unload(name):
+ raise RuntimeError("inference engine is busy")
+
+ backend.inference_backend = types.SimpleNamespace(
+ models = {"chat": object()}, unload_model = unload
+ )
+ assert backend.cleanup_memory() is False
+ assert backend._reap_key is None and backend._reap_model is None
+
+
class _GgufModel:
def save_pretrained_gguf(self, model_save_path, tokenizer, quantization_method):
output = Path(f"{model_save_path}_gguf")
diff --git a/studio/backend/tests/test_export_npu_q4nx.py b/studio/backend/tests/test_export_npu_q4nx.py
index b66e4fb8ce5..14c060c9dbf 100644
--- a/studio/backend/tests/test_export_npu_q4nx.py
+++ b/studio/backend/tests/test_export_npu_q4nx.py
@@ -8,6 +8,8 @@ Reuses the harness in test_export_gguf_discovery.py; the converter itself is stu
from __future__ import annotations
+import weakref
+
import json
import sys
from pathlib import Path
@@ -419,3 +421,36 @@ def test_existing_gguf_without_tokenizer_config_fails_before_converting(monkeypa
else:
raise AssertionError("expected a RuntimeError")
assert calls == []
+
+
[email protected]("pruned", [True, False])
+def test_q4nx_folder_carries_the_current_reap_report(monkeypatch, tmp_path, pruned):
+ # The NPU folder is deployed on its own, so its pruning provenance travels with it; a stale
+ # report from an earlier pruned conversion never survives an unpruned one.
+ import importlib.util
+ import sys
+
+ spec = importlib.util.spec_from_file_location(
+ "core.export.reap", Path(__file__).resolve().parents[1] / "core/export/reap.py"
+ )
+ reap = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(reap)
+ monkeypatch.setitem(sys.modules, "core.export.reap", reap)
+ model = _Model()
+ model._unsloth_reap_report = {"model.layers.0.mlp": [0, 2]}
+ export_mod, backend, save_dir, _cwd = _backend(monkeypatch, tmp_path, model)
+ backend.current_tokenizer = _Tokenizer()
+ backend._reap_key = (0.5, 512, None) if pruned else None
+ backend._reap_model = weakref.ref(model)
+ _fake_converter(export_mod, monkeypatch, [])
+ q4nx = save_dir / "npu-q4nx"
+ q4nx.mkdir(parents = True)
+ (q4nx / "reap_report.json").write_text('{"kept_experts": {"old": [1]}}')
+
+ success, message, _ = backend.export_gguf(str(save_dir), ["q4_1"], npu_q4nx = True)
+
+ assert success is True, message
+ report = q4nx / "reap_report.json"
+ assert report.is_file() is pruned
+ if pruned:
+ assert json.loads(report.read_text())["kept_experts"] == {"model.layers.0.mlp": [0, 2]}
diff --git a/studio/backend/tests/test_export_reap.py b/studio/backend/tests/test_export_reap.py
new file mode 100644
index 00000000000..9ee65aa11cc
--- /dev/null
+++ b/studio/backend/tests/test_export_reap.py
@@ -0,0 +1,1419 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Opt-in REAP expert pruning on the export page: MoE detection, the worker step, request models.
+
+Core's FastLanguageModel.reap_prune is stubbed; Core has its own GPU tests for the pruning itself.
+"""
+
+from __future__ import annotations
+
+import weakref
+
+import asyncio
+import json
+import queue
+import sys
+import tempfile
+import types
+
+import pytest
+from pydantic import ValidationError
+
+from core.export import reap as reap_mod
+from models.export import (
+ ExportBaseModelRequest,
+ ExportGGUFRequest,
+ ExportMergedModelRequest,
+ ReapOptions,
+)
+
+
+def test_moe_info_from_config_layouts():
+ assert reap_mod.moe_info_from_config({"num_experts": 128, "num_experts_per_tok": 8}) == {
+ "num_experts": 128,
+ "top_k": 8,
+ }
+ # Mixtral / DeepSeek / multimodal text_config / per-layer top_k lists.
+ assert (
+ reap_mod.moe_info_from_config({"num_local_experts": 8, "num_experts_per_tok": 2})[
+ "num_experts"
+ ]
+ == 8
+ )
+ assert (
+ reap_mod.moe_info_from_config({"n_routed_experts": 64, "num_experts_per_tok": 6})["top_k"]
+ == 6
+ )
+ assert reap_mod.moe_info_from_config(
+ {"model_type": "x_vl", "text_config": {"num_experts": 16, "top_k": 2}}
+ ) == {"num_experts": 16, "top_k": 2}
+ assert reap_mod.moe_info_from_config({"moe_num_experts": 32, "top_k": [4, 8]})["top_k"] == 8
+
+
+ "config",
+ [
+ None,
+ {"model_type": "llama", "hidden_size": 64},
+ {"num_experts": 0, "num_experts_per_tok": 2},
+ {"num_experts": 1, "num_experts_per_tok": 1},
+ {"num_experts": True, "num_experts_per_tok": 1},
+ {"num_experts": 8},
+ ],
+)
+def test_moe_info_from_config_rejects_dense(config):
+ assert reap_mod.moe_info_from_config(config) is None
+
+
+def test_moe_export_info_local_folder_and_lora(tmp_path):
+ base = tmp_path / "base"
+ base.mkdir()
+ (base / "config.json").write_text(json.dumps({"num_experts": 8, "num_experts_per_tok": 2}))
+ lora = tmp_path / "lora"
+ lora.mkdir()
+ (lora / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": str(base)}))
+ assert reap_mod.moe_export_info(str(base)) == {"num_experts": 8, "top_k": 2}
+ # A LoRA checkpoint resolves to its base model's config.
+ assert reap_mod.moe_export_info(str(lora)) == {"num_experts": 8, "top_k": 2}
+ # Unreadable or missing never raises.
+ assert reap_mod.moe_export_info(str(tmp_path / "missing")) is None
+ (base / "config.json").write_text("{not json")
+ assert reap_mod.moe_export_info(str(base)) is None
+
+
+class _Model:
+ def __init__(self, four_bit = False):
+ self.is_loaded_in_4bit = four_bit
+ self.config = types.SimpleNamespace(_name_or_path = "org/base-model")
+ self.merged = False
+
+ def merge_and_unload(self):
+ merged = _Model()
+ merged.merged = True
+ return merged
+
+
+class _Backend:
+ def __init__(
+ self,
+ model,
+ is_peft = False,
+ ):
+ self.current_model = model
+ self.current_tokenizer = object()
+ self.is_peft = is_peft
+
+
+def fake_reap(monkeypatch):
+ calls = []
+
+ def reap_prune(model, tokenizer, **kwargs):
+ calls.append(kwargs)
+ model._unsloth_reap_report = {
+ "model.layers.0.mlp": [0, 2, 3],
+ "model.layers.1.mlp": [1, 2, 3],
+ }
+ return model
+
+ fake = types.ModuleType("unsloth")
+ fake.FastLanguageModel = types.SimpleNamespace(reap_prune = reap_prune)
+ monkeypatch.setitem(sys.modules, "unsloth", fake)
+ return calls
+
+
+def test_apply_reap_prunes_once_and_reuses(fake_reap, tmp_path):
+ backend = _Backend(_Model())
+ options = {"sparsity": 0.25, "num_calibration_samples": 64, "dataset": " "}
+ ok, message = reap_mod.apply_reap(backend, options, str(tmp_path))
+ assert ok and "3 experts" in message and "2 layers" in message
+ assert len(fake_reap) == 1
+ kwargs = fake_reap[0]
+ assert kwargs["sparsity"] == 0.25 and kwargs["num_calibration_samples"] == 64
+ assert kwargs["dataset"] is None
+ # Staged where it fits (export dir or the temp dir), discarded with the loaded model; the folder
+ # carries the model name, which GGUF file names come from.
+ staging = backend._reap_staging.name
+ import os
+
+ assert os.path.isdir(staging) and kwargs["save_directory"] == os.path.join(
+ staging, "base-model-REAP"
+ )
+ # A multi-format export calls the worker again with the same settings: no second pruning.
+ assert reap_mod.apply_reap(backend, dict(options), str(tmp_path)) == (True, "")
+ assert len(fake_reap) == 1
+ ok, message = reap_mod.apply_reap(backend, {**options, "sparsity": 0.5}, str(tmp_path))
+ assert not ok and "different REAP settings" in message
+ reap_mod.discard_reap_staging(backend)
+ assert backend._reap_key is None
+ assert not os.path.exists(staging)
+
+
+def test_apply_reap_merges_lora_and_refuses_4bit(fake_reap, tmp_path):
+ assert reap_mod.apply_reap(_Backend(_Model()), None, str(tmp_path)) == (True, "")
+ ok, message = reap_mod.apply_reap(
+ _Backend(_Model(four_bit = True)), {"sparsity": 0.25}, str(tmp_path)
+ )
+ assert not ok and "16-bit" in message and not fake_reap
+ backend = _Backend(_Model(), is_peft = True)
+ ok, _ = reap_mod.apply_reap(backend, {"sparsity": 0.25}, str(tmp_path))
+ assert ok and backend.current_model.merged and backend.is_peft is False
+ reap_mod.discard_reap_staging(backend)
+
+
+def test_write_reap_report(fake_reap, tmp_path):
+ backend = _Backend(_Model())
+ reap_mod.apply_reap(backend, {"sparsity": 0.25, "num_calibration_samples": 64}, str(tmp_path))
+ out = tmp_path / "export"
+ out.mkdir()
+ reap_mod.write_reap_report(backend, str(out))
+ report = json.loads((out / reap_mod.REPORT_NAME).read_text())
+ assert report["sparsity"] == 0.25 and report["dataset"] == "mlabonne/open-perfectblend"
+ assert report["kept_experts"]["model.layers.1.mlp"] == [1, 2, 3]
+ # A Hub-only export (no local folder) writes nothing and does not raise.
+ reap_mod.write_reap_report(backend, None)
+ reap_mod.discard_reap_staging(backend)
+
+
+class _ExportBackend:
+ def __init__(self):
+ self.calls = []
+
+ def export_merged_model(self, **kwargs):
+ self.calls.append(("merged", kwargs))
+ return True, "ok", "/out"
+
+ def export_gguf(self, **kwargs):
+ self.calls.append(("gguf", kwargs))
+ return True, "ok", "/out"
+
+ def export_lora_adapter(self, **kwargs):
+ self.calls.append(("lora", kwargs))
+ return True, "ok", "/out"
+
+
+def _drain(q):
+ items = []
+ while not q.empty():
+ items.append(q.get())
+ return items
+
+
+def test_worker_runs_reap_before_export(monkeypatch):
+ from core.export.worker import _handle_export
+
+ seen = []
+ monkeypatch.setattr(
+ reap_mod, "apply_reap", lambda b, o, p, **k: (seen.append(o) or (True, "kept"))
+ )
+ monkeypatch.setattr(reap_mod, "sync_reap_report", lambda b, path: seen.append(("report", path)))
+ backend, q = _ExportBackend(), queue.Queue()
+ _handle_export(
+ backend, {"export_type": "gguf", "save_directory": "/tmp/o", "reap": {"sparsity": 0.5}}, q
+ )
+ # GGUF exports keep one report per file themselves, before their upload.
+ assert seen == [{"sparsity": 0.5}]
+ assert backend.calls[0][0] == "gguf"
+ final = _drain(q)[-1]
+ assert final["success"] is True
+
+ # Off by default: no pruning; only the report sync, which clears a stale report.
+ seen.clear()
+ _handle_export(backend, {"export_type": "merged", "save_directory": "/tmp/o"}, q)
+ assert seen == [("report", "/out")]
+
+
+def test_worker_reap_failure_skips_export(monkeypatch):
+ from core.export.worker import _handle_export
+
+ monkeypatch.setattr(reap_mod, "apply_reap", lambda b, o, p, **k: (False, "needs 16-bit"))
+ backend, q = _ExportBackend(), queue.Queue()
+ _handle_export(
+ backend,
+ {"export_type": "merged", "save_directory": "/tmp/o", "reap": {"sparsity": 0.25}},
+ q,
+ )
+ assert backend.calls == []
+ final = _drain(q)[-1]
+ assert final["success"] is False and final["message"] == "needs 16-bit"
+
+
+def test_request_models_reap_is_optional_and_bounded():
+ for cls in (ExportMergedModelRequest, ExportBaseModelRequest, ExportGGUFRequest):
+ assert cls(save_directory = "/tmp/o").reap is None
+ req = cls(save_directory = "/tmp/o", reap = {"sparsity": 0.5})
+ assert req.reap.num_calibration_samples == 512 and req.reap.dataset is None
+ assert ReapOptions(dataset = "mlabonne/open-perfectblend").dataset == "mlabonne/open-perfectblend"
+ for bad in (
+ {"sparsity": 0},
+ {"sparsity": 1},
+ {"num_calibration_samples": 4},
+ {"dataset": "../etc"},
+ {"dataset": "a b"},
+ {"dataset": "a/b/c"},
+ ):
+ with pytest.raises(ValidationError):
+ ReapOptions(**bad)
+
+
+def test_moe_info_route_local_folder(monkeypatch):
+ from routes import export as export_route
+ with tempfile.TemporaryDirectory() as d:
+ with open(f"{d}/config.json", "w") as f:
+ json.dump({"num_local_experts": 8, "num_experts_per_tok": 2}, f)
+ res = asyncio.run(
+ export_route.get_moe_info(
+ model = d, hf_token = None, current_subject = "t", allow_ambient = False
+ )
+ )
+ assert (res.num_experts, res.top_k) == (8, 2)
+ with open(f"{d}/config.json", "w") as f:
+ json.dump({"model_type": "llama"}, f)
+ res = asyncio.run(
+ export_route.get_moe_info(
+ model = d, hf_token = None, current_subject = "t", allow_ambient = False
+ )
+ )
+ assert res.num_experts is None and res.top_k is None
+
+
+def test_moe_info_reports_router_groups():
+ dsv3 = {"n_routed_experts": 256, "num_experts_per_tok": 8, "n_group": 8, "topk_group": 4}
+ assert reap_mod.moe_info_from_config(dsv3) == {
+ "num_experts": 256,
+ "top_k": 8,
+ "n_group": 8,
+ "topk_group": 4,
+ }
+ # Grouped routing without topk_group: Core refuses it, so the card is hidden.
+ assert reap_mod.moe_info_from_config({**dsv3, "topk_group": None}) is None
+
+
+def test_staging_parent_follows_the_chosen_drive(tmp_path, monkeypatch):
+ from utils.paths import storage_roots
+
+ exports = tmp_path / "exports"
+ exports.mkdir()
+ other = tmp_path / "other_drive"
+ other.mkdir()
+ monkeypatch.setattr(storage_roots, "resolve_export_dir", lambda *a, **k: exports)
+ monkeypatch.setattr(
+ storage_roots,
+ "resolve_export_write_dir",
+ lambda p = None: (other / "new" / "folder") if p else exports,
+ )
+ # An absolute save folder on another drive stages there (its nearest existing ancestor).
+ assert reap_mod.reap_staging_parent(str(other / "new" / "folder")) == other
+ assert reap_mod.reap_staging_parent("") == exports
+
+
+def test_cancel_sweeps_a_killed_workers_staging(tmp_path, monkeypatch):
+ registry = tmp_path / "reap_staging.json"
+ monkeypatch.setattr(reap_mod, "_registry", lambda: registry)
+ owned = tmp_path / "unsloth-hub-upload-a"
+ owned.mkdir()
+ (owned / reap_mod._OWNER_FILE).write_text("4242")
+ (owned / "model.safetensors").write_bytes(b"x" * 16)
+ foreign = tmp_path / "not-ours"
+ foreign.mkdir()
+ live = tmp_path / "unsloth-hub-upload-live"
+ live.mkdir()
+ import os
+
+ (live / reap_mod._OWNER_FILE).write_text(str(os.getpid()))
+ registry.write_text(
+ json.dumps(
+ [
+ {"path": str(owned), "pid": 4242},
+ # A path without its owner marker is never deleted.
+ {"path": str(foreign), "pid": 4242},
+ {"path": str(live), "pid": os.getpid()},
+ ]
+ )
+ )
+ reap_mod.sweep_reap_staging(dead_pid = 4242)
+ assert not owned.exists() and foreign.exists() and live.exists()
+ # The live worker's copy stays registered; the next sweep without a dead pid keeps it too.
+ reap_mod.sweep_reap_staging()
+ assert live.exists()
+ assert {e["path"] for e in json.loads(registry.read_text())} == {str(foreign), str(live)}
+
+
+def test_moe_info_route_uses_the_authorized_adapter_base(monkeypatch, tmp_path):
+ from routes import export as export_route
+
+ lora = tmp_path / "lora"
+ lora.mkdir()
+ # The adapter names one base; the authorizer resolves (and checks) the one that is used.
+ (lora / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": "/elsewhere"}))
+ base = tmp_path / "base"
+ base.mkdir()
+ (base / "config.json").write_text(json.dumps({"num_experts": 8, "num_experts_per_tok": 2}))
+ checked = []
+ monkeypatch.setattr(export_route, "_authorized_adapter_base", lambda p: str(base))
+ monkeypatch.setattr(
+ export_route, "validate_job_paths", lambda values, **k: checked.append(values)
+ )
+ res = asyncio.run(
+ export_route.get_moe_info(
+ model = str(lora), hf_token = None, current_subject = "t", allow_ambient = False
+ )
+ )
+ assert (res.num_experts, res.top_k) == (8, 2)
+ assert {"base_model": str(base), "hf_token": None} in checked
+
+
+def _core_keys():
+ import ast
+ from pathlib import Path
+
+ core = Path(__file__).resolve().parents[3] / "unsloth" / "models" / "reap.py"
+ if not core.is_file():
+ pytest.skip("Core reap.py is not in this tree")
+ tree = ast.parse(core.read_text(encoding = "utf-8"))
+ return {
+ t.id: ast.literal_eval(node.value)
+ for node in tree.body
+ if isinstance(node, ast.Assign)
+ for t in node.targets
+ if isinstance(t, ast.Name) and t.id in ("_NUM_EXPERTS_KEYS", "_TOP_K_KEYS")
+ }
+
+
+def test_probe_keys_cover_core():
+ # A key Core reads but the probe does not would hide REAP for a model Core can prune.
+ consts = _core_keys()
+ for name in ("_NUM_EXPERTS_KEYS", "_TOP_K_KEYS"):
+ assert set(consts[name]) <= set(getattr(reap_mod, name))
+ # HunYuan-A13B and Ernie 4.5 as their config.json files spell them.
+ assert reap_mod.moe_info_from_config({"num_experts": 64, "moe_topk": [8] * 32})["top_k"] == 8
+ assert reap_mod.moe_info_from_config({"moe_num_experts": 64, "moe_k": 6})["top_k"] == 6
+
+
+def test_probe_extra_keys_are_raw_names_core_reads():
+ # Studio may only add raw config.json names that a transformers config maps onto a Core key
+ # (Core reads them through attribute_map); anything else would advertise a model Core refuses.
+ pytest.importorskip("transformers")
+ from transformers.models.auto.configuration_auto import CONFIG_MAPPING
+
+ consts = _core_keys()
+ mapped = {}
+ for config_class in CONFIG_MAPPING.values():
+ for alias, raw in (getattr(config_class, "attribute_map", None) or {}).items():
+ mapped.setdefault(raw, set()).add(alias)
+ for name in ("_NUM_EXPERTS_KEYS", "_TOP_K_KEYS"):
+ core_keys, studio_keys = consts[name], getattr(reap_mod, name)
+ for extra in set(studio_keys) - set(core_keys):
+ assert mapped.get(extra, set()) & set(core_keys), f"{extra} is not read by Core"
+
+
+def test_custom_calibration_dataset_uses_the_request_token(fake_reap, tmp_path, monkeypatch):
+ import datasets
+
+ opened = []
+ monkeypatch.setattr(
+ datasets, "load_dataset", lambda *a, **k: opened.append((a, k)) or {"train": ["rows"]}
+ )
+ backend = _Backend(_Model())
+ reap_mod.apply_reap(
+ backend, {"sparsity": 0.25, "dataset": "org/private"}, str(tmp_path), hf_token = "hf_x"
+ )
+ assert opened == [(("org/private",), {"streaming": True, "token": "hf_x"})]
+ assert fake_reap[0]["dataset"] == ["rows"]
+ reap_mod.discard_reap_staging(backend)
+ # The default dataset is left to Core.
+ backend = _Backend(_Model())
+ reap_mod.apply_reap(backend, {"sparsity": 0.25}, str(tmp_path), hf_token = "hf_x")
+ assert fake_reap[1]["dataset"] is None and len(opened) == 1
+ reap_mod.discard_reap_staging(backend)
+
+
+def test_worker_forwards_the_export_token_to_reap(monkeypatch):
+ from core.export.worker import _handle_export
+
+ seen = {}
+ monkeypatch.setattr(
+ reap_mod,
+ "apply_reap",
+ lambda b, o, p, hf_token = None: (seen.update(token = hf_token) or (True, "")),
+ )
+ monkeypatch.setattr(reap_mod, "sync_reap_report", lambda b, path: None)
+ backend, q = _ExportBackend(), queue.Queue()
+ backend._checkpoint_token = "hf_load"
+ _handle_export(
+ backend, {"export_type": "merged", "save_directory": "/tmp/o", "reap": {"sparsity": 0.5}}, q
+ )
+ assert seen["token"] == "hf_load"
+ _handle_export(
+ backend,
+ {
+ "export_type": "merged",
+ "save_directory": "/tmp/o",
+ "hf_token": "hf_push",
+ "reap": {"sparsity": 0.5},
+ },
+ q,
+ )
+ assert seen["token"] == "hf_push"
+
+
+def test_moe_info_route_follows_a_hub_lora_to_its_authorized_base(monkeypatch):
+ from routes import export as export_route
+ from utils.models import model_config
+
+ checked, probed = [], []
+
+ async def require(model, token):
+ checked.append((model, token))
+
+ monkeypatch.setattr(
+ export_route, "_require_model_access_or_caller_token", require, raising = False
+ )
+ import routes.models as models_route
+
+ monkeypatch.setattr(models_route, "_require_model_access_or_caller_token", require)
+ monkeypatch.setattr(
+ model_config, "get_base_model_from_lora_identifier", lambda m, t = None: "org/moe-base"
+ )
+
+ def probe(model, token, local, **kwargs):
+ probed.append(model)
+ return None if model == "me/lora" else {"num_experts": 8, "top_k": 2}
+
+ monkeypatch.setattr(reap_mod, "moe_export_info", probe)
+ # No network: the up-front adapter check finds nothing, so the config-less fallback runs.
+ monkeypatch.setattr(reap_mod, "hub_file_exists", lambda repo, name, token = None: False)
+ res = asyncio.run(
+ export_route.get_moe_info(
+ model = "me/lora", hf_token = "hf_x", current_subject = "t", allow_ambient = False
+ )
+ )
+ assert (res.num_experts, res.top_k) == (8, 2)
+ assert probed == ["me/lora", "org/moe-base"]
+ # The base is authorized with the caller's token before its config is read.
+ assert checked == [("me/lora", "hf_x"), ("org/moe-base", "hf_x")]
+
+
+def test_local_adapter_with_a_hub_base_reads_the_base_online(tmp_path, monkeypatch):
+ from utils.models import model_config
+
+ lora = tmp_path / "lora"
+ lora.mkdir()
+ (lora / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": "org/moe"}))
+ calls = []
+
+ def read(model, token, local_files_only, revision):
+ calls.append((model, local_files_only))
+ return {"num_experts": 8, "num_experts_per_tok": 2}
+
+ monkeypatch.setattr(model_config, "_read_raw_config_json", read)
+ # The Hub base has no hf_quant_config.json (checked without network here).
+ monkeypatch.setattr(reap_mod, "hub_file_exists", lambda repo, name, token = None: False)
+ assert reap_mod.moe_export_info(str(lora)) == {"num_experts": 8, "top_k": 2}
+ # The adapter is local, its Hub base is not: an uncached base must still be fetched.
+ assert calls == [("org/moe", False)]
+
+
+def test_attached_mtp_head_is_refused_before_merging(fake_reap, tmp_path):
+ model = _Model()
+ model._unsloth_mtp_head = object()
+ backend = _Backend(model, is_peft = True)
+ ok, message = reap_mod.apply_reap(backend, {"sparsity": 0.25}, str(tmp_path))
+ assert not ok and "MTP head" in message
+ assert not fake_reap and backend.is_peft is True and not model.merged
+
+
+def test_hub_cards_name_the_model_reap_started_from(fake_reap, tmp_path):
+ from core.export.export import _card_base_model
+
+ backend = _Backend(_Model())
+ reap_mod.apply_reap(backend, {"sparsity": 0.25}, str(tmp_path))
+ model = backend.current_model
+ # Core repoints the config at the staging copy; the card keeps the original id.
+ model.config._name_or_path = str(tmp_path / "staging" / "base-model-REAP")
+ assert _card_base_model(model) == "org/base-model"
+ plain = _Model()
+ assert _card_base_model(plain) == "org/base-model"
+ reap_mod.discard_reap_staging(backend)
+
+
+def test_base_export_of_a_lora_keeps_its_refusal(monkeypatch):
+ from core.export.worker import _handle_export
+
+ seen = []
+ monkeypatch.setattr(reap_mod, "apply_reap", lambda *a, **k: seen.append(a) or (True, ""))
+
+ class _PeftBackend(_ExportBackend):
+ is_peft = True
+
+ def export_base_model(self, **kwargs):
+ return False, "This is a LoRA checkpoint; use the merged export.", None
+
+ backend, q = _PeftBackend(), queue.Queue()
+ _handle_export(
+ backend, {"export_type": "base", "save_directory": "/tmp/o", "reap": {"sparsity": 0.5}}, q
+ )
+ assert seen == []
+ final = _drain(q)[-1]
+ assert final["success"] is False and "LoRA" in final["message"]
+
+
+def test_sweep_writes_nothing_for_users_who_never_used_reap(tmp_path, monkeypatch):
+ registry = tmp_path / "cache" / "reap_staging.json"
+ monkeypatch.setattr(reap_mod, "_registry", lambda: registry)
+ reap_mod.sweep_reap_staging()
+ reap_mod.sweep_reap_staging(dead_pid = 12345)
+ reap_mod.discard_reap_staging(_Backend(_Model()))
+ assert not registry.exists() and not registry.parent.exists()
+
+
+def test_failed_pruning_unloads_the_partly_pruned_model(tmp_path, monkeypatch):
+ def reap_prune(model, tokenizer, **kwargs):
+ raise RuntimeError("out of memory in layer 7")
+
+ fake = types.ModuleType("unsloth")
+ fake.FastLanguageModel = types.SimpleNamespace(reap_prune = reap_prune)
+ monkeypatch.setitem(sys.modules, "unsloth", fake)
+ monkeypatch.setattr(reap_mod, "_registry", lambda: tmp_path / "reap_staging.json")
+ unloaded = []
+
+ class _Loaded(_Backend):
+ def cleanup_memory(self):
+ unloaded.append(True)
+ reap_mod.discard_reap_staging(self)
+ self.current_model = None
+
+ backend = _Loaded(_Model(), is_peft = True)
+ with pytest.raises(RuntimeError, match = "unloaded"):
+ reap_mod.apply_reap(backend, {"sparsity": 0.25}, str(tmp_path))
+ # Merged and possibly part pruned: unloaded, so no later export (REAP or not) can use it.
+ assert unloaded and backend.current_model is None
+ assert backend._reap_key is None and backend._reap_staging is None
+ import glob
+
+ assert not glob.glob(str(tmp_path / "unsloth-hub-upload-*"))
+
+
+def test_probe_matches_core_on_identity_experts_and_split_levels():
+ # LongCat style identity experts: Core refuses, so the card must not appear.
+ assert (
+ reap_mod.moe_info_from_config(
+ {"n_routed_experts": 8, "num_experts_per_tok": 2, "zero_expert_num": 2}
+ )
+ is None
+ )
+ assert (
+ reap_mod.moe_info_from_config(
+ {"num_experts": 8, "top_k": 2, "use_bidirectional_attention": "all"}
+ )
+ is None
+ )
+ # Each field from the first level that has it, as Core's _first_attr reads them.
+ split = {"num_experts": 8, "text_config": {"top_k": 2}}
+ assert reap_mod.moe_info_from_config(split) == {"num_experts": 8, "top_k": 2}
+
+
+def test_validated_sparsity_reaches_core_unrounded(fake_reap, tmp_path):
+ backend = _Backend(_Model())
+ reap_mod.apply_reap(
+ backend, {"sparsity": 0.33337, "num_calibration_samples": 64}, str(tmp_path)
+ )
+ assert fake_reap[0]["sparsity"] == 0.33337
+ reap_mod.discard_reap_staging(backend)
+
+
+def test_report_follows_the_exported_model(fake_reap, tmp_path):
+ out = tmp_path / "export"
+ out.mkdir()
+ backend = _Backend(_Model())
+ reap_mod.apply_reap(backend, {"sparsity": 0.25, "num_calibration_samples": 64}, str(tmp_path))
+ reap_mod.sync_reap_report(backend, str(out))
+ assert (out / reap_mod.REPORT_NAME).is_file()
+ reap_mod.discard_reap_staging(backend)
+ # The same folder reused for an export of an unpruned model: the old report goes.
+ reap_mod.sync_reap_report(_Backend(_Model()), str(out))
+ assert not (out / reap_mod.REPORT_NAME).exists()
+
+
+def test_probe_hides_layouts_core_refuses():
+ base = {"n_routed_experts": 16, "num_experts_per_tok": 2}
+ # Grouped routing without topk_group, and model-parallel layouts saved in the config.
+ assert reap_mod.moe_info_from_config({**base, "n_group": 4}) is None
+ assert reap_mod.moe_info_from_config({**base, "n_group": 1})["num_experts"] == 16
+ for layout in (
+ {"tp_size": 2},
+ {"pp_size": 4},
+ {"fsdp_size": 2},
+ {"enable_expert_parallel": True},
+ ):
+ assert reap_mod.moe_info_from_config({**base, "distributed_config": layout}) is None
+ assert (
+ reap_mod.moe_info_from_config({**base, "distributed_config": {"tp_size": 1}})["top_k"] == 2
+ )
+
+
+def test_probe_hides_stateful_decoders_core_refuses():
+ moe = {"num_experts": 64, "num_experts_per_tok": 4}
+ for model_type in ("glm_moe_dsa", "hy_v4", "zaya"):
+ assert reap_mod.moe_info_from_config({**moe, "model_type": model_type}) is None
+ assert (
+ reap_mod.moe_info_from_config(
+ {"model_type": "glm5_next", "text_config": {**moe, "model_type": "glm5_next_text"}}
+ )
+ is None
+ )
+ assert reap_mod.moe_info_from_config({**moe, "model_type": "qwen3_moe"})["num_experts"] == 64
+
+
+def test_stateful_model_types_match_transformers():
+ # Each listed type really has decoder layers taking prev_* state, and no other type does.
+ pytest.importorskip("transformers")
+ # The modeling modules import torch (absent on the CPU-only CI runners).
+ pytest.importorskip("torch")
+ import importlib
+ import inspect
+
+ from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES
+
+ for model_type in sorted(reap_mod._STATEFUL_MODEL_TYPES - {"glm5_next_text"}):
+ if model_type not in CONFIG_MAPPING_NAMES:
+ continue
+ module = importlib.import_module(f"transformers.models.{model_type}.modeling_{model_type}")
+ layers = [
+ c
+ for n, c in vars(module).items()
+ if inspect.isclass(c) and n.endswith("DecoderLayer") and hasattr(c, "forward")
+ ]
+ assert any(
+ any(p.startswith("prev_") for p in inspect.signature(c.forward).parameters)
+ for c in layers
+ ), model_type
+
+
+def test_probe_hides_hash_routed_moe():
+ dsv4 = {"model_type": "deepseek_v4", "n_routed_experts": 256, "num_experts_per_tok": 6}
+ assert reap_mod.moe_info_from_config(dsv4) is None
+
+
+def test_hash_routed_model_types_match_transformers():
+ # The listed types are exactly the installed transformers models whose code builds tid2eid.
+ pytest.importorskip("transformers")
+ from pathlib import Path
+
+ import transformers
+
+ models = Path(transformers.__file__).parent / "models"
+ found = {
+ f.parent.name
+ for f in models.glob("*/modeling_*.py")
+ if "tid2eid" in f.read_text(encoding = "utf-8", errors = "ignore")
+ }
+ assert found <= reap_mod._HASH_ROUTED_MODEL_TYPES, found - reap_mod._HASH_ROUTED_MODEL_TYPES
+
+
[email protected]("dies_on", ["graceful", "terminate", "kill", "already_dead"])
+def test_every_confirmed_worker_death_sweeps_its_reap_staging(monkeypatch, dies_on):
+ # Server shutdown with REAP pruning: the worker cannot remove its staging copy itself, so the
+ # orchestrator sweeps for that pid once it knows the worker is dead, not only on a cancel.
+ from core.export import orchestrator as orchestrator_module
+
+ class Worker:
+ pid = 4321
+
+ def __init__(self):
+ self.alive = dies_on != "already_dead"
+
+ def is_alive(self):
+ return self.alive
+
+ def join(self, timeout = None):
+ if dies_on == "graceful":
+ self.alive = False
+
+ def terminate(self):
+ if dies_on == "terminate":
+ self.alive = False
+
+ def kill(self):
+ self.alive = False
+
+ swept = []
+ monkeypatch.setattr(
+ reap_mod, "sweep_reap_staging", lambda dead_pid = None: swept.append(dead_pid)
+ )
+ orch = orchestrator_module.ExportOrchestrator()
+ orch._proc = Worker()
+ monkeypatch.setattr(orch, "_drain_queue", lambda: None)
+ orch._cmd_queue = type("Q", (), {"put": lambda self, item: None})()
+ try:
+ assert orch._shutdown_subprocess(timeout = 0) is True
+ finally:
+ orch._proc = None
+ assert swept == [4321]
+
+
+def test_a_worker_that_survives_kill_is_not_swept(monkeypatch):
+ from core.export import orchestrator as orchestrator_module
+
+ class Wedged:
+ pid = 4321
+ is_alive = staticmethod(lambda: True)
+ join = terminate = kill = staticmethod(lambda *a, **k: None)
+
+ swept = []
+ monkeypatch.setattr(
+ reap_mod, "sweep_reap_staging", lambda dead_pid = None: swept.append(dead_pid)
+ )
+ orch = orchestrator_module.ExportOrchestrator()
+ orch._proc = Wedged()
+ monkeypatch.setattr(orch, "_drain_queue", lambda: None)
+ orch._cmd_queue = type("Q", (), {"put": lambda self, item: None})()
+ try:
+ assert orch._shutdown_subprocess(timeout = 0) is False
+ finally:
+ orch._proc = None
+ assert swept == []
+
+
+ "result",
+ [
+ (False, "GGUF files were saved to /out, but the Hub upload failed: 503", "/out"),
+ (False, "GGUF export failed: out of disk", None),
+ (True, "ok", "/out"),
+ ],
+)
+def test_the_worker_leaves_gguf_reports_to_the_gguf_export(monkeypatch, result):
+ # export_gguf writes one report per GGUF before its upload; a folder-level one would describe
+ # every GGUF a reused folder holds.
+ from core.export.worker import _handle_export
+
+ seen = []
+ monkeypatch.setattr(reap_mod, "sync_reap_report", lambda b, path, *a: seen.append(path))
+ backend, q = _ExportBackend(), queue.Queue()
+ backend.export_gguf = lambda **kwargs: result
+ _handle_export(backend, {"export_type": "gguf", "save_directory": "/tmp/o"}, q)
+ assert seen == []
+
+
+def test_gguf_report_names_follow_each_file():
+ assert (
+ reap_mod.gguf_report_name("/x/model-REAP.Q4_K_M.gguf")
+ == "model-REAP.Q4_K_M.reap_report.json"
+ )
+ assert reap_mod.gguf_report_name(".Q8_0.GGUF") == ".Q8_0.reap_report.json"
+
+
+def test_cleanup_after_a_worker_crash_sweeps_its_staging(monkeypatch):
+ # The worker died on its own (CUDA crash, OOM kill) after staging: cleanup sees it dead.
+ from core.export import orchestrator as orchestrator_module
+
+ class Dead:
+ pid = 777
+ is_alive = staticmethod(lambda: False)
+
+ swept = []
+ monkeypatch.setattr(
+ reap_mod, "sweep_reap_staging", lambda dead_pid = None: swept.append(dead_pid)
+ )
+ orch = orchestrator_module.ExportOrchestrator()
+ orch._proc = Dead()
+ try:
+ assert orch.cleanup_memory() is True
+ finally:
+ orch._proc = None
+ assert swept == [777]
+
+
[email protected]("export_type", ["merged", "base"])
[email protected]("saved_locally", [True, False])
+def test_a_failed_upload_after_a_complete_local_save_still_syncs_the_report(
+ monkeypatch, export_type, saved_locally
+):
+ # merged / base return no path when the Hub upload raises; the local save is complete by then.
+ from core.export.worker import _handle_export
+
+ seen = []
+ monkeypatch.setattr(reap_mod, "sync_reap_report", lambda b, path: seen.append(path))
+ backend, q = _ExportBackend(), queue.Queue()
+ backend._local_export_path = "/stale" # from an earlier export: never reused
+
+ def export(**kwargs):
+ if saved_locally:
+ backend._local_export_path = "/out"
+ return False, "Export failed: 503 from the Hub", None
+
+ setattr(
+ backend, "export_merged_model" if export_type == "merged" else "export_base_model", export
+ )
+ _handle_export(backend, {"export_type": export_type, "save_directory": "/tmp/o"}, q)
+ assert seen == (["/out"] if saved_locally else [])
+ assert _drain(q)[-1]["success"] is False
+
+
+ "method, offered",
+ [
+ ("fp8", False),
+ ("compressed-tensors", False),
+ ("sparseml", False),
+ ("modelopt", False),
+ ("gptq", False),
+ ("awq", False),
+ ("nvfp4", False),
+ ("some-future-format", False),
+ # Packed unless the Hub id maps back to 16-bit (below); gpt-oss MXFP4 dequantizes to
+ # bf16 without native kernels.
+ ("bitsandbytes", False),
+ ("mxfp4", True),
+ ],
+)
+def test_probe_offers_reap_only_for_quantization_a_16_bit_load_unpacks(method, offered):
+ config = {"model_type": "qwen3_moe", "num_experts": 128, "num_experts_per_tok": 8}
+ for holder in ("top", "text_config"):
+ quant = {"quant_method": method}
+ cfg = (
+ dict(config, quantization_config = quant)
+ if holder == "top"
+ else dict(config, text_config = {"quantization_config": quant})
+ )
+ assert (reap_mod.moe_info_from_config(cfg) is not None) is offered, (method, holder)
+ # A bitsandbytes config from before quant_method existed reads the same.
+ old_bnb = dict(config, quantization_config = {"load_in_4bit": True})
+ assert reap_mod.moe_info_from_config(old_bnb) is None
+
+
+def test_probe_hides_reap_for_an_older_modelopt_export(tmp_path, monkeypatch):
+ # Declared in hf_quant_config.json, not config.json, as the loader reads it.
+ folder = tmp_path / "moe-modelopt"
+ folder.mkdir()
+ (folder / "config.json").write_text(json.dumps({"num_experts": 8, "num_experts_per_tok": 2}))
+ assert reap_mod.moe_export_info(str(folder))["num_experts"] == 8
+ (folder / "hf_quant_config.json").write_text('{"quantization": {"quant_algo": "FP8"}}')
+ assert reap_mod.moe_export_info(str(folder)) is None
+ # A Hub id is checked for the same file.
+ import utils.models.model_config as model_config
+
+ monkeypatch.setattr(
+ model_config,
+ "_read_raw_config_json",
+ lambda *a, **k: {"num_experts": 8, "num_experts_per_tok": 2},
+ )
+ monkeypatch.setattr(reap_mod, "hub_file_exists", lambda repo, name, token = None: True)
+ assert reap_mod.moe_export_info("org/moe-modelopt", local_files_only = False) is None
+ monkeypatch.setattr(reap_mod, "hub_file_exists", lambda repo, name, token = None: False)
+ assert reap_mod.moe_export_info("org/moe-modelopt", local_files_only = False)["num_experts"] == 8
+
+
+ "route, request_cls",
+ [
+ ("export_merged_model", ExportMergedModelRequest),
+ ("export_base_model", ExportBaseModelRequest),
+ ("export_gguf", ExportGGUFRequest),
+ ],
+)
+def test_custom_reap_dataset_is_validated_with_the_callers_token(route, request_cls):
+ # Managed accounts refuse a remote dataset without the caller's own token (403), so the
+ # dataset check must carry the token the request supplied.
+ from routes import export as export_route
+
+ class Stop(Exception):
+ pass
+
+ checked = []
+
+ def validate(values, **kwargs):
+ checked.append(values)
+ if "hf_dataset" in values:
+ raise Stop
+
+ request = request_cls(
+ save_directory = "out",
+ hf_token = "hf_caller",
+ reap = {"sparsity": 0.25, "dataset": "org/calib"},
+ )
+ original = export_route.validate_job_paths
+ export_route.validate_job_paths = validate
+ try:
+ with pytest.raises(Stop):
+ asyncio.run(
+ getattr(export_route, route)(
+ request = request, current_subject = "t", allow_ambient = False
+ )
+ )
+ finally:
+ export_route.validate_job_paths = original
+ assert {"hf_dataset": "org/calib", "hf_token": "hf_caller"} in checked
+
+
+ "splits, expected",
+ [
+ ({"train": ["t"], "validation": ["v"]}, ["t"]),
+ ({"validation": ["v"]}, ["v"]),
+ ({"test": ["x"]}, ["x"]),
+ (["plain"], ["plain"]),
+ ],
+)
+def test_calibration_dataset_takes_train_or_its_only_split(monkeypatch, splits, expected):
+ import datasets
+ monkeypatch.setattr(datasets, "load_dataset", lambda *a, **k: splits)
+ assert reap_mod._calibration_dataset("org/calib", None) == expected
+
+
+def test_calibration_dataset_with_several_splits_and_no_train_is_refused(monkeypatch):
+ import datasets
+ monkeypatch.setattr(
+ datasets, "load_dataset", lambda *a, **k: {"validation": ["v"], "test": ["x"]}
+ )
+ with pytest.raises(ValueError, match = r"no train split .*\(test, validation\)"):
+ reap_mod._calibration_dataset("org/calib", None)
+
+
+def test_probe_follows_an_adapter_even_beside_a_dense_config(tmp_path):
+ # A LoRA folder may also hold a config.json (dense, stale or the base's); the export loader
+ # follows adapter_config.json, so the probe reads the base it names.
+ base = tmp_path / "moe_base"
+ base.mkdir()
+ (base / "config.json").write_text(json.dumps({"num_experts": 8, "num_experts_per_tok": 2}))
+ lora = tmp_path / "lora"
+ lora.mkdir()
+ (lora / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": str(base)}))
+ (lora / "config.json").write_text(json.dumps({"model_type": "llama", "hidden_size": 64}))
+ info = reap_mod.moe_export_info(str(lora))
+ assert (info["num_experts"], info["top_k"]) == (8, 2)
+
+
+def test_probe_reads_a_folders_own_config_when_its_adapter_names_no_base(tmp_path):
+ folder = tmp_path / "model"
+ folder.mkdir()
+ (folder / "adapter_config.json").write_text("{}")
+ (folder / "config.json").write_text(json.dumps({"num_experts": 8, "num_experts_per_tok": 2}))
+ assert reap_mod.moe_export_info(str(folder))["num_experts"] == 8
+
+
+def test_failed_pruning_drops_the_model_even_when_cleanup_reports_failure(tmp_path, monkeypatch):
+ # cleanup_memory catches its own errors and returns False (e.g. an inference unload failing
+ # first): the merged, partly pruned model must still never be exported again.
+ def reap_prune(model, tokenizer, **kwargs):
+ raise RuntimeError("out of memory in layer 7")
+
+ fake = types.ModuleType("unsloth")
+ fake.FastLanguageModel = types.SimpleNamespace(reap_prune = reap_prune)
+ monkeypatch.setitem(sys.modules, "unsloth", fake)
+ monkeypatch.setattr(reap_mod, "_registry", lambda: tmp_path / "reap_staging.json")
+
+ class _Stuck(_Backend):
+ current_checkpoint = "/ckpt"
+
+ def cleanup_memory(self):
+ return False
+
+ backend = _Stuck(_Model(), is_peft = True)
+ with pytest.raises(RuntimeError, match = "unloaded"):
+ reap_mod.apply_reap(backend, {"sparsity": 0.25}, str(tmp_path))
+ assert backend.current_model is None and backend.current_tokenizer is None
+ assert backend.current_checkpoint is None
+ assert backend._reap_key is None and backend._reap_staging is None
+
+
+def test_reap_merge_marks_the_lora_load_until_the_next_load(fake_reap, tmp_path):
+ backend = _Backend(_Model(), is_peft = True)
+ reap_mod.apply_reap(backend, {"sparsity": 0.25}, str(tmp_path))
+ assert backend.is_peft is False and backend._reap_merged_peft is True
+ # An unload / new load clears it with the staging copy.
+ reap_mod.discard_reap_staging(backend)
+ assert backend._reap_merged_peft is False
+
+
+def test_worker_skips_reap_for_a_base_export_after_a_reap_merge(monkeypatch):
+ from core.export.worker import _handle_export
+
+ applied = []
+ monkeypatch.setattr(reap_mod, "apply_reap", lambda *a, **k: applied.append(a) or (True, ""))
+ monkeypatch.setattr(reap_mod, "sync_reap_report", lambda b, path: None)
+ backend, q = _ExportBackend(), queue.Queue()
+ backend.is_peft, backend._reap_merged_peft = False, True
+ backend.export_base_model = lambda **kwargs: (False, "This is a PEFT model.", None)
+ _handle_export(
+ backend, {"export_type": "base", "save_directory": "/tmp/o", "reap": {"sparsity": 0.5}}, q
+ )
+ assert applied == []
+
+
[email protected]("export_type", ["merged", "base", "gguf"])
+def test_an_export_without_reap_after_a_pruned_one_on_the_same_load_is_refused(export_type):
+ # The loaded weights are the pruned ones now; omitting `reap` means "not pruned".
+ from core.export.worker import _handle_export
+
+ backend, q = _ExportBackend(), queue.Queue()
+ backend._reap_key = (0.25, 512, None)
+ backend.current_model = _Model()
+ backend._reap_model = weakref.ref(backend.current_model)
+ backend.export_base_model = lambda **kwargs: backend.calls.append(("base", kwargs))
+ _handle_export(backend, {"export_type": export_type, "save_directory": "/tmp/o"}, q)
+ assert backend.calls == []
+ final = _drain(q)[-1]
+ assert final["success"] is False and "Load it again" in final["message"]
+
+
[email protected]("strategy, offered", [("mtp", False), ("eagle3", True), (None, True)])
+def test_probe_hides_reap_for_a_full_checkpoint_carrying_a_trained_mtp_head(
+ tmp_path, strategy, offered
+):
+ # The export attaches that head on load, and REAP refuses an attached MTP head.
+ folder = tmp_path / "checkpoint-30"
+ folder.mkdir()
+ (folder / "config.json").write_text(json.dumps({"num_experts": 8, "num_experts_per_tok": 2}))
+ if strategy:
+ (folder / "drafter.json").write_text(json.dumps({"strategy": strategy}))
+ (folder / "eagle3").mkdir()
+ (folder / "eagle3" / "config.json").write_text("{}")
+ assert (reap_mod.moe_export_info(str(folder)) is not None) is offered
+
+
[email protected]("with_head", [True, False])
+def test_probe_hides_reap_for_a_lora_folder_with_a_trained_mtp_head(tmp_path, with_head):
+ # Unsloth's adapter loader re-attaches mtp_head.safetensors, and REAP refuses an attached head.
+ base = tmp_path / "moe_base"
+ base.mkdir()
+ (base / "config.json").write_text(json.dumps({"num_experts": 8, "num_experts_per_tok": 2}))
+ lora = tmp_path / "lora"
+ lora.mkdir()
+ (lora / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": str(base)}))
+ if with_head:
+ (lora / "mtp_head.safetensors").write_bytes(b"head")
+ assert (reap_mod.moe_export_info(str(lora)) is None) is with_head
+
+
+def test_bitsandbytes_is_offered_only_for_hub_ids_unsloth_maps_to_16_bit(tmp_path, monkeypatch):
+ config = {
+ "num_experts": 8,
+ "num_experts_per_tok": 2,
+ "quantization_config": {"quant_method": "bitsandbytes", "load_in_4bit": True},
+ }
+ assert reap_mod.moe_info_from_config(config, bnb_maps_to_16_bit = True)["num_experts"] == 8
+ assert reap_mod.moe_info_from_config(config) is None
+ # A local folder never maps: loading it in 16-bit keeps the packed weights.
+ folder = tmp_path / "Qwen3-30B-A3B-bnb-4bit"
+ folder.mkdir()
+ (folder / "config.json").write_text(json.dumps(config))
+ monkeypatch.setattr(reap_mod, "_maps_to_16_bit", lambda model: True)
+ assert reap_mod.moe_export_info(str(folder)) is None
+
+
+def test_unsloth_mapper_is_read_without_importing_unsloth():
+ import sys
+
+ pytest.importorskip("importlib.util")
+ if __import__("importlib.util").util.find_spec("unsloth") is None:
+ pytest.skip("unsloth is not installed")
+ reap_mod._int_to_float_mapper.cache_clear()
+ already = "unsloth" in sys.modules
+ mapper = reap_mod._int_to_float_mapper()
+ assert any(k.endswith("-bnb-4bit") for k in mapper)
+ assert ("unsloth" in sys.modules) is already
+
+
+def test_moe_info_route_skips_a_hub_lora_with_an_mtp_head(monkeypatch):
+ from routes import export as export_route
+
+ import routes.models as models_route
+
+ # Imported inside the route from routes.models.
+ monkeypatch.setattr(models_route, "_require_model_access_or_caller_token", _async_none)
+ monkeypatch.setattr(
+ reap_mod,
+ "moe_export_info",
+ lambda model, *a, **k: None if model == "org/lora" else {"num_experts": 8, "top_k": 2},
+ )
+ monkeypatch.setattr(reap_mod, "hub_adapter_has_mtp_head", lambda repo, token = None: True)
+ # No network: the repo is not seen as an adapter up front, so the fallback path runs.
+ monkeypatch.setattr(reap_mod, "hub_file_exists", lambda repo, name, token = None: False)
+ import utils.models.model_config as model_config
+
+ monkeypatch.setattr(
+ model_config, "get_base_model_from_lora_identifier", lambda m, t = None: "org/moe-base"
+ )
+ res = asyncio.run(
+ export_route.get_moe_info(
+ model = "org/lora", hf_token = None, current_subject = "t", allow_ambient = False
+ )
+ )
+ assert res.num_experts is None
+ monkeypatch.setattr(reap_mod, "hub_adapter_has_mtp_head", lambda repo, token = None: False)
+ res = asyncio.run(
+ export_route.get_moe_info(
+ model = "org/lora", hf_token = None, current_subject = "t", allow_ambient = False
+ )
+ )
+ assert res.num_experts == 8
+
+
+async def _async_none(*args, **kwargs):
+ return None
+
+
[email protected]("mtp_head", [True, False])
+def test_moe_info_route_probes_a_hub_adapter_through_its_base_even_with_a_config(
+ monkeypatch, mtp_head
+):
+ # A Hub LoRA repo can ship a config.json too; the loader follows adapter_config.json.
+ from routes import export as export_route
+ import routes.models as models_route
+ import utils.models.model_config as model_config
+
+ monkeypatch.setattr(models_route, "_require_model_access_or_caller_token", _async_none)
+ probed = []
+
+ def info(model, *a, **k):
+ probed.append(model)
+ return {"num_experts": 4 if model == "org/lora" else 8, "top_k": 2}
+
+ monkeypatch.setattr(reap_mod, "moe_export_info", info)
+ monkeypatch.setattr(
+ reap_mod,
+ "hub_file_exists",
+ lambda repo, name, token = None: name == "adapter_config.json"
+ or (mtp_head and name == "mtp_head.safetensors"),
+ )
+ monkeypatch.setattr(reap_mod, "hub_adapter_has_mtp_head", lambda repo, token = None: mtp_head)
+ monkeypatch.setattr(
+ model_config, "get_base_model_from_lora_identifier", lambda m, t = None: "org/base"
+ )
+ res = asyncio.run(
+ export_route.get_moe_info(
+ model = "org/lora", hf_token = None, current_subject = "t", allow_ambient = False
+ )
+ )
+ assert "org/lora" not in probed
+ assert res.num_experts == (None if mtp_head else 8)
+
+
+def test_probe_tells_an_unreadable_config_from_a_dense_or_missing_one(tmp_path, monkeypatch):
+ import utils.models.model_config as model_config
+
+ # Read failure (network, Hub 5xx): unknown, raised for the route to report.
+ def flaky(*a, **k):
+ raise OSError("Connection reset by peer")
+
+ monkeypatch.setattr(model_config, "_read_raw_config_json", flaky)
+ with pytest.raises(reap_mod.MoeProbeError, match = "Connection reset"):
+ reap_mod.moe_export_info("org/moe", local_files_only = False)
+ # No config.json at all (a GGUF repo): a definite answer.
+ monkeypatch.setattr(model_config, "_read_raw_config_json", lambda *a, **k: None)
+ assert reap_mod.moe_export_info("org/gguf-only", local_files_only = False) is None
+ # A malformed config.json stays malformed: hidden, not retried.
+ folder = tmp_path / "broken"
+ folder.mkdir()
+ (folder / "config.json").write_text("{not json")
+ monkeypatch.undo()
+ assert reap_mod.moe_export_info(str(folder)) is None
+
+
+def test_moe_info_route_answers_503_when_the_config_cannot_be_read(monkeypatch):
+ # The page then keeps a REAP export blocked with a retry instead of exporting unpruned.
+ from fastapi import HTTPException
+
+ from routes import export as export_route
+ import routes.models as models_route
+
+ monkeypatch.setattr(models_route, "_require_model_access_or_caller_token", _async_none)
+ monkeypatch.setattr(reap_mod, "hub_file_exists", lambda repo, name, token = None: False)
+
+ def unreadable(*a, **k):
+ raise reap_mod.MoeProbeError("Could not read the config of 'org/moe': timeout")
+
+ monkeypatch.setattr(reap_mod, "moe_export_info", unreadable)
+ with pytest.raises(HTTPException) as err:
+ asyncio.run(
+ export_route.get_moe_info(
+ model = "org/moe", hf_token = None, current_subject = "t", allow_ambient = False
+ )
+ )
+ assert err.value.status_code == 503
+
+
+def test_hub_file_checks_tell_a_missing_file_from_an_unknown_one(monkeypatch):
+ import huggingface_hub
+
+ class Api:
+ answer = False
+
+ def __init__(self, token = None):
+ pass
+
+ def file_exists(self, repo, filename):
+ if isinstance(Api.answer, Exception):
+ raise Api.answer
+ return Api.answer
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", Api)
+ # file_exists answers False only for a definite absence.
+ assert reap_mod.hub_file_exists("org/lora", "mtp_head.safetensors") is False
+ Api.answer = True
+ assert reap_mod.hub_adapter_has_mtp_head("org/lora") is True
+ # A timeout or gated repo is unknown: never assumed absent.
+ Api.answer = TimeoutError("read timed out")
+ with pytest.raises(reap_mod.MoeProbeError, match = "timed out"):
+ reap_mod.hub_adapter_has_mtp_head("org/lora")
+
+
+def test_moe_info_route_answers_503_when_the_adapter_check_fails(monkeypatch):
+ from fastapi import HTTPException
+
+ from routes import export as export_route
+ import routes.models as models_route
+
+ monkeypatch.setattr(models_route, "_require_model_access_or_caller_token", _async_none)
+
+ def unknown(
+ repo,
+ name,
+ token = None,
+ ):
+ raise reap_mod.MoeProbeError(f"Could not check '{repo}' for {name}: timeout")
+
+ monkeypatch.setattr(reap_mod, "hub_file_exists", unknown)
+ with pytest.raises(HTTPException) as err:
+ asyncio.run(
+ export_route.get_moe_info(
+ model = "org/lora", hf_token = None, current_subject = "t", allow_ambient = False
+ )
+ )
+ assert err.value.status_code == 503
+
+
+def test_a_reap_key_left_by_an_older_model_is_never_reused(fake_reap, tmp_path):
+ # An unload that failed part way, then a new load: the old settings must not read as
+ # "already pruned" for the unpruned new model.
+ backend = _Backend(_Model())
+ backend._reap_key = (0.25, 512, None)
+ backend._reap_model = weakref.ref(_Model()) # some other, earlier model
+ assert reap_mod.current_reap_key(backend) is None
+ ok, _ = reap_mod.apply_reap(backend, {"sparsity": 0.25}, str(tmp_path))
+ assert ok and len(fake_reap) == 1 # pruned again, this time for the loaded model
+ assert reap_mod.current_reap_key(backend) == (0.25, 512, None)
+ reap_mod.discard_reap_staging(backend)
+
+
+def test_a_stale_reap_key_does_not_refuse_an_unpruned_export(monkeypatch):
+ from core.export.worker import _handle_export
+
+ monkeypatch.setattr(reap_mod, "sync_reap_report", lambda *a, **k: None)
+ backend, q = _ExportBackend(), queue.Queue()
+ backend.current_model = _Model()
+ backend._reap_key = (0.25, 512, None)
+ backend._reap_model = weakref.ref(_Model())
+ _handle_export(backend, {"export_type": "merged", "save_directory": "/tmp/o"}, q)
+ assert backend.calls and backend.calls[0][0] == "merged"
+
+
+def test_hub_file_checks_fall_back_to_the_local_cache(monkeypatch):
+ # Offline (or a failed request), a cached repo still answers from the Hub cache, so a cached
+ # export never needs the network just to show the card.
+ import huggingface_hub
+ from huggingface_hub import constants
+
+ cache = {}
+
+ def from_cache(
+ repo,
+ filename,
+ cache_dir = None,
+ ):
+ return cache.get(filename)
+
+ monkeypatch.setattr(huggingface_hub, "try_to_load_from_cache", from_cache)
+ monkeypatch.setattr(constants, "HF_HUB_OFFLINE", True)
+ cache["mtp_head.safetensors"] = "/cache/snap/mtp_head.safetensors"
+ assert reap_mod.hub_file_exists("org/lora", "mtp_head.safetensors") is True
+ # Offline with the snapshot cached but no such file: the loader cannot fetch it either.
+ cache.clear()
+ cache["config.json"] = "/cache/snap/config.json"
+ assert reap_mod.hub_file_exists("org/moe", "hf_quant_config.json") is False
+ # Nothing cached: still unknown.
+ cache.clear()
+ with pytest.raises(reap_mod.MoeProbeError):
+ reap_mod.hub_file_exists("org/moe", "hf_quant_config.json")
+
+ # Online but the request fails: only a definite cache answer counts (a snapshot alone does not).
+ class Api:
+ def __init__(self, token = None):
+ pass
+
+ def file_exists(self, repo, filename):
+ raise ConnectionError("unreachable")
+
+ monkeypatch.setattr(constants, "HF_HUB_OFFLINE", False)
+ monkeypatch.setattr(huggingface_hub, "HfApi", Api)
+ cache["config.json"] = "/cache/snap/config.json"
+ with pytest.raises(reap_mod.MoeProbeError):
+ reap_mod.hub_file_exists("org/moe", "hf_quant_config.json")
+ cache["hf_quant_config.json"] = "/cache/snap/hf_quant_config.json"
+ assert reap_mod.hub_file_exists("org/moe", "hf_quant_config.json") is True
+
+
+ "tier, default, offered",
+ [
+ ("457", "5.5.0", False),
+ ("default", "4.57.6", False), # Python 3.9: the default tier is transformers 4.57.6
+ ("default", "5.5.0", True),
+ ("530", "4.57.6", True),
+ (RuntimeError("probe failed"), "5.5.0", True), # unknown: Core still refuses clearly
+ ],
+)
+def test_probe_hides_reap_when_the_export_would_run_transformers_4(
+ tmp_path, monkeypatch, tier, default, offered
+):
+ import utils.transformers_version as tv
+
+ folder = tmp_path / "Mixtral-tiny"
+ folder.mkdir()
+ (folder / "config.json").write_text(
+ json.dumps({"num_local_experts": 8, "num_experts_per_tok": 2})
+ )
+
+ def activation_tier(model, token = None):
+ if isinstance(tier, Exception):
+ raise tier
+ return tier
+
+ monkeypatch.setattr(tv, "get_transformers_activation_tier", activation_tier)
+ monkeypatch.setattr(tv, "TRANSFORMERS_DEFAULT_VERSION", default)
+ assert (reap_mod.moe_export_info(str(folder)) is not None) is offered
+
+
+def test_moe_info_route_answers_503_when_a_confirmed_adapters_base_cannot_be_read(monkeypatch):
+ from fastapi import HTTPException
+
+ from routes import export as export_route
+ import routes.models as models_route
+ import utils.models.model_config as model_config
+
+ monkeypatch.setattr(models_route, "_require_model_access_or_caller_token", _async_none)
+ monkeypatch.setattr(
+ reap_mod, "hub_file_exists", lambda repo, name, token = None: name == "adapter_config.json"
+ )
+ # The adapter_config.json download failed after its retries.
+ monkeypatch.setattr(model_config, "get_base_model_from_lora_identifier", lambda m, t = None: None)
+ with pytest.raises(HTTPException) as err:
+ asyncio.run(
+ export_route.get_moe_info(
+ model = "org/lora", hf_token = None, current_subject = "t", allow_ambient = False
+ )
+ )
+ assert err.value.status_code == 503
+
+
+def test_a_stray_mtp_head_file_in_a_full_checkpoint_does_not_hide_reap(tmp_path):
+ # The loader attaches a full checkpoint's head only per its training manifest; a leftover
+ # mtp_head.safetensors next to full weights is never loaded.
+ folder = tmp_path / "full-moe"
+ folder.mkdir()
+ (folder / "config.json").write_text(json.dumps({"num_experts": 8, "num_experts_per_tok": 2}))
+ (folder / "mtp_head.safetensors").write_bytes(b"head")
+ assert reap_mod.moe_export_info(str(folder))["num_experts"] == 8
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index 3c00de86658..f35a91de85a 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -345,8 +345,11 @@ export const BUDGET = {
// The Settings > Chat memory editor (#14357) keeps its strings in the eager English locale and the AGENTS.md
// cache counter in the chat adapter (the section itself is lazy): +989 B raw / +364 B transfer over main
// (6,863,532 -> 6,864,521 B raw, 2,066,692 -> 2,067,056 B transfer at e08466e82, 97 chunks). Raised by that.
- transferBytes: 2_071_574,
- rawBytes: 6_878_779,
+ // REAP on the Export page (#14130) passes its options through the eager export runtime store (the card is
+ // in the lazy export page): +371 B raw / +119 B transfer (6,878,631 -> 6,879,002 B raw, 2,071,507 ->
+ // 2,071,626 B transfer against 4df9ce74f, one machine and build, Node 24, 97 chunks). Raised by that.
+ transferBytes: 2_071_693,
+ rawBytes: 6_879_150,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/features/export/api/export-api.ts b/studio/frontend/src/features/export/api/export-api.ts
index d5030a0d417..6bcbe0faf84 100644
--- a/studio/frontend/src/features/export/api/export-api.ts
+++ b/studio/frontend/src/features/export/api/export-api.ts
@@ -153,6 +153,54 @@ export async function fetchDecisionExportInfo(
return (await fetchCheckpointExportProbe(checkpointPath, signal)).decision;
}
+/** Opt-in REAP expert pruning applied to an MoE model before it is exported. */
+export interface ReapOptions {
+ /** Fraction of the routed experts removed in every MoE layer, e.g. 0.25. */
+ sparsity: number;
+ num_calibration_samples: number;
+ /** Hugging Face dataset id for calibration; the backend default when null. */
+ dataset?: string | null;
+}
+
+export interface MoeInfo {
+ num_experts: number;
+ top_k: number;
+ /** Group-limited routers (DeepSeek style): Core prunes the same number from every group. */
+ n_group?: number | null;
+ topk_group?: number | null;
+}
+
+/** Routed-expert counts for a local folder or Hub id; null for a dense model or when unknown. */
+export async function fetchMoeInfo(
+ model: string,
+ hfToken?: string | null,
+ signal?: AbortSignal,
+): Promise<MoeInfo | null> {
+ // Token in a header (not the query string) so it never lands in URLs/logs.
+ const headers: Record<string, string> = {};
+ if (hfToken) {
+ headers["X-HF-Token"] = hfToken;
+ }
+ const response = await authFetch(
+ `/api/export/moe-info?model=${encodeURIComponent(model)}`,
+ { signal, headers },
+ );
+ const body = await parseJson<{
+ num_experts: number | null;
+ top_k: number | null;
+ n_group?: number | null;
+ topk_group?: number | null;
+ }>(response);
+ return body.num_experts && body.top_k
+ ? {
+ num_experts: body.num_experts,
+ top_k: body.top_k,
+ n_group: body.n_group ?? null,
+ topk_group: body.topk_group ?? null,
+ }
+ : null;
+}
+
export async function fetchCheckpoints(): Promise<CheckpointListResponse> {
const response = await authFetch("/api/models/checkpoints");
return parseJson<CheckpointListResponse>(response);
@@ -207,6 +255,7 @@ export async function exportMerged(params: {
hf_token?: string | null;
private?: boolean;
install_missing_dependencies?: boolean;
+ reap?: ReapOptions | null;
}): Promise<ExportOperationResponse> {
const response = await authFetch("/api/export/export/merged", {
method: "POST",
@@ -223,6 +272,7 @@ export async function exportBase(params: {
hf_token?: string | null;
private?: boolean;
base_model_id?: string | null;
+ reap?: ReapOptions | null;
}): Promise<ExportOperationResponse> {
const response = await authFetch("/api/export/export/base", {
method: "POST",
@@ -244,6 +294,7 @@ export async function exportGGUF(params: {
private?: boolean;
/** Also convert a Q4_0/Q4_1/Q4_K_M GGUF to Q4NX for the AMD NPU, into <save_directory>/npu-q4nx. */
npu_q4nx?: boolean;
+ reap?: ReapOptions | null;
}): Promise<ExportOperationResponse> {
const response = await authFetch("/api/export/export/gguf", {
method: "POST",
diff --git a/studio/frontend/src/features/export/components/export-run-panel.tsx b/studio/frontend/src/features/export/components/export-run-panel.tsx
index 7fb493402e8..6cd53a52b8d 100644
--- a/studio/frontend/src/features/export/components/export-run-panel.tsx
+++ b/studio/frontend/src/features/export/components/export-run-panel.tsx
@@ -122,6 +122,8 @@ export interface ExportRunPanelProps {
onClose: () => void;
/** Decision model: output goes to the run folder's gguf/ only; this note replaces the destination picker. */
decisionNote?: string;
+ /** REAP expert pruning on this export, e.g. "25% of experts removed (96 of 128 kept)"; hidden when null. */
+ reapLabel?: string | null;
}
export function ExportRunPanel(props: ExportRunPanelProps) {
@@ -139,6 +141,7 @@ export function ExportRunPanel(props: ExportRunPanelProps) {
saveDirectoryOverridden,
onSaveDirectoryChange,
decisionNote,
+ reapLabel,
hfUsername,
onHfUsernameChange,
modelName,
@@ -218,6 +221,7 @@ export function ExportRunPanel(props: ExportRunPanelProps) {
const summaryFormats = (summary?.mergedFormats ?? []).map(
(v) => findMergedFormat(v)?.label ?? v,
);
+ const summaryReap = summary ? (summary.reapLabel ?? null) : (reapLabel ?? null);
const showProgress = isExporting || isTerminal;
const hubRepoMissing =
destination === "hub" &&
@@ -521,6 +525,14 @@ export function ExportRunPanel(props: ExportRunPanelProps) {
</span>
</div>
)}
+ {summaryReap && (
+ <div className="flex justify-between gap-3">
+ <span>Expert pruning</span>
+ <span className="font-medium text-foreground text-right">
+ REAP, {summaryReap}
+ </span>
+ </div>
+ )}
</div>
{/* Progress */}
diff --git a/studio/frontend/src/features/export/components/reap-card.tsx b/studio/frontend/src/features/export/components/reap-card.tsx
new file mode 100644
index 00000000000..738d11acde0
--- /dev/null
+++ b/studio/frontend/src/features/export/components/reap-card.tsx
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Switch } from "@/components/ui/switch";
+import type { MoeInfo } from "../api/export-api";
+import {
+ REAP_SAMPLES,
+ REAP_SPARSITIES,
+ type ReapSettings,
+ reapEffectiveSparsity,
+ reapKeptExperts,
+ reapSparsityAllowed,
+} from "../lib/reap";
+
+export function ReapCard({
+ moe,
+ settings,
+ onChange,
+ disabled,
+}: {
+ moe: MoeInfo;
+ settings: ReapSettings;
+ onChange: (next: ReapSettings) => void;
+ disabled?: boolean;
+}) {
+ const sparsity = reapEffectiveSparsity(settings, moe) ?? settings.sparsity;
+ const kept = reapKeptExperts(moe, sparsity);
+ const set = (patch: Partial<ReapSettings>) =>
+ onChange({ ...settings, ...patch });
+ return (
+ <div className="space-y-3 rounded-lg border p-3">
+ <div className="flex items-center justify-between gap-3">
+ <div className="space-y-0.5">
+ <div className="text-sm font-medium">Prune experts (REAP)</div>
+ <div className="text-xs text-muted-foreground">
+ This model routes each token to {moe.top_k} of {moe.num_experts}{" "}
+ experts. REAP scores every expert on calibration chats and removes
+ the least used ones, for a smaller model that needs less memory.
+ </div>
+ </div>
+ <Switch
+ aria-label="Prune experts (REAP)"
+ checked={settings.enabled}
+ onCheckedChange={(enabled) => set({ enabled })}
+ disabled={disabled}
+ />
+ </div>
+ {settings.enabled && (
+ <div className="space-y-3">
+ <div className="space-y-1.5">
+ <div className="text-sm font-medium">Experts to remove</div>
+ <div className="flex flex-wrap gap-2">
+ {REAP_SPARSITIES.map((s) => (
+ <Button
+ key={s}
+ type="button"
+ size="sm"
+ variant={sparsity === s ? "default" : "outline"}
+ onClick={() => set({ sparsity: s })}
+ disabled={disabled || !reapSparsityAllowed(moe, s)}
+ title={
+ reapSparsityAllowed(moe, s)
+ ? undefined
+ : `Would keep fewer than the ${moe.top_k} experts each token is routed to`
+ }
+ >
+ {Math.round(s * 100)}%
+ </Button>
+ ))}
+ </div>
+ <div className="text-xs text-muted-foreground">
+ Keeps {kept} of {moe.num_experts} experts in every MoE layer.
+ Quality drops more the more you remove; 25% is the safer start.
+ </div>
+ </div>
+ <div className="space-y-1.5">
+ <div className="text-sm font-medium">Calibration</div>
+ <div className="flex flex-wrap gap-2">
+ {REAP_SAMPLES.map((o) => (
+ <Button
+ key={o.value}
+ type="button"
+ size="sm"
+ variant={settings.samples === o.value ? "default" : "outline"}
+ onClick={() => set({ samples: o.value })}
+ title={o.hint}
+ disabled={disabled}
+ >
+ {o.label}
+ </Button>
+ ))}
+ </div>
+ <Input
+ aria-label="Calibration dataset"
+ placeholder="mlabonne/open-perfectblend (default)"
+ value={settings.dataset}
+ onChange={(e) => set({ dataset: e.target.value })}
+ disabled={disabled}
+ />
+ <div className="text-xs text-muted-foreground">
+ Optional Hugging Face dataset with chat or text rows. Use data
+ like what the model will see, for example your training set.
+ </div>
+ </div>
+ <div className="text-xs text-muted-foreground">
+ The model is loaded in 16-bit to score the experts, so this needs
+ more memory than a 4-bit export. Your checkpoint is not changed; the
+ export folder gets a reap_report.json listing the kept experts.
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/export/export-page.tsx b/studio/frontend/src/features/export/export-page.tsx
index eb5763a5f6e..3a0c8785898 100644
--- a/studio/frontend/src/features/export/export-page.tsx
+++ b/studio/frontend/src/features/export/export-page.tsx
@@ -69,7 +69,9 @@ import {
type DecisionExportInfo,
type DiffusionLmExportInfo,
type ModelCheckpoints,
+ type MoeInfo,
fetchCheckpointExportProbe,
+ fetchMoeInfo,
} from "./api/export-api";
import { adapterCompatibilityTip, type AdapterFormat } from "./constants";
import { ExportRunPanel } from "./components/export-run-panel";
@@ -77,6 +79,7 @@ import { ImageLoraExportCard } from "./components/image-lora-export-card";
import { MethodPicker } from "./components/method-picker";
import { Q4nxConvertCard } from "./components/q4nx-convert-card";
import { QuantPicker } from "./components/quant-picker";
+import { ReapCard } from "./components/reap-card";
import {
EXPORT_METHODS,
type ExportMethod,
@@ -97,6 +100,16 @@ import {
} from "./export-navigation-cache";
import { confirmLlmCompressorInstallIfNeeded } from "./hooks/use-llm-compressor-consent";
import { useExportSizeEstimate } from "./hooks/use-export-size-estimate";
+import {
+ DEFAULT_REAP_SETTINGS,
+ type ReapSettings,
+ reapAllowedSparsities,
+ reapProbeFailed,
+ reapProbePending,
+ reapUnavailable,
+ reapRequest,
+ reapSummaryLabel,
+} from "./lib/reap";
import { saveDirectoryField } from "./lib/save-directory";
import { exportUnsupportedText } from "./lib/unsupported-text";
import {
@@ -229,6 +242,9 @@ export function ExportPage() {
// GGUF importance matrix (required for the IQ quants) and merged-export precision.
const [useImatrix, setUseImatrix] = useState(false);
const [npuQ4nx, setNpuQ4nx] = useState(false);
+ const [reapSettings, setReapSettings] = useState<ReapSettings>(
+ DEFAULT_REAP_SETTINGS,
+ );
const [customImatrix, setCustomImatrix] = useState({ sourceKey: "", path: "" });
// Merged precision: one or more MERGED_FORMATS values exported in one run; seeded like exportMethod.
const [selectedFormats, setSelectedFormats] = useState<string[]>(() => {
@@ -590,6 +606,36 @@ export function ExportPage() {
);
const decisionExistingQuants =
decisionInfo?.existing_export?.quantizations ?? [];
+ // REAP is offered only for routed-MoE models: a local checkpoint / model folder, or a Hub id.
+ const moeProbeTarget =
+ decisionProbePath ??
+ (sourceMode !== "checkpoint" && modelSource === "hf"
+ ? selectedSourceModel || null
+ : null);
+ const moeProbeToken = debouncedHfToken?.trim() || "";
+ const moeProbeKey = moeProbeTarget ? `${moeProbeTarget}|${moeProbeToken}` : "";
+ const [moeState, setMoeState] = useState<{
+ key: string;
+ info: MoeInfo | null;
+ failed?: boolean;
+ } | null>(null);
+ const [moeRetry, setMoeRetry] = useState(0);
+ useEffect(() => {
+ if (!moeProbeTarget) return;
+ const controller = new AbortController();
+ fetchMoeInfo(moeProbeTarget, moeProbeToken || null, controller.signal)
+ .then((info) => {
+ if (!controller.signal.aborted) setMoeState({ key: moeProbeKey, info });
+ })
+ .catch(() => {
+ // A dense or unreadable config answers null; a thrown request is not an answer.
+ if (!controller.signal.aborted)
+ setMoeState({ key: moeProbeKey, info: null, failed: true });
+ });
+ return () => controller.abort();
+ }, [moeProbeKey, moeProbeTarget, moeProbeToken, moeRetry]);
+ const moeInfo =
+ moeProbeKey && moeState?.key === moeProbeKey ? moeState.info : null;
const localResultIds = useMemo(() => {
const ids = exportableLocalModels.map((model) => model.id);
@@ -778,6 +824,42 @@ export function ExportPage() {
effectiveIsAdapter &&
!isMacHost;
+ // REAP prunes the full model before a merged or full-model GGUF export (torch backends only).
+ const reapMethodApplies =
+ !isMacHost &&
+ !isDecision &&
+ !exportUnsupported &&
+ !!exportMethod &&
+ !diffusionDisabledMethods.includes(exportMethod) &&
+ (exportMethod === "merged" || (exportMethod === "gguf" && !ggufAsLora));
+ const showReap =
+ !!moeInfo && reapAllowedSparsities(moeInfo).length > 0 && reapMethodApplies;
+ // With REAP on, a merged / full-model GGUF export started before the new source's probe
+ // answers would go out unpruned. Other methods never send REAP, so they never wait.
+ const reapPending =
+ reapMethodApplies &&
+ reapProbePending(reapSettings, moeProbeKey, moeState?.key);
+ const reapFailed =
+ reapMethodApplies &&
+ reapProbeFailed(
+ reapSettings,
+ moeProbeKey,
+ moeState?.failed ? moeState.key : null,
+ );
+ const reapBlocked =
+ reapMethodApplies &&
+ reapUnavailable(
+ reapSettings,
+ moeProbeKey,
+ moeState?.key,
+ !!moeState?.failed,
+ showReap,
+ );
+ const reapOptions =
+ showReap && moeInfo ? reapRequest(reapSettings, moeInfo) : null;
+ const reapLabel =
+ showReap && moeInfo ? reapSummaryLabel(reapSettings, moeInfo) : null;
+
// Restrict a Hub merged export to a single format; multi-format stays available for local export.
const hubMultiFormat =
destination === "hub" &&
@@ -792,7 +874,10 @@ export function ExportPage() {
!hubMultiFormat &&
(exportMethod !== "gguf" || ggufAsLora || quantLevels.length > 0) &&
(exportMethod !== "merged" || selectedFormats.length > 0) &&
- (!isDecision || (exportMethod === "gguf" && !decisionIneligible))
+ (!isDecision || (exportMethod === "gguf" && !decisionIneligible)) &&
+ !reapPending &&
+ !reapFailed &&
+ !reapBlocked
);
const applyHfSourceModel = useCallback((value: string) => {
@@ -867,6 +952,8 @@ export function ExportPage() {
// No supported accelerator (or PyTorch/MLX missing): the backend would reject anyway; don't submit.
if (exportUnsupported) return;
if (diffusionDisabledMethods.includes(exportMethod)) return;
+ // REAP is on but the new source's MoE probe has not answered (or failed): never send it unpruned.
+ if (reapPending || reapFailed || reapBlocked) return;
// GGUF with no quant, or merged with no format, would run an empty export; require at least one.
if (exportMethod === "gguf" && !ggufAsLora && quantLevels.length === 0)
return;
@@ -971,6 +1058,7 @@ export function ExportPage() {
privateRepo,
installMissingDependencies,
baseModelId: selectedModelData?.base_model ?? undefined,
+ reap: reapOptions,
summary: {
baseModelName: sourceBaseModelName,
checkpointLabel: selectedExportSource,
@@ -979,9 +1067,15 @@ export function ExportPage() {
quantLevels,
mergedFormats: exportMethod === "merged" ? selectedFormats : [],
destination,
+ reapLabel,
},
});
}, [
+ reapPending,
+ reapFailed,
+ reapBlocked,
+ reapOptions,
+ reapLabel,
checkpoint,
checkpointsForModel,
sourceMode,
@@ -2019,6 +2113,70 @@ export function ExportPage() {
)}
</div>
)}
+ {showReap && moeInfo && (
+ <ReapCard
+ moe={moeInfo}
+ settings={reapSettings}
+ onChange={setReapSettings}
+ disabled={isExporting}
+ />
+ )}
+ {reapFailed && (
+ <div
+ role="alert"
+ className="rounded-lg border border-amber-500/40 bg-amber-500/5 p-3 text-xs"
+ >
+ <p>
+ Expert pruning (REAP) is on, but checking whether this model
+ can be pruned failed. Retry, or turn pruning off to export
+ the full model.
+ </p>
+ <div className="mt-2 flex gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setMoeRetry((n) => n + 1)}
+ >
+ Retry
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() =>
+ setReapSettings((s) => ({ ...s, enabled: false }))
+ }
+ >
+ Turn off expert pruning
+ </Button>
+ </div>
+ </div>
+ )}
+ {reapBlocked && (
+ <div
+ role="alert"
+ className="rounded-lg border border-amber-500/40 bg-amber-500/5 p-3 text-xs"
+ >
+ <p>
+ Expert pruning (REAP) is on, but this model cannot be
+ pruned: it is not a routed MoE, or its weights or setup are
+ not supported. Turn pruning off to export it.
+ </p>
+ <div className="mt-2 flex gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ setReapSettings((s) => ({ ...s, enabled: false }))
+ }
+ >
+ Turn off expert pruning
+ </Button>
+ </div>
+ </div>
+ )}
{estimatedSize && (
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
<HugeiconsIcon
@@ -2061,6 +2219,7 @@ export function ExportPage() {
})
: undefined
}
+ reapLabel={reapLabel}
/>
)}
{showPanel && (
diff --git a/studio/frontend/src/features/export/lib/reap.ts b/studio/frontend/src/features/export/lib/reap.ts
new file mode 100644
index 00000000000..b590f5b3052
--- /dev/null
+++ b/studio/frontend/src/features/export/lib/reap.ts
@@ -0,0 +1,149 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { MoeInfo, ReapOptions } from "../api/export-api";
+
+export const REAP_SPARSITIES = [0.25, 0.5] as const;
+export const REAP_SAMPLES = [
+ { value: 128, label: "Quick", hint: "128 samples" },
+ { value: 512, label: "Standard", hint: "512 samples, recommended" },
+] as const;
+
+export interface ReapSettings {
+ enabled: boolean;
+ sparsity: number;
+ samples: number;
+ dataset: string;
+}
+
+export const DEFAULT_REAP_SETTINGS: ReapSettings = {
+ enabled: false,
+ sparsity: 0.25,
+ samples: 512,
+ dataset: "",
+};
+
+/** Python's round(): halves go to the even neighbour. */
+function roundHalfEven(x: number): number {
+ const floor = Math.floor(x);
+ const diff = x - floor;
+ if (diff !== 0.5) return Math.round(x);
+ return floor % 2 === 0 ? floor : floor + 1;
+}
+
+/** Core's plan for one sparsity (unsloth/models/reap.py): experts dropped, and whether it runs. */
+function reapPlan(
+ moe: MoeInfo,
+ sparsity: number,
+): { dropped: number; allowed: boolean } {
+ const experts = moe.num_experts;
+ let dropped = Math.floor(experts * sparsity);
+ if (dropped === 0) return { dropped, allowed: false };
+ let reachable = experts - dropped;
+ const groups = moe.n_group ?? 0;
+ const topkGroup = moe.topk_group ?? 0;
+ if (groups > 0 && topkGroup > 0) {
+ // Group-limited routing drops the same number from every group.
+ if (experts % groups !== 0) return { dropped, allowed: false };
+ const perGroup = roundHalfEven(dropped / groups);
+ const groupSize = experts / groups;
+ dropped = perGroup * groups;
+ if (perGroup === 0 || groupSize - perGroup < 2) {
+ return { dropped, allowed: false };
+ }
+ reachable = topkGroup * (groupSize - perGroup);
+ }
+ return { dropped, allowed: moe.top_k <= reachable };
+}
+
+/** Experts kept per MoE layer, as Core computes it. */
+export function reapKeptExperts(moe: MoeInfo, sparsity: number): number {
+ return moe.num_experts - reapPlan(moe, sparsity).dropped;
+}
+
+/** Core refuses a sparsity that drops no expert or leaves fewer experts than the router reaches. */
+export function reapSparsityAllowed(moe: MoeInfo, sparsity: number): boolean {
+ return reapPlan(moe, sparsity).allowed;
+}
+
+export function reapAllowedSparsities(moe: MoeInfo): number[] {
+ return REAP_SPARSITIES.filter((s) => reapSparsityAllowed(moe, s));
+}
+
+/** The chosen sparsity, or the first allowed one when the model changed under it. */
+export function reapEffectiveSparsity(
+ settings: ReapSettings,
+ moe: MoeInfo,
+): number | null {
+ const allowed = reapAllowedSparsities(moe);
+ return allowed.includes(settings.sparsity)
+ ? settings.sparsity
+ : (allowed[0] ?? null);
+}
+
+/** The request block for an enabled setting, else null (REAP stays off). */
+export function reapRequest(
+ settings: ReapSettings,
+ moe: MoeInfo,
+): ReapOptions | null {
+ const sparsity = reapEffectiveSparsity(settings, moe);
+ if (!settings.enabled || sparsity === null) return null;
+ const dataset = settings.dataset.trim();
+ return {
+ sparsity,
+ num_calibration_samples: settings.samples,
+ dataset: dataset || null,
+ };
+}
+
+export function reapSummaryLabel(
+ settings: ReapSettings,
+ moe: MoeInfo,
+): string | null {
+ const sparsity = reapEffectiveSparsity(settings, moe);
+ if (!settings.enabled || sparsity === null) return null;
+ const kept = reapKeptExperts(moe, sparsity);
+ // From the experts Core actually drops: grouped routers round per group (12 in 4 groups at 25%
+ // drops 4, i.e. 33%).
+ const removed = Math.round(((moe.num_experts - kept) / moe.num_experts) * 100);
+ return `${removed}% of experts removed (${kept} of ${moe.num_experts} kept)`;
+}
+
+/** REAP is on and the probe for the current source has not answered yet: an export started now
+ * would go out unpruned, so the page blocks it until the answer arrives. */
+/** REAP is on but this source's MoE probe failed (network / server error, not a dense answer): the
+ * export waits for a retry or for REAP to be turned off, instead of going out unpruned. */
+export function reapProbeFailed(
+ settings: ReapSettings,
+ probeKey: string,
+ failedKey: string | null | undefined,
+): boolean {
+ return settings.enabled && !!probeKey && failedKey === probeKey;
+}
+
+/** REAP is on, but the probe for this source answered that it cannot be pruned (dense, packed
+ * weights, a transformers 4 load, ...): the export waits for the user to turn REAP off rather than
+ * quietly dropping the opt-in. */
+export function reapUnavailable(
+ settings: ReapSettings,
+ probeKey: string,
+ answeredKey: string | null | undefined,
+ probeFailed: boolean,
+ available: boolean,
+): boolean {
+ return (
+ settings.enabled &&
+ !!probeKey &&
+ answeredKey === probeKey &&
+ !probeFailed &&
+ !available
+ );
+}
+
+export function reapProbePending(
+ settings: ReapSettings,
+ probeKey: string,
+ answeredKey: string | null | undefined,
+): boolean {
+ return settings.enabled && !!probeKey && answeredKey !== probeKey;
+}
diff --git a/studio/frontend/src/features/export/stores/export-runtime-store.ts b/studio/frontend/src/features/export/stores/export-runtime-store.ts
index f144bb85c15..997efd530bd 100644
--- a/studio/frontend/src/features/export/stores/export-runtime-store.ts
+++ b/studio/frontend/src/features/export/stores/export-runtime-store.ts
@@ -16,6 +16,7 @@ import {
type ExportLogPollEntry,
type ExportOperationResponse,
type ExportStatus,
+ type ReapOptions,
} from "../api/export-api";
import type { ExportMethod } from "../constants";
@@ -145,6 +146,8 @@ export interface ExportRunSummary {
/** Merged: the selected format values (for the summary "Formats" row and to reseed the picker). */
mergedFormats: string[];
destination: ExportDestination;
+ /** REAP expert pruning applied before the export, e.g. "25% of experts removed", else null. */
+ reapLabel?: string | null;
}
/** Everything `runExport` needs to drive the load -> export -> cleanup sequence. */
@@ -186,6 +189,8 @@ export interface RunExportParams {
privateRepo: boolean;
baseModelId?: string | null;
installMissingDependencies?: boolean;
+ /** Prune MoE experts with REAP before exporting; loads the model in 16-bit. Off when null. */
+ reap?: ReapOptions | null;
/** Decision model (Clef / Laya): labels the run folder's gguf/ output with the quants it holds. */
decisionOutputLabel?: (quantizations: string[]) => string;
summary: ExportRunSummary;
@@ -473,6 +478,8 @@ export const useExportRuntimeStore = create<ExportRuntimeStore>()((set, get) =>
loadCheckpoint({
checkpoint_path: checkpointPath,
hf_token: params.loadToken ?? null,
+ // REAP scores and slices 16-bit expert weights.
+ ...(params.reap ? { load_in_4bit: false } : {}),
}),
);
} else {
@@ -518,6 +525,7 @@ export const useExportRuntimeStore = create<ExportRuntimeStore>()((set, get) =>
install_missing_dependencies: Boolean(
params.installMissingDependencies,
),
+ reap: params.reap ?? null,
}),
);
if (outputPath) outputs.push({ label: sel.label, path: outputPath });
@@ -543,6 +551,7 @@ export const useExportRuntimeStore = create<ExportRuntimeStore>()((set, get) =>
: null,
private: params.privateRepo,
npu_q4nx: params.npuQ4nx,
+ reap: params.reap ?? null,
}),
);
if (outputPath) {
diff --git a/studio/frontend/tests/export-reap-options.test.ts b/studio/frontend/tests/export-reap-options.test.ts
new file mode 100644
index 00000000000..152d597f775
--- /dev/null
+++ b/studio/frontend/tests/export-reap-options.test.ts
@@ -0,0 +1,117 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ DEFAULT_REAP_SETTINGS,
+ reapAllowedSparsities,
+ reapKeptExperts,
+ reapProbeFailed,
+ reapProbePending,
+ reapUnavailable,
+ reapRequest,
+ reapSummaryLabel,
+} from "../src/features/export/lib/reap.ts";
+
+const QWEN3_30B = { num_experts: 128, top_k: 8 };
+
+test("REAP is off by default and sends nothing", () => {
+ assert.equal(DEFAULT_REAP_SETTINGS.enabled, false);
+ assert.equal(reapRequest(DEFAULT_REAP_SETTINGS, QWEN3_30B), null);
+ assert.equal(reapSummaryLabel(DEFAULT_REAP_SETTINGS, QWEN3_30B), null);
+});
+
+test("an enabled setting sends sparsity, samples and a trimmed dataset", () => {
+ const on = { ...DEFAULT_REAP_SETTINGS, enabled: true, dataset: " " };
+ assert.deepEqual(reapRequest(on, QWEN3_30B), {
+ sparsity: 0.25,
+ num_calibration_samples: 512,
+ dataset: null,
+ });
+ assert.equal(
+ reapRequest({ ...on, dataset: " org/data " }, QWEN3_30B)?.dataset,
+ "org/data",
+ );
+ assert.equal(
+ reapSummaryLabel({ ...on, sparsity: 0.5 }, QWEN3_30B),
+ "50% of experts removed (64 of 128 kept)",
+ );
+});
+
+test("kept experts match Core's int(E * sparsity) drop", () => {
+ assert.equal(reapKeptExperts({ num_experts: 60, top_k: 4 }, 0.25), 45);
+ assert.equal(reapKeptExperts({ num_experts: 7, top_k: 2 }, 0.5), 4);
+});
+
+test("a sparsity Core would refuse is not offered or sent", () => {
+ // 4 experts, top-3: 50% would keep 2 < 3; 25% keeps 3.
+ const small = { num_experts: 4, top_k: 3 };
+ assert.deepEqual(reapAllowedSparsities(small), [0.25]);
+ const chose50 = { ...DEFAULT_REAP_SETTINGS, enabled: true, sparsity: 0.5 };
+ assert.equal(reapRequest(chose50, small)?.sparsity, 0.25);
+ // 3 experts, top-2: 25% drops none, 50% keeps 2.
+ assert.deepEqual(reapAllowedSparsities({ num_experts: 3, top_k: 2 }), [0.5]);
+ // Nothing valid: the card is hidden and no request goes out.
+ const none = { num_experts: 2, top_k: 2 };
+ assert.deepEqual(reapAllowedSparsities(none), []);
+ assert.equal(reapRequest(chose50, none), null);
+});
+
+test("group-limited routers count like Core: per group, at least 2 left in each", () => {
+ // DeepSeek-V3: 256 experts, 8 groups, top-8 over 4 groups.
+ const dsv3 = { num_experts: 256, top_k: 8, n_group: 8, topk_group: 4 };
+ assert.deepEqual(reapAllowedSparsities(dsv3), [0.25, 0.5]);
+ assert.equal(reapKeptExperts(dsv3, 0.25), 192);
+ // 8 experts in 4 groups: 50% would leave 1 per group, which Core refuses.
+ const tiny = { num_experts: 8, top_k: 2, n_group: 4, topk_group: 2 };
+ assert.deepEqual(reapAllowedSparsities(tiny), []);
+ // 12 experts in 4 groups at 25%: int(3) dropped, round(0.75) = 1 per group, 4 in total.
+ const odd = { num_experts: 12, top_k: 2, n_group: 4, topk_group: 2 };
+ assert.equal(reapKeptExperts(odd, 0.25), 8);
+ // 20 experts in 4 groups at 50%: 10 dropped, round(2.5) = 2 per group (half to even), 8 in total.
+ const half = { num_experts: 20, top_k: 2, n_group: 4, topk_group: 2 };
+ assert.equal(reapKeptExperts(half, 0.5), 12);
+});
+
+test("the summary reports what Core removes, not the requested fraction", () => {
+ const odd = { num_experts: 12, top_k: 2, n_group: 4, topk_group: 2 };
+ const on = { ...DEFAULT_REAP_SETTINGS, enabled: true, sparsity: 0.25 };
+ assert.equal(reapSummaryLabel(on, odd), "33% of experts removed (8 of 12 kept)");
+ assert.equal(
+ reapSummaryLabel(on, { num_experts: 128, top_k: 8 }),
+ "25% of experts removed (96 of 128 kept)",
+ );
+});
+
+test("an export waits while REAP is on and the new source has not been probed", () => {
+ const on = { ...DEFAULT_REAP_SETTINGS, enabled: true };
+ assert.equal(reapProbePending(on, "org/moe|", null), true);
+ assert.equal(reapProbePending(on, "org/moe|", "org/old|"), true);
+ assert.equal(reapProbePending(on, "org/moe|", "org/moe|"), false);
+ // REAP off, or no source selected: nothing to wait for.
+ assert.equal(reapProbePending(DEFAULT_REAP_SETTINGS, "org/moe|", null), false);
+ assert.equal(reapProbePending(on, "", null), false);
+});
+
+test("a failed MoE probe keeps a REAP export blocked until a retry answers or REAP is off", () => {
+ const on = { ...DEFAULT_REAP_SETTINGS, enabled: true };
+ assert.equal(reapProbeFailed(on, "org/moe|", "org/moe|"), true);
+ // An answer (dense or MoE) for this source, or a failure for an older one, does not block.
+ assert.equal(reapProbeFailed(on, "org/moe|", null), false);
+ assert.equal(reapProbeFailed(on, "org/moe|", "org/old|"), false);
+ // Turned off: the full model exports.
+ assert.equal(reapProbeFailed(DEFAULT_REAP_SETTINGS, "org/moe|", "org/moe|"), false);
+});
+
+test("a source the probe confirms cannot be pruned keeps a REAP export blocked until REAP is off", () => {
+ const on = { ...DEFAULT_REAP_SETTINGS, enabled: true };
+ // Answered for this source, not failed, no usable REAP options: blocked.
+ assert.equal(reapUnavailable(on, "org/fp8-moe|", "org/fp8-moe|", false, false), true);
+ // Available, still being probed, failed (handled by its own notice), or REAP off: not this gate.
+ assert.equal(reapUnavailable(on, "org/moe|", "org/moe|", false, true), false);
+ assert.equal(reapUnavailable(on, "org/fp8-moe|", "org/old|", false, false), false);
+ assert.equal(reapUnavailable(on, "org/fp8-moe|", "org/fp8-moe|", true, false), false);
+ assert.equal(reapUnavailable(DEFAULT_REAP_SETTINGS, "org/fp8-moe|", "org/fp8-moe|", false, false), false);
+});