Run this model with HF Jobs
Run AXERA-TECH/InternVL3_5-1B on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/AXERA-TECH/InternVL3_5-1B. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/AXERA-TECH/InternVL3_5-1B on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/AXERA-TECH/InternVL3_5-1B. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/AXERA-TECH/InternVL3_5-1B. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use AXERA-TECH/InternVL3_5-1B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use AXERA-TECH/InternVL3_5-1B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="AXERA-TECH/InternVL3_5-1B")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("AXERA-TECH/InternVL3_5-1B", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use AXERA-TECH/InternVL3_5-1B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "AXERA-TECH/InternVL3_5-1B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "AXERA-TECH/InternVL3_5-1B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/AXERA-TECH/InternVL3_5-1B
- SGLang
How to use AXERA-TECH/InternVL3_5-1B with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "AXERA-TECH/InternVL3_5-1B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "AXERA-TECH/InternVL3_5-1B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "AXERA-TECH/InternVL3_5-1B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "AXERA-TECH/InternVL3_5-1B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use AXERA-TECH/InternVL3_5-1B with Docker Model Runner:
docker model run hf.co/AXERA-TECH/InternVL3_5-1B
yongqiang commited on
Commit ·
8a9aaa0
0
Parent(s):
Initialize the repository
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded+44
- .gitignoreAdded+14
- README.mdAdded+147
- assets/demo_1.pngAdded
- assets/demo_2.pngAdded
- config.jsonAdded+3
- examples/image_0.jpgAdded
- examples/image_1.jpgAdded
- examples/image_2.pngAdded
- examples/image_3.pngAdded
- examples/laorenshuaidao.mp4Added+3
- examples/red-panda.mp4Added+3
- examples/tuboshu.mp4Added+3
- gradio_demo.pyAdded+389
- infer_axmodel.pyAdded+183
- infer_torch.pyAdded+212
- internvl3-5_axmodel/model.embed_tokens.weight.bfloat16.binAdded+3
- internvl3-5_axmodel/model.embed_tokens.weight.float32.binAdded+3
- internvl3-5_axmodel/model.embed_tokens.weight.npyAdded+3
- internvl3-5_axmodel/qwen3_p128_l0_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l10_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l11_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l12_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l13_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l14_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l15_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l16_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l17_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l18_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l19_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l1_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l20_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l21_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l22_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l23_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l24_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l25_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l26_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l27_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l2_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l3_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l4_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l5_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l6_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l7_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l8_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_p128_l9_together.axmodelAdded+3
- internvl3-5_axmodel/qwen3_post.axmodelAdded+3
- internvl3-5_tokenizer/.gitattributesAdded+36
- internvl3-5_tokenizer/README.mdAdded+830
1234567891011121314151617181920212223242526272829303132333435363738394041424344*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text*.axmodel filter=lfs diff=lfs merge=lfs -textmain_api_ax650 filter=lfs diff=lfs merge=lfs -textmain_api_axcl_x86 filter=lfs diff=lfs merge=lfs -textmain_ax650 filter=lfs diff=lfs merge=lfs -textmain_axcl_x86 filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text*.mp4 filter=lfs diff=lfs merge=lfs -text*.json filter=lfs diff=lfs merge=lfs -text1234567891011121314__pycache__*.tarbuild-output/*.onnx*.pth*.pkl*.bin*.npy*.axmodel*_axmodel/*.safetensorscompiled**tmp/
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147---library_name: transformerslicense: bsd-3-clausebase_model:- OpenGVLab/InternVL3_5-1Btags:- InternVL3- InternVL3_5-1B- Int8- VLMpipeline_tag: image-text-to-textlanguage:- en---
# InternVL3_5-1B
This version of InternVL3_5-1B has been converted to run on the Axera NPU using **w8a16** quantization.
This model has been optimized with the following LoRA:
Compatible with Pulsar2 version: 4.1
## Convert tools links:
For those who are interested in model conversion, you can try to export axmodel through the original repo:
https://huggingface.co/OpenGVLab/InternVL3_5-1B
[How to Convert LLM from Huggingface to axmodel](https://github.com/AXERA-TECH/InternVL3_5-1B.axera/tree/main/model_convert)
[AXera NPU HOST LLM Runtime](https://github.com/AXERA-TECH/ax-llm/tree/ax-internvl)
[AXera NPU AXCL LLM Runtime](https://github.com/AXERA-TECH/ax-llm/tree/axcl-internvl)
## Support Platform
- AX650 - AX650N DEMO Board - [M4N-Dock(爱芯派Pro)](https://wiki.sipeed.com/hardware/zh/maixIV/m4ndock/m4ndock.html) - [M.2 Accelerator card](https://axcl-docs.readthedocs.io/zh-cn/latest/doc_guide_hardware.html) |Chips|image encoder 448|ttft|w8a16||--|--|--|--||AX650| 364.412 ms | 5072 ms | 21.60 tokens/sec|
## How to use
Download all files from this repository to the device
```$ tree -L 1.├── assets├── config.json├── examples├── gradio_demo.py├── infer_axmodel.py├── infer_torch.py├── internvl3-5_axmodel├── internvl3-5_tokenizer├── README.md├── utils└── vit-models
6 directories, 5 files```
#### Install transformer
```pip install transformers==4.57.1```
#### Inference with AX650 Host, such as M4N-Dock(爱芯派Pro) or AX650 DEMO Board
Interactive conversations using the `Gradio API`:
```bash$ python3 gradio_demo.py --hf_model internvl3-5_tokenizer/ --axmodel_path internvl3-5_axmodel/ --vit_model vit-models/internvl_vit_model_1x3x448x448.axmodel```
Plain text dialogue:

Image understanding:

---
Run the following command on the Axera board to start a chat conversation:
```sh$ cd InternVL3_5-1B.axera/python$ python3 infer_axmodel.py --hf_model internvl3-5_tokenizer/ --axmodel_path internvl3-5_axmodel/ --question "请计算函数[y=2x^2+2]的导数, 并提供 markdown 格式的推理过程"```
output:
```bash[INFO] Using provider: AxEngineExecutionProvider[INFO] Model type: 2 (triple core)[INFO] Compiler version: 5.1-dirty 0fdbfe15-dirtyModel loaded successfully!slice_indices: [0]Slice prefill done: 0answer >> 函数 \( y = 2x^2 + 2 \) 的导数可以通过求导法则来计算。首先,我们对函数中的每一项分别求导:
1. 对于 \( 2x^2 \),使用幂法则求导: \[ \frac{d}{dx}(2x^2) = 2 \cdot 2x = 4x \]
2. 对于常数项 \( 2 \),其导数为 0,因为常数的导数为 0。
将这两部分的结果相加,得到函数 \( y \) 的导数:\[y' = 4x\]
因此,函数 \( y = 2x^2 + 2 \) 的导数为 \( y' = 4x \)。```
Enter the following command to perform the single-image understanding task:
```sh$ cd InternVL3_5-1B.axera/python$ python3 infer_axmodel.py --hf_model internvl3-5_tokenizer/ --axmodel_path internvl3-5_axmodel/ --question "请描述这幅图" -i examples/image_0.jpg --vit_model vit-models/internvl_vit_model_1x3x448x448.axmodel```

output:
```bash[INFO] Model type: 2 (triple core)[INFO] Compiler version: 5.1-dirty 0fdbfe15-dirtyModel loaded successfully!slice_indices: [0, 1, 2]Slice prefill done: 0Slice prefill done: 1Slice prefill done: 2answer >> 这是一张红熊猫的照片。红熊猫是一种红棕色的哺乳动物,通常生活在亚洲的森林中。它们以捕食昆虫和小型无脊椎动物为生。图片中,红熊猫正坐在一个木制的平台上,背景是绿色的树木和植被,显得非常自然和生动。红熊猫的表情看起来很友好,似乎在观察或等待什么。```123version https://git-lfs.github.com/spec/v1oid sha256:e960e7c7b8924496695fb1e1676f969d6243afd404e21c16e4287d39f0756da5size 3874123version https://git-lfs.github.com/spec/v1oid sha256:8f5c00b37b23af3d01d133da880eb7f6e50d4af608e3575784be7063eb137011size 2704112123version https://git-lfs.github.com/spec/v1oid sha256:d921c07bb97224d65a37801541d246067f0d506f08723ffa1ad85c217907ccb8size 1867237123version https://git-lfs.github.com/spec/v1oid sha256:ced4d95877b9a7f8b48f79bdfe4287eff8837f20348daec2f2e2987459ec1712size 5952043123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389import argparseimport osimport timefrom typing import Any, Dict, List, Optional, Generator, Tuple
import gradio as grimport numpy as npimport torchimport torchvision.transforms as Tfrom ml_dtypes import bfloat16from PIL import Imagefrom torchvision.transforms.functional import InterpolationModefrom transformers import AutoConfig, AutoTokenizer
from utils.infer_func import InferManagerfrom axengine import InferenceSession
IMAGENET_MEAN = (0.485, 0.456, 0.406)IMAGENET_STD = (0.229, 0.224, 0.225)IMG_PLACEHOLDER_TOKEN_ID = 151669 # <img>IMG_CONTEXT_REPEAT = 256 # number of image context tokens expected by the model
SYSTEM_PROMPT = ( "<|im_start|>system\n" "你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型, 英文名叫 InternVL3, " "是一个有用无害的人工智能助手, 擅长思考和回答用户的问题. 请你在回答问题时使用简体中文." "<|im_end|>\n")
def build_transform(input_size: int): transform = T.Compose([ T.Lambda(lambda img: img.convert("RGB") if img.mode != "RGB" else img), T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC), T.ToTensor(), T.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD), ]) return transform
def dynamic_preprocess(image: Image.Image, min_num: int = 1, max_num: int = 12, image_size: int = 448, use_thumbnail: bool = False): orig_width, orig_height = image.size aspect_ratio = orig_width / orig_height
target_ratios = set( (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if i * j <= max_num and i * j >= min_num ) target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
def find_closest_aspect_ratio(ar: float, ratios: List[tuple]): best_ratio_diff = float("inf") best_ratio = (1, 1) area = orig_width * orig_height for ratio in ratios: target_aspect_ratio = ratio[0] / ratio[1] ratio_diff = abs(ar - target_aspect_ratio) if ratio_diff < best_ratio_diff: best_ratio_diff = ratio_diff best_ratio = ratio elif ratio_diff == best_ratio_diff: if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]: best_ratio = ratio return best_ratio
target_aspect_ratio = find_closest_aspect_ratio(aspect_ratio, target_ratios) target_width = image_size * target_aspect_ratio[0] target_height = image_size * target_aspect_ratio[1] blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
resized_img = image.resize((target_width, target_height)) processed_images = [] for i in range(blocks): box = ( (i % (target_width // image_size)) * image_size, (i // (target_width // image_size)) * image_size, ((i % (target_width // image_size)) + 1) * image_size, ((i // (target_width // image_size)) + 1) * image_size, ) split_img = resized_img.crop(box) processed_images.append(split_img) assert len(processed_images) == blocks if use_thumbnail and len(processed_images) != 1: processed_images.append(image.resize((image_size, image_size))) return processed_images
def load_image(image_file: Image.Image, input_size: int = 448, max_num: int = 12): transform = build_transform(input_size=input_size) images = dynamic_preprocess(image_file, image_size=input_size, use_thumbnail=True, max_num=max_num) pixel_values = [transform(img) for img in images] pixel_values = torch.stack(pixel_values) return pixel_values
class InternVLGradioDemo: def __init__(self, hf_model: str, axmodel_dir: str, vit_axmodel: str, max_seq_len: int = 2047): self.hf_model = hf_model self.axmodel_dir = axmodel_dir self.vit_axmodel = vit_axmodel self.device = "cuda" if torch.cuda.is_available() else "cpu"
self.embeds = np.load(os.path.join(axmodel_dir, "model.embed_tokens.weight.npy")) self.tokenizer = AutoTokenizer.from_pretrained(self.hf_model) config = AutoConfig.from_pretrained(self.hf_model, trust_remote_code=True) self.cfg = config.llm_config
self.vit_session = InferenceSession(self.vit_axmodel) self.infer_manager = InferManager(self.cfg, self.axmodel_dir, max_seq_len=max_seq_len)
def _build_single_turn_prompt(self, user_text: str, vit_features: List[np.ndarray]): prompt = SYSTEM_PROMPT prompt += f"<|im_start|>user\n{user_text}" for _ in vit_features: prompt += "\n<img>" + "<IMG_CONTEXT>" * IMG_CONTEXT_REPEAT + "</img>" prompt += "<|im_end|>\n<|im_start|>assistant\n" return prompt
def _insert_vision_features(self, token_ids: List[int], prefill_data: np.ndarray, vit_features: List[np.ndarray]): image_start_indices = np.where(np.array(token_ids) == IMG_PLACEHOLDER_TOKEN_ID)[0].tolist() if len(image_start_indices) != len(vit_features): raise ValueError("图片数量与占位符数量不一致, 请检查输入和模板生成逻辑") for idx, image_start_index in enumerate(image_start_indices): insert_pos = image_start_index + 1 prefill_data[insert_pos: insert_pos + IMG_CONTEXT_REPEAT] = vit_features[idx][0, :, :] return prefill_data
def _run_model(self, prompt: str, vit_features: List[np.ndarray]): """Non-streaming推理,保留以防需要一次性结果。""" for k_cache in self.infer_manager.k_caches: k_cache.fill(0) for v_cache in self.infer_manager.v_caches: v_cache.fill(0)
token_ids = self.tokenizer.encode(prompt) prefill_data = np.take(self.embeds, token_ids, axis=0).astype(bfloat16) if vit_features: prefill_data = self._insert_vision_features(token_ids, prefill_data, vit_features)
eos_token_id = None if isinstance(self.cfg.eos_token_id, list) and len(self.cfg.eos_token_id) > 1: eos_token_id = self.cfg.eos_token_id
slice_len = 128 token_ids = self.infer_manager.prefill(self.tokenizer, token_ids, prefill_data, slice_len=slice_len) return self.infer_manager.decode( self.tokenizer, token_ids, self.embeds, slice_len=slice_len, eos_token_id=eos_token_id, stream=False, )
def _stream_generate(self, prompt: str, vit_features: List[np.ndarray]): """流式生成,逐 token 产出累积文本与计时信息 (TTFT 与平均 decode ms/token)。""" # reset kv cache per request for k_cache in self.infer_manager.k_caches: k_cache.fill(0) for v_cache in self.infer_manager.v_caches: v_cache.fill(0)
token_ids = self.tokenizer.encode(prompt) prefill_data = np.take(self.embeds, token_ids, axis=0).astype(bfloat16) if vit_features: prefill_data = self._insert_vision_features(token_ids, prefill_data, vit_features)
eos_token_id = None if isinstance(self.cfg.eos_token_id, list) and len(self.cfg.eos_token_id) > 1: eos_token_id = self.cfg.eos_token_id
slice_len = 128 t_start = time.time() token_ids = self.infer_manager.prefill(self.tokenizer, token_ids, prefill_data, slice_len=slice_len)
# copy decode逻辑,实现手动流式输出 mask = np.zeros((1, 1, self.infer_manager.max_seq_len + 1), dtype=np.float32).astype(bfloat16) mask[:, :, :self.infer_manager.max_seq_len] -= 65536 seq_len = len(token_ids) - 1 if slice_len > 0: mask[:, :, :seq_len] = 0
ttft_ms: Optional[float] = None decode_tokens = 0 decode_elapsed_ms: float = 0.0 generated_text = "" yield generated_text, ttft_ms, None, None, False
for step_idx in range(self.infer_manager.max_seq_len): if slice_len > 0 and step_idx < seq_len: continue cur_token = token_ids[step_idx] indices = np.array([step_idx], np.uint32).reshape((1, 1)) data = self.embeds[cur_token, :].reshape((1, 1, self.cfg.hidden_size)).astype(bfloat16) for layer_idx in range(self.cfg.num_hidden_layers): input_feed = { "K_cache": self.infer_manager.k_caches[layer_idx], "V_cache": self.infer_manager.v_caches[layer_idx], "indices": indices, "input": data, "mask": mask, } outputs = self.infer_manager.decoder_sessions[layer_idx].run(None, input_feed, shape_group=0) self.infer_manager.k_caches[layer_idx][:, step_idx, :] = outputs[0][:, :, :] self.infer_manager.v_caches[layer_idx][:, step_idx, :] = outputs[1][:, :, :] data = outputs[2] mask[..., step_idx] = 0 if step_idx < seq_len - 1: continue post_out = self.infer_manager.post_process_session.run(None, {"input": data})[0] next_token, possible_tokens, possible_probs = self.infer_manager.post_process(post_out, temperature=0.7) if eos_token_id is not None and next_token in eos_token_id: ttft_ms = ttft_ms or (time.time() - t_start) * 1000 break if next_token == self.tokenizer.eos_token_id: ttft_ms = ttft_ms or (time.time() - t_start) * 1000 break
token_ids.append(next_token) # 使用完整 token 列表解码,避免多字节 UTF-8 字符被截断显示为乱码 # 只解码新生成的 tokens(从 seq_len 开始) generated_text = self.tokenizer.decode(token_ids[seq_len:], skip_special_tokens=True)
if ttft_ms is None: ttft_ms = (time.time() - t_start) * 1000 else: decode_tokens += 1 decode_elapsed_ms = (time.time() - t_start) * 1000 - ttft_ms
avg_decode = (decode_elapsed_ms / decode_tokens) if decode_tokens > 0 else None yield generated_text, ttft_ms, avg_decode, decode_tokens, False
total_ms = (time.time() - t_start) * 1000 avg_decode = (decode_elapsed_ms / decode_tokens) if decode_tokens > 0 else None yield generated_text, ttft_ms, avg_decode, decode_tokens, True
def chat(self, user_input: str, image: Optional[Image.Image]) -> Generator: user_text = (user_input or "").strip() if not user_text and image is None: yield [], gr.update(), gr.update(), gr.update(), gr.update() return
# 先展示占位,保持图片不清空;同时占位速度信息 yield [(user_text, "处理中…")], gr.update(value=""), gr.update(), gr.update(value="<div style='text-align: right; font-size: 13px; color: #6b7280; font-family: monospace;'>TTFT -- ms | Decode -- ms/token | Tokens --</div>"), gr.update(interactive=False)
vit_outputs = [] if image is not None: pixel_values = load_image(image, input_size=448, max_num=1) vit_output = self.vit_session.run(None, {"image": pixel_values.numpy()})[0] vit_outputs.append(vit_output.copy())
prompt = self._build_single_turn_prompt(user_text, vit_outputs)
chatbot_history = [(user_text, "")] # 将在流式过程中填充 for partial, ttft_ms, avg_decode_ms, decode_tokens, finished in self._stream_generate(prompt, vit_outputs): chatbot_history[-1] = (user_text, partial) ttft_disp = f"{ttft_ms:.0f}" if ttft_ms is not None else "--" decode_disp = f"{avg_decode_ms:.1f}" if avg_decode_ms is not None else "--" tok_disp = f"{decode_tokens}" if decode_tokens is not None else "--" metrics_text = f"<div style='text-align: right; font-size: 13px; color: #6b7280; font-family: monospace;'>TTFT {ttft_disp} ms | Decode {decode_disp} ms/token | Tokens {tok_disp}</div>" if finished: yield chatbot_history, gr.update(value=""), gr.update(), gr.update(value=metrics_text), gr.update(interactive=True) else: yield chatbot_history, gr.update(value=""), gr.update(), gr.update(value=metrics_text), gr.update(interactive=False)
@staticmethod def build_ui(demo: "InternVLGradioDemo", server_name: str = "0.0.0.0", server_port: int = 7860, share: bool = False): # 自定义 JavaScript: Enter 发送, Shift+Enter 换行 custom_js = """ function() { // 等待 DOM 加载完成后绑定事件 setTimeout(() => { const textareas = document.querySelectorAll('#user-input textarea'); textareas.forEach(textarea => { // 移除可能存在的旧监听器 textarea.removeEventListener('keydown', textarea._customKeyHandler);
textarea._customKeyHandler = function(e) { if (e.key === 'Enter') { if (e.shiftKey) { // Shift+Enter: 插入换行符 e.preventDefault(); const start = this.selectionStart; const end = this.selectionEnd; const value = this.value; this.value = value.substring(0, start) + '\\n' + value.substring(end); this.selectionStart = this.selectionEnd = start + 1; // 触发 input 事件让 Gradio 感知变化 this.dispatchEvent(new Event('input', { bubbles: true })); } else { // Enter: 发送消息 e.preventDefault(); const sendBtn = document.querySelector('#send-btn'); if (sendBtn) { sendBtn.click(); } } } }; textarea.addEventListener('keydown', textarea._customKeyHandler); }); }, 500); } """
with gr.Blocks(title="InternVL3-5-1B AX Gradio Demo", theme=gr.themes.Soft(), js=custom_js) as iface: gr.HTML("""<style> #image-pane img {object-fit: contain; max-height: 380px;} #chat-wrap {position: relative;} #metrics-display {position: absolute; right: 12px; bottom: 12px; z-index: 5; pointer-events: none; text-align: right;} #metrics-display > div {display: inline-block;} </style>""") gr.Markdown("""### InternVL3-5-1B 图文对话演示\n上传一张图片 (可选),输入问题,获取中文回答。""")
with gr.Row(): # 左侧:对话框和输入区域 with gr.Column(scale=5): with gr.Group(elem_id="chat-wrap"): chatbot = gr.Chatbot(height=500, label="对话") metrics_md = gr.Markdown("<div style='text-align: right; font-size: 13px; color: #6b7280; font-family: monospace;'>TTFT -- ms | Decode -- ms/token | Tokens --</div>", elem_id="metrics-display")
with gr.Row(): user_input = gr.Textbox( placeholder="按 Enter 发送,Shift+Enter 换行", lines=2, scale=7, max_lines=5, show_label=False, elem_id="user-input", ) with gr.Column(scale=1, min_width=100): send_btn = gr.Button("发送", variant="primary", size="sm", elem_id="send-btn") clear_btn = gr.Button("清空对话", variant="secondary", size="sm")
# 右侧:图像上传和信息提示 with gr.Column(scale=3): image_input = gr.Image( type="pil", label="上传图片 (可选)", height=380, image_mode="RGB", show_download_button=False, elem_id="image-pane", ) gr.Markdown("""- 支持单张图像理解\n- 仅当前问题与回答,不保留历史\n- 处理时间取决于硬件,请耐心等待""")
def _clear(): return [], gr.update(value=""), gr.update(), gr.update(value="<div style='text-align: right; font-size: 13px; color: #6b7280; font-family: monospace;'>TTFT -- ms | Decode -- ms/token | Tokens --</div>"), gr.update(interactive=True)
send_btn.click( fn=demo.chat, inputs=[user_input, image_input], outputs=[chatbot, user_input, image_input, metrics_md, send_btn], show_progress=False, queue=True, ) # 移除 user_input.submit,由自定义 JS 处理 Enter 发送,Shift+Enter 换行 clear_btn.click(fn=_clear, inputs=None, outputs=[chatbot, user_input, image_input, metrics_md, send_btn])
iface.queue().launch(server_name=server_name, server_port=server_port, share=share)
def parse_args(): parser = argparse.ArgumentParser(description="InternVL3-5-1B AX gradio demo") parser.add_argument("--hf_model", type=str, default="./InternVL3_5-1B", help="HuggingFace 模型路径") parser.add_argument("--axmodel_path", type=str, default="./InternVL3_5-1B_axmodel", help="LLM axmodel 目录") parser.add_argument("--vit_model", type=str, default="./vit-models/internvl_vit_model_1x3x448x448.axmodel", help="ViT axmodel 路径") parser.add_argument("--port", type=int, default=7860, help="Gradio 端口") parser.add_argument("--host", type=str, default="0.0.0.0", help="Gradio 监听地址") parser.add_argument("--share", action="store_true", help="启用 gradio share") return parser.parse_args()
def main(): args = parse_args() demo = InternVLGradioDemo(args.hf_model, args.axmodel_path, args.vit_model) InternVLGradioDemo.build_ui(demo, server_name=args.host, server_port=args.port, share=args.share)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183from transformers import AutoProcessor, AutoModelForImageTextToTextimport torchimport onnximport onnxruntime as ortimport numpy as npimport osfrom tqdm import tqdmfrom transformers import AutoConfig, AutoTokenizerfrom typing import List, Tuplefrom axengine import InferenceSessionfrom ml_dtypes import bfloat16from utils.infer_func import InferManagerimport argparsefrom PIL import Imageimport torchvision.transforms as Tfrom torchvision.transforms.functional import InterpolationMode
IMAGENET_MEAN = (0.485, 0.456, 0.406)IMAGENET_STD = (0.229, 0.224, 0.225)
def build_transform(input_size): MEAN, STD = IMAGENET_MEAN, IMAGENET_STD transform = T.Compose([ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img), T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC), T.ToTensor(), T.Normalize(mean=MEAN, std=STD) ]) return transform
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size): best_ratio_diff = float('inf') best_ratio = (1, 1) area = width * height for ratio in target_ratios: target_aspect_ratio = ratio[0] / ratio[1] ratio_diff = abs(aspect_ratio - target_aspect_ratio) if ratio_diff < best_ratio_diff: best_ratio_diff = ratio_diff best_ratio = ratio elif ratio_diff == best_ratio_diff: if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]: best_ratio = ratio return best_ratio
def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False): orig_width, orig_height = image.size aspect_ratio = orig_width / orig_height
# calculate the existing image aspect ratio target_ratios = set( (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if i * j <= max_num and i * j >= min_num) target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
# find the closest aspect ratio to the target target_aspect_ratio = find_closest_aspect_ratio( aspect_ratio, target_ratios, orig_width, orig_height, image_size)
# calculate the target width and height target_width = image_size * target_aspect_ratio[0] target_height = image_size * target_aspect_ratio[1] blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
# resize the image resized_img = image.resize((target_width, target_height)) processed_images = [] for i in range(blocks): box = ( (i % (target_width // image_size)) * image_size, (i // (target_width // image_size)) * image_size, ((i % (target_width // image_size)) + 1) * image_size, ((i // (target_width // image_size)) + 1) * image_size ) # split the image split_img = resized_img.crop(box) processed_images.append(split_img) assert len(processed_images) == blocks if use_thumbnail and len(processed_images) != 1: thumbnail_img = image.resize((image_size, image_size)) processed_images.append(thumbnail_img) return processed_images
def load_image(image_file, input_size=448, max_num=12): image = Image.open(image_file).convert('RGB') transform = build_transform(input_size=input_size) images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num) pixel_values = [transform(image) for image in images] pixel_values = torch.stack(pixel_values) return pixel_values
if __name__ == "__main__":
""" python3 infer_axmodel.py --vit_model vit-models/internvl_vit_model_1x3x448x448.axmodel --images examples/image_0.jpg """ prompt = None parser = argparse.ArgumentParser(description="Model configuration parameters") parser.add_argument("--hf_model", type=str, default="./InternVL3_5-1B", help="Path to HuggingFace model") parser.add_argument("--axmodel_path", type=str, default="./InternVL3_5-1B_axmodel", help="Path to save compiled axmodel of llama model") parser.add_argument("--vit_model", type=str, default=None, help="Path to save compiled axmodel of llama model") parser.add_argument("-i", "--images", nargs='+', type=str, default=None, help="Path to the test image.") parser.add_argument("-q", "--question", type=str, default="请你描述这幅图的内容.", help="Your question that you want to ask the model.") args = parser.parse_args()
hf_model_path = args.hf_model axmodel_path = args.axmodel_path images = args.images prompt = args.question
device = "cuda" if torch.cuda.is_available() else "cpu" embeds = np.load(os.path.join(axmodel_path, "model.embed_tokens.weight.npy"))
# load the tokenizer and the model tokenizer = AutoTokenizer.from_pretrained(hf_model_path) config = AutoConfig.from_pretrained(hf_model_path, trust_remote_code=True)
# model = AutoModelForCausalLM.from_pretrained( # hf_model_path, # ).to(device)
test_imgs_path = args.images vit_axmodel_path = args.vit_model
# set the max number of tiles in `max_num` pixel_values_list = [] if test_imgs_path is not None: for img_path in test_imgs_path: pixel_values = load_image(img_path, input_size=448, max_num=1) pixel_values_list.append(pixel_values) print(f"输入图像数: {len(pixel_values_list)}") print("preprocess image done!")
# extract img feature by vit vit_session = InferenceSession(vit_axmodel_path) vit_output_list = [] for idx, pixel_values in enumerate(pixel_values_list): vit_output = vit_session.run(None, {"image": pixel_values.numpy()})[0] vit_output_list.append(vit_output.copy()) # 避免 vit 输出结果使用同一块内存
print(f"vit_output.shape is {vit_output_list[0].shape}, vit feature extract done!")
prompt = "<|im_start|>system\n你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型, 英文名叫 InternVL3, 是一个有用无害的人工智能助手, 擅长思考和回答用户的问题. 请你在回答问题时使用简体中文.<|im_end|>\n" question = args.question prompt += "<|im_start|>user\n" + question
if len(pixel_values_list) > 0: for idx in range(len(pixel_values_list)): prompt += "\n<img>" + "<IMG_CONTEXT>" * 256 + "</img>\n" prompt += "<|im_end|>\n<|im_start|>assistant\n" print(f"prompt is {prompt}") token_ids = tokenizer.encode(prompt) # 图像理解 image_start_indices = np.where(np.array(token_ids) == 151669)[0].tolist() # <img> tag 151669, 151665 prefill_data = np.take(embeds, token_ids, axis=0) prefill_data = prefill_data.astype(bfloat16) token_len = len(token_ids)
for idx, image_start_index in enumerate(image_start_indices): image_insert_index = image_start_index + 1 prefill_data[image_insert_index : image_insert_index + 256] = vit_output_list[idx][0, :, :] ##################################
cfg = config.llm_config
eos_token_id = None if isinstance(cfg.eos_token_id, list) and len(cfg.eos_token_id) > 1: eos_token_id = cfg.eos_token_id
slice_len = 128 prefill_max_len = 1024 - 1 max_seq_len = 2048 - 1 # prefill + decode max length
imer = InferManager(cfg, axmodel_path, max_seq_len=max_seq_len) # prefill + decode max length # import pdb; pdb.set_trace() token_ids = imer.prefill(tokenizer, token_ids, prefill_data, slice_len=slice_len) imer.decode(tokenizer, token_ids, embeds, slice_len=slice_len, eos_token_id=eos_token_id) print("\n")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212import mathimport numpy as npimport torchimport torchvision.transforms as Tfrom decord import VideoReader, cpufrom PIL import Imagefrom torchvision.transforms.functional import InterpolationModefrom transformers import AutoModel, AutoTokenizer
IMAGENET_MEAN = (0.485, 0.456, 0.406)IMAGENET_STD = (0.229, 0.224, 0.225)
def build_transform(input_size): MEAN, STD = IMAGENET_MEAN, IMAGENET_STD transform = T.Compose([ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img), T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC), T.ToTensor(), T.Normalize(mean=MEAN, std=STD) ]) return transform
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size): best_ratio_diff = float('inf') best_ratio = (1, 1) area = width * height for ratio in target_ratios: target_aspect_ratio = ratio[0] / ratio[1] ratio_diff = abs(aspect_ratio - target_aspect_ratio) if ratio_diff < best_ratio_diff: best_ratio_diff = ratio_diff best_ratio = ratio elif ratio_diff == best_ratio_diff: if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]: best_ratio = ratio return best_ratio
def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False): orig_width, orig_height = image.size aspect_ratio = orig_width / orig_height
# calculate the existing image aspect ratio target_ratios = set( (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if i * j <= max_num and i * j >= min_num) target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
# find the closest aspect ratio to the target target_aspect_ratio = find_closest_aspect_ratio( aspect_ratio, target_ratios, orig_width, orig_height, image_size)
# calculate the target width and height target_width = image_size * target_aspect_ratio[0] target_height = image_size * target_aspect_ratio[1] blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
# resize the image resized_img = image.resize((target_width, target_height)) processed_images = [] for i in range(blocks): box = ( (i % (target_width // image_size)) * image_size, (i // (target_width // image_size)) * image_size, ((i % (target_width // image_size)) + 1) * image_size, ((i // (target_width // image_size)) + 1) * image_size ) # split the image split_img = resized_img.crop(box) processed_images.append(split_img) assert len(processed_images) == blocks if use_thumbnail and len(processed_images) != 1: thumbnail_img = image.resize((image_size, image_size)) processed_images.append(thumbnail_img) return processed_images
def load_image(image_file, input_size=448, max_num=12): image = Image.open(image_file).convert('RGB') transform = build_transform(input_size=input_size) images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num) pixel_values = [transform(image) for image in images] pixel_values = torch.stack(pixel_values) return pixel_values
path = './InternVL3_5-1B'model = AutoModel.from_pretrained( path, torch_dtype=torch.bfloat16, load_in_8bit=False, low_cpu_mem_usage=True, use_flash_attn=True, trust_remote_code=True, device_map="auto").eval()tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
# set the max number of tiles in `max_num`pixel_values = load_image('./examples/image_1.jpg', input_size=448, max_num=1).to(torch.bfloat16).cuda()generation_config = dict(max_new_tokens=1024, do_sample=True)
# pure-text conversation (纯文本对话)question = '中国的首都'response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)print(f'User: {question}\nAssistant: {response}')
# single-image single-round conversation (单图单轮对话)question = '<image>\n请你描述这幅图的内容.'response = model.chat(tokenizer, pixel_values, question, generation_config)print(f'User: {question}\nAssistant: {response}')
# # single-image multi-round conversation (单图多轮对话)# question = '<image>\nPlease describe the image in detail.'# response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)# print(f'User: {question}\nAssistant: {response}')
# question = 'Please write a poem according to the image.'# response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)# print(f'User: {question}\nAssistant: {response}')
# # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)# pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()# pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()# pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
# question = '<image>\nDescribe the two images in detail.'# response, history = model.chat(tokenizer, pixel_values, question, generation_config,# history=None, return_history=True)# print(f'User: {question}\nAssistant: {response}')
# question = 'What are the similarities and differences between these two images.'# response, history = model.chat(tokenizer, pixel_values, question, generation_config,# history=history, return_history=True)# print(f'User: {question}\nAssistant: {response}')
# # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)# pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()# pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()# pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)# num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
# question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'# response, history = model.chat(tokenizer, pixel_values, question, generation_config,# num_patches_list=num_patches_list,# history=None, return_history=True)# print(f'User: {question}\nAssistant: {response}')
# question = 'What are the similarities and differences between these two images.'# response, history = model.chat(tokenizer, pixel_values, question, generation_config,# num_patches_list=num_patches_list,# history=history, return_history=True)# print(f'User: {question}\nAssistant: {response}')
# # batch inference, single image per sample (单图批处理)# pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()# pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()# num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]# pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
# questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)# responses = model.batch_chat(tokenizer, pixel_values,# num_patches_list=num_patches_list,# questions=questions,# generation_config=generation_config)# for question, response in zip(questions, responses):# print(f'User: {question}\nAssistant: {response}')
# # video multi-round conversation (视频多轮对话)# def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):# if bound:# start, end = bound[0], bound[1]# else:# start, end = -100000, 100000# start_idx = max(first_idx, round(start * fps))# end_idx = min(round(end * fps), max_frame)# seg_size = float(end_idx - start_idx) / num_segments# frame_indices = np.array([# int(start_idx + (seg_size / 2) + np.round(seg_size * idx))# for idx in range(num_segments)# ])# return frame_indices
# def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):# vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)# max_frame = len(vr) - 1# fps = float(vr.get_avg_fps())
# pixel_values_list, num_patches_list = [], []# transform = build_transform(input_size=input_size)# frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)# for frame_index in frame_indices:# img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')# img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)# pixel_values = [transform(tile) for tile in img]# pixel_values = torch.stack(pixel_values)# num_patches_list.append(pixel_values.shape[0])# pixel_values_list.append(pixel_values)# pixel_values = torch.cat(pixel_values_list)# return pixel_values, num_patches_list
# video_path = './examples/red-panda.mp4'# pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)# pixel_values = pixel_values.to(torch.bfloat16).cuda()# video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])# question = video_prefix + 'What is the red panda doing?'# # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}# response, history = model.chat(tokenizer, pixel_values, question, generation_config,# num_patches_list=num_patches_list, history=None, return_history=True)# print(f'User: {question}\nAssistant: {response}')
# question = 'Describe this video in detail.'# response, history = model.chat(tokenizer, pixel_values, question, generation_config,# num_patches_list=num_patches_list, history=history, return_history=True)# print(f'User: {question}\nAssistant: {response}')123version https://git-lfs.github.com/spec/v1oid sha256:9458f8d6cac0fb032e0d9aa5e237148a2ee2e6f9c98ebf7584b065e174127009size 311164928123version https://git-lfs.github.com/spec/v1oid sha256:e69f2b742ddc9d789d16f46073fbe8fdfce77222958071fabf4ff708af07bf23size 622329856123version https://git-lfs.github.com/spec/v1oid sha256:0e826d74d8269b0085d3fdd397e7fa6303ec26719c76f4d5b1d029fab63fcf50size 622329984123version https://git-lfs.github.com/spec/v1oid sha256:f12d7e947b42e933d6c3119e08d6be0ecb703df7746839cb91a0452d12c490f0size 21568292123version https://git-lfs.github.com/spec/v1oid sha256:452cc345d0b182b95f3e961ac9faa1767563f8324fc3d3ed3372f5b63851059bsize 21569348123version https://git-lfs.github.com/spec/v1oid sha256:c9f031d1f7e7713d4f0aee4a5fc1a3beffd4593eae922e81946537eca946b04fsize 21568292123version https://git-lfs.github.com/spec/v1oid sha256:3295106128b7d41ae737274abc58a9b9e49fc1d56df904eb8b44d08b2a13462bsize 21569220123version https://git-lfs.github.com/spec/v1oid sha256:3b192de65f95a19271ddcf91eca383c782ecd23fb6be2fdb47369ec76d480e21size 21569156123version https://git-lfs.github.com/spec/v1oid sha256:2cd05f0f6d2b2f6b07c74cece9dfd09a86a5e2a0d1b941b6a01baf31a19edc53size 21568292123version https://git-lfs.github.com/spec/v1oid sha256:205d2b186e641bd8efb5cbcba1422d7f47384fc2e308ea791f79e0cffb002d48size 21568836123version https://git-lfs.github.com/spec/v1oid sha256:4ab96615046ebf359d86fbab9c45af036fb79bcd8e4bbf2d9cab63fef8b0ef47size 21568292123version https://git-lfs.github.com/spec/v1oid sha256:01b2569ba99a274fee59ef56ea4ba0e4109971d196240b254a68e4e0f0808ac2size 21568292123version https://git-lfs.github.com/spec/v1oid sha256:6eb521e5c3e03f3b96b6370362234e741910cf82c038984081e9ab95a101c31dsize 21568900123version https://git-lfs.github.com/spec/v1oid sha256:821a3937c506eaa268440ee116961ef2ceb17b5362661d3c9f41997a7aacf54fsize 21568740123version https://git-lfs.github.com/spec/v1oid sha256:5ba82686a72bb26759fbf96c7544277d5547ec23634f4128579bd53464072432size 21568932123version https://git-lfs.github.com/spec/v1oid sha256:5e70045401bd0c6748558ec0374d11cb381644109b687c0358fb8cec5e88de1csize 21568292123version https://git-lfs.github.com/spec/v1oid sha256:35ecb18c9bd8d79fe019df779b5f7212f0af1b742adbd69b9968f9e93ec83a83size 21568772123version https://git-lfs.github.com/spec/v1oid sha256:c5037445038d24a9a44c6defc22638f53ef9875ca62e9ea836077d1518c28d8dsize 21568964123version https://git-lfs.github.com/spec/v1oid sha256:510b76060ef414a7100989e631d6d8336ebf5573467eceb9cf5ad0641df15119size 21568644123version https://git-lfs.github.com/spec/v1oid sha256:87b6fed1cb82fee89097d326ddfd414e41f0d9bdc27087b630dc678235085a4csize 21569508123version https://git-lfs.github.com/spec/v1oid sha256:86f1c7b43867ca7c38b942d78b81eed377e61123c3ec1b954bc309c71793f4aasize 21568964123version https://git-lfs.github.com/spec/v1oid sha256:c7726bb67ea16ba081e73b9982c464cbd7317de09b7c1e34c58072b7a55a1cb8size 21568292123version https://git-lfs.github.com/spec/v1oid sha256:fa0888376b5c59ee87687961078bce26e9dc016a8207838659dabbaa400ce4f3size 21570244123version https://git-lfs.github.com/spec/v1oid sha256:59ed31ea8c87f7ea9d4e31b4911ad4be22d3b917b9ce4a8723ea11eaf53f2acasize 21568292123version https://git-lfs.github.com/spec/v1oid sha256:681988b5ae14445af3219f465b53dea50590bd755b91aeaee83646401b08d058size 21568708123version https://git-lfs.github.com/spec/v1oid sha256:10e4d21c3ee0a63b2e3d4728a784885611105c796bc400d0f4403cc68e5113dfsize 21568292123version https://git-lfs.github.com/spec/v1oid sha256:f15c93c5e243ff7a55e96dc1dd38a47747164c1ef4ef7a9ba3acc6846fe93e3csize 21568996123version https://git-lfs.github.com/spec/v1oid sha256:88dddad7925e2c455cb8ee7ed23de8743efd51378aa4a16fae11049649841981size 21568292123version https://git-lfs.github.com/spec/v1oid sha256:a2fb8302f98ec47f75e0d0608af30df1bdaebdad870d3412ea4cdf4f9a9a0632size 21569988123version https://git-lfs.github.com/spec/v1oid sha256:0ff0ddf70c1cefe35bae6e06dbcda6e1714a3077255085db50a7184314baccdcsize 21569060123version https://git-lfs.github.com/spec/v1oid sha256:2df43e2bf7490043031395eedfd7c099b420ed4bd752fe2d8ef7b3c60489f952size 21568612123version https://git-lfs.github.com/spec/v1oid sha256:b0475e343fc60202f8ae651fd3a4ff574e31a61563bca4840aacd3f59539307esize 170001027123456789101112131415161718192021222324252627282930313233343536*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830---license: apache-2.0pipeline_tag: image-text-to-textlibrary_name: transformersbase_model: - OpenGVLab/InternVL3_5-1B-MPObase_model_relation: finetunedatasets: - OpenGVLab/MMPR-v1.2language: - multilingualtags: - internvl - custom_code---
# InternVL3_5-1B
[\[📂 GitHub\]](https://github.com/OpenGVLab/InternVL) [\[📜 InternVL 1.0\]](https://huggingface.co/papers/2312.14238) [\[📜 InternVL 1.5\]](https://huggingface.co/papers/2404.16821) [\[📜 InternVL 2.5\]](https://huggingface.co/papers/2412.05271) [\[📜 InternVL2.5-MPO\]](https://huggingface.co/papers/2411.10442) [\[📜 InternVL3\]](https://huggingface.co/papers/2504.10479) [\[📜 InternVL3.5\]](https://huggingface.co/papers/2508.18265)
[\[🆕 Blog\]](https://internvl.github.io/blog/) [\[🗨️ Chat Demo\]](https://chat.intern-ai.org.cn/) [\[🚀 Quick Start\]](#quick-start) [\[📖 Documents\]](https://internvl.readthedocs.io/en/latest/)
<div align="center"> <img width="500" alt="image" src="https://cdn-uploads.huggingface.co/production/uploads/64006c09330a45b03605bba3/zJsd2hqd3EevgXo6fNgC-.png"></div>
## Introduction
We introduce *InternVL3.5*, a new family of open-source multimodal models that significantly advances versatility, reasoning capability, and inference efficiency along the InternVL series. A key innovation is the *Cascade Reinforcement Learning (Cascade RL)* framework, which enhances reasoning through a two-stage process: offline RL for stable convergence and online RL for refined alignment. This coarse-to-fine training strategy leads to substantial improvements on downstream reasoning tasks, e.g., MMMU and MathVista. To optimize efficiency, we propose a *Visual Resolution Router (ViR)* that dynamically adjusts the resolution of visual tokens without compromising performance. Coupled with ViR, our Decoupled *Vision-Language Deployment (DvD)* strategy separates the vision encoder and language model across different GPUs, effectively balancing computational load. These contributions collectively enable InternVL3.5 to achieve up to a +16.0\% gain in overall reasoning performance and a 4.05 \\(\times\\) inference speedup compared to its predecessor, i.e., InternVL3. In addition, InternVL3.5 supports novel capabilities such as GUI interaction and embodied agency. Notably, our largest model, i.e., InternVL3.5-241B-A28B, attains state-of-the-art results among open-source MLLMs across general multimodal, reasoning, text, and agentic tasks—narrowing the performance gap with leading commercial models like GPT-5. All models and code are publicly released.

> Hatched bars represent closed-source commercial models. We report average scores on a set of multimodal general, reasoning, text, and agentic benchmarks: MMBench v1.1 (en), MMStar,BLINK, HallusionBench, AI2D, OCRBench, MMVet, MME-RealWorld (en), MVBench, VideoMME, MMMU, MathVista, MathVision, MathVerse, DynaMath, WeMath, LogicVista, MATH500, AIME24, AIME25, GPQA, MMLU-Pro, GAOKAO, IFEval, SGP-Bench, VSI-Bench, ERQA, SpaCE-10, and OmniSpatial.
See [quick start](#quick-start) for how to use our model.
## InternVL3.5 Family
In the following table, we provide an overview of the InternVL3.5 series.To maintain consistency with earlier generations, we provide two model formats: [the GitHub format](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B), consistent with prior releases, and [the HF format](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B-HF), aligned with the official Transformers standard.
> If you want to convert the checkpoint between these two formats, please refer to the scripts about [custom2hf](https://github.com/OpenGVLab/InternVL/blob/main/internvl_chat/tools/internvl_custom2hf.py) and [hf2custom](https://github.com/OpenGVLab/InternVL/blob/main/internvl_chat/tools/internvl_hf2custom.py).
| Model | #Vision Param | #Language Param | #Total Param | HF Link | ModelScope Link || --------------------- | ------------- | --------------- | ------------ | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- || InternVL3.5-1B | 0.3B | 0.8B | 1.1B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-1B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-1B) || InternVL3.5-2B | 0.3B | 2.0B | 2.3B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-2B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-2B) || InternVL3.5-4B | 0.3B | 4.4B | 4.7B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-4B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-4B) || InternVL3.5-8B | 0.3B | 8.2B | 8.5B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-8B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-8B) || InternVL3.5-14B | 0.3B | 14.8B | 15.1B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-14B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-14B) || InternVL3.5-38B | 5.5B | 32.8B | 38.4B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-38B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-38B) || InternVL3.5-20B-A4B | 0.3B | 20.9B | 21.2B-A4B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-GPT-OSS-20B-A4B-Preview) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-GPT-OSS-20B-A4B-Preview) || InternVL3.5-30B-A3B | 0.3B | 30.5B | 30.8B-A3B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-30B-A3B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-30B-A3B) || InternVL3.5-241B-A28B | 5.5B | 235.1B | 240.7B-A29B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-241B-A28B) |

> We conduct the evaluation with [VLMEvalkit](https://github.com/open-compass/VLMEvalKit). ***To enable the Thinking mode of our model, please set the system prompt to [R1_SYSTEM_PROMPT](https://github.com/open-compass/VLMEvalKit/blob/main/vlmeval/vlm/internvl/internvl_chat.py#L38).*** When enabling Thinking mode, we recommend setting `do_sample=True` and `temperature=0.6` to mitigate undesired repetition.
Our training pipeline comprises four stages: Multimodal Continual Pre-Training (**CPT**), Supervised Fine-Tuning (**SFT**), and Cascade Reinforcement Learning (**CascadeRL**). In CascadeRL, we first fine-tune the model using Mixed Preference Optimization (**MPO**) under an offline RL setting, followed by **GSPO** under an oneline RL setting.For the Flash version of InternVL3.5, we additionally introduce a lightweight training stage, termed Visual Consistency Learning (**ViCO**), which reduces the token cost required to represent an image patch.

Here, we also open-source the model weights after different training stages for potential research usage.***If you're unsure which version to use, please select the one without any suffix, as it has completed the full training pipeline.***
| Model | Training Pipeline | HF Link | ModelScope Link || -------------------------------- | --------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- || InternVL3.5-1B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-1B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-1B-Pretrained) || InternVL3.5-1B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-1B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-1B-Instruct) || InternVL3.5-1B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-1B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-1B-MPO) || InternVL3.5-1B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-1B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-1B) || InternVL3.5-2B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-2B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-2B-Pretrained) || InternVL3.5-2B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-2B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-2B-Instruct) || InternVL3.5-2B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-2B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-2B-MPO) || InternVL3.5-2B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-2B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-2B) || InternVL3.5-4B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-4B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-4B-Pretrained) || InternVL3.5-4B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-4B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-4B-Instruct) || InternVL3.5-4B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-4B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-4B-MPO) || InternVL3.5-4B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-4B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-4B) || InternVL3.5-8B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-8B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-8B-Pretrained) || InternVL3.5-8B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-8B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-8B-Instruct) || InternVL3.5-8B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-8B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-8B-MPO) || InternVL3.5-8B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-8B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-8B) || InternVL3.5-14B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-14B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-14B-Pretrained) || InternVL3.5-14B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-14B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-14B-Instruct) || InternVL3.5-14B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-14B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-14B-MPO) || InternVL3.5-14B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-14B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-14B) || InternVL3.5-30B-A3B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-30B-A3B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-30B-A3B-Pretrained) || InternVL3.5-30B-A3B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-30B-A3B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-30B-A3B-Instruct) || InternVL3.5-30B-A3B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-30B-A3B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-30B-A3B-MPO) || InternVL3.5-30B-A3B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-30B-A3B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-30B-A3B) || InternVL3.5-38B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-38B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-38B-Pretrained) || InternVL3.5-38B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-38B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-38B-Instruct) || InternVL3.5-38B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-38B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-38B-MPO) || InternVL3.5-38B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-38B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-38B) || InternVL3.5-241B-A28B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-241B-A28B-Pretrained) || InternVL3.5-241B-A28B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-241B-A28B-Instruct) || InternVL3.5-241B-A28B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-241B-A28B-MPO) || InternVL3.5-241B-A28B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-241B-A28B) |
The Flash version of our model will be released as soon as possible.
## Model Architecture
`InternVL3.5`:This series of models follow the "ViT–MLP–LLM" paradigm adopted in previous versions of InternVL.We initialize the language model using the Qwen3 series and GPT-OSS, and the vision encoder using InternViT-300M and InternViT-6B.The Dynamic High Resolution strategy introduced in InternVL1.5 is also retained in our design.
`InternVL3.5-Flash`:Compared to InternVL3.5, InternVL3.5-Flash further integrates the *Visual Resolution Router (ViR)*, thus yielding a series of efficient variants friendly suitable for resource-constrained scenarios. Specifically, in InternVL3.5, each image patch is initially represented as 1024 visual tokens for the vision encoder, which are then compressed into 256 tokens via a pixel shuffle module before being passed to the Large Language Model (LLM).In InternVL3.5-Flash, as shown in the Figure below, an additional pixel shuffle module with a higher compression rate is included, enabling the compression of visual tokens down to 64 tokens.For each patch, the patch router determines the appropriate compression rate by assessing its semantic richness, and routes it to the corresponding pixel shuffle module accordingly.Benefiting from this patch-aware compression mechanism, InternVL3.5-Flash is able to reduce the number of visual tokens by 50\% while maintaining nearly 100\% of the performance of InternVL3.5.

## Training and Deployment Strategy
### Pre-Training
During the pre-training stage, we update all model parameters jointly using the combination of large-scale text and multimodal corpora. Specifically, given an arbitrary training sample consisting of a multimodal token sequence \\(\mathbf{x}=\left(x_1, x_2, \ldots, x_L\right)\\), the next token prediction (NTP) loss is calculated on each text token as follows:
$$ \mathcal{L}_{i}=-\log p_\theta\left(x_i \mid x_1, \ldots, x_{i-1}\right),$$
where \\(x_i\\) is the predicted token and prefix tokens in \\(\{x_1, x_2, \ldots, x_{i-1}\}\\) can be either text tokens or image tokens. Notably, for conversation samples, only response tokens are included for the calculation of the loss.Additionally, to mitigate bias toward either longer or shorter responses during training, we adopt the square averaging to re-weight the NTP loss as follows:
$$\mathcal{L}_{i}^{'} = \frac{w_i}{\sum_j w_j} \cdot \mathcal{L}_i, \quad w_i = \frac{1}{N^{0.5}},$$
where \\(N\\) denotes the number of tokens in the training sample on which the loss needs to be calculated. The random JPEG compression is also included to enhance the model's real-world performance.
### Supervised Fine-Tuning
During the SFT phase, we adopt the same objective as in the pre-training stage and use the square-root averaging strategy to calculate the final loss. In this stage, the context window is set to 32K tokens to adapt long-context information.Compared to InternVL3, the SFT stage of InternVL3.5 contains more high-quality and diverse training data derived from three sources:
(1) Instruction-following data from InternVL3, which are reused to preserve broad coverage of vision–language tasks.
(2) Multimodal reasoning data in the "Thinking" mode, which are included to instill long-thinking capabilities in the model. To construct such data, we first use InternVL3-78B to describe the image and then input the description into DeepSeek-R1 to sample rollouts with detailed reasoning processes. Rollouts with an incorrect final answer are filtered out. The questions in these datasets cover various expert domains, such as mathematics and scientific disciplines, thereby strengthening performance on different reasoning tasks.
(3) Capability-expansion datasets, which endow InternVL3.5 with new skills, including GUI-based interaction, embodied interaction, and scalable vect
### Cascade Reinforcement Learning
Cascade RL aims to combine the benefits of offline RL and online RL to progressively facilitate the post-training of MLLMs in an efficient manner.Specifically, we first fine-tune the model using an offline RL algorithm as an efficient warm-up stage to reach a satisfied results, which can guarantee the high-quality rollouts for the latter stage. Subsequently, we employ an online RL algorithm to further refine the output distribution based on rollouts generated by the model itself. Compared to the single offline or online RL stage, our cascaded RL achieves significant performance improvements at a fraction of the GPU time cost.
During the offline RL stage, we employ mixed preference optimization (MPO) to fine-tune the model. Specifically, the training objective of MPO is a combination of preference loss \\(\mathcal{L}_{p}\\), quality loss \\(\mathcal{L}_{q}\\), and generation loss \\(\mathcal{L}_{g}\\), which can be formulated as follows:
$$ \mathcal{L}_{\text{MPO}}= w_{p} \mathcal{L}_{p} + w_{q} \mathcal{L}_{q} + w_{g} \mathcal{L}_{g} ,$$
where \\(w_{*}\\) represents the weight assigned to each loss component.The DPO loss, BCO loss, and LM loss serve as the preference loss, quality loss, and generation loss, respectively.
During the online RL stage, we employ GSPO, without reference model constraints, as our online RL algorithm, which we find more effective in training both dense and mixture-of-experts (MoE) models. Similar to GRPO, the advantage is defined as the normalized reward across responses sampled from the same query.The training objective of GSPO is given by:
$$ \mathcal{L}_{\mathrm{GSPO}}(\theta)=\mathbb{E}_{x \sim \mathcal{D},\left\{y_i\right\}_{i=1}^G \sim \pi_{\theta \text { old }}(\cdot \mid x)}\left[\frac{1}{G} \sum_{i=1}^G \min \left(s_i(\theta) \widehat{A}_i, \operatorname{clip}\left(s_i(\theta), 1-\varepsilon, 1+\varepsilon\right) \widehat{A}_i\right)\right],$$
where the importance sampling ratio is defined as the geometric mean of the per-token ratios.
> Please see [our paper](https://huggingface.co/papers/2508.18265) for more technical and experimental details.
### Visual Consistency Learning
We further include ViCO as an additional training stage to integrate the *visual resolution router (ViR)* into InternVL3.5, thereby reducing the inference cost of InternVL3.5. The obtained efficient version of InternVL3.5 are termed as *InternVL3.5-Flash*. In particular, ViCO comprises two stages:
`Consistency training`:In this stage, the entire model is trained to minimize the divergence between response distributions conditioned on visual tokens with different compression rates.In practice, we introduce an extra reference model, which is frozen and initialized with InternVL3.5.Given a sample, each image patch is represented as either 256 or 64 tokens, and the training objective is defined as follows:
$$\mathcal{L}_\text{ViCO} =\mathbb{E}_{\xi \sim \mathcal{R}} \Bigg[\frac{1}{N} \sum_{i=1}^{N} \mathrm{KL} \Big(\pi_{\theta_{ref}}\left(y_i \mid y_{<i}, I\right) \;\Big\|\;\pi_{\theta_{policy}}\left(y_i \mid y_{<i}, I_\xi\right)\Big)\Bigg],$$
where \\(\mathrm{KL}\) denotes the KL divergence and \(\xi\) denotes the compression rate, which is uniformly sampled from \(\{\frac{1}{4},\frac{1}{16}\}\). The image \(I_\xi\) is represented as 256 tokens when \(\xi=\frac{1}{4}\) and 64 tokens when \(\xi=\frac{1}{16}\). Notably, the reference model always performs inference with \(\xi=\frac{1}{4}\).
`Router training`:This stage aims to train the ViR to select an appropriate trade-off resolution for different inputs.ViR is formulated as a binary classifier and trained using standard cross-entropy loss.To construct the route targets, we first compute the KL divergence between the model outputs conditioned on uncompressed visual tokens (i.e., 256 tokens per patch) and those conditioned on compressed visual tokens (i.e., 64 tokens per patch).During this stage, the main MLLM (ViT, MLP and LLM) is kept frozen, and only the ViR is trained.Specifically, we first compute the loss ratio for each patch:
$$r_i = \frac{\mathcal{L}_\text{ViCO}\big(y_i \mid I_{\frac{1}{16}}\big)}{\mathcal{L}_\text{ViCO}\big(y_i \mid I_{\frac{1}{4}}\big)},$$
which quantifies the relative increase in loss caused by compressing the visual tokens. Based on this ratio, the binary ground-truth label for the patch router is defined as:
$$y_i^\text{router} =\begin{cases}0, & r_i < \tau \; \text{(compression has negligible impact)} \\1, & r_i \ge \tau \; \text{(compression has significant impact)},\end{cases}$$
where \(y_i^{\text{router}}=0\) and \(y_i^{\text{router}}=1\) indicate that the compression rate \(\xi\) is set to \(\tfrac{1}{16}\) and \(\tfrac{1}{4}\), respectively.
> Please see [our paper](https://huggingface.co/papers/2508.18265) for more technical and experimental details.
### Test-Time Scaling
Test-time scaling (TTS) has been empirically demonstrated as an effective approach to enhance the reasoning capabilities of LLMs and MLLMs, particularly for complex tasks necessitating multi-step inference.In this work, we implement a comprehensive test-time scaling approach that simultaneously improves reasoning depth (i.e., deep thinking) and breadth (i.e., parallel thinking).
`Deep Thinking`: By activating the Thinking mode, we guide the model to deliberately engage in step-by-step reasoning (i.e., decomposing complex problems into logical steps and validating intermediate conclusions) prior to generating the final answer. This approach systematically improves the logical structure of solutions for complex problems, particularly those requiring multi-step inference, and enhances reasoning depth.
`Parallel Thinking`: Following InternVL3, for reasoning tasks, we adopt the Best-of-N (BoN) strategy by employing [VisualPRM-v1.1](https://huggingface.co/OpenGVLab/VisualPRM-8B-v1_1) as the critic model to select the optimal response from multiple reasoning candidates.This approach improves reasoning breadth.
> Notably, unless otherwise specified, the experimental results reported in our paper are obtained without applying TTS. Thus far, we have only applied TTS to reasoning benchmarks, since we found that the model already exhibits strong perception and understanding capabilities, and initiating TTS yields no significant improvement.
### Decoupled Vision-Language Deployment
In multimodal inference, the vision encoder and language model have distinct computational characteristics. The vision encoder that transforms images into semantic features is highly parallelizable and does not rely on long-term history state. In contrast, the language model adopts the inference in an autoregressive manner, which requires previous states to compute the next one. This sequential property makes the language part more sensitive to memory bandwidth and latency. When MLLMs are deployed online at scale, the vision and language models often block each other, thus incurring additional inference cost. This effect becomes more pronounced with larger vision models or higher-resolution images.

As shown in the Figure above, we propose decoupled vision-language deployment (DvD) to address this issue by separating vision and language processing, with a particular focus on optimizing the prefilling stage. The vision subsystem batches and processes images to produce compact feature embeddings, which are then transmitted to the language subsystem for fusion with the text context prior to decoding. This separation alleviates blocking and brings multimodal prefilling performance closer to that of pure language models.In our system implementation, the ViT and MLP (and ViR for InternVL3.5-Flash) are deployed on the vision server, while the language server executes only the LLM. The communication is unidirectional, transmitting BF16 visual features over TCP, with RDMA optionally employed to achieve higher transmission speed. Vision processing, feature transmission, and language processing are organized into an asynchronous three-stage pipeline, enabling overlapped execution and minimizing pipeline stalls.
DvD increases GPU utilization and processing efficiency on the vision side, while enabling the language server to focus exclusively on the LLM’s prefilling and decoding without being blocked by vision computation. This design leads to improved throughput and responsiveness. Moreover, the architecture supports independent hardware cost optimization for the vision and language modules, and facilitates the seamless integration of new modules without requiring modifications to the language server deployment.
## Evaluation on Multimodal Capability
### Multimodal Reasoning and Mathematics

### OCR, Chart, and Document Understanding

### Multi-Image Understanding & Real-World Comprehension

### Comprehensive Multimodal Understanding & Multimodal Hallucination Evaluation

### Visual Grounding

### Multimodal Multilingual Understanding

### Video Understanding

### GUI Tasks

### Embodied Tasks

### SVG Tasks


## Evaluation on Language Capability

## Ablation Study
### Cascade Reinforcement Learning


### Decoupled Vision-Language Deployment

## Quick Start
We provide an example code to run `InternVL3.5-8B` using `transformers`. Please note that our models with up to 30B parameters can be deployed on a single A100 GPU, while the 38B model requires two A100 GPUs and the 235B model requires eight A100 GPUs.
> In most cases, both [LMDeploy](https://github.com/InternLM/lmdeploy) and [vLLM](https://github.com/vllm-project/vllm) can be used for model deployment. However, for InternVL3.5-20B-A4B, we recommend using vLLM since lmdeploy has not yet supported GPT-OSS.
> Please use transformers>=4.52.1 to ensure the model works normally. For the 20B version of our model, transformers>=4.55.0 is required.
### Model Loading
#### 16-bit (bf16 / fp16)
```pythonimport torchfrom transformers import AutoTokenizer, AutoModelpath = "OpenGVLab/InternVL3_5-8B"model = AutoModel.from_pretrained( path, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True, use_flash_attn=True, trust_remote_code=True).eval().cuda()```
#### BNB 8-bit Quantization
```pythonimport torchfrom transformers import AutoTokenizer, AutoModelpath = "OpenGVLab/InternVL3_5-8B"model = AutoModel.from_pretrained( path, torch_dtype=torch.bfloat16, load_in_8bit=True, low_cpu_mem_usage=True, use_flash_attn=True, trust_remote_code=True).eval()```
#### Multiple GPUs
```pythonimport mathimport torchfrom transformers import AutoTokenizer, AutoModel
path = "OpenGVLab/InternVL3_5-8B"model = AutoModel.from_pretrained( path, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True, use_flash_attn=True, trust_remote_code=True, device_map="auto").eval()```
### Thinking Mode
To enable thinking mode, please set the system prompt to our Thinking System Prompt. When enabling Thinking mode, we recommend setting `do_sample=True` and `temperature=0.6` to mitigate undesired repetition.
```pythonR1_SYSTEM_PROMPT = """You are an AI assistant that rigorously follows this response protocol:
1. First, conduct a detailed analysis of the question. Consider different angles, potential solutions, and reason through the problem step-by-step. Enclose this entire thinking process within <think> and </think> tags.
2. After the thinking section, provide a clear, concise, and direct answer to the user's question. Separate the answer from the think section with a newline.
Ensure that the thinking process is thorough but remains focused on the query. The final answer should be standalone and not reference the thinking section.""".strip()
model.system_message = R1_SYSTEMP_PROMPT```
### Inference with Transformers
```pythonimport mathimport numpy as npimport torchimport torchvision.transforms as Tfrom decord import VideoReader, cpufrom PIL import Imagefrom torchvision.transforms.functional import InterpolationModefrom transformers import AutoModel, AutoTokenizer
IMAGENET_MEAN = (0.485, 0.456, 0.406)IMAGENET_STD = (0.229, 0.224, 0.225)
def build_transform(input_size): MEAN, STD = IMAGENET_MEAN, IMAGENET_STD transform = T.Compose([ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img), T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC), T.ToTensor(), T.Normalize(mean=MEAN, std=STD) ]) return transform
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size): best_ratio_diff = float('inf') best_ratio = (1, 1) area = width * height for ratio in target_ratios: target_aspect_ratio = ratio[0] / ratio[1] ratio_diff = abs(aspect_ratio - target_aspect_ratio) if ratio_diff < best_ratio_diff: best_ratio_diff = ratio_diff best_ratio = ratio elif ratio_diff == best_ratio_diff: if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]: best_ratio = ratio return best_ratio
def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False): orig_width, orig_height = image.size aspect_ratio = orig_width / orig_height
# calculate the existing image aspect ratio target_ratios = set( (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if i * j <= max_num and i * j >= min_num) target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
# find the closest aspect ratio to the target target_aspect_ratio = find_closest_aspect_ratio( aspect_ratio, target_ratios, orig_width, orig_height, image_size)
# calculate the target width and height target_width = image_size * target_aspect_ratio[0] target_height = image_size * target_aspect_ratio[1] blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
# resize the image resized_img = image.resize((target_width, target_height)) processed_images = [] for i in range(blocks): box = ( (i % (target_width // image_size)) * image_size, (i // (target_width // image_size)) * image_size, ((i % (target_width // image_size)) + 1) * image_size, ((i // (target_width // image_size)) + 1) * image_size ) # split the image split_img = resized_img.crop(box) processed_images.append(split_img) assert len(processed_images) == blocks if use_thumbnail and len(processed_images) != 1: thumbnail_img = image.resize((image_size, image_size)) processed_images.append(thumbnail_img) return processed_images
def load_image(image_file, input_size=448, max_num=12): image = Image.open(image_file).convert('RGB') transform = build_transform(input_size=input_size) images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num) pixel_values = [transform(image) for image in images] pixel_values = torch.stack(pixel_values) return pixel_values
path = 'OpenGVLab/InternVL3_5-8B'model = AutoModel.from_pretrained( path, torch_dtype=torch.bfloat16, load_in_8bit=False, low_cpu_mem_usage=True, use_flash_attn=True, trust_remote_code=True, device_map="auto").eval()tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
# set the max number of tiles in `max_num`pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()generation_config = dict(max_new_tokens=1024, do_sample=True)
# pure-text conversation (纯文本对话)question = 'Hello, who are you?'response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)print(f'User: {question}\nAssistant: {response}')
question = 'Can you tell me a story?'response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)print(f'User: {question}\nAssistant: {response}')
# single-image single-round conversation (单图单轮对话)question = '<image>\nPlease describe the image shortly.'response = model.chat(tokenizer, pixel_values, question, generation_config)print(f'User: {question}\nAssistant: {response}')
# single-image multi-round conversation (单图多轮对话)question = '<image>\nPlease describe the image in detail.'response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)print(f'User: {question}\nAssistant: {response}')
question = 'Please write a poem according to the image.'response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)print(f'User: {question}\nAssistant: {response}')
# multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
question = '<image>\nDescribe the two images in detail.'response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)print(f'User: {question}\nAssistant: {response}')
question = 'What are the similarities and differences between these two images.'response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)print(f'User: {question}\nAssistant: {response}')
# multi-image multi-round conversation, separate images (多图多轮对话,独立图像)pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'response, history = model.chat(tokenizer, pixel_values, question, generation_config, num_patches_list=num_patches_list, history=None, return_history=True)print(f'User: {question}\nAssistant: {response}')
question = 'What are the similarities and differences between these two images.'response, history = model.chat(tokenizer, pixel_values, question, generation_config, num_patches_list=num_patches_list, history=history, return_history=True)print(f'User: {question}\nAssistant: {response}')
# batch inference, single image per sample (单图批处理)pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)responses = model.batch_chat(tokenizer, pixel_values, num_patches_list=num_patches_list, questions=questions, generation_config=generation_config)for question, response in zip(questions, responses): print(f'User: {question}\nAssistant: {response}')
# video multi-round conversation (视频多轮对话)def get_index(bound, fps, max_frame, first_idx=0, num_segments=32): if bound: start, end = bound[0], bound[1] else: start, end = -100000, 100000 start_idx = max(first_idx, round(start * fps)) end_idx = min(round(end * fps), max_frame) seg_size = float(end_idx - start_idx) / num_segments frame_indices = np.array([ int(start_idx + (seg_size / 2) + np.round(seg_size * idx)) for idx in range(num_segments) ]) return frame_indices
def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32): vr = VideoReader(video_path, ctx=cpu(0), num_threads=1) max_frame = len(vr) - 1 fps = float(vr.get_avg_fps())
pixel_values_list, num_patches_list = [], [] transform = build_transform(input_size=input_size) frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments) for frame_index in frame_indices: img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB') img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num) pixel_values = [transform(tile) for tile in img] pixel_values = torch.stack(pixel_values) num_patches_list.append(pixel_values.shape[0]) pixel_values_list.append(pixel_values) pixel_values = torch.cat(pixel_values_list) return pixel_values, num_patches_list
video_path = './examples/red-panda.mp4'pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)pixel_values = pixel_values.to(torch.bfloat16).cuda()video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])question = video_prefix + 'What is the red panda doing?'# Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}response, history = model.chat(tokenizer, pixel_values, question, generation_config, num_patches_list=num_patches_list, history=None, return_history=True)print(f'User: {question}\nAssistant: {response}')
question = 'Describe this video in detail.'response, history = model.chat(tokenizer, pixel_values, question, generation_config, num_patches_list=num_patches_list, history=history, return_history=True)print(f'User: {question}\nAssistant: {response}')```
#### Streaming Output
Besides this method, you can also use the following code to get streamed output.
```pythonfrom transformers import TextIteratorStreamerfrom threading import Thread
# Initialize the streamerstreamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)# Define the generation configurationgeneration_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)# Start the model chat in a separate threadthread = Thread(target=model.chat, kwargs=dict( tokenizer=tokenizer, pixel_values=pixel_values, question=question, history=None, return_history=False, generation_config=generation_config,))thread.start()
# Initialize an empty string to store the generated textgenerated_text = ''# Loop through the streamer to get the new text as it is generatedfor new_text in streamer: if new_text == model.conv_template.sep: break generated_text += new_text print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line```
## Finetune
Many repositories now support fine-tuning of the InternVL series models, including [InternVL](https://github.com/OpenGVLab/InternVL), [SWIFT](https://github.com/modelscope/ms-swift), [XTuner](https://github.com/InternLM/xtuner), and others. Please refer to their documentation for more details on fine-tuning.
## Deployment
### LMDeploy
LMDeploy is a toolkit for compressing, deploying, and serving LLMs & VLMs.
```shpip install lmdeploy>=0.9.1```
LMDeploy abstracts the complex inference process of multi-modal Vision-Language Models (VLM) into an easy-to-use pipeline, similar to the Large Language Model (LLM) inference pipeline.
#### A 'Hello, world' Example
```pythonfrom lmdeploy import pipeline, PytorchEngineConfigfrom lmdeploy.vl import load_image
image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
# Please set tp=2 for the 38B version and tp=8 for the 241B-A28B version.model = 'OpenGVLab/InternVL3_5-8B'pipe = pipeline(model, backend_config=PytorchEngineConfig(session_len=32768, tp=1))
response = pipe(('describe this image', image))print(response.text)```
#### Multi-images Inference
When dealing with multiple images, you can put them all in one list. Keep in mind that multiple images will lead to a higher number of input tokens, and as a result, the size of the context window typically needs to be increased.
```pythonfrom lmdeploy import pipeline, PytorchEngineConfigfrom lmdeploy.vl import load_imagefrom lmdeploy.vl.constants import IMAGE_TOKEN
# Please set tp=2 for the 38B version and tp=8 for the 241B-A28B version.model = 'OpenGVLab/InternVL3_5-8B'pipe = pipeline(model, backend_config=PytorchEngineConfig(session_len=32768, tp=1))
image_urls=[ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg', 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg']
images = [load_image(img_url) for img_url in image_urls]# Numbering images improves multi-image conversationsresponse = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))print(response.text)```
#### Batch Prompts Inference
Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
```pythonfrom lmdeploy import pipeline, PytorchEngineConfigfrom lmdeploy.vl import load_image
# Please set tp=2 for the 38B version and tp=8 for the 241B-A28B version.model = 'OpenGVLab/InternVL3_5-8B'pipe = pipeline(model, backend_config=PytorchEngineConfig(session_len=32768, tp=1))
image_urls=[ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg", "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"]prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]response = pipe(prompts)print(response)```
#### Multi-turn Conversation
There are two ways to do the multi-turn conversations with the pipeline. One is to construct messages according to the format of OpenAI and use above introduced method, the other is to use the `pipeline.chat` interface.
```pythonfrom lmdeploy import pipeline, PytorchEngineConfig, GenerationConfigfrom lmdeploy.vl import load_image
# Please set tp=2 for the 38B version and tp=8 for the 241B-A28B version.model = 'OpenGVLab/InternVL3_5-8B'pipe = pipeline(model, backend_config=PytorchEngineConfig(session_len=32768, tp=1))
image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')gen_config = GenerationConfig(top_k=50, top_p=0.95, temperature=0.6, max_new_tokens=8192)sess = pipe.chat(('describe this image', image), gen_config=gen_config)print(sess.response.text)sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)print(sess.response.text)```
#### Service
LMDeploy's `api_server` enables models to be easily packed into services with a single command. The provided RESTful APIs are compatible with OpenAI's interfaces. Below are an example of service startup:
```shelllmdeploy serve api_server OpenGVLab/InternVL3_5-8B --server-port 23333 --tp 1 --backend pytorch```
To use the OpenAI-style interface, you need to install OpenAI:
```shellpip install openai```
Then, use the code below to make the API call:
```pythonfrom openai import OpenAI
client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')model_name = client.models.list().data[0].idresponse = client.chat.completions.create( model=model_name, messages=[{ 'role': 'user', 'content': [{ 'type': 'text', 'text': 'describe this image', }, { 'type': 'image_url', 'image_url': { 'url': 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg', }, }], }], temperature=0.8, top_p=0.8)print(response)```
## License
This project is released under the apache-2.0 License. This project uses the pre-trained Qwen3 as a component, which is licensed under the apache-2.0 License.
## Citation
If you find this project useful in your research, please consider citing:
```BibTeX@article{chen2024expanding, title={Expanding Performance Boundaries of Open-Source Multimodal Models with Model, Data, and Test-Time Scaling}, author={Chen, Zhe and Wang, Weiyun and Cao, Yue and Liu, Yangzhou and Gao, Zhangwei and Cui, Erfei and Zhu, Jinguo and Ye, Shenglong and Tian, Hao and Liu, Zhaoyang and others}, journal={arXiv preprint arXiv:2412.05271}, year={2024}}@article{wang2024mpo, title={Enhancing the Reasoning Ability of Multimodal Large Language Models via Mixed Preference Optimization}, author={Wang, Weiyun and Chen, Zhe and Wang, Wenhai and Cao, Yue and Liu, Yangzhou and Gao, Zhangwei and Zhu, Jinguo and Zhu, Xizhou and Lu, Lewei and Qiao, Yu and Dai, Jifeng}, journal={arXiv preprint arXiv:2411.10442}, year={2024}}@article{chen2024far, title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites}, author={Chen, Zhe and Wang, Weiyun and Tian, Hao and Ye, Shenglong and Gao, Zhangwei and Cui, Erfei and Tong, Wenwen and Hu, Kongzhi and Luo, Jiapeng and Ma, Zheng and others}, journal={arXiv preprint arXiv:2404.16821}, year={2024}}@inproceedings{chen2024internvl, title={Internvl: Scaling up vision foundation models and aligning for generic visual-linguistic tasks}, author={Chen, Zhe and Wu, Jiannan and Wang, Wenhai and Su, Weijie and Chen, Guo and Xing, Sen and Zhong, Muyan and Zhang, Qinglong and Zhu, Xizhou and Lu, Lewei and others}, booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, pages={24185--24198}, year={2024}}```.gitattributesAdded+44
.gitignoreAdded+14
README.mdAdded+147
assets/demo_1.pngAdded

Large File Pointer Details
- SHA256: 512b585d3edf0f2a90ecdec6d98508d4a551057c2f125f5f1ac61d75164f637c
- Pointer size: 131 Bytes
- Size of remote file: 488 kB
assets/demo_2.pngAdded

Large File Pointer Details
- SHA256: 30ff98a4537cc4329da2646e577469e0bc1ca171b7aa0e0c0aa96539a027e217
- Pointer size: 131 Bytes
- Size of remote file: 979 kB
config.jsonAdded+3
examples/image_0.jpgAdded

Large File Pointer Details
- SHA256: c587294b3bf637dacbb3c96324c127187a2f242c94f639633a0d8a2775a9a399
- Pointer size: 130 Bytes
- Size of remote file: 78.1 kB
examples/image_1.jpgAdded

Large File Pointer Details
- SHA256: 08487494b8dc08d44bc36491adf3ab89ff30d13a3122da86f3cd67cad89eeee8
- Pointer size: 131 Bytes
- Size of remote file: 126 kB
examples/image_2.pngAdded

Large File Pointer Details
- SHA256: 622ae2d01ff4467fa69a7888728d776650117a0f4887e96ba0fb9a8a6d77b3c3
- Pointer size: 131 Bytes
- Size of remote file: 355 kB
examples/image_3.pngAdded

Large File Pointer Details
- SHA256: 729e80e77d8611778859d2f232cb7f2a8fda04ed67dd8dcc3e7cd7a657367402
- Pointer size: 131 Bytes
- Size of remote file: 394 kB
examples/laorenshuaidao.mp4Added+3
examples/red-panda.mp4Added+3
examples/tuboshu.mp4Added+3
gradio_demo.pyAdded+389
infer_axmodel.pyAdded+183
infer_torch.pyAdded+212
internvl3-5_axmodel/model.embed_tokens.weight.bfloat16.binAdded+3
internvl3-5_axmodel/model.embed_tokens.weight.float32.binAdded+3
internvl3-5_axmodel/model.embed_tokens.weight.npyAdded+3
internvl3-5_axmodel/qwen3_p128_l0_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l10_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l11_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l12_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l13_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l14_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l15_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l16_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l17_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l18_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l19_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l1_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l20_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l21_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l22_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l23_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l24_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l25_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l26_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l27_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l2_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l3_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l4_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l5_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l6_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l7_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l8_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_p128_l9_together.axmodelAdded+3
internvl3-5_axmodel/qwen3_post.axmodelAdded+3
internvl3-5_tokenizer/.gitattributesAdded+36
internvl3-5_tokenizer/README.mdAdded+830