Skip to content

Personal AI, On Personal Devices

Python

feat(mining): validate Gemma E4B and Qwen 3.6 Pearl artifacts (#328)

Avanika Narayanb8c3b417ec10
diff --git a/docs/development/pearl-model-enablement.md b/docs/development/pearl-model-enablement.md
index 96ae302d..f9fa0040 100644
--- a/docs/development/pearl-model-enablement.md
+++ b/docs/development/pearl-model-enablement.md
@@ -8,22 +8,19 @@ not enough. The Pearl vLLM plugin expects a Pearl-compatible quantized model
whose metadata marks mining layers for 7-bit NoisyGEMM and non-mining layers
for the vanilla Pearl GEMM path.
-## Target Models
+## Supported Models
-| Raw model | Planned Pearl model | Status | Tracking |
-|---|---|---|---|
-| `Qwen/Qwen3.5-9B` | `ScalingIntelligence/Qwen3.5-9B-pearl` | Validated staging | [#316](https://github.com/open-jarvis/OpenJarvis/issues/316) |
-| `Qwen/Qwen3.6-27B` | `pearl-ai/Qwen3.6-27B-pearl` | Planned | [#317](https://github.com/open-jarvis/OpenJarvis/issues/317) |
-| `google/gemma-4-E4B-it` | `pearl-ai/Gemma-4-E4B-it-pearl` | Planned | [#318](https://github.com/open-jarvis/OpenJarvis/issues/318) |
-| `google/gemma-4-31B-it` | `ScalingIntelligence/Gemma-4-31B-it-pearl` | Validated staging | [#319](https://github.com/open-jarvis/OpenJarvis/issues/319) |
+OpenJarvis only supports Pearl models published by the `pearl-ai` Hugging Face
+organization. Private staging artifacts and OpenJarvis-specific conversion
+repos are not user-facing supported mining models.
-The current validated models are:
+The current public support set is:
-```text
-pearl-ai/Llama-3.3-70B-Instruct-pearl
-ScalingIntelligence/Gemma-4-31B-it-pearl
-ScalingIntelligence/Qwen3.5-9B-pearl
-```
+| Raw model | Pearl model | Status |
+|---|---|---|
+| `meta-llama/Llama-3.3-70B-Instruct` | `pearl-ai/Llama-3.3-70B-Instruct-pearl` | Validated default |
+| `google/gemma-4-31B-it` | `pearl-ai/Gemma-4-31B-it-pearl` | Planned until H100/H200 validation passes |
+| `meta-llama/Llama-3.1-8B-Instruct` | `pearl-ai/Llama-3.1-8B-Instruct-pearl` | Planned until H100/H200 validation passes |
## Current Validation Findings
@@ -31,49 +28,10 @@ The H100 smoke run validated the default Llama Pearl model end to end through
`jarvis mine start`, vLLM `/v1/models`, OpenJarvis inference routing, Pearl
gateway template refresh, and `jarvis mine validate-model`.
-The remaining Qwen 3.6 and smaller Gemma target remain planned:
-
-- `pearl-ai/Qwen3.6-27B-pearl` and `pearl-ai/Gemma-4-E4B-it-pearl` are not
- publicly available artifacts yet.
-- `pearl-ai/Gemma-4-31B-it-pearl` exists and selects Pearl mining kernels on
- H100, but vLLM fails during Gemma4 multimodal profiling because the published
- artifact is missing processor/preprocessor metadata required by Transformers.
- A local cache experiment proved the processor can be loaded only after
- injecting metadata from `google/gemma-4-31B-it`; that is not sufficient for
- OpenJarvis promotion because a clean user install would still fail.
-
-PR #323 added a local staging path for original checkpoint conversion and H100
-runtime validation. The validated staging artifacts are private repositories in
-the `ScalingIntelligence` Hugging Face org and grouped in the
-`OpenJarvis Pearl Mining Models` collection. Users need Hugging Face access to
-the org/repositories before `jarvis mine inspect-model`, `jarvis mine init`, or
-`jarvis mine start` can fetch them:
-
-- `ScalingIntelligence/Gemma-4-31B-it-pearl`
-- `ScalingIntelligence/Qwen3.5-9B-pearl`
-
-Current validation evidence:
-
-- `google/gemma-4-31B-it` converted to
- `/tmp/openjarvis-h100/converted/Gemma-4-31B-it-pearl-experimental`.
- The local artifact passes `jarvis mine inspect-model`, starts through
- `jarvis mine start --local-model-path`, exposes
- `pearl-ai/Gemma-4-31B-it-pearl` at `/v1/models`, completes a chat prompt,
- and passes `jarvis mine validate-model --allow-planned`. Validation artifact:
- `/tmp/openjarvis-h100/converted/Gemma-4-31B-it-pearl-experimental-validate.json`.
- The published `ScalingIntelligence/Gemma-4-31B-it-pearl` repo includes the
- same validation artifact as `openjarvis_validation.json`.
-- `Qwen/Qwen3.5-9B` converted to
- `/tmp/openjarvis-h100/converted/Qwen3.5-9B-pearl-experimental`.
- The local artifact passes `jarvis mine inspect-model`, starts Pearl gateway,
- resolves `Qwen3_5ForConditionalGeneration`, selects Pearl kernels, loads all
- four safetensors shards, exposes `pearl-ai/Qwen3.5-9B-pearl` at `/v1/models`,
- completes a chat prompt, and passes `jarvis mine validate-model
- --allow-planned`. Required validation flags: `--gdn-prefill-backend triton`
- and a 4096-token context. Validation artifact:
- `/tmp/openjarvis-h100/converted/Qwen3.5-9B-pearl-experimental-validate.json`.
- The published `ScalingIntelligence/Qwen3.5-9B-pearl` repo includes the same
- validation artifact as `openjarvis_validation.json`.
+`pearl-ai/Gemma-4-31B-it-pearl` and
+`pearl-ai/Llama-3.1-8B-Instruct-pearl` are listed because they are public Pearl
+org artifacts. They remain `planned` in OpenJarvis until we have clean
+H100/H200 validation artifacts for the published repos.
## Enablement Checklist
@@ -84,18 +42,19 @@ Current validation evidence:
- Record calibration data and SmoothQuant settings, if used.
2. Convert the target model.
- - Start with `Qwen/Qwen3.5-9B`; it is the smallest target.
+ - Start with a model Pearl intends to publish under the `pearl-ai` org.
- Generate Pearl-compatible quantized weights and metadata.
- For Gemma4 artifacts, include the base model's processor metadata required
by vLLM's Gemma4 multimodal profiler.
- - Publish under the planned `pearl-ai/*-pearl` id or a staging namespace.
+ - Publish under the planned `pearl-ai/*-pearl` id before enabling it in
+ OpenJarvis.
OpenJarvis includes an experimental local converter for this work:
```bash
- python scripts/mining/pearl_model_converter.py \
- Qwen/Qwen3.5-9B \
- /tmp/pearl-ai-Qwen3.5-9B-pearl \
+ python scripts/pearl/model_converter.py \
+ meta-llama/Llama-3.1-8B-Instruct \
+ /tmp/pearl-ai-Llama-3.1-8B-Instruct-pearl \
--device cuda
```
@@ -110,7 +69,7 @@ Current validation evidence:
```bash
jarvis mine inspect-model \
- --model /tmp/pearl-ai-Qwen3.5-9B-pearl
+ --model /tmp/pearl-ai-Llama-3.1-8B-Instruct-pearl
```
To run a local staging artifact through the Docker miner, keep `--model` as
@@ -121,18 +80,14 @@ Current validation evidence:
jarvis mine init \
--provider vllm-pearl \
--wallet-address <prl1...> \
- --model pearl-ai/Qwen3.5-9B-pearl \
- --local-model-path /tmp/pearl-ai-Qwen3.5-9B-pearl \
+ --model pearl-ai/Llama-3.1-8B-Instruct-pearl \
+ --local-model-path /tmp/pearl-ai-Llama-3.1-8B-Instruct-pearl \
--cuda-visible-devices 1 \
--vllm-arg=--language-model-only \
- --vllm-arg=--skip-mm-profiling \
- --vllm-arg=--gdn-prefill-backend \
- --vllm-arg=triton
+ --vllm-arg=--skip-mm-profiling
jarvis mine start
```
- For Qwen3.5 validation, set `max_model_len = 4096` in `[mining.extra]`.
-
3. Validate the Pearl vLLM plugin path.
- Run `jarvis mine inspect-model --model <pearl-model-id>
--allow-planned` before starting the miner.
diff --git a/docs/user-guide/mining.md b/docs/user-guide/mining.md
index 33fba8c6..62bd8cde 100644
--- a/docs/user-guide/mining.md
+++ b/docs/user-guide/mining.md
@@ -75,35 +75,35 @@ Run:
jarvis mine models
```
-OpenJarvis only enables models that have Pearl-compatible quantized artifacts
-and real hardware validation. Raw Hugging Face models such as
-`Qwen/Qwen3.5-9B` or `google/gemma-4-E4B-it` are not mineable by themselves;
-they need corresponding Pearl-compatible variants.
+OpenJarvis only lists Pearl-compatible models published by the Pearl Research
+Labs Hugging Face org. Raw Hugging Face base models such as
+`meta-llama/Llama-3.3-70B-Instruct` or `google/gemma-4-31B-it` are not mineable
+by themselves; they need corresponding `pearl-ai/*-pearl` variants.
-The validated models are:
+The supported Pearl model ids are:
```text
pearl-ai/Llama-3.3-70B-Instruct-pearl
-ScalingIntelligence/Gemma-4-31B-it-pearl
-ScalingIntelligence/Qwen3.5-9B-pearl
+pearl-ai/Gemma-4-31B-it-pearl
+pearl-ai/Llama-3.1-8B-Instruct-pearl
```
-The Gemma 31B and Qwen 3.5 9B artifacts are experimental private staging
-artifacts under the `ScalingIntelligence` Hugging Face org. You need Hugging
-Face access to those repos before OpenJarvis can inspect or run them. They were
-validated on H100 with `jarvis mine validate-model`, but the short validation
-runs did not find a reward-bearing block or accepted share.
+`pearl-ai/Llama-3.3-70B-Instruct-pearl` is the default validated model.
+Additional public `pearl-ai/*` artifacts may remain marked `planned` until they
+pass the OpenJarvis H100/H200 validation run.
-When validating a newly converted Pearl model on a mining host, run:
+When validating a Pearl org model on a mining host, run:
```bash
jarvis mine inspect-model \
- --model ScalingIntelligence/Qwen3.5-9B-pearl
+ --model pearl-ai/Gemma-4-31B-it-pearl \
+ --allow-planned
jarvis mine validate-model \
- --model ScalingIntelligence/Qwen3.5-9B-pearl \
+ --model pearl-ai/Gemma-4-31B-it-pearl \
+ --allow-planned \
--prompt "Say hello in one sentence." \
- --output qwen3.5-9b-pearl-validation.json
+ --output gemma-4-31b-pearl-validation.json
```
Attach the JSON artifact to the validation issue when promoting additional
diff --git a/scripts/mining/pearl_model_converter.py b/scripts/mining/pearl_model_converter.py
index a5b5bacc..9c3b06de 100644
--- a/scripts/mining/pearl_model_converter.py
+++ b/scripts/mining/pearl_model_converter.py
@@ -1,359 +1,16 @@
#!/usr/bin/env python3
-"""Create experimental Pearl-compatible compressed-tensors checkpoints.
+"""Compatibility wrapper for Pearl model conversion tooling.
-This utility converts raw Hugging Face safetensors checkpoints into the minimal
-Pearl quantization shape consumed by Pearl's vLLM plugin:
-
-- int7 channel-wise weights for mining layers
-- int8 channel-wise weights for non-mining layers
-- dynamic token-wise symmetric activation metadata
-
-It is intentionally conservative and aimed at Gemma4/Qwen3.5 enablement work.
-It does not upload to Hugging Face and does not mark a model validated.
+The implementation lives in ``scripts/pearl/model_converter.py``.
"""
from __future__ import annotations
-import argparse
-import json
-import os
-import re
-import shutil
-from dataclasses import dataclass
+import runpy
from pathlib import Path
-from typing import Any
-
-import torch
-from safetensors.torch import load_file, save_file
-
-NON_MINING_RE = re.compile(
- r"(self_attn\.(q_proj|k_proj|v_proj|qkv_proj)|mlp\.down_proj)\.weight$"
-)
-IGNORED_TEXT_RE = re.compile(
- r"(^|\.)(embed_tokens|lm_head|norm|layernorm|layer_norm)\.weight$"
-)
-IGNORED_MULTIMODAL_RE = re.compile(
- r"(^model\.(vision|audio|embed_vision)|vision_tower|vision_model|visual|audio)"
-)
-
-
-@dataclass(frozen=True)
-class ConversionStats:
- copied: int = 0
- mining: int = 0
- non_mining: int = 0
-
- def add(self, kind: str) -> "ConversionStats":
- return ConversionStats(
- copied=self.copied + (kind == "copied"),
- mining=self.mining + (kind == "mining"),
- non_mining=self.non_mining + (kind == "non_mining"),
- )
-
-
-def classify_weight(name: str, tensor: torch.Tensor) -> str:
- """Classify one safetensors entry as copied, mining, or non_mining."""
-
- if not name.endswith(".weight") or tensor.ndim != 2:
- return "copied"
- if IGNORED_TEXT_RE.search(name) or IGNORED_MULTIMODAL_RE.search(name):
- return "copied"
- if NON_MINING_RE.search(name):
- return "non_mining"
- return "mining"
-
-
-def quantize_channelwise(
- weight: torch.Tensor,
- *,
- max_val: int,
- device: str,
- chunk_rows: int,
-) -> tuple[torch.Tensor, torch.Tensor]:
- """Symmetric per-output-channel int quantization for one 2D weight."""
-
- if weight.ndim != 2:
- raise ValueError(f"expected 2D weight, got shape {tuple(weight.shape)}")
- rows = weight.shape[0]
- q_chunks: list[torch.Tensor] = []
- scale_chunks: list[torch.Tensor] = []
- for start in range(0, rows, chunk_rows):
- chunk = weight[start : start + chunk_rows].to(
- device=device, dtype=torch.float32
- )
- scale = chunk.abs().amax(dim=1, keepdim=True) / float(max_val)
- scale = torch.where(scale == 0, torch.ones_like(scale), scale)
- quantized = torch.round(chunk / scale).clamp(-max_val, max_val).to(torch.int8)
- q_chunks.append(quantized.cpu())
- scale_chunks.append(scale.to(dtype=torch.bfloat16).cpu())
- return torch.cat(q_chunks, dim=0), torch.cat(scale_chunks, dim=0)
-
-
-def quantization_config() -> dict[str, Any]:
- """Return the Pearl quantization config for generated checkpoints."""
-
- dynamic_token = {
- "actorder": None,
- "block_structure": None,
- "dynamic": True,
- "group_size": None,
- "num_bits": 7,
- "observer": None,
- "observer_kwargs": {},
- "strategy": "token",
- "symmetric": True,
- "type": "int",
- }
- weight_channel = {
- "actorder": None,
- "block_structure": None,
- "dynamic": False,
- "group_size": None,
- "num_bits": 7,
- "observer": "minmax",
- "observer_kwargs": {},
- "strategy": "channel",
- "symmetric": True,
- "type": "int",
- }
-
- int8_input = {**dynamic_token, "num_bits": 8}
- int8_weight = {**weight_channel, "num_bits": 8}
-
- return {
- "config_groups": {
- "group_0": {
- "format": "int-quantized",
- "input_activations": int8_input,
- "output_activations": None,
- "targets": [
- "re:.*self_attn\\.[qkv]_proj$",
- "re:.*self_attn\\.qkv_proj$",
- "re:.*\\.down_proj$",
- ],
- "weights": int8_weight,
- },
- "group_1": {
- "format": "int-quantized",
- "input_activations": dynamic_token,
- "output_activations": None,
- "targets": ["Linear"],
- "weights": weight_channel,
- },
- },
- "format": "mixed-precision",
- "global_compression_ratio": None,
- "ignore": [
- "lm_head",
- "re:.*embed_tokens$",
- "re:.*vision.*",
- "re:.*visual.*",
- "re:.*vision_tower.*",
- "re:.*vision_model.*",
- "re:.*image.*",
- "re:.*audio.*",
- "re:.*embed_vision.*",
- "re:.*multi_modal_projector.*",
- ],
- "kv_cache_scheme": None,
- "quant_method": "pearl",
- "quantization_status": "compressed",
- "sparsity_config": {},
- "transform_config": {},
- "version": "0.13.0",
- }
-
-
-def resolve_source(source: str, token: str | None) -> Path:
- """Resolve a local path or download a Hugging Face snapshot."""
-
- path = Path(source)
- if path.exists():
- return path
- from huggingface_hub import snapshot_download
-
- return Path(
- snapshot_download(
- source,
- token=token,
- allow_patterns=[
- "*.json",
- "*.jinja",
- "*.txt",
- "*.model",
- "*.safetensors",
- ".gitattributes",
- ],
- )
- )
-
-
-def copy_metadata_files(source_dir: Path, output_dir: Path) -> None:
- """Copy non-safetensors model metadata into the output directory."""
-
- for src in source_dir.rglob("*"):
- if not src.is_file() or src.suffix == ".safetensors":
- continue
- rel = src.relative_to(source_dir)
- dst = output_dir / rel
- dst.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(src, dst)
-
-
-def patch_config(output_dir: Path) -> None:
- config_path = output_dir / "config.json"
- if not config_path.exists():
- raise FileNotFoundError(f"missing {config_path}")
- config = json.loads(config_path.read_text())
- config["quantization_config"] = quantization_config()
- output_dir.mkdir(parents=True, exist_ok=True)
- config_path.write_text(json.dumps(config, indent=2, sort_keys=True) + "\n")
-
-
-def patch_processor_metadata(output_dir: Path) -> None:
- """Provide compatibility filenames required by vLLM Gemma4 profiling."""
-
- config_path = output_dir / "config.json"
- if not config_path.exists():
- return
- config = json.loads(config_path.read_text())
- architectures = config.get("architectures") or []
- is_gemma4 = any(
- isinstance(item, str) and "Gemma4" in item for item in architectures
- )
- if not is_gemma4:
- return
-
- processor = output_dir / "processor_config.json"
- preprocessor = output_dir / "preprocessor_config.json"
- if processor.exists() and not preprocessor.exists():
- shutil.copy2(processor, preprocessor)
-
-
-def convert_safetensors_file(
- src: Path,
- dst: Path,
- *,
- device: str,
- chunk_rows: int,
- dry_run: bool,
-) -> tuple[int, dict[str, str], ConversionStats]:
- tensors = load_file(str(src), device="cpu")
- out: dict[str, torch.Tensor] = {}
- stats = ConversionStats()
- for name, tensor in tensors.items():
- kind = classify_weight(name, tensor)
- stats = stats.add(kind)
- if dry_run or kind == "copied":
- out[name] = tensor
- continue
- max_val = 63 if kind == "mining" else 127
- quantized, scale = quantize_channelwise(
- tensor,
- max_val=max_val,
- device=device,
- chunk_rows=chunk_rows,
- )
- out[name] = quantized
- out[f"{name.removesuffix('.weight')}.weight_scale"] = scale
-
- if not dry_run:
- dst.parent.mkdir(parents=True, exist_ok=True)
- save_file(out, str(dst))
- total_size = sum(tensor.nbytes for tensor in out.values())
- weight_map = {key: dst.name for key in out}
- return total_size, weight_map, stats
-
-
-def write_index(output_dir: Path, total_size: int, weight_map: dict[str, str]) -> None:
- index = {
- "metadata": {"total_size": total_size},
- "weight_map": dict(sorted(weight_map.items())),
- }
- (output_dir / "model.safetensors.index.json").write_text(
- json.dumps(index, indent=2, sort_keys=True) + "\n"
- )
-
-
-def convert_checkpoint(
- source: str,
- output_dir: Path,
- *,
- hf_token_env: str,
- device: str,
- chunk_rows: int,
- dry_run: bool,
-) -> ConversionStats:
- token = os.environ.get(hf_token_env)
- source_dir = resolve_source(source, token)
- output_dir.mkdir(parents=True, exist_ok=True)
-
- safetensors_files = sorted(source_dir.glob("*.safetensors"))
- if not safetensors_files:
- raise FileNotFoundError(f"no .safetensors files found in {source_dir}")
-
- if not dry_run:
- copy_metadata_files(source_dir, output_dir)
- patch_config(output_dir)
- patch_processor_metadata(output_dir)
-
- total_size = 0
- weight_map: dict[str, str] = {}
- stats = ConversionStats()
- for src in safetensors_files:
- dst = output_dir / src.name
- file_size, file_map, file_stats = convert_safetensors_file(
- src,
- dst,
- device=device,
- chunk_rows=chunk_rows,
- dry_run=dry_run,
- )
- total_size += file_size
- weight_map.update(file_map)
- stats = ConversionStats(
- copied=stats.copied + file_stats.copied,
- mining=stats.mining + file_stats.mining,
- non_mining=stats.non_mining + file_stats.non_mining,
- )
- print(
- f"{src.name}: copied={file_stats.copied} "
- f"mining={file_stats.mining} non_mining={file_stats.non_mining}"
- )
-
- if not dry_run:
- write_index(output_dir, total_size, weight_map)
- return stats
-
-
-def parse_args() -> argparse.Namespace:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("source", help="Local model directory or Hugging Face model id")
- parser.add_argument("output_dir", type=Path)
- parser.add_argument("--hf-token-env", default="HF_TOKEN")
- parser.add_argument("--device", default="cpu", help="cpu or cuda")
- parser.add_argument("--chunk-rows", type=int, default=4096)
- parser.add_argument("--dry-run", action="store_true")
- return parser.parse_args()
-
-
-def main() -> None:
- args = parse_args()
- stats = convert_checkpoint(
- args.source,
- args.output_dir,
- hf_token_env=args.hf_token_env,
- device=args.device,
- chunk_rows=args.chunk_rows,
- dry_run=args.dry_run,
- )
- print(
- "total: "
- f"copied={stats.copied} mining={stats.mining} non_mining={stats.non_mining}"
- )
- if args.dry_run:
- print("dry run only; no checkpoint was written")
-
if __name__ == "__main__":
- main()
+ runpy.run_path(
+ str(Path(__file__).parents[1] / "pearl" / "model_converter.py"),
+ run_name="__main__",
+ )
diff --git a/scripts/pearl/README.md b/scripts/pearl/README.md
new file mode 100644
index 00000000..490af8e2
--- /dev/null
+++ b/scripts/pearl/README.md
@@ -0,0 +1,11 @@
+# Pearl Tooling
+
+This directory holds standalone Pearl ecosystem utilities that are useful during
+model enablement or validation but are not part of the OpenJarvis runtime.
+
+- `model_converter.py` creates experimental Pearl-compatible staging
+ checkpoints from raw Hugging Face safetensors models.
+
+Keep user-facing mining commands in `src/openjarvis/cli/` and runtime provider
+code in `src/openjarvis/mining/`. Scripts here should be explicit operational
+tools that developers run manually.
diff --git a/scripts/pearl/model_converter.py b/scripts/pearl/model_converter.py
new file mode 100644
index 00000000..2bacdf39
--- /dev/null
+++ b/scripts/pearl/model_converter.py
@@ -0,0 +1,361 @@
+#!/usr/bin/env python3
+"""Create experimental Pearl-compatible compressed-tensors checkpoints.
+
+This utility converts raw Hugging Face safetensors checkpoints into the minimal
+Pearl quantization shape consumed by Pearl's vLLM plugin:
+
+- int7 channel-wise weights for mining layers
+- int8 channel-wise weights for non-mining layers
+- dynamic token-wise symmetric activation metadata
+
+It is intentionally conservative and aimed at Gemma4/Qwen3.5 enablement work.
+It does not upload to Hugging Face and does not mark a model validated.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import shutil
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import torch
+from safetensors.torch import load_file, save_file
+
+NON_MINING_RE = re.compile(
+ r"(self_attn\.(q_proj|k_proj|v_proj|qkv_proj)|mlp\.down_proj)\.weight$"
+)
+IGNORED_TEXT_RE = re.compile(
+ r"(^|\.)(embed_tokens|embed_tokens_per_layer|lm_head|norm|layernorm|layer_norm)"
+ r"\.weight$"
+)
+IGNORED_MULTIMODAL_RE = re.compile(
+ r"(^model\.(vision|audio|embed_vision)|vision_tower|vision_model|visual|audio)"
+)
+
+
+@dataclass(frozen=True)
+class ConversionStats:
+ copied: int = 0
+ mining: int = 0
+ non_mining: int = 0
+
+ def add(self, kind: str) -> "ConversionStats":
+ return ConversionStats(
+ copied=self.copied + (kind == "copied"),
+ mining=self.mining + (kind == "mining"),
+ non_mining=self.non_mining + (kind == "non_mining"),
+ )
+
+
+def classify_weight(name: str, tensor: torch.Tensor) -> str:
+ """Classify one safetensors entry as copied, mining, or non_mining."""
+
+ if not name.endswith(".weight") or tensor.ndim != 2:
+ return "copied"
+ if IGNORED_TEXT_RE.search(name) or IGNORED_MULTIMODAL_RE.search(name):
+ return "copied"
+ if NON_MINING_RE.search(name):
+ return "non_mining"
+ return "mining"
+
+
+def quantize_channelwise(
+ weight: torch.Tensor,
+ *,
+ max_val: int,
+ device: str,
+ chunk_rows: int,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Symmetric per-output-channel int quantization for one 2D weight."""
+
+ if weight.ndim != 2:
+ raise ValueError(f"expected 2D weight, got shape {tuple(weight.shape)}")
+ rows = weight.shape[0]
+ q_chunks: list[torch.Tensor] = []
+ scale_chunks: list[torch.Tensor] = []
+ for start in range(0, rows, chunk_rows):
+ chunk = weight[start : start + chunk_rows].to(
+ device=device, dtype=torch.float32
+ )
+ scale = chunk.abs().amax(dim=1, keepdim=True) / float(max_val)
+ scale = torch.where(scale == 0, torch.ones_like(scale), scale)
+ quantized = torch.round(chunk / scale).clamp(-max_val, max_val).to(torch.int8)
+ q_chunks.append(quantized.cpu())
+ scale_chunks.append(scale.to(dtype=torch.bfloat16).cpu())
+ return torch.cat(q_chunks, dim=0), torch.cat(scale_chunks, dim=0)
+
+
+def quantization_config() -> dict[str, Any]:
+ """Return the Pearl quantization config for generated checkpoints."""
+
+ dynamic_token = {
+ "actorder": None,
+ "block_structure": None,
+ "dynamic": True,
+ "group_size": None,
+ "num_bits": 7,
+ "observer": None,
+ "observer_kwargs": {},
+ "strategy": "token",
+ "symmetric": True,
+ "type": "int",
+ }
+ weight_channel = {
+ "actorder": None,
+ "block_structure": None,
+ "dynamic": False,
+ "group_size": None,
+ "num_bits": 7,
+ "observer": "minmax",
+ "observer_kwargs": {},
+ "strategy": "channel",
+ "symmetric": True,
+ "type": "int",
+ }
+
+ int8_input = {**dynamic_token, "num_bits": 8}
+ int8_weight = {**weight_channel, "num_bits": 8}
+
+ return {
+ "config_groups": {
+ "group_0": {
+ "format": "int-quantized",
+ "input_activations": int8_input,
+ "output_activations": None,
+ "targets": [
+ "re:.*self_attn\\.[qkv]_proj$",
+ "re:.*self_attn\\.qkv_proj$",
+ "re:.*\\.down_proj$",
+ ],
+ "weights": int8_weight,
+ },
+ "group_1": {
+ "format": "int-quantized",
+ "input_activations": dynamic_token,
+ "output_activations": None,
+ "targets": ["Linear"],
+ "weights": weight_channel,
+ },
+ },
+ "format": "mixed-precision",
+ "global_compression_ratio": None,
+ "ignore": [
+ "lm_head",
+ "re:.*embed_tokens$",
+ "re:.*embed_tokens_per_layer$",
+ "re:.*vision.*",
+ "re:.*visual.*",
+ "re:.*vision_tower.*",
+ "re:.*vision_model.*",
+ "re:.*image.*",
+ "re:.*audio.*",
+ "re:.*embed_vision.*",
+ "re:.*multi_modal_projector.*",
+ ],
+ "kv_cache_scheme": None,
+ "quant_method": "pearl",
+ "quantization_status": "compressed",
+ "sparsity_config": {},
+ "transform_config": {},
+ "version": "0.13.0",
+ }
+
+
+def resolve_source(source: str, token: str | None) -> Path:
+ """Resolve a local path or download a Hugging Face snapshot."""
+
+ path = Path(source)
+ if path.exists():
+ return path
+ from huggingface_hub import snapshot_download
+
+ return Path(
+ snapshot_download(
+ source,
+ token=token,
+ allow_patterns=[
+ "*.json",
+ "*.jinja",
+ "*.txt",
+ "*.model",
+ "*.safetensors",
+ ".gitattributes",
+ ],
+ )
+ )
+
+
+def copy_metadata_files(source_dir: Path, output_dir: Path) -> None:
+ """Copy non-safetensors model metadata into the output directory."""
+
+ for src in source_dir.rglob("*"):
+ if not src.is_file() or src.suffix == ".safetensors":
+ continue
+ rel = src.relative_to(source_dir)
+ dst = output_dir / rel
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(src, dst)
+
+
+def patch_config(output_dir: Path) -> None:
+ config_path = output_dir / "config.json"
+ if not config_path.exists():
+ raise FileNotFoundError(f"missing {config_path}")
+ config = json.loads(config_path.read_text())
+ config["quantization_config"] = quantization_config()
+ output_dir.mkdir(parents=True, exist_ok=True)
+ config_path.write_text(json.dumps(config, indent=2, sort_keys=True) + "\n")
+
+
+def patch_processor_metadata(output_dir: Path) -> None:
+ """Provide compatibility filenames required by vLLM Gemma4 profiling."""
+
+ config_path = output_dir / "config.json"
+ if not config_path.exists():
+ return
+ config = json.loads(config_path.read_text())
+ architectures = config.get("architectures") or []
+ is_gemma4 = any(
+ isinstance(item, str) and "Gemma4" in item for item in architectures
+ )
+ if not is_gemma4:
+ return
+
+ processor = output_dir / "processor_config.json"
+ preprocessor = output_dir / "preprocessor_config.json"
+ if processor.exists() and not preprocessor.exists():
+ shutil.copy2(processor, preprocessor)
+
+
+def convert_safetensors_file(
+ src: Path,
+ dst: Path,
+ *,
+ device: str,
+ chunk_rows: int,
+ dry_run: bool,
+) -> tuple[int, dict[str, str], ConversionStats]:
+ tensors = load_file(str(src), device="cpu")
+ out: dict[str, torch.Tensor] = {}
+ stats = ConversionStats()
+ for name, tensor in tensors.items():
+ kind = classify_weight(name, tensor)
+ stats = stats.add(kind)
+ if dry_run or kind == "copied":
+ out[name] = tensor
+ continue
+ max_val = 63 if kind == "mining" else 127
+ quantized, scale = quantize_channelwise(
+ tensor,
+ max_val=max_val,
+ device=device,
+ chunk_rows=chunk_rows,
+ )
+ out[name] = quantized
+ out[f"{name.removesuffix('.weight')}.weight_scale"] = scale
+
+ if not dry_run:
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ save_file(out, str(dst))
+ total_size = sum(tensor.nbytes for tensor in out.values())
+ weight_map = {key: dst.name for key in out}
+ return total_size, weight_map, stats
+
+
+def write_index(output_dir: Path, total_size: int, weight_map: dict[str, str]) -> None:
+ index = {
+ "metadata": {"total_size": total_size},
+ "weight_map": dict(sorted(weight_map.items())),
+ }
+ (output_dir / "model.safetensors.index.json").write_text(
+ json.dumps(index, indent=2, sort_keys=True) + "\n"
+ )
+
+
+def convert_checkpoint(
+ source: str,
+ output_dir: Path,
+ *,
+ hf_token_env: str,
+ device: str,
+ chunk_rows: int,
+ dry_run: bool,
+) -> ConversionStats:
+ token = os.environ.get(hf_token_env)
+ source_dir = resolve_source(source, token)
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ safetensors_files = sorted(source_dir.glob("*.safetensors"))
+ if not safetensors_files:
+ raise FileNotFoundError(f"no .safetensors files found in {source_dir}")
+
+ if not dry_run:
+ copy_metadata_files(source_dir, output_dir)
+ patch_config(output_dir)
+ patch_processor_metadata(output_dir)
+
+ total_size = 0
+ weight_map: dict[str, str] = {}
+ stats = ConversionStats()
+ for src in safetensors_files:
+ dst = output_dir / src.name
+ file_size, file_map, file_stats = convert_safetensors_file(
+ src,
+ dst,
+ device=device,
+ chunk_rows=chunk_rows,
+ dry_run=dry_run,
+ )
+ total_size += file_size
+ weight_map.update(file_map)
+ stats = ConversionStats(
+ copied=stats.copied + file_stats.copied,
+ mining=stats.mining + file_stats.mining,
+ non_mining=stats.non_mining + file_stats.non_mining,
+ )
+ print(
+ f"{src.name}: copied={file_stats.copied} "
+ f"mining={file_stats.mining} non_mining={file_stats.non_mining}"
+ )
+
+ if not dry_run:
+ write_index(output_dir, total_size, weight_map)
+ return stats
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("source", help="Local model directory or Hugging Face model id")
+ parser.add_argument("output_dir", type=Path)
+ parser.add_argument("--hf-token-env", default="HF_TOKEN")
+ parser.add_argument("--device", default="cpu", help="cpu or cuda")
+ parser.add_argument("--chunk-rows", type=int, default=4096)
+ parser.add_argument("--dry-run", action="store_true")
+ return parser.parse_args()
+
+
+def main() -> None:
+ args = parse_args()
+ stats = convert_checkpoint(
+ args.source,
+ args.output_dir,
+ hf_token_env=args.hf_token_env,
+ device=args.device,
+ chunk_rows=args.chunk_rows,
+ dry_run=args.dry_run,
+ )
+ print(
+ "total: "
+ f"copied={stats.copied} mining={stats.mining} non_mining={stats.non_mining}"
+ )
+ if args.dry_run:
+ print("dry run only; no checkpoint was written")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/openjarvis/mining/_models.py b/src/openjarvis/mining/_models.py
index c7bcbebd..7534a90b 100644
--- a/src/openjarvis/mining/_models.py
+++ b/src/openjarvis/mining/_models.py
@@ -37,51 +37,6 @@ PEARL_MODEL_SPECS: tuple[PearlModelSpec, ...] = (
default_max_model_len=8192,
notes="Default Pearl-blessed vLLM mining model.",
),
- PearlModelSpec(
- model_id="pearl-ai/Qwen3.5-9B-pearl",
- base_model_id="Qwen/Qwen3.5-9B",
- status="planned",
- min_vram_gb=24.0,
- default_max_model_len=8192,
- notes=(
- "Planned target; Pearl artifact is not publicly available yet. "
- "Validation tracked in open-jarvis/OpenJarvis#316."
- ),
- ),
- PearlModelSpec(
- model_id="ScalingIntelligence/Qwen3.5-9B-pearl",
- base_model_id="Qwen/Qwen3.5-9B",
- status="validated",
- min_vram_gb=24.0,
- default_max_model_len=4096,
- notes=(
- "Experimental OpenJarvis/Pearl artifact validated on H100. "
- "Runtime requires --language-model-only, --skip-mm-profiling, "
- "and --gdn-prefill-backend triton."
- ),
- ),
- PearlModelSpec(
- model_id="pearl-ai/Qwen3.6-27B-pearl",
- base_model_id="Qwen/Qwen3.6-27B",
- status="planned",
- min_vram_gb=80.0,
- default_max_model_len=8192,
- notes=(
- "Planned target; Pearl artifact is not publicly available yet. "
- "Validation tracked in open-jarvis/OpenJarvis#317."
- ),
- ),
- PearlModelSpec(
- model_id="pearl-ai/Gemma-4-E4B-it-pearl",
- base_model_id="google/gemma-4-E4B-it",
- status="planned",
- min_vram_gb=24.0,
- default_max_model_len=8192,
- notes=(
- "Planned target; Pearl artifact is not publicly available yet. "
- "Validation tracked in open-jarvis/OpenJarvis#318."
- ),
- ),
PearlModelSpec(
model_id="pearl-ai/Gemma-4-31B-it-pearl",
base_model_id="google/gemma-4-31B-it",
@@ -89,20 +44,19 @@ PEARL_MODEL_SPECS: tuple[PearlModelSpec, ...] = (
min_vram_gb=80.0,
default_max_model_len=8192,
notes=(
- "Artifact exists but H100 validation is blocked by missing Gemma4 "
- "processor/preprocessor metadata in the published Pearl artifact. "
- "Validation tracked in open-jarvis/OpenJarvis#319."
+ "Public Pearl org artifact; requires H100/H200 validation in "
+ "OpenJarvis before mining is enabled by default."
),
),
PearlModelSpec(
- model_id="ScalingIntelligence/Gemma-4-31B-it-pearl",
- base_model_id="google/gemma-4-31B-it",
- status="validated",
- min_vram_gb=80.0,
+ model_id="pearl-ai/Llama-3.1-8B-Instruct-pearl",
+ base_model_id="meta-llama/Llama-3.1-8B-Instruct",
+ status="planned",
+ min_vram_gb=24.0,
default_max_model_len=8192,
notes=(
- "Experimental OpenJarvis/Pearl artifact validated on H100 with "
- "Gemma4 processor/preprocessor metadata included."
+ "Public Pearl org artifact; requires H100/H200 validation in "
+ "OpenJarvis before mining is enabled by default."
),
),
)
diff --git a/tests/cli/test_mine_cmd.py b/tests/cli/test_mine_cmd.py
index 83e2012b..af46d014 100644
--- a/tests/cli/test_mine_cmd.py
+++ b/tests/cli/test_mine_cmd.py
@@ -28,24 +28,22 @@ def test_mine_models_lists_validated_and_planned_models() -> None:
assert result.exit_code == 0
assert "Pearl Mining Models" in result.output
assert "pearl-ai/Llama-3.3-70B-Instruct-pearl" in result.output
- assert "ScalingIntelligence/Gemma-4-31B-it-pearl" in result.output
- assert "ScalingIntelligence/Qwen3.5-9B-pearl" in result.output
- assert "pearl-ai/Qwen3.5-9B-pearl" in result.output
+ assert "pearl-ai/Gemma-4-31B-it-pearl" in result.output
+ assert "pearl-ai/Llama-3.1-8B-Instruct-pearl" in result.output
+ assert "Qwen" not in result.output
assert "validated" in result.output
assert "planned" in result.output
-def test_pearl_base_model_lookup_prefers_validated_scalingintelligence_artifacts():
+def test_pearl_base_model_lookup_uses_public_pearl_ai_artifacts():
from openjarvis.mining._models import pearl_variant_for_base_model
assert (
pearl_variant_for_base_model("google/gemma-4-31B-it")
- == "ScalingIntelligence/Gemma-4-31B-it-pearl"
- )
- assert (
- pearl_variant_for_base_model("Qwen/Qwen3.5-9B")
- == "ScalingIntelligence/Qwen3.5-9B-pearl"
+ == "pearl-ai/Gemma-4-31B-it-pearl"
)
+ assert pearl_variant_for_base_model("Qwen/Qwen3.5-9B") is None
+ assert pearl_variant_for_base_model("google/gemma-4-E4B-it") is None
def test_mine_inspect_model_validated_artifact_passes(monkeypatch) -> None:
@@ -245,7 +243,7 @@ def test_mine_init_writes_local_model_path_for_vllm(
"--pearld-rpc-password-env",
"TEST_PEARLD_PASSWORD",
"--model",
- "pearl-ai/Qwen3.5-9B-pearl",
+ "pearl-ai/Llama-3.1-8B-Instruct-pearl",
"--local-model-path",
str(local_model),
"--vllm-arg=--language-model-only",
@@ -256,7 +254,7 @@ def test_mine_init_writes_local_model_path_for_vllm(
assert result.exit_code == 0
content = config_path.read_text()
- assert 'model = "pearl-ai/Qwen3.5-9B-pearl"' in content
+ assert 'model = "pearl-ai/Llama-3.1-8B-Instruct-pearl"' in content
assert f'local_model_path = "{local_model.resolve()}"' in content
assert 'vllm_args = ["--language-model-only", "--skip-mm-profiling"]' in content
@@ -401,7 +399,7 @@ def test_mine_validate_model_blocks_planned_without_allow(
tmp_path: Path, monkeypatch
) -> None:
sidecar_path = tmp_path / "mining.json"
- model = "pearl-ai/Qwen3.5-9B-pearl"
+ model = "pearl-ai/Gemma-4-31B-it-pearl"
Sidecar.write(
sidecar_path,
{
@@ -435,7 +433,7 @@ def test_mine_validate_model_allows_planned_with_runtime_evidence(
tmp_path: Path, monkeypatch
) -> None:
sidecar_path = tmp_path / "mining.json"
- model = "pearl-ai/Qwen3.5-9B-pearl"
+ model = "pearl-ai/Gemma-4-31B-it-pearl"
Sidecar.write(
sidecar_path,
{
@@ -482,7 +480,7 @@ def test_mine_validate_model_allows_planned_with_runtime_evidence(
def test_mine_validate_model_writes_json_artifact(tmp_path: Path, monkeypatch) -> None:
sidecar_path = tmp_path / "mining.json"
output_path = tmp_path / "artifacts" / "qwen-validation.json"
- model = "pearl-ai/Qwen3.5-9B-pearl"
+ model = "pearl-ai/Gemma-4-31B-it-pearl"
Sidecar.write(
sidecar_path,
{
diff --git a/tests/mining/test_discovery.py b/tests/mining/test_discovery.py
index 0a2b2456..12ddcc12 100644
--- a/tests/mining/test_discovery.py
+++ b/tests/mining/test_discovery.py
@@ -91,12 +91,12 @@ def test_detect_raw_planned_model_points_to_pearl_variant(hopper_hw):
cap = detect_for_engine_model(
hw=hopper_hw,
engine_id="vllm",
- model="Qwen/Qwen3.5-9B",
+ model="google/gemma-4-31B-it",
provider_id="vllm-pearl",
)
assert cap.supported is False
- assert "ScalingIntelligence/Qwen3.5-9B-pearl" in cap.reason
+ assert "pearl-ai/Gemma-4-31B-it-pearl" in cap.reason
def test_detect_planned_pearl_model_is_not_enabled_yet(hopper_hw):
@@ -105,7 +105,7 @@ def test_detect_planned_pearl_model_is_not_enabled_yet(hopper_hw):
cap = detect_for_engine_model(
hw=hopper_hw,
engine_id="vllm",
- model="pearl-ai/Qwen3.5-9B-pearl",
+ model="pearl-ai/Gemma-4-31B-it-pearl",
provider_id="vllm-pearl",
)
diff --git a/tests/mining/test_docker.py b/tests/mining/test_docker.py
index 7c7c3323..e180f59c 100644
--- a/tests/mining/test_docker.py
+++ b/tests/mining/test_docker.py
@@ -222,7 +222,7 @@ def test_launcher_start_mounts_local_model_path(_env_password, tmp_path):
from openjarvis.mining._docker import LOCAL_MODEL_BIND_PATH, PearlDockerLauncher
from openjarvis.mining._stubs import MiningConfig, SoloTarget
- local_model = tmp_path / "qwen-pearl"
+ local_model = tmp_path / "llama31-pearl"
local_model.mkdir()
fake = MagicMock()
fake.containers.run.return_value = MagicMock(id="cid-1", status="running")
@@ -232,7 +232,7 @@ def test_launcher_start_mounts_local_model_path(_env_password, tmp_path):
wallet_address="prl1qaaa",
submit_target=SoloTarget(pearld_rpc_url="http://localhost:44107"),
extra={
- "model": "pearl-ai/Qwen3.5-9B-pearl",
+ "model": "pearl-ai/Llama-3.1-8B-Instruct-pearl",
"local_model_path": str(local_model),
"pearld_rpc_password_env": "PEARLD_RPC_PASSWORD",
"vllm_args": ["--language-model-only", "--skip-mm-profiling"],
@@ -244,7 +244,7 @@ def test_launcher_start_mounts_local_model_path(_env_password, tmp_path):
kwargs = fake.containers.run.call_args.kwargs
assert kwargs["command"][0] == LOCAL_MODEL_BIND_PATH
assert "--served-model-name" in kwargs["command"]
- assert "pearl-ai/Qwen3.5-9B-pearl" in kwargs["command"]
+ assert "pearl-ai/Llama-3.1-8B-Instruct-pearl" in kwargs["command"]
assert "--language-model-only" in kwargs["command"]
assert "--skip-mm-profiling" in kwargs["command"]
assert kwargs["volumes"][str(local_model.resolve())] == {
diff --git a/tests/scripts/test_pearl_model_converter.py b/tests/pearl/test_model_converter.py
similarity index 89%
rename from tests/scripts/test_pearl_model_converter.py
rename to tests/pearl/test_model_converter.py
index 6eff4cb3..37a78e9c 100644
--- a/tests/scripts/test_pearl_model_converter.py
+++ b/tests/pearl/test_model_converter.py
@@ -15,7 +15,7 @@ save_file = safetensors_torch.save_file
def _load_converter():
- path = Path(__file__).parents[2] / "scripts" / "mining" / "pearl_model_converter.py"
+ path = Path(__file__).parents[2] / "scripts" / "pearl" / "model_converter.py"
spec = importlib.util.spec_from_file_location("pearl_model_converter", path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
@@ -37,6 +37,9 @@ def test_converter_quantizes_linear_weights_and_writes_pearl_config(
save_file(
{
"model.embed_tokens.weight": torch.ones(4, 4, dtype=torch.bfloat16),
+ "model.embed_tokens_per_layer.weight": torch.full(
+ (4, 4), 2, dtype=torch.bfloat16
+ ),
"model.layers.0.self_attn.q_proj.weight": torch.arange(
16, dtype=torch.float32
).reshape(4, 4),
@@ -65,6 +68,8 @@ def test_converter_quantizes_linear_weights_and_writes_pearl_config(
assert tensors["model.layers.0.self_attn.q_proj.weight_scale"].shape == (4, 1)
assert tensors["model.layers.0.self_attn.o_proj.weight_scale"].shape == (4, 1)
assert tensors["model.embed_tokens.weight"].dtype == torch.bfloat16
+ assert tensors["model.embed_tokens_per_layer.weight"].dtype == torch.bfloat16
+ assert "model.embed_tokens_per_layer.weight_scale" not in tensors
config = json.loads((out / "config.json").read_text())
assert config["quantization_config"]["quant_method"] == "pearl"
@@ -73,6 +78,7 @@ def test_converter_quantizes_linear_weights_and_writes_pearl_config(
== 7
)
assert "re:.*visual.*" in config["quantization_config"]["ignore"]
+ assert "re:.*embed_tokens_per_layer$" in config["quantization_config"]["ignore"]
index = json.loads((out / "model.safetensors.index.json").read_text())
assert "model.layers.0.self_attn.o_proj.weight_scale" in index["weight_map"]