Image-Text-to-Text
Transformers
Joblib
Safetensors
English
qwen3_5
ocr
pdf
markdown
document-parsing
tables
charts
parsebench
autoround
w4a16
gptq
llm-compressor
compressed-tensors
quantized
vllm
conversational
Eval Results
4-bit precision
auto-round
Run this model with HF Jobs
Run OpenTensorLab/OCRia-1-W4A16-AutoRound on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/OpenTensorLab/OCRia-1-W4A16-AutoRound. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/OpenTensorLab/OCRia-1-W4A16-AutoRound on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/OpenTensorLab/OCRia-1-W4A16-AutoRound. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Instructions to use OpenTensorLab/OCRia-1-W4A16-AutoRound with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use OpenTensorLab/OCRia-1-W4A16-AutoRound with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="OpenTensorLab/OCRia-1-W4A16-AutoRound") 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("OpenTensorLab/OCRia-1-W4A16-AutoRound") model = AutoModelForMultimodalLM.from_pretrained("OpenTensorLab/OCRia-1-W4A16-AutoRound", 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 OpenTensorLab/OCRia-1-W4A16-AutoRound with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "OpenTensorLab/OCRia-1-W4A16-AutoRound" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "OpenTensorLab/OCRia-1-W4A16-AutoRound", "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/OpenTensorLab/OCRia-1-W4A16-AutoRound
- SGLang
How to use OpenTensorLab/OCRia-1-W4A16-AutoRound 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 "OpenTensorLab/OCRia-1-W4A16-AutoRound" \ --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": "OpenTensorLab/OCRia-1-W4A16-AutoRound", "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 "OpenTensorLab/OCRia-1-W4A16-AutoRound" \ --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": "OpenTensorLab/OCRia-1-W4A16-AutoRound", "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 OpenTensorLab/OCRia-1-W4A16-AutoRound with Docker Model Runner:
docker model run hf.co/OpenTensorLab/OCRia-1-W4A16-AutoRound
Vishva R commited on
Update model weights, configs, and auxiliary files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .eval_results/parsebench-2.yamlAdded+32
- .eval_results/parsebench.yamlAdded+28
- .gitattributes+9
- LICENSEAdded+73
- assets/boxes_table_texas.jpgAdded
- assets/chart_line_output.pngAdded
- assets/chart_line_page.jpgAdded
- assets/format_hearing_output.pngAdded
- assets/format_hearing_page.jpgAdded
- assets/handwritten_math_output.pngAdded
- assets/handwritten_math_page.jpgAdded
- assets/llamaindex-logo.pngAdded
- assets/ocria1_radar.pngAdded
- assets/table_texas_output.pngAdded
- assets/table_texas_page.jpgAdded
- chat_template.jinjaAdded+154
- config.jsonAdded+632
- examples/boxes.pyAdded+76
- examples/serve_boxes.pyAdded+86
- fast_layout_models/manifest.jsonAdded+11
- fast_layout_models/peaks.joblibAdded+3
- fast_layout_models/pictures.joblibAdded+3
- fast_layout_models/regions.joblibAdded+3
- fast_layout_models/tables.joblibAdded+3
- fast_layout_models/words.joblibAdded+3
- generation_config.jsonAdded+9
- model-00001-of-00002.safetensorsAdded+3
- model-00002-of-00002.safetensorsAdded+3
- model.safetensors.index.jsonAdded+988
- ocria_grounding/__init__.pyAdded+76
- ocria_grounding/align.pyAdded+123
- ocria_grounding/blocks.pyAdded+227
- ocria_grounding/boxes.pyAdded+390
- ocria_grounding/capture.pyAdded+103
- ocria_grounding/detector.pyAdded+44
- ocria_grounding/geometry.pyAdded+90
- ocria_grounding/ground.pyAdded+415
- ocria_grounding/heads.jsonAdded+10
- ocria_grounding/heads.pyAdded+16
- ocria_grounding/layout.pyAdded+258
- ocria_grounding/pdf.pyAdded+59
- ocria_grounding/regions.pyAdded+165
- ocria_grounding/tune.pyAdded+5
- ocria_grounding/words.pyAdded+32
- parse_rl_utils/ocria_attention_grounding/__init__.pyAdded+4
- parse_rl_utils/ocria_attention_grounding/api.pyAdded+155
- parse_rl_utils/ocria_attention_grounding/blocks.pyAdded+289
- parse_rl_utils/ocria_attention_grounding/boxes.pyAdded+61
- parse_rl_utils/ocria_attention_grounding/bullet_tables.pyAdded+63
- parse_rl_utils/ocria_attention_grounding/coarse.pyAdded+159
1234567891011121314151617181920212223242526272829303132- dataset: id: llamaindex/ParseBench-2 task_id: overall value: 85.24 source: url: https://github.com/run-llama/ParseBench name: parse-bench notes: "Pipeline name: ocria_1 (dataset revision 2d9a2344, parse-bench 2.2.1)"- dataset: id: llamaindex/ParseBench-2 task_id: text value: 87.87- dataset: id: llamaindex/ParseBench-2 task_id: formatting value: 91.59- dataset: id: llamaindex/ParseBench-2 task_id: tables value: 86.28- dataset: id: llamaindex/ParseBench-2 task_id: charts value: 77.63- dataset: id: llamaindex/ParseBench-2 task_id: layout value: 85.96- dataset: id: llamaindex/ParseBench-2 task_id: forms value: 82.0912345678910111213141516171819202122232425262728- dataset: id: llamaindex/ParseBench task_id: mean value: 84.65 source: url: https://github.com/run-llama/ParseBench name: parse-bench notes: "Pipeline name: ocria_1 (dataset revision 2805a1d9, parse-bench 2.2.1)"- dataset: id: llamaindex/ParseBench task_id: table value: 91.8- dataset: id: llamaindex/ParseBench task_id: chart value: 82.47- dataset: id: llamaindex/ParseBench task_id: text_content value: 90.27- dataset: id: llamaindex/ParseBench task_id: text_formatting value: 85.5- dataset: id: llamaindex/ParseBench task_id: layout value: 73.2332 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373839404142434432 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textassets/boxes_table_texas.jpg filter=lfs diff=lfs merge=lfs -textassets/chart_line_page.jpg filter=lfs diff=lfs merge=lfs -textassets/format_hearing_output.png filter=lfs diff=lfs merge=lfs -textassets/format_hearing_page.jpg filter=lfs diff=lfs merge=lfs -textassets/handwritten_math_page.jpg filter=lfs diff=lfs merge=lfs -textassets/ocria1_radar.png filter=lfs diff=lfs merge=lfs -textassets/table_texas_output.png filter=lfs diff=lfs merge=lfs -textassets/table_texas_page.jpg filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 OCRia-1 MODEL AND CODE LICENSE
Licensor: LlamaIndex, Inc.Based on the AI Pubs Open RAIL-M License, Version 0.1, March 2, 2023 (http://licenses.ai/), as modified below.
LICENSING INQUIRIES: Anyone interested in licensing the Model or the Licensed Code, including for uses that Attachment A restricts, may contact LlamaIndex at https://www.llamaindex.ai/contact. This notice does not change the terms below.
PLEASE READ THESE TERMS CAREFULLY BEFORE USING THE MODEL, THE LICENSED CODE OR A DERIVATIVE WORK OF EITHER MADE AVAILABLE IN CONNECTION WITH THESE TERMS. BY DOWNLOADING, REPRODUCING, DISTRIBUTING OR USING THE MODEL, THE LICENSED CODE OR A DERIVATIVE WORK OF EITHER IN ANY MANNER, YOU (“YOU”) AGREE TO BE BOUND BY THESE TERMS (THE “AGREEMENT”) TO THE EXCLUSION OF ALL OTHER TERMS. YOU REPRESENT AND WARRANT THAT YOU HAVE THE AUTHORITY TO ENTER INTO THIS AGREEMENT; IF YOU ARE ENTERING INTO THIS AGREEMENT ON BEHALF OF AN ORGANIZATION OR ENTITY, REFERENCES TO AND “YOU” IN THIS AGREEMENT, REFER TO THAT ORGANIZATION OR ENTITY. IF YOU DO NOT AGREE TO ALL OF THE FOLLOWING, YOU MAY NOT DOWNLOAD, REPRODUCE, DISTRIBUTE OR USE THE MODEL, THE LICENSED CODE OR A DERIVATIVE WORK OF EITHER IN ANY MANNER. Section I: PREAMBLEThis OpenRAIL-M License, as modified, is generally applicable to any machine-learning Model.The “Open” nomenclature indicates that the licensed Model is freely accessible to downstream and other users. The “RAIL” nomenclature indicates that there are use restrictions prohibiting the use of the Model. These restrictions are intended to avoid potential misuse. This License specifies that the use restrictions in the original License must apply to such derivatives. As modified, this License also covers the Licensed Code that Licensor distributes with the Model, on the same terms as the Model (see paragraph 1A).NOW THEREFORE, You and Licensor agree as follows:1. Definitions(a) “Complementary Material” means the applicable source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, and any related information, if any. Complementary Material is not licensed under this License, except for the Licensed Code, which is.(b) "Contribution" means any work, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model by the rights owner or by an individual or legal entity authorized to submit on behalf of the rights owner. For the purposes of this definition, “submitted” means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the rights owner as "Not a Contribution."(c) "Contributor" means Licensor and any individual or legal entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model.(d) “Data” means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.(e) “Derivatives of the Model” means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.(f) “Distribution” means any transmission, reproduction, publication, distribution, or other sharing of the Licensed Materials to a third party, including providing the Model or the Licensed Code as a hosted service made available by electronic or other remote means, including but not limited to API-based or web access.(g) “Harm” includes but is not limited to physical, mental, psychological, financial and reputational damage, pain, or loss(h) "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.(i) “Licensor” means LlamaIndex, Inc., the rights owner of the Model, together with any entity authorized by it to distribute the Model.(j) “Model” means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.(k) “Output” means the results of operating a Model or the Licensed Code as embodied in informational content resulting therefrom, including transcriptions and layout boxes.(l) “Third Parties” means individuals or legal entities that are not under common control with Licensor or You.(m) "You" (or "Your") means an individual or legal entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application, including but not limited to a chatbot, translator, or image generator.(n) “Research Purposes” means (i) non-commercial research, teaching and study, including at academic and non-profit institutions; (ii) evaluating or benchmarking the Model, by any person or organization, including publishing the results; and (iii) internal research and development that does not use the Model, its Derivatives or its Output in a product, service or production workflow offered to or used for third parties or for Your business operations.(o) “Competing Service” means any product or service, including any API, hosted service or software, that offers document parsing, optical character recognition, or extraction of text, tables, charts or fields from documents, and that competes with any product or service offered by Licensor or its affiliates, including LlamaParse and LlamaCloud.(p) “Licensed Code” means the source code, and the configuration and data files it reads, that Licensor distributes together with the Model under this License, in source or compiled form, including the files in the `ocria_grounding` directory of the repository in which Licensor publishes the Model (the code that derives layout boxes from the Model’s attention, and its selection of attention heads), and any other file Licensor marks as licensed under this License.(q) “Derivatives of the Licensed Code” means any modification of the Licensed Code, any work based on or derived from the Licensed Code, including a translation or port of it to another programming language or framework, and any software that incorporates the Licensed Code in whole or in part.(r) “Licensed Materials” means the Model, Derivatives of the Model, the Licensed Code and Derivatives of the Licensed Code.1A. Licensed Code. Every grant, condition, use-based restriction and other provision of this License that applies to the Model applies equally to the Licensed Code, and every provision that applies to Derivatives of the Model applies equally to Derivatives of the Licensed Code. In particular, the Licensed Code may be used, reproduced, modified and Distributed only as this License permits for the Model, and the use-based restrictions of Attachment A, including its revenue and funding thresholds and the Competing Service restriction, apply to the Licensed Code and to its Output. The Licensed Code is not open-source software. Section II: INTELLECTUAL PROPERTY RIGHTSBoth copyright and patent grants may apply to the Model and Derivatives of the Model. The Model and Derivatives of the Model are subject to additional terms as described in Section III, which shall govern the use of the Model and Derivatives of the Model even in the event Section II is held unenforceable.2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Model and Derivatives of the Model.3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and/or Derivatives of the Model where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Model or Derivatives of the Model to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model or Derivative of the Model and/or a Contribution incorporated within the Model or Derivative of the Model constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Derivative of the Model shall terminate as of the date such litigation is asserted or filed.Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION4. Distribution and Redistribution. You may host the Model or Derivatives of the Model for remote access by Third Parties, including but not limited to software-as-a-service, reproduce, or Distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the conditions in this Section III:(a) Use-based restrictions in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (for example, a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model and Derivatives of the Model are subject to paragraph 5;(b) You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;(c) You must cause any modified files to carry prominent notices stating that You changed the files; and(d) You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model or Derivatives of the Model.You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions, consistent with paragraph 4.a., for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Accordingly, You cannot use the Model or the Derivatives of the Model in violation of such restrictions. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, fine-tuning, updating, running, training, evaluating and/or re-parametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph 5.6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are solely responsible for the Output you generate and its subsequent uses. No use of the Output can contravene any provision as stated in the License.7. Attribution. In connection with any use or Distribution of any Model or Derivatives of the Model, You agree to give appropriate credit and attribution to Licensor, provide a link to the original Model or Derivatives of the Model, provide a copy of this License, and identify any changes You have made to the Model or Derivatives of the Model (collectively, the “Attribution”). The Attribution must not suggest endorsement by any Licensor.8. Share-a-Like. As a condition to the license and authorizations herein, You agree to apply this License (to the exclusion of all others) to any and all copies of the Model, Derivatives of the Model, and any changes or improvements to the Model or Derivatives of the Model. This paragraph does not apply to Output, except that Output may not be used to create a Derivative of the Model (for example, by distillation) other than for Research Purposes.Section IV: OTHER PROVISIONS9. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License, update the Model through electronic means, or cause modification to the Output resulting from updates to the Model based.10. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors.11. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model and Derivatives of the Model, and assume any risks associated with Your exercise of permissions under this License.12. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.13. Accepting Warranty or Additional Liability. While Distributing the Model or Derivatives of the Model, You may choose to charge a fee in exchange for support, warranty, indemnity, or other obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor or Licensor, and only if You agree to indemnify, defend, and hold each Contributor and the Licensor harmless for any liability incurred by, or claims asserted against, such Contributor or Licensor by reason of your accepting any such warranty or additional liability.14. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.END OF TERMS AND CONDITIONS
Attachment AUSE RESTRICTIONSAs conditions to the Licenses set forth in this Agreement, You agree not to use, reproduce, modify, create or Distribute the Licensed Materials or Output (collectively, “Use”) in any of the following ways:1. Legal:(a) In any way that violates any applicable national, federal, state, local or international law or regulation; or(b) to directly or indirectly infringe or misappropriate any third party intellectual property rights (including those of Licensor or any Contributor)2. Commercial:(a) for any purpose if You (your employer, or the entity you are affiliated with) generated more than two million US Dollars ($2,000,000) in gross revenue in the prior year, except where Your Use is limited to personal use or Research Purposes;(b) for any purpose if You (your employer, or the entity you are affiliated with) has raised more than two million US dollars ($2,000,000) in total equity or debt funding from any source, except where Your Use is limited to personal use or Research Purposes; or(c) to provide, or as part of, a Competing Service, whatever Your revenue or funding, except for Research Purposes.Anyone interested in licensing the Model or the Licensed Code, including commercial and broader use licenses for the uses restricted above, may contact LlamaIndex at: https://www.llamaindex.ai/contact
Attachment BTHIRD-PARTY NOTICEThe Model is a fine-tuned derivative of Qwen3.5-4B (https://huggingface.co/Qwen/Qwen3.5-4B) by the Qwen team, Alibaba Cloud, licensed under the Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0). The Apache License, Version 2.0 continues to govern the Qwen3.5-4B materials as provided by their authors.The Licensed Code uses, but does not include, third-party libraries (including PyTorch, Hugging Face Transformers, NumPy, SciPy, Pillow and pypdfium2), each governed by its own license.The Licensed Code downloads and runs, but does not include, the Docling Heron layout detector (https://huggingface.co/docling-project/docling-layout-heron), licensed under the Apache License, Version 2.0, which continues to govern it.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154{%- set image_count = namespace(value=0) %}{%- set video_count = namespace(value=0) %}{%- macro render_content(content, do_vision_count, is_system_content=false) %} {%- if content is string %} {{- content }} {%- elif content is iterable and content is not mapping %} {%- for item in content %} {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} {%- if is_system_content %} {{- raise_exception('System message cannot contain images.') }} {%- endif %} {%- if do_vision_count %} {%- set image_count.value = image_count.value + 1 %} {%- endif %} {%- if add_vision_id %} {{- 'Picture ' ~ image_count.value ~ ': ' }} {%- endif %} {{- '<|vision_start|><|image_pad|><|vision_end|>' }} {%- elif 'video' in item or item.type == 'video' %} {%- if is_system_content %} {{- raise_exception('System message cannot contain videos.') }} {%- endif %} {%- if do_vision_count %} {%- set video_count.value = video_count.value + 1 %} {%- endif %} {%- if add_vision_id %} {{- 'Video ' ~ video_count.value ~ ': ' }} {%- endif %} {{- '<|vision_start|><|video_pad|><|vision_end|>' }} {%- elif 'text' in item %} {{- item.text }} {%- else %} {{- raise_exception('Unexpected item type in content.') }} {%- endif %} {%- endfor %} {%- elif content is none or content is undefined %} {{- '' }} {%- else %} {{- raise_exception('Unexpected content type.') }} {%- endif %}{%- endmacro %}{%- if not messages %} {{- raise_exception('No messages provided.') }}{%- endif %}{%- if tools and tools is iterable and tools is not mapping %} {{- '<|im_start|>system\n' }} {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }} {%- for tool in tools %} {{- "\n" }} {{- tool | tojson }} {%- endfor %} {{- "\n</tools>" }} {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }} {%- if messages[0].role == 'system' %} {%- set content = render_content(messages[0].content, false, true)|trim %} {%- if content %} {{- '\n\n' + content }} {%- endif %} {%- endif %} {{- '<|im_end|>\n' }}{%- else %} {%- if messages[0].role == 'system' %} {%- set content = render_content(messages[0].content, false, true)|trim %} {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} {%- endif %}{%- endif %}{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}{%- for message in messages[::-1] %} {%- set index = (messages|length - 1) - loop.index0 %} {%- if ns.multi_step_tool and message.role == "user" %} {%- set content = render_content(message.content, false)|trim %} {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %} {%- set ns.multi_step_tool = false %} {%- set ns.last_query_index = index %} {%- endif %} {%- endif %}{%- endfor %}{%- if ns.multi_step_tool %} {{- raise_exception('No user query found in messages.') }}{%- endif %}{%- for message in messages %} {%- set content = render_content(message.content, true)|trim %} {%- if message.role == "system" %} {%- if not loop.first %} {{- raise_exception('System message must be at the beginning.') }} {%- endif %} {%- elif message.role == "user" %} {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {%- set reasoning_content = '' %} {%- if message.reasoning_content is string %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- if '</think>' in content %} {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %} {%- set content = content.split('</think>')[-1].lstrip('\n') %} {%- endif %} {%- endif %} {%- set reasoning_content = reasoning_content|trim %} {%- if loop.index0 > ns.last_query_index %} {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} {%- for tool_call in message.tool_calls %} {%- if tool_call.function is defined %} {%- set tool_call = tool_call.function %} {%- endif %} {%- if loop.first %} {%- if content|trim %} {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- else %} {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- endif %} {%- else %} {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- endif %} {%- if tool_call.arguments is defined %} {%- for args_name, args_value in tool_call.arguments|items %} {{- '<parameter=' + args_name + '>\n' }} {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} {{- args_value }} {{- '\n</parameter>\n' }} {%- endfor %} {%- endif %} {{- '</function>\n</tool_call>' }} {%- endfor %} {%- endif %} {{- '<|im_end|>\n' }} {%- elif message.role == "tool" %} {%- if loop.previtem and loop.previtem.role != "tool" %} {{- '<|im_start|>user' }} {%- endif %} {{- '\n<tool_response>\n' }} {{- content }} {{- '\n</tool_response>' }} {%- if not loop.last and loop.nextitem.role != "tool" %} {{- '<|im_end|>\n' }} {%- elif loop.last %} {{- '<|im_end|>\n' }} {%- endif %} {%- else %} {{- raise_exception('Unexpected message role.') }} {%- endif %}{%- endfor %}{%- if add_generation_prompt %} {{- '<|im_start|>assistant\n' }} {%- if enable_thinking is defined and enable_thinking is false %} {{- '<think>\n\n</think>\n\n' }} {%- else %} {{- '<think>\n' }} {%- endif %}{%- endif %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632{ "architectures": [ "Qwen3_5ForConditionalGeneration" ], "bos_token_id": null, "dtype": "float32", "eos_token_id": 248046, "image_token_id": 248056, "model_type": "qwen3_5", "pad_token_id": 248044, "text_config": { "attention_bias": false, "attention_dropout": 0.0, "attn_output_gate": true, "bos_token_id": null, "dtype": "float32", "eos_token_id": 248044, "full_attention_interval": 4, "head_dim": 256, "hidden_act": "silu", "hidden_size": 2560, "initializer_range": 0.02, "intermediate_size": 9216, "layer_types": [ "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention" ], "linear_conv_kernel_dim": 4, "linear_key_head_dim": 128, "linear_num_key_heads": 16, "linear_num_value_heads": 32, "linear_value_head_dim": 128, "mamba_ssm_dtype": "float32", "max_position_embeddings": 262144, "mlp_only_layers": [], "model_type": "qwen3_5_text", "mtp_num_hidden_layers": 1, "mtp_use_dedicated_embeddings": false, "num_attention_heads": 16, "num_hidden_layers": 32, "num_key_value_heads": 4, "pad_token_id": null, "partial_rotary_factor": 0.25, "rms_norm_eps": 1e-06, "rope_parameters": { "mrope_interleaved": true, "mrope_section": [ 11, 11, 10 ], "partial_rotary_factor": 0.25, "rope_theta": 10000000, "rope_type": "default" }, "tie_word_embeddings": true, "use_cache": true, "vocab_size": 248320 }, "tie_word_embeddings": true, "transformers_version": "5.3.0", "video_token_id": 248057, "vision_config": { "deepstack_visual_indexes": [], "depth": 24, "dtype": "float32", "hidden_act": "gelu_pytorch_tanh", "hidden_size": 1024, "in_channels": 3, "initializer_range": 0.02, "intermediate_size": 4096, "model_type": "qwen3_5", "num_heads": 16, "num_position_embeddings": 2304, "out_hidden_size": 2560, "patch_size": 16, "spatial_merge_size": 2, "temporal_patch_size": 2 }, "vision_end_token_id": 248054, "vision_start_token_id": 248053, "quantization_config": { "bits": 4, "data_type": "int", "group_size": 32, "sym": true, "amp": true, "batch_size": 2, "low_gpu_mem_usage": false, "nsamples": 512, "scale_dtype": "torch.float16", "seqlen": 4096, "iters": 1000, "lr": 0.001, "minmax_lr": 0.001, "enable_minmax_tuning": true, "enable_norm_bias_tuning": false, "enable_quanted_input": true, "gradient_accumulate_steps": 4, "autoround_version": "0.17.0", "block_name_to_quantize": "model.language_model.layers", "quant_method": "auto-round", "packing_format": "auto_round:auto_gptq", "extra_config": { "model.language_model.layers.0.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.0.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.0.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.0.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.0.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.1.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.1.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.1.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.1.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.1.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.2.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.2.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.2.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.2.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.2.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.4.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.4.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.4.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.4.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.4.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.5.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.5.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.5.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.5.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.5.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.6.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.6.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.6.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.6.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.6.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.8.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.8.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.8.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.8.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.8.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.9.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.9.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.9.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.9.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.9.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.10.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.10.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.10.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.10.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.10.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.12.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.12.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.12.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.12.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.12.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.13.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.13.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.13.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.13.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.13.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.14.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.14.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.14.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.14.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.14.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.16.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.16.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.16.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.16.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.16.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.17.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.17.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.17.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.17.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.17.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.18.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.18.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.18.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.18.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.18.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.20.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.20.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.20.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.20.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.20.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.21.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.21.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.21.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.21.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.21.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.22.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.22.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.22.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.22.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.22.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.24.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.24.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.24.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.24.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.24.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.25.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.25.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.25.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.25.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.25.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.26.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.26.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.26.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.26.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.26.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.28.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.28.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.28.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.28.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.28.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.29.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.29.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.29.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.29.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.29.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, "model.language_model.layers.30.linear_attn.out_proj": { "bits": 16, "data_type": "float" }, "model.language_model.layers.30.linear_attn.in_proj_qkv": { "bits": 16, "data_type": "float" }, "model.language_model.layers.30.linear_attn.in_proj_z": { "bits": 16, "data_type": "float" }, "model.language_model.layers.30.linear_attn.in_proj_b": { "bits": 16, "data_type": "float" }, "model.language_model.layers.30.linear_attn.in_proj_a": { "bits": 16, "data_type": "float" }, ".*mtp.*": { "bits": 16, "data_type": "float" }, ".*mtp\\.fc.*": { "data_type": "bfloat16" }, ".*linear_attn.*": { "bits": 16, "data_type": "float" }, ".*visual.*": { "bits": 16, "data_type": "float" } } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Transcribe one page with OCRia-1 and draw its layout boxes (experimental).
pip install "transformers==5.22.2" accelerate torchvision timm scipy pypdfium2 huggingface_hub python examples/boxes.py doc.pdf --page 0 # a PDF page: exact word positions from its text layer python examples/boxes.py page.png # an image: word positions from the model's attention python examples/boxes.py page.png --attention-only # no layout detector (less accurate)
Writes <name>.boxes.png and <name>.boxes.json next to the input. Needs a CUDA GPU for OCRia-1; the Heron layoutdetector (docling-project/docling-layout-heron, Apache-2.0) is downloaded from its own repository on first use. Run itfrom a download of this repository (huggingface-cli download llamaindex/OCRia-1 --local-dir OCRia-1); the weights comefrom the Hub (or a local copy: OCRIA_MODEL=/path/to/OCRia-1)."""import argparseimport jsonimport osimport sysimport timefrom pathlib import Path
from PIL import Image, ImageDraw
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # the repository root holds ocria_grounding/from ocria_grounding import MODEL, ground_layout, load, load_detector, load_fast_layout, render_pdf_page, transcribe # noqa: E402
COLORS = {"Section-header": "#d62728", "Title": "#d62728", "Text": "#1f77b4", "List-item": "#2ca02c", "Table": "#ff7f0e", "Picture": "#9467bd", "Caption": "#8c564b", "Footnote": "#8c564b", "Page-header": "#7f7f7f", "Page-footer": "#7f7f7f"}
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("path", help="a PDF or a page image") ap.add_argument("--page", type=int, default=0, help="PDF page index (0-based)") ap.add_argument("--attention-only", action="store_true", help="skip the layout detector") ap.add_argument("--layout", choices=["accurate-layout", "fast-layout"], default="accurate-layout") args = ap.parse_args()
if args.path.lower().endswith(".pdf"): image, words = render_pdf_page(args.path, args.page, dpi=300) else: image, words = Image.open(args.path).convert("RGB"), None g = load(os.environ.get("OCRIA_MODEL", MODEL)) fast = load_fast_layout() if args.layout == "fast-layout" else None det = None if args.attention_only or fast is not None else load_detector() t0 = time.perf_counter() answer = transcribe(g, image) t1 = time.perf_counter() page = ground_layout(g, image, answer, detector=det, words=words if fast is None else None, method=args.layout, fast_backend=fast) t2 = time.perf_counter()
out = image.copy() draw = ImageDraw.Draw(out) width = max(2, image.width // 500) pad = width + 2 # draw outside the box so the outline never covers the first or last letter for it in page["items"]: color = COLORS.get(it["type"], "#17becf") x0, y0, x1, y1 = it["box"] draw.rectangle([x0 - pad, y0 - pad, x1 + pad, y1 + pad], outline=color, width=width) tw, th = draw.textbbox((0, 0), it["type"])[2:] # the type label sits above the box, on a white tab ty = max(0, y0 - pad - th - 2) draw.rectangle([x0 - pad, ty, x0 - pad + tw + 4, ty + th + 2], fill="white") draw.text((x0 - pad + 2, ty), it["type"], fill=color) stem = Path(args.path).with_suffix("") if args.path.lower().endswith(".pdf"): stem = Path(f"{stem}.p{args.page}") out.save(f"{stem}.boxes.png") Path(f"{stem}.boxes.json").write_text(json.dumps({"answer": answer, **page}, indent=1)) print(f"{len(page['items'])} items -> {stem}.boxes.png (transcription {t1 - t0:.1f} s, boxes {t2 - t1:.1f} s)")
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""HTTP server for OCRia-1 layout boxes: transcribe pages anywhere (vLLM, ...), get the boxes here.
pip install "transformers==5.22.2" accelerate torchvision timm scipy pypdfium2 huggingface_hub python examples/serve_boxes.py --port 8100 # loads OCRia-1 (CUDA) and the Heron layout detector
POST /ground {"image_png_b64": ..., "answer": ..., "words": [{"text", "box": [x0, y0, x1, y1]}] | null} -> {"width", "height", "items": [{"type", "label", "md", "box": [x0, y0, x1, y1], "start"}]} GET /health -> {"ok": true}
`image_png_b64` must be the exact page image the answer was generated from, and `answer` the raw answer. `words` arethe page's PDF text-layer words in pixels of that image (`ocria_grounding.pdf.page_words`); pass null for images.Boxes are pixels of the image. One request runs at a time on the GPU; run several servers for throughput."""import argparseimport base64import ioimport jsonimport osimport sysimport threadingfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Path
from PIL import Image
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # the repository root holds ocria_grounding/from ocria_grounding import MODEL, ground_layout, load, load_detector, load_fast_layout # noqa: E402
STATE: dict = {}LOCK = threading.Lock()
class Handler(BaseHTTPRequestHandler): def _send(self, code: int, obj: dict) -> None: body = json.dumps(obj).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body)
def do_GET(self) -> None: # noqa: N802 self._send(200, {"ok": True}) if self.path == "/health" else self._send(404, {"error": "not found"})
def do_POST(self) -> None: # noqa: N802 if self.path != "/ground": return self._send(404, {"error": "not found"}) try: req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0)))) image = Image.open(io.BytesIO(base64.b64decode(req["image_png_b64"]))).convert("RGB") answer = req["answer"] except Exception as e: # malformed request return self._send(400, {"error": f"bad request: {e}"}) try: with LOCK: page = ground_layout(STATE["g"], image, answer, detector=STATE["det"], words=req.get("words"), method=STATE["method"], fast_backend=STATE["fast"]) except Exception as e: return self._send(500, {"error": repr(e)}) self._send(200, page)
def log_message(self, fmt, *args) -> None: # quiet access log pass
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--host", default="0.0.0.0") ap.add_argument("--port", type=int, default=8100) ap.add_argument("--no-detector", action="store_true", help="attention-only boxes (less accurate)") ap.add_argument("--layout", choices=["accurate-layout", "fast-layout"], default="accurate-layout") args = ap.parse_args() STATE["g"] = load(os.environ.get("OCRIA_MODEL", MODEL)) STATE["method"] = args.layout STATE["fast"] = load_fast_layout() if args.layout == "fast-layout" else None STATE["det"] = None if args.no_detector or STATE["fast"] is not None else load_detector() print(f"serving OCRia-1 layout boxes on http://{args.host}:{args.port}", flush=True) ThreadingHTTPServer((args.host, args.port), Handler).serve_forever()
if __name__ == "__main__": main()1234567891011{ "source_commit": "763c56ea11", "frozen": true, "sha256": { "pictures.joblib": "8c3724d22c36e13d6bffebf90f7b1eecc7d2cae12ffd5d17f2de469f013c9d1a", "peaks.joblib": "c6755864b47aad70f5ecc59173a6cd0879f889fc91e6243028617878fa61d5ea", "words.joblib": "1fc131e9dfebe34647e31636a817000c2cfce0c9f6131481a59ee2ac35268b43", "tables.joblib": "ea554fc7b19462b30ec55a925c24fa04c7107c13e72e655593320df07830fe4e", "regions.joblib": "7837010ee75619bc70d07fa79162b6b58a4fab16b49c8f00c9fa2925e0e90329" }}123version https://git-lfs.github.com/spec/v1oid sha256:c6755864b47aad70f5ecc59173a6cd0879f889fc91e6243028617878fa61d5easize 235608123version https://git-lfs.github.com/spec/v1oid sha256:8c3724d22c36e13d6bffebf90f7b1eecc7d2cae12ffd5d17f2de469f013c9d1asize 1374212123version https://git-lfs.github.com/spec/v1oid sha256:7837010ee75619bc70d07fa79162b6b58a4fab16b49c8f00c9fa2925e0e90329size 3047721123version https://git-lfs.github.com/spec/v1oid sha256:ea554fc7b19462b30ec55a925c24fa04c7107c13e72e655593320df07830fe4esize 323350123version https://git-lfs.github.com/spec/v1oid sha256:1fc131e9dfebe34647e31636a817000c2cfce0c9f6131481a59ee2ac35268b43size 2629519123456789{ "_from_model_config": true, "eos_token_id": 248046, "output_attentions": false, "output_hidden_states": false, "pad_token_id": 248044, "transformers_version": "5.24.1", "use_cache": true}123version https://git-lfs.github.com/spec/v1oid sha256:c7fb5defbb448d1576e5aa28abf4cd15dfa3fe0c12505625bbdc7fb7bf92b681size 4982546256123version https://git-lfs.github.com/spec/v1oid sha256:056bf85227fd2ae96e518cc5816b34a670e93abadb2a26c3eb8ce2c247b4aaaesize 1729601144123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988{ "metadata": { "total_parameters": 2616439296, "total_size": 6712026112 }, "weight_map": { "lm_head.weight": "model-00001-of-00002.safetensors", "model.language_model.embed_tokens.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.0.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.0.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.0.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.0.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.0.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.0.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.0.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.0.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.0.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.0.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.0.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.0.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.0.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.0.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.0.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.0.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.0.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.0.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.1.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.1.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.1.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.1.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.1.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.1.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.1.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.1.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.1.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.1.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.1.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.1.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.1.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.1.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.1.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.1.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.1.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.1.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.10.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.10.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.10.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.10.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.10.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.10.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.10.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.10.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.10.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.10.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.10.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.10.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.10.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.10.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.10.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.10.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.10.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.10.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.11.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.11.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.11.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.11.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.11.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.11.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.11.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.11.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.11.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.k_norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.k_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.k_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.k_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.o_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.o_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.o_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.q_norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.q_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.q_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.q_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.v_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.v_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.11.self_attn.v_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.12.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.12.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.12.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.12.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.12.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.12.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.12.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.12.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.12.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.12.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.12.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.12.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.12.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.12.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.12.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.12.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.12.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.12.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.13.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.13.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.13.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.13.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.13.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.13.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.13.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.13.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.13.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.13.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.13.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.13.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.13.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.13.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.13.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.13.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.13.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.13.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.14.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.14.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.14.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.14.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.14.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.14.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.14.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.14.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.14.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.14.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.14.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.14.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.14.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.14.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.14.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.14.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.14.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.14.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.15.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.15.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.15.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.15.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.15.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.15.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.15.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.15.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.15.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.k_norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.k_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.k_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.k_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.o_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.o_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.o_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.q_norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.q_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.q_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.q_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.v_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.v_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.15.self_attn.v_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.16.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.16.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.16.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.16.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.16.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.16.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.16.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.16.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.16.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.16.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.16.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.16.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.16.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.16.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.16.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.16.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.16.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.16.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.17.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.17.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.17.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.17.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.17.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.17.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.17.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.17.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.17.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.17.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.17.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.17.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.17.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.17.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.17.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.17.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.17.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.17.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.18.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.18.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.18.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.18.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.18.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.18.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.18.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.18.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.18.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.18.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.18.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.18.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.18.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.18.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.18.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.18.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.18.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.18.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.19.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.19.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.19.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.19.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.19.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.19.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.19.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.19.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.19.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.k_norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.k_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.k_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.k_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.o_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.o_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.o_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.q_norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.q_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.q_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.q_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.v_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.v_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.19.self_attn.v_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.2.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.2.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.2.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.2.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.2.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.2.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.2.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.2.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.2.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.2.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.2.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.2.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.2.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.2.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.2.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.2.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.2.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.2.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.20.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.20.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.20.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.20.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.20.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.20.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.20.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.20.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.20.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.20.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.20.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.20.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.20.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.20.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.20.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.20.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.20.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.20.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.21.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.21.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.21.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.21.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.21.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.21.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.21.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.21.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.21.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.21.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.21.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.21.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.21.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.21.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.21.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.21.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.21.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.21.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.21.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.21.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.22.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.22.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.22.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.22.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.22.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.22.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.22.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.22.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.22.linear_attn.norm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.22.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.22.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.22.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.22.mlp.down_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.22.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.22.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.22.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.22.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.22.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.22.mlp.up_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.23.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.23.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.23.mlp.down_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.23.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.23.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.23.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.23.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.23.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.23.mlp.up_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.k_norm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.k_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.k_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.k_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.o_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.o_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.o_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.q_norm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.q_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.q_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.q_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.v_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.v_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.23.self_attn.v_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.24.linear_attn.A_log": "model-00002-of-00002.safetensors", "model.language_model.layers.24.linear_attn.conv1d.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.24.linear_attn.dt_bias": "model-00002-of-00002.safetensors", "model.language_model.layers.24.linear_attn.in_proj_a.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.24.linear_attn.in_proj_b.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.24.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.24.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.24.linear_attn.norm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.24.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.24.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.24.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.24.mlp.down_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.24.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.24.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.24.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.24.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.24.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.24.mlp.up_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.25.linear_attn.A_log": "model-00002-of-00002.safetensors", "model.language_model.layers.25.linear_attn.conv1d.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.25.linear_attn.dt_bias": "model-00002-of-00002.safetensors", "model.language_model.layers.25.linear_attn.in_proj_a.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.25.linear_attn.in_proj_b.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.25.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.25.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.25.linear_attn.norm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.25.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.25.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.25.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.25.mlp.down_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.25.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.25.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.25.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.25.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.25.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.25.mlp.up_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.26.linear_attn.A_log": "model-00002-of-00002.safetensors", "model.language_model.layers.26.linear_attn.conv1d.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.26.linear_attn.dt_bias": "model-00002-of-00002.safetensors", "model.language_model.layers.26.linear_attn.in_proj_a.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.26.linear_attn.in_proj_b.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.26.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.26.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.26.linear_attn.norm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.26.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.26.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.26.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.26.mlp.down_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.26.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.26.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.26.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.26.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.26.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.26.mlp.up_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.27.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.27.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.27.mlp.down_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.27.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.27.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.27.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.27.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.27.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.27.mlp.up_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.k_norm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.k_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.k_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.k_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.o_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.o_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.o_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.q_norm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.q_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.q_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.q_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.v_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.v_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.27.self_attn.v_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.28.linear_attn.A_log": "model-00002-of-00002.safetensors", "model.language_model.layers.28.linear_attn.conv1d.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.28.linear_attn.dt_bias": "model-00002-of-00002.safetensors", "model.language_model.layers.28.linear_attn.in_proj_a.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.28.linear_attn.in_proj_b.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.28.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.28.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.28.linear_attn.norm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.28.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.28.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.28.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.28.mlp.down_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.28.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.28.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.28.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.28.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.28.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.28.mlp.up_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.29.linear_attn.A_log": "model-00002-of-00002.safetensors", "model.language_model.layers.29.linear_attn.conv1d.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.29.linear_attn.dt_bias": "model-00002-of-00002.safetensors", "model.language_model.layers.29.linear_attn.in_proj_a.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.29.linear_attn.in_proj_b.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.29.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.29.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.29.linear_attn.norm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.29.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.29.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.29.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.29.mlp.down_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.29.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.29.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.29.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.29.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.29.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.29.mlp.up_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.3.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.3.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.3.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.3.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.3.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.3.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.3.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.3.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.3.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.k_norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.k_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.k_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.k_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.o_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.o_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.o_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.q_norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.q_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.q_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.q_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.v_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.v_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.3.self_attn.v_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.30.linear_attn.A_log": "model-00002-of-00002.safetensors", "model.language_model.layers.30.linear_attn.conv1d.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.30.linear_attn.dt_bias": "model-00002-of-00002.safetensors", "model.language_model.layers.30.linear_attn.in_proj_a.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.30.linear_attn.in_proj_b.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.30.linear_attn.in_proj_qkv.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.30.linear_attn.in_proj_z.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.30.linear_attn.norm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.30.linear_attn.out_proj.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.30.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.30.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.30.mlp.down_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.30.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.30.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.30.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.30.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.30.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.30.mlp.up_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.31.mlp.down_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.31.mlp.down_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.31.mlp.down_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.31.mlp.gate_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.31.mlp.gate_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.31.mlp.gate_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.31.mlp.up_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.31.mlp.up_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.31.mlp.up_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.k_norm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.k_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.k_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.k_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.o_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.o_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.o_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.q_norm.weight": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.q_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.q_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.q_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.v_proj.qweight": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.v_proj.qzeros": "model-00002-of-00002.safetensors", "model.language_model.layers.31.self_attn.v_proj.scales": "model-00002-of-00002.safetensors", "model.language_model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.4.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.4.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.4.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.4.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.4.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.4.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.4.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.4.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.4.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.4.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.4.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.4.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.4.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.4.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.4.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.4.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.4.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.4.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.5.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.5.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.5.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.5.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.5.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.5.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.5.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.5.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.5.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.5.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.5.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.5.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.5.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.5.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.5.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.5.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.5.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.5.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.6.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.6.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.6.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.6.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.6.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.6.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.6.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.6.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.6.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.6.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.6.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.6.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.6.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.6.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.6.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.6.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.6.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.6.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.7.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.7.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.7.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.7.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.7.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.7.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.7.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.7.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.7.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.k_norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.k_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.k_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.k_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.o_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.o_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.o_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.q_norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.q_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.q_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.q_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.v_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.v_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.7.self_attn.v_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.8.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.8.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.8.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.8.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.8.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.8.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.8.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.8.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.8.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.8.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.8.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.8.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.8.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.8.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.8.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.8.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.8.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.8.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.9.linear_attn.A_log": "model-00001-of-00002.safetensors", "model.language_model.layers.9.linear_attn.conv1d.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.9.linear_attn.dt_bias": "model-00001-of-00002.safetensors", "model.language_model.layers.9.linear_attn.in_proj_a.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.9.linear_attn.in_proj_b.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.9.linear_attn.in_proj_qkv.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.9.linear_attn.in_proj_z.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.9.linear_attn.norm.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.9.linear_attn.out_proj.weight": "model-00001-of-00002.safetensors", "model.language_model.layers.9.mlp.down_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.9.mlp.down_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.9.mlp.down_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.9.mlp.gate_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.9.mlp.gate_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.9.mlp.gate_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.9.mlp.up_proj.qweight": "model-00001-of-00002.safetensors", "model.language_model.layers.9.mlp.up_proj.qzeros": "model-00001-of-00002.safetensors", "model.language_model.layers.9.mlp.up_proj.scales": "model-00001-of-00002.safetensors", "model.language_model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors", "model.language_model.norm.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.0.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.0.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.0.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.0.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.0.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.0.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.0.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.0.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.0.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.0.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.0.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.0.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.1.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.1.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.1.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.1.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.1.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.1.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.1.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.1.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.1.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.1.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.1.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.1.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.10.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.10.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.10.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.10.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.10.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.10.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.10.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.10.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.10.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.10.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.10.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.10.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.11.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.11.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.11.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.11.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.11.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.11.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.11.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.11.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.11.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.11.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.11.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.11.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.12.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.12.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.12.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.12.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.12.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.12.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.12.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.12.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.12.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.12.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.12.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.12.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.13.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.13.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.13.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.13.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.13.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.13.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.13.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.13.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.13.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.13.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.13.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.13.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.14.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.14.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.14.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.14.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.14.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.14.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.14.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.14.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.14.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.14.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.14.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.14.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.15.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.15.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.15.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.15.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.15.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.15.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.15.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.15.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.15.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.15.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.15.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.15.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.16.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.16.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.16.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.16.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.16.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.16.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.16.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.16.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.16.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.16.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.16.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.16.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.17.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.17.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.17.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.17.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.17.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.17.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.17.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.17.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.17.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.17.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.17.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.17.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.18.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.18.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.18.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.18.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.18.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.18.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.18.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.18.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.18.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.18.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.18.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.18.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.19.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.19.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.19.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.19.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.19.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.19.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.19.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.19.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.19.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.19.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.19.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.19.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.2.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.2.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.2.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.2.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.2.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.2.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.2.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.2.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.2.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.2.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.2.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.2.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.20.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.20.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.20.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.20.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.20.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.20.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.20.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.20.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.20.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.20.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.20.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.20.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.21.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.21.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.21.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.21.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.21.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.21.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.21.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.21.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.21.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.21.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.21.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.21.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.22.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.22.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.22.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.22.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.22.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.22.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.22.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.22.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.22.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.22.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.22.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.22.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.23.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.23.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.23.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.23.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.23.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.23.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.23.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.23.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.23.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.23.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.23.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.23.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.3.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.3.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.3.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.3.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.3.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.3.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.3.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.3.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.3.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.3.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.3.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.3.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.4.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.4.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.4.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.4.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.4.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.4.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.4.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.4.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.4.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.4.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.4.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.4.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.5.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.5.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.5.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.5.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.5.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.5.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.5.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.5.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.5.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.5.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.5.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.5.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.6.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.6.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.6.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.6.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.6.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.6.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.6.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.6.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.6.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.6.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.6.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.6.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.7.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.7.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.7.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.7.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.7.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.7.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.7.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.7.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.7.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.7.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.7.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.7.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.8.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.8.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.8.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.8.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.8.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.8.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.8.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.8.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.8.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.8.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.8.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.8.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.9.attn.proj.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.9.attn.proj.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.9.attn.qkv.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.9.attn.qkv.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.9.mlp.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.9.mlp.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.9.mlp.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.9.mlp.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.9.norm1.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.9.norm1.weight": "model-00002-of-00002.safetensors", "model.visual.blocks.9.norm2.bias": "model-00002-of-00002.safetensors", "model.visual.blocks.9.norm2.weight": "model-00002-of-00002.safetensors", "model.visual.merger.linear_fc1.bias": "model-00002-of-00002.safetensors", "model.visual.merger.linear_fc1.weight": "model-00002-of-00002.safetensors", "model.visual.merger.linear_fc2.bias": "model-00002-of-00002.safetensors", "model.visual.merger.linear_fc2.weight": "model-00002-of-00002.safetensors", "model.visual.merger.norm.bias": "model-00002-of-00002.safetensors", "model.visual.merger.norm.weight": "model-00002-of-00002.safetensors", "model.visual.patch_embed.proj.bias": "model-00002-of-00002.safetensors", "model.visual.patch_embed.proj.weight": "model-00002-of-00002.safetensors", "model.visual.pos_embed.weight": "model-00002-of-00002.safetensors" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Layout boxes for OCRia-1 answers (experimental).
OCRia-1 writes markdown without boxes. This package places that markdown on the page:
1. A layout detector (Docling's Heron, Apache-2.0, downloaded from its own repository) finds the page's regions.2. Every word of the answer gets a position: its PDF word box when the page has a text layer, else the ink its attention points at, read from a second, teacher-forced pass of the same weights over the page and the answer.3. Each region becomes an item holding the answer's words that fall in it.
from ocria_grounding import load, load_detector, transcribe, ground_layout, render_pdf_page g, det = load(), load_detector() # OCRia-1 (CUDA) and Heron (cuda, else mps, else cpu) image, words = render_pdf_page("doc.pdf", 0) # 300-DPI page + its text-layer words (omit for image inputs) answer = transcribe(g, image) # or the raw answer from any other server (vLLM, ...) page = ground_layout(g, image, answer, detector=det, words=words) # {width, height, items: [{type, label, md, box: [x0, y0, x1, y1], start}]}, boxes in pixels of `image`
Pass exactly the image and system prompt the answer was generated with. `to_layout_items_page` serializes the resultas a ParseBench layout page. Without a detector, `ground_layout` (and the older `ground_page`) fall back to boxesfrom attention alone, which are much less accurate."""from __future__ import annotations
from pathlib import Path
from .detector import DETECTOR, Detectorfrom .ground import ground_page, to_box_markdown, to_layout_pagefrom .heads import heads_forfrom .layout import ground_layout, to_layout_items_pagefrom .pdf import render_pdf_page
MODEL = "llamaindex/OCRia-1"__all__ = ["load_fast_layout", "MODEL", "DETECTOR", "load", "load_detector", "transcribe", "ground_layout", "to_layout_items_page", "render_pdf_page", "Detector", "ground_page", "to_box_markdown", "to_layout_page", "heads_for"]
def load_detector(model: str = DETECTOR, device: str | None = None) -> Detector: """Docling's Heron layout detector (Apache-2.0, a separate download from its own repository).""" return Detector(model, device)
def load(model: str = MODEL, device: str = "cuda", heads=None, system_prompt: str | None = None): """A Grounder for OCRia-1: `model` is the repo id or a local copy of it; the heads and the system prompt default to the ones shipped in this repository (prompt.txt).""" from .capture import Grounder
if system_prompt is None: local = Path(__file__).resolve().parent.parent / "prompt.txt" if not local.exists(): from huggingface_hub import hf_hub_download
local = Path(hf_hub_download(MODEL, "prompt.txt")) system_prompt = local.read_text() return Grounder(model, heads or heads_for(MODEL), system_prompt, device)
def transcribe(grounder, image, max_new_tokens: int = 24576) -> str: """OCRia-1's raw answer for one page image (greedy), from the grounder's own model, so one model load serves both the transcription and the boxes. For throughput, transcribe with vLLM instead and pass its raw answer.""" import torch
enc = grounder.proc(text=[grounder.prompt], images=[image.convert("RGB")], return_tensors="pt").to(grounder.device) with torch.no_grad(): ids = grounder.model.generate(**enc, max_new_tokens=max_new_tokens, do_sample=False) return grounder.proc.decode(ids[0, enc["input_ids"].shape[1]:], skip_special_tokens=True)
def load_fast_layout(model_dir: str | Path | None = None): """Load the five trusted frozen layout artifacts once, without GPU or downloads.""" from parse_rl_utils.ocria_attention_grounding.api import FastLayout
directory = Path(model_dir) if model_dir else Path(__file__).resolve().parent.parent / "fast_layout_models" return FastLayout(**{key: directory / f"{key}.joblib" for key in ("words", "pictures", "regions", "tables", "peaks")})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Answer words -> PDF word boxes, by character-level alignment of the answer with the page's text layer.
PDF text layers split words (kerning), merge them, and store columns and sidebars in another order than the answer.The answer and the PDF text are folded to lowercase alphanumerics and aligned in order; then each long unmatched runof the answer is aligned against the PDF text not used yet, in any order, but only where that text is unique on thepage (a header repeated in several tables would otherwise be matched to the wrong copy)."""import difflibimport unicodedata
def _fold(ch): ch = unicodedata.normalize("NFKC", ch).lower() return "".join(c for c in ch if c.isalnum())
def pdf_chars(words): """Flatten PDF words into (char, box) with each word's box split evenly across its folded chars.""" out = [] for w in words: t = "".join(_fold(c) for c in w["text"]) if not t: continue x0, y0, x1, y1 = w["box"]; n = len(t); dx = (x1 - x0) / n for k, c in enumerate(t): out.append((c, [x0 + k * dx, y0, x0 + (k + 1) * dx, y1])) return out
def unit_boxes(answer, units, words, min_share=0.6, min_block=3): pc = pdf_chars(words) if not pc: return {} ps = "".join(c for c, _ in pc) achars, owner = [], [] for u, (s, e) in enumerate(units): for ch in answer[s:e]: f = _fold(ch) for c in f: achars.append(c); owner.append(u) a = "".join(achars) sm = difflib.SequenceMatcher(None, a, ps, autojunk=False) hit = {} for m in sm.get_matching_blocks(): if m.size < min_block: continue for k in range(m.size): hit.setdefault(owner[m.a + k], []).append(pc[m.b + k][1]) n_by_unit = {} for u in owner: n_by_unit[u] = n_by_unit.get(u, 0) + 1 out = {} for u, bs in hit.items(): if len(bs) < min_share * n_by_unit[u]: continue # keep the chars on the line of the median char (a word never spans lines) ys = sorted((b[1] + b[3]) / 2 for b in bs); ym = ys[len(ys) // 2] h = sorted(b[3] - b[1] for b in bs)[len(bs) // 2] bs = [b for b in bs if abs((b[1] + b[3]) / 2 - ym) <= 0.6 * h] out[u] = [min(b[0] for b in bs), min(b[1] for b in bs), max(b[2] for b in bs), max(b[3] for b in bs)] return out
def unit_boxes_multi(answer, units, words, min_share=0.6, min_block=4, seg_min=8, passes=3, unique=True): """unit_boxes plus out-of-order passes: each long run of unmatched answer chars is aligned against the PDF chars not used yet (used ones masked), so columns / sidebars the PDF stores in another order still get boxes.""" pc = pdf_chars(words) if not pc: return {} pchars = [c for c, _ in pc] achars, owner = [], [] for u, (s, e) in enumerate(units): for ch in answer[s:e]: for c in _fold(ch): achars.append(c); owner.append(u) amatch = [None] * len(achars); pused = [False] * len(pchars)
full = "".join(pchars)
def align(a_lo, a_hi, out_of_order=False): a = "".join(achars[a_lo:a_hi]) p = "".join(c if not pused[k] else "\x00" for k, c in enumerate(pchars)) sm = difflib.SequenceMatcher(None, a, p, autojunk=False) for m in sm.get_matching_blocks(): if m.size < (max(min_block, 8) if out_of_order and unique else min_block): continue if out_of_order and unique and full.count(a[m.a:m.a + m.size]) > 1: continue # repeated text (same header in several tables): the out-of-order pass cannot tell which for k in range(m.size): if amatch[a_lo + m.a + k] is None and not pused[m.b + k]: amatch[a_lo + m.a + k] = m.b + k; pused[m.b + k] = True align(0, len(achars)) for _ in range(passes): segs, k = [], 0 while k < len(achars): if amatch[k] is None: j = k while j < len(achars) and amatch[j] is None: j += 1 if j - k >= seg_min: segs.append((k, j)) k = j else: k += 1 if not segs: break for lo, hi in sorted(segs, key=lambda x: x[0] - x[1]): align(lo, hi, out_of_order=True) hit = {} for i, b in enumerate(amatch): if b is not None: hit.setdefault(owner[i], []).append(pc[b][1]) n_by_unit = {} for u in owner: n_by_unit[u] = n_by_unit.get(u, 0) + 1 out = {} for u, bs in hit.items(): if len(bs) < min_share * n_by_unit[u]: continue ys = sorted((b[1] + b[3]) / 2 for b in bs); ym = ys[len(ys) // 2] h = sorted(b[3] - b[1] for b in bs)[len(bs) // 2] bs = [b for b in bs if abs((b[1] + b[3]) / 2 - ym) <= 0.6 * h] out[u] = [min(b[0] for b in bs), min(b[1] for b in bs), max(b[2] for b in bs), max(b[3] for b in bs)] return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Layout elements of a raw ocria answer: the character spans that each get one box, with a type.
The answer is ocria's no-layout transcription (markdown, HTML tables, `<page_header>`/`<page_footer>`/`<page_number>`furniture tags, `![label: description]` image references, ```mermaid diagrams). Each element becomes one`<!-- bbox: TYPE x0 y0 x1 y1 -->` marker, so the types are the box-mode vocabulary the layout scorer already reads(`layout_score._BOX_TYPE_TO_REGION_LABEL`): text, heading, list, table, image, code, header, footer.
Granularity (one element per ...): paragraph (blank-line separated), heading line, list item (with its indentedcontinuation lines), whole table, image reference, fenced block, display-math block, furniture band. A standalone`<page_number>` gets type "page_number" and is resolved to header/footer from its box (`resolve_page_numbers`).Offsets index the raw answer, fence included, so they line up with the teacher-forced tokens."""from __future__ import annotations
import refrom dataclasses import dataclass
from .tune import FLAGS
_OPEN_FENCE = re.compile(r"\A\s*```(?:markdown|md)?[ \t]*\n")_FURN_OPEN = re.compile(r"<(page_header|page_footer|watermark)>")_PAGE_NUMBER = re.compile(r"^\s*<page_number>.*?</page_number>\s*$")_HEADING = re.compile(r"^\s{0,3}#{1,6}\s")_IMAGE = re.compile(r"^\s*!\[")_FENCE = re.compile(r"^\s*```")_MATH = re.compile(r"^\s*\$\$")_PIPE_ROW = re.compile(r"^\s*\|")_TABLE_OPEN = re.compile(r"<(table|rcl)\b", re.I) # HTML table, or ocria-1.5's RCL grid_LIST_ITEM = re.compile(r"^(\s*)(?:[*\-+•▪◦]\s|\d{1,3}[.)]\s|\(?[a-zA-Z][.)]\s|\[[ xX_]*\]\s)")_BOLD_LINE = re.compile(r"^\s*\*\*[^*]+\*\*:?\s*$")_TYPES_FOR_FURN = {"page_header": "header", "page_footer": "footer", "watermark": "text"}
@dataclassclass Block: type: str start: int end: int
def _lines(text: str, lo: int, hi: int) -> list[tuple[int, int, str]]: """(start, end, line) for each line of text[lo:hi]; end excludes the newline.""" out, pos = [], lo while pos < hi: nl = text.find("\n", pos, hi) end = hi if nl < 0 else nl out.append((pos, end, text[pos:end])) pos = end + 1 return out
def body_span(text: str) -> tuple[int, int]: """The transcription inside the ```markdown fence (the whole answer when there is none).""" lo, hi = 0, len(text) m = _OPEN_FENCE.match(text) if m: lo = m.end() close = text.rfind("```") if close >= lo: hi = close return lo, hi
def _starts_construct(line: str) -> bool: return bool(_HEADING.match(line) or _IMAGE.match(line) or _FENCE.match(line) or _MATH.match(line) or _PIPE_ROW.match(line) or _TABLE_OPEN.search(line) or _FURN_OPEN.search(line) or _PAGE_NUMBER.match(line) or _LIST_ITEM.match(line))
def split_blocks(text: str) -> list[Block]: """Layout elements of one page's raw answer, in reading order.""" lo, hi = body_span(text) lines = _lines(text, lo, hi) blocks: list[Block] = [] i = 0
def until(j: int, pred) -> int: """Index of the first line from j on for which pred holds (the last line when none does).""" while j < len(lines) and not pred(lines[j][2]): j += 1 return min(j, len(lines) - 1)
while i < len(lines): s, e, line = lines[i] if not line.strip(): i += 1 continue m = _FURN_OPEN.search(line) if m: tag = m.group(1) close = f"</{tag}>" j = i if close in line else until(i + 1, lambda x: close in x) blocks.append(Block(_TYPES_FOR_FURN[tag], s, lines[j][1])) i = j + 1 continue if _PAGE_NUMBER.match(line): blocks.append(Block("page_number", s, e)) i += 1 continue tm = _TABLE_OPEN.search(line) if tm: close = "</table>" if tm.group(1).lower() == "table" else "</rcl>" j = i if close in line.lower() else until(i + 1, lambda x: close in x.lower()) if "split_layout_tables" in FLAGS and _is_layout_table(text[s:lines[j][1]]): blocks.extend(_layout_table_blocks(text, s, lines[j][1])) else: blocks.append(Block("table", s, lines[j][1])) i = j + 1 continue if _FENCE.match(line): j = until(i + 1, lambda x: _FENCE.match(x) is not None) kind = "image" if "mermaid" in line.lower() else "code" blocks.append(Block(kind, s, lines[j][1])) i = j + 1 continue if _MATH.match(line): rest = line.strip()[2:] j = i if "$$" in rest else until(i + 1, lambda x: "$$" in x) blocks.append(Block("text", s, lines[j][1])) i = j + 1 continue if _HEADING.match(line): blocks.append(Block("heading", s, e)) i += 1 continue if _IMAGE.match(line): blocks.append(Block("image", s, e)) i += 1 continue if _PIPE_ROW.match(line): j = i while j + 1 < len(lines) and _PIPE_ROW.match(lines[j + 1][2]): j += 1 blocks.append(Block("table", s, lines[j][1])) i = j + 1 continue lm = _LIST_ITEM.match(line) if lm: indent = len(lm.group(1)) j = i while j + 1 < len(lines): nxt = lines[j + 1][2] if not nxt.strip() or _starts_construct(nxt): break if len(nxt) - len(nxt.lstrip()) <= indent: # a continuation line is indented under the marker break j += 1 blocks.append(Block("list", s, lines[j][1])) i = j + 1 continue if "split_lines" in FLAGS: # each line its own element; a bold-only line is a heading blocks.append(Block("heading" if _BOLD_LINE.match(line) else "text", s, e)) i += 1 continue j = i # paragraph: until a blank line or a line that opens another element while j + 1 < len(lines) and lines[j + 1][2].strip() and not _starts_construct(lines[j + 1][2]): j += 1 blocks.append(Block("text", s, lines[j][1])) i = j + 1 if "inline_images" in FLAGS: blocks = [p for b in blocks for p in _split_inline_images(text, b)] return blocks
_INLINE_IMAGE = re.compile(r"!\[[^\]\n]*\](?:\([^)\s]*\))?")
def _split_inline_images(text: str, b: Block) -> list[Block]: """An image reference inside a text-like element (an icon after a heading, a logo next to a footer's page number) is a picture of its own on the page: the element is cut into the text before it, the image, and the text after.""" if b.type in ("image", "table", "code") or "![" not in text[b.start:b.end]: return [b] out, pos = [], b.start for m in _INLINE_IMAGE.finditer(text, b.start, b.end): if _TAGS.sub("", text[pos:m.start()]).strip(" \t\n|*#-"): out.append(Block(b.type, pos, m.start())) out.append(Block("image", m.start(), m.end())) pos = m.end() if _TAGS.sub("", text[pos:b.end]).strip(" \t\n|*#-"): out.append(Block(b.type, pos, b.end)) return out or [b]
def resolve_page_numbers(blocks: list[Block], boxes: list, page_height: float) -> None: """A standalone page number is furniture: header when its box sits in the top half, else footer.""" for b, box in zip(blocks, boxes): if b.type == "page_number": b.type = "header" if box is not None and (box[1] + box[3]) / 2 < page_height / 2 else "footer"
_CELL = re.compile(r"<t[dh][^>]*>(.*?)</t[dh]>", re.S | re.I)_TAGS = re.compile(r"<[^>]+>")
def _is_layout_table(html: str) -> bool: """A table used to lay out a page (people grids, card layouts), not data: it holds image references, or its cells hold prose (mean >= 8 words).""" if "![" in html: return True words = [len(_TAGS.sub(" ", c).split()) for c in _CELL.findall(html) if c.strip()] return bool(words) and sum(words) / len(words) >= 8
def _layout_table_blocks(text: str, lo: int, hi: int) -> list[Block]: """One element per segment of each cell: segments split at blank lines (two or more <br>, or any <br> with split_br), an image reference is its own element.""" sep = re.compile(r"(?:<br\s*/?>\s*)+" if "split_br" in FLAGS else r"(?:<br\s*/?>\s*){2,}", re.I) out: list[Block] = [] for m in _CELL.finditer(text, lo, hi): a, b = m.start(1), m.end(1) pos = a for cut in [*sep.finditer(text, a, b), None]: end = cut.start() if cut else b seg = text[pos:end] if _TAGS.sub("", seg).strip(): k = pos + (len(seg) - len(seg.lstrip())) for im in re.finditer(r"!\[[^\]]*\]", text[k:end]): if text[k:k + im.start()].strip(): out.append(Block("text", k, k + im.start())) out.append(Block("image", k + im.start(), k + im.end())) k = k + im.end() if _TAGS.sub("", text[k:end]).strip(): out.append(Block("text", k, end)) pos = cut.end() if cut else b return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Attention maps -> boxes on the page image (CPU only: numpy, scipy, PIL).
Word boxes (82% of words at IoU >= 0.5 against exact PDF word boxes on held-out pages): the page ink is closed along the line into word blobs, and each word takes the blob near its attention peakthat has the most attention times a width prior from its character count, grown along the line toward that width.
An element's box is the envelope of its words' boxes, after dropping words that sit apart from the element's maincluster (a stray token attending somewhere else must not stretch the box across the page). An image reference has nowords on the page, so its box comes from the attention of its own tokens, snapped to the graphic under the peak."""from __future__ import annotations
import statistics
import numpy as npfrom PIL import Imagefrom scipy import ndimage
from .tune import FLAGS
BIG_FONT = 2.0 # blob height / body glyph height above which a word is set in a larger fontMAX_FONT = 5.0 # taller blobs are frames, rules or graphics, never one line of text
def _u8(a): return a.view(np.uint8) if a.dtype == bool else a.astype(np.uint8)
def dilate(a, shape): """binary_dilation by an all-ones (h, w) rectangle, as two 1D max filters (same output, linear time).""" h, w = shape out = _u8(a) if h > 1: out = ndimage.maximum_filter1d(out, h, axis=0, mode="constant", cval=0, origin=-1 if h % 2 == 0 else 0) if w > 1: out = ndimage.maximum_filter1d(out, w, axis=1, mode="constant", cval=0, origin=-1 if w % 2 == 0 else 0) return out.astype(bool)
def erode(a, shape): """binary_erosion by an all-ones (h, w) rectangle (border counts as background), as two 1D min filters.""" h, w = shape out = _u8(a) if h > 1: out = ndimage.minimum_filter1d(out, h, axis=0, mode="constant", cval=0) if w > 1: out = ndimage.minimum_filter1d(out, w, axis=1, mode="constant", cval=0) return out.astype(bool)
def close(a, shape): """binary_closing by an all-ones (h, w) rectangle.""" return erode(dilate(a, shape), shape)
class Page: """Ink analysis of one rendered page, computed once and shared by every word on it."""
def __init__(self, rgb: np.ndarray, grid: tuple[int, int]): self.h, self.w = rgb.shape[:2] self.gh, self.gw = grid self.cell = (self.w / self.gw, self.h / self.gh) gray = np.asarray(Image.fromarray(rgb).convert("L"), dtype=np.float32) # PIL luma self.ink = gray < min(160.0, float(gray.mean()) - 40.0) if "contrast_ink" in FLAGS: # also light text on a dark local background (white on a coloured panel) k = 8 small = gray[::k, ::k] bg_small = ndimage.median_filter(small, size=int(FLAGS.get("bg_size", "9"))) bg = np.kron(bg_small, np.ones((k, k), np.float32))[:self.h, :self.w] dark_bg = bg < float(FLAGS.get("dark_bg", "120")) self.ink = (self.ink & ~dark_bg) | (dark_bg & (gray > bg + float(FLAGS.get("light_delta", "60")))) # any non-background mark, light colours included: photos, chart fills, shaded boxes sat = rgb.max(-1).astype(np.float32) - rgb.min(-1).astype(np.float32) self.fg = (gray < 235.0) | (sat > 40.0) lab, _ = ndimage.label(self.ink) hs = [s[0].stop - s[0].start for s in ndimage.find_objects(lab) if s is not None] self.line_h = float(statistics.median([x for x in hs if x >= 4] or [10])) closed = close(self.ink, (1, max(3, int(0.45 * self.line_h)))) | self.ink self.lab, n = ndimage.label(closed) self.blobs = [[s[1].start, s[0].start, s[1].stop, s[0].stop] for s in ndimage.find_objects(self.lab)] tall = sorted(b[3] - b[1] for b in self.blobs if b[3] - b[1] >= 4) self.med_h = float(tall[len(tall) // 2] if tall else 10) # long thin or large ink pieces (table rulings, frames, rules): what a table box snaps out to raw = [[s[1].start, s[0].start, s[1].stop, s[0].stop] for s in ndimage.find_objects(lab) if s is not None] big = 4 * self.line_h self.structures = [b for b in raw if b[2] - b[0] > big or b[3] - b[1] > big] self.blob_arr = np.array(self.blobs, dtype=np.float64).reshape(-1, 4) self._fg_lab = None
def fg_components(self): """Labels and slices of the foreground closed by one body line: the graphics an image reference snaps to (computed once per page; every image reference on it reads the same).""" if self._fg_lab is None: k = int(self.line_h) | 1 # a k x k closing fg = close(self.fg, (k, k)) lab, _ = ndimage.label(fg) self._fg_lab = (lab, ndimage.find_objects(lab)) return self._fg_lab
def snap_word(self, m: np.ndarray, n_chars: int) -> list[float] | None: """Box of one word from its attention map (gh x gw): see the module docstring. None when there is no ink around the attention peak: the peak sits on blank paper (often an edge column of the image grid), which says nothing about where the word is, and a cell box there would stretch the element's box to the margin.""" gh, gw = m.shape cw, ch = self.cell py, px = np.unravel_index(int(m.argmax()), m.shape) y0, y1 = int(max(0, (py - 1) * ch)), int(min(self.h, (py + 2) * ch)) x0, x1 = int(max(0, (px - 1) * cw)), int(min(self.w, (px + 2) * cw)) ids = np.unique(self.lab[y0:y1, x0:x1]) ids = ids[ids > 0] n = max(n_chars, 1)
def fit(b): # expected width = characters x half the body glyph height; on a blob clearly taller than body text (a # large heading) its own height, else the heading looks like several short words. Measuring every blob's # own height instead cost 2.3 points of word IoU>=0.5 on the dev pages (ascenders, brackets). bh = float(b[3] - b[1]) ew = n * 0.5 * (bh if BIG_FONT * self.med_h < bh <= MAX_FONT * self.med_h else self.med_h) return abs(np.log(max(b[2] - b[0], 1) / ew))
best, best_s = None, -1.0 for i in ids: b = self.blobs[i - 1] ty0, ty1 = int(b[1] // ch), int(min(gh - 1, (b[3] - 1) // ch)) tx0, tx1 = int(b[0] // cw), int(min(gw - 1, (b[2] - 1) // cw)) s = float(m[ty0:ty1 + 1, tx0:tx1 + 1].sum()) * float(np.exp(-fit(b))) if s > best_s: best, best_s = b, s if best is None: return None b = list(best) A = self.blob_arr while True: # grow along the line while the width gets closer to the expected width h, nxt = b[3] - b[1], None vo = np.minimum(b[3], A[:, 3]) - np.maximum(b[1], A[:, 1]) gap = np.maximum(A[:, 0] - b[2], b[0] - A[:, 2]) for k in np.nonzero((vo >= 0.5 * np.minimum(h, A[:, 3] - A[:, 1])) & (gap >= 0) & (gap <= 0.8 * h))[0]: o = self.blobs[k] nb = [min(b[0], o[0]), min(b[1], o[1]), max(b[2], o[2]), max(b[3], o[3])] if fit(nb) < fit(b) - 1e-6 and (nxt is None or gap[k] < nxt[0]): nxt = (gap[k], nb) if nxt is None: return [float(v) for v in b] b = nxt[1]
def graphic_around(self, box: list[float], max_frac: float = 0.6) -> list[float] | None: """The union of `box` with the graphic it sits on (a chart ocria read as a table: the words are its values and labels, the figure is larger), or None. The graphic is the closed-foreground component that overlaps the box most; it must be larger than the box, under `max_frac` of the page, and filled like a figure (not text).""" lab, sl = self.fg_components() x0, y0, x1, y1 = (int(v) for v in box) ids, counts = np.unique(lab[max(0, y0):y1, max(0, x0):x1], return_counts=True) keep = ids > 0 if not keep.any(): return None i = int(ids[keep][np.argmax(counts[keep])]) s = sl[i - 1] g = [s[1].start, s[0].start, s[1].stop, s[0].stop] ga, ba = (g[2] - g[0]) * (g[3] - g[1]), max((x1 - x0) * (y1 - y0), 1) if ga <= 1.2 * ba or ga > max_frac * self.w * self.h: return None if float(self.fg[s].mean()) < float(FLAGS.get("chart_fill", "0.15")) or float(self.ink[s].mean()) > 0.5: return None return [float(min(box[0], g[0])), float(min(box[1], g[1])), float(max(box[2], g[2])), float(max(box[3], g[3]))]
def image_hot_box(self, m: np.ndarray) -> list[float]: """The attention hot area of an image reference (cells >= 30% of its peak), without snapping to graphics.""" cw, ch = self.cell ys, xs = np.nonzero(m >= 0.3 * float(m.max())) return [float(xs.min() * cw), float(ys.min() * ch), float((xs.max() + 1) * cw), float((ys.max() + 1) * ch)]
def image_box(self, m: np.ndarray) -> list[float]: """Box of an image reference: the graphic (foreground component) under its strongest attention.""" cw, ch = self.cell hot = m >= 0.3 * float(m.max()) ys, xs = np.nonzero(hot) tok = [xs.min() * cw, ys.min() * ch, (xs.max() + 1) * cw, (ys.max() + 1) * ch] lab, sl = self.fg_components() if "exact_image_grid" in FLAGS: # Map pixels back to their cells; rounding cell widths before repeating # accumulates drift toward the bottom/right of non-divisible images. iy = np.arange(self.h) * self.gh // self.h ix = np.arange(self.w) * self.gw // self.w up = hot[iy[:, None], ix[None, :]] else: up = np.kron(hot, np.ones((int(np.ceil(ch)), int(np.ceil(cw))), dtype=bool))[:self.h, :self.w] ids = np.unique(lab[:up.shape[0], :up.shape[1]][up]) ids = ids[ids > 0] if not len(ids): return [float(v) for v in tok] boxes = [[sl[i - 1][1].start, sl[i - 1][0].start, sl[i - 1][1].stop, sl[i - 1][0].stop] for i in ids] # the component that holds most of the attention, plus any other big one inside the hot area mass = [float(m[int(b[1] // ch):int(np.ceil(b[3] / ch)), int(b[0] // cw):int(np.ceil(b[2] / cw))].sum()) for b in boxes] b = boxes[int(np.argmax(mass))] if (b[2] - b[0]) * (b[3] - b[1]) > 0.9 * self.w * self.h: # the closing merged the whole page return [float(v) for v in tok] return [float(v) for v in b]
def snap_table(page: Page, env: list[float]) -> list[float]: """A table box reaches its ruling: the envelope of its words grows to the ruling pieces that touch it and either stay within a few lines of it, or are the table's own grid (covers most of the envelope, at most twice its area). A page-wide rule above a heading or a form's page frame is neither.""" m = 3 * page.line_h lim = [env[0] - m, env[1] - m, env[2] + m, env[3] + m] area = max((env[2] - env[0]) * (env[3] - env[1]), 1.0) box = list(env) for s in page.structures: touches = s[0] < env[2] and s[2] > env[0] and s[1] < env[3] and s[3] > env[1] inside = s[0] >= lim[0] and s[1] >= lim[1] and s[2] <= lim[2] and s[3] <= lim[3] inter = max(0, min(s[2], env[2]) - max(s[0], env[0])) * max(0, min(s[3], env[3]) - max(s[1], env[1])) grid = inter >= 0.6 * area and (s[2] - s[0]) * (s[3] - s[1]) <= 2.0 * area if touches and (inside or grid): box = [min(box[0], s[0]), min(box[1], s[1]), max(box[2], s[2]), max(box[3], s[3])] return [float(v) for v in box]
def _overlap(a0: float, a1: float, b0: float, b1: float) -> float: return max(0.0, min(a1, b1) - max(a0, b0))
def absorb_uncovered_ink(page: Page, boxes: list, can_grow: list[bool], passes: int = 0, line_only: list[bool] | None = None) -> list: """Every word blob on the page that no element box covers joins the nearest element on its line (the label of a form row whose value sits far to the right, a time printed left of an entry, a closing "2)") or on the line just above or below it (the rest of a heading or paragraph), provided no other element's box lies between them. The attention places most words of an element, but the words it misses or that the cluster drops as strays are still the element's ink, and a box that leaves them out cuts the element's content.
Only text-sized blobs count (rulings, frames and graphics are not words). `can_grow[i]` False keeps box i as it is (pictures: their box is the graphic). Returns new boxes; None stays None.""" passes = passes or int(FLAGS.get("absorb_passes", "3")) out = [None if b is None else list(map(float, b)) for b in boxes] lo, hi = 0.4 * page.med_h, MAX_FONT * page.med_h words = [b for b in page.blobs if lo <= b[3] - b[1] <= hi and b[2] - b[0] <= 0.6 * page.w]
def covered(b) -> bool: area = max((b[2] - b[0]) * (b[3] - b[1]), 1) return any(e is not None and _overlap(b[0], b[2], e[0], e[2]) * _overlap(b[1], b[3], e[1], e[3]) >= 0.5 * area for e in ref)
def blocked(i: int, region: list[float]) -> bool: return any(j != i and e is not None and _overlap(region[0], region[2], e[0], e[2]) > 0 and _overlap(region[1], region[3], e[1], e[3]) > 0 for j, e in enumerate(ref))
# absorb_frozen: every blob is matched against the attention boxes as they came in and all growth is applied at # once, so a box that took one line cannot reach the next one through it (a cascade down a column, across a page) frozen = "absorb_frozen" in FLAGS ref = [None if b is None else list(b) for b in out] if frozen else out if frozen: passes = 1 for _ in range(passes): changed = False for b in words: if covered(b): continue h = b[3] - b[1] best, best_gap = None, None for i, e in enumerate(ref): if e is None or not can_grow[i]: continue if _overlap(b[1], b[3], e[1], e[3]) >= 0.5 * h: # same line: gap along x gap = max(e[0] - b[2], b[0] - e[2], 0.0) if "absorb_gap" in FLAGS and gap > float(FLAGS["absorb_gap"]) * page.med_h: continue region = [min(b[2], e[2]), b[1], max(b[0], e[0]), b[3]] elif line_only and line_only[i]: # a heading or furniture band does not take the lines around it continue elif _overlap(b[0], b[2], e[0], e[2]) >= 0.5 * (b[2] - b[0]): # line above or below: gap along y gap = max(e[1] - b[3], b[1] - e[3], 0.0) if gap > float(FLAGS.get("absorb_vgap", "1.0")) * page.med_h: continue region = [max(b[0], e[0]), min(b[3], e[3]), min(b[2], e[2]), max(b[1], e[1])] else: continue if region[2] > region[0] and region[3] > region[1] and blocked(i, region): continue if best_gap is None or gap < best_gap: best, best_gap = i, gap if best is not None: e = out[best] out[best] = [min(e[0], b[0]), min(e[1], b[1]), max(e[2], b[2]), max(e[3], b[3])] changed = True if not changed: break return out
def envelope(boxes: list[list[float]]) -> list[float]: return [min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes)]
def main_cluster(boxes: list[list[float]], line_h: float, wide: bool = False) -> list[list[float]]: """The largest group of word boxes chained by proximity (vertical gap <= 1.5 lines; horizontal gap <= 4 lines, or any for a table, whose columns sit far apart). Words outside it are attention strays.""" n = len(boxes) if n <= 2: return boxes dy_max, dx_max = 1.5 * line_h, (float("inf") if wide else 4.0 * line_h) parent = list(range(n))
def find(i): while parent[i] != i: parent[i] = parent[parent[i]] i = parent[i] return i
order = sorted(range(n), key=lambda i: boxes[i][1]) for a_i, a in enumerate(order): for b in order[a_i + 1:]: if boxes[b][1] - boxes[a][3] > dy_max: break p, q = boxes[a], boxes[b] dy = max(0.0, max(p[1], q[1]) - min(p[3], q[3])) dx = max(0.0, max(p[0], q[0]) - min(p[2], q[2])) if dy <= dy_max and dx <= dx_max: parent[find(a)] = find(b) groups: dict[int, list[int]] = {} for i in range(n): groups.setdefault(find(i), []).append(i) best = max(groups.values(), key=len) return [boxes[i] for i in best]
def unclaimed_graphics(page: Page, boxes: list, min_side: float = 2.0, max_frac: float = 0.4) -> list[list[float]]: """Graphics on the page that no element covers (icons, logos, photos the answer does not mention): foreground components that are filled or coloured like a picture (not thin text strokes), between `min_side` body-glyph heights square and `max_frac` of the page, and less than 30% covered by element boxes.""" rgb_sat = None fg = close(page.fg, (int(page.line_h) | 1, int(page.line_h) | 1)) lab, _ = ndimage.label(fg) out = [] side = min_side * page.med_h for sl in ndimage.find_objects(lab): if sl is None: continue y0, y1, x0, x1 = sl[0].start, sl[0].stop, sl[1].start, sl[1].stop w, h = x1 - x0, y1 - y0 if w < side or h < side or w * h > max_frac * page.w * page.h or max(w / h, h / w) > 6: continue b = [float(x0), float(y0), float(x1), float(y1)] area = w * h cov = sum(_overlap(b[0], b[2], e[0], e[2]) * _overlap(b[1], b[3], e[1], e[3]) for e in boxes if e is not None) if cov >= 0.3 * area: continue fill = float(page.fg[y0:y1, x0:x1].mean()) if fill < float(FLAGS.get("pic_fill", "0.35")): # thin strokes: text or line art the answer left out continue out.append(b) return out
def fill_tables(page: Page, boxes: list, is_table: list[bool], max_gap: float = 2.5) -> list: """A table box grows up and down through the ink lines inside its horizontal range, line by line, while the gap to the next line stays under `max_gap` body lines and the line touches no other element's box. ocria's attention collapses a long table's later rows onto its first ones, so the words alone stop short of the table's end.""" out = [None if b is None else list(map(float, b)) for b in boxes] gap_px = max_gap * page.line_h for i, b in enumerate(out): if b is None or not is_table[i]: continue x0, x1 = int(max(0, b[0])), int(min(page.w, b[2])) prof = page.ink[:, x0:x1].sum(1) > max(2, 0.002 * (x1 - x0)) others = [o for j, o in enumerate(out) if j != i and o is not None and _overlap(o[0], o[2], b[0], b[2]) > 0]
def hits(y0: float, y1: float) -> bool: return any(_overlap(y0, y1, o[1], o[3]) > 0 for o in others) for step in (1, -1): # down, then up edge = int(b[3]) if step == 1 else int(b[1]) - 1 while True: y, gap = edge + step, 0 while 0 <= y < page.h and not prof[y] and gap <= gap_px: y += step gap += 1 if not (0 <= y < page.h) or gap > gap_px: break y_end = y while 0 <= y_end + step < page.h and prof[y_end + step]: y_end += step lo, hi = sorted((y, y_end)) if hits(lo, hi + 1) or hi - lo > 6 * page.line_h: # another element, or a graphic / frame break edge = y_end if step == 1: b[3] = float(hi + 1) else: b[1] = float(lo) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Teacher-forced attention of ocria over the page image, per text unit (GPU; torch + transformers imported lazily).
The answer is appended as the assistant turn after the system prompt and the image-only user turn, and ONE forwardpass is run. A decoder's attention at a position depends only on the tokens before it, so this is the attention themodel had while writing that text (teacher forcing and the model's own decoding gave the same box quality). For each unit (a char span: a word, or a whole image reference) and each chosen (layer, head):the mean softmax over image tokens of the queries that GENERATE the unit's tokens (query i-1 predicts token i),divided by that head's total image mass for the unit; the unit's map is the sum over the chosen heads.
Only Qwen3.5's full-attention layers have attention maps (the Gated DeltaNet layers have none); the probe runs insidethose layers' attention call and computes q.k only for the chosen heads."""from __future__ import annotations
import numpy as np
CHUNK = 256
class Grounder: def __init__(self, model_dir: str, heads: list[tuple[int, int]], system_prompt: str, device: str = "cuda"): import torch from transformers import AttentionInterface, AutoProcessor, Qwen3_5ForConditionalGeneration from transformers.integrations.sdpa_attention import sdpa_attention_forward
self.torch, self.device, self.ctx = torch, device, {} self.by_layer: dict[int, list[int]] = {} for layer, head in heads: self.by_layer.setdefault(int(layer), []).append(int(head)) ctx = self.ctx
def probe(module, query, key, value, attention_mask=None, scaling=None, **kwargs): out, w = sdpa_attention_forward(module, query, key, value, attention_mask=attention_mask, scaling=scaling, **kwargs) hs = self.by_layer.get(module.layer_idx) if not hs or "W" not in ctx or query.shape[2] == 1: return out, w g = query.shape[1] // key.shape[1] hsel = torch.tensor(hs, device=query.device) k = key[0, hsel // g].float() # (h, T, d): each query head's own kv head (GQA) T = k.shape[1] img, q0, W = ctx["img"], ctx["q0"], ctx["W"] acc = torch.zeros(W.shape[0], len(hs), int(img.sum()), device=query.device) for c0 in range(q0, T, CHUNK): q = query[0, hsel, c0:c0 + CHUNK].float() pos = torch.arange(c0, c0 + q.shape[1], device=query.device) s = torch.einsum("hqd,htd->hqt", q, k) * scaling s = s.masked_fill(torch.arange(T, device=query.device)[None, None, :] > pos[None, :, None], float("-inf")) p = s.softmax(-1)[..., img] acc += torch.einsum("uc,hcn->uhn", W[:, c0 - q0:c0 - q0 + q.shape[1]], p) acc = acc / acc.sum(-1, keepdim=True).clamp_min(1e-9) ctx["maps"] += acc.sum(1) return out, w
AttentionInterface.register("ocria_ground_probe", probe) self.model = Qwen3_5ForConditionalGeneration.from_pretrained( model_dir, dtype=torch.bfloat16, attn_implementation="sdpa").to(device).eval() self.model.config.text_config._attn_implementation = "ocria_ground_probe" self.proc = AutoProcessor.from_pretrained(model_dir) full = [i for i, t in enumerate(self.model.config.text_config.layer_types) if t == "full_attention"] bad = sorted(set(self.by_layer) - set(full)) if bad: raise ValueError(f"heads on layers {bad}, which have no attention map (full-attention layers: {full})") self.prompt = self.proc.apply_chat_template( [{"role": "system", "content": [{"type": "text", "text": system_prompt}]}, {"role": "user", "content": [{"type": "image"}]}], add_generation_prompt=True, enable_thinking=False)
def unit_maps(self, image, answer: str, units: list[tuple[int, int]]) -> tuple[np.ndarray, tuple[int, int], np.ndarray]: """(maps [U, gh, gw] float32, (gh, gw), has_tokens [U] bool) for char spans `units` of `answer`.""" torch, dev = self.torch, self.device enc = self.proc(text=[self.prompt], images=[image.convert("RGB")], return_tensors="pt") tok = self.proc.tokenizer(answer, add_special_tokens=False, return_offsets_mapping=True) ans = torch.tensor([tok["input_ids"]]) offs = tok["offset_mapping"] start = enc["input_ids"].shape[1] enc["input_ids"] = torch.cat([enc["input_ids"], ans], 1) enc["attention_mask"] = torch.cat([enc["attention_mask"], torch.ones_like(ans)], 1) if "mm_token_type_ids" in enc: enc["mm_token_type_ids"] = torch.cat([enc["mm_token_type_ids"], torch.zeros_like(ans)], 1) enc = {k: v.to(dev) for k, v in enc.items()} img = enc["input_ids"][0] == self.model.config.image_token_id thw = enc["image_grid_thw"][0].tolist() gh, gw = thw[1] // 2, thw[2] // 2 assert int(img.sum()) == gh * gw, (int(img.sum()), gh, gw) T, q0 = start + ans.shape[1], start - 1 W = torch.zeros(len(units), T - q0, device=dev) has = np.zeros(len(units), bool) tok_starts = np.array([a for a, b in offs]) if offs else np.zeros(0) tok_ends = np.array([b for a, b in offs]) if offs else np.zeros(0) for u, (s, e) in enumerate(units): t = np.nonzero((tok_starts < e) & (tok_ends > s) & (tok_ends > tok_starts))[0] if len(t): W[u, torch.as_tensor(start + t - 1 - q0, device=dev)] = 1.0 / len(t) has[u] = True self.ctx.update(W=W, img=img, q0=q0, maps=torch.zeros(len(units), gh * gw, device=dev)) try: with torch.no_grad(): self.model(**enc, use_cache=False, logits_to_keep=1) maps = self.ctx["maps"].reshape(len(units), gh, gw).float().cpu().numpy() finally: self.ctx.clear() return maps, (gh, gw), has1234567891011121314151617181920212223242526272829303132333435363738394041424344# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Layout regions from Docling's Heron detector (docling-project/docling-layout-heron, RT-DETRv2, Apache-2.0).
Heron is a third-party model: it is downloaded from its own repository and governed by its own license (Apache-2.0),not by this repository's license.
det = Detector() # cuda, else mps, else cpu regions = det(image) # [{label, score, box: [x0, y0, x1, y1]}] in pixels of `image`"""from __future__ import annotations
DETECTOR = "docling-project/docling-layout-heron"
class Detector: def __init__(self, model: str = DETECTOR, device: str | None = None, max_side: int = 1600): import torch from transformers import AutoImageProcessor, AutoModelForObjectDetection
if device is None: device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" self.torch, self.device, self.max_side = torch, device, max_side self.proc = AutoImageProcessor.from_pretrained(model) self.model = AutoModelForObjectDetection.from_pretrained(model).to(device).eval()
def __call__(self, image, threshold: float = 0.2) -> list[dict]: """Detections in pixels of `image`. The page is downscaled to <= max_side px first (Heron reads 640 x 640).""" from PIL import Image
im = image.convert("RGB") w, h = im.size s = min(1.0, self.max_side / max(w, h)) if s < 1: im = im.resize((max(1, int(w * s)), max(1, int(h * s))), Image.LANCZOS) sx, sy = w / im.width, h / im.height with self.torch.no_grad(): out = self.model(**self.proc(images=[im], return_tensors="pt").to(self.device)) r = self.proc.post_process_object_detection(out, target_sizes=[(im.height, im.width)], threshold=threshold)[0] return [{"label": self.model.config.id2label[int(lab)], "score": round(float(sc), 3), "box": [round(float(b[0]) * sx, 1), round(float(b[1]) * sy, 1), round(float(b[2]) * sx, 1), round(float(b[3]) * sy, 1)]} for sc, lab, b in zip(r["scores"], r["labels"], r["boxes"])]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Conservative reading-order paths for horizontal left-to-right prose.
Coordinates are image pixels. Word indices remain in transcript order, so askipped attention outlier does not delete text. Unsupported layouts fall backto the existing spatial clustering; tables, formulas and code bypass this pass."""
import statistics
WordBox = list[float]
def paragraph_paths(boxes: list[WordBox]) -> list[list[int]] | None: """Return supported word paths, splitting column continuations when justified.
Nearby words form spatial components. Within each component a longest path must move right on a line or wrap onto a nearby lower line. At least 60% of words must support the result. Separate columns need three words each and non-interleaving transcript spans; otherwise keep only a dominant path. """ n = len(boxes) if n < 3: return None height = max(1.0, statistics.median(b[3] - b[1] for b in boxes)) parents = list(range(n))
def root(i: int) -> int: while parents[i] != i: parents[i] = parents[parents[i]] i = parents[i] return i
# Proximity establishes candidate columns independently of transcript order. # A nearby wrong word can still belong here; the ordered path rejects it. for i, a in enumerate(boxes): for j in range(i): b = boxes[j] dx = max(a[0] - b[2], b[0] - a[2], 0.0) dy = max(a[1] - b[3], b[1] - a[3], 0.0) if dx <= 4 * height and dy <= 2.5 * height: parents[root(i)] = root(j) components: dict[int, list[int]] = {} for i in range(n): components.setdefault(root(i), []).append(i)
paths: list[list[int]] = [] for indices in components.values(): lengths = {i: 1 for i in indices} previous: dict[int, int] = {} for pos, i in enumerate(indices): b = boxes[i] for j in indices[:pos]: a = boxes[j] overlap = min(a[3], b[3]) - max(a[1], b[1]) same_line = overlap >= 0.5 * min(a[3] - a[1], b[3] - b[1]) if same_line: follows = b[0] >= a[0] + 0.2 * height and -0.5 * height <= b[0] - a[2] <= 4 * height else: follows = ( b[1] >= a[1] + 0.5 * height and b[1] - a[3] <= 2.5 * height and b[0] < a[2] ) if follows and lengths[j] + 1 > lengths[i]: lengths[i] = lengths[j] + 1 previous[i] = j end = max(indices, key=lengths.__getitem__) path = [end] while path[-1] in previous: path.append(previous[path[-1]]) path.reverse() if len(path) >= 3: paths.append(path) if not paths: return None paths.sort(key=lambda p: p[0]) if sum(map(len, paths)) < 0.6 * n: return None
# A column jump is supported by whole runs, not a single distant word. # Interleaved components or a jump down to unrelated text are ambiguous. for left, right in zip(paths, paths[1:]): gutter = min(boxes[i][0] for i in right) - max(boxes[i][2] for i in left) if left[-1] >= right[0] or gutter < height or boxes[right[0]][1] > boxes[left[-1]][1]: dominant = max(paths, key=len) return [dominant] if len(dominant) >= 0.6 * n else None return paths123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""One page: raw ocria answer + page image -> layout elements with boxes, in the two forms the benches read.
elements = ground_page(grounder, image, answer) # GPU pass + CPU snapping md = to_box_markdown(answer, elements, w, h) # box-mode markers (0-1000 grid) page = to_layout_page(answer, elements, w, h, scale) # a ParseBench layout page
Pure functions below `ground_page` need no GPU and are what the tests exercise."""from __future__ import annotations
import re
import numpy as np
from .blocks import Block, body_span, resolve_page_numbers, split_blocksfrom .boxes import Page, absorb_uncovered_ink, envelope, fill_tables, main_cluster, snap_table, unclaimed_graphicsfrom .geometry import paragraph_pathsfrom .tune import FLAGSfrom .words import norm, word_spans
_PAGE_NO = re.compile(r"(?:^|\s)(?:page\s*)?\d{1,4}(?:\s*(?:of|/)\s*\d{1,4})?\s*$", re.I)_FURN_TAG = re.compile(r"</?(page_header|page_footer|page_number|watermark)>")
def units_for(answer: str, blocks: list[Block]) -> tuple[list[tuple[int, int]], list[list[int]]]: """Attention units and, per block, the indices of its units: every content word inside the block; an image block is one unit (its whole reference), because the picture it points at has no words to snap to.""" spans = word_spans(answer) units: list[tuple[int, int]] = [] per_block: list[list[int]] = [] k = 0 for b in blocks: mine: list[int] = [] if b.type == "image": mine.append(len(units)) units.append((b.start, b.end)) per_block.append(mine) continue while k < len(spans) and spans[k][0] < b.start: k += 1 j = k while j < len(spans) and spans[j][1] <= b.end: mine.append(len(units)) units.append((spans[j][0], spans[j][1])) j += 1 per_block.append(mine) return units, per_block
def element_boxes(page: Page, answer: str, blocks: list[Block], units, per_block, maps, has) -> list: """Pixel box [x0, y0, x1, y1] per block (None when none of its units reached a token).""" return [bx for _, bx in element_pieces(page, answer, blocks, units, per_block, maps, has, split=False)]
def element_pieces(page: Page, answer: str, blocks: list[Block], units, per_block, maps, has, split: bool = True, words_out: dict | None = None, geometry_spans: set[tuple[int, int]] | None = None) -> list[tuple[Block, list | None]]: """(block, box) per element. With `split` (tuning flag split_gaps), a text element whose words fall into clusters separated by whitespace gaps becomes one element per cluster when the clusters follow each other in the text (vertical gap > 1.4, horizontal > 2.0 line heights).""" out = [] W, H = page.w, page.h snaps = {} # unit -> word box, for every text unit on the page (image units excluded) for b, idx in zip(blocks, per_block): if b.type != "image": for u in idx: if has[u]: snaps[u] = page.snap_word(maps[u], len(norm(answer[units[u][0]:units[u][1]]))) if "drop_big_words" in FLAGS: # not inside tables: a table word on its ruling gives the table its extent table_units = {u for b, idx in zip(blocks, per_block) if b.type == "table" for u in idx} dropped = _drop_oversized(snaps) snaps = {u: (w if u in table_units else dropped[u]) for u, w in snaps.items()} for b, idx in zip(blocks, per_block): idx = [u for u in idx if has[u]] if not idx: out.append((b, None)) continue if b.type == "image": bx = page.image_box(maps[idx[0]]) if "pic_cap" in FLAGS and (bx[2] - bx[0]) * (bx[3] - bx[1]) > float(FLAGS["pic_cap"]) * W * H: bx = page.image_hot_box(maps[idx[0]]) if (bx[2] - bx[0]) * (bx[3] - bx[1]) > float(FLAGS["pic_cap"]) * W * H: bx = None out.append((b, bx)) continue snapped = [(u, snaps.get(u)) for u in idx] snapped = [(u, w) for u, w in snapped if w is not None] if not snapped: out.append((b, None)) continue words = [w for _, w in snapped] if "paragraph_geometry" in FLAGS and b.type in ("text", "list"): paths = paragraph_paths(words) if paths and (split or len(paths) == 1): for k, path in enumerate(paths): start = b.start if k == 0 else units[snapped[path[0]][0]][0] end = b.end if k + 1 == len(paths) else units[snapped[paths[k + 1][0]][0]][0] piece = Block(b.type, start, end) core = [words[i] for i in path] if words_out is not None: words_out[id(piece)] = core if geometry_spans is not None: geometry_spans.add((start, end)) out.append((piece, envelope(core))) continue if "seq_filter" in FLAGS and b.type != "table" and len(words) >= 3: words = _reading_order_core(words, page.med_h) or words core = main_cluster(words, page.line_h, wide=b.type == "table") if words_out is not None: words_out[id(b)] = core env = envelope(core) if b.type == "table": bx = snap_table(page, env) if "chart_tables" in FLAGS and bx == [float(v) for v in env]: bx = page.graphic_around(bx) or bx out.append((b, bx)) continue pieces = _split_at_gaps(page, b, snapped, units, env) if split and "split_gaps" in FLAGS else None if pieces: out.extend(pieces) else: out.append((b, env)) return out
def _follows(a, b, h: float) -> bool: """Word box b can be the word written after a: further right on the same line, or the start of a line below.""" ha, hb = a[3] - a[1], b[3] - b[1] same_line = min(a[3], b[3]) - max(a[1], b[1]) >= 0.5 * min(ha, hb) if same_line: return -0.5 * h <= b[0] - a[2] <= float(FLAGS.get("seq_dx", "4")) * h return b[1] > a[1] + 0.3 * h and b[1] - a[3] <= float(FLAGS.get("seq_dy", "2.5")) * h and b[0] < a[2]
def _reading_order_core(words: list, h: float) -> list | None: """The words that sit where the text order says they should: runs of consecutive words in which each follows the previous one on the page (`_follows`, one missing word allowed), keeping runs of >= 2 words; None when no run.""" n = len(words) parent = list(range(n))
def find(i): while parent[i] != i: parent[i] = parent[parent[i]] i = parent[i] return i for i in range(n - 1): if _follows(words[i], words[i + 1], h): parent[find(i + 1)] = find(i) elif i + 2 < n and _follows(words[i], words[i + 2], h): parent[find(i + 2)] = find(i) groups: dict[int, list[int]] = {} for i in range(n): groups.setdefault(find(i), []).append(i) keep = sorted(i for g in groups.values() if len(g) >= 2 for i in g) return [words[i] for i in keep] if keep else None
def _iou(a, b) -> float: i = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) * max(0.0, min(a[3], b[3]) - max(a[1], b[1])) u = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - i return i / u if u > 0 else 0.0
def _drop_duplicate_boxes(answer: str, blocks, boxes) -> list: """Of two elements whose boxes overlap at IoU >= 0.5, the one with fewer letters loses its box (two elements placed on the same block: one of them is misplaced, and the longer text is more likely to own the block).""" letters = [sum(c.isalnum() for c in answer[b.start:b.end]) for b in blocks] out = list(boxes) for i in range(len(out)): for j in range(i + 1, len(out)): if out[i] is None or out[j] is None or _iou(out[i], out[j]) < 0.5: continue if letters[i] >= letters[j]: out[j] = None else: out[i] = None return out
def _drop_nested_text_boxes(blocks, boxes) -> list: """A text box >= 90% inside another element's text box at least 1.5x its area is a misplaced fragment of that block.""" text = [b.type not in ("image", "table") for b in blocks] area = [0.0 if bx is None else (bx[2] - bx[0]) * (bx[3] - bx[1]) for bx in boxes] out = list(boxes) for i, r in enumerate(boxes): if r is None or not text[i] or area[i] <= 0: continue for j, host in enumerate(boxes): if j == i or host is None or not text[j] or area[j] <= 1.5 * area[i]: continue inter = max(0.0, min(r[2], host[2]) - max(r[0], host[0])) * max(0.0, min(r[3], host[3]) - max(r[1], host[1])) if inter / area[i] >= 0.9: out[i] = None break return out
def _drop_oversized(snaps: dict) -> dict: """A word whose box is taller than 4x the page's median word height or larger than 50x its median word area snapped to a frame, a rule or a graphic, not to a word, and one such box stretches its element across the page. Such words get no box (pages with >= 10 words).""" boxes = [w for w in snaps.values() if w is not None] if len(boxes) < 10: return snaps hs = sorted(w[3] - w[1] for w in boxes) areas = sorted((w[2] - w[0]) * (w[3] - w[1]) for w in boxes) mh, ma = hs[len(hs) // 2], areas[len(areas) // 2] return {u: (None if w is None or w[3] - w[1] > 4 * mh or (w[2] - w[0]) * (w[3] - w[1]) > 50 * ma else w) for u, w in snaps.items()}
def _split_at_gaps(page: Page, b: Block, snapped, units, env): """Pieces of one element split at whitespace gaps, or None. Only for big elements (>= 4% of the page, >= 6 words), and only when each cluster is one run of consecutive words (else the text cannot be cut).""" W, H = page.w, page.h if len(snapped) < int(FLAGS.get("sg_min_words", "6")) or \ (env[2] - env[0]) * (env[3] - env[1]) < float(FLAGS.get("sg_min_area", "0.04")) * W * H: return None vg, hg = float(FLAGS.get("sg_v", "1.4")) * page.line_h, float(FLAGS.get("sg_h", "2.0")) * page.line_h n = len(snapped) parent = list(range(n))
def find(i): while parent[i] != i: parent[i] = parent[parent[i]] i = parent[i] return i for i in range(n): p = snapped[i][1] for j in range(i + 1, n): q = snapped[j][1] dy = max(0.0, max(p[1], q[1]) - min(p[3], q[3])) dx = max(0.0, max(p[0], q[0]) - min(p[2], q[2])) if dy <= vg and dx <= hg: parent[find(i)] = find(j) lab = [find(i) for i in range(n)] runs = [] # consecutive words with the same cluster for i, l in enumerate(lab): if runs and runs[-1][0] == l: runs[-1][1].append(i) else: runs.append((l, [i])) # a single stray word between two runs of one cluster joins its neighbours merged = [] for l, ws in runs: if merged and (merged[-1][0] == l or len(ws) == 1): merged[-1][1].extend(ws) else: merged.append((l, ws)) if len(merged) < 2 or len({l for l, _ in merged}) != len(merged): return None pieces = [] for k, (_, ws) in enumerate(merged): start = b.start if k == 0 else units[snapped[ws[0]][0]][0] end = b.end if k == len(merged) - 1 else units[snapped[merged[k + 1][1][0]][0]][0] pieces.append((Block(b.type, start, end), envelope([snapped[i][1] for i in ws]))) return pieces
def ground_page(grounder, image, answer: str, keep_maps: bool = False) -> dict: """{width, height, elements: [{type, start, end, box}]} for one page (box in pixels of `image`, or None). `keep_maps` also returns the sparse attention maps (`sparse_maps`) so the CPU step can be re-run offline.""" blocks = split_blocks(answer) units, per_block = units_for(answer, blocks) w, h = image.size if not units: return {"width": w, "height": h, "elements": []} maps, grid, has = grounder.unit_maps(image, answer, units) out = boxes_from_maps(image, answer, blocks, units, per_block, maps, grid, has) if keep_maps: out["sparse_maps"] = sparsify(maps, has, [b.type == "image" for b in blocks], per_block) return out
def boxes_from_maps(image, answer: str, blocks, units, per_block, maps, grid, has, regions: list | None = None, page: Page | None = None) -> dict: """The CPU half of `ground_page`: attention maps -> element boxes. With `regions` (layout-detector detections, [{label, score, box}] in image pixels) elements are placed on the regions (regions.place_on_regions).""" w, h = image.size page = page or Page(np.asarray(image.convert("RGB")), grid) words_of: dict = {} geometry_spans: set[tuple[int, int]] = set() pieces = element_pieces(page, answer, blocks, units, per_block, maps, has, words_out=words_of, geometry_spans=geometry_spans) piece_words = [words_of.get(id(pb), []) for pb, _ in pieces] blocks = [Block(pb.type, pb.start, pb.end) for pb, _ in pieces] boxes = [bx for _, bx in pieces] if regions is None and "ink_regions" in FLAGS: from .regions import ink_regions regions = ink_regions(page, float(FLAGS.get("ink_kv", "1.0")), float(FLAGS.get("ink_kh", "1.5"))) if regions is not None: from .regions import clean_regions, place_on_regions boxes, extra_pics = place_on_regions([b.type for b in blocks], piece_words, boxes, clean_regions(regions, float(FLAGS.get("region_score", "0.35"))), page.line_h, add_unclaimed_pictures="no_region_pics" not in FLAGS, text_too=FLAGS.get("region_kinds", "all") != "visual") if "region_absorb" not in FLAGS and FLAGS.get("region_kinds", "all") != "visual": # regions cover blocks FLAGS_NO_ABSORB = True else: FLAGS_NO_ABSORB = False else: extra_pics, FLAGS_NO_ABSORB = [], False if "no_absorb" not in FLAGS and not FLAGS_NO_ABSORB: # Unconstrained ink absorption can reattach a rejected outlier or bridge # the gutter. Keep accepted geometry paths at their supported extent. boxes = absorb_uncovered_ink(page, boxes, [b.type != "image" and (b.start, b.end) not in geometry_spans for b in blocks], line_only=[b.type in ("heading", "header", "footer", "page_number") for b in blocks] if "absorb_head_line" in FLAGS else None) if "table_fill" in FLAGS: boxes = fill_tables(page, boxes, [b.type == "table" for b in blocks], float(FLAGS.get("table_gap", "2.5"))) if "pad" in FLAGS: # ink-tight boxes vs annotated boxes with a margin: grow text-like boxes by pad x body glyph height m = float(FLAGS["pad"]) * page.med_h boxes = [bx if bx is None or b.type == "image" else [max(0.0, bx[0] - m), max(0.0, bx[1] - m), min(float(w), bx[2] + m), min(float(h), bx[3] + m)] for b, bx in zip(blocks, boxes)] if "dedupe" in FLAGS: boxes = _drop_duplicate_boxes(answer, blocks, boxes) if "drop_nested" in FLAGS: boxes = _drop_nested_text_boxes(blocks, boxes) resolve_page_numbers(blocks, boxes, h) if "furniture_bands" in FLAGS: # detector-free furniture labels by position for b, bx in zip(blocks, boxes): if bx is None or b.type not in ("text", "heading"): continue if bx[3] <= 0.09 * h: b.type = "header" elif bx[1] >= 0.93 * h or (bx[1] >= 0.88 * h and _PAGE_NO.search(answer[b.start:b.end])): b.type = "footer" elements = [{"type": b.type, "start": b.start, "end": b.end, "box": None if bx is None else [round(float(v), 1) for v in bx]} for b, bx in zip(blocks, boxes)] if extra_pics: # detector pictures the answer does not mention end = body_span(answer)[1] elements += [{"type": "image", "start": end, "end": end, "box": [round(float(v), 1) for v in bx]} for bx in extra_pics] elif "add_pictures" in FLAGS: # graphics the answer does not mention: picture boxes with no text, at the end end = body_span(answer)[1] elements += [{"type": "image", "start": end, "end": end, "box": [round(v, 1) for v in bx]} for bx in unclaimed_graphics(page, boxes)] return {"width": w, "height": h, "grid": list(grid), "elements": elements}
def sparsify(maps, has, is_image_block, per_block, k_word: int = 64, k_image: int = 512) -> dict: """Top-k cells per unit (indices into the flattened grid, fp16 values): enough to re-run snapping offline at a fraction of the size of the dense maps. Image units keep more cells (their hot area is large).""" img_units = {u for blk, idx in zip(is_image_block, per_block) if blk for u in idx} flat = maps.reshape(maps.shape[0], -1) idx, val = [], [] for u in range(flat.shape[0]): k = min(flat.shape[1], k_image if u in img_units else k_word) top = np.argpartition(-flat[u], k - 1)[:k] if has[u] else np.zeros(0, dtype=np.int64) idx.append(top.astype(np.int32).tolist()) val.append(np.round(flat[u][top].astype(np.float32), 6).tolist()) return {"idx": idx, "val": val, "has": [bool(x) for x in has]}
def dense_maps(sparse: dict, grid) -> tuple[np.ndarray, np.ndarray]: """Inverse of `sparsify` (cells outside the kept top-k are 0).""" gh, gw = grid maps = np.zeros((len(sparse["idx"]), gh * gw), np.float32) for u, (i, v) in enumerate(zip(sparse["idx"], sparse["val"])): if i: maps[u, i] = v return maps.reshape(-1, gh, gw), np.array(sparse["has"], bool)
def to_box_markdown(answer: str, elements: list[dict], width: float, height: float) -> str: """The answer with a box-mode marker `<!-- bbox: TYPE x0 y0 x1 y1 -->` (0-1000 grid) opening each boxed element, i.e. what a box-mode model would have written; `layout_score.box_markers_to_attribution` reads it unchanged.""" out, pos = [], 0 for el in sorted(elements, key=lambda e: e["start"]): if el["box"] is None: continue x0, y0, x1, y1 = el["box"] g = [int(round(1000 * x0 / width)), int(round(1000 * y0 / height)), int(round(1000 * x1 / width)), int(round(1000 * y1 / height))] g = [max(0, min(1000, v)) for v in g] if g[2] <= g[0] or g[3] <= g[1]: continue out.append(answer[pos:el["start"]]) out.append(f"<!-- bbox: {el['type']} {g[0]} {g[1]} {g[2]} {g[3]} -->\n") pos = el["start"] out.append(answer[pos:]) return "".join(out)
# (item type, segment label). The v2 detection metrics resolve a box's class from Canonical17 names only, so a raw# "heading"/"header"/"footer"/"image" type is dropped from localization/classification; segment labels keep the# raw LlamaParse layout names ("heading" itself is excluded by ParseBench's label mapper)._V2_TYPE = {"text": ("Text", "text"), "heading": ("Section-header", "paragraph_title"), "table": ("Table", "table"), "image": ("Picture", "image"), "header": ("Page-header", "header"), "footer": ("Page-footer", "footer")}
def to_layout_page(answer: str, elements: list[dict], width: float, height: float, scale: float = 1.0, page_md: str = "") -> dict: """A ParseBench `layout_pages` entry. Boxes are x, y, w, h in the page's own units (pixels x `scale`; use 72 / DPI for PDF points), each item with one `layout_segments` entry equal to its box, because the v2 layout scorer ignores items without layout-aware segments.""" items = [] for el in elements: if el["box"] is None: continue x0, y0, x1, y1 = (v * scale for v in el["box"]) if x1 <= x0 or y1 <= y0: continue md = _FURN_TAG.sub("", answer[el["start"]:el["end"]]).strip() typ, label = _V2_TYPE.get(el["type"], _V2_TYPE["text"]) seg = {"x": x0, "y": y0, "w": x1 - x0, "h": y1 - y0, "label": label} items.append({"type": typ, "md": md, "value": md, "bbox": dict(seg), "layout_segments": [seg]}) return {"page_number": 1, "width": width * scale, "height": height * scale, "md": page_md, "items": items}12345678910{ "llamaindex/OCRia-1": { "heads": [[27, 13], [19, 12], [23, 14], [15, 13], [23, 0], [19, 13], [27, 1], [27, 2]], "chosen_on": "6 pages with exact PDF word boxes (none from any public benchmark)", "word_iou50_held_out": { "pages": 24, "percent": 81.8 } }}12345678910111213141516# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Attention heads (layer, head) used for grounding, per model. Chosen on pages with exact PDF word boxes (none fromany public benchmark): the heads whose top image token most often falls inside the word being written."""import jsonfrom pathlib import Path
_FILE = Path(__file__).with_name("heads.json")
def heads_for(model: str) -> list[tuple[int, int]]: table = json.loads(_FILE.read_text()) if model not in table: raise KeyError(f"no grounding heads recorded for {model}; known: {sorted(table)}") return [tuple(h) for h in table[model]["heads"]]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Region-first layout: a layout detector's regions are the items, and OCRia-1's answer is distributed into them.
Per page:1. Every word of the answer gets a position: its PDF word box when the page has a text layer (align.py), else the ink blob its attention points at (boxes.Page.snap_word).2. A word goes to the smallest non-picture region holding its centre; a word with no position, or outside every region, takes the region of the word before it in the same block (else the next one). Each region's text is its words in answer order, one block's words kept together.3. An image reference goes to the Picture or Table region under its attention box. A table goes to the Table region holding most of its words (else the Picture region); with neither, the table gets its own box around its words.4. Regions that get no text are dropped, except pictures. Pictures scoring under 0.6 are dropped first, and of a Picture and a Table region with IoU >= 0.5 only the higher-scoring one is kept.5. Elements none of whose words reach a region keep their attention box. Finally, of two items whose boxes overlap at IoU >= 0.5, the one with less text is dropped, and image references are removed from text items.
Boxes are pixels of the page image, like the detector's regions and the word boxes."""from __future__ import annotations
import re
import numpy as np
from .align import unit_boxes_multifrom .blocks import split_blocksfrom .boxes import Pagefrom .ground import _FURN_TAG, boxes_from_maps, units_forfrom .regions import PICTURE, TABLE, clean_regionsfrom .words import norm
MIN_SCORE = 0.35 # detections below this are ignoredPICTURE_MIN_SCORE = 0.6 # pictures need more (most low-score pictures duplicate a table, a chart or an icon)PAIR_IOU = 0.5 # a Picture and a Table region this close are one regionTABLE_SHARE = 0.3 # a table goes to the Table/Picture region holding at least this share of its words
# detector label -> (item type, segment label), Docling label namesTYPE = {"text": "Text", "section_header": "Section-header", "list_item": "List-item", "picture": "Picture", "page_header": "Page-header", "page_footer": "Page-footer", "caption": "Caption", "footnote": "Footnote", "table": "Table", "formula": "Formula", "title": "Title", "code": "Code", "document_index": "Document Index", "form": "Form", "key_value_region": "Key-Value Region"}SEG = {"Section-header": "paragraph_title", "Title": "doc_title", "Picture": "image", "Table": "table", "Page-header": "header", "Page-footer": "footer"}EL_TYPE = {"text": "Text", "heading": "Section-header", "table": "Table", "image": "Picture", "header": "Page-header", "footer": "Page-footer", "list": "List-item", "code": "Code", "page_number": "Page-footer"}_IMAGE_REF = re.compile(r"[ \t]*!\[[^\]]*\](\([^)]*\))?[ \t]*")
def _ov(a, b): i = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) * max(0.0, min(a[3], b[3]) - max(a[1], b[1])) aa, ab = max(1e-9, (a[2] - a[0]) * (a[3] - a[1])), max(1e-9, (b[2] - b[0]) * (b[3] - b[1])) return i / (aa + ab - i)
def tidy_regions(regs: list[dict]) -> list[dict]: """Of a Picture and a Table region with IoU >= PAIR_IOU keep the higher-scoring one; drop weak pictures.""" drop = set() by_score = sorted(range(len(regs)), key=lambda j: -regs[j]["score"]) for a in by_score: if a in drop: continue la, ba = regs[a]["label"], regs[a]["box"] for b in by_score: if b == a or b in drop: continue lb = regs[b]["label"] if {la, lb} <= PICTURE | TABLE and (la in TABLE) != (lb in TABLE) and _ov(ba, regs[b]["box"]) >= PAIR_IOU: drop.add(b) return [r for j, r in enumerate(regs) if j not in drop and (r["label"] not in PICTURE or r["score"] >= PICTURE_MIN_SCORE)]
def _table_region(words, regs, R): ws = [w for w in words if w is not None] if not ws: return None for kinds in (TABLE, PICTURE): cnt = [(sum(R[j][0] <= (w[0] + w[2]) / 2 <= R[j][2] and R[j][1] <= (w[1] + w[3]) / 2 <= R[j][3] for w in ws), j) for j in range(len(R)) if regs[j]["label"] in kinds] if cnt and max(cnt)[0] >= TABLE_SHARE * len(ws): return max(cnt)[1] return None
def _dedupe(out_items): """Two items whose boxes overlap at IoU >= 0.5 are one element: the one with more text keeps it.""" order = sorted(range(len(out_items)), key=lambda k: -len(out_items[k][1]["md"])) keep, gone = [], set() for k in order: if any(_ov(out_items[k][1]["box"], out_items[h][1]["box"]) >= 0.5 for h in keep): gone.add(k) else: keep.append(k) return [x for k, x in enumerate(out_items) if k not in gone]
def page_words(image, answer, blocks, units, per_block, maps, grid, has, words=None) -> list[dict]: """Per block: its type, span, markdown, attention box, and (for non-image blocks) each word's box and offset.""" page = Page(np.asarray(image.convert("RGB")), grid) base = boxes_from_maps(image, answer, blocks, units, per_block, maps, grid, has, page=page) # attention-only boxes pdfbox = unit_boxes_multi(answer, units, words) if words else {} el_by_span = {(e["start"], e["end"]): e for e in base["elements"]} out = [] for b, idx in zip(blocks, per_block): el = el_by_span.get((b.start, b.end)) f = {"type": b.type, "start": b.start, "end": b.end, "md": _FURN_TAG.sub("", answer[b.start:b.end]).strip(), "box": el["box"] if el else None} if b.type != "image": ws, starts = [], [] for u in idx: w = pdfbox.get(u) if w is None and has[u]: w = page.snap_word(maps[u], len(norm(answer[units[u][0]:units[u][1]]))) ws.append(w) starts.append(units[u][0]) f["words"], f["starts"] = ws, starts out.append(f) return out
def place(answer: str, blocks_info: list[dict], detections: list[dict]) -> list[dict]: """Region-first items [{type, label, md, box, start}] from `page_words` output and detector regions.""" regs = tidy_regions(clean_regions(detections, MIN_SCORE)) R = [r["box"] for r in regs] area = [(r[2] - r[0]) * (r[3] - r[1]) for r in R]
def region_of(b): cx, cy = (b[0] + b[2]) / 2, (b[1] + b[3]) / 2 hold = [j for j, r in enumerate(R) if r[0] <= cx <= r[2] and r[1] <= cy <= r[3] and regs[j]["label"] not in PICTURE] return min(hold, key=lambda j: area[j]) if hold else None
texts = {j: [] for j in range(len(R))} # region -> [(answer offset, md)] leftovers = [] # (element type, md, attention box) for b in blocks_info: md = b["md"] if b["type"] == "image": bx = b["box"] cand = [(j, max(0.0, min(bx[2], R[j][2]) - max(bx[0], R[j][0])) * max(0.0, min(bx[3], R[j][3]) - max(bx[1], R[j][1])) / max(1e-9, min(area[j], (bx[2] - bx[0]) * (bx[3] - bx[1])))) for j in range(len(R)) if regs[j]["label"] in PICTURE | TABLE] if bx else [] cand = [c for c in cand if c[1] >= 0.5] if cand: texts[max(cand, key=lambda c: c[1])[0]].append((b["start"], md)) elif bx: leftovers.append(("image", md, bx)) continue ws = [region_of(w) if w is not None else None for w in b["words"]] last = None for k in range(len(ws)): # words without a region: the previous word's, else the next one's if ws[k] is None: ws[k] = last last = ws[k] nxt = None for k in range(len(ws) - 1, -1, -1): if ws[k] is None: ws[k] = nxt nxt = ws[k] if not ws or all(w is None for w in ws): if b["box"]: leftovers.append((b["type"], md, b["box"])) continue if b["type"] == "table": tj = _table_region(b["words"], regs, R) bw = [w for w in b["words"] if w is not None] if tj is None and bw: # no Table/Picture region: the table's own words give its box h = sorted(w[3] - w[1] for w in bw)[len(bw) // 2] * 0.3 box = [min(w[0] for w in bw) - h, min(w[1] for w in bw) - h, max(w[2] for w in bw) + h, max(w[3] for w in bw) + h] regs.append({"label": "table", "score": 0.0, "box": box}) R.append(box) area.append((box[2] - box[0]) * (box[3] - box[1])) texts[len(R) - 1] = [(b["start"], md)] continue texts[tj if tj is not None else max(set(ws), key=ws.count)].append((b["start"], md)) continue starts = b["starts"] run_start = 0 # contiguous runs of words per region keep their own markdown slice for k in range(1, len(ws) + 1): if k == len(ws) or ws[k] != ws[run_start]: s = starts[run_start] if run_start else b["start"] e = starts[k] if k < len(ws) else b["end"] texts[ws[run_start]].append((s, _FURN_TAG.sub("", answer[s:e]).strip())) run_start = k
def item(t, md, bx): if t != "Picture": # an image reference's alt text is not page text md = _IMAGE_REF.sub(" ", md).strip() return {"type": t, "label": SEG.get(t, "text"), "md": md, "box": [round(float(v), 1) for v in bx]}
out = [] for j, r in enumerate(regs): t = TYPE.get(r["label"], "Text") parts = [m for _, m in sorted(texts[j]) if m] if not parts and r["label"] not in PICTURE: continue out.append((min((o for o, _ in texts[j]), default=10 ** 9), item(t, "\n\n".join(parts), R[j]))) for t, md, bx in leftovers: out.append((10 ** 9, item(EL_TYPE.get(t, "Text"), md, bx))) out.sort(key=lambda x: x[0]) return [{**it, "start": off if off < 10 ** 9 else None} for off, it in _dedupe(out)]
def ground_layout(grounder, image, answer: str, detector=None, words: list[dict] | None = None, detections: list[dict] | None = None, *, method: str = "accurate-layout", fast_backend=None, attention: dict | None = None) -> dict: """{width, height, items: [{type, label, md, box, start}]} for one page; `box` is [x0, y0, x1, y1] in pixels of `image`. `detector` (detector.Detector) or precomputed `detections` give the regions; `words` (pdf.render_pdf_page) give exact word positions on pages with a text layer. With neither detector nor detections the items are the attention-only elements.""" if method == "fast-layout": if fast_backend is None: raise ValueError("fast-layout requires an initialized FastLayout backend") if detector is not None or detections is not None or words is not None: raise ValueError("fast-layout accepts attention only; omit detector, detections, and words") from parse_rl_utils.ocria_attention_grounding.hf_adapter import ground_fast_layout
return ground_fast_layout(grounder, image, answer, backend=fast_backend, attention=attention) if method != "accurate-layout": raise ValueError(f"Unknown layout method: {method}") if attention is not None or fast_backend is not None: raise ValueError("attention and fast_backend require method='fast-layout'") w, h = image.size blocks = split_blocks(answer) units, per_block = units_for(answer, blocks) if not units: return {"width": w, "height": h, "items": []} maps, grid, has = grounder.unit_maps(image, answer, units) if detections is None and detector is not None: detections = detector(image) if detections is None: base = boxes_from_maps(image, answer, blocks, units, per_block, maps, grid, has) items = [{"type": EL_TYPE.get(e["type"], "Text"), "label": SEG.get(EL_TYPE.get(e["type"], "Text"), "text"), "md": _FURN_TAG.sub("", answer[e["start"]:e["end"]]).strip(), "box": e["box"], "start": e["start"]} for e in base["elements"] if e["box"] is not None] return {"width": w, "height": h, "items": items} info = page_words(image, answer, blocks, units, per_block, maps, grid, has, words) return {"width": w, "height": h, "items": place(answer, info, detections)}
def to_layout_items_page(page: dict, scale: float = 1.0, page_md: str = "") -> dict: """`ground_layout` output as a ParseBench `layout_pages` entry (x, y, w, h boxes in pixels x `scale`; use 72 / DPI for PDF points).""" items = [] for it in page["items"]: x0, y0, x1, y1 = (v * scale for v in it["box"]) if x1 <= x0 or y1 <= y0: continue seg = {"x": x0, "y": y0, "w": x1 - x0, "h": y1 - y0, "label": it["label"]} segments = [seg] if "layout_segments" in it: segments = [{**part, **{key: part[key] * scale for key in ("x", "y", "w", "h")}} for part in it["layout_segments"]] items.append({"type": it["type"], "md": it["md"], "value": it["md"], "bbox": dict(seg), "layout_segments": segments}) return {"page_number": 1, "width": page["width"] * scale, "height": page["height"] * scale, "md": page_md, "items": items}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""A PDF page as an image plus its text-layer words, both in the same pixel frame (pypdfium2).
image, words = render_pdf_page("doc.pdf", page=0, dpi=300) # words: [{text, box: [x0, y0, x1, y1]}]
The page is rendered from its CropBox with its /Rotate applied, which is how PDF viewers and ParseBench show it, andevery word box is mapped into that image (CropBox origin, rotation). Pages without a text layer give no words; theboxes then come from the model's attention alone."""from __future__ import annotations
def _to_image(l, b, r, t, crop, rot, s): cx0, cy0, cx1, cy1 = crop
def m(ux, uy): return {0: (ux - cx0, cy1 - uy), 90: (uy - cy0, ux - cx0), 180: (cx1 - ux, uy - cy0), 270: (cy1 - uy, cx1 - ux)}[rot] xs, ys = zip(m(l, b), m(r, t)) return [min(xs) * s, min(ys) * s, max(xs) * s, max(ys) * s]
def page_words(page, dpi: int = 300) -> list[dict]: """Words of a pypdfium2 page in pixels of its `render_pdf_page` image: characters joined while the gap to the next one is under 0.35 of the line height and they stay on the same line.""" s, rot, crop = dpi / 72, page.get_rotation() % 360, page.get_cropbox() tp = page.get_textpage() out, cur = [], None for i in range(tp.count_chars()): ch = tp.get_text_range(i, 1) if not ch or ch.isspace() or ch in "\r\n\x00": if cur: out.append(cur) cur = None continue box = _to_image(*tp.get_charbox(i), crop, rot, s) hgt = box[3] - box[1] if cur and box[0] - cur["box"][2] < 0.35 * hgt and abs(box[1] - cur["box"][1]) < 0.5 * hgt: cur["text"] += ch cb = cur["box"] cur["box"] = [min(cb[0], box[0]), min(cb[1], box[1]), max(cb[2], box[2]), max(cb[3], box[3])] else: if cur: out.append(cur) cur = {"text": ch, "box": box} if cur: out.append(cur) return out
def render_pdf_page(path: str, page: int = 0, dpi: int = 300): """(PIL image of the page at `dpi`, its text-layer words in that image's pixels).""" import pypdfium2 as pdfium
pg = pdfium.PdfDocument(path)[page] image = pg.render(scale=dpi / 72).to_pil().convert("RGB") return image, page_words(pg, dpi)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Place attention-grounded elements on layout-detector regions (element-first placement).
The attention says WHICH words belong to an element and roughly where they are; a detector region says where a blockof the page starts and ends. Each element takes the region(s) holding most of its words:
- one region, owned by this element alone -> the region's box- one region shared with other elements -> the region's width, over this element's own words (vertically)- several regions each holding >= 25% of words -> their union (a paragraph that continues in the next column)- a table -> the Table region holding most of its words (union with its words)- an image reference -> the Picture/Table region under its attention box (IoU or holding)- no region holding any of its words -> its attention box, unchanged
Picture regions no element claims become picture elements of their own (graphics the answer does not mention).Region boxes are pixels of the page image, like the element boxes."""from __future__ import annotations
PICTURE = {"picture", "chart", "figure"}TABLE = {"table"}SKIP = {"checkbox_selected", "checkbox_unselected"}
def _norm(label: str) -> str: """Detector label in one spelling: Docling's "Picture" / "picture", "Checkbox-Selected" / "checkbox_selected".""" return label.lower().replace("-", "_").replace(" ", "_")
def _inter(a, b) -> float: return max(0.0, min(a[2], b[2]) - max(a[0], b[0])) * max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
def _area(a) -> float: return max(0.0, a[2] - a[0]) * max(0.0, a[3] - a[1])
def _holds(r, w, pad: float) -> bool: cx, cy = (w[0] + w[2]) / 2, (w[1] + w[3]) / 2 return r[0] - pad <= cx <= r[2] + pad and r[1] - pad <= cy <= r[3] + pad
def clean_regions(dets: list[dict], min_score: float = 0.35) -> list[dict]: """Detections above `min_score`, minus a box mostly (>= 80%) inside a higher-scoring box of the same kind.""" keep: list[dict] = [] dets = [{**d, "label": _norm(d["label"])} for d in dets] for d in sorted((d for d in dets if d["score"] >= min_score and d["label"] not in SKIP), key=lambda d: -d["score"]): b = d["box"] if any(k["label"] == d["label"] and _inter(b, k["box"]) >= 0.8 * max(_area(b), 1e-9) for k in keep): continue keep.append(d) return keep
def place_on_regions(types: list[str], words: list[list], boxes: list, regions: list[dict], line_h: float, add_unclaimed_pictures: bool = True, text_too: bool = True) -> tuple[list, list[list[float]]]: """(new boxes per element, extra picture boxes). `types[i]` is element i's block type, `words[i]` its snapped word boxes (after stray filtering), `boxes[i]` its attention box (None allowed).""" pad = 0.3 * line_h R = [r["box"] for r in regions] counts = [[sum(_holds(r, w, pad) for w in ws) for r in R] for ws in words] # region -> elements that hold words in it users: dict[int, list[int]] = {} for i, c in enumerate(counts): for j, n in enumerate(c): if n and types[i] not in ("image",): users.setdefault(j, []).append(i) out = list(boxes) claimed: set[int] = set() for i, t in enumerate(types): if t == "image": b = boxes[i] if b is None: continue cand = [(j, _inter(b, R[j]) / max(min(_area(b), _area(R[j])), 1e-9)) for j, r in enumerate(regions) if r["label"] in PICTURE | TABLE] cand = [(j, v) for j, v in cand if v >= 0.5] if cand: j = max(cand, key=lambda x: x[1])[0] out[i] = list(R[j]) claimed.add(j) continue ws, c = words[i], counts[i] n = len(ws) if not n or not any(c): continue if t == "table": tj = [j for j in range(len(R)) if regions[j]["label"] in TABLE | PICTURE and c[j]] if tj: j = max(tj, key=lambda j: c[j]) if c[j] >= 0.3 * n: r = R[j] b = boxes[i] or r out[i] = [min(r[0], b[0]), min(r[1], b[1]), max(r[2], b[2]), max(r[3], b[3])] \ if _inter(b, r) >= 0.5 * _area(b) else list(r) claimed.add(j) continue if not text_too: # visual-only mode: text keeps its attention box continue main = [j for j in range(len(R)) if c[j] >= 0.25 * n and regions[j]["label"] not in PICTURE] if not main: continue for j in main: claimed.add(j) if len(main) == 1 and len(users.get(main[0], [])) == 1: out[i] = list(R[main[0]]) continue if len(main) > 1 and all(len(users.get(j, [])) == 1 for j in main): out[i] = [min(R[j][0] for j in main), min(R[j][1] for j in main), max(R[j][2] for j in main), max(R[j][3] for j in main)] continue # shared region(s): the region's horizontal extent, the element's own words vertically inside = [w for w in ws if any(_holds(R[j], w, pad) for j in main)] if not inside: continue x0 = min(R[j][0] for j in main) x1 = max(R[j][2] for j in main) y0 = max(min(w[1] for w in inside), min(R[j][1] for j in main)) y1 = min(max(w[3] for w in inside), max(R[j][3] for j in main)) if y1 > y0: out[i] = [x0, y0, x1, y1] extra = [] if add_unclaimed_pictures: for j, r in enumerate(regions): if j in claimed or r["label"] not in PICTURE: continue if any(b is not None and _inter(b, R[j]) >= 0.5 * _area(R[j]) for b in out): continue extra.append(list(R[j])) return out, extra
def ink_regions(page, kv: float = 1.0, kh: float = 1.5) -> list[dict]: """Detector-free regions from the page image alone: text blocks are the ink closed across word gaps (kh x body glyph height) and line spacing (kv x), so a paragraph is one block and a column gutter stays open; pictures are filled foreground components (the graphics an image reference snaps to). Same shape as detector output.""" import numpy as np from scipy import ndimage
h = page.med_h row, col = np.ones((1, max(3, int(kh * h)) | 1), bool), np.ones((max(3, int(kv * h)) | 1, 1), bool) closed = ndimage.binary_erosion(ndimage.binary_erosion( ndimage.binary_dilation(ndimage.binary_dilation(page.ink, row), col), row), col) lab, _ = ndimage.label(closed | page.ink) out = [] for s in ndimage.find_objects(lab): if s is None: continue y0, y1, x0, x1 = s[0].start, s[0].stop, s[1].start, s[1].stop if (y1 - y0) < 0.5 * h or (x1 - x0) < h: continue out.append({"label": "text", "score": 1.0, "box": [float(x0), float(y0), float(x1), float(y1)]}) flab, fsl = page.fg_components() for s in fsl: if s is None: continue y0, y1, x0, x1 = s[0].start, s[0].stop, s[1].start, s[1].stop w_, h_ = x1 - x0, y1 - y0 if w_ < 3 * h or h_ < 3 * h or w_ * h_ > 0.6 * page.w * page.h: continue if float(page.fg[s].mean()) < 0.35 or float(page.ink[s].mean()) > 0.5: continue out.append({"label": "picture", "score": 1.0, "box": [float(x0), float(y0), float(x1), float(y1)]}) return out12345# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""The attention-box settings this release uses (fixed; the code paths behind other switches are kept but off)."""FLAGS: dict[str, str] = {"table_fill": "1", "add_pictures": "1", "chart_tables": "1", "drop_big_words": "1", "dedupe": "1"}1234567891011121314151617181920212223242526272829303132# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Content words of a transcript (shared by the GPU capture and the scoring): character spans that hold page text,with markup removed, so ocria's RCL / HTML / markdown and Gemini's markdown / HTML are cut the same way."""import re
# HTML tags (a letter after "<", one line: a bare "<" is text, e.g. RCL's merge-left cell or "< 8.0 V");# markdown link / image targetsTAG = re.compile(r"</?[A-Za-z][^<>\n]*>|\]\([^)\s]*\)|!\[")# a word starts with a letter or digit (or a currency sign / opening bracket before one) and runs over letters, digits and# in-word punctuation; markdown/RCL markup (#, *, |, !, `, _, quotes) is never part of a wordWORD = re.compile(r"[$€£¥₹(]?[^\W_][^\s<>|*`\"\t]*")TRAIL = ".,;:)]}!?'’"
def norm(w: str) -> str: return re.sub(r"[\W_]", "", w.lower())
def word_spans(text: str) -> list[tuple[int, int, str]]: masked = TAG.sub(lambda m: " " * len(m.group()), text) masked = masked.replace(" ", " ").replace("&", "& ") out = [] for m in WORD.finditer(masked): s, e = m.start(), m.end() while e > s + 1 and masked[e - 1] in TRAIL and not (masked[e - 1] == ")" and "(" in masked[s:e - 1]): e -= 1 w = text[s:e] if norm(w): out.append((s, e, w)) return out1234# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""CPU grounding from cached attention and generated text, without raster processing."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Reusable pixel-free layout extraction from precomputed word attention.
Frozen predictors are loaded once per instance. Capture coordinates and outputboxes use the original image pixel frame; PDF frame conversion belongs to the caller."""
from pathlib import Pathimport timefrom numbers import Integral
import numpy as np
import joblib
from .navigation import constrain_sidebar_iconsfrom .headings import ( expand_table_to_embedded_heading, merge_bold_heading_continuations, merge_heading_lines, merge_numeric_callouts, trim_paragraph_heading_overlap,)from .pictures import ( merge_figure_tables, trim_picture_text_overlap, trim_picture_table_overlap,)from .io import join_paragraph_segments, merge_duplicate_text, to_layout_pagefrom .learned import ground_cached
def finalize_layout(answer: str, page: dict) -> dict: """Apply the retained checkpoint's geometry rules in their evaluation order.""" page["items"] = merge_duplicate_text(merge_heading_lines(page["items"])) trim_picture_text_overlap(page["items"]) page["items"] = merge_numeric_callouts(page["items"]) trim_paragraph_heading_overlap(page["items"]) page["items"] = join_paragraph_segments(answer, page["items"]) page["items"] = merge_figure_tables(page["items"]) page["items"] = merge_bold_heading_continuations(answer, page["items"]) page["items"] = constrain_sidebar_icons( page["items"], page["width"], page["height"] ) trim_picture_table_overlap(page["items"]) expand_table_to_embedded_heading(page["items"]) return page
def validate_capture(attention: dict) -> None: """Check external sparse coordinates before indexing arrays or native buffers.""" dimensions = np.asarray([attention["width"], attention["height"]], dtype=float) if not np.isfinite(dimensions).all() or (dimensions <= 0).any(): raise ValueError("Page dimensions must be finite and positive") grid = attention["grid"] if len(grid) != 2 or any( not isinstance(n, Integral) or isinstance(n, bool) or n <= 0 for n in grid ): raise ValueError("Attention grid must contain two positive integers") sparse = attention["sparse_maps"] if not len(sparse["idx"]) == len(sparse["val"]) == len(sparse["has"]): raise ValueError("Sparse indices, values, and validity rows must align") flags = np.asarray(sparse["has"]) if flags.ndim != 1 or (len(flags) and flags.dtype.kind != "b"): raise ValueError("Attention validity flags must be boolean") cells = int(grid[0]) * int(grid[1]) for indices, values in zip(sparse["idx"], sparse["val"], strict=True): if len(indices) != len(values): raise ValueError("Each sparse index must have one attention value") if not len(indices): continue indices = np.asarray(indices) values = np.asarray(values, dtype=np.float32) if ( indices.ndim != 1 or indices.dtype.kind not in "iu" or (indices < 0).any() or (indices >= cells).any() ): raise ValueError( "Sparse indices must be integers inside the attention grid" ) if values.ndim != 1 or not np.isfinite(values).all() or (values < 0).any(): raise ValueError("Sparse attention values must be finite and nonnegative")
class FastLayout: """A reusable backend with explicit, trusted frozen predictor artifacts."""
def __init__( self, *, words: Path, pictures: Path, regions: Path, tables: Path, peaks: Path ) -> None: self.words = joblib.load(words) self.pictures = joblib.load(pictures) self.regions = joblib.load(regions) self.tables = joblib.load(tables) self.peaks = joblib.load(peaks)
def layout_page(self, *, answer: str, attention: dict) -> dict: """Return a ParseBench page in pixels, including spatial text segments.
Attention uses the existing cache contract: width, height, grid [h,w], sparse_maps {idx, val, has}, one row per transcript attention unit. This method performs no image, PDF, network, or model-inference I/O. """ validate_capture(attention) result = ground_cached( answer, attention, self.words, picture_model=self.pictures, with_extended_context=True, region_models=self.regions, table_model=self.tables, with_region_context=True, peak_model=self.peaks, ) page = to_layout_page( answer, result["elements"], attention["width"], attention["height"] ) return finalize_layout(answer, page)
def __call__(self, *, answer: str, attention: dict) -> dict: """Return the public OCRia item schema, retaining detailed text segments.""" started = time.perf_counter() page = self.layout_page(answer=answer, attention=attention) items = [] for item in page["items"]: box = item["bbox"] items.append( { "type": item["type"], "label": box["label"], "md": item["md"], "box": [ box["x"], box["y"], box["x"] + box["w"], box["y"] + box["h"], ], "layout_segments": item["layout_segments"], } ) return { "width": page["width"], "height": page["height"], "items": items, "attention_source": "precomputed", "timings_ms": { "attention_capture": 0.0, "layout_postprocessing": (time.perf_counter() - started) * 1000, }, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Layout elements of a raw ocria answer: the character spans that each get one box, with a type.
The answer is ocria's no-layout transcription (markdown, HTML tables, `<page_header>`/`<page_footer>`/`<page_number>`furniture tags, `![label: description]` image references, ```mermaid diagrams). Each element becomes one`<!-- bbox: TYPE x0 y0 x1 y1 -->` marker, so the types are the box-mode vocabulary the layout scorer already reads(`layout_score._BOX_TYPE_TO_REGION_LABEL`): text, heading, list, table, image, code, header, footer.
Granularity (one element per ...): paragraph (blank-line separated), heading line, list item (with its indentedcontinuation lines), whole table, image reference, fenced block, display-math block, furniture band. A standalone`<page_number>` gets type "page_number" and is resolved to header/footer from its box (`resolve_page_numbers`).Offsets index the raw answer, fence included, so they line up with the teacher-forced tokens."""
from __future__ import annotations
import refrom collections.abc import Callablefrom dataclasses import dataclass
from .tune import FLAGS
_OPEN_FENCE = re.compile(r"\A\s*```(?:markdown|md)?[ \t]*\n")_FURN_OPEN = re.compile(r"<(page_header|page_footer|watermark)>")_PAGE_NUMBER = re.compile(r"^\s*<page_number>.*?</page_number>\s*$")_HEADING = re.compile(r"^\s{0,3}#{1,6}\s")_IMAGE = re.compile(r"^\s*!\[")_FENCE = re.compile(r"^\s*```")_MATH = re.compile(r"^\s*\$\$")_PIPE_ROW = re.compile(r"^\s*\|")_TABLE_OPEN = re.compile(r"<(table|rcl)\b", re.I) # HTML table, or ocria-1.5's RCL grid_LIST_ITEM = re.compile( r"^(\s*)(?:[*\-+•▪◦»]\s|\d{1,3}[.)]\s|\(?[a-zA-Z][.)]\s|\[[ xX_]*\]\s)")_QUOTE_PREFIX = re.compile(r"^(?: {0,3}>[ \t]?)+")_BOLD_LINE = re.compile(r"^\s*\*\*[^*]+\*\*:?\s*$")_TYPES_FOR_FURN = { "page_header": "header", "page_footer": "footer", "watermark": "text",}
@dataclassclass Block: type: str start: int end: int
def _lines(text: str, lo: int, hi: int) -> list[tuple[int, int, str]]: """(start, end, line) for each line of text[lo:hi]; end excludes the newline.""" out, pos = [], lo while pos < hi: nl = text.find("\n", pos, hi) end = hi if nl < 0 else nl out.append((pos, end, text[pos:end])) pos = end + 1 return out
def body_span(text: str) -> tuple[int, int]: """The transcription inside the ```markdown fence (the whole answer when there is none).""" lo, hi = 0, len(text) m = _OPEN_FENCE.match(text) if m: lo = m.end() close = text.rfind("```") if close >= lo: hi = close return lo, hi
def _starts_construct(line: str) -> bool: return bool( _HEADING.match(line) or _IMAGE.match(line) or _FENCE.match(line) or _MATH.match(line) or _PIPE_ROW.match(line) or _TABLE_OPEN.search(line) or _FURN_OPEN.search(line) or _PAGE_NUMBER.match(line) or _LIST_ITEM.match(line) )
def split_blocks(text: str) -> list[Block]: """Layout elements of one page's raw answer, in reading order.""" lo, hi = body_span(text) lines = _lines(text, lo, hi) blocks: list[Block] = [] i = 0
def until(j: int, pred: Callable[[str], bool]) -> int: """Index of the first line from j on for which pred holds (the last line when none does).""" while j < len(lines) and not pred(lines[j][2]): j += 1 return min(j, len(lines) - 1)
while i < len(lines): s, e, line = lines[i] if not line.strip(): i += 1 continue m = _FURN_OPEN.search(line) if m: tag = m.group(1) close = f"</{tag}>" j = i if close in line else until(i + 1, lambda x: close in x) blocks.append(Block(_TYPES_FOR_FURN[tag], s, lines[j][1])) i = j + 1 continue if _PAGE_NUMBER.match(line): blocks.append(Block("page_number", s, e)) i += 1 continue tm = _TABLE_OPEN.search(line) if tm: close = "</table>" if tm.group(1).lower() == "table" else "</rcl>" j = ( i if close in line.lower() else until(i + 1, lambda x: close in x.lower()) ) if "split_layout_tables" in FLAGS and _is_layout_table( text[s : lines[j][1]] ): blocks.extend(_layout_table_blocks(text, s, lines[j][1])) else: blocks.append(Block("table", s, lines[j][1])) i = j + 1 continue if _FENCE.match(line): j = until(i + 1, lambda x: _FENCE.match(x) is not None) kind = "image" if "mermaid" in line.lower() else "code" blocks.append(Block(kind, s, lines[j][1])) i = j + 1 continue if _MATH.match(line): rest = line.strip()[2:] j = i if "$$" in rest else until(i + 1, lambda x: "$$" in x) blocks.append(Block("text", s, lines[j][1])) i = j + 1 continue if _HEADING.match(line): blocks.append(Block("heading", s, e)) i += 1 continue if _IMAGE.match(line): blocks.append(Block("image", s, e)) i += 1 continue if _PIPE_ROW.match(line): j = i while j + 1 < len(lines) and _PIPE_ROW.match(lines[j + 1][2]): j += 1 blocks.append(Block("table", s, lines[j][1])) i = j + 1 continue lm = _LIST_ITEM.match(line) if lm: indent = len(lm.group(1)) j = i while j + 1 < len(lines): nxt = lines[j + 1][2] if not nxt.strip() or _starts_construct(nxt): break if ( len(nxt) - len(nxt.lstrip()) <= indent ): # a continuation line is indented under the marker break j += 1 blocks.append(Block("list", s, lines[j][1])) i = j + 1 continue if ( "split_lines" in FLAGS ): # each line its own element; a bold-only line is a heading blocks.append(Block("heading" if _BOLD_LINE.match(line) else "text", s, e)) i += 1 continue j = i # paragraph: until a blank line or a line that opens another element while ( j + 1 < len(lines) and lines[j + 1][2].strip() and not _starts_construct(lines[j + 1][2]) ): j += 1 blocks.append(Block("text", s, lines[j][1])) i = j + 1 blocks = [piece for block in blocks for piece in _split_quoted_list(text, block)] if "inline_images" in FLAGS: blocks = [p for b in blocks for p in _split_inline_images(text, b)] return blocks
def _split_quoted_list(text: str, block: Block) -> list[Block]: """Expose quoted list items while retaining raw offsets and continuation lines.
Quote prefixes are ignored only for recognizing markers. Keeping the raw spans preserves the word sequence used by cached sparse attention maps. """ if block.type != "text" or ">" not in text[block.start : block.end]: return [block] result: list[Block] = [] start, kind = block.start, block.type for line_start, _, line in _lines(text, block.start, block.end): prefix = _QUOTE_PREFIX.match(line) if prefix is None or not _LIST_ITEM.match(line[prefix.end() :]): continue if line_start > start and text[start:line_start].strip(" >\t\r\n"): result.append(Block(kind, start, line_start)) start, kind = line_start, "list" result.append(Block(kind, start, block.end)) return result
_INLINE_IMAGE = re.compile(r"!\[[^\]\n]*\](?:\([^)\s]*\))?")
def _split_inline_images(text: str, b: Block) -> list[Block]: """An image reference inside a text-like element (an icon after a heading, a logo next to a footer's page number) is a picture of its own on the page: the element is cut into the text before it, the image, and the text after.""" if b.type in ("image", "table", "code") or "![" not in text[b.start : b.end]: return [b] out, pos = [], b.start for m in _INLINE_IMAGE.finditer(text, b.start, b.end): if _TAGS.sub("", text[pos : m.start()]).strip(" \t\n|*#-"): out.append(Block(b.type, pos, m.start())) out.append(Block("image", m.start(), m.end())) pos = m.end() if _TAGS.sub("", text[pos : b.end]).strip(" \t\n|*#-"): out.append(Block(b.type, pos, b.end)) return out or [b]
def resolve_page_numbers(blocks: list[Block], boxes: list, page_height: float) -> None: """A standalone page number is furniture: header when its box sits in the top half, else footer.""" for b, box in zip(blocks, boxes): if b.type == "page_number": b.type = ( "header" if box is not None and (box[1] + box[3]) / 2 < page_height / 2 else "footer" )
_CELL = re.compile(r"<t[dh][^>]*>(.*?)</t[dh]>", re.S | re.I)_TAGS = re.compile(r"<[^>]+>")
def _is_layout_table(html: str) -> bool: """A table used to lay out a page (people grids, card layouts), not data: it holds image references, or its cells hold prose (mean >= 8 words).""" if "![" in html: return True words = [len(_TAGS.sub(" ", c).split()) for c in _CELL.findall(html) if c.strip()] return bool(words) and sum(words) / len(words) >= 8
def _layout_table_blocks(text: str, lo: int, hi: int) -> list[Block]: """One element per segment of each cell: segments split at blank lines (two or more <br>, or any <br> with split_br), an image reference is its own element.""" sep = re.compile( r"(?:<br\s*/?>\s*)+" if "split_br" in FLAGS else r"(?:<br\s*/?>\s*){2,}", re.I ) out: list[Block] = [] for m in _CELL.finditer(text, lo, hi): a, b = m.start(1), m.end(1) pos = a for cut in [*sep.finditer(text, a, b), None]: end = cut.start() if cut else b seg = text[pos:end] if _TAGS.sub("", seg).strip(): k = pos + (len(seg) - len(seg.lstrip())) origin = k for im in re.finditer(r"!\[[^\]]*\]", text[origin:end]): start, stop = origin + im.start(), origin + im.end() if text[k:start].strip(): out.append(Block("text", k, start)) out.append(Block("image", start, stop)) k = stop if _TAGS.sub("", text[k:end]).strip(): out.append(Block("text", k, end)) pos = cut.end() if cut else b return out12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Spatial operations on attention-derived rectangles; no raster input."""
def envelope(boxes: list[list[float]]) -> list[float]: return [ min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes), ]
def main_cluster( boxes: list[list[float]], line_h: float, wide: bool = False) -> list[list[float]]: """The largest group of word boxes chained by proximity (vertical gap <= 1.5 lines; horizontal gap <= 4 lines, or any for a table, whose columns sit far apart). Words outside it are attention strays.""" n = len(boxes) if n <= 2: return boxes dy_max, dx_max = 1.5 * line_h, (float("inf") if wide else 4.0 * line_h) if wide and line_h >= 0: # With no horizontal limit, connected components are merged y intervals. interval_groups = [] current = [] bottom = float("-inf") for i in sorted(range(n), key=lambda i: boxes[i][1]): if current and boxes[i][1] - bottom > dy_max: interval_groups.append(current) current = [] current.append(i) bottom = max(bottom, boxes[i][3]) interval_groups.append(current) best = max(interval_groups, key=lambda group: (len(group), -min(group))) return [boxes[i] for i in sorted(best)] parent = list(range(n))
def find(i: int) -> int: while parent[i] != i: parent[i] = parent[parent[i]] i = parent[i] return i
order = sorted(range(n), key=lambda i: boxes[i][1]) for a_i, a in enumerate(order): for b in order[a_i + 1 :]: if boxes[b][1] - boxes[a][3] > dy_max: break p, q = boxes[a], boxes[b] dy = max(0.0, max(p[1], q[1]) - min(p[3], q[3])) dx = max(0.0, max(p[0], q[0]) - min(p[2], q[2])) if dy <= dy_max and dx <= dx_max: parent[find(a)] = find(b) groups: dict[int, list[int]] = {} for i in range(n): groups.setdefault(find(i), []).append(i) best = max(groups.values(), key=len) return [boxes[i] for i in best]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Recover list items stored as HTML rows with a bullet-only first cell."""
import re
from .blocks import Block
_TABLE = re.compile(r"\s*<table\b[^>]*>(.*?)</table>\s*", re.I | re.S)_ROW = re.compile(r"<tr\b[^>]*>(.*?)</tr>", re.I | re.S)_CELL = re.compile(r"<(td|th)\b([^>]*)>(.*?)</\1>", re.I | re.S)_TAG = re.compile(r"<[^>]*>")_SPAN = re.compile(r"\b(?:rowspan|colspan)\s*=", re.I)
def split_bullet_tables(answer: str, blocks: list[Block]) -> list[Block]: """Keep raw content spans so existing cached word indices remain valid.
Every body row must contain exactly a literal bullet cell and a text cell. An optional first header becomes a heading. Unparsed content or merged body cells preserve the whole table, avoiding loss of words or table relationships. """ result = [] for block in blocks: if block.type != "table": result.append(block) continue table = _TABLE.fullmatch(answer[block.start : block.end]) if table is None or "<table" in table[1].lower(): result.append(block) continue body = table[1] rows = list(_ROW.finditer(body)) pieces = [] bullets = 0 if _ROW.sub("", body).strip(): result.append(block) continue for index, row in enumerate(rows): cells = list(_CELL.finditer(row[1])) if _CELL.sub("", row[1]).strip(): break if len(cells) == 1 and index == 0 and cells[0][1].lower() == "th": kind, cell = "heading", cells[0] elif ( len(cells) == 2 and _TAG.sub("", cells[0][3]).strip() in {"•", "●", "▪", "◦"} and not any(_SPAN.search(cell[2]) for cell in cells) ): kind, cell = "list", cells[1] bullets += 1 else: break if not _TAG.sub("", cell[3]).strip(): break offset = block.start + table.start(1) + row.start(1) pieces.append(Block(kind, offset + cell.start(3), offset + cell.end(3))) if bullets and len(pieces) == len(rows) and len(pieces) >= 2: result.extend(pieces) else: result.append(block) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).# This is not open-source software: see the license for permitted uses."""Detector-free boxes from attention cells, without reading page pixels."""
import statistics
import numpy as npfrom scipy import ndimage
from .blocks import Block, resolve_page_numbersfrom .boxes import envelope, main_clusterfrom .geometry import paragraph_pathsfrom .words import normfrom .io import SparseWordMaps
def attention_boxes( size: tuple[int, int], blocks: list[Block], units: list[tuple[int, int]], per_block: list[list[int]], maps: np.ndarray | SparseWordMaps, grid: tuple[int, int], has: np.ndarray, support: bool = False, answer: str = "", infer_words: bool = False, support_boxes: dict[int, tuple[int, int, int, int]] | None = None, peak_indices: np.ndarray | None = None,) -> dict: """Use peak cells for words and connected attention support for pictures.
Coordinates are projected directly from the attention grid to image pixels. Consecutive words sharing a cell collapse for path selection, while their original text spans remain intact. No ink, rendering, or pixel masks are used. Optional support boxes are per-unit cell bounds for the same 0.3-threshold, eight-connected peak component; omitted entries use the normal calculation. """ width, height = size gh, gw = grid cw, ch = width / gw, height / gh if peak_indices is None and isinstance(maps, SparseWordMaps): peaks = maps.peaks elif peak_indices is None: peaks = ( np.argmax(maps.reshape(len(maps), -1), axis=1) if len(maps) else np.array([], dtype=int) ) else: peaks = peak_indices lengths = [max(1, len(norm(answer[s:e]))) for s, e in units] if infer_words else [] advances: dict[int, list[float]] = {} if infer_words: # Adjacent word centres constrain character advance without a font or # pixel detector. Ignore reversed/different-line pairs and large gaps. for k, (block, indices) in enumerate(zip(blocks, per_block)): if block.type == "image": continue estimates = [] for a, b in zip(indices, indices[1:]): ya, xa = divmod(int(peaks[a]), gw) yb, xb = divmod(int(peaks[b]), gw) advance = (xb - xa) * cw / ((lengths[a] + lengths[b]) / 2 + 1) if has[a] and has[b] and ya == yb and 0.1 * cw <= advance <= 1.5 * cw: estimates.append(advance) advances[k] = estimates global_advance = statistics.median( [a for values in advances.values() for a in values] or [0.5 * ch] ) pieces: list[Block] = [] boxes: list[list[float] | None] = [] for block_index, (block, indices) in enumerate(zip(blocks, per_block)): estimates = advances.get(block_index, []) advance = ( statistics.median(estimates) if len(estimates) >= 3 else global_advance ) located: list[tuple[int, list[float]]] = [] for u in indices: if not has[u]: continue y, x = divmod(int(peaks[u]), gw) maximum = ( maps.maxima[u] if isinstance(maps, SparseWordMaps) else maps[u, y, x] ) if maximum <= 0: continue x0, y0, x1, y1 = int(x), int(y), int(x) + 1, int(y) + 1 if support and support_boxes is not None and u in support_boxes: x0, y0, x1, y1 = support_boxes[u] elif support or block.type == "image": m = maps[u] labels, _ = ndimage.label( m >= 0.3 * float(m[y, x]), structure=np.ones((3, 3)) ) yy, xx = np.nonzero(labels == labels[y, x]) x0, y0, x1, y1 = ( int(xx.min()), int(yy.min()), int(xx.max()) + 1, int(yy.max()) + 1, ) box = [x0 * cw, y0 * ch, x1 * cw, y1 * ch] if infer_words and block.type != "image": cx, cy = (x + 0.5) * cw, (y + 0.5) * ch half_width, half_height = ( max(cw / 2, lengths[u] * advance / 2), 0.85 * advance, ) box = [ max(0.0, cx - half_width), max(0.0, cy - half_height), min(float(width), cx + half_width), min(float(height), cy + half_height), ] if not located or box != located[-1][1]: located.append((u, box)) if not located: pieces.append(Block(block.type, block.start, block.end)) boxes.append(None) continue words = [box for _, box in located] paths = ( paragraph_paths(words) if block.type in ("text", "list", "heading") else None ) if infer_words and block.type == "heading" and paths: # A heading can have wide spaces; its supported runs share one box. paths = [[i for path in paths for i in path]] if paths: for k, path in enumerate(paths): start = block.start if k == 0 else units[located[path[0]][0]][0] end = ( block.end if k + 1 == len(paths) else units[located[paths[k + 1][0]][0]][0] ) pieces.append(Block(block.type, start, end)) boxes.append(envelope([words[i] for i in path])) else: pieces.append(Block(block.type, block.start, block.end)) boxes.append(envelope(main_cluster(words, ch, wide=block.type == "table"))) resolve_page_numbers(pieces, boxes, height) return { "width": width, "height": height, "grid": list(grid), "elements": [ { "type": b.type, "start": b.start, "end": b.end, "box": None if box is None else [round(v, 1) for v in box], } for b, box in zip(pieces, boxes) ], }.eval_results/parsebench-2.yamlAdded+32
.eval_results/parsebench.yamlAdded+28
.gitattributes+9
LICENSEAdded+73
assets/boxes_table_texas.jpgAdded

Large File Pointer Details
- SHA256: f746cb579c4ac59d4bc4e8c32d64f27811e07f2b565d73198346bb6221cd433f
- Pointer size: 131 Bytes
- Size of remote file: 358 kB
assets/chart_line_output.pngAdded

assets/chart_line_page.jpgAdded

Large File Pointer Details
- SHA256: 93593d987b1689cb685af0b2676fd327f7cd4110bcd8bba3f8a0e376adb2799e
- Pointer size: 131 Bytes
- Size of remote file: 111 kB
assets/format_hearing_output.pngAdded

Large File Pointer Details
- SHA256: 84850f9794c890755f875e37be3ac652f5540e2877abec62e406b97d1cda41bf
- Pointer size: 131 Bytes
- Size of remote file: 288 kB
assets/format_hearing_page.jpgAdded

Large File Pointer Details
- SHA256: adf6668209ba2dc7c31c1bf8398397f037ece24beebfa9a870d042201c268c41
- Pointer size: 131 Bytes
- Size of remote file: 492 kB
assets/handwritten_math_output.pngAdded

assets/handwritten_math_page.jpgAdded

Large File Pointer Details
- SHA256: e65d04d4712f4d66a32de7137038ba60df0a2ded68fcfdae9cca3b0d0538eebd
- Pointer size: 131 Bytes
- Size of remote file: 208 kB
assets/llamaindex-logo.pngAdded

assets/ocria1_radar.pngAdded

Large File Pointer Details
- SHA256: 96f9bc2a7a3cfb20bb11ad3274ba9345386bad19fc9e40f5b86f68ced783e69f
- Pointer size: 131 Bytes
- Size of remote file: 121 kB
assets/table_texas_output.pngAdded

Large File Pointer Details
- SHA256: fb4c254f097bba4d87e01cf050eada915ed732e6cc385e0024fa6da572774d4d
- Pointer size: 131 Bytes
- Size of remote file: 240 kB
assets/table_texas_page.jpgAdded

Large File Pointer Details
- SHA256: 77015e54fde0b30d7e75ae9b65629c774c5a4656bf532cb0e72d5aed98fa7b45
- Pointer size: 131 Bytes
- Size of remote file: 323 kB
chat_template.jinjaAdded+154
config.jsonAdded+632
examples/boxes.pyAdded+76
examples/serve_boxes.pyAdded+86
fast_layout_models/manifest.jsonAdded+11
fast_layout_models/peaks.joblibAdded+3
fast_layout_models/pictures.joblibAdded+3
fast_layout_models/regions.joblibAdded+3
fast_layout_models/tables.joblibAdded+3
fast_layout_models/words.joblibAdded+3
generation_config.jsonAdded+9
model-00001-of-00002.safetensorsAdded+3
model-00002-of-00002.safetensorsAdded+3
model.safetensors.index.jsonAdded+988
ocria_grounding/__init__.pyAdded+76
ocria_grounding/align.pyAdded+123
ocria_grounding/blocks.pyAdded+227
ocria_grounding/boxes.pyAdded+390
ocria_grounding/capture.pyAdded+103
ocria_grounding/detector.pyAdded+44
ocria_grounding/geometry.pyAdded+90
ocria_grounding/ground.pyAdded+415
ocria_grounding/heads.jsonAdded+10
ocria_grounding/heads.pyAdded+16
ocria_grounding/layout.pyAdded+258
ocria_grounding/pdf.pyAdded+59
ocria_grounding/regions.pyAdded+165
ocria_grounding/tune.pyAdded+5
ocria_grounding/words.pyAdded+32
parse_rl_utils/ocria_attention_grounding/__init__.pyAdded+4
parse_rl_utils/ocria_attention_grounding/api.pyAdded+155
parse_rl_utils/ocria_attention_grounding/blocks.pyAdded+289
parse_rl_utils/ocria_attention_grounding/boxes.pyAdded+61
parse_rl_utils/ocria_attention_grounding/bullet_tables.pyAdded+63
parse_rl_utils/ocria_attention_grounding/coarse.pyAdded+159