diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..e6db1df0c00110bc0a61a75445ddc6c192230652 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,44 @@ +*.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 -text +saved_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 -text +main_api_ax650 filter=lfs diff=lfs merge=lfs -text +main_api_axcl_x86 filter=lfs diff=lfs merge=lfs -text +main_ax650 filter=lfs diff=lfs merge=lfs -text +main_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 -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..2c9cbe2556be7837c0c0d841bc780aa5c3bcd612 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +__pycache__ +*.tar +build-output/ +*.onnx +*.pth +*.pkl +*.bin +*.npy +*.axmodel +*_axmodel/ +*.safetensors +compiled* +*tmp/ + diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dafb93a33eab065dad7aa2835f5aecee8998cf0d --- /dev/null +++ b/README.md @@ -0,0 +1,147 @@ +--- +library_name: transformers +license: bsd-3-clause +base_model: +- OpenGVLab/InternVL3_5-1B +tags: +- InternVL3 +- InternVL3_5-1B +- Int8 +- VLM +pipeline_tag: image-text-to-text +language: +- 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: + +![demo_1](assets/demo_1.png) + +Image understanding: + +![demo_2](assets/demo_2.png) + +--- + +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-dirty +Model loaded successfully! +slice_indices: [0] +Slice prefill done: 0 +answer >> 函数 \( 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 +``` + +![image_0.jpg](examples/image_0.jpg) + +output: + +```bash +[INFO] Model type: 2 (triple core) +[INFO] Compiler version: 5.1-dirty 0fdbfe15-dirty +Model loaded successfully! +slice_indices: [0, 1, 2] +Slice prefill done: 0 +Slice prefill done: 1 +Slice prefill done: 2 +answer >> 这是一张红熊猫的照片。红熊猫是一种红棕色的哺乳动物,通常生活在亚洲的森林中。它们以捕食昆虫和小型无脊椎动物为生。图片中,红熊猫正坐在一个木制的平台上,背景是绿色的树木和植被,显得非常自然和生动。红熊猫的表情看起来很友好,似乎在观察或等待什么。 +``` diff --git a/assets/demo_1.png b/assets/demo_1.png new file mode 100644 index 0000000000000000000000000000000000000000..d7b265c50c81e60e73b8575a658bb3fc3564eda9 --- /dev/null +++ b/assets/demo_1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:512b585d3edf0f2a90ecdec6d98508d4a551057c2f125f5f1ac61d75164f637c +size 487777 diff --git a/assets/demo_2.png b/assets/demo_2.png new file mode 100644 index 0000000000000000000000000000000000000000..c6c743cdf647a707ee35be022ad5c980d615f7e5 --- /dev/null +++ b/assets/demo_2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30ff98a4537cc4329da2646e577469e0bc1ca171b7aa0e0c0aa96539a027e217 +size 979184 diff --git a/config.json b/config.json new file mode 100644 index 0000000000000000000000000000000000000000..703a3acaee2bfaf35b2200b37bbf8fd90e446929 --- /dev/null +++ b/config.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e960e7c7b8924496695fb1e1676f969d6243afd404e21c16e4287d39f0756da5 +size 3874 diff --git a/examples/image_0.jpg b/examples/image_0.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6b74a0e82a8022c54e9dbd5b95127ef5f945be64 --- /dev/null +++ b/examples/image_0.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c587294b3bf637dacbb3c96324c127187a2f242c94f639633a0d8a2775a9a399 +size 78073 diff --git a/examples/image_1.jpg b/examples/image_1.jpg new file mode 100644 index 0000000000000000000000000000000000000000..09af6e4e6aa5656cd6d6c545780be523d752e3ca --- /dev/null +++ b/examples/image_1.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08487494b8dc08d44bc36491adf3ab89ff30d13a3122da86f3cd67cad89eeee8 +size 125656 diff --git a/examples/image_2.png b/examples/image_2.png new file mode 100644 index 0000000000000000000000000000000000000000..97e4ed3533707c045a4dd76a50fa66125acd8a2c --- /dev/null +++ b/examples/image_2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:622ae2d01ff4467fa69a7888728d776650117a0f4887e96ba0fb9a8a6d77b3c3 +size 355241 diff --git a/examples/image_3.png b/examples/image_3.png new file mode 100644 index 0000000000000000000000000000000000000000..670a71e00b92ee8ede95e1463239d9285bd1c533 --- /dev/null +++ b/examples/image_3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:729e80e77d8611778859d2f232cb7f2a8fda04ed67dd8dcc3e7cd7a657367402 +size 394457 diff --git a/examples/laorenshuaidao.mp4 b/examples/laorenshuaidao.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..c62d3d1e8e7b9c84caea7d64c4703fe4bf99a9bd --- /dev/null +++ b/examples/laorenshuaidao.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f5c00b37b23af3d01d133da880eb7f6e50d4af608e3575784be7063eb137011 +size 2704112 diff --git a/examples/red-panda.mp4 b/examples/red-panda.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..28ff3b1291a2cb3525220a86a2b2b17156735848 --- /dev/null +++ b/examples/red-panda.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d921c07bb97224d65a37801541d246067f0d506f08723ffa1ad85c217907ccb8 +size 1867237 diff --git a/examples/tuboshu.mp4 b/examples/tuboshu.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..847e9d17a6705ead6a2a1b427a79d0bdf8f1bd12 --- /dev/null +++ b/examples/tuboshu.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ced4d95877b9a7f8b48f79bdfe4287eff8837f20348daec2f2e2987459ec1712 +size 5952043 diff --git a/gradio_demo.py b/gradio_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..28e2c9032447b6ebf00843489e297f9092617cf3 --- /dev/null +++ b/gradio_demo.py @@ -0,0 +1,389 @@ +import argparse +import os +import time +from typing import Any, Dict, List, Optional, Generator, Tuple + +import gradio as gr +import numpy as np +import torch +import torchvision.transforms as T +from ml_dtypes import bfloat16 +from PIL import Image +from torchvision.transforms.functional import InterpolationMode +from transformers import AutoConfig, AutoTokenizer + +from utils.infer_func import InferManager +from 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_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_CONTEXT_REPEAT + "" + 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="
TTFT -- ms  |  Decode -- ms/token  |  Tokens --
"), 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"
TTFT {ttft_disp} ms  |  Decode {decode_disp} ms/token  |  Tokens {tok_disp}
" + 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("""""") + 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("
TTFT -- ms  |  Decode -- ms/token  |  Tokens --
", 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="
TTFT -- ms  |  Decode -- ms/token  |  Tokens --
"), 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() diff --git a/infer_axmodel.py b/infer_axmodel.py new file mode 100644 index 0000000000000000000000000000000000000000..75233a68441456b9bd7de2b5a6e7399d412f9724 --- /dev/null +++ b/infer_axmodel.py @@ -0,0 +1,183 @@ +from transformers import AutoProcessor, AutoModelForImageTextToText +import torch +import onnx +import onnxruntime as ort +import numpy as np +import os +from tqdm import tqdm +from transformers import AutoConfig, AutoTokenizer +from typing import List, Tuple +from axengine import InferenceSession +from ml_dtypes import bfloat16 +from utils.infer_func import InferManager +import argparse +from PIL import Image +import torchvision.transforms as T +from 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" + "" * 256 + "\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() # 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") \ No newline at end of file diff --git a/infer_torch.py b/infer_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..1f718b6525fff55d7b40ddc968729e3e623742f6 --- /dev/null +++ b/infer_torch.py @@ -0,0 +1,212 @@ +import math +import numpy as np +import torch +import torchvision.transforms as T +from decord import VideoReader, cpu +from PIL import Image +from torchvision.transforms.functional import InterpolationMode +from 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 = '\n请你描述这幅图的内容.' +response = model.chat(tokenizer, pixel_values, question, generation_config) +print(f'User: {question}\nAssistant: {response}') + +# # single-image multi-round conversation (单图多轮对话) +# question = '\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 = '\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: \nImage-2: \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 = ['\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}: \n' for i in range(len(num_patches_list))]) +# question = video_prefix + 'What is the red panda doing?' +# # Frame1: \nFrame2: \n...\nFrame8: \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}') diff --git a/internvl3-5_axmodel/model.embed_tokens.weight.bfloat16.bin b/internvl3-5_axmodel/model.embed_tokens.weight.bfloat16.bin new file mode 100644 index 0000000000000000000000000000000000000000..ff68cfc6e311f6bd2619d21687e7b6fa02ad395e --- /dev/null +++ b/internvl3-5_axmodel/model.embed_tokens.weight.bfloat16.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9458f8d6cac0fb032e0d9aa5e237148a2ee2e6f9c98ebf7584b065e174127009 +size 311164928 diff --git a/internvl3-5_axmodel/model.embed_tokens.weight.float32.bin b/internvl3-5_axmodel/model.embed_tokens.weight.float32.bin new file mode 100644 index 0000000000000000000000000000000000000000..ab6c9fc5137d6dd29ccf595ee6b996558c7f971b --- /dev/null +++ b/internvl3-5_axmodel/model.embed_tokens.weight.float32.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e69f2b742ddc9d789d16f46073fbe8fdfce77222958071fabf4ff708af07bf23 +size 622329856 diff --git a/internvl3-5_axmodel/model.embed_tokens.weight.npy b/internvl3-5_axmodel/model.embed_tokens.weight.npy new file mode 100644 index 0000000000000000000000000000000000000000..3660027a3d7e54534aeb0ba345c7dd7e4bc101bc --- /dev/null +++ b/internvl3-5_axmodel/model.embed_tokens.weight.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0e826d74d8269b0085d3fdd397e7fa6303ec26719c76f4d5b1d029fab63fcf50 +size 622329984 diff --git a/internvl3-5_axmodel/qwen3_p128_l0_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l0_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..6d6aa294a270f1bc7e0719e49c484f6ef693b279 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l0_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f12d7e947b42e933d6c3119e08d6be0ecb703df7746839cb91a0452d12c490f0 +size 21568292 diff --git a/internvl3-5_axmodel/qwen3_p128_l10_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l10_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..5424bb093388f186638611198417cea4e16ff9df --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l10_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:452cc345d0b182b95f3e961ac9faa1767563f8324fc3d3ed3372f5b63851059b +size 21569348 diff --git a/internvl3-5_axmodel/qwen3_p128_l11_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l11_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..8f21b83fe00ad4df51f7b72b69a6546db33ad01e --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l11_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9f031d1f7e7713d4f0aee4a5fc1a3beffd4593eae922e81946537eca946b04f +size 21568292 diff --git a/internvl3-5_axmodel/qwen3_p128_l12_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l12_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..b5a6c06093b253014757b1bc809c317da11201a5 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l12_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3295106128b7d41ae737274abc58a9b9e49fc1d56df904eb8b44d08b2a13462b +size 21569220 diff --git a/internvl3-5_axmodel/qwen3_p128_l13_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l13_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..31792de8a5f0e8a55bbe6b08dc1b0323282fc2fe --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l13_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b192de65f95a19271ddcf91eca383c782ecd23fb6be2fdb47369ec76d480e21 +size 21569156 diff --git a/internvl3-5_axmodel/qwen3_p128_l14_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l14_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..7ceb74fb0599b277969e83063a843dd684c6612b --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l14_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2cd05f0f6d2b2f6b07c74cece9dfd09a86a5e2a0d1b941b6a01baf31a19edc53 +size 21568292 diff --git a/internvl3-5_axmodel/qwen3_p128_l15_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l15_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..431fff961b12daefd240485d1823d898d1b67cbd --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l15_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:205d2b186e641bd8efb5cbcba1422d7f47384fc2e308ea791f79e0cffb002d48 +size 21568836 diff --git a/internvl3-5_axmodel/qwen3_p128_l16_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l16_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..d596e18d66b057223f8b1dc8148d61b40a35b21a --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l16_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ab96615046ebf359d86fbab9c45af036fb79bcd8e4bbf2d9cab63fef8b0ef47 +size 21568292 diff --git a/internvl3-5_axmodel/qwen3_p128_l17_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l17_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..475bc78830b118137e1ed12ea62bdd65e6d26fc1 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l17_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01b2569ba99a274fee59ef56ea4ba0e4109971d196240b254a68e4e0f0808ac2 +size 21568292 diff --git a/internvl3-5_axmodel/qwen3_p128_l18_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l18_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..f9d7b754cb807beda1a0bb478e6253403c9fbb7c --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l18_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6eb521e5c3e03f3b96b6370362234e741910cf82c038984081e9ab95a101c31d +size 21568900 diff --git a/internvl3-5_axmodel/qwen3_p128_l19_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l19_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..611448d9a7c269b7c4dbe2db99467275dfecbda5 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l19_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:821a3937c506eaa268440ee116961ef2ceb17b5362661d3c9f41997a7aacf54f +size 21568740 diff --git a/internvl3-5_axmodel/qwen3_p128_l1_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l1_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..b940f17bb738064aceb93715915dd52700384aa7 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l1_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ba82686a72bb26759fbf96c7544277d5547ec23634f4128579bd53464072432 +size 21568932 diff --git a/internvl3-5_axmodel/qwen3_p128_l20_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l20_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..f86a62b553e794939c6ee773bb91225f621ebd2a --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l20_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e70045401bd0c6748558ec0374d11cb381644109b687c0358fb8cec5e88de1c +size 21568292 diff --git a/internvl3-5_axmodel/qwen3_p128_l21_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l21_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..40620dc27170585cdb90b4431ae956cce0eaf71c --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l21_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:35ecb18c9bd8d79fe019df779b5f7212f0af1b742adbd69b9968f9e93ec83a83 +size 21568772 diff --git a/internvl3-5_axmodel/qwen3_p128_l22_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l22_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..c5dbb908f190fedc8af11495a365f2a94ca7bb22 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l22_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c5037445038d24a9a44c6defc22638f53ef9875ca62e9ea836077d1518c28d8d +size 21568964 diff --git a/internvl3-5_axmodel/qwen3_p128_l23_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l23_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..b768b139c989d3ad41d6f0130babddf3e8c3edb8 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l23_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:510b76060ef414a7100989e631d6d8336ebf5573467eceb9cf5ad0641df15119 +size 21568644 diff --git a/internvl3-5_axmodel/qwen3_p128_l24_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l24_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..250283a14d342b880361a3d1a8faab1e0c3d2fcb --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l24_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87b6fed1cb82fee89097d326ddfd414e41f0d9bdc27087b630dc678235085a4c +size 21569508 diff --git a/internvl3-5_axmodel/qwen3_p128_l25_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l25_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..f735fe2e80557363b30766ed2af0ed7c27127585 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l25_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:86f1c7b43867ca7c38b942d78b81eed377e61123c3ec1b954bc309c71793f4aa +size 21568964 diff --git a/internvl3-5_axmodel/qwen3_p128_l26_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l26_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..3d167a06a7f86b9bad1b4a8e5240c31b8d2eba1e --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l26_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c7726bb67ea16ba081e73b9982c464cbd7317de09b7c1e34c58072b7a55a1cb8 +size 21568292 diff --git a/internvl3-5_axmodel/qwen3_p128_l27_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l27_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..959ae24ba9ee24d699b5d31c638d2b222804e4c4 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l27_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa0888376b5c59ee87687961078bce26e9dc016a8207838659dabbaa400ce4f3 +size 21570244 diff --git a/internvl3-5_axmodel/qwen3_p128_l2_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l2_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..0a66583f42e8a2ffec6c213a2ca64f10233e9dd6 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l2_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59ed31ea8c87f7ea9d4e31b4911ad4be22d3b917b9ce4a8723ea11eaf53f2aca +size 21568292 diff --git a/internvl3-5_axmodel/qwen3_p128_l3_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l3_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..a328de25529e6990a1c55d97b53eeb5bc99b80f5 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l3_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:681988b5ae14445af3219f465b53dea50590bd755b91aeaee83646401b08d058 +size 21568708 diff --git a/internvl3-5_axmodel/qwen3_p128_l4_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l4_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..254a3f28b3161fd2be0f4fab149e2e16e99b7c48 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l4_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10e4d21c3ee0a63b2e3d4728a784885611105c796bc400d0f4403cc68e5113df +size 21568292 diff --git a/internvl3-5_axmodel/qwen3_p128_l5_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l5_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..a0b956266567cdc4af3553403b53fb50a20ffde0 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l5_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f15c93c5e243ff7a55e96dc1dd38a47747164c1ef4ef7a9ba3acc6846fe93e3c +size 21568996 diff --git a/internvl3-5_axmodel/qwen3_p128_l6_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l6_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..b55c69e10ac5f2a1989df91e22390b6fadeaaf06 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l6_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88dddad7925e2c455cb8ee7ed23de8743efd51378aa4a16fae11049649841981 +size 21568292 diff --git a/internvl3-5_axmodel/qwen3_p128_l7_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l7_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..39e94fb57cc67db7f54be795e126f196f3aea332 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l7_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2fb8302f98ec47f75e0d0608af30df1bdaebdad870d3412ea4cdf4f9a9a0632 +size 21569988 diff --git a/internvl3-5_axmodel/qwen3_p128_l8_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l8_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..7abe3330cde632202033042bfee5107ad248a345 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l8_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ff0ddf70c1cefe35bae6e06dbcda6e1714a3077255085db50a7184314baccdc +size 21569060 diff --git a/internvl3-5_axmodel/qwen3_p128_l9_together.axmodel b/internvl3-5_axmodel/qwen3_p128_l9_together.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..3b304616803e938769af91f69207593ec0f9472b --- /dev/null +++ b/internvl3-5_axmodel/qwen3_p128_l9_together.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2df43e2bf7490043031395eedfd7c099b420ed4bd752fe2d8ef7b3c60489f952 +size 21568612 diff --git a/internvl3-5_axmodel/qwen3_post.axmodel b/internvl3-5_axmodel/qwen3_post.axmodel new file mode 100644 index 0000000000000000000000000000000000000000..8dbf45abbf608083e257876e68e1a081bdae6006 --- /dev/null +++ b/internvl3-5_axmodel/qwen3_post.axmodel @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0475e343fc60202f8ae651fd3a4ff574e31a61563bca4840aacd3f59539307e +size 170001027 diff --git a/internvl3-5_tokenizer/.gitattributes b/internvl3-5_tokenizer/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..52373fe24473b1aa44333d318f578ae6bf04b49b --- /dev/null +++ b/internvl3-5_tokenizer/.gitattributes @@ -0,0 +1,36 @@ +*.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 -text +saved_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 +tokenizer.json filter=lfs diff=lfs merge=lfs -text diff --git a/internvl3-5_tokenizer/README.md b/internvl3-5_tokenizer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0e04c4e23aa13d0297b5088c432d792757341f51 --- /dev/null +++ b/internvl3-5_tokenizer/README.md @@ -0,0 +1,830 @@ +--- +license: apache-2.0 +pipeline_tag: image-text-to-text +library_name: transformers +base_model: + - OpenGVLab/InternVL3_5-1B-MPO +base_model_relation: finetune +datasets: + - OpenGVLab/MMPR-v1.2 +language: + - multilingual +tags: + - 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/) + +
+ image +
+ +## 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. + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance.jpg) + +> 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) | + + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_overall.jpg) + +> 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. + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/training_pipeline.jpg) + +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. + + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/architecture.jpg) + +## 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_{ 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. + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/DvD.jpg) + +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 + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_reasoning.jpg) + +### OCR, Chart, and Document Understanding + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_ocr.jpg) + +### Multi-Image Understanding & Real-World Comprehension + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_multi_images.jpg) + +### Comprehensive Multimodal Understanding & Multimodal Hallucination Evaluation + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_comprehensive.jpg) + +### Visual Grounding + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_grounding.jpg) + +### Multimodal Multilingual Understanding + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_multilingual.jpg) + +### Video Understanding + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_video.jpg) + +### GUI Tasks + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_gui.jpg) + +### Embodied Tasks + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_embody.jpg) + +### SVG Tasks + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_svg.jpg) + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_svg_gen.jpg) + +## Evaluation on Language Capability + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_text.jpg) + +## Ablation Study + +### Cascade Reinforcement Learning + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/ablation_cascade_rl.jpg) + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/ablation_cascade_rl_table.jpg) + +### Decoupled Vision-Language Deployment + + +![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/ablation_dvd.jpg) + +## 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) + +```python +import torch +from 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).eval().cuda() +``` + +#### BNB 8-bit Quantization + +```python +import torch +from transformers import AutoTokenizer, AutoModel +path = "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 + +```python +import math +import torch +from 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. + +```python +R1_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 and 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 + +```python +import math +import numpy as np +import torch +import torchvision.transforms as T +from decord import VideoReader, cpu +from PIL import Image +from torchvision.transforms.functional import InterpolationMode +from 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 = '\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 = '\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 = '\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: \nImage-2: \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 = ['\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}: \n' for i in range(len(num_patches_list))]) +question = video_prefix + 'What is the red panda doing?' +# Frame1: \nFrame2: \n...\nFrame8: \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. + +```python +from transformers import TextIteratorStreamer +from threading import Thread + +# Initialize the streamer +streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10) +# Define the generation configuration +generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer) +# Start the model chat in a separate thread +thread = 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 text +generated_text = '' +# Loop through the streamer to get the new text as it is generated +for 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. + +```sh +pip 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 + +```python +from lmdeploy import pipeline, PytorchEngineConfig +from 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. + +```python +from lmdeploy import pipeline, PytorchEngineConfig +from lmdeploy.vl import load_image +from 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 conversations +response = 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: + +```python +from lmdeploy import pipeline, PytorchEngineConfig +from 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. + +```python +from lmdeploy import pipeline, PytorchEngineConfig, GenerationConfig +from 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: + +```shell +lmdeploy 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: + +```shell +pip install openai +``` + +Then, use the code below to make the API call: + +```python +from 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].id +response = 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} +} +``` diff --git a/internvl3-5_tokenizer/added_tokens.json b/internvl3-5_tokenizer/added_tokens.json new file mode 100644 index 0000000000000000000000000000000000000000..a584813833ad01eee44a2f793eb22c640d3466b8 --- /dev/null +++ b/internvl3-5_tokenizer/added_tokens.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5c2531bd62d25dd2a7401203a20f7ffb0976a026299cb4d6ff2d559d7ac3e28 +size 892 diff --git a/internvl3-5_tokenizer/chat_template.jinja b/internvl3-5_tokenizer/chat_template.jinja new file mode 100644 index 0000000000000000000000000000000000000000..2e5dcf6ad9edfd8c89a52da19c23bd8a8d87a7f2 --- /dev/null +++ b/internvl3-5_tokenizer/chat_template.jinja @@ -0,0 +1,6 @@ +{% for message in messages %}{{'<|im_start|>' + message['role'] + ' +'}}{% if message['content'] is string %}{{ message['content'] }}{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' %}{{ ' +' }}{% elif content['type'] == 'video' %}{{ '