baidu/Unlimited-OCR-2

Hugging Face Models Trending 模型

摘要

百度发布 Unlimited-OCR-2,借助 SR-SWA(稀疏参考滑动窗口注意力)在有限上下文窗口内实现超长乃至无界文档解析,并同步推出 MarathonDocBench 超长文档解析基准。

任务:图像文本转文本 标签:transformers、safetensors、unlimited-ocr、特征提取、百度、视觉语言、光学字符识别、自定义代码、图像文本转文本、多语言、arxiv:2606.23050、许可证:mit、地区:美国
查看原文
查看缓存全文

缓存时间: 2026/10/28 01:28

baidu/Unlimited-OCR-2 · Hugging Face 来源:https://huggingface.co/baidu/Unlimited-OCR-2 百度公司 — GitHub (https://github.com/baidu/Unlimited-OCR)Hugging Face (https://huggingface.co/baidu/Unlimited-OCR-2) arXiv (https://huggingface.co/baidu/Unlimited-OCR-2/blob/main/Unlimited-OCR-2.pdf)在 Twitter 上关注 (https://x.com/Baidu_Inc) ### 开创 OCR-3.0 时代:从长程解析到无限程解析。Unlimited OCR 2 概览 ## https://huggingface.co/baidu/Unlimited-OCR-2#release发布动态 - [2026/10/27] 📊 我们发布了MarathonDocBench (https://huggingface.co/datasets/baidu/MarathonDocBench),一个用于超长文档解析的新基准 - [2026/10/27] 🤝 感谢 ModelScope 社区 (https://github.com/modelscope)的支持。我们的模型现已上线 ModelScope (https://modelscope.cn/models/PaddlePaddle/Unlimited-OCR-2)。- [2026/10/27] 🤝 感谢百度智能云团队的支持。我们的模型现已上线百度智能云 (https://cloud.baidu.com/doc/OCR/s/fmr1p39gb)。- [2026/10/27] 🤝 感谢 AK (https://x.com/akhaliq)为我们创建了新的演示。欢迎在 Unlimited-OCR-2 (https://huggingface.co/spaces/baidu/Unlimited-OCR-2)体验。- [2026/10/27] 🚀 我们发布了Unlimited OCR 2 (https://github.com/baidu/Unlimited-OCR),通过 SR-SWA 实现无限程解析。- [2026/07/21] 🤝 感谢 ms-swift 社区 (https://github.com/modelscope/ms-swift)的支持,我们的模型现已支持使用 ms-swift (https://github.com/modelscope/ms-swift)进行训练。- [2026/07/03] 🤝 感谢百度智能云团队的支持。我们的模型现已上线百度智能云 (https://cloud.baidu.com/doc/OCR/s/fmr1p39gb)。- [2026/06/28] 🤝 感谢 vLLM 社区 (https://github.com/vllm-project/vllm)和 Tianyu Guo (https://github.com/gty111)的支持,我们的模型现已支持 vLLM 推理。- [2026/06/24] 🤝 感谢 AK (https://x.com/akhaliq)为我们创建了演示。现已在 Hugging Face Spaces (https://huggingface.co/spaces/baidu/Unlimited-OCR)上线。- [2026/06/23] 📄 我们的论文现已在 arXiv (https://arxiv.org/abs/2606.23050)上线。- [2026/06/23] 🤝 感谢 ModelScope 社区 (https://github.com/modelscope)的支持。我们的模型现已上线 ModelScope (https://modelscope.cn/models/PaddlePaddle/Unlimited-OCR)。- [2026/06/22] 🚀 我们推出 Unlimited-OCR (https://github.com/baidu/Unlimited-OCR/tree/UnlimitedOCR1.0),旨在让 Deepseek-OCR (https://github.com/deepseek-ai/DeepSeek-OCR)更进一步。## https://huggingface.co/baidu/Unlimited-OCR-2#whats-new-in-2第 2 版的新特性 - 稀疏参考滑动窗口注意力 (SR-SWA):将超长序列中的文本与视觉注意力交互压缩为一组固定大小的工作参考信息 (例如,512 个词元)。这使计算复杂度受到约束,无论文档多长,每一步解码的延迟和内存占用都保持近乎恒定。- 从长程解析到无限程解析:在 SR-SWA 的支持下,Unlimited-OCR 2 能在有限的上下文窗口内实现真正无界的文档解析,有效消除文档增长带来的注意力计算量二次增长和内存瓶颈。- 超长文档解析达到最先进水平:在数十页文档基准 (例如 MPDocBench) 和极端的百页文档基准 (例如 MarathonDocBench) 上均达到最先进的性能。Unlimited OCR 2 性能 ## https://huggingface.co/baidu/Unlimited-OCR-2#inference推理 > Unlimited OCR 2 支持Transformers(原生支持,适合快速测试) 和SGLang(推荐用于部署服务)。### https://huggingface.co/baidu/Unlimited-OCR-2#transformersTransformers 已在 NVIDIA A800-80GB 上使用 Python 3.10、torch==2\.13\.0、transformers==4\.52\.1、huggingface\-hub==0\.36\.0、tokenizers==0\.21\.4 进行测试:pip install torch==2.13.0 torchvision pillow transformers==4.52.1 huggingface-hub==0.36.0 \ tokenizers==0.21.4 addict==2.4.0 einops==0.8.2 easydict==1.13 加载模型一次:import torch from transformers import AutoModel, AutoTokenizer model_name = "baidu/Unlimited-OCR-2" tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) model = AutoModel.from_pretrained(model_name, trust_remote_code=True, use_safetensors=True, torch_dtype=torch.bfloat16).eval().cuda() 多页推理(infer\_multi)。在一次请求中解析文档的所有页面,以便模型利用跨页上下文。请按页面顺序传入页面图像:pages = [f"your_doc/page_{i}.jpg" for i in range(1, 8)] text, num_tokens = model.infer_multi(tokenizer, image_files=pages, output_path="output/multi", save_results=True) 提示词会自动构建为"" \* num\_pages \+ "Multi page parsing\.",每页均编码为一个全局视图 (base 模式)。对于每个输入页面,输出都包含一个,顺序与`image\_files`相同。**单页推理**\(`infer`\)。默认情况下,单页使用动态分块 \(gundam 模式\) 进行编码: text = model.infer(tokenizer, image_file=“your_doc/page_1.jpg”, output_path=“output/single”, save_results=True) ### https://huggingface.co/baidu/Unlimited-OCR-2#sglangSGLang 配置环境 \(使用 uv 管理的虚拟环境,Python 3\.10\),安装定制的 SGLang wheel 包`sglang\-0\.5\.20\.dev10\+g8d62f5fb9c\-py3\-none\-any\.whl`,以及用于将 PDF 转换为图像的 PyMuPDF: uv venv –python 3.10 source .venv/bin/activate uv pip install wheel/sglang-0.5.20.dev10+g8d62f5fb9c-py3-none-any.whl uv pip install pymupdf==1.27.2.2 uv pip install fastokens==0.3.2 启动 SGLang 服务器: # 针对超长文档的页面窗口调度(复用上一个窗口末尾的 KV)。export SGLANG_UOCR_EANABLE_DOC_LIMIT=1 # 1 = 启用,0 = 整篇文档放在一个窗口中 export SGLANG_UOCR_DOC_GUNDAM_PAGE_WINDOW=10 # 每个窗口的页数(gundam 模式)export SGLANG_UOCR_DOC_BASE_PAGE_WINDOW=10 # 每个窗口的页数(base 模式)export SGLANG_UOCR_MAX_PAGE_TOKENS=20000 # 每页输出上限;必须 > 0 # SAM 注意力偏置的分块大小上限。内置默认值(512)允许单次 # 分配约 462 MiB,可能导致内存不足;64 的效果相同,但峰值占用更低。export SGLANG_OPT_UOCR_SAM_REL_POS_BIAS_MB=64 # 通过 /dev/shm 传递大型裁剪张量,而不是将它们 pickle 序列化到 # 分词器 -> 调度器的消息帧中。export SGLANG_UOCR_SHM_WRAP_MODEL_DATA=1 export SGLANG_UOCR_SHM_WRAP_MIN_MB=1 export SGLANG_VLM_CACHE_SIZE_MB=0 # 减少大块连续内存分配时因碎片化导致的失败。export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True python -m sglang.launch_server \ –model-path baidu/Unlimited-OCR-2 \ –served-model-name Unlimited-OCR-2 \ –chat-template unlimited-ocr \ –tokenizer-backend fastokens \ –tokenizer-worker-num 8 \ –mem-fraction-static 0.7 \ –max-running-requests 64 \ –max-prefill-tokens 2048 \ –enable-custom-logit-processor \ –enable-streaming-session \ –allow-auto-truncate \ –disable-radix-cache \ –mm-preprocess-cache-size-mb 0 \ –cuda-graph-backend-decode full –cuda-graph-max-bs-decode 64 \ –cuda-graph-backend-prefill full \ –cuda-graph-max-bs-prefill 16384 \ –cuda-graph-bs-prefill 1024 2048 \ –cuda-graph-config ‘{“prefill”: {“backend”: “full”, “full_prefill_max_req”: 64}}’ \ –host 0.0.0.0 \ –port 10000 对影响内存的关键参数的说明:- `\-\-mem\-fraction\-static`是为权重 \+ KV 预留的比例。`0\.75`在 32 个及以上并发请求时留下的余量过小;`0\.7`运行稳定。- `\-\-max\-prefill\-tokens`会决定一个形状约为`\[tokens, context/32\]`的临时张量的大小,因此内存占用随其线性增长:`4096 \-\> 2048`可将该峰值减半。- `\-\-cuda\-graph\-bs\-prefill`的最大分桶值必须等于`\-\-max\-prefill\-tokens`。更小的值会让超大批次回退到即时执行模式;更大的值则永远不会被使用,只会浪费图捕获所需的内存。- `\-\-cuda\-graph\-config`中的`full\_prefill\_max\_req`是完整预填充 CUDA 图的请求槽位数。默认值 \(8\) 会导致并发数为 16/32 时回退到即时执行模式。- 更小的页面窗口能降低内存峰值,但会影响跨页合并,因为跨越窗口边界的内容块会失去上下文。若要在一个窗口中解析整篇文档,请设置 \(`SGLANG\_UOCR\_EANABLE\_DOC\_LIMIT=0`\)。向兼容 OpenAI 的 API 发送请求: import base64 import json import os import tempfile import fitz import requests from sglang.srt.sampling.custom_logit_processor import DeepseekOCRNoRepeatNGramLogitProcessor server_url = “http://127.0.0.1:10000” NGRAM_PROCESSOR = DeepseekOCRNoRepeatNGramLogitProcessor.to_str() session = requests.Session() session.trust_env = False def pdf_to_images(pdf_path, dpi=300): doc = fitz.open(pdf_path) tmp_dir = tempfile.mkdtemp(prefix=“pdf_ocr”) mat = fitz.Matrix(dpi / 72, dpi / 72) image_paths = [] for i, page in enumerate(doc): image_path = os.path.join(tmp_dir, f“page{i + 1:04d}.png“) page.get_pixmap(matrix=mat).save(image_path) image_paths.append(image_path) doc.close() return image_paths def encode_image(image_path): ext = os.path.splitext(image_path)[1].lower() mime = “image/jpeg” if ext in (“.jpg”, “.jpeg”) else f“image/{ext.lstrip(‘.’)}“ with open(image_path, “rb”) as f: data = base64.b64encode(f.read()).decode(“utf-8”) return {“type”: “image_url”, “image_url”: {“url”: f“data:{mime};base64,{data}“}} def build_content(image_paths): prompt = “” * len(image_paths) + “Multi page parsing.” return [encode_image(path) for path in image_paths] + [{“type”: “text”, “text”: prompt}] def generate(image_paths, crop_mode=True, tokens_per_page=8000): # 对多页文档使用更大的 n-gram 窗口,与我们的评估设置一致。window_size = 1024 if len(image_paths) > 1 else 128 payload = { “model”: “Unlimited-OCR-2”, “messages”: [{“role”: “user”, “content”: build_content(image_paths)}], # 必须为正数:这是整篇文档的全局输出预算。“max_tokens”: tokens_per_page * len(image_paths), “temperature”: 0, “skip_special_tokens”: False, “images_config”: {“crop_mode”: crop_mode}, # True = gundam(分块),False = base “custom_logit_processor”: NGRAM_PROCESSOR, “custom_params”: { “ngram_size”: 35, “window_size”: window_size, “page_token_id”: 128827, # 标记 ID(= sparse_attention_config.page_token_id)“eos_token_id”: 1, # = config.json 中的 eos_token_id “max_page_tokens”: 20000, # 每页输出上限,<= 0 时禁用页面限制 }, “stream”: True, } response = session.post( f“{server_url}/v1/chat/completions“, headers={“Content-Type”: “application/json”}, data=json.dumps(payload), timeout=6000, stream=True, ) response.raise_for_status() chunks = [] for line in response.iter_lines(decode_unicode=True): if not line or not line.startswith(“data:”): continue data = line[len(“data:”):].strip() if data == “[DONE]”: break event = json.loads(data) choices = event.get(“choices”) or [] # 最后一个数据块仅包含用量信息 if not choices: continue delta = (choices[0].get(“delta”) or {}).get(“content”) or “” if delta: print(delta, end=“”, flush=True) chunks.append(delta) return “”.join(chunks) # 多页:在一次请求中解析文档的所有页面 pages = [f“your_doc/page_{i}.jpg“ for i in range(1, 8)] generate(pages) # 单页 generate([“your_doc/page_1.jpg”]) # PDF generate(pdf_to_images(“your_doc.pdf”, dpi=300)) ## https://huggingface.co/baidu/Unlimited-OCR-2#visualization可视化 无限程解析实测:在一次请求中解析一整本书 \(回放\)。哈利·波特解析回放 (https://huggingface.co/baidu/Unlimited-OCR-2/blob/main/assets/HarryPotter.gif) ## https://huggingface.co/baidu/Unlimited-OCR-2#acknowledgement致谢 我们感谢 Deepseek\-OCR (https://github.com/deepseek-ai/DeepSeek-OCR)、Deepseek\-OCR\-2 (https://github.com/deepseek-ai/DeepSeek-OCR-2)、PaddleOCR (https://github.com/PaddlePaddle/PaddleOCR)提供的宝贵模型和思路,并感谢 SGLang (https://github.com/sgl-project/sglang)提供的服务部署框架。## https://huggingface.co/baidu/Unlimited-OCR-2#citation引用 @misc{yin2026unlimitedocrworks, title={Unlimited OCR Works}, author={Youyang Yin and Huanhuan Liu and YY and Qunyi Xie and Chaorun Liu and Shiqi Yang and Shaohua Wang and Zhanlong Liu and Hao Zou and Jinyue Chen and Shu Wei and Jingjing Wu and Mingxin Huang and Zhen Wu and Guibin Wang and Tengyu Du and Lei Jia}, year={2026}, eprint={2606.23050}, archivePrefix={arXiv}, primaryClass={cs.CV}, url={https://arxiv.org/abs/2606.23050}, } ``

相似文章

baidu/Unlimited-OCR

Hugging Face Models Trending

百度发布了Unlimited-OCR,一种用于一次性长程文档解析的新模型,基于Deepseek-OCR构建。它支持通过Hugging Face Transformers和SGLang进行单图像和多页/PDF解析。