Skip to content

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

Reorganize inference runtime and device examples

xiaoyuan1996dc5a3fa1c0a8
diff --git a/.gitignore b/.gitignore
index 5599303..5f3883f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -18,7 +18,7 @@ venv/
# Logs / temp
*.log
tmp/
-examples/inference/results/
+examples/**/results/
# Raw demo footage: only the compressed MP4 under assert/ is tracked
*.mov
diff --git a/README.md b/README.md
index 75db893..b4c12ea 100644
--- a/README.md
+++ b/README.md
@@ -94,7 +94,17 @@ If the player above is not rendered by your Markdown viewer, open the [MP4 demo]
## 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.
+The repository keeps runtime code, runnable cases, and model weights separate:
+
+```text
+inference/ # Complete inference implementation
+examples/gpu/ # NVIDIA GPU task cases and input assets
+examples/cpu/ # CPU task cases and input assets
+checkpoints/huggingface # Hugging Face safetensors checkpoint
+checkpoints/gguf/ # Hybrid GGUF bundle (not ONNX)
+```
+
+The current runnable examples use the complete Hugging Face checkpoint and support generation, embedding extraction, and structured decision. Generation cases cover single-text, single-image, and ordered text–image interleaving.
### Hardware and precision
@@ -103,24 +113,19 @@ The examples in [`examples/inference`](examples/inference) load the complete `ta
| 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
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
+python -m pip install -r inference/requirements.txt
```
CPU:
@@ -128,97 +133,56 @@ 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
+python -m pip install -r inference/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
-```
+The scripts use `checkpoints/huggingface` by default. Set `WEPM_MODEL` to use another complete Hugging Face checkpoint.
### NVIDIA GPU inference
-#### Text generation
+#### Generation: single text, single image, or interleaved content
```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/gpu-text-generation.json
-```
-
-#### Image-conditioned generation
-
-```bash
-CUDA_VISIBLE_DEVICES=0 python infer.py \
- --model "$WEPM_MODEL" --task generate \
- --prompt "Describe this figure in one sentence." \
- --image ../../assert/wepm_function.png \
- --max-new-tokens 64 --output results/gpu-image-generation.json
+bash examples/gpu/generation/run.sh single_text
+bash examples/gpu/generation/run.sh single_image
+bash examples/gpu/generation/run.sh interleaved
```
#### Embedding extraction
```bash
-CUDA_VISIBLE_DEVICES=0 python infer.py \
- --model "$WEPM_MODEL" --task embed \
- --prompt "A multimodal foundation model." \
- --embedding-dim 1024 --output results/gpu-embedding.json
+bash examples/gpu/embedding/run.sh
```
#### Structured decision
```bash
-CUDA_VISIBLE_DEVICES=0 python infer.py \
- --model "$WEPM_MODEL" --task decision \
- --decision-json examples/decision.json \
- --output results/gpu-decision.json
+bash examples/gpu/decision/run.sh
```
### CPU inference
-#### Text generation
-
-```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-text-generation.json
-```
-
-#### Image-conditioned generation
+#### Generation: single text, single image, or interleaved content
```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-image-generation.json
+bash examples/cpu/generation/run.sh single_text
+bash examples/cpu/generation/run.sh single_image
+bash examples/cpu/generation/run.sh interleaved
```
#### Embedding extraction
```bash
-python infer_cpu.py \
- --model "$WEPM_MODEL" --task embed \
- --prompt "A multimodal foundation model." \
- --embedding-dim 1024 --threads 8 \
- --output results/cpu-embedding.json
+bash examples/cpu/embedding/run.sh
```
#### Structured decision
```bash
-python infer_cpu.py \
- --model "$WEPM_MODEL" --task decision \
- --decision-json examples/decision.json --threads 8 \
- --output results/cpu-decision.json
+bash examples/cpu/decision/run.sh
```
-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.
+Each command writes a timestamped JSON result, releases the model, and exits. See the [inference guide](inference/README.md) for the CLI and ordered multimodal input format, and the [examples guide](examples/README.md) for all runnable cases.
## Citation
diff --git a/checkpoints/README.md b/checkpoints/README.md
new file mode 100644
index 0000000..2b40af2
--- /dev/null
+++ b/checkpoints/README.md
@@ -0,0 +1,6 @@
+# WePM Checkpoints
+
+- `huggingface/`: complete Hugging Face safetensors checkpoint used by the current GPU and CPU examples.
+- `gguf/`: hybrid GGUF bundle for the language backbone and multimodal/task modules. It is not an ONNX model and requires the complete bundle plus the matching native runtime.
+
+Large weight files are stored with Git LFS. Clone with Git LFS enabled so model pointers are replaced by their binary contents.
diff --git a/examples/README.md b/examples/README.md
new file mode 100644
index 0000000..28f8562
--- /dev/null
+++ b/examples/README.md
@@ -0,0 +1,53 @@
+# WePM Inference Examples
+
+The runnable examples are grouped by device. Each device directory contains generation, embedding, and structured-decision tasks.
+
+```text
+examples/
+├── gpu/
+│ ├── assets/
+│ ├── generation/
+│ ├── embedding/
+│ └── decision/
+└── cpu/
+ ├── assets/
+ ├── generation/
+ ├── embedding/
+ └── decision/
+```
+
+The generation examples cover all supported input layouts:
+
+- `single_text`: one text item
+- `single_image`: one image item
+- `interleaved`: text → image → text → image → text
+
+The original HEIC images are preserved byte-for-byte in each device's `assets/` directory. The inference dependencies include `pillow-heif` for decoding them.
+
+## NVIDIA GPU
+
+```bash
+bash examples/gpu/generation/run.sh single_text
+bash examples/gpu/generation/run.sh single_image
+bash examples/gpu/generation/run.sh interleaved
+bash examples/gpu/embedding/run.sh
+bash examples/gpu/decision/run.sh
+```
+
+## CPU
+
+```bash
+bash examples/cpu/generation/run.sh single_text
+bash examples/cpu/generation/run.sh single_image
+bash examples/cpu/generation/run.sh interleaved
+bash examples/cpu/embedding/run.sh
+bash examples/cpu/decision/run.sh
+```
+
+The scripts use `checkpoints/huggingface` by default. To use another complete checkpoint, set:
+
+```bash
+export WEPM_MODEL=/path/to/WePM-HF
+```
+
+GPU selection, CPU threads, and output location can be controlled with `CUDA_VISIBLE_DEVICES`, `WEPM_THREADS`, and `WEPM_OUTPUT_DIR` respectively. Results are written to timestamped JSON files under each task's `results/` directory by default.
diff --git a/examples/cpu/assets/img2.heic b/examples/cpu/assets/img2.heic
new file mode 100644
index 0000000..3540b68
Binary files /dev/null and b/examples/cpu/assets/img2.heic differ
diff --git a/examples/cpu/assets/img3.heic b/examples/cpu/assets/img3.heic
new file mode 100644
index 0000000..cb8ec06
Binary files /dev/null and b/examples/cpu/assets/img3.heic differ
diff --git a/examples/inference/examples/decision.json b/examples/cpu/decision/request.json
similarity index 100%
rename from examples/inference/examples/decision.json
rename to examples/cpu/decision/request.json
diff --git a/examples/cpu/decision/run.sh b/examples/cpu/decision/run.sh
new file mode 100755
index 0000000..334fb13
--- /dev/null
+++ b/examples/cpu/decision/run.sh
@@ -0,0 +1,13 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
+MODEL="${WEPM_MODEL:-$REPO_ROOT/checkpoints/huggingface}"
+OUTPUT_DIR="${WEPM_OUTPUT_DIR:-$SCRIPT_DIR/results}"
+
+mkdir -p "$OUTPUT_DIR"
+python "$REPO_ROOT/inference/infer_cpu.py" \
+ --model "$MODEL" --task decision --decision-json "$SCRIPT_DIR/request.json" \
+ --threads "${WEPM_THREADS:-8}" \
+ --output "$OUTPUT_DIR/choice-$(date -u +%Y%m%dT%H%M%SZ).json"
diff --git a/examples/cpu/embedding/run.sh b/examples/cpu/embedding/run.sh
new file mode 100755
index 0000000..864550e
--- /dev/null
+++ b/examples/cpu/embedding/run.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
+MODEL="${WEPM_MODEL:-$REPO_ROOT/checkpoints/huggingface}"
+INPUT="$SCRIPT_DIR/../generation/single_image.json"
+OUTPUT_DIR="${WEPM_OUTPUT_DIR:-$SCRIPT_DIR/results}"
+
+mkdir -p "$OUTPUT_DIR"
+python "$REPO_ROOT/inference/infer_cpu.py" \
+ --model "$MODEL" --task embed --content-json "$INPUT" \
+ --threads "${WEPM_THREADS:-8}" --embedding-dim 1024 \
+ --output "$OUTPUT_DIR/single_image-$(date -u +%Y%m%dT%H%M%SZ).json"
diff --git a/examples/cpu/generation/interleaved.json b/examples/cpu/generation/interleaved.json
new file mode 100644
index 0000000..62e3c72
--- /dev/null
+++ b/examples/cpu/generation/interleaved.json
@@ -0,0 +1,24 @@
+{
+ "content": [
+ {
+ "type": "text",
+ "text": "First inspect this weather scene:"
+ },
+ {
+ "type": "image",
+ "path": "../assets/img2.heic"
+ },
+ {
+ "type": "text",
+ "text": "Then compare it with this mountain landscape:"
+ },
+ {
+ "type": "image",
+ "path": "../assets/img3.heic"
+ },
+ {
+ "type": "text",
+ "text": "Summarize the main visual differences between the two scenes."
+ }
+ ]
+}
diff --git a/examples/cpu/generation/run.sh b/examples/cpu/generation/run.sh
new file mode 100755
index 0000000..9ce676e
--- /dev/null
+++ b/examples/cpu/generation/run.sh
@@ -0,0 +1,21 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
+MODEL="${WEPM_MODEL:-$REPO_ROOT/checkpoints/huggingface}"
+CASE="${1:-single_text}"
+INPUT="$SCRIPT_DIR/$CASE.json"
+OUTPUT_DIR="${WEPM_OUTPUT_DIR:-$SCRIPT_DIR/results}"
+
+if [[ ! -f "$INPUT" ]]; then
+ echo "Unknown generation case: $CASE" >&2
+ echo "Choose single_text, single_image, or interleaved." >&2
+ exit 2
+fi
+
+mkdir -p "$OUTPUT_DIR"
+python "$REPO_ROOT/inference/infer_cpu.py" \
+ --model "$MODEL" --task generate --content-json "$INPUT" \
+ --threads "${WEPM_THREADS:-8}" --max-new-tokens 32 \
+ --output "$OUTPUT_DIR/$CASE-$(date -u +%Y%m%dT%H%M%SZ).json"
diff --git a/examples/cpu/generation/single_image.json b/examples/cpu/generation/single_image.json
new file mode 100644
index 0000000..5ccd4af
--- /dev/null
+++ b/examples/cpu/generation/single_image.json
@@ -0,0 +1,8 @@
+{
+ "content": [
+ {
+ "type": "image",
+ "path": "../assets/img3.heic"
+ }
+ ]
+}
diff --git a/examples/cpu/generation/single_text.json b/examples/cpu/generation/single_text.json
new file mode 100644
index 0000000..7b79083
--- /dev/null
+++ b/examples/cpu/generation/single_text.json
@@ -0,0 +1,8 @@
+{
+ "content": [
+ {
+ "type": "text",
+ "text": "Describe WePM in one sentence."
+ }
+ ]
+}
diff --git a/examples/gpu/assets/img2.heic b/examples/gpu/assets/img2.heic
new file mode 100644
index 0000000..3540b68
Binary files /dev/null and b/examples/gpu/assets/img2.heic differ
diff --git a/examples/gpu/assets/img3.heic b/examples/gpu/assets/img3.heic
new file mode 100644
index 0000000..cb8ec06
Binary files /dev/null and b/examples/gpu/assets/img3.heic differ
diff --git a/examples/gpu/decision/request.json b/examples/gpu/decision/request.json
new file mode 100644
index 0000000..0cbc2f7
--- /dev/null
+++ b/examples/gpu/decision/request.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/gpu/decision/run.sh b/examples/gpu/decision/run.sh
new file mode 100755
index 0000000..14c7de7
--- /dev/null
+++ b/examples/gpu/decision/run.sh
@@ -0,0 +1,12 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
+MODEL="${WEPM_MODEL:-$REPO_ROOT/checkpoints/huggingface}"
+OUTPUT_DIR="${WEPM_OUTPUT_DIR:-$SCRIPT_DIR/results}"
+
+mkdir -p "$OUTPUT_DIR"
+CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0}" python "$REPO_ROOT/inference/infer.py" \
+ --model "$MODEL" --task decision --decision-json "$SCRIPT_DIR/request.json" \
+ --output "$OUTPUT_DIR/choice-$(date -u +%Y%m%dT%H%M%SZ).json"
diff --git a/examples/gpu/embedding/run.sh b/examples/gpu/embedding/run.sh
new file mode 100755
index 0000000..5e0cbb3
--- /dev/null
+++ b/examples/gpu/embedding/run.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
+MODEL="${WEPM_MODEL:-$REPO_ROOT/checkpoints/huggingface}"
+INPUT="$SCRIPT_DIR/../generation/single_image.json"
+OUTPUT_DIR="${WEPM_OUTPUT_DIR:-$SCRIPT_DIR/results}"
+
+mkdir -p "$OUTPUT_DIR"
+CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0}" python "$REPO_ROOT/inference/infer.py" \
+ --model "$MODEL" --task embed --content-json "$INPUT" \
+ --embedding-dim 1024 \
+ --output "$OUTPUT_DIR/single_image-$(date -u +%Y%m%dT%H%M%SZ).json"
diff --git a/examples/gpu/generation/interleaved.json b/examples/gpu/generation/interleaved.json
new file mode 100644
index 0000000..62e3c72
--- /dev/null
+++ b/examples/gpu/generation/interleaved.json
@@ -0,0 +1,24 @@
+{
+ "content": [
+ {
+ "type": "text",
+ "text": "First inspect this weather scene:"
+ },
+ {
+ "type": "image",
+ "path": "../assets/img2.heic"
+ },
+ {
+ "type": "text",
+ "text": "Then compare it with this mountain landscape:"
+ },
+ {
+ "type": "image",
+ "path": "../assets/img3.heic"
+ },
+ {
+ "type": "text",
+ "text": "Summarize the main visual differences between the two scenes."
+ }
+ ]
+}
diff --git a/examples/gpu/generation/run.sh b/examples/gpu/generation/run.sh
new file mode 100755
index 0000000..7737b6c
--- /dev/null
+++ b/examples/gpu/generation/run.sh
@@ -0,0 +1,21 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
+MODEL="${WEPM_MODEL:-$REPO_ROOT/checkpoints/huggingface}"
+CASE="${1:-single_text}"
+INPUT="$SCRIPT_DIR/$CASE.json"
+OUTPUT_DIR="${WEPM_OUTPUT_DIR:-$SCRIPT_DIR/results}"
+
+if [[ ! -f "$INPUT" ]]; then
+ echo "Unknown generation case: $CASE" >&2
+ echo "Choose single_text, single_image, or interleaved." >&2
+ exit 2
+fi
+
+mkdir -p "$OUTPUT_DIR"
+CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0}" python "$REPO_ROOT/inference/infer.py" \
+ --model "$MODEL" --task generate --content-json "$INPUT" \
+ --max-new-tokens 64 \
+ --output "$OUTPUT_DIR/$CASE-$(date -u +%Y%m%dT%H%M%SZ).json"
diff --git a/examples/gpu/generation/single_image.json b/examples/gpu/generation/single_image.json
new file mode 100644
index 0000000..5ccd4af
--- /dev/null
+++ b/examples/gpu/generation/single_image.json
@@ -0,0 +1,8 @@
+{
+ "content": [
+ {
+ "type": "image",
+ "path": "../assets/img3.heic"
+ }
+ ]
+}
diff --git a/examples/gpu/generation/single_text.json b/examples/gpu/generation/single_text.json
new file mode 100644
index 0000000..7b79083
--- /dev/null
+++ b/examples/gpu/generation/single_text.json
@@ -0,0 +1,8 @@
+{
+ "content": [
+ {
+ "type": "text",
+ "text": "Describe WePM in one sentence."
+ }
+ ]
+}
diff --git a/examples/inference/README.md b/examples/inference/README.md
deleted file mode 100644
index 5687891..0000000
--- a/examples/inference/README.md
+++ /dev/null
@@ -1,151 +0,0 @@
-# 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/inference/README.md b/inference/README.md
new file mode 100644
index 0000000..11e05dd
--- /dev/null
+++ b/inference/README.md
@@ -0,0 +1,122 @@
+# WePM Inference
+
+This directory contains the complete Hugging Face Transformers inference implementation for WePM `task_slots_v1`. It loads the language and vision backbone, MGVB, independent embedding/decision slots, embedding head, and structured-decision head.
+
+Supported tasks:
+
+- `generate`: text or multimodal generation
+- `embed`: L2-normalized multimodal embeddings
+- `decision`: structured choice, score, and binary judgment
+
+## Installation
+
+Create a Python 3.10–3.13 environment and install the PyTorch build for the target device.
+
+NVIDIA GPU (CUDA 12.8 example):
+
+```bash
+python -m venv .venv
+source .venv/bin/activate
+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 inference/requirements.txt
+```
+
+CPU:
+
+```bash
+python -m venv .venv
+source .venv/bin/activate
+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 inference/requirements.txt
+```
+
+`Pillow` handles standard images and `pillow-heif` decodes the unmodified HEIC files bundled with the examples.
+
+## Model directory
+
+The default examples use `checkpoints/huggingface`. A complete model directory contains:
+
+```text
+huggingface/
+├── 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 are part of the checkpoint contract.
+
+## Simple input
+
+Use `--prompt` for one text item and repeat `--image` for one or more images. In this compact form, images are placed before the text.
+
+```bash
+CUDA_VISIBLE_DEVICES=0 python inference/infer.py \
+ --model checkpoints/huggingface --task generate \
+ --prompt "Describe this image." --image /path/to/image.png \
+ --output results/generation.json
+```
+
+For CPU, use `inference/infer_cpu.py` and add `--threads 8`.
+
+## Ordered multimodal input
+
+Use `--content-json` when text and images must retain an explicit order. Relative image paths are resolved from the JSON file's directory.
+
+```json
+{
+ "content": [
+ {"type": "text", "text": "Inspect the first image:"},
+ {"type": "image", "path": "../assets/first.heic"},
+ {"type": "text", "text": "Compare it with the second image:"},
+ {"type": "image", "path": "../assets/second.heic"},
+ {"type": "text", "text": "Summarize the differences."}
+ ]
+}
+```
+
+```bash
+CUDA_VISIBLE_DEVICES=0 python inference/infer.py \
+ --model checkpoints/huggingface --task generate \
+ --content-json /path/to/content.json \
+ --output results/interleaved.json
+```
+
+`--content-json` cannot be combined with `--prompt` or `--image`.
+
+## Structured decision
+
+```bash
+CUDA_VISIBLE_DEVICES=0 python inference/infer.py \
+ --model checkpoints/huggingface --task decision \
+ --decision-json examples/gpu/decision/request.json \
+ --output results/decision.json
+```
+
+The decision request uses `state` for the content being evaluated and `questions.q` for the task definition. Supported types are `choice`, `score`, and `noul`.
+
+## Main arguments
+
+| Argument | Description |
+| --- | --- |
+| `--model` | Complete local WePM Hugging Face directory |
+| `--task` | `generate`, `embed`, `both`, or `decision` |
+| `--prompt` | Simple text input |
+| `--image` | Simple local image input; may be repeated |
+| `--content-json` | Ordered text/image content for generation or embedding |
+| `--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 |
+
+Each invocation processes one request, writes a JSON result, releases the model, and exits. See [`examples/`](../examples) for complete GPU and CPU cases.
diff --git a/examples/inference/common.py b/inference/common.py
similarity index 100%
rename from examples/inference/common.py
rename to inference/common.py
diff --git a/examples/inference/infer.py b/inference/infer.py
similarity index 59%
rename from examples/inference/infer.py
rename to inference/infer.py
index 34ab977..6ad6927 100755
--- a/examples/inference/infer.py
+++ b/inference/infer.py
@@ -12,6 +12,34 @@ from common import write_json
from runtime import UniModelTransformers, wait_for_gpu
+def load_content(path: Path) -> list[dict]:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ content = payload.get("content") if isinstance(payload, dict) else None
+ if not isinstance(content, list) or not content:
+ raise ValueError(f"{path} must contain a nonempty content array")
+ resolved = []
+ for index, item in enumerate(content):
+ if not isinstance(item, dict) or item.get("type") not in {"text", "image"}:
+ raise ValueError(f"content[{index}] must be a text or image object")
+ if item["type"] == "text":
+ text = item.get("text")
+ if not isinstance(text, str) or not text.strip():
+ raise ValueError(f"content[{index}].text must be nonempty")
+ resolved.append({"type": "text", "text": text})
+ continue
+ value = item.get("path")
+ if not isinstance(value, str) or not value:
+ raise ValueError(f"content[{index}].path must be nonempty")
+ image = Path(value).expanduser()
+ if not image.is_absolute():
+ image = path.parent / image
+ image = image.resolve()
+ if not image.is_file():
+ raise FileNotFoundError(image)
+ resolved.append({"type": "image", "path": image})
+ return resolved
+
+
def main(*, device="cuda:0"):
device = torch.device(device)
is_cpu = device.type == "cpu"
@@ -25,8 +53,13 @@ def main(*, device="cuda:0"):
parser.add_argument(
"--task", choices=["generate", "embed", "both", "decision"], default="generate"
)
- parser.add_argument("--prompt", default="请用一句话介绍你自己。")
+ parser.add_argument("--prompt", help="text input; images are placed before it")
parser.add_argument("--image", type=Path, action="append", default=[])
+ parser.add_argument(
+ "--content-json",
+ type=Path,
+ help="ordered content array for text/image interleaving",
+ )
parser.add_argument(
"--decision-json",
type=Path,
@@ -60,9 +93,24 @@ def main(*, device="cuda:0"):
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")
+ if args.content_json and (args.prompt is not None or args.image):
+ parser.error("--content-json cannot be combined with --prompt or --image")
+ if args.task == "decision" and args.content_json:
+ parser.error("decision input is defined by --decision-json")
decision_request = (
- json.loads(args.decision_json.read_text()) if args.decision_json else None
+ json.loads(args.decision_json.read_text(encoding="utf-8"))
+ if args.decision_json
+ else None
)
+ if args.content_json:
+ content = load_content(args.content_json.resolve())
+ else:
+ content = [{"type": "image", "path": image.resolve()} for image in args.image]
+ prompt = args.prompt
+ if prompt is None and not content and args.task != "decision":
+ prompt = "请用一句话介绍你自己。"
+ if prompt:
+ content.append({"type": "text", "text": prompt})
if args.output.exists():
raise FileExistsError(args.output)
@@ -80,12 +128,10 @@ def main(*, device="cuda:0"):
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
- )
+ result["generation"] = model.generate(content, args.max_new_tokens)
if args.task in ("embed", "both"):
result["embedding"] = model.embed(
- args.prompt, args.image, dims=[args.embedding_dim]
+ content, dims=[args.embedding_dim]
)
if args.task == "decision":
result["decision"] = model.decide(decision_request, args.image)
diff --git a/examples/inference/infer_cpu.py b/inference/infer_cpu.py
similarity index 100%
rename from examples/inference/infer_cpu.py
rename to inference/infer_cpu.py
diff --git a/examples/inference/requirements.txt b/inference/requirements.txt
similarity index 87%
rename from examples/inference/requirements.txt
rename to inference/requirements.txt
index dfe2104..3d29413 100644
--- a/examples/inference/requirements.txt
+++ b/inference/requirements.txt
@@ -4,5 +4,6 @@ transformers==5.3.0
accelerate==1.14.0
safetensors==0.8.0
Pillow==12.3.0
+pillow-heif==1.1.1
Jinja2==3.1.6
numpy==2.2.6
diff --git a/examples/inference/runtime.py b/inference/runtime.py
similarity index 85%
rename from examples/inference/runtime.py
rename to inference/runtime.py
index 3beafb0..4cdda34 100644
--- a/examples/inference/runtime.py
+++ b/inference/runtime.py
@@ -14,17 +14,48 @@ from PIL import Image
from safetensors.torch import load_file
from transformers import AutoProcessor, Qwen3_5ForConditionalGeneration
+try:
+ from pillow_heif import register_heif_opener
+except ImportError:
+ register_heif_opener = None
+else:
+ register_heif_opener()
-def load_images(paths, prepare_image):
- """Apply the training-aligned RGB and longest-edge resize policy."""
+
+def prepare_content(content, prepare_image):
+ """Load images without changing the declared text/image order."""
+ processor_content = []
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
+ content_types = []
+ for item in content:
+ item_type = item.get("type") if isinstance(item, dict) else None
+ if item_type == "text":
+ text = item.get("text")
+ if not isinstance(text, str) or not text.strip():
+ raise ValueError("text content must be nonempty")
+ processor_content.append({"type": "text", "text": text})
+ elif item_type == "image":
+ source = item.get("path", item.get("bytes"))
+ if source is None:
+ raise ValueError("image content requires path or bytes")
+ if (
+ register_heif_opener is None
+ and not isinstance(source, bytes)
+ and Path(source).suffix.lower() in {".heic", ".heif"}
+ ):
+ raise RuntimeError("HEIC input requires pillow-heif; install requirements.txt")
+ with Image.open(
+ io.BytesIO(source) if isinstance(source, bytes) else source
+ ) as original:
+ image = prepare_image(original.convert("RGB"))
+ images.append(image)
+ processor_content.append({"type": "image", "image": image})
+ else:
+ raise ValueError("content items must have type text or image")
+ content_types.append(item_type)
+ if not processor_content:
+ raise ValueError("content must not be empty")
+ return processor_content, images, content_types
def wait_for_gpu(min_free_gib=14, timeout=120):
@@ -48,8 +79,8 @@ def wait_for_gpu(min_free_gib=14, timeout=120):
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
+ Each call accepts one ordered 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.
"""
@@ -191,21 +222,16 @@ class UniModelTransformers:
)
@torch.inference_mode()
- def _prepare_inputs(self, prompt: str, images, *, task: str):
+ def _prepare_inputs(self, content, *, 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
+ processor_content, loaded_images, content_types = prepare_content(
+ content, 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}],
+ [{"role": "user", "content": processor_content}],
tokenize=False,
add_generation_prompt=generation,
enable_thinking=False,
@@ -264,17 +290,18 @@ class UniModelTransformers:
"slot_role": slot_role,
"mrope_delta": int(delta[0, 0]),
"generation_prompt": generation,
+ "content_types": content_types,
}
return ids, embeddings, position_ids, metadata
@torch.inference_mode()
- def generate(self, prompt, images=(), max_new_tokens=64):
+ def generate(self, content, 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"
+ content, task="generate"
)
result = self.model.model.language_model(
inputs_embeds=embeddings,
@@ -322,11 +349,11 @@ class UniModelTransformers:
}
@torch.inference_mode()
- def embed(self, prompt, images=(), *, dims=None):
+ def embed(self, content, *, dims=None):
"""Return normalized embedding vectors at the requested MRL dimensions."""
start = time.monotonic()
_, embeddings, positions, metadata = self._prepare_inputs(
- prompt, images, task="embedding"
+ content, task="embedding"
)
result = self.model.model.language_model(
inputs_embeds=embeddings,
@@ -368,10 +395,18 @@ class UniModelTransformers:
raise ValueError(
"decision supports at most eight images and 64 MiB of image bytes"
)
+ decision_content = [
+ {
+ "type": "image",
+ "path" if not isinstance(image, bytes) else "bytes": image,
+ }
+ for image in (images or wire_images)
+ ]
+ decision_content.append(
+ {"type": "text", "text": protocol.render_input(value)[0]}
+ )
_, embeddings, positions, metadata = self._prepare_inputs(
- protocol.render_input(value)[0],
- images or wire_images,
- task="decision",
+ decision_content, task="decision"
)
result = self.model.model.language_model(
inputs_embeds=embeddings,