Skip to content

A compact, unified multimodal model family with a single shared vision–language backbone, built for on-device and in-app intelligence.

Add complete GPU and CPU inference examples

xiaoyuan1996d935468c3656
diff --git a/.gitignore b/.gitignore
index 375c977..5599303 100644
--- a/.gitignore
+++ b/.gitignore
@@ -18,6 +18,7 @@ venv/
# Logs / temp
*.log
tmp/
+examples/inference/results/
# Raw demo footage: only the compressed MP4 under assert/ is tracked
*.mov
diff --git a/README.md b/README.md
index e952893..2c57d5d 100644
--- a/README.md
+++ b/README.md
@@ -92,73 +92,96 @@ The same WePM-4B interprets game frames and interface text, retrieves local know
If the player above is not rendered by your Markdown viewer, open the [MP4 demo](assert/game_assistant_demo.mp4) directly.
-## Inference on NVIDIA GPU
+## Inference
-An approximate memory budget for BF16 inference:
+The examples in [`examples/inference`](examples/inference) load the complete `task_slots_v1` checkpoint, including MGVB, the independent embedding and decision slots, and their trained task heads. They support text and image inputs for generation, embedding extraction, and structured decision tasks.
-<table align="center">
- <thead>
- <tr><th>Precision</th><th>Weights</th><th>Recommended GPU memory</th></tr>
- </thead>
- <tbody>
- <tr><td>BF16</td><td>≈8 GB</td><td>≥16 GB (e.g. RTX 4090 / A100)</td></tr>
- <tr><td>FP16</td><td>≈8 GB</td><td>≥16 GB</td></tr>
- </tbody>
-</table>
+### Hardware and precision
-Install dependencies:
+| Device | Compute | Approximate weight memory | Recommended memory |
+| --- | --- | --- | --- |
+| NVIDIA GPU | BF16 | ≈8 GB | ≥16 GB GPU memory |
+| CPU | FP32 | ≈17 GiB | ≥24 GiB system memory |
+
+The GPU example uses one BF16-capable NVIDIA GPU. The CPU example disables CUDA before importing PyTorch and runs the same Hugging Face safetensors checkpoint in FP32.
+
+### Installation
+
+```bash
+cd examples/inference
+python -m venv .venv
+source .venv/bin/activate
+```
+
+Install PyTorch for the target device, followed by the shared dependencies.
+
+NVIDIA GPU (CUDA 12.8 example):
```bash
-pip install -r requirements.txt
+python -m pip install torch==2.10.0 torchvision==0.25.0 \
+ --index-url https://download.pytorch.org/whl/cu128
+python -m pip install -r requirements.txt
```
-Run the bundled script:
+CPU:
```bash
-python inference.py \
- --model ./checkpoints/WePM-4B \
- --image ./assert/wepm_function.png \
+python -m pip install torch==2.10.0 torchvision==0.25.0 \
+ --index-url https://download.pytorch.org/whl/cpu
+python -m pip install -r requirements.txt
+```
+
+Set the complete model directory. It must include `runtime_sources/`, `unimodel_aux.safetensors`, the tokenizer and processor files, and all Hugging Face shards.
+
+```bash
+export WEPM_MODEL=/path/to/WePM-HF
+```
+
+### NVIDIA GPU
+
+Text or image-conditioned generation:
+
+```bash
+CUDA_VISIBLE_DEVICES=0 python infer.py \
+ --model "$WEPM_MODEL" --task generate \
--prompt "Describe this figure in one sentence." \
- --max-new-tokens 256
+ --image ../../assert/wepm_function.png \
+ --max-new-tokens 64 --output results/gpu-generation.json
+```
+
+### CPU
+
+```bash
+python infer_cpu.py \
+ --model "$WEPM_MODEL" --task generate \
+ --prompt "Describe this figure in one sentence." \
+ --image ../../assert/wepm_function.png \
+ --threads 8 --max-new-tokens 32 \
+ --output results/cpu-generation.json
+```
+
+### Embedding and decision tasks
+
+Extract a normalized multimodal embedding on GPU:
+
+```bash
+CUDA_VISIBLE_DEVICES=0 python infer.py \
+ --model "$WEPM_MODEL" --task embed \
+ --prompt "A multimodal foundation model." \
+ --embedding-dim 1024 --output results/embedding.json
```
-`inference.py` loads the model with `device_map="auto"` and `torch.bfloat16`, applies the chat template, and prints the decoded answer. The core of it is:
-
-```python
-from transformers import AutoModelForImageTextToText, AutoProcessor
-
-model_path = "./checkpoints/WePM-4B"
-
-processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
-model = AutoModelForImageTextToText.from_pretrained(
- model_path,
- dtype=torch.bfloat16,
- device_map="auto",
- trust_remote_code=True,
-).eval()
-
-messages = [{
- "role": "user",
- "content": [
- {"type": "image", "path": "./assert/wepm_function.png"},
- {"type": "text", "text": "Describe this figure in one sentence."},
- ],
-}]
-inputs = processor.apply_chat_template(
- messages,
- add_generation_prompt=True,
- tokenize=True,
- return_dict=True,
- return_tensors="pt",
-).to(model.device)
-
-output_ids = model.generate(**inputs, max_new_tokens=256)
-answer = processor.tokenizer.decode(
- output_ids[0, inputs["input_ids"].shape[-1]:], skip_special_tokens=True
-)
-print(answer)
+Run the bundled structured decision example:
+
+```bash
+CUDA_VISIBLE_DEVICES=0 python infer.py \
+ --model "$WEPM_MODEL" --task decision \
+ --decision-json examples/decision.json \
+ --output results/decision.json
```
+For CPU embedding or decision inference, use `infer_cpu.py` and add `--threads 8`. Each command writes a JSON result, releases the model, and exits. See the [inference guide](examples/inference/README.md) for model layout, all arguments, image input, embedding dimensions, and decision request formats.
+
## Citation
If you find this work useful, please consider citing it:
diff --git a/examples/inference/README.md b/examples/inference/README.md
new file mode 100644
index 0000000..5687891
--- /dev/null
+++ b/examples/inference/README.md
@@ -0,0 +1,151 @@
+# WePM Inference Examples
+
+These examples run the complete `task_slots_v1` WePM checkpoint with Hugging Face Transformers. They support text and image inputs across three capability families:
+
+- `generate`: text or image-conditioned generation
+- `embed`: L2-normalized multimodal embeddings
+- `decision`: structured choice, score, and binary judgment
+
+Each invocation processes one request, writes a JSON result, releases the model, and exits.
+
+## Requirements
+
+The examples target Linux and Python 3.10–3.13. Create a virtual environment first:
+
+```bash
+python -m venv .venv
+source .venv/bin/activate
+```
+
+Install PyTorch for the target device.
+
+NVIDIA GPU (CUDA 12.8 example):
+
+```bash
+python -m pip install torch==2.10.0 torchvision==0.25.0 \
+ --index-url https://download.pytorch.org/whl/cu128
+python -m pip install -r requirements.txt
+```
+
+CPU:
+
+```bash
+python -m pip install torch==2.10.0 torchvision==0.25.0 \
+ --index-url https://download.pytorch.org/whl/cpu
+python -m pip install -r requirements.txt
+```
+
+For another CUDA version, select the matching PyTorch and torchvision wheels from the [PyTorch installation guide](https://pytorch.org/get-started/previous-versions/).
+
+## Model directory
+
+Set the path to the complete Hugging Face checkpoint:
+
+```bash
+export WEPM_MODEL=/path/to/WePM-HF
+```
+
+The directory must contain the model shards and all custom WePM assets:
+
+```text
+WePM-HF/
+├── config.json
+├── model-*.safetensors
+├── model.safetensors.index.json
+├── unimodel_aux.safetensors
+├── tokenizer.json
+├── tokenizer_config.json
+├── processor_config.json
+├── chat_template.jinja
+├── runtime_sources/
+└── export_complete.json
+```
+
+Do not remove `runtime_sources/` or `unimodel_aux.safetensors`: they contain the checkpoint-aligned MGVB implementation, task slots, embedding head, and decision head.
+
+## NVIDIA GPU
+
+The GPU entry uses BF16 on one CUDA device. At least 16 GiB of GPU memory is recommended.
+
+Text generation:
+
+```bash
+CUDA_VISIBLE_DEVICES=0 python infer.py \
+ --model "$WEPM_MODEL" --task generate \
+ --prompt 'Describe WePM in one sentence.' \
+ --max-new-tokens 64 --output results/generation.json
+```
+
+Image-conditioned generation:
+
+```bash
+CUDA_VISIBLE_DEVICES=0 python infer.py \
+ --model "$WEPM_MODEL" --task generate \
+ --prompt 'Describe this image.' --image /path/to/image.png \
+ --output results/image-generation.json
+```
+
+## CPU
+
+The CPU entry disables CUDA before importing PyTorch and loads the same safetensors checkpoint in FP32. Model weights require approximately 17 GiB of system memory; at least 24 GiB total memory is recommended.
+
+```bash
+python infer_cpu.py \
+ --model "$WEPM_MODEL" --task generate \
+ --prompt 'Describe WePM in one sentence.' \
+ --threads 8 --max-new-tokens 32 \
+ --output results/cpu-generation.json
+```
+
+## Embeddings
+
+Text embedding on GPU:
+
+```bash
+CUDA_VISIBLE_DEVICES=0 python infer.py \
+ --model "$WEPM_MODEL" --task embed \
+ --prompt 'A cat is sitting by the window.' \
+ --embedding-dim 1024 --output results/text-embedding.json
+```
+
+For CPU, replace `infer.py` with `infer_cpu.py` and add `--threads 8`.
+
+Image embedding accepts one or more `--image` arguments. Text and images can also be supplied together. Supported dimensions are 64, 128, 256, 512, 1024, and 2048. The vectors are L2-normalized and stored under `embedding.embeddings`.
+
+## Structured decision
+
+Run the bundled choice example on GPU:
+
+```bash
+CUDA_VISIBLE_DEVICES=0 python infer.py \
+ --model "$WEPM_MODEL" --task decision \
+ --decision-json examples/decision.json \
+ --output results/decision.json
+```
+
+For CPU, replace `infer.py` with `infer_cpu.py` and add `--threads 8`.
+
+The request uses `state` for the content being evaluated and `questions.q` for the task definition:
+
+- `choice`: `criteria` maps ordered candidate IDs to descriptions.
+- `score`: `criteria` is an ordered list of score descriptions.
+- `noul`: no `criteria` is provided; the result is the probability that the statement holds.
+
+Local decision images can be supplied with repeated `--image` arguments. Alternatively, the request JSON may contain base64 image data URLs. Do not use both forms in one request.
+
+## Main arguments
+
+| Argument | Description |
+| --- | --- |
+| `--model` | Complete local WePM Hugging Face directory |
+| `--task` | `generate`, `embed`, `both`, or `decision` |
+| `--prompt` | Text input |
+| `--image` | Local image path; may be repeated |
+| `--decision-json` | Structured decision request; required only for `decision` |
+| `--max-new-tokens` | Generation length from 1 to 512 |
+| `--embedding-dim` | Embedding dimension; default 2048 |
+| `--threads` | CPU compute threads; default 8 |
+| `--timeout` | Maximum runtime in seconds; default 1200 |
+| `--output` | New JSON output path; required and must not already exist |
+
+Generation uses greedy decoding and each process handles one request at a time.
diff --git a/examples/inference/common.py b/examples/inference/common.py
new file mode 100644
index 0000000..6e533c2
--- /dev/null
+++ b/examples/inference/common.py
@@ -0,0 +1,121 @@
+"""File utilities and standalone imports of the checkpoint's model code."""
+
+from __future__ import annotations
+
+import ast
+import hashlib
+import importlib.util
+import json
+import sys
+import types
+from pathlib import Path
+
+
+def write_json(path: Path, payload) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = path.with_suffix(path.suffix + ".tmp")
+ temporary.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n")
+ temporary.replace(path)
+
+
+def sha256(path: Path) -> str:
+ result = hashlib.sha256()
+ with path.open("rb") as stream:
+ for block in iter(lambda: stream.read(4 * 1024 * 1024), b""):
+ result.update(block)
+ return result.hexdigest()
+
+
+def load_file(name: str, path: Path):
+ spec = importlib.util.spec_from_file_location(name, path)
+ if spec is None or spec.loader is None:
+ raise ImportError(str(path))
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+def load_contracts(source: Path):
+ """Load the checkpoint's own task routing, decision protocol and geometry."""
+ name = (
+ "_wepm_nvidia_"
+ + hashlib.sha256(str(source.resolve()).encode()).hexdigest()[:16]
+ )
+ package = types.ModuleType(name)
+ package.__path__ = [str(source)]
+ sys.modules[name] = package
+ modules = {
+ key: load_file(f"{name}.{key}", source / f"{key}.py")
+ for key in (
+ "generation_slots",
+ "decision_config",
+ "decision_protocol",
+ "image_geometry",
+ )
+ }
+ return types.SimpleNamespace(**modules)
+
+
+def validate_architecture(config, contracts):
+ """Accept the formal task_slots_v1 direct-J architecture, never legacy slots."""
+ if config.get("unimodel_decision_enable") is not True:
+ raise ValueError("this runtime requires the new JEV task_slots_v1 checkpoint")
+ contracts.decision_config.validate_task_slots(config, checkpoint=True)
+ decision = contracts.decision_config.DecisionConfig.from_config(config)
+ if decision.head_type != "direct":
+ raise ValueError("the NVIDIA example requires the trained direct decision head")
+ if (
+ config.get("unimodel_decision_input_profile")
+ != contracts.decision_protocol.INPUT_PROFILE
+ ):
+ raise ValueError("checkpoint decision input protocol is incompatible")
+ if not config.get("unimodel_slot_enable") or not config.get("unimodel_mgvb_enable"):
+ raise ValueError("the formal model requires E/J slots and MGVB")
+ if config.get("unimodel_ds_lora_enable") or config.get("unimodel_mgve_enable"):
+ raise ValueError("DS-LoRA/MGVE are not part of this architecture")
+ return decision
+
+
+def load_runtime_sources(source: Path):
+ """Reuse canonical math without importing Megatron, VeRL, or XPU packages."""
+ geometry = load_file("_unimodel_hf_geometry", source / "mgvb_utils.py")
+ tree = ast.parse((source / "mgvb.py").read_text())
+ for node in tree.body:
+ if (
+ isinstance(node, ast.ImportFrom)
+ and node.module == "mbridge.models.qwen3_5.mgvb_utils"
+ ):
+ node.module = geometry.__name__
+ module = types.ModuleType("_unimodel_hf_mgvb")
+ sys.modules[module.__name__] = module
+ # Execute the frozen module after replacing its Megatron-dependent import.
+ exec(compile(tree, str(source / "mgvb.py"), "exec"), module.__dict__) # noqa: S102
+
+ # The standalone function only needs torch; the original file's other
+ # imports initialize Megatron and transformer-engine unnecessarily.
+ rope_tree = ast.parse((source / "rope_utils.py").read_text())
+ function = next(
+ n
+ for n in rope_tree.body
+ if isinstance(n, ast.FunctionDef) and n.name == "get_rope_index"
+ )
+ standalone = ast.Module(
+ body=[
+ ast.ImportFrom(
+ module="__future__", names=[ast.alias(name="annotations")], level=0
+ ),
+ function,
+ ],
+ type_ignores=[],
+ )
+ import torch
+
+ namespace = {"torch": torch}
+ exec( # noqa: S102 -- import the canonical RoPE function without Megatron
+ compile(
+ ast.fix_missing_locations(standalone), str(source / "rope_utils.py"), "exec"
+ ),
+ namespace,
+ )
+ return module.MultiGranularityVisualBottleneck, namespace["get_rope_index"]
diff --git a/examples/inference/examples/decision.json b/examples/inference/examples/decision.json
new file mode 100644
index 0000000..0cbc2f7
--- /dev/null
+++ b/examples/inference/examples/decision.json
@@ -0,0 +1,14 @@
+{
+ "state": "A customer received the wrong item and asks for a replacement.",
+ "questions": {
+ "q": {
+ "type": "choice",
+ "instructions": "Choose the response that best addresses the customer's request.",
+ "criteria": {
+ "replace": "Apologize and arrange a replacement for the correct item.",
+ "ignore": "Ignore the request and close the conversation.",
+ "refuse": "Tell the customer that no help is available."
+ }
+ }
+ }
+}
diff --git a/examples/inference/infer.py b/examples/inference/infer.py
new file mode 100755
index 0000000..34ab977
--- /dev/null
+++ b/examples/inference/infer.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python3
+"""Finite G/E/J inference with Transformers on CPU or CUDA; save JSON and exit."""
+
+import argparse
+import gc
+import json
+import signal
+from pathlib import Path
+
+import torch
+from common import write_json
+from runtime import UniModelTransformers, wait_for_gpu
+
+
+def main(*, device="cuda:0"):
+ device = torch.device(device)
+ is_cpu = device.type == "cpu"
+ parser = argparse.ArgumentParser(description=f"{__doc__} Device: {device}.")
+ parser.add_argument(
+ "--model",
+ type=Path,
+ required=True,
+ help="complete local Hugging Face model directory",
+ )
+ parser.add_argument(
+ "--task", choices=["generate", "embed", "both", "decision"], default="generate"
+ )
+ parser.add_argument("--prompt", default="请用一句话介绍你自己。")
+ parser.add_argument("--image", type=Path, action="append", default=[])
+ parser.add_argument(
+ "--decision-json",
+ type=Path,
+ help="SystemOne request with state and questions.q",
+ )
+ parser.add_argument("--max-new-tokens", type=int, default=32 if is_cpu else 64)
+ if is_cpu:
+ parser.add_argument(
+ "--threads", type=int, default=8, help="CPU compute threads (default: 8)"
+ )
+ parser.add_argument(
+ "--embedding-dim",
+ type=int,
+ choices=[64, 128, 256, 512, 1024, 2048],
+ default=2048,
+ )
+ parser.add_argument(
+ "--timeout",
+ type=int,
+ default=1200,
+ help="Maximum inference lifetime in seconds (1-1800)",
+ )
+ parser.add_argument("--output", type=Path, required=True)
+ args = parser.parse_args()
+ if not 1 <= args.max_new_tokens <= 512 or not 1 <= args.timeout <= 1800:
+ parser.error("max-new-tokens must be in [1, 512] and timeout in [1, 1800]")
+ if is_cpu:
+ if args.threads < 1:
+ parser.error("threads must be positive")
+ torch.set_num_threads(args.threads)
+ torch.set_num_interop_threads(1)
+ if (args.task == "decision") != (args.decision_json is not None):
+ parser.error("--decision-json is required only with --task decision")
+ decision_request = (
+ json.loads(args.decision_json.read_text()) if args.decision_json else None
+ )
+ if args.output.exists():
+ raise FileExistsError(args.output)
+
+ def timeout_handler(_signum, _frame):
+ raise TimeoutError(f"inference exceeded {args.timeout} seconds")
+
+ signal.signal(signal.SIGALRM, timeout_handler)
+ signal.alarm(args.timeout)
+ probe = None
+ model = None
+ try:
+ if not is_cpu:
+ probe = wait_for_gpu()
+ backend = "hf"
+ model = UniModelTransformers(args.model, device=device)
+ result = {}
+ if args.task in ("generate", "both"):
+ result["generation"] = model.generate(
+ args.prompt, args.image, args.max_new_tokens
+ )
+ if args.task in ("embed", "both"):
+ result["embedding"] = model.embed(
+ args.prompt, args.image, dims=[args.embedding_dim]
+ )
+ if args.task == "decision":
+ result["decision"] = model.decide(decision_request, args.image)
+ write_json(args.output, result)
+ print(
+ json.dumps(
+ {
+ "output": str(args.output),
+ "device": str(model.device),
+ "backend": backend,
+ "language_precision": str(model.dtype),
+ "dtype": str(model.dtype),
+ "generation": result.get("generation", {}).get("text"),
+ "decision": result.get("decision", {}).get("answers"),
+ },
+ ensure_ascii=False,
+ )
+ )
+ finally:
+ if model is not None and hasattr(model, "close"):
+ model.close()
+ del model, probe
+ gc.collect()
+ if not is_cpu:
+ torch.cuda.empty_cache()
+ signal.alarm(0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/inference/infer_cpu.py b/examples/inference/infer_cpu.py
new file mode 100755
index 0000000..d68c409
--- /dev/null
+++ b/examples/inference/infer_cpu.py
@@ -0,0 +1,17 @@
+#!/usr/bin/env python3
+"""Run Hugging Face G/E/J inference on CPU, then exit."""
+
+import os
+
+
+def main():
+ # Set visibility before importing PyTorch or Transformers. The CPU path
+ # neither waits for the GPU keeper nor initializes a CUDA context.
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
+ from infer import main as run_inference
+
+ run_inference(device="cpu")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/inference/requirements.txt b/examples/inference/requirements.txt
new file mode 100644
index 0000000..dfe2104
--- /dev/null
+++ b/examples/inference/requirements.txt
@@ -0,0 +1,8 @@
+torch==2.10.0
+torchvision==0.25.0
+transformers==5.3.0
+accelerate==1.14.0
+safetensors==0.8.0
+Pillow==12.3.0
+Jinja2==3.1.6
+numpy==2.2.6
diff --git a/examples/inference/runtime.py b/examples/inference/runtime.py
new file mode 100644
index 0000000..3beafb0
--- /dev/null
+++ b/examples/inference/runtime.py
@@ -0,0 +1,395 @@
+"""Transformers CPU/CUDA inference for the formal task_slots_v1 G/E/J model."""
+
+from __future__ import annotations
+
+import io
+import json
+import time
+from pathlib import Path
+
+import torch
+import torch.nn.functional as F
+from common import load_contracts, load_runtime_sources, validate_architecture
+from PIL import Image
+from safetensors.torch import load_file
+from transformers import AutoProcessor, Qwen3_5ForConditionalGeneration
+
+
+def load_images(paths, prepare_image):
+ """Apply the training-aligned RGB and longest-edge resize policy."""
+ images = []
+ for path in paths:
+ with Image.open(
+ io.BytesIO(path) if isinstance(path, bytes) else path
+ ) as original:
+ image = original.convert("RGB")
+ images.append(prepare_image(image))
+ return images
+
+
+def wait_for_gpu(min_free_gib=14, timeout=120):
+ """Wait for sufficient free CUDA memory before loading the model."""
+ probe = torch.empty(256 * 1024, device="cuda", dtype=torch.float32)
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ free, total = torch.cuda.mem_get_info()
+ if free >= min_free_gib * 2**30:
+ print(
+ f"CUDA ready: {free / 2**30:.1f}/{total / 2**30:.1f} GiB free",
+ flush=True,
+ )
+ return probe
+ time.sleep(2)
+ raise RuntimeError(
+ f"CUDA memory did not reach {min_free_gib} GiB free within {timeout}s"
+ )
+
+
+class UniModelTransformers:
+ """Qwen3.5 + MGVB + independent E/J slots and trained task heads.
+
+ Each call accepts one text/image request. Generation uses a KV/recurrent
+ cache and no slot. E reads the embedding slot and applies the normalized
+ projection; J reads its own slot and applies the direct candidate-index head.
+ """
+
+ def __init__(self, model_dir: str | Path, device="cuda:0"):
+ self.model_dir = Path(model_dir).resolve()
+ manifest = json.loads((self.model_dir / "export_complete.json").read_text())
+ if manifest.get("schema") != "wepm-nvidia-task-slots-v1":
+ raise ValueError("a complete WePM Hugging Face model directory is required")
+ self.config = json.loads((self.model_dir / "config.json").read_text())
+ c = self.config
+ self.contracts = load_contracts(self.model_dir / "runtime_sources")
+ self.decision_config = validate_architecture(c, self.contracts)
+ self.device = torch.device(device)
+ if self.device.type not in {"cpu", "cuda"}:
+ raise ValueError("supported inference devices are cpu and cuda")
+ # FP32 also works on CPUs without native BF16 instructions. CUDA keeps
+ # the BF16 path used by training and the verified NVIDIA example.
+ self.dtype = torch.float32 if self.device.type == "cpu" else torch.bfloat16
+ self.model, self.loading_info = Qwen3_5ForConditionalGeneration.from_pretrained(
+ self.model_dir,
+ dtype=self.dtype,
+ device_map={"": str(self.device)},
+ attn_implementation="sdpa",
+ local_files_only=True,
+ output_loading_info=True,
+ )
+ for key in ("missing_keys", "unexpected_keys", "mismatched_keys", "error_msgs"):
+ if self.loading_info.get(key):
+ raise ValueError(f"incomplete HF load: {key}={self.loading_info[key]}")
+ self.loading_info = {
+ key: sorted(value) if isinstance(value, set) else value
+ for key, value in self.loading_info.items()
+ }
+ self.model.eval()
+ self.processor = AutoProcessor.from_pretrained(
+ self.model_dir, local_files_only=True
+ )
+ if not self.processor.chat_template:
+ raise ValueError("missing saved training chat template")
+ self.processor.tokenizer.chat_template = self.processor.chat_template
+ self.slot_token_id = self.processor.tokenizer.pad_token_id
+ if self.slot_token_id is None:
+ self.slot_token_id = self.processor.tokenizer.eos_token_id
+ auxiliary = load_file(
+ self.model_dir / "unimodel_aux.safetensors", device=str(self.device)
+ )
+ self.slots = {
+ role: auxiliary.pop(f"unimodel.slot_pooler.{role}_slot").to(self.dtype)
+ for role in ("embedding", "decision")
+ }
+ self.head = auxiliary.pop("unimodel.embedding_head.weight").to(self.dtype)
+ self.decision_head = auxiliary.pop("unimodel.decision_head.output.weight").to(
+ self.dtype
+ )
+ hidden = c["text_config"]["hidden_size"]
+ if any(tuple(slot.shape) != (hidden,) for slot in self.slots.values()) or tuple(
+ self.head.shape
+ ) != (
+ c["unimodel_embedding_dim"],
+ hidden,
+ ):
+ raise ValueError("slot/head shape mismatch")
+ if tuple(self.decision_head.shape) != (
+ self.decision_config.output_size,
+ hidden,
+ ):
+ raise ValueError("direct decision head shape mismatch")
+ cls, self.get_rope_index = load_runtime_sources(
+ self.model_dir / "runtime_sources"
+ )
+ if not c.get("unimodel_mgvb_enable"):
+ raise ValueError(
+ "this example requires a UniModel checkpoint with MGVB enabled"
+ )
+ self.mgvb = cls(
+ hidden,
+ adapter_dim=c["unimodel_mgvb_adapter_dim"],
+ token_budget=c["unimodel_mgvb_token_budget"],
+ global_tokens=c["unimodel_mgvb_global_tokens"],
+ region_tokens=c["unimodel_mgvb_region_tokens"],
+ num_global_heads=c["unimodel_mgvb_num_global_heads"],
+ device=self.device,
+ dtype=self.dtype,
+ )
+ prefix = "unimodel.mgvb."
+ if any(not k.startswith(prefix) for k in auxiliary):
+ raise ValueError(f"unknown auxiliary weights: {sorted(auxiliary)}")
+ self.mgvb.load_state_dict(
+ {k.removeprefix(prefix): v for k, v in auxiliary.items()}, strict=True
+ )
+ self.mgvb.eval()
+
+ def _compact_image_tokens(self, ids, grids):
+ """Reserve exactly min(native length, MGVB budget) placeholders per image."""
+ merge = self.config["vision_config"]["spatial_merge_size"]
+ image_id = self.config["image_token_id"]
+ native_lengths = (grids.prod(-1) // merge**2).tolist()
+ compact_lengths = [min(int(n), self.mgvb.token_budget) for n in native_lengths]
+ indices = torch.nonzero(ids[0] == image_id).flatten()
+ spans = torch.split(indices, [int(n) for n in native_lengths])
+ keep = torch.ones(ids.shape[1], dtype=torch.bool, device=self.device)
+ for span, count in zip(spans, compact_lengths, strict=True):
+ if not torch.all(torch.diff(span) == 1):
+ raise ValueError("non-contiguous image placeholders")
+ keep[span[count:]] = False
+ return ids[:, keep], native_lengths, compact_lengths
+
+ def _text_query(self, ids, embeddings, slot_role):
+ """Build the training MGVB mean+last query from non-special prompt tokens."""
+ mask = torch.ones_like(ids, dtype=torch.bool)
+ for token_id in self.processor.tokenizer.all_special_ids:
+ mask &= ids != token_id
+ if slot_role is not None:
+ mask[:, -1] = False
+ count = mask.sum(dim=1)
+ if not int(count[0]):
+ return None
+ mean = (embeddings * mask.unsqueeze(-1)).sum(dim=1) / count.to(
+ self.dtype
+ ).unsqueeze(-1)
+ last = embeddings[:, torch.nonzero(mask[0]).flatten()[-1], :]
+ return torch.cat([mean, last], dim=-1)[0]
+
+ def _encode_images(self, pixels, grids, query):
+ """Run native ViT/merger, then the learned MGVB in image order."""
+ pixels = pixels.to(self.device, self.dtype)
+ patches = torch.split(pixels, [int(n) for n in grids.prod(-1).tolist()])
+ native_features = []
+ for patch, grid in zip(patches, grids, strict=True):
+ visual = self.model.model.get_image_features(
+ patch, grid.unsqueeze(0), return_dict=True
+ )
+ native_features.append(visual.pooler_output[0])
+ return self.mgvb(
+ native_features,
+ image_grid_thw=grids,
+ query_embeddings=[query] * len(native_features),
+ spatial_merge_size=self.config["vision_config"]["spatial_merge_size"],
+ )
+
+ @torch.inference_mode()
+ def _prepare_inputs(self, prompt: str, images, *, task: str):
+ if task not in {"generate", "embedding", "decision"}:
+ raise ValueError(f"unknown task: {task}")
+ generation = task == "generate"
+ slot_role = None if generation else task
+ if not prompt.strip() and not images:
+ raise ValueError("an image or nonempty prompt is required")
+ loaded_images = load_images(
+ images, self.contracts.image_geometry.prepare_model_image
+ )
+ content = [{"type": "image", "image": image} for image in loaded_images]
+ if prompt:
+ content.append({"type": "text", "text": prompt})
+ rendered = self.processor.apply_chat_template(
+ [{"role": "user", "content": content}],
+ tokenize=False,
+ add_generation_prompt=generation,
+ enable_thinking=False,
+ )
+ encoded = self.processor(
+ text=[rendered], images=loaded_images or None, return_tensors="pt"
+ )
+ ids = encoded["input_ids"].to(self.device)
+ if ids.shape[0] != 1:
+ raise ValueError("only unpadded single-request inference is supported")
+ if slot_role is not None:
+ ids = torch.cat(
+ [ids, torch.tensor([[self.slot_token_id]], device=self.device)], dim=1
+ )
+ grids = encoded.get("image_grid_thw")
+ positions, native_lengths, compact_lengths = [], [], []
+ if grids is not None:
+ grids = grids.to(self.device)
+ ids, native_lengths, compact_lengths = self._compact_image_tokens(
+ ids, grids
+ )
+ embeddings = self.model.get_input_embeddings()(ids)
+ # Only the appended position is a soft slot. Literal pad tokens in
+ # the prompt and generated tokens always retain native embeddings.
+ if slot_role is not None:
+ embeddings[:, -1, :] = self.slots[slot_role]
+ if grids is not None:
+ compressed = self._encode_images(
+ encoded["pixel_values"],
+ grids,
+ self._text_query(ids, embeddings, slot_role),
+ )
+ positions = compressed.positions
+ features = torch.cat(compressed.embeddings)
+ mask = ids[0] == self.config["image_token_id"]
+ if int(mask.sum()) != features.shape[0]:
+ raise ValueError("MGVB image-feature/placeholder mismatch")
+ embeddings[0, mask, :] = features.to(self.dtype)
+ rope, delta = self.get_rope_index(
+ spatial_merge_size=self.config["vision_config"]["spatial_merge_size"],
+ image_token_id=self.config["image_token_id"],
+ video_token_id=self.config["video_token_id"],
+ vision_start_token_id=self.config["vision_start_token_id"],
+ input_ids=ids,
+ image_grid_thw=grids,
+ image_position_ids=positions if grids is not None else None,
+ attention_mask=torch.ones_like(ids),
+ )
+ text_positions = torch.arange(ids.shape[1], device=self.device).view(1, 1, -1)
+ position_ids = torch.cat([text_positions, rope], dim=0)
+ metadata = {
+ "input_tokens": ids.shape[1],
+ "native_visual_tokens": native_lengths,
+ "compact_visual_tokens": compact_lengths,
+ "slot_positions": [ids.shape[1] - 1] if slot_role is not None else [],
+ "slot_role": slot_role,
+ "mrope_delta": int(delta[0, 0]),
+ "generation_prompt": generation,
+ }
+ return ids, embeddings, position_ids, metadata
+
+ @torch.inference_mode()
+ def generate(self, prompt, images=(), max_new_tokens=64):
+ """Greedy generation using the Transformers text model's native cache."""
+ if not 0 < max_new_tokens <= 512:
+ raise ValueError("max_new_tokens must be in [1, 512]")
+ start = time.monotonic()
+ ids, embeddings, positions, metadata = self._prepare_inputs(
+ prompt, images, task="generate"
+ )
+ result = self.model.model.language_model(
+ inputs_embeds=embeddings,
+ position_ids=positions,
+ use_cache=True,
+ return_dict=True,
+ )
+ cache = result.past_key_values
+ hidden = result.last_hidden_state[:, -1:, :]
+ rope_start = int(positions[1:].max()) + 1
+ stop_ids = {self.config["eos_token_id"], self.processor.tokenizer.eos_token_id}
+ generated = []
+ finish = "length"
+ for index in range(max_new_tokens):
+ logits = self.model.lm_head(hidden)[:, -1, :].float()
+ if not torch.isfinite(logits).all():
+ raise ValueError("nonfinite generation logits")
+ token = logits.argmax(dim=-1)
+ generated.append(int(token[0]))
+ if int(token[0]) in stop_ids:
+ finish = "eos"
+ break
+ if index + 1 == max_new_tokens:
+ break
+ pos = torch.full(
+ (4, 1, 1), rope_start + index, dtype=torch.long, device=self.device
+ )
+ pos[0] = ids.shape[1] + index
+ result = self.model.model.language_model(
+ input_ids=token[:, None],
+ position_ids=pos,
+ past_key_values=cache,
+ use_cache=True,
+ return_dict=True,
+ )
+ hidden, cache = result.last_hidden_state, result.past_key_values
+ return {
+ "text": self.processor.tokenizer.decode(
+ generated, skip_special_tokens=True
+ ),
+ "token_ids": generated,
+ "finish_reason": finish,
+ "seconds": time.monotonic() - start,
+ "input": metadata,
+ }
+
+ @torch.inference_mode()
+ def embed(self, prompt, images=(), *, dims=None):
+ """Return normalized embedding vectors at the requested MRL dimensions."""
+ start = time.monotonic()
+ _, embeddings, positions, metadata = self._prepare_inputs(
+ prompt, images, task="embedding"
+ )
+ result = self.model.model.language_model(
+ inputs_embeds=embeddings,
+ position_ids=positions,
+ use_cache=False,
+ return_dict=True,
+ )
+ # Training projects in the model dtype before FP32 L2 normalization.
+ projected = F.linear(result.last_hidden_state[:, -1, :], self.head).float()
+ if not torch.isfinite(projected).all() or projected.norm() == 0:
+ raise ValueError("nonfinite or zero embedding")
+ dims = dims or self.config["unimodel_embedding_mrl_dims"]
+ allowed = set(self.config["unimodel_embedding_mrl_dims"])
+ if any(d not in allowed for d in dims):
+ raise ValueError(f"dimensions must be chosen from {sorted(allowed)}")
+ vectors = {
+ str(dim): F.normalize(projected[:, :dim], dim=-1)[0].cpu().tolist()
+ for dim in dims
+ }
+ return {
+ "embeddings": vectors,
+ "seconds": time.monotonic() - start,
+ "input": metadata,
+ }
+
+ @torch.inference_mode()
+ def decide(self, request, images=()):
+ """Evaluate one SystemOne choice/score/noul request using the J slot."""
+ start = time.monotonic()
+ protocol = self.contracts.decision_protocol
+ value = protocol.request_input(request)
+ count = len(value.ids)
+ if count > self.decision_config.max_candidates:
+ raise ValueError("candidate count exceeds the trained direct head capacity")
+ wire_images = protocol.request_images(request)
+ if images and wire_images:
+ raise ValueError("use either local --image inputs or JSON image data URLs")
+ if len(images) > 8 or sum(map(len, wire_images)) > 64 * 1024 * 1024:
+ raise ValueError(
+ "decision supports at most eight images and 64 MiB of image bytes"
+ )
+ _, embeddings, positions, metadata = self._prepare_inputs(
+ protocol.render_input(value)[0],
+ images or wire_images,
+ task="decision",
+ )
+ result = self.model.model.language_model(
+ inputs_embeds=embeddings,
+ position_ids=positions,
+ use_cache=False,
+ return_dict=True,
+ )
+ # The direct head maps h_J to option indices. E normalization and
+ # physical padding rows must never enter the candidate distribution.
+ logits = F.linear(
+ result.last_hidden_state[:, -1, :], self.decision_head
+ ).float()[0, :count]
+ if not torch.isfinite(logits).all():
+ raise ValueError("nonfinite decision logits")
+ probabilities = logits.softmax(dim=-1).cpu().tolist()
+ return {
+ **protocol.response_from_probabilities(value, probabilities),
+ "candidate_count": count,
+ "seconds": time.monotonic() - start,
+ "input": metadata,
+ }
diff --git a/inference.py b/inference.py
deleted file mode 100644
index 5ce7288..0000000
--- a/inference.py
+++ /dev/null
@@ -1,86 +0,0 @@
-"""Minimal single-GPU inference example for WePM-4B.
-
-Usage:
- python inference.py --image ./assert/wepm_function.png \
- --prompt "Describe this figure in one sentence."
-"""
-
-import argparse
-from pathlib import Path
-
-import torch
-from transformers import AutoModelForImageTextToText, AutoProcessor
-
-DEFAULT_MODEL = "./checkpoints/WePM-4B"
-
-
-def load_model(model_path: str, dtype: str, device_map: str):
- processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
- model = AutoModelForImageTextToText.from_pretrained(
- model_path,
- dtype=getattr(torch, dtype),
- device_map=device_map,
- trust_remote_code=True,
- )
- model.eval()
- return model, processor
-
-
-def build_inputs(processor, image_path: str, prompt: str):
- messages = [
- {
- "role": "user",
- "content": [
- {"type": "image", "path": image_path},
- {"type": "text", "text": prompt},
- ],
- }
- ]
- return processor.apply_chat_template(
- messages,
- add_generation_prompt=True,
- tokenize=True,
- return_dict=True,
- return_tensors="pt",
- )
-
-
-def generate(model, processor, inputs, max_new_tokens: int) -> str:
- inputs = inputs.to(model.device)
- output_ids = model.generate(**inputs, max_new_tokens=max_new_tokens)
- new_tokens = output_ids[0, inputs["input_ids"].shape[-1] :]
- tokenizer = getattr(processor, "tokenizer", processor)
- return tokenizer.decode(new_tokens, skip_special_tokens=True)
-
-
-def main() -> None:
- parser = argparse.ArgumentParser(description="WePM-4B single-image inference")
- parser.add_argument("--model", default=DEFAULT_MODEL, help="model directory or hub id")
- parser.add_argument("--image", required=True, help="path to one local image")
- parser.add_argument(
- "--prompt",
- default="Describe this image in one sentence.",
- help="user instruction paired with the image",
- )
- parser.add_argument("--max-new-tokens", type=int, default=256)
- parser.add_argument(
- "--dtype", default="bfloat16", choices=["bfloat16", "float16"], help="compute dtype"
- )
- parser.add_argument(
- "--device-map",
- default="auto",
- help='device placement, e.g. "auto" or "cuda:0"',
- )
- args = parser.parse_args()
-
- if not Path(args.image).is_file():
- raise FileNotFoundError(f"image not found: {args.image}")
-
- model, processor = load_model(args.model, args.dtype, args.device_map)
- inputs = build_inputs(processor, args.image, args.prompt)
- print(generate(model, processor, inputs, args.max_new_tokens))
-
-
-if __name__ == "__main__":
- main()
diff --git a/requirements.txt b/requirements.txt
deleted file mode 100644
index 7f3c9aa..0000000
--- a/requirements.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-torch>=2.4.0
-transformers>=4.56.0
-accelerate>=1.1.0
-pillow>=10.0.0
-sentencepiece>=0.2.0