[Bug of MXC500] triton.runtime.errors.OutOfResources: out of resource: shared memory, Required: 73728, Hardware limit: 65536.
Checklist
- [x] 1. I have searched related issues but cannot get the expected help.
- [x] 2. The bug has not been fixed in the latest version.
- [ ] 3. Please note that if the bug-related issue you submitted lacks corresponding environment info and a minimal reproducible demo, it will be challenging for us to reproduce and resolve the issue, reducing the likelihood of receiving feedback.
Describe the bug
When I started an InternVL3-8B inference demo by LMDeploy on MXC500 GPU(沐曦显卡), I got an error:
triton.runtime.errors.OutOfResources: out of resource: shared memory, Required: 73728, Hardware limit: 65536. Reducing block sizes or `num_stages` may help.
2025-04-28 18:58:47,270 - lmdeploy - ERROR - async_engine.py:789 - session 0 finished, reason "error"
internal error happened
The inference demo stript(https://huggingface.co/OpenGVLab/InternVL3-8B#lmdeploy) is:
from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
from lmdeploy.vl import load_image
model = '/root/public-model/models/OpenGVLab/InternVL3-8B'
image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
# image = load_image('/root/cli-demo/tiger.jpeg')
pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=1), chat_template_config=ChatTemplateConfig(model_name='internvl3'))
response = pipe(('describe this image', image))
print(response.text)
Reproduction
python /root/cli-demo/test.py
Environment
My packages are as below:
(base) root@ins-lvlhd:~/cli-demo# pip list
Package Version Editable project location
----------------------------- --------------------------------- -------------------------
absl-py 2.2.0
accelerate 0.32.1
addict 2.4.0
aiofiles 23.2.1
aiohappyeyeballs 2.6.1
aiohttp 3.11.14
aiosignal 1.3.2
altair 5.5.0
annotated-types 0.7.0
anyio 4.9.0
apex 0.1+metax2.31.0.4
archspec 0.2.5
argon2-cffi 23.1.0
argon2-cffi-bindings 21.2.0
arrow 1.3.0
arxiv 2.1.3
asttokens 3.0.0
async-lru 2.0.5
async-timeout 5.0.1
attrs 25.3.0
av 14.2.0
babel 2.17.0
backports.cached-property 1.0.2
beautifulsoup4 4.13.3
bitsandbytes 0.44.0+maca2.31.0.3
bleach 6.2.0
blessings 1.7
blinker 1.9.0
boltons 24.0.0
Brotli 1.1.0
cachetools 5.5.2
certifi 2025.1.31
cffi 1.17.1
chardet 5.2.0
charset-normalizer 3.4.1
click 8.1.8
cloudpickle 3.1.1
codecov 2.1.13
colorama 0.4.6
coloredlogs 15.0.1
colour-runner 0.1.1
comm 0.2.2
conda 25.1.1
conda-libmamba-solver 25.1.1
conda-package-handling 2.4.0
conda_package_streaming 0.11.0
contourpy 1.3.1
coverage 7.7.0
cycler 0.12.1
datasets 3.1.0
debugpy 1.8.13
decorator 5.2.1
deepdiff 8.4.2
deepspeed 0.15.1+f0c2dd0d
defusedxml 0.7.1
dill 0.3.8
diskcache 5.6.3
distlib 0.3.9
distro 1.9.0
docstring_parser 0.16
dropout_layer_norm 0.1+metax2.31.0.4torch2.4
duckduckgo_search 5.3.1b1
einops 0.8.1
et_xmlfile 2.0.0
exceptiongroup 1.2.2
executing 2.2.0
fastapi 0.115.11
fastjsonschema 2.21.1
feedparser 6.0.11
ffmpy 0.5.0
filelock 3.18.0
fire 0.7.0
flash_attn 2.6.3+metax2.31.0.4torch2.4
flashinfer 0.2.1.post2+metax2.31.0.4torch2.4
fonttools 4.56.0
fqdn 1.5.1
frozendict 2.4.6
frozenlist 1.5.0
fsspec 2024.9.0
ftfy 6.3.1
func_timeout 4.3.5
fused_dense_lib 2.6.3+metax2.31.0.4torch2.4
gitdb 4.0.12
GitPython 3.1.44
google-auth 2.38.0
google-auth-oauthlib 0.4.6
gradio 4.44.1
gradio_client 1.3.0
griffe 0.49.0
grpcio 1.71.0
h11 0.14.0
h2 4.1.0
hjson 3.1.0
hpack 4.0.0
httpcore 1.0.7
httpx 0.28.1
huggingface-hub 0.29.3
humanfriendly 10.0
hyperframe 6.0.1
idna 3.10
imageio 2.37.0
importlib_resources 6.5.2
iniconfig 2.0.0
interegular 0.3.3
ipykernel 6.29.5
ipython 8.34.0
ipywidgets 8.1.5
isoduration 20.11.0
jedi 0.19.2
Jinja2 3.1.6
jiter 0.4.0
json5 0.10.0
jsonpatch 1.33
jsonpointer 3.0.0
jsonschema 4.23.0
jsonschema-specifications 2024.10.1
jupyter 1.1.1
jupyter_client 8.6.3
jupyter-console 6.6.3
jupyter_core 5.7.2
jupyter-events 0.12.0
jupyter-lsp 2.2.5
jupyter_server 2.15.0
jupyter_server_terminals 0.5.3
jupyterlab 4.3.6
jupyterlab_pygments 0.3.0
jupyterlab_server 2.27.3
jupyterlab_widgets 3.0.13
kiwisolver 1.4.8
lagent 0.2.4
lark 1.2.2
lazy_loader 0.4
libmambapy 2.0.7
liger_kernel 0.5.3
llamafactory 0.9.1.dev0
llvmlite 0.44.0
lmdeploy 0.7.2.post1 /root/lmdeploy
Markdown 3.7
markdown-it-py 3.0.0
MarkupSafe 2.1.5
matplotlib 3.10.1
matplotlib-inline 0.1.7
mcspconv 2.1.0+metax2.31.0.4torch2.4
mdurl 0.1.2
menuinst 2.2.0
mistune 3.1.3
mmengine 0.10.7
mmengine-lite 0.10.7
mpmath 1.3.0
multidict 6.2.0
multiprocess 0.70.16
narwhals 1.31.0
nbclient 0.10.2
nbconvert 7.16.6
nbformat 5.10.4
nest-asyncio 1.6.0
networkx 3.4.2
ninja 1.11.1.3
notebook 7.3.3
notebook_shim 0.2.4
numba 0.61.2
numpy 1.26.4
nvidia-ml-py 12.570.86
oauthlib 3.2.2
openai 1.76.0
opencv-python 4.11.0.86
openpyxl 3.1.5
orderly-set 5.3.0
orjson 3.10.15
outlines 0.0.46
overrides 7.7.0
packaging 24.2
pandas 2.2.3
pandocfilters 1.5.1
parso 0.8.4
peft 0.12.0
pexpect 4.9.0
phx-class-registry 4.1.0
pillow 10.4.0
pip 24.3.1
platformdirs 4.3.6
pluggy 1.5.0
prometheus_client 0.21.1
prompt_toolkit 3.0.50
propcache 0.3.0
protobuf 3.20.3
psutil 7.0.0
ptyprocess 0.7.0
pure_eval 0.2.3
py-cpuinfo 9.0.0
pyairports 2.1.1
pyarrow 19.0.1
pyasn1 0.6.1
pyasn1_modules 0.4.1
pybind11 2.13.1
pycosat 0.6.6
pycountry 24.6.1
pycparser 2.22
pydantic 2.10.6
pydantic_core 2.27.2
pydeck 0.9.1
pydub 0.25.1
Pygments 2.19.1
pynvml 12.0.0
pyparsing 3.2.1
pyproject-api 1.9.0
PySocks 1.7.1
pytest 8.3.5
python-dateutil 2.9.0.post0
python-json-logger 3.3.0
python-multipart 0.0.20
pytz 2025.1
PyYAML 6.0.2
pyzmq 26.3.0
referencing 0.36.2
regex 2024.11.6
requests 2.32.3
requests-oauthlib 2.0.0
rfc3339-validator 0.1.4
rfc3986-validator 0.1.1
rich 13.9.4
rootpath 0.1.1
rotary_emb 0.1+metax2.31.0.4torch2.4
rpds-py 0.23.1
rsa 4.9
ruamel.yaml 0.18.10
ruamel.yaml.clib 0.2.8
ruff 0.11.2
safetensors 0.5.3
scikit-image 0.25.2
scipy 1.15.2
semantic-version 2.10.0
Send2Trash 1.8.3
sentencepiece 0.2.0
setuptools 69.5.1
sgmllib3k 1.0.0
shellingham 1.5.4
shortuuid 1.0.13
shtab 1.7.1
six 1.17.0
smmap 5.0.2
sniffio 1.3.1
socksio 1.0.0
soupsieve 2.6
sse-starlette 2.2.1
stack-data 0.6.3
starlette 0.46.1
streamlit 1.43.2
sympy 1.13.3
tenacity 9.0.0
tensorboard 2.11.0
tensorboard-data-server 0.6.1
tensorboard-plugin-wit 1.8.1
termcolor 2.5.0
terminado 0.18.1
tifffile 2025.3.13
tiktoken 0.9.0
timeout-decorator 0.5.0
tinycss2 1.4.0
tokenizers 0.21.1
toml 0.10.2
tomli 2.2.1
tomlkit 0.12.0
torch 2.4.0+metax2.31.0.4
torchaudio 2.4.1+metax2.31.0.4
torchvision 0.15.1+metax2.31.0.4
tornado 6.4.2
tox 4.24.2
tqdm 4.67.1
traitlets 5.14.3
transformers 4.47.1
transformers-stream-generator 0.0.5
triton 3.0.0+metax2.31.0.4
trl 0.9.6
truststore 0.10.0
typer 0.15.2
types-python-dateutil 2.9.0.20241206
typing_extensions 4.12.2
tyro 0.8.14
tzdata 2025.1
uri-template 1.3.0
urllib3 2.3.0
uvicorn 0.34.0
virtualenv 20.29.3
watchdog 6.0.0
wcwidth 0.2.13
webcolors 24.11.1
webencodings 0.5.1
websocket-client 1.8.0
websockets 12.0
Werkzeug 3.1.3
wheel 0.45.1
widgetsnbextension 4.0.13
xentropy_cuda_lib 0.1+metax2.31.0.4torch2.4
xtuner 0.1.23 /workspace/xtuner
xxhash 3.5.0
yapf 0.43.0
yarl 1.18.3
zstandard 0.23.0
Error traceback
Full error report is as below:
(base) root@ins-lvlhd:~/cli-demo# python test.py
/opt/conda/lib/python3.10/site-packages/torchvision/io/image.py:13: UserWarning: Failed to load image Python extension: 'libjpeg.so.62: cannot open shared object file: No such file or directory'If you don't plan on using image functionality from `torchvision.io`, you can ignore this warning. Otherwise, there might be something wrong with your environment. Did you have `libjpeg` or `libpng` installed before building `torchvision` from source?
warn(
/opt/conda/lib/python3.10/site-packages/torchvision/datapoints/__init__.py:12: UserWarning: The torchvision.datapoints and torchvision.transforms.v2 namespaces are still Beta. While we do not expect major breaking changes, some APIs may still change according to user feedback. Please submit any feedback you may have in this issue: https://github.com/pytorch/vision/issues/6753, and you can also check out https://github.com/pytorch/vision/issues/7319 to learn more about the APIs that we suspect might involve future changes. You can silence this warning by calling torchvision.disable_beta_transforms_warning().
warnings.warn(_BETA_TRANSFORMS_WARNING)
/opt/conda/lib/python3.10/site-packages/torchvision/transforms/v2/__init__.py:54: UserWarning: The torchvision.datapoints and torchvision.transforms.v2 namespaces are still Beta. While we do not expect major breaking changes, some APIs may still change according to user feedback. Please submit any feedback you may have in this issue: https://github.com/pytorch/vision/issues/6753, and you can also check out https://github.com/pytorch/vision/issues/7319 to learn more about the APIs that we suspect might involve future changes. You can silence this warning by calling torchvision.disable_beta_transforms_warning().
warnings.warn(_BETA_TRANSFORMS_WARNING)
2025-04-28 18:58:37,793 - lmdeploy - WARNING - archs.py:57 - Fallback to pytorch engine because turbomind engine is not installed correctly. If you insist to use turbomind engine, you may need to reinstall lmdeploy from pypi or build from source and try again.
2025-04-28 18:58:38,064 - lmdeploy - WARNING - model.py:1990 - Did not find a chat template matching /root/public-model/models/OpenGVLab/InternVL3-8B.
2025-04-28 18:58:38,064 - lmdeploy - WARNING - model.py:74 - Could not find internvl3 in registered models. Register internvl3 using the BaseChatTemplate.
2025-04-28 18:58:38,068 - lmdeploy - WARNING - tokenizer.py:88 - The current version of `transformers` is transformers==4.47.1, which is lower than the required version transformers==4.48.3. Please upgrade to the required version.
Loading weights from safetensors: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 4/4 [00:06<00:00, 1.70s/it]
2025-04-28 18:58:46,160 - lmdeploy - WARNING - async_engine.py:643 - GenerationConfig: GenerationConfig(n=1, max_new_tokens=512, do_sample=False, top_p=1.0, top_k=50, min_p=0.0, temperature=0.8, repetition_penalty=1.0, ignore_eos=False, random_seed=None, stop_words=None, bad_words=None, stop_token_ids=[151645], bad_token_ids=None, min_new_tokens=None, skip_special_tokens=True, spaces_between_special_tokens=True, logprobs=None, response_format=None, logits_processors=None, output_logits=None, output_last_hidden_state=None)
2025-04-28 18:58:46,161 - lmdeploy - WARNING - async_engine.py:644 - Since v0.6.0, lmdeploy add `do_sample` in GenerationConfig. It defaults to False, meaning greedy decoding. Please set `do_sample=True` if sampling decoding is needed
2025-04-28 18:58:47,146 - lmdeploy - ERROR - model_agent.py:498 - Task <ModelAgentLoop> failed
Traceback (most recent call last):
File "/root/lmdeploy/lmdeploy/pytorch/engine/model_agent.py", line 493, in _on_finish_callback
task.result()
File "/root/lmdeploy/lmdeploy/pytorch/engine/model_agent.py", line 484, in _async_loop_background
await self._async_step_background(**forward_inputs, )
File "/root/lmdeploy/lmdeploy/pytorch/engine/model_agent.py", line 421, in _async_step_background
output = await self._async_model_forward(
File "/root/lmdeploy/lmdeploy/pytorch/engine/model_agent.py", line 289, in _async_model_forward
ret = await __forward(inputs)
File "/root/lmdeploy/lmdeploy/pytorch/engine/model_agent.py", line 249, in __forward
return await self.async_forward(inputs, swap_in_map=swap_in_map, swap_out_map=swap_out_map)
File "/root/lmdeploy/lmdeploy/pytorch/engine/model_agent.py", line 660, in async_forward
output = self._forward_impl(inputs, swap_in_map=swap_in_map, swap_out_map=swap_out_map)
File "/root/lmdeploy/lmdeploy/pytorch/engine/model_agent.py", line 644, in _forward_impl
output = model_forward(
File "/opt/conda/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context
return func(*args, **kwargs)
File "/root/lmdeploy/lmdeploy/pytorch/engine/model_agent.py", line 73, in model_forward
output = model(**input_dict)
File "/root/lmdeploy/lmdeploy/pytorch/backends/cuda/graph_runner.py", line 146, in __call__
return self.model(**kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl
return forward_call(*args, **kwargs)
File "/root/lmdeploy/lmdeploy/pytorch/models/internvl.py", line 372, in forward
return self.language_model.forward(input_ids=input_ids,
File "/root/lmdeploy/lmdeploy/pytorch/models/qwen2.py", line 325, in forward
hidden_states = self.model(
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl
return forward_call(*args, **kwargs)
File "/root/lmdeploy/lmdeploy/pytorch/models/qwen2.py", line 265, in forward
hidden_states, residual = decoder_layer(
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl
return forward_call(*args, **kwargs)
File "/root/lmdeploy/lmdeploy/pytorch/models/qwen2.py", line 189, in forward
hidden_states = self.self_attn(
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl
return forward_call(*args, **kwargs)
File "/root/lmdeploy/lmdeploy/pytorch/models/qwen2.py", line 87, in forward
attn_output = self.attn_fwd(
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1553, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1562, in _call_impl
return forward_call(*args, **kwargs)
File "/root/lmdeploy/lmdeploy/pytorch/nn/attention.py", line 78, in forward
return self.impl.forward(
File "/root/lmdeploy/lmdeploy/pytorch/backends/cuda/attention.py", line 166, in forward
self.flash_attention_fwd(
File "/root/lmdeploy/lmdeploy/pytorch/kernels/cuda/flashattention.py", line 416, in flash_attention_fwd
_flash_prefill_fwd_kernel[grid](
File "/opt/conda/lib/python3.10/site-packages/triton/runtime/jit.py", line 345, in <lambda>
return lambda *args, **kwargs: self.run(grid=grid, warmup=False, *args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/triton/runtime/jit.py", line 691, in run
kernel.run(grid_0, grid_1, grid_2, stream, kernel.function, kernel.packed_metadata, launch_metadata,
File "/opt/conda/lib/python3.10/site-packages/triton/compiler/compiler.py", line 381, in __getattribute__
self._init_handles()
File "/opt/conda/lib/python3.10/site-packages/triton/compiler/compiler.py", line 374, in _init_handles
raise OutOfResources(self.metadata.shared, max_shared, "shared memory")
triton.runtime.errors.OutOfResources: out of resource: shared memory, Required: 73728, Hardware limit: 65536. Reducing block sizes or `num_stages` may help.
2025-04-28 18:58:47,270 - lmdeploy - ERROR - async_engine.py:789 - session 0 finished, reason "error"
internal error happened
用nivida显卡试了一下,下载模型,创环境装lmdeploy==0.7.3,然后python /root/cli-demo/test.py,三步能顺利跑通。
用MCX500显卡则会遇到这个硬件限制64KB的问题。
you are running lmdeploy with turbomind engine on C500, which is not fully supported. please use PyTorch engine with dlinfer instead.
you are running lmdeploy with turbomind engine on C500, which is not fully supported. please use PyTorch engine with dlinfer instead.
Fine, It works due to the Inference with Transformers tutorial
you are running lmdeploy with turbomind engine on C500, which is not fully supported. please use PyTorch engine with dlinfer instead.
Fine, It works due to the Inference with Transformers tutorial
Hi, can you share the details, How should I do to deploy it on MX C500?
在MXC500上部署InternVL3-8B的推理脚本,inference_by_Transformers.py
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, AutoConfig
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
def split_model(model_name):
device_map = {}
world_size = torch.cuda.device_count()
config = AutoConfig.from_pretrained('/root/public-model/models/OpenGVLab/InternVL3-8B', trust_remote_code=True)
num_layers = config.llm_config.num_hidden_layers
# Since the first GPU will be used for ViT, treat it as half a GPU.
num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
num_layers_per_gpu = [num_layers_per_gpu] * world_size
num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
layer_cnt = 0
for i, num_layer in enumerate(num_layers_per_gpu):
for j in range(num_layer):
device_map[f'language_model.model.layers.{layer_cnt}'] = i
layer_cnt += 1
device_map['vision_model'] = 0
device_map['mlp1'] = 0
device_map['language_model.model.tok_embeddings'] = 0
device_map['language_model.model.embed_tokens'] = 0
device_map['language_model.output'] = 0
device_map['language_model.model.norm'] = 0
device_map['language_model.model.rotary_emb'] = 0
device_map['language_model.lm_head'] = 0
device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
return device_map
# If you set `load_in_8bit=True`, you will need two 80GB GPUs.
# If you set `load_in_8bit=False`, you will need at least three 80GB GPUs.
path = '/root/public-model/models/OpenGVLab/InternVL3-8B'
device_map = split_model('InternVL3-8B')
model = AutoModel.from_pretrained(
path,
torch_dtype=torch.bfloat16,
load_in_8bit=False,
low_cpu_mem_usage=True,
use_flash_attn=False,
trust_remote_code=True,
device_map=device_map).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('/root/cli-demo/tiger.jpeg', max_num=12).to(torch.bfloat16).cuda()
generation_config = dict(max_new_tokens=1024, do_sample=True)
# single-image single-round conversation (单图单轮对话)
question = '<image>\nPlease describe the image shortly.'
response = model.chat(tokenizer, pixel_values, question, generation_config)
print(f'User: {question}\nAssistant: {response}')
# single-image multi-round conversation (单图多轮对话)
question = '<image>\nPlease describe the image in detail.'
response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
print(f'User: {question}\nAssistant: {response}')
question = 'Please write a poem according to the image.'
response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
print(f'User: {question}\nAssistant: {response}')
(如果成功了的话可以给个正面反馈,如果不成功可以提问,我帮忙解答一下
在MXC500上部署InternVL3-8B的推理脚本,inference_by_Transformers.py
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, AutoConfig
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_imagesdef 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
def split_model(model_name): device_map = {} world_size = torch.cuda.device_count() config = AutoConfig.from_pretrained('/root/public-model/models/OpenGVLab/InternVL3-8B', trust_remote_code=True) num_layers = config.llm_config.num_hidden_layers # Since the first GPU will be used for ViT, treat it as half a GPU. num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5)) num_layers_per_gpu = [num_layers_per_gpu] * world_size num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5) layer_cnt = 0 for i, num_layer in enumerate(num_layers_per_gpu): for j in range(num_layer): device_map[f'language_model.model.layers.{layer_cnt}'] = i layer_cnt += 1 device_map['vision_model'] = 0 device_map['mlp1'] = 0 device_map['language_model.model.tok_embeddings'] = 0 device_map['language_model.model.embed_tokens'] = 0 device_map['language_model.output'] = 0 device_map['language_model.model.norm'] = 0 device_map['language_model.model.rotary_emb'] = 0 device_map['language_model.lm_head'] = 0 device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
return device_mapIf you set
load_in_8bit=True, you will need two 80GB GPUs.If you set
load_in_8bit=False, you will need at least three 80GB GPUs.path = '/root/public-model/models/OpenGVLab/InternVL3-8B' device_map = split_model('InternVL3-8B') model = AutoModel.from_pretrained( path, torch_dtype=torch.bfloat16, load_in_8bit=False, low_cpu_mem_usage=True, use_flash_attn=False, trust_remote_code=True, device_map=device_map).eval() tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
set the max number of tiles in
max_numpixel_values = load_image('/root/cli-demo/tiger.jpeg', max_num=12).to(torch.bfloat16).cuda() generation_config = dict(max_new_tokens=1024, do_sample=True)
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}') (如果成功了的话可以给个正面反馈,如果不成功可以提问,我帮忙
在MXC500上部署InternVL3-8B的推理脚本,inference_by_Transformers.py
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, AutoConfig
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_imagesdef 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
def split_model(model_name): device_map = {} world_size = torch.cuda.device_count() config = AutoConfig.from_pretrained('/root/public-model/models/OpenGVLab/InternVL3-8B', trust_remote_code=True) num_layers = config.llm_config.num_hidden_layers # Since the first GPU will be used for ViT, treat it as half a GPU. num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5)) num_layers_per_gpu = [num_layers_per_gpu] * world_size num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5) layer_cnt = 0 for i, num_layer in enumerate(num_layers_per_gpu): for j in range(num_layer): device_map[f'language_model.model.layers.{layer_cnt}'] = i layer_cnt += 1 device_map['vision_model'] = 0 device_map['mlp1'] = 0 device_map['language_model.model.tok_embeddings'] = 0 device_map['language_model.model.embed_tokens'] = 0 device_map['language_model.output'] = 0 device_map['language_model.model.norm'] = 0 device_map['language_model.model.rotary_emb'] = 0 device_map['language_model.lm_head'] = 0 device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
return device_mapIf you set
load_in_8bit=True, you will need two 80GB GPUs.If you set
load_in_8bit=False, you will need at least three 80GB GPUs.path = '/root/public-model/models/OpenGVLab/InternVL3-8B' device_map = split_model('InternVL3-8B') model = AutoModel.from_pretrained( path, torch_dtype=torch.bfloat16, load_in_8bit=False, low_cpu_mem_usage=True, use_flash_attn=False, trust_remote_code=True, device_map=device_map).eval() tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
set the max number of tiles in
max_numpixel_values = load_image('/root/cli-demo/tiger.jpeg', max_num=12).to(torch.bfloat16).cuda() generation_config = dict(max_new_tokens=1024, do_sample=True)
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}') (如果成功了的话可以给个正面反馈,如果不成功可以提问,我帮忙解答一下 多谢,暂时我们的机器没法连外网下载模型,后续有机会再试了。