Views
No views yet
Qwen2-VL-7B-CML-SFT is fully supported by the latest Hugging Face Transformers codebase.pip install git+https://github.com/huggingface/transformers accelerateQwen2-VL-7B-CML-SFT models.pip install qwen-vl-utils[decord]==0.0.8requirements.txt for the complete environment configuration.Qwen2-VL-7B-CML-SFT chat model with 🤗 Transformers. The example integrates qwen_vl_utils to preprocess and normalize visual inputs before inference.1
2# -- coding: utf-8 --
3# @time : 2025/12/4 14:33
4# @author : shajiu
5# @file :
6# @software: pycharm
7
8
9
10import random
11import numpy as np
12import torch
13
14
15import torch
16from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
17from qwen_vl_utils import process_vision_info
18
19MODEL_ID = "shajiu/Qwen2-VL-7B-CML-SFT"
20
21# 1) 加载模型与处理器
22model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
23 MODEL_ID,
24 torch_dtype="auto",
25 device_map="auto",
26 #attn_implementation="flash_attention_2"#(需额外安装 flash-attn)
27)
28processor = AutoProcessor.from_pretrained(MODEL_ID)
29
30# 2) 构造多模态对话(image + text)
31image_path = "bo_10070.png" # 注意:官方示例使用 file:/// 前缀
32messages = [
33 {
34 "role": "user",
35 "content": [
36 {"type": "image", "image": image_path},
37 {"type": "text", "text": "《རྨ་བྱའི་རྒྱན་གོས་ཏེ།ལུས་ཐོག་གྱོན་པའི་ལོ་ངོ་སྟོང་གི་ལོ་རྒྱུས།》ཡི་རྩ་རྒྱུད་ལ་གཞིགས་ནས་བརྗོད་བྱ་གཙོ་བོར་ཞིབ་ཚགས་བྱས་ནས་རྒྱས་བཤད་བྱེད་པ་མ་ཟད།པར་རིས་ཁྲོད་ཀྱི་གཙོ་གནད་ལ་བརྟེན་ནས་གསལ་བཤད་བྱེད་དགོས།"},
38 ],
39 }
40]
41
42# 3) 预处理 -> 张量
43text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
44image_inputs, video_inputs = process_vision_info(messages)
45
46inputs = processor(
47 text=[text],
48 images=image_inputs,
49 videos=video_inputs,
50 padding=True,
51 return_tensors="pt",
52)
53
54# 放到模型所在设备(多卡/auto device_map 时更稳)
55inputs = {k: v.to(model.device) for k, v in inputs.items()}
56
57
58seed = 1234
59random.seed(seed)
60np.random.seed(seed)
61torch.manual_seed(seed)
62torch.cuda.manual_seed_all(seed)
63
64gen_kwargs = dict(
65 max_new_tokens=4000,
66 do_sample=True, # 开采样
67 temperature=0.2, # 越小越稳(0.2~0.4 常用)
68 top_p=0.9, # 核采样
69 top_k=50, # 限制候选集合,减少乱跑
70 repetition_penalty=1.08, # 稍强一点抑制复读
71)
72
73# 4) 推理生成
74with torch.inference_mode():
75 generated_ids = model.generate(**inputs, **gen_kwargs)
76
77
78
79# 5) 只解码新生成部分
80generated_ids_trimmed = [
81 out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs["input_ids"], generated_ids)
82]
83out_text = processor.batch_decode(
84 generated_ids_trimmed,
85 skip_special_tokens=True,
86 clean_up_tokenization_spaces=False,
87)[0]
88
89print("推理结果:\n",out_text)
90