A compact, unified multimodal model family with a single shared vision–language backbone, built for on-device and in-app intelligence.
Add GGUF inference and update README demos
KivingYa6b913037404
diff --git a/README.md b/README.mdindex a994aa7..60f1ae4 100644--- a/README.md+++ b/README.md@@ -33,10 +33,10 @@ Simply mixing heterogeneous tasks does not make them compatible. WePM identifies- **ULKD (Unified Listwise Knowledge Distillation)** transfers generation and embedding knowledge from a frozen multimodal teacher into one student. On the generation path, on-policy token-level KL distillation supervises prefixes visited by the student itself; on the embedding path, candidate-list KL distillation and representation alignment teach the student candidate rankings and embedding structure.- **SEMO (Stable and Efficient Multitask Optimization)** accumulates fixed-weight task gradients through sequential forward/backward passes at the same model parameters, releasing each computation graph after backward before one joint optimizer update. This stabilizes optimization while avoiding the memory cost of retaining every task graph concurrently.-Together, these designs align visual evidence, learning signals and optimization dynamics within one compact backbone. Inference uses one vision encoder, one shared multimodal LLM backbone and one shared soft slot, with projection-based embedding/decision readouts and autoregressive generation.+Together, these designs align visual evidence, learning signals and optimization dynamics within one compact backbone. Inference shares one vision encoder and one multimodal LLM backbone across all three tasks. Embedding appends a learned E slot, then projects and L2-normalizes its hidden state. Decision appends a separate learned J slot and maps its hidden state to candidate logits with a direct head. Generation uses autoregressive decoding without a soft slot.<p align="center">- <img src="assert/last.png" width="640" alt="WePM shared inference substrate and MGVB, ULKD and SEMO training components">+ <img src="assert/wepm_architecture.svg" width="1000" alt="WePM architecture with separate embedding and decision slots, slotless generation, and the MGVB, ULKD and SEMO components"></p>## Performance Across Three Capability Families@@ -75,11 +75,9 @@ WePM is intended as a shared local intelligence layer rather than a collection oA single resident WePM-4B supports the complete local workflow: it retrieves relevant personal content, understands multimodal context, generates a grounded response and makes the typed decision that routes the next step. Retrieval, generation and decision are composed within one model instead of being dispatched to separate services.-<p align="center">- <video src="assert/personal_agent_demo.mp4" poster="assert/personal_agent_poster.jpg" width="640" controls muted loop playsinline></video>-</p>+https://github.com/user-attachments/assets/0ce0bf91-3d01-4c98-b255-9a0e3d4b6dcd-If the player above is not rendered by your Markdown viewer, open the [MP4 demo](assert/personal_agent_demo.mp4) directly.+[Open the MP4 file](assert/personal_agent_demo.mp4)<!-- TBD: capture device, memory footprint, precision and latency numbers for this demo. -->@@ -87,11 +85,9 @@ If the player above is not rendered by your Markdown viewer, open the [MP4 demo]The same WePM-4B interprets game frames and interface text, retrieves local knowledge and interaction history, generates contextual suggestions, and performs option judgment or action routing. This turns one continuously resident model into a complete multimodal game assistant without separately loading vision, retrieval and decision models.-<p align="center">- <video src="assert/game_assistant_demo.mp4" poster="assert/game_assistant_poster.jpg" width="640" controls muted loop playsinline></video>-</p>+https://github.com/user-attachments/assets/095ca925-6012-417c-8be2-eb50f7339f61-If the player above is not rendered by your Markdown viewer, open the [MP4 demo](assert/game_assistant_demo.mp4) directly.+[Open the MP4 file](assert/game_assistant_demo.mp4)## Inference@@ -105,13 +101,13 @@ Runtime code and runnable cases are maintained in GitLab; the 2B and 4B model reThese are the planned release addresses; downloads require the corresponding repositories to be published.```text-inference/ # Hugging Face Transformers inference implementation+inference/ # Transformers inference and optional CPU GGUF backendexamples/gpu/ # NVIDIA GPU task cases and input assetsexamples/cpu/ # CPU task cases and input assetscheckpoints/ # Optional local downloads; model files are not tracked```-The runnable examples use the complete Hugging Face export and support generation, embedding extraction, and structured decision. Generation cases cover single-text, single-image, and ordered text–image interleaving. The hardware figures below apply to WePM-4B. The shared loader requires the same `task_slots_v1` export contract, and 2B inference will be validated after its checkpoint is available.+The runnable examples default to a complete Hugging Face export and support generation, embedding extraction, and structured decision. Generation cases cover single-text, single-image, and ordered text–image interleaving. The hardware figures below apply to WePM-4B. The inference CLI also loads compatible 2B or 4B raw training exports and supports [GGUF inference on CPU](inference/README.md#gguf-on-cpu).### Hardware and precision (4B)@@ -129,7 +125,7 @@ git clone https://github.com/Tencent/WePocketModelcd WePocketModel```-The current branch does not bundle model weights or require Git LFS. Inference resolves the complete 2B or 4B export from Hugging Face or an explicitly selected local directory.+The current branch does not bundle model weights or require Git LFS. Use a complete export from Hugging Face or point inference to an existing local checkpoint directory.### Installation@@ -171,7 +167,7 @@ hf download tencent/WePocketModel1.0-4B --local-dir checkpoints/WePocketModel1.0export WEPM_MODEL="$PWD/checkpoints/WePocketModel1.0-4B"```-A local model directory is loaded without network access. For a cached repository ID, set `HF_HUB_OFFLINE=1` to prohibit network access. The [inference CLI](inference/README.md) also provides `--revision`, `--cache-dir`, and `--local-files-only`. Download the complete repository, not just the safetensors shards: auxiliary weights, runtime sources, tokenizer, processor and export metadata are required.+A local model directory is loaded without network access. For a cached repository ID, set `HF_HUB_OFFLINE=1` to prohibit network access. The [inference CLI](inference/README.md) also provides `--revision`, `--cache-dir`, and `--local-files-only`. Download the complete export for its auxiliary weights, tokenizer, processor and metadata. Inference uses the Python runtime shipped with this repository by default. Use `--trust-model-code` only for a model whose custom runtime code you have reviewed.### NVIDIA GPU inferencediff --git a/assert/last.png b/assert/last.pngdeleted file mode 100644index b4b376c..0000000Binary files a/assert/last.png and /dev/null differdiff --git a/assert/wepm_architecture.svg b/assert/wepm_architecture.svgnew file mode 100644index 0000000..2f40821--- /dev/null+++ b/assert/wepm_architecture.svg@@ -0,0 +1,128 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1120" height="750" viewBox="0 0 1120 750" role="img" aria-labelledby="title desc">+ <title id="title">WePM inference and training architecture</title>+ <desc id="desc">A shared vision encoder and multimodal backbone serve three task paths. Embedding uses an E slot, Decision uses a J slot and a direct candidate head, and Generation decodes without a soft slot. MGVB budgets visual tokens. ULKD distills generation and embedding knowledge, and SEMO accumulates task gradients before a joint update.</desc>+ <defs>+ <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">+ <path d="M0 0L10 5L0 10Z" fill="#47806a"/>+ </marker>+ <style>+ text { font-family: "DejaVu Sans", Arial, sans-serif; fill: #18372c; }+ .section { font-size: 29px; font-weight: 700; fill: #0e5038; }+ .heading { font-size: 20px; font-weight: 700; fill: #0e5038; }+ .label { font-size: 16px; font-weight: 700; }+ .body { font-size: 15px; }+ .detail { font-size: 14px; fill: #365e4d; }+ .muted { fill: #365e4d; }+ .center { text-anchor: middle; }+ .panel { fill: #f2f8f4; stroke: #a7c9b7; stroke-width: 1.5; }+ .card { fill: #fff; stroke: #b5d3c3; stroke-width: 1.5; }+ .shared { fill: #e2f0e8; stroke: #8dbba4; stroke-width: 1.5; }+ .chip { fill: #e4f1ea; }+ .route { fill: none; stroke: #47806a; stroke-linecap: round; stroke-linejoin: round; stroke-width: 2; }+ .arrow { marker-end: url(#arrow); }+ </style>+ </defs>++ <rect width="1120" height="750" fill="#fff"/>++ <g id="inference">+ <rect class="panel" x="12" y="12" width="1096" height="404" rx="24"/>+ <text class="section" x="38" y="54">Shared inference architecture</text>+ <text class="body muted" x="39" y="80">One vision encoder and one multimodal backbone serve three task paths.</text>++ <rect class="card" x="38" y="144" width="104" height="76" rx="13"/>+ <text class="label center" x="90" y="188">Images</text>+ <path class="route arrow" d="M142 182H169"/>++ <rect class="card" x="175" y="144" width="130" height="76" rx="13"/>+ <text class="label center" x="240" y="177">Vision</text>+ <text class="label center" x="240" y="198">encoder</text>+ <path class="route arrow" d="M305 182H330"/>++ <rect class="card" x="336" y="117" width="179" height="144" rx="13"/>+ <text class="heading" x="352" y="147">MGVB</text>+ <text class="detail" x="352" y="168">Visual token budget</text>+ <rect class="chip" x="352" y="178" width="147" height="70" rx="7"/>+ <text class="detail" x="363" y="197">Global bank</text>+ <text class="detail" x="363" y="217">Regional bank</text>+ <text class="detail" x="363" y="237">Fine-grained bank</text>+ <path class="route arrow" d="M515 182H550"/>++ <rect class="card" x="38" y="325" width="104" height="56" rx="13"/>+ <text class="label center" x="90" y="359">Prompt</text>+ <path class="route arrow" d="M90 325V282H424V265"/>+ <text class="detail" x="111" y="272">Prompt-conditioned visual selection</text>+ <path class="route arrow" d="M142 353H550"/>+ <text class="detail" x="163" y="342">Text tokens</text>++ <rect class="shared" x="556" y="117" width="176" height="264" rx="16"/>+ <text class="heading center" x="644" y="168">Multimodal</text>+ <text class="heading center" x="644" y="195">LLM backbone</text>+ <path d="M577 218H711" stroke="#9fc6b1" stroke-width="1.5"/>+ <text class="body center" x="644" y="250">Ordered text</text>+ <text class="body center" x="644" y="272">and visual tokens</text>+ <text class="detail center" x="644" y="318">Task-specific input</text>+ <text class="detail center" x="644" y="338">and readout</text>++ <path class="route arrow" d="M732 156H762"/>+ <path class="route arrow" d="M732 249H762"/>+ <path class="route arrow" d="M732 342H762"/>++ <rect class="card" x="768" y="117" width="314" height="78" rx="13"/>+ <text class="heading" x="784" y="146">Embedding</text>+ <rect class="chip" x="993" y="130" width="73" height="24" rx="12"/>+ <text class="detail center" x="1029.5" y="147">E slot</text>+ <text class="body" x="784" y="174">Linear projection → L2 normalization</text>++ <rect class="card" x="768" y="210" width="314" height="78" rx="13"/>+ <text class="heading" x="784" y="239">Decision (JEV)</text>+ <rect class="chip" x="993" y="223" width="73" height="24" rx="12"/>+ <text class="detail center" x="1029.5" y="240">J slot</text>+ <text class="body" x="784" y="267">Direct candidate head → softmax</text>++ <rect class="card" x="768" y="303" width="314" height="78" rx="13"/>+ <text class="heading" x="784" y="332">Generation</text>+ <rect class="chip" x="993" y="316" width="73" height="24" rx="12"/>+ <text class="detail center" x="1029.5" y="333">No slot</text>+ <text class="body" x="784" y="360">Autoregressive token decoding</text>+ </g>++ <path class="route arrow" d="M240 445V422" stroke-dasharray="4 5"/>+ <path class="route arrow" d="M788 445V422" stroke-dasharray="4 5"/>++ <g id="training">+ <rect class="panel" x="12" y="441" width="1096" height="297" rx="24"/>+ <text class="section" x="38" y="480">Training</text>++ <rect class="card" x="38" y="498" width="430" height="214" rx="15"/>+ <text class="heading" x="56" y="527">ULKD</text>+ <text class="detail" x="56" y="548">Unified Listwise Knowledge Distillation</text>+ <text class="label" x="56" y="575">Frozen multimodal teacher</text>+ <path class="route arrow" d="M65 583V605H80"/>+ <path class="route arrow" d="M65 605V656H80"/>++ <text class="label" x="89" y="611">Generation</text>+ <text class="detail" x="89" y="632">On-policy token KL on student rollout prefixes</text>+ <text class="label" x="89" y="662">Embedding</text>+ <text class="detail" x="89" y="683">Candidate-list KL and representation alignment</text>++ <rect class="card" x="488" y="498" width="594" height="214" rx="15"/>+ <text class="heading" x="506" y="527">SEMO</text>+ <text class="detail" x="506" y="548">Stable and Efficient Multitask Optimization</text>++ <rect class="chip" x="506" y="568" width="181" height="51" rx="9"/>+ <rect class="chip" x="695" y="568" width="181" height="51" rx="9"/>+ <rect class="chip" x="884" y="568" width="180" height="51" rx="9"/>+ <text class="label center" x="596.5" y="590">Embedding</text>+ <text class="label center" x="785.5" y="590">Generation</text>+ <text class="label center" x="974" y="590">Decision</text>+ <text class="detail center" x="596.5" y="609">λ<tspan baseline-shift="sub" font-size="10">rep</tspan> × L<tspan baseline-shift="sub" font-size="10">rep</tspan></text>+ <text class="detail center" x="785.5" y="609">λ<tspan baseline-shift="sub" font-size="10">gen</tspan> × L<tspan baseline-shift="sub" font-size="10">gen</tspan></text>+ <text class="detail center" x="974" y="609">λ<tspan baseline-shift="sub" font-size="10">dec</tspan> × L<tspan baseline-shift="sub" font-size="10">dec</tspan></text>++ <text class="detail center" x="785" y="643">Sequential backward passes at fixed parameters</text>+ <text class="detail center" x="785" y="662">Release each graph after backward</text>+ <rect class="shared" x="506" y="675" width="558" height="25" rx="8"/>+ <text class="label center" x="785" y="693">Accumulate weighted gradients → one optimizer step</text>+ </g>+</svg>diff --git a/examples/README.md b/examples/README.mdindex 1e2c3c7..d6d90b5 100644--- a/examples/README.md+++ b/examples/README.md@@ -60,7 +60,7 @@ To select the 2B release once available:export WEPM_MODEL=tencent/WePocketModel1.0-2B```-The shared runtime requires a compatible `task_slots_v1` export; 2B execution remains to be validated with the released checkpoint. The embedding examples explicitly request 1024 dimensions, which the chosen checkpoint must support.+The shared runtime requires a compatible `task_slots_v1` checkpoint. The embedding examples explicitly request 1024 dimensions, which the chosen checkpoint must support.For a pre-downloaded local model:@@ -70,4 +70,6 @@ export WEPM_MODEL=/path/to/WePocketModel1.0-4BLocal model directories are loaded without network access. Set `HF_HUB_OFFLINE=1` to use only the existing Hub cache when `WEPM_MODEL` is a repository ID. Use the [inference CLI](../inference/README.md) for `--revision`, `--cache-dir`, and `--local-files-only`.-GPU selection, CPU threads, and output location can be controlled with `CUDA_VISIBLE_DEVICES`, `WEPM_THREADS`, and `WEPM_OUTPUT_DIR` respectively. GPU scripts also accept `WEPM_MIN_FREE_GIB`, defaulting to the conservative 4B threshold of 14 GiB free CUDA memory; lowering this threshold does not reduce actual model memory requirements. Results are written to timestamped JSON files under each task's `results/` directory by default.+CPU examples also accept a local WePM GGUF bundle via `WEPM_MODEL` after [building the native library](../inference/README.md#gguf-on-cpu).++GPU selection, CPU threads, and output location can be controlled with `CUDA_VISIBLE_DEVICES`, `WEPM_THREADS`, and `WEPM_OUTPUT_DIR` respectively. Set `WEPM_MIN_FREE_GIB` to override the default CUDA loading threshold of checkpoint size plus 2 GiB. Results are written to timestamped JSON files under each task's `results/` directory by default.diff --git a/examples/gpu/decision/run.sh b/examples/gpu/decision/run.shindex d23c3b5..077a318 100755--- a/examples/gpu/decision/run.sh+++ b/examples/gpu/decision/run.sh@@ -5,9 +5,13 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"MODEL="${WEPM_MODEL:-tencent/WePocketModel1.0-4B}"OUTPUT_DIR="${WEPM_OUTPUT_DIR:-$SCRIPT_DIR/results}"+GPU_ARGS=()+if [[ -n "${WEPM_MIN_FREE_GIB:-}" ]]; then+ GPU_ARGS=(--min-free-gib "$WEPM_MIN_FREE_GIB")+fimkdir -p "$OUTPUT_DIR"CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0}" python "$REPO_ROOT/inference/infer.py" \--model "$MODEL" --task decision --decision-json "$SCRIPT_DIR/../demo_data/decision/request.json" \- --min-free-gib "${WEPM_MIN_FREE_GIB:-14}" \+ "${GPU_ARGS[@]}" \--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.shindex f5e8c5e..39a6ba1 100755--- a/examples/gpu/embedding/run.sh+++ b/examples/gpu/embedding/run.sh@@ -6,9 +6,13 @@ REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"MODEL="${WEPM_MODEL:-tencent/WePocketModel1.0-4B}"INPUT="$SCRIPT_DIR/../demo_data/generation/single_image.json"OUTPUT_DIR="${WEPM_OUTPUT_DIR:-$SCRIPT_DIR/results}"+GPU_ARGS=()+if [[ -n "${WEPM_MIN_FREE_GIB:-}" ]]; then+ GPU_ARGS=(--min-free-gib "$WEPM_MIN_FREE_GIB")+fimkdir -p "$OUTPUT_DIR"CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0}" python "$REPO_ROOT/inference/infer.py" \--model "$MODEL" --task embed --content-json "$INPUT" \- --min-free-gib "${WEPM_MIN_FREE_GIB:-14}" --embedding-dim 1024 \+ "${GPU_ARGS[@]}" --embedding-dim 1024 \--output "$OUTPUT_DIR/single_image-$(date -u +%Y%m%dT%H%M%SZ).json"diff --git a/examples/gpu/generation/run.sh b/examples/gpu/generation/run.shindex 84ff20c..2b63bce 100755--- a/examples/gpu/generation/run.sh+++ b/examples/gpu/generation/run.sh@@ -7,6 +7,10 @@ MODEL="${WEPM_MODEL:-tencent/WePocketModel1.0-4B}"CASE="${1:-single_text}"INPUT="$SCRIPT_DIR/../demo_data/generation/$CASE.json"OUTPUT_DIR="${WEPM_OUTPUT_DIR:-$SCRIPT_DIR/results}"+GPU_ARGS=()+if [[ -n "${WEPM_MIN_FREE_GIB:-}" ]]; then+ GPU_ARGS=(--min-free-gib "$WEPM_MIN_FREE_GIB")+fiif [[ ! -f "$INPUT" ]]; thenecho "Unknown generation case: $CASE" >&2@@ -17,5 +21,5 @@ fimkdir -p "$OUTPUT_DIR"CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0}" python "$REPO_ROOT/inference/infer.py" \--model "$MODEL" --task generate --content-json "$INPUT" \- --min-free-gib "${WEPM_MIN_FREE_GIB:-14}" --max-new-tokens 64 \+ "${GPU_ARGS[@]}" --max-new-tokens 64 \--output "$OUTPUT_DIR/$CASE-$(date -u +%Y%m%dT%H%M%SZ).json"diff --git a/inference/README.md b/inference/README.mdindex 9311ff3..5bbccee 100644--- a/inference/README.md+++ b/inference/README.md@@ -1,6 +1,6 @@# 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.+WePM `task_slots_v1` runs with Transformers on CPU or CUDA and with a native GGUF language backend on CPU. Both backends use the WePM vision encoder, MGVB, independent embedding and decision slots, and trained task heads.Supported tasks:@@ -36,7 +36,9 @@ python -m pip install -r inference/requirements.txt## Model download and local directory-`--model` accepts a Hugging Face model repository ID or a complete local export directory. The default is `tencent/WePocketModel1.0-4B`; use `tencent/WePocketModel1.0-2B` to select the smaller release once published. The same loader requires a compatible `task_slots_v1` export; 2B inference must be validated after its checkpoint is available.+`--model` accepts a Hugging Face model repository ID or a local checkpoint directory. The default is `tencent/WePocketModel1.0-4B`. To switch between compatible 2B and 4B Transformers checkpoints, change `--model` to the desired checkpoint. On CPU, a directory containing a GGUF `bundle.json` selects the GGUF backend.++Both backends use the Python runtime included in this inference repository by default. If an export requires custom task code, review its `runtime_sources/` directory and pass `--trust-model-code` to execute that code with your user permissions. This applies to local directories and Hub snapshots. For Hub models, use `--revision` with the commit you reviewed.The first online run downloads a complete snapshot, including the auxiliary weights and runtime sources, into the standard Hugging Face cache. Later runs reuse cached files, but may check the repository for updates. Use `--revision` to pin a tag or commit, `--cache-dir` to select a cache location, and `--local-files-only` (or `HF_HUB_OFFLINE=1`) to prohibit network access. Downloads finish before the inference timeout starts and before CUDA resources are allocated. Download errors, including an unpublished repository or a missing offline cache, are not silently replaced by another model.@@ -46,7 +48,7 @@ To download ahead of time into a local directory:hf download tencent/WePocketModel1.0-4B --local-dir checkpoints/WePocketModel1.0-4B```-Pass `--model checkpoints/WePocketModel1.0-4B` to load that directory without network access. The GitLab repository does not bundle model weights; download either the 2B or 4B complete Hugging Face export.+Pass `--model checkpoints/WePocketModel1.0-4B` to load that directory without network access.A complete local model directory contains:@@ -64,7 +66,29 @@ huggingface/└── export_complete.json```-Do not remove `runtime_sources/` or `unimodel_aux.safetensors`; they are part of the checkpoint contract.+Keep `unimodel_aux.safetensors` alongside the backbone weights. The Transformers backend uses the export's `runtime_sources/` only with `--trust-model-code`. A release can also contain a single `model.safetensors` file without a shard index.++A raw `task_slots_v1` training export has a `model.safetensors.index.json` that points to both the backbone shards and `model-unimodel.safetensors`. Pass its Hugging Face export directory directly as `--model`. The loader separates the task weights from the backbone without copying any tensors.++CUDA waits for free memory equal to the selected checkpoint's weight files plus 2 GiB by default. This is a loading threshold. Actual peak usage depends on the input and generation length. Use `--min-free-gib` to override the threshold.++## GGUF on CPU++Install the optional GGUF requirements and build the native library on the target machine. The build requires Git, CMake 3.20 or later, and a C++17 compiler. It fetches the pinned llama.cpp revision. For an offline build, pass `--llama-source` with that revision already available locally.++```bash+python -m pip install -r inference/requirements-gguf.txt+python inference/build_gguf.py+```++Use a complete WePM GGUF bundle with `bundle.json`, the language weights, `multimodal-BF16.gguf`, and the accompanying tokenizer, processor, and runtime assets.++```bash+python inference/infer_cpu.py --model /path/to/wepm-gguf --task both \+ --prompt "Introduce yourself in one sentence." --output results/gguf.json+```++The language weights default to Q4_K_M. Use `--gguf-variant bf16` for BF16 language weights. The shared visual and task tensors are stored in BF16 and computed in FP32. To override discovery of the native library, use `--gguf-library` or `WEPM_GGUF_LIBRARY`. Keep its companion shared libraries in the same directory.## Simple input@@ -119,11 +143,12 @@ The decision request uses `state` for the content being evaluated and `questions| Argument | Description || --- | --- |-| `--model` | Hugging Face repository ID or complete local WePM directory; default `tencent/WePocketModel1.0-4B` |+| `--model` | Hugging Face repository ID, local Transformers export, or CPU GGUF bundle. Defaults to `tencent/WePocketModel1.0-4B` |+| `--trust-model-code` | Execute Python from the selected export’s `runtime_sources/` directory. Defaults to the runtime shipped with this inference repository || `--revision` | Hub branch, tag, or commit; pin a commit for reproducible inference || `--cache-dir` | Hugging Face cache directory; otherwise use the standard Hub cache || `--local-files-only` | Do not access the network; fail if the requested snapshot is not cached |-| `--min-free-gib` | CUDA only: free-memory threshold before loading; default 14 GiB for 4B, not a measured 2B requirement |+| `--min-free-gib` | CUDA free-memory threshold before loading. Defaults to checkpoint size plus 2 GiB || `--task` | `generate`, `embed`, `both`, or `decision` || `--prompt` | Simple text input || `--image` | Simple local image input; may be repeated |@@ -132,7 +157,10 @@ The decision request uses `state` for the content being evaluated and `questions| `--max-new-tokens` | Generation length from 1 to 512 || `--embedding-dim` | Dimension supported by the chosen checkpoint; defaults to its full embedding dimension (2048 for the current 4B export) || `--threads` | CPU compute threads; default 8 |-| `--timeout` | Maximum inference lifetime in seconds, excluding model download; default 1200 |-| `--output` | New JSON output path; required and must not already exist |+| `--gguf-variant` | GGUF language weights. Accepts `q4` (default) or `bf16` |+| `--gguf-library` | Override the path to the native GGUF runtime |+| `--context-size` | GGUF context budget for input and generated tokens. Defaults to 4096 |+| `--timeout` | Request interruption after 1–1800 seconds, starting after model download (default 1200). Native calls can delay interruption until they return |+| `--output` | Required path for a new JSON result. Concurrent writes to the same path allow only one to succeed |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/inference/build_gguf.py b/inference/build_gguf.pynew file mode 100644index 0000000..f0a7195--- /dev/null+++ b/inference/build_gguf.py@@ -0,0 +1,101 @@+#!/usr/bin/env python3+"""Build the CPU GGUF inference library from the pinned llama.cpp revision."""++import argparse+import shutil+import subprocess+from pathlib import Path+from tempfile import TemporaryDirectory++from checkpoint import LLAMA_CPP_COMMIT++LLAMA_REPOSITORY = "https://github.com/ggml-org/llama.cpp.git"+DEFAULT_CACHE = Path.home() / ".cache/wepm-gguf"+++def source_revision(source):+ # The offline converter's source archive includes this identity marker.+ marker = source / "SOURCE_COMMIT"+ if marker.is_file() and not (source / ".git").exists():+ return marker.read_text().strip()+ return subprocess.check_output(+ ["git", "-C", source, "rev-parse", "HEAD"], text=True+ ).strip()+++def fetch_source(path):+ if not path.exists():+ with TemporaryDirectory(dir=path.parent, prefix=".llama-fetch-") as tmp:+ checkout = Path(tmp) / "llama.cpp"+ subprocess.run(["git", "init", "-q", checkout], check=True)+ subprocess.run(+ [+ "git",+ "-C",+ checkout,+ "fetch",+ "--depth=1",+ LLAMA_REPOSITORY,+ LLAMA_CPP_COMMIT,+ ],+ check=True,+ )+ subprocess.run(+ ["git", "-C", checkout, "checkout", "--detach", "-q", LLAMA_CPP_COMMIT],+ check=True,+ )+ checkout.rename(path)+ return path+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--threads", type=int, default=4, help="parallel build jobs")+ parser.add_argument("--cache", type=Path, default=DEFAULT_CACHE)+ parser.add_argument(+ "--llama-source", type=Path, help="existing pinned llama.cpp source"+ )+ args = parser.parse_args()+ if args.threads < 1:+ parser.error("--threads must be positive")+ if not shutil.which("cmake"):+ parser.error("CMake 3.20 or later is required")+ cache = args.cache.expanduser().resolve() / LLAMA_CPP_COMMIT+ cache.mkdir(parents=True, exist_ok=True)+ source = (+ args.llama_source.expanduser().resolve()+ if args.llama_source+ else fetch_source(cache / "llama.cpp")+ )+ if source_revision(source) != LLAMA_CPP_COMMIT:+ parser.error(f"llama.cpp source must match {LLAMA_CPP_COMMIT}")+ build = cache / "native-build"+ subprocess.run(+ [+ "cmake",+ "-S",+ Path(__file__).resolve().parent / "native",+ "-B",+ build,+ "-DCMAKE_BUILD_TYPE=Release",+ f"-DLLAMA_CPP_ROOT={source}",+ ],+ check=True,+ )+ subprocess.run(+ [+ "cmake",+ "--build",+ build,+ "--target",+ "wepm_gguf",+ "--parallel",+ str(args.threads),+ ],+ check=True,+ )+ print(f"WePM GGUF runtime is in {build / 'bin'}")+++if __name__ == "__main__":+ main()diff --git a/inference/checkpoint.py b/inference/checkpoint.pynew file mode 100644index 0000000..d8f7173--- /dev/null+++ b/inference/checkpoint.py@@ -0,0 +1,132 @@+"""Locate and validate the files of a WePM release or raw training export."""++from __future__ import annotations++import json+from contextlib import contextmanager+from pathlib import Path+from tempfile import TemporaryDirectory++INDEX_NAME = "model.safetensors.index.json"+RELEASE_SCHEMA = "wepm-nvidia-task-slots-v1"+LLAMA_CPP_COMMIT = "37b0f9c36ae910c5a445b3934e840084ebc9b132"+BUNDLED_RUNTIME = Path(__file__).resolve().with_name("runtime_sources")+RUNTIME_FILES = (+ "generation_slots.py",+ "decision_config.py",+ "decision_protocol.py",+ "image_geometry.py",+ "mgvb.py",+ "mgvb_utils.py",+ "rope_utils.py",+)+++def select_runtime_sources(model_dir: Path, *, trust_model_code: bool) -> Path:+ source = model_dir / "runtime_sources" if trust_model_code else BUNDLED_RUNTIME+ missing = [name for name in RUNTIME_FILES if not (source / name).is_file()]+ if missing:+ raise ValueError(+ f"incomplete WePM runtime at {source}; missing: {', '.join(missing)}"+ )+ return source+++class WePMCheckpoint:+ def __init__(self, model_dir: str | Path):+ self.path = Path(model_dir).expanduser().resolve()+ manifest = self.path / "export_complete.json"+ self.is_release = manifest.is_file()+ if self.is_release:+ if json.loads(manifest.read_text()).get("schema") != RELEASE_SCHEMA:+ raise ValueError(+ f"a compatible task_slots_v1 WePM export is required: {manifest}"+ )+ self.auxiliary_path = self.path / "unimodel_aux.safetensors"+ required = (+ "config.json",+ "unimodel_aux.safetensors",+ "tokenizer.json",+ "tokenizer_config.json",+ "processor_config.json",+ "chat_template.jinja",+ )+ missing = [name for name in required if not (self.path / name).is_file()]+ if missing:+ raise ValueError(+ f"incomplete WePM export at {self.path}; missing: {', '.join(missing)}. "+ "Download the complete model repository, not only the weight files."+ )+ else:+ self.auxiliary_path = self.path / "model-unimodel.safetensors"+ if not self.auxiliary_path.is_file():+ raise ValueError(+ f"expected a WePM release or training export: {self.path}"+ )++ self.config = json.loads((self.path / "config.json").read_text())+ index = self.path / INDEX_NAME+ self.indexed_auxiliary_keys = set()+ if index.is_file():+ weight_map = json.loads(index.read_text()).get("weight_map")+ if not isinstance(weight_map, dict) or not weight_map:+ raise ValueError(f"invalid weight index: {index}")+ self.backbone_weights = {+ key: name+ for key, name in weight_map.items()+ if not key.startswith("unimodel.")+ }+ self.indexed_auxiliary_keys = set(weight_map) - self.backbone_weights.keys()+ if self.is_release:+ if self.indexed_auxiliary_keys:+ raise ValueError("a WePM release must index only backbone weights")+ elif not self.indexed_auxiliary_keys or any(+ weight_map[key] != self.auxiliary_path.name+ for key in self.indexed_auxiliary_keys+ ):+ raise ValueError(+ "training export must index all task weights in model-unimodel.safetensors"+ )+ if not self.backbone_weights or any(+ not isinstance(name, str)+ or Path(name).is_absolute()+ or ".." in Path(name).parts+ or Path(name).suffix != ".safetensors"+ or Path(name) == Path(self.auxiliary_path.name)+ for name in self.backbone_weights.values()+ ):+ raise ValueError(f"invalid WePM backbone shard index: {index}")+ self.backbone_shards = sorted(set(self.backbone_weights.values()))+ elif self.is_release:+ self.backbone_shards = ["model.safetensors"]+ else:+ raise ValueError(f"training export requires a weight index: {index}")++ weights = [+ self.auxiliary_path,+ *(self.path / name for name in self.backbone_shards),+ ]+ for path in weights:+ if not path.is_file():+ raise ValueError(f"missing model weight file: {path}")+ self.weight_bytes = sum(path.stat().st_size for path in weights)++ @contextmanager+ def backbone_directory(self):+ """Present only backbone tensors to Transformers without copying weights."""+ if self.is_release:+ yield self.path+ return+ with TemporaryDirectory(prefix="wepm-backbone-") as directory:+ backbone = Path(directory)+ for name in ("config.json", *self.backbone_shards):+ link = backbone / name+ link.parent.mkdir(parents=True, exist_ok=True)+ link.symlink_to(self.path / name)+ generation_config = self.path / "generation_config.json"+ if generation_config.is_file():+ (backbone / generation_config.name).symlink_to(generation_config)+ (backbone / INDEX_NAME).write_text(+ json.dumps({"metadata": {}, "weight_map": self.backbone_weights})+ )+ yield backbonediff --git a/inference/common.py b/inference/common.pyindex 6e533c2..054c883 100644--- a/inference/common.py+++ b/inference/common.py@@ -1,4 +1,4 @@-"""File utilities and standalone imports of the checkpoint's model code."""+"""File utilities and standalone imports of the selected WePM runtime."""from __future__ import annotations@@ -6,16 +6,22 @@ import astimport hashlibimport importlib.utilimport json+import osimport sysimport typesfrom pathlib import Path+from tempfile import TemporaryDirectorydef 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)+ with TemporaryDirectory(dir=path.parent) as directory:+ temporary = Path(directory) / "result.json"+ with temporary.open("w", encoding="utf-8") as stream:+ json.dump(payload, stream, indent=2, ensure_ascii=False)+ stream.write("\n")+ # Publish the complete file only if the destination is still available.+ os.link(temporary, path)def sha256(path: Path) -> str:@@ -37,7 +43,7 @@ def load_file(name: str, path: Path):def load_contracts(source: Path):- """Load the checkpoint's own task routing, decision protocol and geometry."""+ """Load the selected runtime's task routing, decision protocol and geometry."""name = ("_wepm_nvidia_"+ hashlib.sha256(str(source.resolve()).encode()).hexdigest()[:16]@@ -64,7 +70,7 @@ def validate_architecture(config, contracts):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")+ raise ValueError("the WePM runtime requires the trained direct decision head")if (config.get("unimodel_decision_input_profile")!= contracts.decision_protocol.INPUT_PROFILEdiff --git a/inference/gguf_runtime.py b/inference/gguf_runtime.pynew file mode 100644index 0000000..7bad580--- /dev/null+++ b/inference/gguf_runtime.py@@ -0,0 +1,291 @@+"""CPU GGUF language execution with the trained Transformers vision/MGVB path.++Language tensors stay in GGUF and execute in the pinned llama.cpp backend.+Only requested token embedding rows and the BF16 visual/task modules are+decoded to FP32 for the common image, E-slot and J-slot implementations.+"""++from __future__ import annotations++import ctypes+import hashlib+import json+import os+import platform+import time+from pathlib import Path++try:+ import gguf+except ModuleNotFoundError as exc:+ if exc.name != "gguf":+ raise+ raise RuntimeError(+ "Install GGUF dependencies: python -m pip install -r inference/requirements-gguf.txt"+ ) from exc+import numpy as np+import torch+from checkpoint import LLAMA_CPP_COMMIT, select_runtime_sources+from common import load_contracts, validate_architecture+from runtime import WePMRuntime+from transformers import AutoConfig+from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5VisionModel+++class TensorStore:+ """Read GGUF tensors, retaining mmap storage for the language table."""++ def __init__(self, path):+ self.reader = gguf.GGUFReader(str(path))+ self.tensors = {tensor.name: tensor for tensor in self.reader.tensors}+ field = self.reader.fields.get("unimodel.tensor_shapes")+ self.shapes = json.loads(field.contents()) if field else {}++ def tensor(self, name):+ tensor = self.tensors[name]+ shape = self.shapes.get(name, tuple(reversed(tensor.shape)))+ data = gguf.dequantize(tensor.data, tensor.tensor_type)+ return torch.from_numpy(+ np.array(data, dtype=np.float32, copy=True).reshape(shape)+ )++ def embedding(self, ids):+ tensor = self.tensors["token_embd.weight"]+ indices = ids.cpu().numpy()+ unique, inverse = np.unique(indices, return_inverse=True)+ if unique.min() < 0 or unique.max() >= tensor.shape[1]:+ raise ValueError("token index outside GGUF vocabulary")+ # Slice packed rows first: never materialize the whole language model.+ rows = gguf.dequantize(tensor.data[unique], tensor.tensor_type)+ values = rows[inverse].reshape(*indices.shape, int(tensor.shape[0]))+ return torch.from_numpy(np.array(values, dtype=np.float32, copy=True))+++class NativeText:+ """Own one CPU context through a small, versioned native C ABI."""++ def __init__(self, model, library, context_size, threads):+ self.handle = None+ self.api = ctypes.CDLL(str(library))+ api = self.api+ api.wepm_error.restype = ctypes.c_char_p+ api.wepm_abi_version.restype = ctypes.c_int+ if api.wepm_abi_version() != 1:+ raise ValueError("unsupported WePM GGUF library ABI")+ api.wepm_load.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int]+ api.wepm_load.restype = ctypes.c_void_p+ api.wepm_free.argtypes = [ctypes.c_void_p]+ for name in ("wepm_width", "wepm_vocabulary"):+ getattr(api, name).argtypes = [ctypes.c_void_p]+ getattr(api, name).restype = ctypes.c_int+ api.wepm_eval.argtypes = [+ ctypes.c_void_p,+ ctypes.POINTER(ctypes.c_float),+ ctypes.POINTER(ctypes.c_int32),+ ctypes.c_int,+ ctypes.c_int,+ ctypes.c_int,+ ctypes.POINTER(ctypes.c_float),+ ]+ api.wepm_eval.restype = ctypes.c_int+ self.handle = api.wepm_load(os.fsencode(model), context_size, threads)+ if not self.handle:+ raise RuntimeError(api.wepm_error().decode())+ self.width = api.wepm_width(self.handle)+ self.vocabulary = api.wepm_vocabulary(self.handle)+ self.context_size = context_size++ def evaluate(self, embeddings, positions, *, reset, hidden):+ if not self.handle:+ raise RuntimeError("GGUF context is closed")+ count = embeddings.shape[1]+ if tuple(embeddings.shape) != (1, count, self.width) or tuple(+ positions.shape+ ) != (4, 1, count):+ raise ValueError(+ "GGUF supports one unpadded request with four position axes"+ )+ data = np.ascontiguousarray(embeddings.float().cpu().numpy())+ # Common runtime: sequence, temporal, height, width.+ # Pinned GGUF ZYXT layout: sequence, height, width, temporal.+ pos = np.ascontiguousarray(+ positions[[0, 2, 3, 1], 0].cpu().numpy(), dtype=np.int32+ )+ output = np.empty(self.width if hidden else self.vocabulary, dtype=np.float32)+ code = self.api.wepm_eval(+ self.handle,+ data.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),+ pos.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),+ count,+ int(reset),+ int(hidden),+ output.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),+ )+ if code:+ raise RuntimeError(self.api.wepm_error().decode())+ if not np.isfinite(output).all():+ raise ValueError("nonfinite GGUF output")+ return torch.from_numpy(output)++ def close(self):+ if self.handle:+ self.api.wepm_free(self.handle)+ self.handle = None++ def __del__(self):+ self.close()+++def library_path(commit, supplied=None):+ if supplied or os.environ.get("WEPM_GGUF_LIBRARY"):+ path = Path(supplied or os.environ["WEPM_GGUF_LIBRARY"]).expanduser().resolve()+ else:+ filename = (+ "libwepm_gguf.dylib" if platform.system() == "Darwin" else "libwepm_gguf.so"+ )+ path = Path.home() / ".cache/wepm-gguf" / commit / "native-build/bin" / filename+ if not path.is_file():+ raise FileNotFoundError(+ f"GGUF CPU library missing: {path}. Run python inference/build_gguf.py, or pass --gguf-library."+ )+ return path+++class UniModelGGUF(WePMRuntime):+ """CPU inference with native GGUF language weights and shared task logic."""++ def __init__(+ self,+ model_dir,+ *,+ variant="q4",+ library=None,+ context_size=4096,+ threads=8,+ trust_model_code=False,+ ):+ self.native = None+ self.model_dir = Path(model_dir).resolve()+ manifest = json.loads((self.model_dir / "bundle.json").read_text())+ if (+ manifest.get("format") != "wepm-gguf-release-v1"+ or manifest.get("llama_cpp_commit") != LLAMA_CPP_COMMIT+ ):+ raise ValueError("unsupported WePM GGUF bundle or llama.cpp revision")+ language_name = manifest["language_variants"].get(variant)+ if not language_name:+ raise ValueError(f"GGUF variant {variant!r} is missing from bundle.json")+ auxiliary_name = "multimodal-BF16.gguf"+ for name in (language_name, auxiliary_name):+ path = self.model_dir / name+ expected = manifest["files"].get(name)+ if (+ Path(name).name != name+ or not expected+ or not path.is_file()+ or path.stat().st_size != expected["bytes"]+ ):+ raise ValueError(f"missing or incomplete GGUF weight file: {path}")++ # Check the small assets and code before using them. Do not read several+ # GiB solely to recompute weight checksums at each invocation.+ for directory, table in (+ (self.model_dir, manifest["asset_sha256"]),+ (self.model_dir / "runtime_sources", manifest["runtime_source_sha256"]),+ ):+ for name, expected in table.items():+ if (+ Path(name).name != name+ or hashlib.sha256((directory / name).read_bytes()).hexdigest()+ != expected+ ):+ raise ValueError(f"GGUF asset integrity mismatch: {name}")+ native_library = library_path(manifest["llama_cpp_commit"], library)+ self.config = json.loads((self.model_dir / "config.json").read_text())+ runtime_sources = select_runtime_sources(+ self.model_dir, trust_model_code=trust_model_code+ )+ self.contracts = load_contracts(runtime_sources)+ self.decision_config = validate_architecture(self.config, self.contracts)+ self.device, self.dtype = torch.device("cpu"), torch.float32+ language = self.model_dir / language_name+ self.language = TensorStore(language)+ aux = TensorStore(self.model_dir / auxiliary_name)+ state = {name: aux.tensor(name) for name in aux.tensors}+ vision_config = AutoConfig.from_pretrained(+ self.model_dir, local_files_only=True, trust_remote_code=False+ ).vision_config+ vision_config._attn_implementation = "sdpa"+ self.vision = Qwen3_5VisionModel(vision_config).float().eval()+ prefix = "model.visual."+ visual = {+ name.removeprefix(prefix): state.pop(name)+ for name in list(state)+ if name.startswith(prefix)+ }+ self.vision.load_state_dict(visual, strict=True)+ del visual+ self._load_task_modules(runtime_sources, state)+ self.native = NativeText(language, native_library, context_size, threads)+ text_config = self.config["text_config"]+ if (+ self.native.width != text_config["hidden_size"]+ or self.native.vocabulary != text_config["vocab_size"]+ ):+ self.close()+ raise ValueError("GGUF language dimensions differ from model config")++ def _token_embeddings(self, ids):+ return self.language.embedding(ids)++ def _last_hidden(self, embeddings, positions):+ return self.native.evaluate(embeddings, positions, reset=True, hidden=True)[+ None, :+ ]++ def _vision_features(self, pixels, grid):+ return self.vision(pixels, grid_thw=grid, return_dict=True).pooler_output++ @torch.inference_mode()+ def generate(self, content, max_new_tokens=64):+ if not 1 <= max_new_tokens <= 512:+ raise ValueError("max_new_tokens must be in [1, 512]")+ start = time.monotonic()+ ids, embeddings, positions, metadata = self._prepare_inputs(+ content, task="generate"+ )+ if ids.shape[1] + max_new_tokens > self.native.context_size:+ raise ValueError("prompt and generation exceed --context-size")+ logits = self.native.evaluate(embeddings, positions, reset=True, hidden=False)+ rope_start = int(positions[1:].max()) + 1+ stop_ids = self._stop_token_ids()+ generated, finish = [], "length"+ for index in range(max_new_tokens):+ token = int(logits.argmax())+ generated.append(token)+ if token 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)+ pos[0] = ids.shape[1] + index+ logits = self.native.evaluate(+ self._token_embeddings(torch.tensor([[token]], device=self.device)),+ pos,+ reset=False,+ hidden=False,+ )+ return {+ "text": self.processor.tokenizer.decode(+ generated, skip_special_tokens=True+ ),+ "token_ids": generated,+ "finish_reason": finish,+ "seconds": time.monotonic() - start,+ "input": metadata,+ }++ def close(self):+ if self.native is not None:+ self.native.close()diff --git a/inference/infer.py b/inference/infer.pyindex fe04e9c..3bacf43 100755--- a/inference/infer.py+++ b/inference/infer.py@@ -1,16 +1,17 @@#!/usr/bin/env python3-"""Finite G/E/J inference with Transformers on CPU or CUDA; save JSON and exit."""+"""Run G/E/J inference with Transformers or CPU GGUF and write a JSON result."""import argparseimport gcimport json+import mathimport signalfrom pathlib import Pathimport torchfrom common import write_jsonfrom model_source import DEFAULT_MODEL, resolve_model_path-from runtime import UniModelTransformers, wait_for_gpu+from runtime import UniModelTransformersdef load_content(path: Path) -> list[dict]:@@ -48,7 +49,12 @@ def main(*, device="cuda:0"):parser.add_argument("--model",default=DEFAULT_MODEL,- help="Hugging Face model repo ID or complete local WePM export directory",+ help="Hugging Face model repo ID, local WePM export, or CPU GGUF bundle",+ )+ parser.add_argument(+ "--trust-model-code",+ action="store_true",+ help="execute the selected model's runtime_sources/ Python code with your user permissions",)parser.add_argument("--revision", help="Hub branch, tag or commit to download")parser.add_argument("--cache-dir", type=Path, help="Hugging Face download cache")@@ -61,8 +67,7 @@ def main(*, device="cuda:0"):parser.add_argument("--min-free-gib",type=float,- default=14,- help="required free CUDA memory before loading (default: 14 GiB for 4B)",+ help="required free CUDA memory (default: checkpoint size plus 2 GiB)",)parser.add_argument("--task", choices=["generate", "embed", "both", "decision"], default="generate"@@ -84,6 +89,15 @@ def main(*, device="cuda:0"):parser.add_argument("--threads", type=int, default=8, help="CPU compute threads (default: 8)")+ parser.add_argument(+ "--gguf-variant",+ choices=["q4", "bf16"],+ help="GGUF language weights (default: q4)",+ )+ parser.add_argument("--gguf-library", type=Path, help="path to libwepm_gguf")+ parser.add_argument(+ "--context-size", type=int, help="GGUF context size (default: 4096)"+ )parser.add_argument("--embedding-dim",type=int,@@ -93,19 +107,26 @@ def main(*, device="cuda:0"):"--timeout",type=int,default=1200,- help="Maximum inference lifetime in seconds (1-1800)",+ help="Request interruption after 1-1800 seconds, excluding download (default: 1200). "+ "Native calls may delay interruption until they return.",)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 not is_cpu and not 0 < args.min_free_gib < float("inf"):- parser.error("min-free-gib must be finite and positive")+ if (+ not is_cpu+ and args.min_free_gib is not None+ and (not math.isfinite(args.min_free_gib) or args.min_free_gib < 0)+ ):+ parser.error("min-free-gib must be finite and nonnegative")if args.embedding_dim is not None and args.embedding_dim < 1:parser.error("embedding-dim must be positive")if is_cpu:if args.threads < 1:parser.error("threads must be positive")+ if args.context_size is not None and args.context_size < 128:+ parser.error("context-size must be at least 128")torch.set_num_threads(args.threads)torch.set_num_interop_threads(1)if (args.task == "decision") != (args.decision_json is not None):@@ -128,7 +149,7 @@ def main(*, device="cuda:0"):prompt = "请用一句话介绍你自己。"if prompt:content.append({"type": "text", "text": prompt})- if args.output.exists():+ if args.output.exists() or args.output.is_symlink():raise FileExistsError(args.output)model_dir = resolve_model_path(args.model,@@ -136,19 +157,46 @@ def main(*, device="cuda:0"):cache_dir=args.cache_dir,local_files_only=args.local_files_only,)+ backend = "gguf" if (model_dir / "bundle.json").is_file() else "hf"+ if backend == "gguf" and not is_cpu:+ parser.error("the GGUF backend runs on CPU; use inference/infer_cpu.py")+ if (+ is_cpu+ and backend == "hf"+ and any(+ value is not None+ for value in (args.gguf_variant, args.gguf_library, args.context_size)+ )+ ):+ parser.error("GGUF options require a GGUF bundle")def timeout_handler(_signum, _frame):raise TimeoutError(f"inference exceeded {args.timeout} seconds")signal.signal(signal.SIGALRM, timeout_handler)signal.alarm(args.timeout)- probe = Nonemodel = Nonetry:- if not is_cpu:- probe = wait_for_gpu(min_free_gib=args.min_free_gib)- backend = "hf"- model = UniModelTransformers(model_dir, device=device)+ if backend == "gguf":+ from gguf_runtime import UniModelGGUF++ language_precision = args.gguf_variant or "q4"+ model = UniModelGGUF(+ model_dir,+ variant=language_precision,+ library=args.gguf_library,+ context_size=args.context_size or 4096,+ threads=args.threads,+ trust_model_code=args.trust_model_code,+ )+ else:+ model = UniModelTransformers(+ model_dir,+ device=device,+ min_free_gib=None if is_cpu else args.min_free_gib,+ trust_model_code=args.trust_model_code,+ )+ language_precision = str(model.dtype)result = {}if args.task in ("generate", "both"):result["generation"] = model.generate(content, args.max_new_tokens)@@ -168,7 +216,7 @@ def main(*, device="cuda:0"):"output": str(args.output),"device": str(model.device),"backend": backend,- "language_precision": str(model.dtype),+ "language_precision": language_precision,"dtype": str(model.dtype),"generation": result.get("generation", {}).get("text"),"decision": result.get("decision", {}).get("answers"),@@ -179,7 +227,7 @@ def main(*, device="cuda:0"):finally:if model is not None and hasattr(model, "close"):model.close()- del model, probe+ del modelgc.collect()if not is_cpu:torch.cuda.empty_cache()diff --git a/inference/infer_cpu.py b/inference/infer_cpu.pyindex d68c409..6c96643 100755--- a/inference/infer_cpu.py+++ b/inference/infer_cpu.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Run Hugging Face G/E/J inference on CPU, then exit."""+"""Run Transformers or GGUF WePM inference on CPU, then exit."""import osdiff --git a/inference/model_source.py b/inference/model_source.pyindex 6aa50fa..c39de11 100644--- a/inference/model_source.py+++ b/inference/model_source.py@@ -1,55 +1,18 @@-"""Resolve a local WePM export or download a complete Hugging Face snapshot."""+"""Resolve a local WePM checkpoint or download a complete Hub snapshot."""from __future__ import annotations-import jsonfrom pathlib import Path+from checkpoint import WePMCheckpoint+DEFAULT_MODEL = "tencent/WePocketModel1.0-4B"def validate_model_directory(model_dir: Path) -> Path:- """Check the export contract before allocating inference resources."""- required = [- "export_complete.json",- "config.json",- "unimodel_aux.safetensors",- "tokenizer.json",- "tokenizer_config.json",- "processor_config.json",- "chat_template.jinja",- ]- required.extend(- f"runtime_sources/{name}.py"- for name in (- "generation_slots",- "decision_config",- "decision_protocol",- "image_geometry",- "mgvb",- "mgvb_utils",- "rope_utils",- )- )- missing = [name for name in required if not (model_dir / name).is_file()]- if missing:- raise ValueError(- f"incomplete WePM export at {model_dir}; missing: {', '.join(missing)}. "- "Download the complete model repository, not only the weight files."- )- manifest = json.loads((model_dir / "export_complete.json").read_text())- if manifest.get("schema") != "wepm-nvidia-task-slots-v1":- raise ValueError("a compatible task_slots_v1 WePM export is required")- index = model_dir / "model.safetensors.index.json"- if index.is_file():- weight_map = json.loads(index.read_text()).get("weight_map")- if not isinstance(weight_map, dict) or not weight_map:- raise ValueError(f"invalid weight index: {index}")- for filename in set(weight_map.values()):- if not isinstance(filename, str) or not (model_dir / filename).is_file():- raise ValueError(f"missing model weight shard: {filename}")- elif not (model_dir / "model.safetensors").is_file():- raise ValueError(f"missing model.safetensors or sharded weight index at {model_dir}")+ """Validate Transformers checkpoints before allocating model resources."""+ if not (model_dir / "bundle.json").is_file():+ WePMCheckpoint(model_dir)return model_dirdiff --git a/inference/native/CMakeLists.txt b/inference/native/CMakeLists.txtnew file mode 100644index 0000000..b79be43--- /dev/null+++ b/inference/native/CMakeLists.txt@@ -0,0 +1,27 @@+cmake_minimum_required(VERSION 3.20)+project(wepm_gguf LANGUAGES C CXX)++if(NOT DEFINED LLAMA_CPP_ROOT)+ message(FATAL_ERROR "Set LLAMA_CPP_ROOT to the pinned llama.cpp source directory")+endif()++set(CMAKE_CXX_STANDARD 17)+set(CMAKE_CXX_STANDARD_REQUIRED ON)+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")+set(CMAKE_BUILD_RPATH_USE_ORIGIN ON)+set(BUILD_SHARED_LIBS ON CACHE BOOL "" FORCE)+set(GGML_NATIVE OFF CACHE BOOL "" FORCE)+set(GGML_CUDA OFF CACHE BOOL "" FORCE)+set(GGML_METAL OFF CACHE BOOL "" FORCE)+set(GGML_BLAS OFF CACHE BOOL "" FORCE)+set(LLAMA_BUILD_COMMON OFF CACHE BOOL "" FORCE)+set(LLAMA_BUILD_TESTS OFF CACHE BOOL "" FORCE)+set(LLAMA_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)+set(LLAMA_BUILD_SERVER OFF CACHE BOOL "" FORCE)+set(LLAMA_BUILD_TOOLS OFF CACHE BOOL "" FORCE)+set(LLAMA_OPENSSL OFF CACHE BOOL "" FORCE)++add_subdirectory("${LLAMA_CPP_ROOT}" llama)+add_library(wepm_gguf SHARED wepm_gguf.cpp)+target_link_libraries(wepm_gguf PRIVATE llama)diff --git a/inference/native/wepm_gguf.cpp b/inference/native/wepm_gguf.cppnew file mode 100644index 0000000..e80f990--- /dev/null+++ b/inference/native/wepm_gguf.cpp@@ -0,0 +1,114 @@+// Stable, small CPU ABI over the pinned llama.cpp C API.+#include "llama.h"+#include <algorithm>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <memory>+#include <stdexcept>+#include <string>+#include <vector>++namespace {+thread_local std::string error;+void log_cpu(ggml_log_level level, const char * message, void *) {+ if (level == GGML_LOG_LEVEL_WARN || level == GGML_LOG_LEVEL_ERROR)+ std::fputs(message, stderr);+}+struct engine {+ llama_model * model = nullptr;+ llama_context * ctx = nullptr;+ int width = 0;+ int vocabulary = 0;+ int context = 0;+ ~engine() {+ if (ctx) llama_free(ctx);+ if (model) llama_model_free(model);+ }+};+}++extern "C" {+const char * wepm_error() { return error.c_str(); }+int wepm_abi_version() { return 1; }++void * wepm_load(const char * path, int context, int threads) {+ try {+ if (context < 128 || threads < 1) throw std::runtime_error("invalid CPU context or threads");+ llama_log_set(std::getenv("WEPM_GGUF_VERBOSE") ? nullptr : log_cpu, nullptr);+ llama_backend_init();+ auto value = std::make_unique<engine>();+ auto mp = llama_model_default_params();+ mp.n_gpu_layers = 0;+ mp.load_mtp = false;+ value->model = llama_model_load_from_file(path, mp);+ if (!value->model) throw std::runtime_error("failed to load GGUF language weights");+ value->width = llama_model_n_embd(value->model);+ value->vocabulary = llama_vocab_n_tokens(llama_model_get_vocab(value->model));+ value->context = context;+ auto cp = llama_context_default_params();+ cp.n_ctx = context;+ cp.n_batch = std::min(context, 256);+ cp.n_ubatch = cp.n_batch;+ cp.n_seq_max = 1;+ cp.n_threads = cp.n_threads_batch = threads;+ cp.pooling_type = LLAMA_POOLING_TYPE_NONE;+ cp.attention_type = LLAMA_ATTENTION_TYPE_CAUSAL;+ cp.offload_kqv = false;+ cp.op_offload = false;+ cp.no_perf = true;+ value->ctx = llama_init_from_model(value->model, cp);+ if (!value->ctx) throw std::runtime_error("failed to create CPU GGUF context");+ return value.release();+ } catch (const std::exception & ex) { error = ex.what(); return nullptr; }+}++void wepm_free(void * handle) { delete static_cast<engine *>(handle); }+int wepm_width(void * handle) { return static_cast<engine *>(handle)->width; }+int wepm_vocabulary(void * handle) { return static_cast<engine *>(handle)->vocabulary; }++// Inputs use section-major positions [sequence, height, width, temporal].+// Embedding input is used during both prefill and decode so multimodal RoPE+// coordinates remain independent of the physical cache position.+int wepm_eval(void * handle, const float * embeddings, const int32_t * positions,+ int count, int reset, int read_hidden, float * output) {+ try {+ auto * value = static_cast<engine *>(handle);+ if (!value || !embeddings || !positions || !output || count < 1)+ throw std::runtime_error("invalid GGUF evaluation input");+ if (positions[count-1] >= value->context)+ throw std::runtime_error("GGUF context budget exceeded");+ if (reset) llama_memory_clear(llama_get_memory(value->ctx), true);+ llama_set_causal_attn(value->ctx, true);+ llama_set_embeddings(value->ctx, read_hidden != 0);+ for (int offset = 0; offset < count; offset += 256) {+ const int size = std::min(256, count-offset);+ std::vector<llama_pos> pos(4*size);+ std::vector<int32_t> seq_counts(size, 1);+ std::vector<llama_seq_id> seq_values(size, 0);+ std::vector<llama_seq_id *> seqs(size);+ std::vector<int8_t> outputs(size, read_hidden ? 1 : 0);+ outputs.at(size-1) = 1;+ for (int i = 0; i < size; ++i) {+ seqs[i] = &seq_values[i];+ for (int axis = 0; axis < 4; ++axis)+ pos[axis*size+i] = positions[axis*count+offset+i];+ }+ llama_batch batch = {};+ batch.n_tokens = size;+ batch.embd = const_cast<float *>(embeddings + offset*value->width);+ batch.pos = pos.data();+ batch.n_seq_id = seq_counts.data();+ batch.seq_id = seqs.data();+ batch.logits = outputs.data();+ if (llama_decode(value->ctx, batch) != 0)+ throw std::runtime_error("llama_decode failed");+ }+ auto * data = read_hidden ? llama_get_embeddings_ith(value->ctx, -1)+ : llama_get_logits_ith(value->ctx, -1);+ if (!data) throw std::runtime_error("GGUF model did not return the requested output");+ std::memcpy(output, data, sizeof(float)*(read_hidden ? value->width : value->vocabulary));+ return 0;+ } catch (const std::exception & ex) { error = ex.what(); return -1; }+}+}diff --git a/inference/requirements-gguf.txt b/inference/requirements-gguf.txtnew file mode 100644index 0000000..d265dbd--- /dev/null+++ b/inference/requirements-gguf.txt@@ -0,0 +1,2 @@+-r requirements.txt+gguf==0.19.0diff --git a/inference/runtime.py b/inference/runtime.pyindex 9b2e4ee..af9cc69 100644--- a/inference/runtime.py+++ b/inference/runtime.py@@ -1,14 +1,15 @@-"""Transformers CPU/CUDA inference for the formal task_slots_v1 G/E/J model."""+"""Shared WePM tasks and the Transformers CPU/CUDA backend."""from __future__ import annotationsimport io-import json+import mathimport timefrom pathlib import Pathimport torchimport torch.nn.functional as F+from checkpoint import WePMCheckpoint, select_runtime_sourcesfrom common import load_contracts, load_runtime_sources, validate_architecturefrom model_source import resolve_model_pathfrom PIL import Image@@ -44,7 +45,9 @@ def prepare_content(content, prepare_image):and not isinstance(source, bytes)and Path(source).suffix.lower() in {".heic", ".heif"}):- raise RuntimeError("HEIC input requires pillow-heif; install requirements.txt")+ raise RuntimeError(+ "HEIC input requires pillow-heif; install requirements.txt"+ )with Image.open(io.BytesIO(source) if isinstance(source, bytes) else source) as original:@@ -59,25 +62,35 @@ def prepare_content(content, prepare_image):return processor_content, images, content_types-def wait_for_gpu(min_free_gib=14, timeout=120):+def wait_for_gpu(device, min_free_gib, timeout=120):"""Wait for sufficient free CUDA memory before loading the model."""- probe = torch.empty(256 * 1024, device="cuda", dtype=torch.float32)+ if not math.isfinite(min_free_gib) or min_free_gib < 0:+ raise ValueError("minimum free CUDA memory must be finite and nonnegative")deadline = time.monotonic() + timeout- while time.monotonic() < deadline:- free, total = torch.cuda.mem_get_info()- if free >= min_free_gib * 2**30:+ minimum = min_free_gib * 2**30+ while True:+ free, total = torch.cuda.mem_get_info(device)+ if total < minimum:+ raise RuntimeError(+ f"{device} has {total / 2**30:.2f} GiB total, below the "+ f"{min_free_gib:.2f} GiB threshold. Use --min-free-gib to override."+ )+ if free >= minimum:print(- f"CUDA ready: {free / 2**30:.1f}/{total / 2**30:.1f} GiB free",+ f"{device} ready: {free / 2**30:.2f}/{total / 2**30:.2f} GiB free "+ f"(minimum {min_free_gib:.2f} GiB)",flush=True,)- return probe- time.sleep(2)- raise RuntimeError(- f"CUDA memory did not reach {min_free_gib} GiB free within {timeout}s"- )+ return+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise RuntimeError(+ f"{device} did not reach {min_free_gib:.2f} GiB free within {timeout}s"+ )+ time.sleep(min(2, remaining))-class UniModelTransformers:+class WePMRuntime:"""Qwen3.5 + MGVB + independent E/J slots and trained task heads.Each call accepts one ordered text/image request. Generation uses a@@ -85,36 +98,22 @@ class UniModelTransformers: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 = resolve_model_path(model_dir)- self.config = json.loads((self.model_dir / "config.json").read_text())+ def _stop_token_ids(self) -> set[int]:+ stop_ids = set()+ for value in (+ self.config.get("eos_token_id"),+ self.processor.tokenizer.eos_token_id,+ ):+ if isinstance(value, list):+ stop_ids.update(value)+ elif value is not None:+ stop_ids.add(value)+ return stop_ids++ def _load_task_modules(self, runtime_sources, auxiliary):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+ self.model_dir, local_files_only=True, trust_remote_code=False)if not self.processor.chat_template:raise ValueError("missing saved training chat template")@@ -122,9 +121,6 @@ class UniModelTransformers:self.slot_token_id = self.processor.tokenizer.pad_token_idif 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")@@ -146,13 +142,7 @@ class UniModelTransformers: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"- )+ cls, self.get_rope_index = load_runtime_sources(runtime_sources)self.mgvb = cls(hidden,adapter_dim=c["unimodel_mgvb_adapter_dim"],@@ -206,12 +196,10 @@ class UniModelTransformers:"""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])+ native_features = [+ self._vision_features(patch, grid.unsqueeze(0))+ for patch, grid in zip(patches, grids, strict=True)+ ]return self.mgvb(native_features,image_grid_thw=grids,@@ -251,7 +239,7 @@ class UniModelTransformers:ids, native_lengths, compact_lengths = self._compact_image_tokens(ids, grids)- embeddings = self.model.get_input_embeddings()(ids)+ embeddings = self._token_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:@@ -292,60 +280,6 @@ class UniModelTransformers:}return ids, embeddings, position_ids, metadata- @torch.inference_mode()- 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(- content, 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, content, *, dims=None):"""Return normalized embedding vectors at the requested MRL dimensions."""@@ -353,14 +287,9 @@ class UniModelTransformers:_, embeddings, positions, metadata = self._prepare_inputs(content, task="embedding")- result = self.model.model.language_model(- inputs_embeds=embeddings,- position_ids=positions,- use_cache=False,- return_dict=True,- )+ hidden = self._last_hidden(embeddings, positions)# Training projects in the model dtype before FP32 L2 normalization.- projected = F.linear(result.last_hidden_state[:, -1, :], self.head).float()+ projected = F.linear(hidden, 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"]@@ -406,17 +335,10 @@ class UniModelTransformers:_, embeddings, positions, metadata = self._prepare_inputs(decision_content, task="decision")- result = self.model.model.language_model(- inputs_embeds=embeddings,- position_ids=positions,- use_cache=False,- return_dict=True,- )+ hidden = self._last_hidden(embeddings, positions)# 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]+ logits = F.linear(hidden, self.decision_head).float()[0, :count]if not torch.isfinite(logits).all():raise ValueError("nonfinite decision logits")probabilities = logits.softmax(dim=-1).cpu().tolist()@@ -426,3 +348,146 @@ class UniModelTransformers:"seconds": time.monotonic() - start,"input": metadata,}+++class UniModelTransformers(WePMRuntime):+ """Hugging Face backbone with the trained WePM task modules."""++ def __init__(+ self,+ model_dir: str | Path,+ device="cuda:0",+ *,+ min_free_gib=None,+ trust_model_code=False,+ ):+ path = Path(model_dir).expanduser()+ checkpoint = WePMCheckpoint(+ path if path.is_dir() else resolve_model_path(model_dir)+ )+ self.model_dir = checkpoint.path+ self.config = checkpoint.config+ c = self.config+ runtime_sources = select_runtime_sources(+ self.model_dir, trust_model_code=trust_model_code+ )+ self.contracts = load_contracts(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")+ if self.device.type == "cuda":+ if not torch.cuda.is_available():+ raise RuntimeError(+ "CUDA is not available. Use inference/infer_cpu.py on CPU."+ )+ if min_free_gib is None:+ # BF16 checkpoint size plus room for the CUDA context, cache and activations.+ min_free_gib = checkpoint.weight_bytes / 2**30 + 2+ wait_for_gpu(self.device, min_free_gib)+ # 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+ with checkpoint.backbone_directory() as backbone_dir:+ self.model, loading_info = Qwen3_5ForConditionalGeneration.from_pretrained(+ backbone_dir,+ dtype=self.dtype,+ device_map={"": str(self.device)},+ attn_implementation="sdpa",+ local_files_only=True,+ trust_remote_code=False,+ use_safetensors=True,+ output_loading_info=True,+ )+ for key in (+ "missing_keys",+ "unexpected_keys",+ "mismatched_keys",+ "error_msgs",+ "conversion_errors",+ ):+ if loading_info.get(key):+ raise ValueError(f"incomplete HF load: {key}={loading_info[key]}")+ self.loading_info = {+ key: sorted(value) if isinstance(value, set) else value+ for key, value in loading_info.items()+ }+ self.model.eval()+ auxiliary = load_file(checkpoint.auxiliary_path, device=str(self.device))+ if checkpoint.indexed_auxiliary_keys and (+ auxiliary.keys() != checkpoint.indexed_auxiliary_keys+ ):+ raise ValueError(+ "training export task weights do not match the shard index"+ )+ self._load_task_modules(runtime_sources, auxiliary)++ def _token_embeddings(self, ids):+ return self.model.get_input_embeddings()(ids)++ def _vision_features(self, pixels, grid):+ visual = self.model.model.get_image_features(pixels, grid, return_dict=True)+ return visual.pooler_output[0]++ def _last_hidden(self, embeddings, positions):+ result = self.model.model.language_model(+ inputs_embeds=embeddings,+ position_ids=positions,+ use_cache=False,+ return_dict=True,+ )+ return result.last_hidden_state[:, -1, :]++ @torch.inference_mode()+ 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(+ content, 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._stop_token_ids()+ 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,+ }diff --git a/inference/runtime_sources/decision_config.py b/inference/runtime_sources/decision_config.pynew file mode 100644index 0000000..f861729--- /dev/null+++ b/inference/runtime_sources/decision_config.py@@ -0,0 +1,79 @@+"""Shared, dependency-free JEV architecture contract for training and assets."""+from dataclasses import dataclass++TASK_SLOT_ARCHITECTURE = "task_slots_v1"+++def validate_task_slots(config, *, checkpoint=False):+ """One physical slot per E/J row; two independently learned role vectors."""+ get = config.get if isinstance(config, dict) else lambda k, d=None: getattr(config, k, d)+ try:+ from .generation_slots import generation_slots_enabled+ except ImportError:+ from generation_slots import generation_slots_enabled+ if (int(get("unimodel_slot_count", 1)) != 1+ or int(get("unimodel_slot_readout_index", 0)) != 0+ or generation_slots_enabled({"unimodel_generation_slot_enable":+ get("unimodel_generation_slot_enable", False)})):+ raise ValueError("task slots require slot_count=1, readout=0 and slotless generation")+ architecture = get("unimodel_architecture", None)+ if architecture not in ((TASK_SLOT_ARCHITECTURE,) if checkpoint else (None, TASK_SLOT_ARCHITECTURE)):+ raise ValueError("legacy combined E/J checkpoint/config is incompatible with task_slots_v1")+++@dataclass(frozen=True)+class DecisionConfig:+ head_type: str = "matching"+ max_candidates: int = 255++ @property+ def output_size(self):+ # Fixed independent of TP world size, so checkpoints remain portable.+ # Spare rows are never included in the decision distribution.+ return ((self.max_candidates + 127) // 128) * 128++ @classmethod+ def from_config(cls, config):+ get = config.get if isinstance(config, dict) else lambda k, d: getattr(config, k, d)+ head = get("unimodel_decision_head_type", "matching")+ capacity = get("unimodel_decision_max_candidates", 255)+ if head not in {"matching", "direct"}:+ raise ValueError("unimodel_decision_head_type must be matching or direct")+ # Read-only compatibility guard for the withdrawn attention variant.+ # Do not silently load a noncausal checkpoint as a causal model.+ if get("unimodel_decision_attention", "causal") != "causal":+ raise ValueError("JEV uses the shared causal backbone; legacy noncausal decision checkpoints/configs are unsupported")+ if isinstance(capacity, bool) or not isinstance(capacity, int) or capacity < 2:+ raise ValueError("unimodel_decision_max_candidates must be an integer >= 2")+ return cls(head, capacity)+++def validate_decision_checkpoint(source, runtime, weight_names, *, allow_native_initialization=False):+ """Reject random reinitialization or architecture changes during HF load."""+ get = runtime.get if isinstance(runtime, dict) else lambda k, d: getattr(runtime, k, d)+ source_enabled = source.get("unimodel_decision_enable", False)+ runtime_enabled = get("unimodel_decision_enable", False)+ weight_names = tuple(weight_names)+ if (allow_native_initialization and runtime_enabled is True+ and source.get("model_type") == "qwen3_5"+ and not any(key.startswith("unimodel") for key in source)+ and not any("unimodel" in name or "embedding_head" in name for name in weight_names)):+ # Native backbone loading intentionally leaves newly attached modules+ # initialized by Megatron. Existing UniModel checkpoints stay strict.+ DecisionConfig.from_config(runtime)+ validate_task_slots(runtime)+ return+ if not source_enabled and not runtime_enabled:+ return+ if source_enabled is not True or runtime_enabled is not True:+ raise ValueError("JEV checkpoint enable mismatch; migrate explicitly with a fresh optimizer")+ validate_task_slots(source, checkpoint=True)+ validate_task_slots(runtime)+ saved, requested = DecisionConfig.from_config(source), DecisionConfig.from_config(runtime)+ if saved != requested:+ raise ValueError("JEV checkpoint architecture mismatch; migrate explicitly with a fresh optimizer")+ roles = ("output",) if saved.head_type == "direct" else ("query", "candidate")+ expected = {f"unimodel.decision_head.{role}.weight" for role in roles}+ actual = {name for name in weight_names if name.startswith("unimodel.decision_head.")}+ if expected != actual:+ raise ValueError(f"JEV checkpoint head weights mismatch: expected {sorted(expected)}, got {sorted(actual)}")diff --git a/inference/runtime_sources/decision_protocol.py b/inference/runtime_sources/decision_protocol.pynew file mode 100644index 0000000..5f5179d--- /dev/null+++ b/inference/runtime_sources/decision_protocol.py@@ -0,0 +1,155 @@+"""SystemOne-visible JEV inputs shared by training and inference.++Transport JSON is decoded into one question. Gold fields never enter the+renderer; score values only establish ordinal order in training assets.+"""+import base64+import binascii+import json+import math+from dataclasses import dataclass++INPUT_PROFILE = "systemone_visible_v1"+NOUL_DESCRIPTIONS = ("No / false", "Yes / true")+++def state_text(state):+ if isinstance(state, str):+ return state+ if not isinstance(state, dict):+ raise ValueError("state must be an object or string")+ return json.dumps(state, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)+++@dataclass(frozen=True)+class DecisionInput:+ kind: str+ context: str+ instructions: str+ ids: tuple[str, ...]+ descriptions: tuple[str, ...]++ def __post_init__(self):+ if self.kind not in {"choice", "score", "noul"}:+ raise ValueError("unsupported decision type")+ if not isinstance(self.instructions, str) or not self.instructions.strip():+ raise ValueError("decision instructions must be nonempty")+ if (len(self.ids) < 2 or len(self.ids) != len(self.descriptions)+ or len(set(self.ids)) != len(self.ids)+ or any(not isinstance(x, str) or not x for x in self.ids)+ or any(not isinstance(x, str) or not x.strip() for x in self.descriptions)):+ raise ValueError("invalid decision candidates")+++def training_input(sample):+ """Return visible input and source indices aligning the training targets."""+ context = sample["context"]+ if context.get("format") not in {"text", "json"} or not isinstance(context.get("payload"), str):+ raise ValueError("invalid decision context")+ state = json.loads(context["payload"]) if context["format"] == "json" else context["payload"]+ decision = sample["decision"]+ # Platform loaders use the question text when meta.state is None or "".+ # Normalized training assets carry that text in decision.instructions.+ if state is None or state == "":+ state = decision["instructions"]+ options = decision["options"]+ kind = decision["kind"]+ order = tuple(range(len(options)))+ if kind == "score":+ values = [o.get("score_value") for o in options]+ if any(v is not None for v in values):+ if any(isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) for v in values):+ raise ValueError("score scale must be wholly known or wholly ordinal")+ order = tuple(sorted(order, key=lambda i: values[i]))+ ids = tuple(str(i) for i in range(len(options)))+ descriptions = tuple(options[i]["description"] for i in order)+ elif kind == "noul":+ if [o["option_id"] for o in options] != ["false", "true"]:+ raise ValueError("Noul order must be false,true")+ ids, descriptions = ("false", "true"), NOUL_DESCRIPTIONS+ else:+ ids = tuple(o["option_id"] for o in options)+ descriptions = tuple(o["description"] for o in options)+ return DecisionInput(kind, state_text(state), decision["instructions"], ids, descriptions), order+++def request_input(request):+ """Decode the documented single-question /systemone protocol, without gold."""+ questions = request.get("questions")+ if not isinstance(questions, dict) or set(questions) != {"q"}:+ raise ValueError("expected exactly questions.q")+ q = questions["q"]+ if not isinstance(q, dict):+ raise ValueError("question must be an object")+ kind = q.get("type")+ if kind == "choice":+ criteria = q.get("criteria")+ if not isinstance(criteria, dict):+ raise ValueError("choice criteria must be an object")+ ids, descriptions = tuple(criteria), tuple(criteria.values())+ elif kind == "score":+ criteria = q.get("criteria")+ if not isinstance(criteria, list):+ raise ValueError("score criteria must be an ordered list")+ ids, descriptions = tuple(str(i) for i in range(len(criteria))), tuple(criteria)+ elif kind == "noul":+ if "criteria" in q:+ raise ValueError("noul has no criteria")+ ids, descriptions = ("false", "true"), NOUL_DESCRIPTIONS+ else:+ raise ValueError("unsupported decision type")+ if "state" not in request:+ raise ValueError("request must include state")+ state = request["state"]+ if state is None or state == "":+ state = q.get("instructions")+ return DecisionInput(kind, state_text(state), q.get("instructions"), ids, descriptions)+++def request_images(request):+ images = request.get("images", [])+ if not isinstance(images, list) or len(images) > 8:+ raise ValueError("expected at most eight ordered images")+ result = []+ for image in images:+ if not isinstance(image, str):+ raise ValueError("image must be a base64 data URL")+ header, separator, content = image.partition(",")+ if not separator or not header.startswith("data:image/") or not header.endswith(";base64"):+ raise ValueError("image must be a base64 data URL")+ try:+ blob = base64.b64decode(content, validate=True)+ except (ValueError, binascii.Error) as exc:+ raise ValueError("invalid image base64") from exc+ if not blob:+ raise ValueError("empty image")+ result.append(blob)+ return result+++def render_input(value):+ text = ("Evaluate the candidates using the context and instructions.\n"+ f"Context:\n{value.context}\nDecision type: {value.kind}\n"+ f"Instructions:\n{value.instructions}\nCandidates:\n")+ spans = []+ for index, (key, description) in enumerate(zip(value.ids, value.descriptions, strict=True)):+ text += f"{index}: "+ if value.kind == "choice":+ text += "id=" + json.dumps(key, ensure_ascii=False) + " description="+ start = len(text)+ text += json.dumps(description, ensure_ascii=False)+ spans.append((start, len(text)))+ text += "\n"+ return text.rstrip("\n"), spans+++def response_from_probabilities(value, probabilities):+ probs = list(probabilities)+ if len(probs) != len(value.ids) or any(isinstance(p, bool) or not isinstance(p, (int, float))+ or not math.isfinite(p) or not 0 <= p <= 1 for p in probs):+ raise ValueError("invalid candidate probability vector")+ if not math.isclose(sum(probs), 1., abs_tol=1e-5, rel_tol=0):+ raise ValueError("probabilities must sum to one")+ answer = ({"noul": probs[1]} if value.kind == "noul" else+ {"probabilities": dict(zip(value.ids, probs, strict=True))})+ return {"answers": {"q": answer}}diff --git a/inference/runtime_sources/generation_slots.py b/inference/runtime_sources/generation_slots.pynew file mode 100644index 0000000..94fc1dd--- /dev/null+++ b/inference/runtime_sources/generation_slots.py@@ -0,0 +1,43 @@+"""Generation-only slot policy, shared by training and serving.++The request ID carries an explicit slotless marker. Never infer task identity+from token values: a literal pad/EOS at the end of a prompt is not a soft slot.+"""++GENERATION_SLOT_KEY = "unimodel_generation_slot_enable"+SLOTLESS_REQUEST_PREFIX = "unimodel-slotless:"+++def generation_slots_enabled(settings):+ value = settings.get(GENERATION_SLOT_KEY, not settings.get("unimodel_decision_enable", False))+ if isinstance(value, bool):+ return value+ if isinstance(value, (int, str)):+ value = str(value).strip().lower()+ if value in {"1", "true", "yes", "y", "on"}:+ return True+ if value in {"0", "false", "no", "n", "off"}:+ return False+ raise ValueError(f"{GENERATION_SLOT_KEY} must be a boolean")+++def generation_request_id(request_id, enabled):+ if str(request_id).startswith(SLOTLESS_REQUEST_PREFIX):+ raise ValueError("request ID already contains a reserved slot policy marker")+ return str(request_id) if enabled else SLOTLESS_REQUEST_PREFIX + str(request_id)+++def prefill_slot_requests(embedding, forward_batch, count):+ """One explicit policy per full prefill; embedding requests remain slotted."""+ enabled = getattr(embedding, "_unimodel_generation_slot_enable", True)+ rids = getattr(forward_batch, "rids", None)+ if rids is None:+ if not enabled:+ raise RuntimeError("slotless generation requires SGLang forward request IDs")+ return [True] * count+ if len(rids) != count:+ raise RuntimeError("slot policy request IDs do not match prefill boundaries")+ slotted = [not str(rid).startswith(SLOTLESS_REQUEST_PREFIX) for rid in rids]+ if enabled and not all(slotted):+ raise RuntimeError("slotless request sent to a slotted generation checkpoint")+ return slotteddiff --git a/inference/runtime_sources/image_geometry.py b/inference/runtime_sources/image_geometry.pynew file mode 100644index 0000000..a6093e8--- /dev/null+++ b/inference/runtime_sources/image_geometry.py@@ -0,0 +1,27 @@+"""Shared model-input geometry; preserve all pixels in extreme-aspect images."""+import math+++def prepared_sizes(width, height, max_long_edge=1500):+ if width < 1 or height < 1:+ raise ValueError('image dimensions must be positive')+ scale = min(1.0, max_long_edge / max(width, height)) if max_long_edge > 0 else 1.0+ resized = (max(1, round(width * scale)), max(1, round(height * scale)))+ w, h = resized+ # Padding only on the right/bottom preserves the origin and existing pixels.+ # Apply after rounding: a legal original aspect ratio can become illegal+ # when a narrow dimension rounds down during long-edge resizing.+ padded = (max(w, math.ceil(h / 200)), max(h, math.ceil(w / 200)))+ return resized, padded+++def prepare_model_image(image, max_long_edge=1500):+ from PIL import Image+ resized, padded = prepared_sizes(*image.size, max_long_edge)+ if image.size != resized:+ image = image.resize(resized, resample=Image.Resampling.BICUBIC)+ if resized != padded:+ result = Image.new(image.mode, padded, 'white')+ result.paste(image, (0, 0))+ image = result+ return imagediff --git a/inference/runtime_sources/mgvb.py b/inference/runtime_sources/mgvb.pynew file mode 100644index 0000000..f55a0d4--- /dev/null+++ b/inference/runtime_sources/mgvb.py@@ -0,0 +1,643 @@+"""True Multi-Granularity Visual Bottleneck for Qwen3.5 UniModel training."""++from __future__ import annotations++import math+from dataclasses import dataclass+from typing import Any, Iterable, Sequence++import torch+import torch.nn.functional as F++from mbridge.models.qwen3_5.mgvb_utils import (+ build_mgvb_visual_positions,+ cell_assignment,+ cell_edges,+ merged_grid_shape,+ native_visual_positions,+ partition_spatial_grid,+)++MGVB_ADDITIVE_METRICS = frozenset({+ "mgvb/reconstruction_loss", "mgvb/diversity_loss", "mgvb/aux_loss",+})+++def _as_bool(value: Any, default: bool = False) -> bool:+ if value is None:+ return default+ if isinstance(value, bool):+ return value+ return str(value).strip().lower() in {"1", "true", "yes", "y", "on"}+++def is_mgvb_enabled(hf_config: Any) -> bool:+ return _as_bool(getattr(hf_config, "unimodel_mgvb_enable", False))+++class _RMSNorm(torch.nn.Module):+ def __init__(self, hidden_size: int, *, eps: float = 1e-6, device=None, dtype=None) -> None:+ super().__init__()+ self.weight = torch.nn.Parameter(torch.ones(hidden_size, device=device, dtype=dtype))+ self.eps = float(eps)++ def forward(self, value: torch.Tensor) -> torch.Tensor:+ normalized = value.float() * torch.rsqrt(+ value.float().square().mean(dim=-1, keepdim=True) + self.eps+ )+ return normalized.to(value.dtype) * self.weight+++class _AdapterResidual(torch.nn.Module):+ def __init__(self, adapter_dim: int, hidden_size: int, *, device=None, dtype=None) -> None:+ super().__init__()+ self.norm = torch.nn.LayerNorm(adapter_dim, device=device, dtype=dtype)+ self.fc1 = torch.nn.Linear(adapter_dim, adapter_dim * 2, bias=False, device=device, dtype=dtype)+ self.fc2 = torch.nn.Linear(adapter_dim * 2, hidden_size, bias=False, device=device, dtype=dtype)+ torch.nn.init.zeros_(self.fc2.weight)++ def forward(self, value: torch.Tensor) -> torch.Tensor:+ return self.fc2(F.gelu(self.fc1(self.norm(value))))+++@dataclass+class MGVBForwardOutput:+ embeddings: list[torch.Tensor]+ positions: list[torch.Tensor]+++class MultiGranularityVisualBottleneck(torch.nn.Module):+ """Replace long native visual sequences with a fixed G/R/F token bank."""++ def __init__(+ self,+ hidden_size: int,+ *,+ adapter_dim: int = 512,+ token_budget: int = 256,+ global_tokens: int = 8,+ region_tokens: int = 64,+ num_global_heads: int = 8,+ device=None,+ dtype=None,+ ) -> None:+ super().__init__()+ self.hidden_size = int(hidden_size)+ self.adapter_dim = int(adapter_dim)+ self.token_budget = int(token_budget)+ self.global_tokens = int(global_tokens)+ self.region_tokens = int(region_tokens)+ self.fine_tokens = self.token_budget - self.global_tokens - self.region_tokens+ self.num_global_heads = int(num_global_heads)+ if self.hidden_size < 1 or self.adapter_dim < 1:+ raise ValueError("MGVB hidden and adapter dimensions must be positive")+ if self.token_budget < 3:+ raise ValueError("MGVB token budget must be at least three")+ if min(self.global_tokens, self.region_tokens, self.fine_tokens) < 1:+ raise ValueError(+ "MGVB budget must leave positive global, region, and fine branches; "+ f"got total={self.token_budget}, global={self.global_tokens}, "+ f"region={self.region_tokens}, fine={self.fine_tokens}"+ )+ if self.adapter_dim % self.num_global_heads:+ raise ValueError(+ f"adapter_dim={self.adapter_dim} must be divisible by num_global_heads={self.num_global_heads}"+ )++ self.input_norm = _RMSNorm(hidden_size, device=device, dtype=dtype)+ self.input_proj = torch.nn.Linear(hidden_size, adapter_dim, bias=False, device=device, dtype=dtype)+ self.query_proj = torch.nn.Linear(hidden_size * 2, adapter_dim, bias=False, device=device, dtype=dtype)+ self.null_query = torch.nn.Parameter(torch.zeros(adapter_dim, device=device, dtype=dtype))++ self.global_queries = torch.nn.Parameter(+ torch.empty(global_tokens, adapter_dim, device=device, dtype=dtype)+ )+ self.global_key = torch.nn.Linear(adapter_dim, adapter_dim, bias=False, device=device, dtype=dtype)+ self.global_value = torch.nn.Linear(adapter_dim, adapter_dim, bias=False, device=device, dtype=dtype)+ self.global_query_condition = torch.nn.Linear(+ adapter_dim, adapter_dim, bias=False, device=device, dtype=dtype+ )+ self.global_residual = _AdapterResidual(adapter_dim, hidden_size, device=device, dtype=dtype)++ self.region_value = torch.nn.Linear(adapter_dim, adapter_dim, bias=False, device=device, dtype=dtype)+ self.region_query = torch.nn.Linear(adapter_dim, adapter_dim, bias=False, device=device, dtype=dtype)+ self.region_position = torch.nn.Linear(4, adapter_dim, bias=False, device=device, dtype=dtype)+ self.region_score = torch.nn.Linear(adapter_dim, 1, bias=False, device=device, dtype=dtype)+ self.region_residual = _AdapterResidual(adapter_dim, hidden_size, device=device, dtype=dtype)++ self.fine_value = torch.nn.Linear(adapter_dim, adapter_dim, bias=False, device=device, dtype=dtype)+ self.fine_query = torch.nn.Linear(adapter_dim, adapter_dim, bias=False, device=device, dtype=dtype)+ self.fine_position = torch.nn.Linear(4, adapter_dim, bias=False, device=device, dtype=dtype)+ self.fine_score = torch.nn.Linear(adapter_dim, 1, bias=False, device=device, dtype=dtype)+ self.fine_residual = _AdapterResidual(adapter_dim, hidden_size, device=device, dtype=dtype)++ self.granularity_embedding = torch.nn.Embedding(3, hidden_size, device=device, dtype=dtype)+ self.output_position = torch.nn.Linear(4, hidden_size, bias=False, device=device, dtype=dtype)+ self.reconstruction_position = torch.nn.Linear(+ 4, hidden_size, bias=False, device=device, dtype=dtype+ )+ self.reconstruction_norm = torch.nn.LayerNorm(hidden_size, device=device, dtype=dtype)+ self.reconstruction_fc1 = torch.nn.Linear(+ hidden_size, adapter_dim, bias=False, device=device, dtype=dtype+ )+ self.reconstruction_fc2 = torch.nn.Linear(+ adapter_dim, hidden_size, bias=False, device=device, dtype=dtype+ )++ torch.nn.init.normal_(self.global_queries, mean=0.0, std=0.02)+ torch.nn.init.zeros_(self.global_query_condition.weight)+ torch.nn.init.zeros_(self.region_query.weight)+ torch.nn.init.zeros_(self.fine_query.weight)+ torch.nn.init.zeros_(self.region_position.weight)+ torch.nn.init.zeros_(self.fine_position.weight)+ torch.nn.init.zeros_(self.region_score.weight)+ torch.nn.init.zeros_(self.fine_score.weight)+ torch.nn.init.normal_(self.granularity_embedding.weight, mean=0.0, std=0.002)+ torch.nn.init.normal_(self.output_position.weight, mean=0.0, std=0.002)+ torch.nn.init.normal_(self.reconstruction_position.weight, mean=0.0, std=0.002)++ self.unimodel_last_mgvb_metrics: dict[str, torch.Tensor] | None = None+ self.unimodel_last_mgvb_losses: dict[str, torch.Tensor] | None = None++ @staticmethod+ def _normalized_coordinates(+ temporal: int,+ height: int,+ width: int,+ *,+ device: torch.device,+ dtype: torch.dtype,+ ) -> torch.Tensor:+ positions = native_visual_positions(+ [temporal, height, width],+ spatial_merge_size=1,+ device=device,+ ).to(dtype=dtype)+ denominators = positions.new_tensor(+ [max(temporal - 1, 1), max(height - 1, 1), max(width - 1, 1)]+ )+ normalized = positions / denominators+ area = positions.new_full((positions.shape[0], 1), 1.0 / max(height * width, 1))+ return torch.cat([normalized, area], dim=-1)++ def _query(self, query_embedding: torch.Tensor | None, reference: torch.Tensor) -> torch.Tensor:+ if query_embedding is None:+ return self.null_query.to(device=reference.device, dtype=reference.dtype)+ if query_embedding.shape[-1] != self.hidden_size * 2:+ raise ValueError(+ f"MGVB query embedding must have size {self.hidden_size * 2}, got {query_embedding.shape}"+ )+ return self.query_proj(+ query_embedding.to(device=reference.device, dtype=self.query_proj.weight.dtype)+ ).to(dtype=reference.dtype)++ @staticmethod+ def _segment_softmax(+ logits: torch.Tensor,+ segment_ids: torch.Tensor,+ segment_count: int,+ ) -> torch.Tensor:+ work = logits.float()+ # P800's XPU backend does not implement aten::scatter_reduce.two_out.+ # Build the small segment-by-edge attention matrix instead: MGVB has at+ # most one row per output token (64 region / 184 fine by default), so+ # this remains bounded while using only well-supported softmax/gather+ # kernels. Every segment is non-empty by the spatial-cell contract.+ row_ids = torch.arange(segment_count, device=segment_ids.device).unsqueeze(1)+ membership = row_ids.eq(segment_ids.unsqueeze(0))+ segmented_logits = work.unsqueeze(0).expand(segment_count, -1).masked_fill(+ ~membership, -torch.inf+ )+ segmented_weights = F.softmax(segmented_logits, dim=-1)+ weights = segmented_weights.gather(0, segment_ids.unsqueeze(0)).squeeze(0)+ return weights.to(logits.dtype)++ def _segment_pool(+ self,+ *,+ native: torch.Tensor,+ adapter: torch.Tensor,+ normalized_positions: torch.Tensor,+ query: torch.Tensor,+ token_indices: torch.Tensor,+ segment_ids: torch.Tensor,+ segment_count: int,+ value_proj: torch.nn.Linear,+ query_proj: torch.nn.Linear,+ position_proj: torch.nn.Linear,+ score_proj: torch.nn.Linear,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ edge_adapter = adapter.index_select(0, token_indices)+ score_hidden = value_proj(edge_adapter)+ score_hidden = score_hidden + query_proj(query).unsqueeze(0)+ score_hidden = score_hidden + position_proj(normalized_positions.index_select(0, token_indices))+ logits = score_proj(torch.tanh(score_hidden)).squeeze(-1)+ weights = self._segment_softmax(logits, segment_ids, segment_count)++ pooled_native = native.new_zeros((segment_count, native.shape[-1]))+ pooled_native.index_add_(+ 0,+ segment_ids,+ native.index_select(0, token_indices) * weights.to(native.dtype).unsqueeze(-1),+ )+ pooled_adapter = adapter.new_zeros((segment_count, adapter.shape[-1]))+ pooled_adapter.index_add_(+ 0,+ segment_ids,+ edge_adapter * weights.to(adapter.dtype).unsqueeze(-1),+ )+ return pooled_native, pooled_adapter++ @staticmethod+ def _position_features(+ positions: torch.Tensor,+ temporal: int,+ height: int,+ width: int,+ *,+ dtype: torch.dtype,+ ) -> torch.Tensor:+ values = positions.to(dtype=dtype)+ denominators = values.new_tensor(+ [max(temporal - 1, 1), max(height - 1, 1), max(width - 1, 1)]+ )+ normalized = values / denominators+ area = values.new_zeros((values.shape[0], 1))+ return torch.cat([normalized, area], dim=-1)++ def _decorate(+ self,+ tokens: torch.Tensor,+ positions: torch.Tensor,+ granularity: int,+ temporal: int,+ height: int,+ width: int,+ ) -> torch.Tensor:+ type_ids = torch.full(+ (tokens.shape[0],), granularity, dtype=torch.long, device=tokens.device+ )+ position_features = self._position_features(+ positions,+ temporal,+ height,+ width,+ dtype=self.output_position.weight.dtype,+ )+ return (+ tokens+ + self.granularity_embedding(type_ids).to(tokens.dtype)+ + self.output_position(position_features).to(tokens.dtype)+ )++ def _compress_one(+ self,+ native: torch.Tensor,+ grid_thw,+ query_embedding: torch.Tensor | None,+ spatial_merge_size: int,+ ) -> tuple[torch.Tensor, torch.Tensor, dict[str, torch.Tensor], dict[str, torch.Tensor]]:+ temporal, height, width = merged_grid_shape(grid_thw, spatial_merge_size)+ expected = temporal * height * width+ if native.shape != (expected, self.hidden_size):+ raise ValueError(+ f"MGVB expected native embeddings {(expected, self.hidden_size)}, got {tuple(native.shape)}"+ )+ native_positions = native_visual_positions(+ grid_thw, spatial_merge_size, device=native.device+ )+ zero = native.sum() * 0.0+ if expected <= self.token_budget:+ metrics = {+ "mgvb/native_visual_tokens": native.new_tensor(float(expected)),+ "mgvb/compact_visual_tokens": native.new_tensor(float(expected)),+ "mgvb/compression_ratio": native.new_tensor(1.0),+ "mgvb/global_tokens": native.new_tensor(0.0),+ "mgvb/region_tokens": native.new_tensor(0.0),+ "mgvb/fine_tokens": native.new_tensor(float(expected)),+ "mgvb/bypass_ratio": native.new_tensor(1.0),+ }+ return native, native_positions, metrics, {"reconstruction": zero, "diversity": zero}++ adapter = self.input_proj(self.input_norm(native))+ query = self._query(query_embedding, adapter)+ normalized_positions = self._normalized_coordinates(+ temporal,+ height,+ width,+ device=native.device,+ dtype=adapter.dtype,+ )++ conditioned_queries = self.global_queries.to(adapter.dtype)+ conditioned_queries = conditioned_queries + self.global_query_condition(query).unsqueeze(0)+ head_dim = self.adapter_dim // self.num_global_heads+ global_query_heads = conditioned_queries.view(+ self.global_tokens, self.num_global_heads, head_dim+ )+ global_key_heads = self.global_key(adapter).view(+ expected, self.num_global_heads, head_dim+ )+ global_value_heads = self.global_value(adapter).view(+ expected, self.num_global_heads, head_dim+ )+ global_logits = torch.einsum(+ "ghd,nhd->ghn", global_query_heads.float(), global_key_heads.float()+ ) / math.sqrt(head_dim)+ global_weights = F.softmax(global_logits, dim=-1).to(adapter.dtype)+ # Average the head maps for a stable direct native-feature path; the+ # learned multi-head values supply the branch residual.+ global_native = global_weights.mean(dim=1).to(native.dtype).matmul(native)+ global_adapter = torch.einsum(+ "ghn,nhd->ghd", global_weights, global_value_heads+ ).reshape(self.global_tokens, self.adapter_dim)+ global_tokens = global_native + self.global_residual(global_adapter).to(native.dtype)++ region_cells = partition_spatial_grid(temporal, height, width, self.region_tokens)+ region_token_indices, region_ids = cell_edges(+ region_cells,+ height,+ width,+ halo=1,+ device=native.device,+ )+ region_native, region_adapter = self._segment_pool(+ native=native,+ adapter=adapter,+ normalized_positions=normalized_positions,+ query=query,+ token_indices=region_token_indices,+ segment_ids=region_ids,+ segment_count=self.region_tokens,+ value_proj=self.region_value,+ query_proj=self.region_query,+ position_proj=self.region_position,+ score_proj=self.region_score,+ )+ region_tokens = region_native + self.region_residual(region_adapter).to(native.dtype)++ fine_cells = partition_spatial_grid(temporal, height, width, self.fine_tokens)+ fine_token_indices, fine_ids = cell_edges(+ fine_cells,+ height,+ width,+ device=native.device,+ )+ fine_native, fine_adapter = self._segment_pool(+ native=native,+ adapter=adapter,+ normalized_positions=normalized_positions,+ query=query,+ token_indices=fine_token_indices,+ segment_ids=fine_ids,+ segment_count=self.fine_tokens,+ value_proj=self.fine_value,+ query_proj=self.fine_query,+ position_proj=self.fine_position,+ score_proj=self.fine_score,+ )+ fine_tokens = fine_native + self.fine_residual(fine_adapter).to(native.dtype)++ positions = build_mgvb_visual_positions(+ grid_thw,+ spatial_merge_size=spatial_merge_size,+ token_budget=self.token_budget,+ global_tokens=self.global_tokens,+ region_tokens=self.region_tokens,+ device=native.device,+ )+ global_positions = positions[: self.global_tokens]+ region_positions = positions[+ self.global_tokens : self.global_tokens + self.region_tokens+ ]+ fine_positions = positions[self.global_tokens + self.region_tokens :]+ global_tokens = self._decorate(+ global_tokens, global_positions, 0, temporal, height, width+ )+ region_tokens = self._decorate(+ region_tokens, region_positions, 1, temporal, height, width+ )+ fine_tokens = self._decorate(+ fine_tokens, fine_positions, 2, temporal, height, width+ )+ compact = torch.cat([global_tokens, region_tokens, fine_tokens], dim=0)+ if compact.shape != (self.token_budget, self.hidden_size):+ raise RuntimeError(f"MGVB emitted invalid compact shape {tuple(compact.shape)}")++ reconstruction_loss = zero.float()+ diversity_loss = zero.float()+ if self.training and torch.is_grad_enabled():+ region_assignment = cell_assignment(+ region_cells, height, width, device=native.device+ )+ fine_assignment = cell_assignment(fine_cells, height, width, device=native.device)+ reconstruction_context = (+ global_tokens.mean(dim=0, keepdim=True)+ + region_tokens.index_select(0, region_assignment)+ + fine_tokens.index_select(0, fine_assignment)+ ) / 3.0+ reconstruction_context = reconstruction_context + self.reconstruction_position(+ normalized_positions.to(self.reconstruction_position.weight.dtype)+ ).to(reconstruction_context.dtype)+ reconstruction = self.reconstruction_fc2(+ F.gelu(self.reconstruction_fc1(self.reconstruction_norm(reconstruction_context)))+ )+ target = native.detach()+ reconstruction_loss = (+ 1.0 - F.cosine_similarity(reconstruction.float(), target.float(), dim=-1).mean()+ ) + 0.1 * F.smooth_l1_loss(reconstruction.float(), target.float())++ normalized_global = F.normalize(global_tokens.float(), p=2, dim=-1)+ similarities = normalized_global.matmul(normalized_global.transpose(0, 1)).square()+ off_diagonal = 1.0 - torch.eye(+ self.global_tokens,+ device=similarities.device,+ dtype=similarities.dtype,+ )+ diversity_loss = (similarities * off_diagonal).sum() / max(+ self.global_tokens * (self.global_tokens - 1), 1+ )++ metrics = {+ "mgvb/native_visual_tokens": native.new_tensor(float(expected)),+ "mgvb/compact_visual_tokens": native.new_tensor(float(self.token_budget)),+ "mgvb/compression_ratio": native.new_tensor(float(self.token_budget / expected)),+ "mgvb/global_tokens": native.new_tensor(float(self.global_tokens)),+ "mgvb/region_tokens": native.new_tensor(float(self.region_tokens)),+ "mgvb/fine_tokens": native.new_tensor(float(self.fine_tokens)),+ "mgvb/bypass_ratio": native.new_tensor(0.0),+ }+ return compact, positions, metrics, {+ "reconstruction": reconstruction_loss,+ "diversity": diversity_loss,+ }++ def forward(+ self,+ image_embeddings: Iterable[torch.Tensor],+ *,+ image_grid_thw: Sequence[torch.Tensor] | torch.Tensor,+ query_embeddings: Sequence[torch.Tensor | None] | None = None,+ spatial_merge_size: int = 1,+ ) -> MGVBForwardOutput:+ image_embeddings = list(image_embeddings)+ if len(image_embeddings) != len(image_grid_thw):+ raise ValueError(+ f"MGVB received {len(image_embeddings)} image tensors but {len(image_grid_thw)} grids"+ )+ if query_embeddings is not None and len(query_embeddings) != len(image_embeddings):+ raise ValueError(+ f"MGVB received {len(query_embeddings)} queries for {len(image_embeddings)} images"+ )++ outputs: list[torch.Tensor] = []+ positions: list[torch.Tensor] = []+ all_metrics: dict[str, list[torch.Tensor]] = {}+ all_losses: dict[str, list[torch.Tensor]] = {"reconstruction": [], "diversity": []}+ for index, native in enumerate(image_embeddings):+ query = query_embeddings[index] if query_embeddings is not None else None+ compact, coords, metrics, losses = self._compress_one(+ native,+ image_grid_thw[index],+ query,+ spatial_merge_size,+ )+ outputs.append(compact)+ positions.append(coords)+ for key, value in metrics.items():+ all_metrics.setdefault(key, []).append(value.detach().float())+ for key, value in losses.items():+ all_losses[key].append(value)++ self.unimodel_last_mgvb_metrics = {+ key: torch.stack(values).mean() for key, values in all_metrics.items() if values+ }+ self.unimodel_last_mgvb_losses = {+ # Additive image numerators; normalize against the original logical+ # batch in the engine, never against this execution microbatch.+ key: torch.stack(values).sum() for key, values in all_losses.items() if values+ }+ return MGVBForwardOutput(outputs, positions)+++def attach_mgvb(model: torch.nn.Module | list[torch.nn.Module], *, hf_config: Any) -> int:+ if not is_mgvb_enabled(hf_config):+ return 0+ if _as_bool(getattr(hf_config, "unimodel_mgve_enable", False)):+ raise ValueError("UNIMODEL_MGVB_ENABLE and UNIMODEL_MGVE_ENABLE cannot both be true")++ roots = model if isinstance(model, list) else [model]+ attached = 0+ for root in roots:+ while hasattr(root, "module"):+ root = root.module+ if not getattr(root, "pre_process", True):+ continue+ if hasattr(root, "unimodel_mgvb"):+ raise RuntimeError("UniModel MGVB was attached more than once")+ language_model = getattr(root, "language_model", None)+ hidden_size = int(+ getattr(+ getattr(language_model, "config", None),+ "hidden_size",+ getattr(getattr(hf_config, "text_config", None), "hidden_size", 0),+ )+ )+ if hidden_size < 1:+ raise ValueError("cannot infer hidden_size for UniModel MGVB")+ reference = next(root.parameters(), None)+ module = MultiGranularityVisualBottleneck(+ hidden_size,+ adapter_dim=int(getattr(hf_config, "unimodel_mgvb_adapter_dim", 512)),+ token_budget=int(+ getattr(+ hf_config,+ "unimodel_mgvb_token_budget",+ getattr(hf_config, "unimodel_mgvb_total_budget", 256),+ )+ ),+ global_tokens=int(getattr(hf_config, "unimodel_mgvb_global_tokens", 8)),+ region_tokens=int(getattr(hf_config, "unimodel_mgvb_region_tokens", 64)),+ num_global_heads=int(getattr(hf_config, "unimodel_mgvb_num_global_heads", 8)),+ device=reference.device if reference is not None else None,+ dtype=reference.dtype if reference is not None else None,+ )+ for parameter in module.parameters():+ setattr(parameter, "average_gradients_across_tp_domain", True)+ root.unimodel_mgvb = module+ attached += 1+ return attached+++def _iter_roots(model: torch.nn.Module | list[torch.nn.Module]):+ roots = model if isinstance(model, list) else [model]+ for root in roots:+ while hasattr(root, "module"):+ root = root.module+ yield root+++def reset_mgvb_state(model: torch.nn.Module | list[torch.nn.Module]) -> None:+ for root in _iter_roots(model):+ mgvb = getattr(root, "unimodel_mgvb", None)+ if mgvb is not None:+ mgvb.unimodel_last_mgvb_metrics = None+ mgvb.unimodel_last_mgvb_losses = None+++def collect_mgvb_metrics(model: torch.nn.Module | list[torch.nn.Module]) -> dict[str, torch.Tensor]:+ collected: dict[str, list[torch.Tensor]] = {}+ for root in _iter_roots(model):+ mgvb = getattr(root, "unimodel_mgvb", None)+ metrics = getattr(mgvb, "unimodel_last_mgvb_metrics", None) if mgvb is not None else None+ if not metrics:+ continue+ for key, value in metrics.items():+ collected.setdefault(key, []).append(value.detach().float())+ return {key: torch.stack(values).mean() for key, values in collected.items() if values}+++def mgvb_auxiliary_loss(+ model: torch.nn.Module | list[torch.nn.Module],+ *,+ hf_config: Any,+ device: torch.device,+ global_sample_count: int,+ dp_size: int,+) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:+ """Sum image losses per logical example, averaged over the source batch.++ Text-only examples contribute zero; graph-free HNs do not contribute.+ E/OPD query-positive(-rollout) groups count as one logical example. DDP+ averages gradients, hence the DP factor on each rank's additive numerator.+ The caller cancels Megatron's microbatch averaging exactly once and applies+ the configured window denominator separately.+ """+ if global_sample_count < 1 or dp_size < 1:+ raise ValueError("MGVB requires positive source batch and DP sizes")+ scales = {+ "reconstruction": float(getattr(hf_config, "unimodel_mgvb_reconstruction_loss_scale", 0.05)),+ "diversity": float(getattr(hf_config, "unimodel_mgvb_diversity_loss_scale", 0.01)),+ }+ total = torch.zeros((), device=device)+ raw: dict[str, list[torch.Tensor]] = {key: [] for key in scales}+ for root in _iter_roots(model):+ mgvb = getattr(root, "unimodel_mgvb", None)+ losses = getattr(mgvb, "unimodel_last_mgvb_losses", None) if mgvb is not None else None+ if not losses:+ continue+ for key in scales:+ value = losses.get(key)+ if value is not None:+ raw[key].append(value.to(device=device))++ metrics: dict[str, torch.Tensor] = {}+ for key, values in raw.items():+ if not values:+ continue+ value = torch.stack(values).sum() * (dp_size / global_sample_count)+ metrics[f"mgvb/{key}_loss"] = value.detach().float()+ total = total + scales[key] * value+ if metrics:+ metrics["mgvb/aux_loss"] = total.detach().float()+ return total, metricsdiff --git a/inference/runtime_sources/mgvb_utils.py b/inference/runtime_sources/mgvb_utils.pynew file mode 100644index 0000000..ab2b9bf--- /dev/null+++ b/inference/runtime_sources/mgvb_utils.py@@ -0,0 +1,226 @@+"""Geometry helpers shared by Qwen3.5 True MGVB and multimodal M-RoPE."""++from __future__ import annotations++from dataclasses import dataclass++import torch+++@dataclass(frozen=True, order=True)+class SpatialCell:+ temporal: int+ top: int+ left: int+ bottom: int+ right: int++ @property+ def area(self) -> int:+ return (self.bottom - self.top) * (self.right - self.left)++ @property+ def height(self) -> int:+ return self.bottom - self.top++ @property+ def width(self) -> int:+ return self.right - self.left+++def merged_grid_shape(grid_thw, spatial_merge_size: int) -> tuple[int, int, int]:+ values = grid_thw.detach().to(device="cpu", dtype=torch.long).tolist() if isinstance(grid_thw, torch.Tensor) else list(grid_thw)+ if len(values) != 3:+ raise ValueError(f"grid_thw must contain exactly three values, got {values!r}")+ temporal, height, width = (int(value) for value in values)+ merge = int(spatial_merge_size)+ if temporal < 1 or height < 1 or width < 1 or merge < 1:+ raise ValueError(f"invalid visual grid={values!r}, spatial_merge_size={merge}")+ if height % merge or width % merge:+ raise ValueError(f"visual grid {values!r} is not divisible by spatial_merge_size={merge}")+ return temporal, height // merge, width // merge+++def native_visual_token_count(grid_thw, spatial_merge_size: int) -> int:+ temporal, height, width = merged_grid_shape(grid_thw, spatial_merge_size)+ return temporal * height * width+++def compact_visual_token_count(grid_thw, spatial_merge_size: int, token_budget: int) -> int:+ budget = int(token_budget)+ if budget < 1:+ raise ValueError(f"MGVB token budget must be positive, got {budget}")+ return min(native_visual_token_count(grid_thw, spatial_merge_size), budget)+++def native_visual_positions(grid_thw, spatial_merge_size: int, *, device=None) -> torch.Tensor:+ temporal, height, width = merged_grid_shape(grid_thw, spatial_merge_size)+ t = torch.arange(temporal, device=device, dtype=torch.long).view(-1, 1, 1)+ h = torch.arange(height, device=device, dtype=torch.long).view(1, -1, 1)+ w = torch.arange(width, device=device, dtype=torch.long).view(1, 1, -1)+ return torch.stack(+ [+ t.expand(temporal, height, width),+ h.expand(temporal, height, width),+ w.expand(temporal, height, width),+ ],+ dim=-1,+ ).reshape(-1, 3)+++def partition_spatial_grid(+ temporal: int,+ height: int,+ width: int,+ cell_count: int,+) -> list[SpatialCell]:+ """Split a THW grid into exactly ``cell_count`` deterministic non-empty rectangles."""++ temporal, height, width, cell_count = map(int, (temporal, height, width, cell_count))+ token_count = temporal * height * width+ if temporal < 1 or height < 1 or width < 1:+ raise ValueError(f"invalid merged grid {(temporal, height, width)!r}")+ if cell_count < 1 or cell_count > token_count:+ raise ValueError(f"cell_count={cell_count} must be in [1, {token_count}]")++ cells = [SpatialCell(t, 0, 0, height, width) for t in range(temporal)]+ if cell_count < len(cells):+ raise ValueError(+ f"cell_count={cell_count} cannot preserve temporal slices for temporal={temporal}"+ )++ while len(cells) < cell_count:+ candidates = [+ (cell.area, max(cell.height, cell.width), -index, index)+ for index, cell in enumerate(cells)+ if cell.area > 1+ ]+ if not candidates:+ raise RuntimeError(+ f"cannot split merged grid {(temporal, height, width)} into {cell_count} cells"+ )+ _, _, _, split_index = max(candidates)+ cell = cells.pop(split_index)+ if cell.width >= cell.height and cell.width > 1:+ middle = cell.left + cell.width // 2+ children = [+ SpatialCell(cell.temporal, cell.top, cell.left, cell.bottom, middle),+ SpatialCell(cell.temporal, cell.top, middle, cell.bottom, cell.right),+ ]+ else:+ middle = cell.top + cell.height // 2+ children = [+ SpatialCell(cell.temporal, cell.top, cell.left, middle, cell.right),+ SpatialCell(cell.temporal, middle, cell.left, cell.bottom, cell.right),+ ]+ cells.extend(children)++ return sorted(cells)+++def cell_center_positions(cells: list[SpatialCell], *, device=None) -> torch.Tensor:+ return torch.tensor(+ [+ [+ cell.temporal,+ (cell.top + cell.bottom - 1) // 2,+ (cell.left + cell.right - 1) // 2,+ ]+ for cell in cells+ ],+ dtype=torch.long,+ device=device,+ )+++def cell_edges(+ cells: list[SpatialCell],+ height: int,+ width: int,+ *,+ halo: int = 0,+ device=None,+) -> tuple[torch.Tensor, torch.Tensor]:+ """Return flattened token indices and their destination cell ids."""++ token_indices: list[int] = []+ cell_indices: list[int] = []+ halo = max(0, int(halo))+ for cell_id, cell in enumerate(cells):+ top = max(0, cell.top - halo)+ left = max(0, cell.left - halo)+ bottom = min(height, cell.bottom + halo)+ right = min(width, cell.right + halo)+ base = cell.temporal * height * width+ for row in range(top, bottom):+ start = base + row * width + left+ count = right - left+ token_indices.extend(range(start, start + count))+ cell_indices.extend([cell_id] * count)+ return (+ torch.tensor(token_indices, dtype=torch.long, device=device),+ torch.tensor(cell_indices, dtype=torch.long, device=device),+ )+++def cell_assignment(+ cells: list[SpatialCell],+ height: int,+ width: int,+ *,+ device=None,+) -> torch.Tensor:+ if not cells:+ raise ValueError("cannot build a cell assignment from an empty cell list")+ temporal = max(cell.temporal for cell in cells) + 1+ assignment = torch.full(+ (temporal, height, width), -1, dtype=torch.long, device=device+ )+ for cell_id, cell in enumerate(cells):+ assignment[cell.temporal, cell.top : cell.bottom, cell.left : cell.right] = cell_id+ if torch.any(assignment < 0):+ raise RuntimeError("spatial cells do not cover the complete visual grid")+ return assignment.reshape(-1)+++def build_mgvb_visual_positions(+ grid_thw,+ *,+ spatial_merge_size: int,+ token_budget: int,+ global_tokens: int,+ region_tokens: int,+ device=None,+) -> torch.Tensor:+ """Build positions in the exact order emitted by True MGVB."""++ temporal, height, width = merged_grid_shape(grid_thw, spatial_merge_size)+ native_count = temporal * height * width+ compact_count = min(native_count, int(token_budget))+ if compact_count == native_count:+ return native_visual_positions(grid_thw, spatial_merge_size, device=device)++ global_count = int(global_tokens)+ region_count = int(region_tokens)+ fine_count = compact_count - global_count - region_count+ if global_count < 1 or region_count < 1 or fine_count < 1:+ raise ValueError(+ "compressed MGVB budget must leave positive global, region, and fine counts; "+ f"got total={compact_count}, global={global_count}, region={region_count}, fine={fine_count}"+ )++ center = torch.tensor(+ [[(temporal - 1) // 2, (height - 1) // 2, (width - 1) // 2]],+ dtype=torch.long,+ device=device,+ ).expand(global_count, -1)+ region_cells = partition_spatial_grid(temporal, height, width, region_count)+ fine_cells = partition_spatial_grid(temporal, height, width, fine_count)+ return torch.cat(+ [+ center,+ cell_center_positions(region_cells, device=device),+ cell_center_positions(fine_cells, device=device),+ ],+ dim=0,+ )diff --git a/inference/runtime_sources/rope_utils.py b/inference/runtime_sources/rope_utils.pynew file mode 100644index 0000000..2626bba--- /dev/null+++ b/inference/runtime_sources/rope_utils.py@@ -0,0 +1,316 @@+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.+# Copyright (c) 2024 Alibaba PAI Team.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+++from __future__ import annotations++import logging+from typing import List, Optional++import torch+from megatron.core import parallel_state+from megatron.core.models.common.embeddings.rope_utils import (+ _apply_rotary_pos_emb_bshd,+ get_pos_emb_on_this_cp_rank,+)+from torch import Tensor, nn++from mbridge.models.qwen3_vl.transformer_config import Qwen3VLTransformerConfig++# Prefer fused RoPE from Apex as we need the `transpose_output_memory` argument for the bshd trick.+# See https://gitlab-master.nvidia.com/ADLR/megatron-lm/-/merge_requests/2469.+try:+ # pylint: disable=unused-import+ from megatron.core.extensions.transformer_engine import fused_apply_rotary_pos_emb+except ImportError:+ fused_apply_rotary_pos_emb = None+from mbridge.models.qwen3_vl.rope_utils import Qwen3VLMultimodalRotaryEmbedding++logger = logging.getLogger(__name__)+++# Slightly modified from Qwen3_5VLModel.get_rope_index+def get_rope_index(+ spatial_merge_size: int,+ image_token_id: int,+ video_token_id: int,+ vision_start_token_id: int,+ input_ids: Optional[torch.LongTensor] = None,+ image_grid_thw: Optional[torch.LongTensor] = None,+ video_grid_thw: Optional[torch.LongTensor] = None,+ image_position_ids: Optional[List[torch.Tensor]] = None,+ attention_mask: Optional[torch.Tensor] = None,+) -> tuple[torch.Tensor, torch.Tensor]:+ """Different from the original implementation, Qwen3VL use timestamps rather than absolute time position ids."""++ # Since we use timestamps to seperate videos, like <t1> <vision_start> <frame1> <vision_end> <t2> <vision_start> <frame2> <vision_end>, the video_grid_thw should also be split+ if video_grid_thw is not None:+ video_grid_thw = torch.repeat_interleave(+ video_grid_thw, video_grid_thw[:, 0], dim=0+ )+ video_grid_thw[:, 0] = 1++ image_grid_thw_list = (+ image_grid_thw.tolist() if image_grid_thw is not None else None+ )+ video_grid_thw_list = (+ video_grid_thw.tolist() if video_grid_thw is not None else None+ )++ mrope_position_deltas = []+ if input_ids is not None and (+ image_grid_thw is not None or video_grid_thw is not None+ ):+ total_input_ids = input_ids+ if attention_mask is None:+ attention_mask = torch.ones_like(total_input_ids)+ position_ids = torch.ones(+ 3,+ input_ids.shape[0],+ input_ids.shape[1],+ dtype=input_ids.dtype,+ device=input_ids.device,+ )+ image_index, video_index = 0, 0+ attention_mask = attention_mask.to(total_input_ids.device)+ for i, input_ids in enumerate(total_input_ids):+ input_ids = input_ids[attention_mask[i] == 1]+ image_nums, video_nums = 0, 0+ vision_start_indices = torch.argwhere(+ input_ids == vision_start_token_id+ ).squeeze(1)+ vision_tokens = input_ids[vision_start_indices + 1]+ image_nums = (vision_tokens == image_token_id).sum()+ video_nums = (vision_tokens == video_token_id).sum()+ input_tokens = input_ids.tolist()+ llm_pos_ids_list: list = []+ st = 0+ remain_images, remain_videos = image_nums, video_nums+ for _ in range(image_nums + video_nums):+ explicit_image_positions = None+ if image_token_id in input_tokens and remain_images > 0:+ ed_image = input_tokens.index(image_token_id, st)+ else:+ ed_image = len(input_tokens) + 1+ if video_token_id in input_tokens and remain_videos > 0:+ ed_video = input_tokens.index(video_token_id, st)+ else:+ ed_video = len(input_tokens) + 1+ if ed_image < ed_video:+ t, h, w = image_grid_thw_list[image_index]+ explicit_image_positions = (+ image_position_ids[image_index]+ if image_position_ids is not None+ else None+ )+ image_index += 1+ remain_images -= 1+ ed = ed_image+ else:+ t, h, w = video_grid_thw_list[video_index]+ video_index += 1+ remain_videos -= 1+ ed = ed_video+ llm_grid_t, llm_grid_h, llm_grid_w = (+ t,+ h // spatial_merge_size,+ w // spatial_merge_size,+ )+ text_len = ed - st++ st_idx = (+ llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0+ )+ llm_pos_ids_list.append(+ torch.arange(text_len, device=input_ids.device).view(1, -1).expand(3, -1) + st_idx+ )++ if ed_image < ed_video and explicit_image_positions is not None:+ visual_positions = explicit_image_positions.to(+ device=input_ids.device, dtype=input_ids.dtype+ )+ if visual_positions.ndim != 2 or visual_positions.shape[-1] != 3:+ raise ValueError(+ "image_position_ids entries must have shape [visual_tokens, 3], "+ f"got {tuple(visual_positions.shape)}"+ )+ visual_positions = visual_positions.transpose(0, 1).contiguous()+ else:+ # Video timestamp spans and native image spans retain the+ # regular Qwen merged-grid positions.+ t_index = (+ torch.arange(llm_grid_t, device=input_ids.device)+ .view(-1, 1)+ .expand(-1, llm_grid_h * llm_grid_w)+ .flatten()+ )+ h_index = (+ torch.arange(llm_grid_h, device=input_ids.device)+ .view(1, -1, 1)+ .expand(llm_grid_t, -1, llm_grid_w)+ .flatten()+ )+ w_index = (+ torch.arange(llm_grid_w, device=input_ids.device)+ .view(1, 1, -1)+ .expand(llm_grid_t, llm_grid_h, -1)+ .flatten()+ )+ visual_positions = torch.stack([t_index, h_index, w_index])+ visual_length = visual_positions.shape[1]+ expected_token = image_token_id if ed_image < ed_video else video_token_id+ actual_visual_length = 0+ while (+ ed + actual_visual_length < len(input_tokens)+ and input_tokens[ed + actual_visual_length] == expected_token+ ):+ actual_visual_length += 1+ if actual_visual_length != visual_length:+ raise ValueError(+ f"visual placeholder length={actual_visual_length} does not match "+ f"position length={visual_length} for token_id={expected_token}"+ )+ llm_pos_ids_list.append(+ visual_positions + text_len + st_idx+ )+ st = ed + visual_length++ if st < len(input_tokens):+ st_idx = (+ llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0+ )+ text_len = len(input_tokens) - st+ llm_pos_ids_list.append(+ torch.arange(text_len, device=input_ids.device).view(1, -1).expand(3, -1) + st_idx+ )++ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)+ if llm_positions.shape[1] != input_ids.shape[0]:+ raise ValueError(+ f"M-RoPE produced {llm_positions.shape[1]} positions for "+ f"{input_ids.shape[0]} valid input tokens"+ )+ position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(+ device=position_ids.device, dtype=position_ids.dtype+ )+ mrope_position_deltas.append(+ llm_positions.max() + 1 - len(total_input_ids[i])+ )+ if image_position_ids is not None and image_index != len(image_position_ids):+ raise ValueError(+ f"consumed {image_index} explicit image position tensors, "+ f"but received {len(image_position_ids)}"+ )+ mrope_position_deltas = torch.tensor(+ mrope_position_deltas, device=input_ids.device+ ).unsqueeze(1)+ return position_ids, mrope_position_deltas+ else:+ if attention_mask is not None:+ position_ids = attention_mask.long().cumsum(-1) - 1+ position_ids.masked_fill_(attention_mask == 0, 1)+ position_ids = (+ position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device)+ )+ max_position_ids = position_ids.max(0, keepdim=False)[0].max(+ -1, keepdim=True+ )[0]+ mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]+ else:+ position_ids = (+ torch.arange(input_ids.shape[1], device=input_ids.device)+ .view(1, 1, -1)+ .expand(3, input_ids.shape[0], -1)+ )+ mrope_position_deltas = torch.zeros(+ [input_ids.shape[0], 1],+ device=input_ids.device,+ dtype=input_ids.dtype,+ )++ return position_ids, mrope_position_deltas+++def apply_rotary_pos_emb_thd_absolute(+ t: Tensor,+ cu_seqlens: Tensor,+ freqs: Tensor,+ rotary_interleaved: bool = False,+ multi_latent_attention: bool = False,+ mscale: float = 1.0,+ cp_group: torch.distributed.ProcessGroup = None,+) -> Tensor:+ """A baseline implementation of applying RoPE for `thd` format.++ Args:+ t (Tensor): Input tensor T is of shape [t, h, d]+ cu_seqlens(Tensor): Cumulative sum of sequence lengths in a batch for `t`,+ with shape [b + 1] and dtype torch.int32.+ freqs (Tensor): Rotary Positional embedding tensor freq is of shape [max_s, 1, 1, d]++ Returns:+ Tensor: Shape [t, h, d]. The input tensor after applying RoPE.+ """+ return _apply_rotary_pos_emb_bshd(+ t[:, None],+ freqs,+ rotary_interleaved=rotary_interleaved,+ multi_latent_attention=multi_latent_attention,+ mscale=mscale,+ ).squeeze(1)+++def apply_rotary_pos_emb_absolute(+ t: Tensor,+ freqs: Tensor,+ config: Qwen3VLTransformerConfig,+ cu_seqlens: Optional[Tensor] = None,+ mscale: float = 1.0,+ cp_group: torch.distributed.ProcessGroup = None,+):+ """+ Reroute to the appropriate apply_rotary_pos_emb function depending on+ bshd (conventional) / thd (packed seq) format++ In Qwen3-VL, the shape of freqs is (seq_length, bs, 1, 2 * dim) instead of [max_seqlen, 1, 1, 2 * dim]+ """+ assert not config.apply_rope_fusion+ orig_t_dtype = t.dtype+ if config.apply_rotary_pos_emb_in_fp32:+ t = t.float()++ if cu_seqlens is None:+ result = _apply_rotary_pos_emb_bshd(+ t,+ freqs,+ rotary_interleaved=config.rotary_interleaved,+ multi_latent_attention=config.multi_latent_attention,+ mscale=mscale,+ )+ else:+ result = apply_rotary_pos_emb_thd_absolute(+ t,+ cu_seqlens,+ freqs,+ rotary_interleaved=config.rotary_interleaved,+ multi_latent_attention=config.multi_latent_attention,+ mscale=mscale,+ cp_group=cp_group,+ )++ if config.apply_rotary_pos_emb_in_fp32:+ result = result.to(orig_t_dtype)++ return resultdiff --git a/inference/test_runtime_contracts.py b/inference/test_runtime_contracts.pynew file mode 100644index 0000000..03ba477--- /dev/null+++ b/inference/test_runtime_contracts.py@@ -0,0 +1,99 @@+"""Regression tests for the inference entry points and shared runtime."""++import json+import unittest+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from tempfile import TemporaryDirectory+from threading import Barrier+from types import SimpleNamespace+from unittest.mock import Mock++import torch+from checkpoint import BUNDLED_RUNTIME, RUNTIME_FILES, select_runtime_sources+from common import write_json+from runtime import UniModelTransformers+++class OutputTests(unittest.TestCase):+ def test_concurrent_writers_publish_one_complete_result(self):+ with TemporaryDirectory() as directory:+ output = Path(directory) / "result.json"+ start = Barrier(4)++ def write(index):+ start.wait()+ try:+ write_json(output, {"writer": index})+ except FileExistsError:+ return None+ return index++ with ThreadPoolExecutor(max_workers=4) as pool:+ winners = [i for i in pool.map(write, range(4)) if i is not None]+ self.assertEqual(winners, [json.loads(output.read_text())["writer"]])+ self.assertEqual(list(output.parent.iterdir()), [output])++ def test_serialization_failure_leaves_destination_available(self):+ with TemporaryDirectory() as directory:+ output = Path(directory) / "result.json"+ with self.assertRaises(TypeError):+ write_json(output, {"invalid": object()})+ self.assertEqual(list(output.parent.iterdir()), [])+ write_json(output, {"retry": True})+ self.assertTrue(json.loads(output.read_text())["retry"])+++class RuntimeSourceTests(unittest.TestCase):+ def test_external_sources_require_opt_in_and_a_complete_directory(self):+ with TemporaryDirectory() as directory:+ model = Path(directory)+ external = model / "runtime_sources"+ external.mkdir()+ with self.assertRaisesRegex(ValueError, "incomplete WePM runtime"):+ select_runtime_sources(model, trust_model_code=True)+ for name in RUNTIME_FILES:+ (external / name).touch()+ self.assertEqual(+ select_runtime_sources(model, trust_model_code=False), BUNDLED_RUNTIME+ )+ self.assertEqual(+ select_runtime_sources(model, trust_model_code=True), external+ )+++class GenerationTests(unittest.TestCase):+ def test_generation_stops_on_config_or_tokenizer_eos(self):+ for eos, tokenizer_eos, finish in (+ (2, None, "eos"),+ ([1, 2], 3, "eos"),+ ([1, 3], 2, "eos"),+ (None, 2, "eos"),+ ([1, 3], None, "length"),+ ):+ with self.subTest(eos=eos, tokenizer_eos=tokenizer_eos):+ runtime = object.__new__(UniModelTransformers)+ runtime.config = {"eos_token_id": eos}+ runtime.processor = Mock()+ runtime.processor.tokenizer.eos_token_id = tokenizer_eos+ runtime._prepare_inputs = Mock(+ return_value=(+ torch.zeros(1, 1),+ torch.zeros(1, 1, 3),+ torch.zeros(4, 1, 1),+ {},+ )+ )+ runtime.model = Mock()+ runtime.model.model.language_model.return_value = SimpleNamespace(+ past_key_values=None,+ last_hidden_state=torch.tensor([[[0.0, 0.0, 1.0]]]),+ )+ runtime.model.lm_head = torch.nn.Identity()+ result = runtime.generate([], max_new_tokens=1)+ self.assertEqual(result["token_ids"], [2])+ self.assertEqual(result["finish_reason"], finish)+++if __name__ == "__main__":+ unittest.main()