Enable KV caching for high-performance inference
mainuse_cache=True parameter in ORTSeq2Seq.repository·main·Indexed 43 days ago
https://github.com/puhuilab/phocrA high-performance Optical Character Recognition (OCR) toolkit featuring the PH-OCRv1 recognition model. It supports multi-language text recognition (including Chinese, English, Japanese, Korean, and Russian) with sub-0.x% character error rates. The toolkit includes components for text detection (TextDetector), orientation classification (TextClassifier), and precise bounding box calculation (CalRecBoxes), with specific optimizations for Transformer inference using ONNX Runtime.
use_cache=True parameter in ORTSeq2Seq.To improve performance and reduce memory overhead during Transformer inference (especially during Beam Search), the following optimizations are implemented:
cross_attn_kvs with shape (num_layers, batch_size, head_size, src_len, 2 * head_dim).cross_attn_kvs along the batch_size dimension (which consumes significant VRAM), the Attention calculation is modified to use lazy broadcasting. The input to the Decoder remains un-repeated.merged_self_attn_kvs output.merged_self_attn_kvs on the GPU).To use PHOCR, initialize the PHOCR engine and pass an image path to the instance. The engine returns a result object that supports visualization and Markdown export.
from phocr import PHOCR
# Initialize OCR engine
engine = PHOCR()
# Perform OCR on an image
result = engine("path/to/image.jpg")
print(result)
# Visualize the results and save to a file
result.vis("output.jpg")
# Export results to Markdown format
print(result.to_markdown())PHOCR includes scripts to run recognition benchmarks and calculate the Character Error Rate (CER) using standardized datasets (e.g., zh_en_rec_bench, jp_rec_bench).
# Run the full benchmark process
sh benchmark/run_recognition.sh
# Calculate the Character Error Rate (CER)
sh benchmark/run_score.shPHOCR includes scripts to run comprehensive benchmarks and evaluate model performance using standardized datasets.
To run the complete benchmark pipeline:
sh benchmark/run_recognition.shTo calculate the Character Error Rate (CER) for model predictions:
sh benchmark/run_score.shsh benchmark/run_recognition.sh
sh benchmark/run_score.shPHOCR offers three installation methods depending on your hardware requirements and how you want to manage ONNX Runtime. Choose one of the following:
Install the version optimized for CPU usage using ONNX Runtime.
Install the version optimized for CUDA. Requirement: You must have the CUDA Toolkit and cuDNN library correctly installed on your system. You can install these via conda or manually.
If you want to manage your own onnxruntime or onnxruntime-gpu installation, install the base package.
# Method 1: CPU version
pip install phocr[cpu]
# Method 2: GPU version
pip install phocr[cuda]
# (Optional) Install dependencies via conda if needed:
# conda install -c nvidia cuda-runtime=12.1 cudnn=9
# Method 3: Manual management
pip install phocrTo perform OCR on an image using the PHOCR Python API, initialize the PHOCR engine and pass the image path to the engine instance. The resulting object allows for visualization and exporting results to Markdown format.
from phocr import PHOCR
# Initialize OCR engine
engine = PHOCR()
# Perform OCR on image
result = engine("path/to/image.jpg")
print(result)
# Visualize results
result.vis("output.jpg")
print(result.to_markdown())PHOCR can be installed using one of three methods depending on your hardware requirements and ONNX Runtime preference. Choose the method that best fits your environment:
For standard CPU-based inference:
pip install phocr[cpu]For hardware-accelerated inference. Note: You must have the CUDA toolkit and cuDNN library properly installed on your system. You can install them via conda:
conda install -c nvidia cuda-runtime=12.1 cudnn=9Then install PHOCR with CUDA support:
pip install phocr[cuda]If you prefer to manage onnxruntime or onnxruntime-gpu yourself, install the base package:
pip install phocrpip install phocr[cpu]
# OR
pip install phocr[cuda]
# OR
pip install phocrBecause ONNX Runtime's automatic memory allocation can be inefficient, you can manually manage KV cache space for better performance:
(num_layers, batchxbeam, head_num, max_seq_len, 2 * head_dim).Warning: When using IO binding, you cannot bind raw pointers obtained directly from cudaMalloc. You must use the memory managed by the framework (e.g., via PyTorch tensors).
# Conceptual approach for pre-allocating KV cache space
# Shape: (num_layers, batchxbeam, head_num, max_seq_len, 2 * head_dim)
kv_cache_space = torch.empty((num_layers, batchxbeam, head_num, max_seq_len, 2 * head_dim), device='cuda')
# Use kv_cache_space with ONNX Runtime IO binding for inferenceThe return type of the PHOCR call depends on which stages are enabled. If all stages are enabled, it returns a PHOCROutput object.
PHOCROutput Fields:
img: The original input image (np.ndarray).boxes: Bounding boxes for detected text (coordinates mapped back to original image scale).txts: A tuple of recognized text strings.scores: A tuple of confidence scores corresponding to the text.elapse_list: A list containing the execution time for [det, cls, rec] stages.lang_type: The language type used for recognition (from config).Conditional Returns:
TextDetOutput.TextClsOutput.TextRecOutput.PHOCROutput object.The ImageSegmenter is used to handle images that are too wide for the recognition model by splitting them into manageable patches.
It works by:
h=32).This ensures that text spanning across a large width is processed in chunks while maintaining the context of the original image structure.