Add HunyuanOCR Vision-Language Model Support #3306
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR adds support for HunyuanOCR, a Vision-Language Model optimized for document OCR tasks developed by Tencent. The model combines a Vision Transformer encoder with a Transformer decoder for high-quality text recognition from document images.
Model: tencent/HunyuanOCR
Features
--features flash-attnArchitecture
HunyuanOCR consists of:
Vision Encoder (
vision.rs)Text Decoder (
text.rs)Configuration (
config.rs)Usage
Implementation Details
xDRoPE Position Encoding
HunyuanOCR uses Extended Dynamic Rotary Position Embedding (xDRoPE) which encodes 4 dimensions:
The
xdrope_sectionconfig[16, 16, 16, 16]specifies how the 64-dim head is split across these 4 dimensions.Smart Resize Algorithm
Images are resized to ensure:
factor(patch_size × spatial_merge_size = 32)Vision-Text Integration
Image tokens are injected into the text sequence using special tokens:
<IM_START>(120118): Marks beginning of image tokens<IMAGE>(120120): Placeholder for each image patch token<IM_END>(120119): Marks end of image tokens<IM_NEWLINE>(120121): Added at end of each patch rowFiles Changed
candle-transformers/src/models/hunyuan_ocr/mod.rs- Main model implementationcandle-transformers/src/models/hunyuan_ocr/vision.rs- Vision encodercandle-transformers/src/models/hunyuan_ocr/text.rs- Text decoder with xDRoPEcandle-transformers/src/models/hunyuan_ocr/config.rs- Configuration structscandle-transformers/src/models/mod.rs- Module exportcandle-examples/examples/hunyuan-ocr/main.rs- Example applicationcandle-examples/examples/hunyuan-ocr/README.md- DocumentationTest Results
Metal (Apple Silicon)
CUDA
CUDA + Flash Attention
Testing
The implementation has been validated against the official PyTorch implementation to ensure numerical correctness.
Huggingface Space
Tencent WebSite
References