# Copyright 2025 The VenusOCR Authors and the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """VenusOCR model configuration.""" import inspect from transformers.configuration_utils import PreTrainedConfig from transformers.modeling_rope_utils import RopeParameters from transformers.utils import logging logger = logging.get_logger(__name__) class VenusOCRVisionConfig(PreTrainedConfig): r"""Configuration for the VenusOCR vision encoder (SigLIP-based ViT). Matches the architecture of ``google/siglip-so400m-patch14-384`` with the following extensions: * ``spatial_merge_size``: used by the projector to group ``m×m`` adjacent patch tokens before projecting into the LLM embedding space. * ``num_channels``: number of input image channels (default 3 for RGB). Args: hidden_size (`int`, *optional*, defaults to 1152): Dimensionality of patch embeddings and encoder hidden states. intermediate_size (`int`, *optional*, defaults to 4304): Dimensionality of the MLP inner layer inside each encoder block. num_hidden_layers (`int`, *optional*, defaults to 27): Number of Transformer encoder layers. num_attention_heads (`int`, *optional*, defaults to 16): Number of attention heads per encoder layer. num_channels (`int`, *optional*, defaults to 3): Number of input image channels. image_size (`int`, *optional*, defaults to 384): Training resolution (height = width = image_size). Used to determine the base number of position-embedding slots before interpolation. patch_size (`int`, *optional*, defaults to 14): Side length of each image patch in pixels. hidden_act (`str`, *optional*, defaults to ``"gelu_pytorch_tanh"``): Activation function used in the vision MLP blocks. layer_norm_eps (`float`, *optional*, defaults to 1e-6): Epsilon for all LayerNorm operations in the vision encoder. attention_dropout (`float`, *optional*, defaults to 0.0): Dropout probability applied to attention weights. spatial_merge_size (`int`, *optional*, defaults to 2): Number of patch rows (= columns) to merge in the projector. Each group of ``spatial_merge_size × spatial_merge_size`` patches is concatenated and projected as a single LLM token. Example:: >>> from transformers import AutoConfig >>> cfg = AutoConfig.from_pretrained("VenusOCR/VenusOCR2-1B", trust_remote_code=True) >>> cfg.vision_config.hidden_size 1152 """ model_type = "venusocr_vision" base_config_key = "vision_config" hidden_size: int = 1152 intermediate_size: int = 4304 num_hidden_layers: int = 27 num_attention_heads: int = 16 num_channels: int = 3 image_size: int = 384 patch_size: int = 14 hidden_act: str = "gelu_pytorch_tanh" layer_norm_eps: float = 1e-6 attention_dropout: float = 0.0 spatial_merge_size: int = 2 class VenusOCRTextConfig(PreTrainedConfig): r"""Configuration for the VenusOCR text decoder. Subclasses :class:`transformers.Qwen3Config` so that ``Qwen3Model`` can be used directly without any adapter layer. All Qwen3-0.6B defaults are inherited and can be overridden via keyword arguments. The key differences from the base ``Qwen3Config`` defaults: * ``use_sliding_window = False`` – VenusOCR does **not** use sliding-window attention (consistent with PaddleOCR-VL and GLM-OCR). Example:: >>> from transformers import AutoConfig >>> cfg = AutoConfig.from_pretrained("VenusOCR/VenusOCR2-1B", trust_remote_code=True) >>> cfg.text_config.hidden_size 1024 """ model_type = "venusocr_text" base_config_key = "text_config" default_theta = 500000.0 hidden_size: int = 4096 intermediate_size: int = 22016 num_hidden_layers: int = 32 num_attention_heads: int = 32 num_key_value_heads: int = 32 head_dim: int = 128 hidden_act: str = "silu" max_position_embeddings: int = 128000 vocab_size: int = 151936 rms_norm_eps: float = 1e-6 use_cache: bool = True pad_token_id: int | None = 151643 bos_token_id: int | None = 151643 eos_token_id: int | list[int] | None = 151645 tie_word_embeddings: bool = True attention_bias: bool = False attention_dropout: float = 0.0 use_sliding_window: bool = False sliding_window: int = 4096 max_window_layers: int = 28 rope_theta: float = 1_000_000.0 initializer_range: float = 0.02 rope_parameters: RopeParameters | dict | None = None def __post_init__(self, **kwargs): if self.num_key_value_heads is None: self.num_key_value_heads = self.num_attention_heads self.head_dim = self.head_dim if self.head_dim is not None else self.hidden_size // self.num_attention_heads super().__post_init__(**kwargs) class VenusOCRConfig(PreTrainedConfig): r"""Configuration class for the VenusOCR multimodal model. VenusOCR consists of three components: 1. **Vision encoder** – SigLIP-based ViT (→ :class:`VenusOCRVisionConfig`) 2. **Spatial-merge projector** – groups ``spatial_merge_size²`` patches and projects them into the LLM embedding space 3. **Language decoder** – Qwen3-based causal LM (→ :class:`VenusOCRTextConfig`) Args: vision_config (`dict` or :class:`VenusOCRVisionConfig`, *optional*): Configuration for the vision encoder. If ``None``, defaults to ``VenusOCRVisionConfig()`` (so400m/14 @ 384 settings). text_config (`dict` or :class:`VenusOCRTextConfig`, *optional*): Configuration for the text decoder. If ``None``, defaults to ``VenusOCRTextConfig()`` (Qwen3-0.6B settings). image_token_id (`int`, *optional*, defaults to 151655): Token id used as the ```` placeholder in input sequences. spatial_merge_size (`int`, *optional*, defaults to 2): Passed through to :class:`VenusOCRVisionConfig` **and** used directly by :class:`VenusOCRProjector`. Setting it here keeps a single source of truth. Example:: >>> from transformers import AutoConfig, AutoModelForCausalLM >>> config = AutoConfig.from_pretrained("VenusOCR/VenusOCR2-1B", trust_remote_code=True) >>> model = AutoModelForCausalLM.from_config(config, trust_remote_code=True) """ model_type = "venusocr" sub_configs = { "vision_config": VenusOCRVisionConfig, "text_config": VenusOCRTextConfig, } keys_to_ignore_at_inference = ["past_key_values"] text_config: dict | PreTrainedConfig | None = None vision_config: dict | PreTrainedConfig | None = None image_token_id: int = 151655 vision_start_token_id: int = 151652 vision_end_token_id: int = 151653 tie_word_embeddings: bool = True def __post_init__(self, **kwargs): if isinstance(self.vision_config, dict): self.vision_config = self.sub_configs["vision_config"](**self.vision_config) elif self.vision_config is None: self.vision_config = self.sub_configs["vision_config"]() # Hub configs are saved as flat dicts so we pop some of kwargs to init `TextConfig` text_params = inspect.signature(self.sub_configs["text_config"].__init__).parameters.keys() text_params = list(text_params) + ["rope_parameters", "rope_scaling", "rope_theta"] text_kwargs = {key: kwargs.pop(key) for key in text_params if key in kwargs} if isinstance(self.text_config, dict): self.text_config = self.sub_configs["text_config"](**self.text_config) elif self.text_config is None: # Hub configs are saved as flat dicts so we pop some of kwargs to init `TextConfig` text_kwargs["dtype"] = kwargs.get("torch_dtype", kwargs.get("dtype")) # don't pop the dtype self.text_config = self.sub_configs["text_config"](**text_kwargs) super().__post_init__(**kwargs) __all__ = [ "VenusOCRVisionConfig", "VenusOCRTextConfig", "VenusOCRConfig", ]