ILD

siglip2 deploy
作者:Yuan Jianpeng 邮箱:yuanjp89@163.com
发布时间:2026-10-21 站点:Inside Linux Development

操作平台是windows。


1 安装windows的python

参考

windows install python

https://linuxdev.cc/article/a0lovc.html


2 安装Hugging Face Transformers

打开cmd,执行:

pip install transformers


3 Download & cache model

使用AutoModel, AutoProcessor,可以自动加载模型,然后缓存到本地。下次就不会再次下载了。


from transformers import AutoModel, AutoProcessor

# Choose your checkpoint (e.g., SigLIP 2 Large)
ckpt = "google/siglip2-large-patch16-512"

# This downloads the model weights
model = AutoModel.from_pretrained(ckpt)

# This downloads the tokenizer and image processor
processor = AutoProcessor.from_pretrained(ckpt)

print("Model and processor downloaded successfully!")


4 save to Local directory

基于第3步,下载或者从缓存中读取模型后,调用save方法可以保存。注意依赖于PyTorch,使用pip安装:

pip install torch torchvision


保存到本地目录。

model.save_pretrained("./my_local_siglip")
processor.save_pretrained("./my_local_siglip")


processor生成了几个文件

processor_config.json图像处理器的配置(如 resize、归一化参数)
tokenizer.json分词器词表
tokenizer_config.json分词器配置
chat_template.jinja对话模板(部分模型会用)


比如processor_config.json,定义了图像处理后的尺寸等。

{
  "image_processor": {
    "do_convert_rgb": null,
    "do_normalize": true,
    "do_rescale": true,
    "do_resize": true,
    "image_mean": [
      0.5,
      0.5,
      0.5
    ],
    "image_processor_type": "SiglipImageProcessor",
    "image_std": [
      0.5,
      0.5,
      0.5
    ],
    "resample": 2,
    "rescale_factor": 0.00392156862745098,
    "size": {
      "height": 512,
      "width": 512
    }
  },
  "processor_class": "SiglipProcessor"
}


model生成了两个文件

config.json模型结构配置
model.safetensors模型权重本体


config.json定义了模型的配置

{
  "architectures": [
    "SiglipModel"
  ],
  "dtype": "float32",
  "initializer_factor": 1.0,
  "model_type": "siglip",
  "text_config": {
    "attention_dropout": 0.0,
    "bos_token_id": 49406,
    "dtype": "float32",
    "eos_token_id": 49407,
    "hidden_act": "gelu_pytorch_tanh",
    "hidden_size": 1024,
    "intermediate_size": 4096,
    "layer_norm_eps": 1e-06,
    "max_position_embeddings": 64,
    "model_type": "siglip_text_model",
    "num_attention_heads": 16,
    "num_hidden_layers": 24,
    "pad_token_id": 1,
    "projection_size": 1024,
    "vocab_size": 256000
  },
  "transformers_version": "5.20.2",
  "vision_config": {
    "attention_dropout": 0.0,
    "dtype": "float32",
    "hidden_act": "gelu_pytorch_tanh",
    "hidden_size": 1024,
    "image_size": 512,
    "intermediate_size": 4096,
    "layer_norm_eps": 1e-06,
    "model_type": "siglip_vision_model",
    "num_attention_heads": 16,
    "num_channels": 3,
    "num_hidden_layers": 24,
    "patch_size": 16
  }
}

可以看到是float32类型,内置了文本和视觉两个模型。

模型权重文件非常大,达到了3个G。


上面这些模型文件是PyTorch的格式。


5 load local directory model

使用下述方法可以加载一个本地的模型。

from transformers import AutoModel, AutoProcessor

model = AutoModel.from_pretrained("./my_local_siglip")
processor = AutoProcessor.from_pretrained("./my_local_siglip")


6 使用pipeline进行推理

siglip这个模型本身不支持输出图片的标签。它只支持输入图片和文本,计算他们的相似度。

如果要输出标签,自己设计一些标签,为图片和每个标签计算相似度。取相似度达标的作为标签。

from transformers import pipeline
from PIL import Image

# 加载你本地的模型,指定任务为零样本图像分类
classifier = pipeline(
    "zero-shot-image-classification",
    model="./my_local_siglip"  # 指向你的本地目录
)

# 准备图片和候选标签
image = Image.open("2.png")
candidate_labels = ["一只猫", "一架飞机", "一个遥控器", "一只狗", "乌龟"]

# 进行预测
results = classifier(image, candidate_labels=candidate_labels)

# 打印结果(按置信度从高到低)
for result in results:
    print(f"标签: {result['label']}, 置信度: {result['score']:.2%}")


2.png是一个乌龟,计算后输出

D:\>python siglip.py

[transformers] Model config: bos_token_id must be `None` or an integer within the vocabulary (between 0 and 31999), got 49406. This may result in unexpected behavior.

[transformers] Model config: eos_token_id must be `None` or an integer within the vocabulary (between 0 and 31999), got 49407. This may result in unexpected behavior.

Loading weights: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 792/792 [00:01<00:00, 595.95it/s]

标签: 乌龟, 置信度: 95.14%

标签: 一只猫, 置信度: 0.35%

标签: 一只狗, 置信度: 0.21%

标签: 一架飞机, 置信度: 0.03%

标签: 一个遥控器, 置信度: 0.01%


7 手动推理

调用model的能力

import torch
from PIL import Image
from transformers import AutoProcessor, AutoModel
from transformers.image_utils import ChannelDimension

model = AutoModel.from_pretrained("./my_local_siglip").eval()
processor = AutoProcessor.from_pretrained("./my_local_siglip")

image = Image.open("2.jpg")
texts = ["一张猫的照片", "一张狗的照片", "一张风景照", "乌龟"]

# 关键:padding 和 max_length 按照官方建议设置
inputs = processor(
    text=texts, images=image,
    padding="max_length", max_length=64,
    return_tensors="pt"
)

with torch.no_grad():
    outputs = model(**inputs)

# 计算概率
probs = torch.sigmoid(outputs.logits_per_image)

for i, text in enumerate(texts):
    print(f"'{text}' 的概率:{probs[0][i]:.2%}")


结果

D:\>python siglip2_manual.py

[transformers] Model config: bos_token_id must be `None` or an integer within the vocabulary (between 0 and 31999), got 49406. This may result in unexpected behavior.

[transformers] Model config: eos_token_id must be `None` or an integer within the vocabulary (between 0 and 31999), got 49407. This may result in unexpected behavior.

Loading weights: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 792/792 [00:02<00:00, 339.18it/s]

'一张猫的照片' 的概率:0.32%

'一张狗的照片' 的概率:0.18%

'一张风景照' 的概率:0.10%

'乌龟' 的概率:81.00%


它的概率算出来和pipeline不同,是因为计算方式有点小差异。


Copyright © linuxdev.cc 2017-2024. Some Rights Reserved.