安装前环境检查

pytorch下载地址

https://pytorch.org/get-started/previous-versions/

检查是否安装好pytorch

python -c "import torch; print(torch.__version__); print(torch.cuda.is_available())"
2.8.0+cu129
True

检查是否安装好torchvision

(qwen-vl) C:\Users\wayso>python -c "import torchvision; print(torchvision.__version__)"
0.23.0+cu129

创建python环境

Qwen2.5系列尽量选用python3.8~3.10的版本

conda create -n qwen-vl python=3.10

构建 Qwen2.5-VL 的代码已在最新的 Huggingface transformers中,建议使用命令从源代码构建:

pip install git+https://github.com/huggingface/transformers accelerate

安装工具包

  • 为了便捷地处理各种类型的视觉输入,包括 base64、URL 以及交错的图像和视频。
pip install qwen-vl-utils[decord]==0.0.8

4、安装modelscope

pip install modelscope

测试代码

参考官方示例:https://modelscope.cn/models/Qwen/Qwen2.5-VL-7B-Instruct-AWQ

from modelscope import Qwen2_5_VLForConditionalGeneration, AutoTokenizer, AutoProcessor
from qwen_vl_utils import process_vision_info

# default: Load the model on the available device(s)
# model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
#     "Qwen/Qwen2.5-VL-7B-Instruct-AWQ", torch_dtype="auto", device_map="auto"
# )
# 正确写法:必须用 from_pretrained 加载预训练模型
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
    r"D:\models\Qwen2.5-VL-7B-Instruct-AWQ",  # 本地模型绝对路径
    torch_dtype="auto",                       # 适配4060的自动精度
    device_map="auto",                        # 自动加载到4060显卡
    trust_remote_code=True                    # Qwen模型强制要求,不可删
)

# We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
# model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
#     "Qwen/Qwen2.5-VL-7B-Instruct-AWQ",
#     torch_dtype=torch.bfloat16,
#     attn_implementation="flash_attention_2",
#     device_map="auto",
# )

# default processer
# processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct-AWQ")
# 本地加载处理器(同步修改)
processor = AutoProcessor.from_pretrained(
    r"D:\models\Qwen2.5-VL-7B-Instruct-AWQ",
    trust_remote_code=True
)
# The default range for the number of visual tokens per image in the model is 4-16384.
# You can set min_pixels and max_pixels according to your needs, such as a token range of 256-1280, to balance performance and cost.
# min_pixels = 256*28*28
# max_pixels = 1280*28*28
# processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct-AWQ", min_pixels=min_pixels, max_pixels=max_pixels)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
            },
            {"type": "text", "text": "Describe this image."},
        ],
    }
]

# Preparation for inference
text = processor.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
    text=[text],
    images=image_inputs,
    videos=video_inputs,
    padding=True,
    return_tensors="pt",
)
inputs = inputs.to("cuda")

# Inference: Generation of the output
generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [
    out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
    generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text)

运行结果

异常问题解决

pip install gptqmodel -i https://pypi.tuna.tsinghua.edu.cn/simple
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting gptqmodel
  Using cached https://pypi.tuna.tsinghua.edu.cn/packages/a3/0e/4981ce4887f47e7da8e6049d1d3d2d6a7d8bfb30d93620cb864e71acb519/gptqmodel-5.6.12.tar.gz (632 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... error
  error: subprocess-exited-with-error

  × Getting requirements to build wheel did not run successfully.
  │ exit code: 1
  ╰─> [28 lines of output]
      Traceback (most recent call last):
        File "<string>", line 220, in _detect_torch_version
        File "C:\ProgramData\anaconda3\envs\qwen-vl\lib\importlib\metadata\__init__.py", line 996, in version
          return distribution(distribution_name).version
        File "C:\ProgramData\anaconda3\envs\qwen-vl\lib\importlib\metadata\__init__.py", line 969, in distribution
          return Distribution.from_name(distribution_name)
        File "C:\ProgramData\anaconda3\envs\qwen-vl\lib\importlib\metadata\__init__.py", line 548, in from_name
          raise PackageNotFoundError(name)
      importlib.metadata.PackageNotFoundError: No package metadata was found for torch

      During handling of the above exception, another exception occurred:

      Traceback (most recent call last):
        File "C:\ProgramData\anaconda3\envs\qwen-vl\lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 389, in <module>
          main()
        File "C:\ProgramData\anaconda3\envs\qwen-vl\lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 373, in main
          json_out["return_val"] = hook(**hook_input["kwargs"])
        File "C:\ProgramData\anaconda3\envs\qwen-vl\lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 143, in get_requires_for_build_wheel
          return hook(config_settings)
        File "C:\Users\wayso\AppData\Local\Temp\pip-build-env-6p_qdznn\overlay\Lib\site-packages\setuptools\build_meta.py", line 333, in get_requires_for_build_wheel
          return self._get_build_requires(config_settings, requirements=[])
        File "C:\Users\wayso\AppData\Local\Temp\pip-build-env-6p_qdznn\overlay\Lib\site-packages\setuptools\build_meta.py", line 301, in _get_build_requires
          self.run_setup()
        File "C:\Users\wayso\AppData\Local\Temp\pip-build-env-6p_qdznn\overlay\Lib\site-packages\setuptools\build_meta.py", line 317, in run_setup
          exec(code, locals())
        File "<string>", line 330, in <module>
        File "<string>", line 224, in _detect_torch_version
      Exception: Unable to detect torch version via uv/pip/conda/importlib. Please install torch >= 2.7.1
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed to build 'gptqmodel' when getting requirements to build wheel

你的 PyTorch 版本是 2.6.0,但错误提示需要 >= 2.7.1。这是版本不匹配导致的。让我们来解决这个问题:

pip install torch==2.8.0 torchvision==0.23.0  --index-url https://download.pytorch.org/whl/cu129
Looking in indexes: https://download.pytorch.org/whl/cu129

再安装gptqmodel

pip install gptqmodel --no-build-isolation -i https://pypi.tuna.tsinghua.edu.cn/simple

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐