Karb-4B Banner

Models Paper GitHub Colab License

Karb-4B-FP8

Quantized variant: This repository provides the 8-bit FP8 (W8A8) quantized checkpoint of Deelle/Karb-4B.

Note: Karb-4B is an experimental model under active research and development. While it shows strong results on Ukrainian handwritten documents, it can still make transcription or layout errors. Please verify outputs for critical tasks and treat this checkpoint as a foundation for further experiments and improvement. Feedback and community experiments are welcome.

Karb-4B visual examples

Karb-4B (4.03B parameters) is a specialized fine-tune of Qwen3.5-4B that performs layout detection, region classification (7 classes), and character-level transcription in a single autoregressive pass.

Available Precisions

  • 16-bit (BF16) (Deelle/Karb-4B) β€” Full-precision checkpoint (7.51 GiB weights)
  • 8-bit (FP8 W8A8) (this repository β€” Deelle/Karb-4B-FP8) β€” Pre-quantized FP8_DYNAMIC checkpoint (4.18 GiB weights, vision encoder preserved in BF16)
  • 4-bit (AWQ W4A16) (Deelle/Karb-4B-AWQ) β€” Pre-quantized symmetric INT4 (group_size=128) checkpoint (2.57 GiB weights, vision encoder preserved in BF16)

Key Modifications

  • Character-level target decomposition & vocabulary pruning: Vocabulary pruned from 248,320 to 24,576 core tokens (24,579 total embedding rows including 1,001 quantized coordinate tokens <loc_0>–<loc_1000>, 7 region-type tokens, markup tags, and multimodal special tokens) with untied embed_tokens / lm_head weights (βˆ’1.70 GiB checkpoint size).
  • Compact structured format: Encodes each region as a flat tuple instead of JSON, reducing output sequence length by ~3.6Γ—.
  • Training recipe: Gaussian KL Loss over the full vocabulary with dynamic Οƒ annealing (2.0 β†’ 1.0), Vision-Forcing Token Dropout (VFTD), Confusable Grapheme Margin Loss (Ξ³ = 2.0), Interline CutMix, and Selective C-AdamW trained in a 7-phase curriculum (1,850 steps on a single RTX 5090).

Output Format

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:

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)

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). For standalone Transformers inference with quantized weights, install compressed-tensors (pip install compressed-tensors); vLLM includes it natively. Keep the exact SYSTEM_PROMPT unchanged and observe two critical settings:

  1. skip_special_tokens=False β€” required so <loc_*> and <t_*> tokens are not stripped.
  2. 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-FP8"
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, ImageOps
from transformers import AutoProcessor
from 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].text
regions = parse_karb_output(raw_output, image.width, image.height)
print(regions[:3])

Transformers

import torch
from PIL import Image, ImageOps
from 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])

Karb-4B Character-Level Recognition

Training Data, Limitations & 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}}
}
Downloads last month
18
Safetensors
Model size
4B params
Tensor type
BF16
Β·
F8_E4M3
Β·
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support

Model tree for Deelle/Karb-4B-FP8

Finetuned
Qwen/Qwen3.5-4B
Finetuned
Deelle/Karb-4B
Quantized
(2)
this model

Dataset used to train Deelle/Karb-4B-FP8

Collection including Deelle/Karb-4B-FP8