Improve Parvulus-Post UX: auto-detect action_scale.json, add --model_path/--model_dir CLI flags
Browse files- README.md +13 -8
- eval_benchmark_parallel.py +23 -2
- eval_libero.py +15 -1
- infer.py +9 -2
- prepare_runtime.py +53 -18
README.md
CHANGED
|
@@ -23,28 +23,33 @@ pipeline_tag: robotics
|
|
| 23 |
|
| 24 |
## Update: `Parvulus-Post` Release
|
| 25 |
|
| 26 |
-
We are releasing **`Parvulus-Post`** (`parvulus-post/`), a post-trained checkpoint of the same **9.97M-parameter** (`~38 MB` FP32) Parvulus architecture, drop-in compatible with the existing PyTorch and C++/CUDA inference runtimes
|
| 27 |
|
| 28 |
-
### Quickstart (`Parvulus-Post`
|
| 29 |
|
| 30 |
```python
|
| 31 |
from infer import ParvulusInference
|
| 32 |
|
| 33 |
-
#
|
| 34 |
infer = ParvulusInference.from_pretrained(
|
| 35 |
"parvulus-post",
|
| 36 |
-
scale_path="parvulus-post/action_scale.json",
|
| 37 |
device="cuda",
|
| 38 |
use_kv_cache=True,
|
| 39 |
num_ode_steps=10,
|
| 40 |
)
|
| 41 |
```
|
| 42 |
|
| 43 |
-
For
|
| 44 |
```bash
|
| 45 |
-
python3
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
```
|
| 49 |
|
| 50 |
### LIBERO-40 Competitiveness vs. Published VLAs & WAMs
|
|
|
|
| 23 |
|
| 24 |
## Update: `Parvulus-Post` Release
|
| 25 |
|
| 26 |
+
We are releasing **`Parvulus-Post`** (`parvulus-post/`), a post-trained checkpoint of the same **9.97M-parameter** (`~38 MB` FP32) Parvulus architecture, drop-in compatible with the existing PyTorch and C++/CUDA inference runtimes. Across **LIBERO-40**, `Parvulus-Post` reaches **98.85% ± 0.25%** average success (and **97.78% ± 0.22%** across all **130 LIBERO tasks**), remaining competitive with the strongest published 2B–7B VLAs and WAMs (98.5%–99.9%) at **200×–700× smaller scale** and without any pretrained VLM or video foundation backbone, while also improving visual, kinematic, and layout generalization over base `Parvulus`.
|
| 27 |
|
| 28 |
+
### Quickstart (`Parvulus-Post`)
|
| 29 |
|
| 30 |
```python
|
| 31 |
from infer import ParvulusInference
|
| 32 |
|
| 33 |
+
# Automatically loads parvulus-post/action_scale.json alongside parvulus-post weights
|
| 34 |
infer = ParvulusInference.from_pretrained(
|
| 35 |
"parvulus-post",
|
|
|
|
| 36 |
device="cuda",
|
| 37 |
use_kv_cache=True,
|
| 38 |
num_ode_steps=10,
|
| 39 |
)
|
| 40 |
```
|
| 41 |
|
| 42 |
+
For evaluation scripts:
|
| 43 |
```bash
|
| 44 |
+
python3 eval_libero.py --model_path parvulus-post --suite libero_10 --task_id 0 --num_trials 5
|
| 45 |
+
python3 eval_benchmark_parallel.py --model_path parvulus-post --backend pytorch
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
For the standalone C++/CUDA engine (compiles `libparvulus.so`, exports weights, action scale, canonical embeddings, and dynamic ONNX text encoder from `parvulus-post/`):
|
| 49 |
+
```bash
|
| 50 |
+
python3 prepare_runtime.py --model_dir parvulus-post
|
| 51 |
+
# Or skip ONNX if using canonical LIBERO-40 tasks only:
|
| 52 |
+
python3 prepare_runtime.py --model_dir parvulus-post --skip_onnx
|
| 53 |
```
|
| 54 |
|
| 55 |
### LIBERO-40 Competitiveness vs. Published VLAs & WAMs
|
eval_benchmark_parallel.py
CHANGED
|
@@ -46,6 +46,8 @@ def run_worker(
|
|
| 46 |
resolution: int,
|
| 47 |
seed_offset: int,
|
| 48 |
backend: str = "cuda_c",
|
|
|
|
|
|
|
| 49 |
):
|
| 50 |
"""Worker process: loops over dynamic task queue and executes rollouts."""
|
| 51 |
# Ensure correct environment variables before importing heavy frameworks
|
|
@@ -68,9 +70,10 @@ def run_worker(
|
|
| 68 |
tasks = json.load(f)
|
| 69 |
|
| 70 |
device = "cuda:0"
|
| 71 |
-
print(f"[Worker {worker_id} (GPU {gpu_id})] Initializing Parvulus policy on {device} (backend={backend})...", flush=True)
|
| 72 |
infer = ParvulusInference.from_pretrained(
|
| 73 |
-
pretrained_path=
|
|
|
|
| 74 |
device=device,
|
| 75 |
backend=backend,
|
| 76 |
use_kv_cache=True,
|
|
@@ -288,6 +291,18 @@ def plot_results(suite_summaries: Dict[str, Dict], overall_rate: float, total_tr
|
|
| 288 |
# ---------------------------------------------------------------------------
|
| 289 |
def main():
|
| 290 |
parser = argparse.ArgumentParser(description="Parvulus 2000-Trial Parallel Benchmark")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
parser.add_argument("--output_dir", type=str, default="./outputs/eval_parvulus_2000")
|
| 292 |
parser.add_argument("--num_trials", type=int, default=50, help="Trials per task (default: 50 -> 2,000 total)")
|
| 293 |
parser.add_argument("--num_gpus", type=int, default=4, help="Number of GPUs to use")
|
|
@@ -322,6 +337,8 @@ def main():
|
|
| 322 |
resolution=args.resolution,
|
| 323 |
seed_offset=args.seed,
|
| 324 |
backend=args.backend,
|
|
|
|
|
|
|
| 325 |
)
|
| 326 |
return
|
| 327 |
|
|
@@ -368,6 +385,7 @@ def main():
|
|
| 368 |
print("=" * 75)
|
| 369 |
print(" PARVULUS 2,000-TRIAL BENCHMARK ORCHESTRATOR")
|
| 370 |
print("=" * 75)
|
|
|
|
| 371 |
print(f" Total Tasks: {total_tasks} across {len(TASK_SUITES)} canonical suites")
|
| 372 |
print(f" Trials per Task: {args.num_trials}")
|
| 373 |
print(f" Total Trials: {total_trials}")
|
|
@@ -392,6 +410,7 @@ def main():
|
|
| 392 |
cmd = [
|
| 393 |
sys.executable,
|
| 394 |
__file__,
|
|
|
|
| 395 |
"--output_dir", str(out_dir),
|
| 396 |
"--num_trials", str(args.num_trials),
|
| 397 |
"--chunk_size", str(args.chunk_size),
|
|
@@ -403,6 +422,8 @@ def main():
|
|
| 403 |
"--worker_id", str(worker_id),
|
| 404 |
"--gpu_id", str(gpu_id),
|
| 405 |
]
|
|
|
|
|
|
|
| 406 |
proc = subprocess.Popen(cmd, stdout=log_file, stderr=subprocess.STDOUT)
|
| 407 |
workers.append({
|
| 408 |
"worker_id": worker_id,
|
|
|
|
| 46 |
resolution: int,
|
| 47 |
seed_offset: int,
|
| 48 |
backend: str = "cuda_c",
|
| 49 |
+
model_path: str = str(SCRIPT_DIR),
|
| 50 |
+
scale_path: Optional[str] = None,
|
| 51 |
):
|
| 52 |
"""Worker process: loops over dynamic task queue and executes rollouts."""
|
| 53 |
# Ensure correct environment variables before importing heavy frameworks
|
|
|
|
| 70 |
tasks = json.load(f)
|
| 71 |
|
| 72 |
device = "cuda:0"
|
| 73 |
+
print(f"[Worker {worker_id} (GPU {gpu_id})] Initializing Parvulus policy from '{model_path}' on {device} (backend={backend})...", flush=True)
|
| 74 |
infer = ParvulusInference.from_pretrained(
|
| 75 |
+
pretrained_path=model_path,
|
| 76 |
+
scale_path=scale_path,
|
| 77 |
device=device,
|
| 78 |
backend=backend,
|
| 79 |
use_kv_cache=True,
|
|
|
|
| 291 |
# ---------------------------------------------------------------------------
|
| 292 |
def main():
|
| 293 |
parser = argparse.ArgumentParser(description="Parvulus 2000-Trial Parallel Benchmark")
|
| 294 |
+
parser.add_argument(
|
| 295 |
+
"--model_path",
|
| 296 |
+
type=str,
|
| 297 |
+
default=str(SCRIPT_DIR),
|
| 298 |
+
help="Directory containing model weights, config.json, and action_scale.json (e.g. '.' or 'parvulus-post')",
|
| 299 |
+
)
|
| 300 |
+
parser.add_argument(
|
| 301 |
+
"--scale_path",
|
| 302 |
+
type=str,
|
| 303 |
+
default=None,
|
| 304 |
+
help="Optional path to action_scale.json (auto-detected from --model_path if omitted)",
|
| 305 |
+
)
|
| 306 |
parser.add_argument("--output_dir", type=str, default="./outputs/eval_parvulus_2000")
|
| 307 |
parser.add_argument("--num_trials", type=int, default=50, help="Trials per task (default: 50 -> 2,000 total)")
|
| 308 |
parser.add_argument("--num_gpus", type=int, default=4, help="Number of GPUs to use")
|
|
|
|
| 337 |
resolution=args.resolution,
|
| 338 |
seed_offset=args.seed,
|
| 339 |
backend=args.backend,
|
| 340 |
+
model_path=args.model_path,
|
| 341 |
+
scale_path=args.scale_path,
|
| 342 |
)
|
| 343 |
return
|
| 344 |
|
|
|
|
| 385 |
print("=" * 75)
|
| 386 |
print(" PARVULUS 2,000-TRIAL BENCHMARK ORCHESTRATOR")
|
| 387 |
print("=" * 75)
|
| 388 |
+
print(f" Model Path: {args.model_path}")
|
| 389 |
print(f" Total Tasks: {total_tasks} across {len(TASK_SUITES)} canonical suites")
|
| 390 |
print(f" Trials per Task: {args.num_trials}")
|
| 391 |
print(f" Total Trials: {total_trials}")
|
|
|
|
| 410 |
cmd = [
|
| 411 |
sys.executable,
|
| 412 |
__file__,
|
| 413 |
+
"--model_path", str(args.model_path),
|
| 414 |
"--output_dir", str(out_dir),
|
| 415 |
"--num_trials", str(args.num_trials),
|
| 416 |
"--chunk_size", str(args.chunk_size),
|
|
|
|
| 422 |
"--worker_id", str(worker_id),
|
| 423 |
"--gpu_id", str(gpu_id),
|
| 424 |
]
|
| 425 |
+
if args.scale_path is not None:
|
| 426 |
+
cmd.extend(["--scale_path", str(args.scale_path)])
|
| 427 |
proc = subprocess.Popen(cmd, stdout=log_file, stderr=subprocess.STDOUT)
|
| 428 |
workers.append({
|
| 429 |
"worker_id": worker_id,
|
eval_libero.py
CHANGED
|
@@ -118,6 +118,18 @@ def run_trial(
|
|
| 118 |
|
| 119 |
def parse_args():
|
| 120 |
parser = argparse.ArgumentParser(description="Parvulus LIBERO Benchmark Evaluation")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
parser.add_argument("--suite", type=str, default="libero_spatial", choices=TASK_SUITES)
|
| 122 |
parser.add_argument("--task_id", type=int, default=0, help="Task index in suite (default: 0)")
|
| 123 |
parser.add_argument("--num_trials", type=int, default=1, help="Number of trials to evaluate")
|
|
@@ -139,6 +151,7 @@ def main():
|
|
| 139 |
print("=" * 70)
|
| 140 |
print(" PARVULUS Physical AI Model - LIBERO Evaluation")
|
| 141 |
print("=" * 70)
|
|
|
|
| 142 |
print(f" Suite: {args.suite}")
|
| 143 |
print(f" Task ID: {args.task_id}")
|
| 144 |
print(f" Trials: {args.num_trials}")
|
|
@@ -149,7 +162,8 @@ def main():
|
|
| 149 |
|
| 150 |
# Initialize policy
|
| 151 |
infer = ParvulusInference.from_pretrained(
|
| 152 |
-
pretrained_path=
|
|
|
|
| 153 |
device=args.device,
|
| 154 |
backend=args.backend,
|
| 155 |
use_kv_cache=args.use_kv_cache,
|
|
|
|
| 118 |
|
| 119 |
def parse_args():
|
| 120 |
parser = argparse.ArgumentParser(description="Parvulus LIBERO Benchmark Evaluation")
|
| 121 |
+
parser.add_argument(
|
| 122 |
+
"--model_path",
|
| 123 |
+
type=str,
|
| 124 |
+
default=str(SCRIPT_DIR),
|
| 125 |
+
help="Directory containing model weights, config.json, and action_scale.json (e.g. '.' or 'parvulus-post')",
|
| 126 |
+
)
|
| 127 |
+
parser.add_argument(
|
| 128 |
+
"--scale_path",
|
| 129 |
+
type=str,
|
| 130 |
+
default=None,
|
| 131 |
+
help="Optional path to action_scale.json (auto-detected from --model_path if omitted)",
|
| 132 |
+
)
|
| 133 |
parser.add_argument("--suite", type=str, default="libero_spatial", choices=TASK_SUITES)
|
| 134 |
parser.add_argument("--task_id", type=int, default=0, help="Task index in suite (default: 0)")
|
| 135 |
parser.add_argument("--num_trials", type=int, default=1, help="Number of trials to evaluate")
|
|
|
|
| 151 |
print("=" * 70)
|
| 152 |
print(" PARVULUS Physical AI Model - LIBERO Evaluation")
|
| 153 |
print("=" * 70)
|
| 154 |
+
print(f" Model Path: {args.model_path}")
|
| 155 |
print(f" Suite: {args.suite}")
|
| 156 |
print(f" Task ID: {args.task_id}")
|
| 157 |
print(f" Trials: {args.num_trials}")
|
|
|
|
| 162 |
|
| 163 |
# Initialize policy
|
| 164 |
infer = ParvulusInference.from_pretrained(
|
| 165 |
+
pretrained_path=args.model_path,
|
| 166 |
+
scale_path=args.scale_path,
|
| 167 |
device=args.device,
|
| 168 |
backend=args.backend,
|
| 169 |
use_kv_cache=args.use_kv_cache,
|
infer.py
CHANGED
|
@@ -18,7 +18,7 @@ class ParvulusInference:
|
|
| 18 |
def __init__(
|
| 19 |
self,
|
| 20 |
model_path: Union[str, Path] = ".",
|
| 21 |
-
scale_path: Union[str, Path] =
|
| 22 |
device: str = "auto",
|
| 23 |
use_kv_cache: bool = True,
|
| 24 |
load_auxiliary: bool = False,
|
|
@@ -35,7 +35,9 @@ class ParvulusInference:
|
|
| 35 |
|
| 36 |
Args:
|
| 37 |
model_path: Directory containing parvulus.safetensors and config.json.
|
| 38 |
-
scale_path: Path to action_scale.json.
|
|
|
|
|
|
|
| 39 |
device: 'cuda', 'cpu', 'xpu', 'hybrid', or 'auto'.
|
| 40 |
'hybrid' executes visual perception on Intel iGPU (xpu) and the ODE loop on CPU.
|
| 41 |
use_kv_cache: Precomputes visual keys/values for fast 38ms action chunking.
|
|
@@ -106,6 +108,11 @@ class ParvulusInference:
|
|
| 106 |
eff_gamma = self.gamma if (self.gamma is not None and self.gamma != 1.0) else 0.55
|
| 107 |
self._gamma_lut = np.array([((i / 255.0) ** eff_gamma) * 255.0 for i in range(256)]).astype(np.uint8)
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
self.action_min, self.action_max = load_action_scale(scale_path)
|
| 110 |
self.action_min = self.action_min.to(self.device)
|
| 111 |
self.action_max = self.action_max.to(self.device)
|
|
|
|
| 18 |
def __init__(
|
| 19 |
self,
|
| 20 |
model_path: Union[str, Path] = ".",
|
| 21 |
+
scale_path: Optional[Union[str, Path]] = None,
|
| 22 |
device: str = "auto",
|
| 23 |
use_kv_cache: bool = True,
|
| 24 |
load_auxiliary: bool = False,
|
|
|
|
| 35 |
|
| 36 |
Args:
|
| 37 |
model_path: Directory containing parvulus.safetensors and config.json.
|
| 38 |
+
scale_path: Path to action_scale.json. If omitted, automatically uses
|
| 39 |
+
`<model_path>/action_scale.json` when present, falling back to
|
| 40 |
+
the repository root `action_scale.json`.
|
| 41 |
device: 'cuda', 'cpu', 'xpu', 'hybrid', or 'auto'.
|
| 42 |
'hybrid' executes visual perception on Intel iGPU (xpu) and the ODE loop on CPU.
|
| 43 |
use_kv_cache: Precomputes visual keys/values for fast 38ms action chunking.
|
|
|
|
| 108 |
eff_gamma = self.gamma if (self.gamma is not None and self.gamma != 1.0) else 0.55
|
| 109 |
self._gamma_lut = np.array([((i / 255.0) ** eff_gamma) * 255.0 for i in range(256)]).astype(np.uint8)
|
| 110 |
|
| 111 |
+
if scale_path is None:
|
| 112 |
+
model_p = Path(model_path)
|
| 113 |
+
candidate = (model_p / "action_scale.json") if model_p.is_dir() else (model_p.parent / "action_scale.json")
|
| 114 |
+
scale_path = candidate if candidate.exists() else DEFAULT_SCALE_PATH
|
| 115 |
+
|
| 116 |
self.action_min, self.action_max = load_action_scale(scale_path)
|
| 117 |
self.action_min = self.action_min.to(self.device)
|
| 118 |
self.action_max = self.action_max.to(self.device)
|
prepare_runtime.py
CHANGED
|
@@ -26,47 +26,68 @@ def build_c_engine():
|
|
| 26 |
print("[Prepare] C engine compiled successfully.")
|
| 27 |
|
| 28 |
|
| 29 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
"""Exports parvulus_model_weights.bin, action_scale.bin, and task_embeddings.bin from SafeTensors/JSON."""
|
| 31 |
out_bin = C_ENGINE_DIR / "parvulus_model_weights.bin"
|
| 32 |
out_scale = C_ENGINE_DIR / "action_scale.bin"
|
| 33 |
out_emb = C_ENGINE_DIR / "task_embeddings.bin"
|
| 34 |
|
| 35 |
-
st_path =
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
| 40 |
|
| 41 |
sys.path.insert(0, str(C_ENGINE_DIR))
|
| 42 |
from export_from_safetensors import export_binary_weights, export_action_scale, export_task_embeddings
|
| 43 |
|
| 44 |
-
if not out_bin.exists():
|
| 45 |
-
print(f"\n[Prepare] Exporting binary model weights from {st_path
|
| 46 |
export_binary_weights(str(st_path), str(out_bin))
|
| 47 |
else:
|
| 48 |
print(f"[Prepare] Found existing {out_bin.name} ({out_bin.stat().st_size / (1024*1024):.2f} MB).")
|
| 49 |
|
| 50 |
-
if not out_scale.exists():
|
| 51 |
-
export_action_scale(str(
|
| 52 |
else:
|
| 53 |
print(f"[Prepare] Found existing {out_scale.name}.")
|
| 54 |
|
| 55 |
-
if not out_emb.exists() and (C_ENGINE_DIR / "canonical_tasks.json").exists():
|
| 56 |
export_task_embeddings(str(C_ENGINE_DIR / "canonical_tasks.json"), str(st_path), str(out_emb))
|
| 57 |
elif out_emb.exists():
|
| 58 |
print(f"[Prepare] Found existing {out_emb.name}.")
|
| 59 |
|
| 60 |
|
| 61 |
-
def obtain_text_encoder_onnx(hf_repo: str = None, force_convert: bool = False):
|
| 62 |
"""Obtains parvulus_text_encoder.onnx via Hugging Face download or local conversion."""
|
| 63 |
onnx_path = C_ENGINE_DIR / "parvulus_text_encoder.onnx"
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
| 65 |
print(f"[Prepare] Found existing {onnx_path.name} ({onnx_path.stat().st_size / (1024*1024):.1f} MB).")
|
| 66 |
return
|
| 67 |
|
| 68 |
repo_id = hf_repo or os.environ.get("PARVULUS_HF_REPO")
|
| 69 |
-
if repo_id and not
|
| 70 |
print(f"\n[Prepare] Attempting to download {onnx_path.name} from Hugging Face Hub: '{repo_id}'...")
|
| 71 |
try:
|
| 72 |
from huggingface_hub import hf_hub_download
|
|
@@ -84,12 +105,13 @@ def obtain_text_encoder_onnx(hf_repo: str = None, force_convert: bool = False):
|
|
| 84 |
print(f"[Prepare] Hugging Face download from '{repo_id}' failed: {e}.")
|
| 85 |
print("[Prepare] Falling back to local conversion...")
|
| 86 |
|
| 87 |
-
|
|
|
|
| 88 |
sys.path.insert(0, str(C_ENGINE_DIR))
|
| 89 |
from export_text_encoder_onnx import export_onnx
|
| 90 |
|
| 91 |
export_onnx(
|
| 92 |
-
weights_path=str(
|
| 93 |
output_path=str(onnx_path),
|
| 94 |
verify=True,
|
| 95 |
)
|
|
@@ -97,6 +119,17 @@ def obtain_text_encoder_onnx(hf_repo: str = None, force_convert: bool = False):
|
|
| 97 |
|
| 98 |
def main():
|
| 99 |
parser = argparse.ArgumentParser(description="Prepare PARVULUS Standalone Native Runtime.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
parser.add_argument(
|
| 101 |
"--hf_repo",
|
| 102 |
type=str,
|
|
@@ -120,18 +153,20 @@ def main():
|
|
| 120 |
)
|
| 121 |
|
| 122 |
args = parser.parse_args()
|
|
|
|
| 123 |
|
| 124 |
print("=" * 70)
|
| 125 |
print(" PREPARING PARVULUS STANDALONE RUNTIME")
|
|
|
|
| 126 |
print("=" * 70)
|
| 127 |
|
| 128 |
if args.build_c:
|
| 129 |
res = subprocess.run(["make", "clean"], cwd=str(C_ENGINE_DIR))
|
| 130 |
build_c_engine()
|
| 131 |
-
export_binary_assets()
|
| 132 |
|
| 133 |
if not args.skip_onnx:
|
| 134 |
-
obtain_text_encoder_onnx(hf_repo=args.hf_repo, force_convert=args.convert_onnx)
|
| 135 |
else:
|
| 136 |
print("[Prepare] Skipping ONNX preparation (--skip_onnx set).")
|
| 137 |
|
|
|
|
| 26 |
print("[Prepare] C engine compiled successfully.")
|
| 27 |
|
| 28 |
|
| 29 |
+
def _resolve_model_dir(model_dir: str = ".") -> Path:
|
| 30 |
+
p = Path(model_dir)
|
| 31 |
+
if not p.is_absolute():
|
| 32 |
+
p = ROOT_DIR / p
|
| 33 |
+
return p.resolve()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _resolve_safetensors(model_dir: Path) -> Path:
|
| 37 |
+
st_path = model_dir / "parvulus.safetensors"
|
| 38 |
+
if not st_path.exists():
|
| 39 |
+
st_path = model_dir / "model.safetensors"
|
| 40 |
+
if not st_path.exists():
|
| 41 |
+
raise FileNotFoundError(f"SafeTensors weights not found in {model_dir}")
|
| 42 |
+
return st_path
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def export_binary_assets(model_dir: Path = ROOT_DIR, force: bool = False):
|
| 46 |
"""Exports parvulus_model_weights.bin, action_scale.bin, and task_embeddings.bin from SafeTensors/JSON."""
|
| 47 |
out_bin = C_ENGINE_DIR / "parvulus_model_weights.bin"
|
| 48 |
out_scale = C_ENGINE_DIR / "action_scale.bin"
|
| 49 |
out_emb = C_ENGINE_DIR / "task_embeddings.bin"
|
| 50 |
|
| 51 |
+
st_path = _resolve_safetensors(model_dir)
|
| 52 |
+
scale_path = model_dir / "action_scale.json"
|
| 53 |
+
if not scale_path.exists():
|
| 54 |
+
scale_path = ROOT_DIR / "action_scale.json"
|
| 55 |
+
|
| 56 |
+
# Always re-export when explicitly targeting a submodel (e.g., parvulus-post) or when --force_export is set
|
| 57 |
+
overwrite = force or (model_dir.resolve() != ROOT_DIR.resolve())
|
| 58 |
|
| 59 |
sys.path.insert(0, str(C_ENGINE_DIR))
|
| 60 |
from export_from_safetensors import export_binary_weights, export_action_scale, export_task_embeddings
|
| 61 |
|
| 62 |
+
if overwrite or not out_bin.exists():
|
| 63 |
+
print(f"\n[Prepare] Exporting binary model weights from {st_path}...")
|
| 64 |
export_binary_weights(str(st_path), str(out_bin))
|
| 65 |
else:
|
| 66 |
print(f"[Prepare] Found existing {out_bin.name} ({out_bin.stat().st_size / (1024*1024):.2f} MB).")
|
| 67 |
|
| 68 |
+
if overwrite or not out_scale.exists():
|
| 69 |
+
export_action_scale(str(scale_path), str(out_scale))
|
| 70 |
else:
|
| 71 |
print(f"[Prepare] Found existing {out_scale.name}.")
|
| 72 |
|
| 73 |
+
if (overwrite or not out_emb.exists()) and (C_ENGINE_DIR / "canonical_tasks.json").exists():
|
| 74 |
export_task_embeddings(str(C_ENGINE_DIR / "canonical_tasks.json"), str(st_path), str(out_emb))
|
| 75 |
elif out_emb.exists():
|
| 76 |
print(f"[Prepare] Found existing {out_emb.name}.")
|
| 77 |
|
| 78 |
|
| 79 |
+
def obtain_text_encoder_onnx(model_dir: Path = ROOT_DIR, hf_repo: str = None, force_convert: bool = False):
|
| 80 |
"""Obtains parvulus_text_encoder.onnx via Hugging Face download or local conversion."""
|
| 81 |
onnx_path = C_ENGINE_DIR / "parvulus_text_encoder.onnx"
|
| 82 |
+
is_submodel = model_dir.resolve() != ROOT_DIR.resolve()
|
| 83 |
+
must_convert = force_convert or is_submodel
|
| 84 |
+
|
| 85 |
+
if onnx_path.exists() and not must_convert:
|
| 86 |
print(f"[Prepare] Found existing {onnx_path.name} ({onnx_path.stat().st_size / (1024*1024):.1f} MB).")
|
| 87 |
return
|
| 88 |
|
| 89 |
repo_id = hf_repo or os.environ.get("PARVULUS_HF_REPO")
|
| 90 |
+
if repo_id and not must_convert:
|
| 91 |
print(f"\n[Prepare] Attempting to download {onnx_path.name} from Hugging Face Hub: '{repo_id}'...")
|
| 92 |
try:
|
| 93 |
from huggingface_hub import hf_hub_download
|
|
|
|
| 105 |
print(f"[Prepare] Hugging Face download from '{repo_id}' failed: {e}.")
|
| 106 |
print("[Prepare] Falling back to local conversion...")
|
| 107 |
|
| 108 |
+
st_path = _resolve_safetensors(model_dir)
|
| 109 |
+
print(f"\n[Prepare] Converting text encoder to ONNX locally from {st_path} (c_engine/export_text_encoder_onnx.py)...")
|
| 110 |
sys.path.insert(0, str(C_ENGINE_DIR))
|
| 111 |
from export_text_encoder_onnx import export_onnx
|
| 112 |
|
| 113 |
export_onnx(
|
| 114 |
+
weights_path=str(st_path),
|
| 115 |
output_path=str(onnx_path),
|
| 116 |
verify=True,
|
| 117 |
)
|
|
|
|
| 119 |
|
| 120 |
def main():
|
| 121 |
parser = argparse.ArgumentParser(description="Prepare PARVULUS Standalone Native Runtime.")
|
| 122 |
+
parser.add_argument(
|
| 123 |
+
"--model_dir",
|
| 124 |
+
type=str,
|
| 125 |
+
default=".",
|
| 126 |
+
help="Model directory containing parvulus.safetensors and action_scale.json (e.g. '.' or 'parvulus-post')",
|
| 127 |
+
)
|
| 128 |
+
parser.add_argument(
|
| 129 |
+
"--force_export",
|
| 130 |
+
action="store_true",
|
| 131 |
+
help="Overwrite existing c_engine/*.bin and ONNX files even when exporting from '.'",
|
| 132 |
+
)
|
| 133 |
parser.add_argument(
|
| 134 |
"--hf_repo",
|
| 135 |
type=str,
|
|
|
|
| 153 |
)
|
| 154 |
|
| 155 |
args = parser.parse_args()
|
| 156 |
+
model_dir = _resolve_model_dir(args.model_dir)
|
| 157 |
|
| 158 |
print("=" * 70)
|
| 159 |
print(" PREPARING PARVULUS STANDALONE RUNTIME")
|
| 160 |
+
print(f" Model Directory: {model_dir}")
|
| 161 |
print("=" * 70)
|
| 162 |
|
| 163 |
if args.build_c:
|
| 164 |
res = subprocess.run(["make", "clean"], cwd=str(C_ENGINE_DIR))
|
| 165 |
build_c_engine()
|
| 166 |
+
export_binary_assets(model_dir=model_dir, force=args.force_export)
|
| 167 |
|
| 168 |
if not args.skip_onnx:
|
| 169 |
+
obtain_text_encoder_onnx(model_dir=model_dir, hf_repo=args.hf_repo, force_convert=args.convert_onnx or args.force_export)
|
| 170 |
else:
|
| 171 |
print("[Prepare] Skipping ONNX preparation (--skip_onnx set).")
|
| 172 |
|