Image-Text-to-Text
Transformers
Safetensors
Slovenian
English
qwen3_5
multimodal
ocr
slovenian
video-text-to-text
conversational
Instructions to use cjvt/Cvetka-R1-27B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use cjvt/Cvetka-R1-27B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="cjvt/Cvetka-R1-27B") 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 AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("cjvt/Cvetka-R1-27B") model = AutoModelForMultimodalLM.from_pretrained("cjvt/Cvetka-R1-27B", device_map="auto") 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?"} ] }, ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use cjvt/Cvetka-R1-27B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "cjvt/Cvetka-R1-27B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "cjvt/Cvetka-R1-27B", "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/cjvt/Cvetka-R1-27B
- SGLang
How to use cjvt/Cvetka-R1-27B 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 "cjvt/Cvetka-R1-27B" \ --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": "cjvt/Cvetka-R1-27B", "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 "cjvt/Cvetka-R1-27B" \ --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": "cjvt/Cvetka-R1-27B", "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 cjvt/Cvetka-R1-27B with Docker Model Runner:
docker model run hf.co/cjvt/Cvetka-R1-27B
File size: 5,560 Bytes
753087c | 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 | """Transcribe one local page using a downloaded Cvetka-R1-27B export."""
import argparse
import json
import math
import sys
from pathlib import Path
import torch
from PIL import Image, ImageOps
from transformers.models.qwen2_vl.image_processing_qwen2_vl import Qwen2VLImageProcessor, smart_resize
import chat
from gams_micka.cvetka.eval_media import load_model
DOC_MAX_SOFT_TOKENS = 2560
SOFT, OPEN, CLOSE = '⸢IMAGE_SOFT⸥', '⸢IMAGE⸥', '⸢/IMAGE⸥'
LONGSFT_SETTINGS = '04b53ff3a706c8604fa71f95cc312a2d506011a328a124f16aeed4c55d8e2e69'
def prepare(root, page):
tokenizer, template, protocol = chat.load_chat(root)
manifest = json.loads((root / 'export_manifest.json').read_bytes())
digest = (LONGSFT_SETTINGS if manifest['stage'] == 'longsft-anchor'
else manifest['files']['cvetka_processor_config.json'])
settings = json.loads(chat.read_checked(root, 'cvetka_processor_config.json', digest))
marks = settings['controls']
for mark, token_id in marks.items():
if tokenizer.encode(mark, add_special_tokens=False) != [token_id]:
raise ValueError(f'image processor and tokenizer disagree on {mark}')
patch, merge = settings['patch_size'], settings['merge_size']
factor = patch * merge
bounds = dict(shortest_edge=settings['image_size']['shortest_edge'],
longest_edge=DOC_MAX_SOFT_TOKENS * factor**2)
processor = Qwen2VLImageProcessor(
patch_size=patch, temporal_patch_size=settings['temporal_patch_size'], merge_size=merge,
image_mean=settings['image_mean'], image_std=settings['image_std'], size=bounds,
)
with Image.open(page) as source:
pixels = ImageOps.exif_transpose(source).convert('RGB')
height, width = smart_resize(pixels.height, pixels.width, factor=factor,
min_pixels=bounds['shortest_edge'], max_pixels=bounds['longest_edge'])
features = processor(images=[pixels], return_tensors='pt')
grid = features['image_grid_thw']
if grid.tolist() != [[1, height // patch, width // patch]]:
raise ValueError('processed image grid differs from the document geometry')
cells = math.prod(grid[0].tolist()) // merge**2
parts = [{'type': 'image'}, {'type': 'text', 'text': '\nPrepiši samo besedilo na sliki.'}]
prompt = tokenizer.apply_chat_template(
[{'role': 'user', 'content': parts}], chat_template=template, tokenize=False,
add_generation_prompt=True, enable_thinking=False, preserve_thinking=True,
)
marker = OPEN + SOFT + CLOSE
if prompt.count(marker) != 1:
raise ValueError('the serving template must contain one framed image placeholder')
ids = tokenizer.encode(prompt.replace(marker, OPEN + SOFT * cells + CLOSE), add_special_tokens=False)
index = ids.index(marks[OPEN])
if (ids[:1] != [tokenizer.bos_token_id] or ids.count(marks[SOFT]) != cells
or ids[index:index+cells+2] != [marks[OPEN], *[marks[SOFT]] * cells, marks[CLOSE]]):
raise ValueError('the image grid and the rendered soft-token slots disagree')
batch = dict(input_ids=torch.tensor([ids]), attention_mask=torch.ones(1, len(ids), dtype=torch.long),
image_grid_thw=grid.long(), pixel_values=features['pixel_values'].to(torch.float16))
batch['mm_token_type_ids'] = batch['input_ids'].eq(marks[SOFT]).int()
return tokenizer, protocol, batch, marks
def transcribe(root, page, device, max_new_tokens):
tokenizer, protocol, batch, marks = prepare(root, page)
net = load_model(root, device=device, dtype=torch.bfloat16).eval()
expected = {'image_token_id': marks[SOFT], 'vision_start_token_id': marks[OPEN],
'vision_end_token_id': marks[CLOSE], 'video_token_id': marks['⸢VIDEO⸥']}
if any(getattr(net.config, k) != v for k, v in expected.items()):
raise ValueError('the model and serving processor disagree on media controls')
count = batch['input_ids'].shape[1]
if count + max_new_tokens > net.config.text_config.max_position_embeddings:
raise ValueError('the page and requested generation exceed the configured context')
batch = {k: v.to(device) for k, v in batch.items()}
stops = protocol['stop_token_ids']
with torch.inference_mode():
seq = net.generate(**batch, do_sample=False, eos_token_id=stops,
suppress_tokens=protocol['suppress_token_ids'],
pad_token_id=tokenizer.pad_token_id, max_new_tokens=max_new_tokens)
new_ids = seq[0, count:].tolist()
stopped = bool(new_ids and new_ids[-1] in stops)
raw = tokenizer.decode(new_ids[:-1] if stopped else new_ids, skip_special_tokens=False)
return chat.visible_answer(raw, False), len(new_ids), stopped
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('model', type=Path)
parser.add_argument('page', type=Path)
parser.add_argument('--device', choices=('cuda', 'cpu'), default='cuda')
parser.add_argument('--max-new-tokens', type=int, default=256)
args = parser.parse_args()
if args.max_new_tokens < 1:
parser.error('a positive generation budget is required')
answer, count, stopped = transcribe(args.model, args.page, args.device, args.max_new_tokens)
if answer:
print(answer)
if not stopped:
print(f'Reached the {count}-token generation limit.', file=sys.stderr)
if not answer:
print('No final transcription was produced.', file=sys.stderr)
if __name__ == '__main__':
main()
|