跳到正文

个人记录

Youtu-VL ncnn Porting Technical Report

AtomAlpaca约 67 分钟
原文
文章信息与版本

文章信息

发布
2026年7月10日
收录
2026年7月19日
更新
2026年11月15日
篇幅
约 67 分钟

版本

  1. v1当前

Youtu-VL ncnn Porting Technical Report

Written for readers who are new to large language models, vision-language models, pnnx, and ncnn.

Repository: Youtu-VL-ncnn

TL;DR: shortest path from clone to inference

The shortest path assumes that you already have the FP32 runtime assets. It builds the C++ runner from source and performs end-to-end image inference without Python, PyTorch, or Transformers.

Prerequisites: CMake, a C++17 compiler, zlib, and approximately 20 GB of space for the runtime assets.

Bash
git clone --recurse-submodules https://github.com/AtomAlpaca/Youtu-VL-ncnn.git
cd Youtu-VL-ncnn

cmake --preset ncnn-source
cmake --build --preset ncnn-source --parallel 4

cpp/build-release/cpp/youtu_ncnn_decode_runner \
  --image assets/youtu_vl_test/images/coco_cats.jpg \
  --prompt "Describe this image in one sentence." \
  --full-decoder-ncnn \
  --max-new-tokens 8

Before running, these paths must exist. The large model .bin files and tokenizer are not committed to Git:

代码
release/youtu-vl-ncnn-fp32/models/text/
release/youtu-vl-ncnn-fp32/models/vision/
release/youtu-vl-ncnn-fp32/tokenizer/tokenizer.json

When the runner and asset package are not in the same repository tree, pass --root /path/to/youtu-vl-ncnn-fp32 or set YOUTU_VL_ROOT=/path/to/youtu-vl-ncnn-fp32.

Also convert the model from official weights

When runtime assets are unavailable, this is the shortest conversion outline. It produces text references, vision references, and the production ncnn subnetworks. Section 11 explains every output mapping, parity check, and failure mode.

Bash
python3 -m venv venv
source venv/bin/activate
python -m pip install -r requirements.txt

huggingface-cli download tencent/Youtu-VL-4B-Instruct \
  --local-dir assets/hf/Youtu-VL-4B-Instruct

venv/bin/python export/youtu_text_reference.py \
  --only en_short --dtype fp32 --capture-decoder-io \
  --capture-decode-hidden-states --no-compress

venv/bin/python export/youtu_vl_vision_embed_probe.py \
  --only coco_cats:describe --max-image-patches 512 --dtype fp32 \
  --output-dir assets/youtu_vl_test/vision_embeds_smoke --no-compress
Bash
# Text boundary graphs
venv/bin/python export/youtu_vl_export.py \
  --model assets/hf/Youtu-VL-4B-Instruct --dtype fp32 \
  --target embed_tokens --trace --run-pnnx --pnnx venv/bin/pnnx

venv/bin/python export/youtu_vl_export.py \
  --model assets/hf/Youtu-VL-4B-Instruct --dtype fp32 \
  --target lm_head --trace --run-pnnx \
  --allow-large-lm-head-pnnx --pnnx venv/bin/pnnx

venv/bin/python export/youtu_final_norm_probe.py \
  --model assets/hf/Youtu-VL-4B-Instruct --dtype fp32 \
  --trace --run-pnnx --pnnx venv/bin/pnnx

# 40-layer decoder: decode and dynamic prefill
venv/bin/python export/youtu_full_decoder_probe.py \
  --model assets/hf/Youtu-VL-4B-Instruct --mode decode --dtype fp32 \
  --trace --run-pnnx --patch-param --pnnx venv/bin/pnnx
venv/bin/python export/youtu_full_decoder_probe.py \
  --model assets/hf/Youtu-VL-4B-Instruct --mode prefill --dtype fp32 \
  --trace --run-pnnx --patch-param --pnnx venv/bin/pnnx

# Dynamic SigLIP2 encoder and merger
venv/bin/python export/youtu_vl_vision_dynamic_export.py \
  --model assets/hf/Youtu-VL-4B-Instruct \
  --input-npz assets/youtu_vl_test/vision_embeds_smoke/coco_cats_describe.npz \
  --dtype fp32 --trace --trace-post-merger \
  --run-pnnx --run-post-merger-pnnx \
  --patch-param --patch-post-merger-param --pnnx venv/bin/pnnx

Finally, assemble outputs according to release/youtu-vl-ncnn-fp32/ASSET_MANIFEST.json, preserve both hard-link pairs, then run the dynamic-prefill and multimodal token parity checks from Section 11. Full FP32 conversion normally needs at least 200 GB of temporary disk and about 64 GB RAM. Do not convert lm_head and the 40-layer decoder in parallel, as that risks OOM.

1. What problem does this project solve?

Youtu-VL-4B-Instruct is a vision-language model (VLM). It can read text, inspect an image, and generate an answer one token at a time like a conventional chat model.

The official model primarily runs through PyTorch and Hugging Face. That environment is excellent for research, but deployment usually brings Python, PyTorch, Transformers, and other large dependencies. ncnn is Tencent’s lightweight, open-source neural-network inference framework for C++ and on-device deployment.

This project aims to:

  1. Convert the core computation of tencent/Youtu-VL-4B-Instruct to ncnn with pnnx.
  2. Implement image loading, preprocessing, tokenization, inference, and generation in C++ with as few dependencies as practical.
  3. Produce the same generated token sequence as the original PyTorch model for identical inputs.
  4. Build with CMake and support at least Linux and Windows compilation and basic execution tests.
  5. Package the work as a maintainable public GitHub repository.

The production path currently implemented is:

代码
source image + user question
        |
        v
C++ image decoding and SigLIP2 preprocessing
        |
        v
dynamic-length SigLIP2 ncnn encoder
        |
        v
post-layernorm + merger ncnn
        |
        v
inject image embeddings into text token embeddings
        |
        v
dynamic-length 40-layer ncnn decoder prefill
        |
        v
token-by-token decode with KV cache
        |
        v
final RMSNorm + lm_head + argmax
        |
        v
C++ tokenizer decodes tokens into text

2. Essential concepts

2.1 Token

Models do not consume text directly. A tokenizer splits text into tokens and maps each token to an integer ID:

代码
"Describe this image."
    -> tokenizer
[42546, 469, 2870, 13]

The IDs are vocabulary indices. Generation produces IDs first; the tokenizer converts them back into text afterward.

2.2 Tensor

A tensor is a multidimensional array. Images, token IDs, weights, and intermediate features are all tensors.

代码
token IDs:       [batch, sequence]
text embedding:  [batch, sequence, hidden_size]
image patches:   [batch, patch_count, patch_features]
logits:          [batch, sequence, vocabulary_size]

Youtu-VL-4B uses a text hidden size of 2560, a vocabulary of 283386 entries, and 40 decoder layers.

2.3 Embedding

A token ID cannot directly participate in neural-network arithmetic. embed_tokens maps each ID to a 2560-element floating-point vector. The vision network also emits vectors with a compatible width, allowing image and text information to enter the language model together.

2.4 Transformer decoder

The decoder is the main language model. Each of its 40 layers roughly performs:

代码
RMSNorm
  -> Self Attention
  -> Residual Add
  -> RMSNorm
  -> MLP
  -> Residual Add

Self-attention determines which earlier positions matter to the current token. The MLP further transforms each position’s features.

2.5 RoPE

Attention alone does not know token order. Rotary Position Embedding (RoPE) rotates Query and Key features according to position. Youtu-VL uses positional information in both its text and vision networks. Vision RoPE is more involved because patches form a two-dimensional grid and are reordered into windows.

2.6 KV cache

During generation, one token is appended at each step. Recomputing every earlier token would be wasteful. Attention Keys and Values from previous tokens are retained:

代码
step 1: compute token 1, save K1/V1
step 2: compute token 2, reuse K1/V1
step 3: compute token 3, reuse K1/V1 and K2/V2

This retained state is the KV cache.

2.7 Prefill and decode

  • prefill processes the complete prompt in one pass and creates the initial KV cache.
  • decode processes one newly generated token and reuses the cache.

Prefill needs a dynamic sequence length. Decode normally has input length 1 while its cache length grows at every step.

2.8 Logits and greedy decoding

lm_head maps a 2560-element hidden vector to 283386 vocabulary scores called logits. The runner currently uses deterministic greedy decoding:

代码
next_token = argmax(logits)

Determinism makes greedy decoding particularly useful for PyTorch/ncnn parity testing.

2.9 PyTorch, TorchScript, pnnx, and ncnn

ToolRole
PyTorch/Hugging FaceRuns the official model and supplies reference values and weights
TorchScriptWraps Python modules in a more stable computation graph
pnnxConverts TorchScript graphs to pnnx/ncnn graphs
ncnnLoads .param and .bin files and executes inference in C++

An ncnn model normally consists of a .param graph description and a .bin weight file.

3. How Youtu-VL passes an image to the language model

3.1 Patch extraction

SigLIP2 does not process an arbitrary image as one object. The image is resized to dimensions divisible by the patch size and split into 16 x 16 RGB patches. Each flattened patch has:

代码
16 x 16 x 3 = 768 values

3.2 Merging 2x2 patches

Youtu-VL’s merger combines neighboring 2 x 2 patches into one image token:

代码
image_token_count = patch_count / 4
ImageResized patch gridPatchesImage tokens
coco_cats.jpg18 x 24432108
synthetic_receipt.png24 x 20480120

3.3 Image placeholders in the prompt

The processor inserts special tokens before the user’s question:

代码
<|vision_start|>
<|image_pad|> repeated image_token_count times
<|vision_end|>

The language model first obtains normal token embeddings. Embeddings at <|image_pad|> positions are then replaced by vision output. Multimodal fusion therefore happens through exact embedding replacement, not by placing image bytes in a prompt string.

4. Final runtime architecture

mermaid
flowchart TD
    A["Source image"] --> B["stb_image decode"]
    B --> C["resize / normalize / patch flatten"]
    C --> D["C++ window index, RoPE, and attention mask"]
    D --> E["Dynamic SigLIP2 encoder ncnn"]
    E --> F["Restore original window order"]
    F --> G["post-layernorm + merger ncnn"]
    G --> H["Image embeddings"]
    I["User prompt"] --> J["C++ byte-level BPE tokenizer"]
    J --> K["embed_tokens ncnn"]
    H --> L["Replace image_pad embeddings"]
    K --> L
    L --> M["Dynamic 40-layer decoder prefill ncnn"]
    M --> N["KV cache"]
    M --> O["final norm + lm_head"]
    O --> P["Argmax token"]
    P --> Q["Single-token decoder with KV cache"]
    N --> Q
    Q --> O
    P --> R["Tokenizer decode"]

Runtime assets live under release/youtu-vl-ncnn-fp32/ with text models, vision models, tokenizer.json, licenses, and ASSET_MANIFEST.json.

5. Implementation process

Stage 1: Establish a PyTorch ruler

Converting the whole model and only checking whether the final prose looks plausible makes failures almost impossible to locate. youtu_text_reference.py and youtu_vl_reference.py therefore record tokenizer output, embeddings, masks, positions, KV tensors, layer boundaries, normalized hidden states, logits, processor output, vision features, and generated tokens. These NPZ dumps serve as test fixtures and can be regenerated even though large dumps are excluded from the release repository.

Stage 2: Convert simple text boundaries first

The first graphs were input_ids -> embed_tokens -> inputs_embeds and hidden_states -> lm_head -> logits. They verified the pnnx toolchain, weight layout, ncnn/PyTorch numerical agreement, and tied embedding/lm_head weights. Their identical .bin payloads are hard-linked in the release package.

Stage 3: Start with decoder layer 0

A 40-layer graph is too large for useful first-failure diagnosis. Layer 0 established wrapper boundaries, RoPE inputs, mask dimensions, the ncnn cache sequence axis, tensor layout conversion, and required .param fixes. The same pipeline then covered layers 0-39. Later layers naturally accumulate floating-point error, so tests inspect maximum, mean, and RMS error, top logits, and the final argmax instead of relying on one absolute-error number.

Stage 4: Build a layer-by-layer C++ runner

The first C++ runtime loaded 40 independent layer graphs. This proved the complete text path, but repeated network loading, extractor creation, and blob copying made it a debugging architecture rather than a production design.

Stage 5: Export one 40-layer decoder graph

The layers were combined into one ncnn_llm-style graph:

代码
hidden states + mask + RoPE + KV cache
    -> all 40 decoder layers
    -> hidden states + updated KV cache

The decode graph consumes one token at a time. Because zero-length cache tensors are unreliable in pnnx/ncnn, the first step uses a masked dummy cache slot and removes it afterward.

Stage 6: Dynamic-sequence prefill

Early experiments used fixed s33, s64, and s128 buckets. The final solution uses the real prompt length, a dynamic causal mask, dynamic RoPE, and one 40-layer pass. Prefill and decode weights are byte-identical and share one physical 16 GB payload through hard links.

Stage 7: End-to-end text token parity

youtu_e2e_token_parity.py creates prompt IDs, generates greedy PyTorch tokens, invokes the C++ runner, parses generated IDs, and compares the complete sequences. This upgrades validation from similar intermediate floats to identical discrete output.

Stage 8: Bridge vision through NPZ

Before the vision graph was available, PyTorch exported merged image embeddings. C++ injected them into text embeddings and ran ncnn prefill/decode. This isolated image-token integration from vision conversion.

Stage 9: Export a fixed-length vision graph

A fixed patch count first proved that SigLIP2 and the merger could be converted. It was useful for parity, but could only accept the traced image shape.

Stage 10: Make patch length dynamic

Runtime-dependent window indices, masks, and vision RoPE were moved to C++. The ncnn graph retained the expensive neural-network layers. One encoder graph can now process different patch grids.

Stage 11: Reimplement preprocessing in C++

The runner gained image decoding, aspect-ratio-preserving resize under a patch budget, antialiased bilinear sampling, normalization, patch flattening in 2x2 merge order, pixel masks, spatial shapes, and image-token count calculation. The normal path no longer needs vision NPZ input.

Stage 12: Multi-sample multimodal parity

youtu_vl_e2e_token_parity.py compares processor/C++ prompt IDs and complete greedy generated sequences across a manifest. Representative three-token results are:

SampleMatching token IDs
Cat description[10392, 5240, 1896]
Cat counting[4356, 516, 4806]
Receipt OCR[9212, 371, 290]

6. Inside the C++ runner

cpp/youtu_ncnn_decode_runner.cpp is currently a monolithic but complete reference runtime.

6.1 Path discovery

std::filesystem locates the repository and release root. --root and YOUTU_VL_ROOT support installed or relocated packages.

6.2 NPY/NPZ reader

A small internal reader plus zlib supports historical parity fixtures. The production image-to-text path does not require NPZ.

6.3 Tokenizer

The tokenizer loads Hugging Face tokenizer.json, performs byte-level BPE, handles special tokens and the image chat template, and decodes generated IDs. --tokenize-only checks it independently.

6.4 Tensor adaptation

PyTorch and ncnn describe dimensions differently. Explicit conversion helpers keep sequence, channel, head, and cache axes consistent and are especially important for KV cache inputs and outputs.

6.5 Vision runtime input

C++ computes resized pixels, flattened patches, spatial shapes, window order, reverse order, RoPE, attention masks, and placeholder positions from the actual image dimensions.

6.6 Runner context

Loaded ncnn networks and options are retained in a context instead of being reloaded for every token. The context owns embedding, vision, prefill, decode, norm, and lm_head networks.

6.7 Generation loop

The runtime tokenizes the prompt, computes text and image embeddings, performs one prefill, selects the first token, then repeatedly embeds one token, runs cache decode, applies norm/head, chooses argmax, updates caches, and stops at EOS or the token limit.

7. How numerical agreement is verified

Four levels are used:

  1. Input parity: token IDs, resized image shape, patches, masks, spatial shapes, RoPE, and special-token positions.
  2. Module parity: embedding, one layer, full decoder, final norm, lm_head, vision encoder, and merger.
  3. Path parity: dynamic prefill versus token-by-token decode and injected PyTorch vision embeddings versus the C++ text path.
  4. Final token parity: complete prompt IDs and generated IDs for text and multimodal samples.

Floating-point outputs need not be bit-identical across frameworks and SIMD implementations. The decisive acceptance criterion for greedy decoding is the same argmax token at every step, supported by intermediate error measurements so that equality is not accidental.

8. Repository files and directories

8.1 Root

PathPurpose
README.md / README.zh-CN.mdEnglish and Chinese project entry points
ROADMAP.md / ROADMAP.zh-CN.mdCurrent status and remaining milestones
CMakeLists.txtTop-level CMake entry
CMakePresets.jsonSource-ncnn and system-ncnn presets
.gitmodulesPinned ncnn dependency
requirements.txtPython export/reference dependencies
THIRD_PARTY_NOTICES.mdThird-party notices; not a project-level license

8.2 cpp/

youtu_ncnn_decode_runner.cpp contains the runtime. CMakeLists.txt builds and installs it. The bilingual READMEs document all execution and debug modes. Build directories are generated and should not be committed.

8.3 docs/

This report is the main implementation narrative. PROJECT_TASK_DESCRIPTION, COMPLETED_TASKS, and NCNN_LLM_CODEBASE_REPORT record scope, status, and reference architecture.

8.4 assets/

Contains small manifests, test images, tokenizer probes, checksums, and regenerable reference outputs. Original Hugging Face weights and large intermediates are ignored.

8.5 release/

release/youtu-vl-ncnn-fp32/ defines the distributable directory layout. Large binaries are local/release assets rather than Git objects.

8.6 third_party/

third_party/ncnn/ is the only required source submodule. ncnn_llm remains a reference and is intentionally not a build dependency.

9. Export script index

9.1 References and tokenizer

ScriptPurpose
youtu_text_reference.pyText-only PyTorch reference dumps
youtu_vl_reference.pyMultimodal PyTorch reference dumps
youtu_vl_tokenizer_probe.pyProcessor/tokenizer JSON probes
extract_youtu_tokenizer_assets.pyExtract legacy tokenizer assets
youtu_vl_vision_embed_probe.pyExport merged/injected vision embeddings

9.2 Text graph export

ScriptPurpose
youtu_vl_export.pyEmbedding and lm_head export
youtu_decoder_layer_probe.pySingle decoder-layer wrapper/export
youtu_decoder_wrapper_probe.pyDecoder boundary experiments
youtu_decoder_layers_pipeline.pyBatch layer export and parity orchestration
youtu_full_decoder_probe.pySingle 40-layer decode graph
youtu_manual_prefill_probe.pyDynamic full-prefill graph
youtu_final_norm_probe.pyFinal RMSNorm export
patch_ncnn_param.pyTargeted generated-param fixes

9.3 Text parity and diagnostics

youtu_ncnn_embed_parity.py, youtu_ncnn_decoder_layer_parity.py, youtu_ncnn_decoder_stack_parity.py, youtu_ncnn_full_decoder_parity.py, youtu_ncnn_prefill_parity.py, youtu_ncnn_lm_head_parity.py, and related blob/runner probes isolate numerical boundaries. youtu_dynamic_prefill_smoke.py tests multiple sequence lengths. youtu_e2e_token_parity.py checks final text tokens.

9.4 Vision export and parity

youtu_vl_vision_export.py and youtu_vl_vision_fixed_export.py preserve earlier fixed-shape work. youtu_vl_vision_dynamic_export.py is the production dynamic exporter. youtu_vl_prefill_embeds_parity.py checks injected embeddings, and youtu_vl_e2e_token_parity.py checks complete multimodal prompt and generated sequences.

10. Build and run for users

Clone with the submodule:

Bash
git clone --recurse-submodules https://github.com/AtomAlpaca/Youtu-VL-ncnn.git
cd Youtu-VL-ncnn

The approximately 20 GB runtime assets are not in Git. Place them under release/youtu-vl-ncnn-fp32/ according to ASSET_MANIFEST.json.

Linux/macOS:

Bash
cmake --preset ncnn-source
cmake --build --preset ncnn-source --parallel 4
ctest --preset ncnn-source

Windows with MSVC and vcpkg:

powershell
vcpkg install zlib:x64-windows-static
cmake --preset ncnn-source `
  -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_INSTALLATION_ROOT/scripts/buildsystems/vcpkg.cmake" `
  -DVCPKG_TARGET_TRIPLET=x64-windows-static
cmake --build --preset ncnn-source --config Release --parallel 4
ctest --preset ncnn-source -C Release

Image description:

Bash
cpp/build-release/cpp/youtu_ncnn_decode_runner \
  --image assets/youtu_vl_test/images/coco_cats.jpg \
  --prompt "Describe this image in one sentence." \
  --full-decoder-ncnn --max-new-tokens 8

OCR uses the same command with synthetic_receipt.png and an OCR prompt. Text-only mode omits --image and adds --full-prefill-ncnn. --tokenize-only tests tokenization. A relocated package can be selected with --root or YOUTU_VL_ROOT.

11. Building the ncnn models from scratch

This section starts with the official Hugging Face checkpoint rather than preconverted .param/.bin files:

代码
HF safetensors + tokenizer + test images
    -> PyTorch reference NPZ
    -> TorchScript subnetworks
    -> pnnx/ncnn param + bin
    -> dynamic-shape param patching
    -> subnetwork parity
    -> C++ end-to-end token parity
    -> release/youtu-vl-ncnn-fp32/

Do not skip references or parity. A successful pnnx exit only proves that files were emitted, not that tensor layouts, dynamic axes, caches, or generated tokens are correct.

11.1 Capacity and prerequisites

The FP32 workflow temporarily stores the HF checkpoint, NPZ dumps, TorchScript, pnnx intermediates, and ncnn weights. Intermediate files reached about 173 GB during development. Plan for at least 200 GB free disk and preferably 64 GB RAM. A CUDA GPU accelerates PyTorch references but is not mandatory for pnnx. Avoid running multiple large conversions concurrently.

When resources are limited, export one boundary at a time in this order: embedding, final norm, vision, decoder, then lm_head. After parity passes, .pt, .pnnx.onnx, and .pnnx.bin intermediates may be removed; retain final .ncnn.param/.ncnn.bin files.

11.2 Clone and pin the toolchain

Bash
git clone --recurse-submodules https://github.com/AtomAlpaca/Youtu-VL-ncnn.git
cd Youtu-VL-ncnn
git submodule update --init --recursive
python3 -m venv venv
source venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -r requirements.txt

The validated toolchain uses Transformers 4.57.1, pnnx 20260526, Python ncnn 1.0.20260526, and C++ ncnn commit 13b6d5318c73be53bb386fa51e8067615d0eb7c1. requirements.txt constrains Transformers to the model-card-supported range. Generated graph structure may change with another pnnx version, so existing param patches must then be reviewed.

11.3 Download the checkpoint

Bash
HF_HUB_ENABLE_HF_TRANSFER=1 huggingface-cli download \
  tencent/Youtu-VL-4B-Instruct \
  --local-dir assets/hf/Youtu-VL-4B-Instruct

Verify config.json, all model-*.safetensors, tokenizer.json, and the manifest test images. The manifests point to this directory by default; alternatively pass --model /path/to/model.

11.4 Generate text and vision references

Bash
venv/bin/python export/youtu_text_reference.py \
  --only en_short --dtype fp32 --max-new-tokens 3 \
  --capture-decoder-io --capture-decode-hidden-states --no-compress

venv/bin/python export/youtu_vl_reference.py \
  --only coco_cats:describe --max-image-patches 512 \
  --max-new-tokens 3 --dtype fp32 \
  --capture-vision-last-hidden --no-compress

venv/bin/python export/youtu_vl_vision_embed_probe.py \
  --only coco_cats:describe --max-image-patches 512 --dtype fp32 \
  --output-dir assets/youtu_vl_test/vision_embeds_smoke --no-compress

The text metadata and NPZ are written under assets/youtu_text_test/dumps/. The dynamic vision exporter consumes assets/youtu_vl_test/vision_embeds_smoke/coco_cats_describe.npz.

11.5 Export embedding, lm_head, and final norm

Bash
venv/bin/python export/youtu_vl_export.py \
  --model assets/hf/Youtu-VL-4B-Instruct --dtype fp32 \
  --target embed_tokens --trace --run-pnnx --pnnx venv/bin/pnnx

venv/bin/python export/youtu_vl_export.py \
  --model assets/hf/Youtu-VL-4B-Instruct --dtype fp32 \
  --target lm_head --trace --run-pnnx \
  --allow-large-lm-head-pnnx --pnnx venv/bin/pnnx

venv/bin/python export/youtu_final_norm_probe.py \
  --model assets/hf/Youtu-VL-4B-Instruct --dtype fp32 \
  --trace --run-pnnx --pnnx venv/bin/pnnx

lm_head projects to 283386 vocabulary entries and can consume substantial memory. Its explicit safeguard is intentional. Embedding and lm_head share tied weight content, so their release bins can be hard-linked after their hashes are confirmed equal; their param files remain distinct.

11.6 Optional layer-level decoder diagnosis

When changing PyTorch, Transformers, or pnnx versions, validate layer 0 before all layers:

Bash
venv/bin/python export/youtu_decoder_layer_probe.py --help
venv/bin/python export/youtu_ncnn_decoder_layer_parity.py --help
venv/bin/python export/youtu_decoder_layers_pipeline.py \
  --layers 0-39 --pnnx venv/bin/pnnx

Per-layer graphs diagnose RoPE, concatenation, dynamic axes, and cache layout. They are not release assets.

11.7 Export decode and dynamic prefill

Bash
venv/bin/python export/youtu_full_decoder_probe.py \
  --model assets/hf/Youtu-VL-4B-Instruct --mode decode --dtype fp32 \
  --trace --run-pnnx --patch-param --pnnx venv/bin/pnnx

venv/bin/python export/youtu_full_decoder_probe.py \
  --model assets/hf/Youtu-VL-4B-Instruct --mode prefill --dtype fp32 \
  --trace --run-pnnx --patch-param --pnnx venv/bin/pnnx

The decode output uses youtu_decoder_full_manual_kv_sdpa_ncnn.ncnn.patched.param. A 33-token reference produces the prefill _s33.ncnn.bin; patching emits youtu_decoder_full_prefill_manual_kv_sdpa_ncnn.dynamic.patched.param, which accepts runtime sequence lengths. --patch-param is required runtime adaptation, not cosmetic cleanup. Decode and prefill bins contain identical weights and should be hard-linked in the release tree.

11.8 Export dynamic vision and merger

Bash
venv/bin/python export/youtu_vl_vision_dynamic_export.py \
  --model assets/hf/Youtu-VL-4B-Instruct \
  --input-npz assets/youtu_vl_test/vision_embeds_smoke/coco_cats_describe.npz \
  --dtype fp32 \
  --trace --trace-post-merger \
  --run-pnnx --run-post-merger-pnnx \
  --patch-param --patch-post-merger-param \
  --pnnx venv/bin/pnnx

Keep the two .dynamic.patched.param files and matching bins. Although tracing uses 432 patches, the patched sequence axis is dynamic; C++ computes runtime window indices, masks, and RoPE. Do not pass --pnnx-fp16: vision attention QK scores can overflow to NaN in the fp16 path.

11.9 Assemble and verify the release tree

Copy the parity-approved files into release/youtu-vl-ncnn-fp32/ using ASSET_MANIFEST.json as the filename map. Rename exported embedding files to the release stem youtu_embed_tokens_fp32. Copy tokenizer.json and the upstream model license. Confirm equal SHA-256 values before creating hard links for embedding/lm_head and decode/prefill.

Validate in increasing scope:

代码
embedding -> final norm -> lm_head -> full decode
-> dynamic prefill at several lengths -> vision at several patch lengths
-> text multi-token parity -> multimodal multi-sample token parity
Bash
venv/bin/python export/youtu_dynamic_prefill_smoke.py \
  --lengths 1,2,3,8,16,33 --compare-lengths 2,3

venv/bin/python export/youtu_vl_e2e_token_parity.py \
  --only coco_cats:describe --only coco_cats:count \
  --only synthetic_receipt:read_text --max-new-tokens 8

Acceptance means identical processor/C++ prompt IDs and identical greedy generated IDs through EOS or the requested length, not merely semantically similar prose.

11.10 Common conversion failures

  • pnnx is killed by OOM: separate tracing from conversion, stop other large processes, and increase RAM/swap. Never convert decoder and lm_head concurrently.
  • An NPZ key is missing: regenerate text references with --capture-decoder-io.
  • Errors grow in later layers: locate the first abnormal layer and inspect top-k/argmax; do not hide a layout bug behind a global tolerance increase.
  • Only the traced length works: ensure the runner loads .dynamic.patched.param, not the raw pnnx param.
  • Vision produces NaN: keep vision FP32 and disable fp16/bf16 storage and arithmetic.
  • The release expands to about 39 GB: the copy/archive operation expanded hard links; recreate the two shared-weight link pairs.

12. CMake and dependencies

The default preset builds pinned third_party/ncnn. A preinstalled package can be selected with system-ncnn, ncnn_DIR, and, when needed, YOUTU_STB_IMAGE_INCLUDE_DIR.

The production runner directly depends on ncnn, zlib for historical NPZ debugging, stb_image from ncnn, and the C++17 standard library. Production inference does not depend on Python, PyTorch, Transformers, OpenCV, or Pillow.

13. Why the release is still about 20 GB

ComponentApproximate physical size
40-layer decoder weights15.5 GiB
Tied embedding/lm_head2.7 GiB
SigLIP2 encoder1.5 GiB
Merger, tokenizer, and other filesabout 0.2 GiB

Hard links share prefill/decode and embedding/lm_head payloads. An archiver that expands hard links can inflate the logical package to roughly 39 GB. FP16, INT8, and INT4 remain future work and require renewed token-parity validation.

14. Known limitations

  1. The roughly 20 GB model package has not yet been published as a GitHub Release.
  2. Representative samples pass consecutive-token parity, but long answers through EOS are not complete for the whole manifest.
  3. Linux and Windows compile and pass CTest; full-model runtime verification has primarily been performed on macOS ARM64.
  4. Only greedy decoding is implemented, without temperature, top-k, or top-p sampling.
  5. The production interface targets one image and one prompt, not a complete chat service.
  6. FP32 size and memory use are not practical for many edge devices.
  7. The C++ runner remains a single large source file.
  8. Fixed-vision, NPZ, and per-layer debug paths remain, but their large assets must be regenerated.
  9. A project-level open-source license has not yet been selected; third-party notices are tracked separately.

15. Frequently asked questions

Why are model files absent from Git? GitHub Git has file-size limits and the model is about 20 GB. Releases, object storage, or model hosting are appropriate; Git should track manifests and hashes.

Why not export one enormous image-to-text graph? Tokenization, image decoding, dynamic grids, the generation loop, and a growing KV cache are control-flow-heavy. C++ handles dynamic control while ncnn handles expensive matrix computation.

Why require equal tokens rather than bit-identical floats? Frameworks, SIMD paths, and operator fusion introduce small numerical differences. Greedy output is identical when every argmax is identical, while intermediate metrics still guard against accidental agreement.

Why compute vision masks and RoPE in C++? They depend on the runtime patch grid. Tracing them as constants fixes the image size, while retaining complex dynamic indexing is unreliable through pnnx/ncnn. C++ generation is the robust compromise.

Why is ncnn_llm not a submodule? Its single-decoder, KV-cache, and runtime organization informed this project, but the production binary does not link it. Only the actual build dependency, ncnn, is pinned.

What causes model file not found? Verify models/text, models/vision, and tokenizer/tokenizer.json under the release root, then set YOUTU_VL_ROOT or --root when necessary.

Why can a parity script not find the HF model? Cleanup removed original weights. Download them again under assets/hf/Youtu-VL-4B-Instruct/.

16. Next work

  1. Publish FP32 assets with resumable downloads and SHA-256 verification.
  2. Run every manifest sample for 16/32 tokens or until EOS.
  3. Run real multimodal inference with the complete model on Linux x86_64 and Windows x64.
  4. Split the C++ runner into tokenizer, vision, model-loading, and generation modules.
  5. Add an asset downloader and automatic integrity checks.
  6. Evaluate FP16/INT8/INT4 and repeat per-token parity.
  7. Publish a GitHub Discussion with technical and performance results.
  8. Identify reusable changes suitable for an optional ncnn_llm pull request.
原文