Image-Text-to-Text
Transformers
Safetensors
piccolo_qwen3_5_loop
feature-extraction
conversational
custom_code
Instructions to use agentscope-ai/Piccolo-2B-VL with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use agentscope-ai/Piccolo-2B-VL with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="agentscope-ai/Piccolo-2B-VL", trust_remote_code=True) messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("agentscope-ai/Piccolo-2B-VL", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use agentscope-ai/Piccolo-2B-VL with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "agentscope-ai/Piccolo-2B-VL" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "agentscope-ai/Piccolo-2B-VL", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker
docker model run hf.co/agentscope-ai/Piccolo-2B-VL
- SGLang
How to use agentscope-ai/Piccolo-2B-VL with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "agentscope-ai/Piccolo-2B-VL" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "agentscope-ai/Piccolo-2B-VL", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "agentscope-ai/Piccolo-2B-VL" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "agentscope-ai/Piccolo-2B-VL", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }' - Docker Model Runner
How to use agentscope-ai/Piccolo-2B-VL with Docker Model Runner:
docker model run hf.co/agentscope-ai/Piccolo-2B-VL
File size: 6,188 Bytes
b08dbc3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | """Frozen Piccolo request processor for text and image candidate scoring."""
from collections.abc import Mapping
from dataclasses import dataclass
import torch
from PIL import Image
from transformers.feature_extraction_utils import BatchFeature
from transformers.models.qwen3_vl.processing_qwen3_vl import Qwen3VLProcessor
from .common_inputs import (
JevRequest,
PreparedDecision,
PreparedRequest,
prepare_decision,
prepare_request,
)
from .common_media import EncodedImages, encode_prompt, prompt_encoding_kwargs
from .piccolo_images import load_request_images, map_unique_images, normalize_image
from .piccolo_ocr import DETECTOR_ID, MAX_IMAGE_PIXELS, RECOGNIZER_ID, TorchOCR
@dataclass
class EncodedDecision:
question_id: str
option_keys: tuple[str, ...]
inputs: BatchFeature
class PiccoloProcessor(Qwen3VLProcessor):
@staticmethod
def load_ocr(detector=DETECTOR_ID, recognizer=RECOGNIZER_ID, *, device="cpu"):
"""Load the optional OCR backend from local directories or the local Hub cache."""
return TorchOCR(detector, recognizer, device=device)
def __init__(
self,
image_processor=None,
tokenizer=None,
video_processor=None,
chat_template=None,
max_length=None,
**kwargs,
):
super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template)
self.max_length = self.tokenizer.model_max_length if max_length is None else max_length
if type(self.max_length) is not int or self.max_length <= 0:
raise ValueError("max_length must be a positive integer")
def __call__(self, payload=None, *, question_key=None, **kwargs):
if isinstance(payload, dict) and "questions" in payload:
ocr = kwargs.pop("ocr", None)
if kwargs.pop("return_tensors", "pt") != "pt" or kwargs:
raise ValueError('Decision encoding accepts only return_tensors="pt"')
if question_key is None:
if len(payload["questions"]) != 1:
raise ValueError(
"Select question_key or use encode_request for multiple questions"
)
question_key = next(iter(payload["questions"]))
return self.encode_question(payload, question_key, ocr=ocr).inputs
if payload is not None:
kwargs["text"] = payload
return super().__call__(**kwargs)
def encode_request(
self,
payload: JevRequest | PreparedRequest,
*,
images: Mapping[str, Image.Image] | None = None,
ocr: TorchOCR | Mapping[str, str] | None = None,
) -> list[EncodedDecision]:
"""Encode questions in order, optionally reusing images keyed by asset ID."""
return self._encode_questions(payload, None, images, ocr)
def encode_question(
self,
payload: JevRequest | PreparedRequest,
question_key: str,
*,
images: Mapping[str, Image.Image] | None = None,
ocr: TorchOCR | Mapping[str, str] | None = None,
) -> EncodedDecision:
"""Encode one question from a raw request or reuse its prepared data."""
return self._encode_questions(payload, (question_key,), images, ocr)[0]
def _encode_questions(self, payload, question_keys, images, ocr):
request = payload if isinstance(payload, PreparedRequest) else prepare_request(payload)
keys = request.payload["questions"] if question_keys is None else question_keys
decisions = [prepare_decision(request, key) for key in keys]
kwargs = prompt_encoding_kwargs(self)
asset_order = decisions[0].prompt.asset_order
if images is None:
images = load_request_images(request.image_sources)
images, ocr_texts = self.prepare_media({key: images[key] for key in asset_order}, ocr=ocr)
if images:
pixels = self.image_processor(images=list(images.values()), **kwargs["images_kwargs"])
else:
pixels = {}
encoded_images = EncodedImages(asset_order, pixels)
return [
self._encode_decision(decision, encoded_images, kwargs["text_kwargs"], ocr_texts)
for decision in decisions
]
def prepare_media(self, images, *, ocr=None):
"""Normalize decoded images and resolve OCR, sharing pixels when the limits agree."""
if not images:
return images, None if isinstance(ocr, TorchOCR) else ocr
limit = self.image_processor.size["longest_edge"]
normalized = map_unique_images(images, lambda image: normalize_image(image, limit))
if isinstance(ocr, TorchOCR):
ocr = ocr.recognize(normalized if limit == MAX_IMAGE_PIXELS else images)
return normalized, ocr
def _encode_decision(self, decision: PreparedDecision, images: EncodedImages, text_kwargs, ocr_texts):
encoded = encode_prompt(
self,
decision,
pixels=images.for_order(decision.prompt.asset_order),
text_kwargs=text_kwargs,
ocr_texts=ocr_texts,
)
tokens = encoded["input_ids"][0].tolist()
if not tokens or len(tokens) > self.max_length:
raise ValueError("Piccolo prompt exceeds max_length; no truncation")
ids = [
self.tokenizer.convert_tokens_to_ids(candidate.label)
for candidate in decision.candidates
]
if len(set(ids)) != len(ids) or any(
self.tokenizer.encode(candidate.label, add_special_tokens=False) != [token_id]
for candidate, token_id in zip(decision.candidates, ids, strict=True)
):
raise ValueError("Piccolo candidates must be distinct single-token labels")
encoded["mm_token_type_ids"] = torch.tensor(self.create_mm_token_type_ids([tokens]))
encoded["candidate_token_ids"] = torch.tensor([ids], dtype=torch.long)
option_keys = tuple(candidate.key for candidate in decision.candidates)
return EncodedDecision(decision.prompt.question_key, option_keys, BatchFeature(encoded))
PiccoloProcessor.register_for_auto_class()
|