Instructions to use Deelle/Karb-4B-FP8 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Deelle/Karb-4B-FP8 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="Deelle/Karb-4B-FP8") 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("Deelle/Karb-4B-FP8") model = AutoModelForMultimodalLM.from_pretrained("Deelle/Karb-4B-FP8", 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 Deelle/Karb-4B-FP8 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Deelle/Karb-4B-FP8" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Deelle/Karb-4B-FP8", "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/Deelle/Karb-4B-FP8
- SGLang
How to use Deelle/Karb-4B-FP8 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 "Deelle/Karb-4B-FP8" \ --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": "Deelle/Karb-4B-FP8", "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 "Deelle/Karb-4B-FP8" \ --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": "Deelle/Karb-4B-FP8", "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 Deelle/Karb-4B-FP8 with Docker Model Runner:
docker model run hf.co/Deelle/Karb-4B-FP8
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 (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 GiBweights) - 8-bit (FP8 W8A8) (this repository β
Deelle/Karb-4B-FP8) β Pre-quantizedFP8_DYNAMICcheckpoint (4.18 GiBweights, vision encoder preserved in BF16) - 4-bit (AWQ W4A16) (
Deelle/Karb-4B-AWQ) β Pre-quantized symmetric INT4 (group_size=128) checkpoint (2.57 GiBweights, 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 untiedembed_tokens/lm_headweights (β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:
skip_special_tokens=Falseβ required so<loc_*>and<t_*>tokens are not stripped.4,194,304pixel 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 (hittingmax_tokens/finish_reason == "length"). To avoid quality degradation on such pages, retry with a slight resolution jitter (e.g., Β±5% aroundTARGET_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])
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
