ARTICLE DETAIL

资讯详情

深耕商务建站与企业官网运营的一线实战洞察。

MLX-VLM 中的 DOTS OCR 实战:文档解析、版面分析与结构化 JSON 提取

MLX-VLM 中的 DOTS OCR 实战:文档解析、版面分析与结构化 JSON 提取 MLX-VLM 中的 DOTS OCR 实战文档解析、版面分析与结构化 JSON 提取【免费下载链接】mlx-vlmMLX-VLM is a package for inference and fine-tuning of Vision Language Models (VLMs) on your Mac using MLX.项目地址: https://gitcode.com/GitHub_Trending/ml/mlx-vlm在 Apple 芯片 Mac 上用 MLX 运行 OCR 与文档解析模型是 MLX-VLM一个基于 MLX 的视觉语言模型推理与微调框架里很实用的一类场景。本文以仓库中的 DOTS OCR 模型文档 为主体完整覆盖dots.ocr/dots.mocr模型的 CLI 用法、Python 脚本写法与配套 Notebook 演示并结合mlx_vlm/models/dots_ocr/目录下的源码实现模型结构、视觉编码器、处理器讲清这套模型在 MLX-VLM 中是如何被加载、组装与调用的读完即可在自己的 Mac 上复现版面 JSON 提取、基础 OCR 与 Markdown 转换三类任务。模型定位DOTS 是什么DOTS 系列是面向文档解析document parsing、版面分析layout analysis与结构化抽取的视觉语言 OCR 模型。仓库文档给出的定位是主要用途OCR、版面解析、表格抽取、公式抽取、结构化 JSON 输出。两个检查点dots.ocr原始的 DOTS OCR 模型dots.mocr在dots.ocr基础上扩展的模型具备更强的多语言解析与结构化图形生成如 SVG能力。对应的模型标识符HF 仓库名在文档示例中为rednote-hilab/dots.mocr与量化版mlx-community/dots.mocr-4bit。MLX-VLM 中该模型由 dots_ocr 模型目录 实现模块导出入口在 mlx_vlm/models/dots_ocr/init.py导出了ModelConfig、TextConfig、VisionConfig、Model、VisionModel、LanguageModel与处理器DotsVLProcessor。安装文档给出的安装方式uv pip install mlx-vlm安装后即可通过mlx_vlm.generateCLI 或 Python API 调用该模型模型权重按--model指定的仓库名自动下载。CLI 实战三类典型任务1) 版面 JSON 提取详细 Prompt这是dots.mocr的招牌用法让模型输出整页版面信息每个元素包含 bbox、类别和文本内容整体是一个 JSON 对象。文档给出的完整命令注意 Prompt 直接内嵌在命令行中uv run mlx_vlm.generate --model rednote-hilab/dots.mocr --prompt Please output the layout information from the PDF image, including each layout elements bbox, its category, and the corresponding text content within the bbox. 1. Bbox format: [x1, y1, x2, y2] 2. Layout Categories: The possible categories are [Caption, Footnote, Formula, List-item, Page-footer, Page-header, Picture, Section-header, Table, Text, Title]. 3. Text Extraction Formatting Rules: - Picture: For the Picture category, the text field should be omitted. - Formula: Format its text as LaTeX. - Table: Format its text as HTML. - All Others (Text, Title, etc.): Format their text as Markdown. 4. Constraints: - The output text must be the original text from the image, with no translation. - All layout elements must be sorted according to human reading order. 5. Final Output: The entire output must be a single JSON object. --image path_to_image.jpg --max-tokens 5000这个 Prompt 的设计要点值得保留bbox 格式固定为[x1, y1, x2, y2]11 种类别枚举Caption、Footnote、Formula、List-item、Page-footer、Page-header、Picture、Section-header、Table、Text、Title按类别分流文本格式图片类省略 text 字段公式输出 LaTeX表格输出 HTML其余输出 Markdown两条硬约束文本必须是图像原文禁止翻译、元素按人类阅读顺序排序最终输出为单一 JSON 对象便于下游程序直接解析。--max-tokens 5000用于覆盖整页密集文本的输出长度。2) 基础 OCR最简单直接的全文字抽取uv run mlx_vlm.generate \ --model rednote-hilab/dots.mocr \ --image receipt.jpg \ --prompt Extract all text from this image. \ --max-tokens 10243) Markdown 文档转换使用 4bit 量化权重做整页转 Markdown保持阅读顺序uv run mlx_vlm.generate \ --model mlx-community/dots.mocr-4bit \ --image page.png \ --prompt Convert this page to clean Markdown while preserving reading order. \ --max-tokens 4096Python API 实战三个脚本示例都遵循同一套模式load加载模型与处理器 →apply_chat_template套用聊天模板 →generate生成。以下按文档原样给出。1)layout_json.py版面 JSON 提取from mlx_vlm import generate, load from mlx_vlm.prompt_utils import apply_chat_template MODEL mlx-community/dots.mocr-4bit IMAGE_PATH path_to_image.jpg PROMPT Please output the layout information from the PDF image, including each layout elements bbox, its category, and the corresponding text content within the bbox. 1. Bbox format: [x1, y1, x2, y2] 2. Layout Categories: The possible categories are [Caption, Footnote, Formula, List-item, Page-footer, Page-header, Picture, Section-header, Table, Text, Title]. 3. Text Extraction Formatting Rules: - Picture: For the Picture category, the text field should be omitted. - Formula: Format its text as LaTeX. - Table: Format its text as HTML. - All Others (Text, Title, etc.): Format their text as Markdown. 4. Constraints: - The output text must be the original text from the image, with no translation. - All layout elements must be sorted according to human reading order. 5. Final Output: The entire output must be a single JSON object. model, processor load(MODEL) formatted_prompt apply_chat_template( processor, model.config, PROMPT, num_images1, ) result generate( modelmodel, processorprocessor, promptformatted_prompt, imageIMAGE_PATH, max_tokens5000, temperature0.0, ) print(result.text)2)basic_ocr.py基础 OCRfrom mlx_vlm import generate, load from mlx_vlm.prompt_utils import apply_chat_template MODEL mlx-community/dots.mocr-4bit IMAGE_PATH receipt.jpg PROMPT Extract all text from this image. model, processor load(MODEL) formatted_prompt apply_chat_template( processor, model.config, PROMPT, num_images1, ) result generate( modelmodel, processorprocessor, promptformatted_prompt, imageIMAGE_PATH, max_tokens1024, temperature0.0, ) print(result.text)3)markdown_document_conversion.pyMarkdown 转换from mlx_vlm import generate, load from mlx_vlm.prompt_utils import apply_chat_template MODEL mlx-community/dots.mocr-4bit IMAGE_PATH page.png PROMPT Convert this page to clean Markdown while preserving reading order. model, processor load(MODEL) formatted_prompt apply_chat_template( processor, model.config, PROMPT, num_images1, ) result generate( modelmodel, processorprocessor, promptformatted_prompt, imageIMAGE_PATH, max_tokens4096, temperature0.0, ) print(result.text)注意三个示例中max_tokens的取值差异版面 JSON 5000、基础 OCR 1024、Markdown 转换 4096——输出长度上限应与任务的内容密度匹配这也是文档 Notes 部分的第一条建议。Notebook 演示dots_mocr_demo.ipynb文档还指向一个完整的交互式演示 examples/dots_mocr_demo.ipynb按文档描述该 Notebook 只用 MLX-VLM 复现了上游dots.mocrREADME 中的全部场景使用仓库自带本地演示素材位于 examples/images避免依赖外网图片会保存原始输出、叠加标注图overlays、渲染后的 SVG 预览与一张拼图总览contact sheet当模型生成的 SVG 非法时Notebook 会回退为可读的文本叠加层而不是直接渲染器报错页其中demo_hf_layout与parser_image_default两个场景因为与主文档解析 run 复用同一张图和同一 PromptNotebook 会写出别名产物alias artifactsSVG 预览渲染在 macOS 上使用qlmanage完成。源码解读DOTS 在 MLX-VLM 中的实现以下结合 mlx_vlm/models/dots_ocr 的源码说明上述命令背后发生的事情。模型配置文本塔 视觉塔config.py 定义了三个 dataclass可看出 DOTS 是一个典型的双塔 VLM 结构TextConfigmodel_typedots_ocr默认hidden_size1536、intermediate_size8960、num_hidden_layers28、num_attention_heads12、num_key_value_heads2即 12 头 Q / 2 头 KV 的 GQA、vocab_size151936、max_position_embeddings131072、rope_theta1000000.0。rope_scaling若提供__post_init__会校验必须含factor/type两个键且type仅支持linear。VisionConfigmodel_typedots_vitembed_dim1536、hidden_size1536、intermediate_size4224、num_hidden_layers42、num_attention_heads12、patch_size14、spatial_merge_size2、temporal_patch_size1、post_normTrue。也就是说视觉编码器有 42 层 Transformer比文本塔还深。ModelConfig聚合text_config/vision_config并定义image_token_id151665、video_token_id151656。from_dict对上游 checkpoint 的配置做了兼容若缺text_config会把顶层字段全部归入text_config仅剔除vision_config若vision_config缺model_type则自动补dots_vit。语言侧默认值与 Qwen2.5 系词表一致vocab_size151936这与其处理器复用 Qwen2.5-VL 体系相呼应见下节。处理器复用 Qwen2.5-VL 的图像预处理processing_dots_ocr.py 中的DotsVLProcessor直接继承transformers的Qwen2_5_VLProcessor关键行为包括图像 token 默认为|imgpad|image_token_id硬编码为151665与ModelConfig.image_token_id对应视频处理器是DotsDummyVideoProcessor——它的__call__直接抛出NotImplementedError(DOTS MLX processors do not support video inputs.)。因此dots_ocr在 MLX-VLM 中仅支持图像输入不支持视频这一点与仓库文档中OCR、文档解析的定位一致from_pretrained会同时加载 tokenizer并尝试从本地目录加载chat_template与 image processoruse_fastFalse失败则回退默认文件末尾install_auto_processor_patch(dots_ocr, DotsVLProcessor)把dots_ocr这个model_type注册进 AutoProcessor 分发使得load()时能按config.json里的model_type找到正确的处理器。在 Prompt 组装层面mlx_vlm/prompt_utils.py 第 62 行将dots_ocr映射为MessageFormat.LIST_WITH_IMAGE_FIRST即图像 token 先于文本出现在消息结构里apply_chat_template(processor, model.config, PROMPT, num_images1)会据此把image占位正确填入聊天模板。模型主体视觉特征如何并入文本嵌入dots_ocr.py 中的Model只做两件事的组合self.vision_tower VisionModel(config.vision_config) self.language_model LanguageModel(config.text_config) # 来自 llava_bunny.language其中语言侧复用了 mlx_vlm/models/llava_bunny/language.py 的LanguageModel视觉侧是dots_ocr/vision.py中的VisionModel。前向时get_input_embeddings的流程是若没有pixel_values退化为纯文本嵌入有图像时要求必须提供image_grid_thw否则抛ValueError并把pixel_values转换为与 patch embed 权重相同的 dtype视觉塔输出图像特征后merge_input_ids_with_image_features静态方法负责把特征塞回文本序列在input_ids中定位所有image_token_id若为 0 个则尝试video_token_id用累积和生成每个图像 token 对应的特征下标按 batch 逐个校验图像 token 位置数 图像特征数不等则抛ValueError最后用mx.where将图像 token 位置的文本嵌入替换为视觉特征。此外还支持cached_image_features关键字参数传入时直接复用缓存的视觉隐状态、跳过视觉塔前向——这与仓库的 vision cache 机制相衔接mlx_vlm/tests/test_vision_cache.py 第 137 行把dots_ocr.dots_ocr列入了覆盖的模型。视觉编码器14×14 patch、2×2 空间合并、2D 旋转位置编码vision.py 中的VisionModel是一条完整的 ViT 流水线Patch 嵌入DotsPatchEmbedConv2d(3, 1536, kernel14, stride14)把图像切成 14×14 的 patch 并映射到 1536 维随后过RMSNorm2D 旋转位置编码VisionRotaryEmbeddingget_pos_ids_by_grid按image_grid_thw为每个 patch 计算 (h, w) 二维位置 id注意位置 id 会先按spatial_merge_size2做 2×2 分组重排使旋转编码与后面的空间合并对齐变长序列打包cu_seqlens多张图的 patch 序列被拼接后用累积序列长度数组切分VisionAttention内部按cu_seqlens逐段调用mx.fast.scaled_dot_product_attention保证跨图 patch 之间互不干扰42 个DotsVisionBlockRMSNorm → 注意力 → 残差 → RMSNorm → SwiGLU FFNfc1/fc2/fc3三线性层silu(fc1(x)) * fc3(x)→ 残差输出端post_normTrue时过post_trunk_norm再过PatchMerger——它先做 LayerNorm再按spatial_merge_size2把相邻 2×24 个 patch 特征拼成一个 6144 维向量经两层线性层夹 GELU投影回 1536 维即最终送入语言模型的每合并块特征。VisionModel.sanitize还处理了权重形状兼容patch_embed.patchifier.proj.weight若非 NCHW 布局会自动transpose(0, 2, 3, 1)并跳过position_ids类键——这是为兼容上游 checkpoint 布局而做的权重清洗。Model.sanitize则负责键名改写model.vision_tower.*→vision_tower.*model.*→language_model.model.*lm_head.*→language_model.model.lm_head.*。加载链路load()到dots_ocr.Model从源码结构看load()内部通过 mlx_vlm/encoder_loader.py 的load_encoder_model完成装配读取config.json得到model_typedots_ocr经get_model_and_args定位到mlx_vlm.models.dots_ocr模块调用ModelConfig.from_dict(config)构造配置再依次用Model、VisionModel、LanguageModel三个模块做权重清洗sanitize_weights。若config.json含quantization字段会对满足weight.size % 64 0且存在.scales键的模块调用nn.quantize完成量化权重反量化/量化装配——这正是mlx-community/dots.mocr-4bit这类 4bit checkpoint 能直接load运行的机制。测试印证mlx_vlm/tests/test_models.py 的test_dots_ocr用缩小尺寸hidden_size64、2 层、patch_size14、spatial_merge_size2构造TextConfig/VisionConfig/ModelConfig实例化dots_ocr.Model并验证语言塔行为与pixel_values(4, 3*14*14)、image_grid_thw[[1, 2, 2]]的视觉前向路径mlx_vlm/tests/test_processors.py 的TestDotsVLProcessor约第 945 行起验证DotsVLProcessor的构造与from_pretrained行为第 3718 行附近还将dots_ocr→DotsVLProcessor的 AutoProcessor 注册关系纳入断言。使用建议Notes 原文与补充文档 Notes 部分给出的两条建议长文档与版面密集的页面调大--max-tokens三个示例分别用了 5000 / 1024 / 4096若需要严格的结构化输出Prompt 中必须显式声明 schema 与排序规则即上面版面 JSON 示例中第 2、4、5 条的写法。结合源码可以补充三点实操注意输入仅限图像。处理器中的DotsDummyVideoProcessor会主动拒绝视频输入不要把dots.ocr/dots.mocr当视频理解模型用temperature0.0适合结构化任务。文档所有 Python 示例都使用temperature0.0对版面 JSON 这类需要严格 schema 的输出贪心解码更稳定图像数量由apply_chat_template的num_images声明。单页文档传num_images1多图场景按实际张数调整模型会依据image_grid_thw与图像 token 数量做严格校验数量不匹配会直接报错。小结DOTS OCR 在 MLX-VLM 中的形态是一个Qwen 系语言塔 42 层自研 ViT 视觉塔的图像 OCR 模型处理器复用 Qwen2.5-VL 的图像预处理链路视觉特征经 14×14 patch 化与 2×2 空间合并后按image_token_id位置注入文本嵌入。对使用者而言只需掌握mlx_vlm.generate的三个 CLI 模式版面 JSON、基础 OCR、Markdown 转换与对应的 Python 三段式调用load→apply_chat_template→generate再参考 examples/dots_mocr_demo.ipynb 的完整演示即可在 Mac 上完成从扫描页到结构化文档的解析管线。【免费下载链接】mlx-vlmMLX-VLM is a package for inference and fine-tuning of Vision Language Models (VLMs) on your Mac using MLX.项目地址: https://gitcode.com/GitHub_Trending/ml/mlx-vlm创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表
PREV
查看更多资讯
NEXT
返回资讯列表