Views
No views yet
pip install torch transformers safetensors pillow1import sys
2from pathlib import Path
3
4# 将模型目录添加到路径
5sys.path.insert(0, '.')
6
7from qwen3vl_embedding import load_embedding_model
8from transformers import AutoTokenizer
9
10# 加载模型
11model = load_embedding_model('.', device='cuda')
12
13# 加载 tokenizer(需要从原始 Qwen3-VL 模型下载)
14tokenizer = AutoTokenizer.from_pretrained(
15 'Qwen/Qwen3-VL-8B-Instruct',
16 trust_remote_code=True
17)1# 单个文本
2text = "机器学习是人工智能的重要分支"
3embedding = model.encode_text(text, tokenizer, normalize=True)
4print(embedding.shape) # torch.Size([1, 4096])
5
6# 批量文本
7texts = ["你好世界", "Hello world", "深度学习"]
8embeddings = model.encode_text(texts, tokenizer, normalize=True)
9
10# 计算相似度
11import torch
12similarity = torch.mm(embeddings, embeddings.T)
13print(similarity)1from PIL import Image
2
3# 单张图片
4image = Image.open("example.jpg")
5embedding = model.encode_image(image, normalize=True)
6
7# 批量图片
8images = ["image1.jpg", "image2.jpg", "image3.jpg"]
9embeddings = model.encode_image(images, normalize=True)
10
11# 支持 URL
12image_url = "https://example.com/image.jpg"
13embedding = model.encode_image(image_url, normalize=True)1# 视频自动抽帧编码
2video_path = "example.mp4"
3embedding = model.encode_video(
4 video_path,
5 fps=2.0, # 每秒采样帧数
6 max_frames=32, # 最大帧数
7 normalize=True
8)1# 文本查询图像
2query_text = "一只可爱的猫"
3query_emb = model.encode_text(query_text, tokenizer, normalize=True)
4
5image_paths = ["cat1.jpg", "dog1.jpg", "cat2.jpg"]
6image_embs = model.encode_image(image_paths, normalize=True)
7
8# 计算相似度并排序
9scores = torch.mm(query_emb, image_embs.T)[0]
10for img, score in sorted(zip(image_paths, scores), key=lambda x: x[1], reverse=True):
11 print(f"{img}: {score:.4f}")| 模型 | 大小 | 文本编码速度 | 图像编码速度 |
|---|---|---|---|
| Qwen3-VL-8B-Instruct (完整) | 17GB | 1x | 1x |
| Qwen3-VL-8B-Embedding (本模型) | 4.5GB | 3.5x | 3.2x |
text: 单个文本或文本列表tokenizer: HuggingFace tokenizernormalize: 是否 L2 归一化 (默认 True)pooling: 池化策略 - "mean" (默认), "first", "last"max_length: 最大序列长度 (默认 512)image: 图像路径、URL 或 PIL.Image 对象normalize: 是否 L2 归一化 (默认 True)pooling: 池化策略 - "mean" (默认), "first", "last", "none"video_path: 视频文件路径fps: 采样帧率 (默认 2.0)max_frames: 最大帧数 (默认 32)normalize: 是否 L2 归一化 (默认 True)pooling: 池化策略 - "mean" (默认), "first", "last".
├── vision_encoder.safetensors # 1.1GB - 视觉编码器权重
├── text_encoder.safetensors # 3.4GB - 文本编码器权重
├── embedding_config.json # 模型配置
├── qwen3vl_embedding.py # 主模型代码
├── text_encoder.py # 文本编码器实现
├── vision_process.py # 视觉预处理
└── weight_index.json # 权重索引1@article{qwen3vl,
2 title={Qwen3-VL: Towards Versatile Vision-Language Understanding},
3 author={Qwen Team},
4 year={2024}
5}