The model generates one compact line per region:
<loc_84><loc_107><loc_912><loc_168><t_handwritten>Приклад рукописного тексту<|next_region|>
Raw <loc_*> coordinates are normalized to 0..1000 ([x1, y1, x2, y2], top-left origin). Valid region types are handwritten, printed, formula (LaTeX), table, annotation, image (empty text), and graph (empty text). The parser parse_karb_output(raw_text, img_w, img_h) scales bounding boxes to absolute pixel coordinates for the input image and converts inline markup tags (<illegible>, <strike>...</strike>, <corr>...</corr>) to RUKOPYS format (example output for a 2000×3000 image):
[ { "bbox": [168.0, 321.0, 1824.0, 504.0], "type": "handwritten", "text": "Приклад рукописного тексту" }]
Evaluation (RUKOPYS v3 Test Set)
Evaluated on the official RUKOPYS v3 test split (382 images, 8,616 regions) with the updated official RUKOPYS evaluation script (v1.1), greedy decoding (temperature=0.0), and target resolution 4,194,304 pixels (min_pixels = max_pixels = 4194304), along with lower long-edge resolution limits for comparison:
Table with columns: Model, Resolution, Composite ↑, Page CER ↓, Region CER ↓, Det F1 ↑, Class Acc ↑| Model | Resolution | Composite ↑ | Page CER ↓ | Region CER ↓ | Det F1 ↑ | Class Acc ↑ |
|---|
| Karb-4B (BF16) | 4.19 MP | 94.55% | 6.53% | 4.83% | 95.42% | 99.07% |
| Karb-4B (4032 px) | 4032 px | 94.43% | 6.78% | 4.75% | 95.25% | 99.15% |
| Karb-4B (2560 px) | 2560 px | 94.37% | 6.80% | 4.91% | 95.36% | 98.81% |
| Karb-4B (2048 px) | 2048 px | 94.19% | 6.97% | 5.20% | 95.20% | 98.99% |
| Karb-4B (1568 px) | 1568 px | 92.13% | 9.63% | 7.56% | 95.01% | 99.14% |
Quantization & Efficiency (RTX 5090, vLLM)
Table with columns: Precision, Weight Size, Min VRAM, Latency, Composite ↑, Page CER ↓| Precision | Weight Size | Min VRAM | Latency | Composite ↑ | Page CER ↓ |
|---|
| BF16 (16-bit) | 7.51 GiB | 9.29 GiB | 769 ms/page | 94.55% | 6.53% |
| FP8 (8-bit, W8A8) | 4.18 GiB | 6.01 GiB | 547 ms/page | 94.46% | 6.66% |
| AWQ (4-bit, W4A16) | 2.57 GiB | 4.36 GiB | 602 ms/page | 94.33% | 6.78% |
Inference
Use Transformers ≥ 5.8.1 (or a recent vLLM build supporting Qwen3.5). Keep the exact SYSTEM_PROMPT unchanged and observe two critical settings:
skip_special_tokens=False — required so <loc_*> and <t_*> tokens are not stripped.
4,194,304 pixel budget (4096 * 32 * 32) — recommended for best results; ensures consistent 4.19 MP scaling (lower pixel budgets may degrade accuracy).
Both generation_config.json (eos_token_id: [23549, 23547] including <|im_end|>) and chat_template.jinja (pre-configured for direct non-thinking output) are set up out of the box, so manual stop_token_ids and enable_thinking=False overrides are no longer required.
Tip (Greedy Decoding Loops): Because inference uses deterministic greedy decoding (temperature=0.0), occasional repetition loops can occur on rare pages (hitting max_tokens / finish_reason == "length"). To avoid quality degradation on such pages, retry with a slight resolution jitter (e.g., ±5% around TARGET_PIXELS).
Shared Prompt & Output Parser
import re MODEL_ID = "Deelle/Karb-4B"TARGET_PIXELS = 4194304 # 4096 * 32 * 32 (4.19 MP) SYSTEM_PROMPT = """You are an expert in Ukrainian handwritten document recognition.Detect ALL text regions in the image and transcribe the text. Output format — one region per line:<loc_X1><loc_Y1><loc_X2><loc_Y2><t_TYPE>TEXT<|next_region|> Rules:- <t_TYPE>: <t_handwritten> | <t_printed> | <t_formula> | <t_table> | <t_annotation> | <t_image> | <t_graph>- box: normalized coordinates 0-1000 encoded as <loc_N> tokens (top-left origin)- Sort regions top-to-bottom, left-to-right- <t_image> / <t_graph> → TEXT is empty- <t_formula> → TEXT is in LaTeX format- Unreadable text → <illegible>- Strikethrough → <strike>word</strike>- Correction → <strike>old</strike><corr>new</corr>""" REGION_TYPES = {"handwritten", "printed", "formula", "table", "annotation", "image", "graph"} def decode_text_tags(text: str) -> str: text = re.sub(r"<strike>(.*?)</strike><corr>(.*?)</corr>", r"~~\1~~{\2}", text) text = re.sub(r"<strike>(.*?)</strike>", r"~~\1~~", text) text = text.replace("<illegible>", "[illegible]") return ( text.replace("<strike>", "~~") .replace("</strike>", "~~") .replace("<corr>", "{") .replace("</corr>", "}") ) def parse_karb_output(raw_text: str, img_w: int, img_h: int) -> list[dict]: if "</think>" in raw_text: raw_text = raw_text.split("</think>")[-1].strip() if "<|im_end|>" in raw_text: raw_text = raw_text.split("<|im_end|>")[0].strip() pattern = re.compile( r"<loc_(\d+)>\s*<loc_(\d+)>\s*<loc_(\d+)>\s*<loc_(\d+)>\s*" r"<t_(.*?)>(.*?)(?=<\|next_region\|>|$)", re.DOTALL, ) regions = [] for m in pattern.finditer(raw_text): x1, y1 = (int(m.group(1)) / 1000.0) * img_w, (int(m.group(2)) / 1000.0) * img_h x2, y2 = (int(m.group(3)) / 1000.0) * img_w, (int(m.group(4)) / 1000.0) * img_h rtype = m.group(5).strip() regions.append({ "bbox": [min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)], "type": rtype if rtype in REGION_TYPES else "handwritten", "text": decode_text_tags(m.group(6).strip()), }) return regions
vLLM (Recommended)
from PIL import Image, ImageOpsfrom transformers import AutoProcessorfrom vllm import LLM, SamplingParams processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)image = ImageOps.exif_transpose(Image.open("document.jpg")).convert("RGB") messages = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": [ {"type": "image"}, {"type": "text", "text": "Transcribe all regions."}, ]},]prompt = processor.apply_chat_template( messages, tokenize=False, add_generation_prompt=True) llm = LLM( model=MODEL_ID, dtype="auto", max_model_len=12288, trust_remote_code=True, limit_mm_per_prompt={"image": 1}, mm_processor_kwargs={"min_pixels": TARGET_PIXELS, "max_pixels": TARGET_PIXELS},) params = SamplingParams( temperature=0.0, max_tokens=4096, skip_special_tokens=False,) outputs = llm.generate( [{"prompt": prompt, "multi_modal_data": {"image": image}}], sampling_params=params,) raw_output = outputs[0].outputs[0].textregions = parse_karb_output(raw_output, image.width, image.height)print(regions[:3])
import torchfrom PIL import Image, ImageOpsfrom transformers import AutoModelForImageTextToText, AutoProcessor processor = AutoProcessor.from_pretrained( MODEL_ID, size={"shortest_edge": TARGET_PIXELS, "longest_edge": TARGET_PIXELS}, trust_remote_code=True,)device = "cuda" if torch.cuda.is_available() else "cpu"model = AutoModelForImageTextToText.from_pretrained( MODEL_ID, dtype="auto", trust_remote_code=True,).to(device) image = ImageOps.exif_transpose(Image.open("document.jpg")).convert("RGB")messages = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": [ {"type": "image"}, {"type": "text", "text": "Transcribe all regions."}, ]},]prompt = processor.apply_chat_template( messages, tokenize=False, add_generation_prompt=True)inputs = processor(text=[prompt], images=[image], return_tensors="pt").to(model.device) with torch.inference_mode(): output_ids = model.generate(**inputs, max_new_tokens=4096, do_sample=False) new_tokens = output_ids[:, inputs["input_ids"].shape[1]:]raw_output = processor.batch_decode(new_tokens, skip_special_tokens=False)[0]regions = parse_karb_output(raw_output, image.width, image.height)print(regions[:3])
Training Data, Limitations & License
Table with columns: Dataset, Split Used, License| Dataset | Split Used | License |
|---|
| RUKOPYS (v2.2) | Train (Gold) + Silver | CC BY 4.0 |
- Dataset version disclosure: This checkpoint was trained exclusively on RUKOPYS v2.2 (Train Gold + Silver) prior to the v2.3 dataset update, in which the dataset authors removed overlapping/leaking samples from the Silver split (the exact count and IDs of affected test pages were not disclosed by the authors). The test split itself was never used during training. A clean retrained checkpoint on RUKOPYS v3+ is planned as a subsequent release.
- Known limitations: Axis-aligned bounding boxes (AABB) may slightly overlap on heavily skewed or wavy lines; VFTD enforces literal transcription of spelling errors and archaic orthography without auto-correction; general-purpose VQA capabilities were intentionally removed during vocabulary pruning.
- License: Model weights are released under the Apache License 2.0 (inherited from
Qwen/Qwen3.5-4B). Training data is not redistributed.
Citation
@misc{cheshenko2026karb4b, title = {Karb-4B: End-to-End Vision-Language Model for Ukrainian Handwritten Document Recognition}, author = {Cheshenko, Dmytro}, year = {2026}, publisher = {Hugging Face}, howpublished = {\url{https://huggingface.co/Deelle/Karb-4B}}}