configuration_blt.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Blt model configuration"""
  15. from huggingface_hub.dataclasses import strict
  16. from ...configuration_utils import PreTrainedConfig
  17. from ...modeling_rope_utils import RopeParameters
  18. from ...utils import auto_docstring, logging
  19. logger = logging.get_logger(__name__)
  20. @auto_docstring(checkpoint="itazap/blt-1b-hf")
  21. @strict
  22. class BltLocalEncoderConfig(PreTrainedConfig):
  23. r"""
  24. cross_attn_all_layers (`bool`, *optional*, defaults to `True`):
  25. Whether all attention layers have cross attention.
  26. cross_attn_k (`int`, *optional*, defaults to 2):
  27. Number of cross-attention heads used in the model.
  28. hidden_size_global (`int`, *int*, defaults to 2048):
  29. Hidden size of the global transformer layer.
  30. """
  31. model_type = "blt_local_encoder"
  32. default_theta = 500000.0
  33. vocab_size: int = 260
  34. cross_attn_all_layers: bool | None = False
  35. cross_attn_k: int | None = 2
  36. hidden_size_global: int | None = 2048
  37. hidden_size: int = 1024
  38. num_attention_heads: int = 16
  39. num_key_value_heads: int | None = None
  40. num_hidden_layers: int = 1
  41. rms_norm_eps: float = 1e-5
  42. dropout: float | int | None = 0.0
  43. max_position_embeddings: int = 24576
  44. rope_parameters: RopeParameters | dict | None = None
  45. hidden_act: str = "silu"
  46. intermediate_size: int | None = None
  47. initializer_range: float = 0.02
  48. def __post_init__(self, **kwargs):
  49. self.num_key_value_heads = self.num_key_value_heads or self.num_attention_heads
  50. self.intermediate_size = self.intermediate_size or int(8 * self.hidden_size / 3)
  51. self.tie_word_embeddings = False
  52. super().__post_init__(**kwargs)
  53. @auto_docstring(checkpoint="itazap/blt-1b-hf")
  54. @strict
  55. class BltLocalDecoderConfig(PreTrainedConfig):
  56. r"""
  57. cross_attn_all_layers (`bool`, *optional*, defaults to `True`):
  58. Whether all attention layers have cross attention.
  59. cross_attn_k (`int`, *optional*, defaults to 2):
  60. Number of cross-attention heads used in the model.
  61. hidden_size_global (`int`, *int*, defaults to 2048):
  62. Hidden size of the global transformer layer.
  63. """
  64. model_type = "blt_local_decoder"
  65. default_theta = 500000.0
  66. vocab_size: int = 260
  67. cross_attn_all_layers: bool | None = True
  68. cross_attn_k: int | None = 2
  69. hidden_size_global: int | None = 2048
  70. hidden_size: int = 1024
  71. num_attention_heads: int = 16
  72. num_key_value_heads: int | None = None
  73. num_hidden_layers: int = 9
  74. rms_norm_eps: float = 1e-5
  75. dropout: float | int | None = 0.0
  76. max_position_embeddings: int = 24576
  77. rope_parameters: RopeParameters | dict | None = None
  78. hidden_act: str = "silu"
  79. intermediate_size: int = 2816
  80. initializer_range: float = 0.02
  81. pad_token_id: int | None = None
  82. bos_token_id: int | None = None
  83. eos_token_id: int | list[int] | None = None
  84. tie_word_embeddings: bool = False
  85. def __post_init__(self, **kwargs):
  86. self.num_key_value_heads = self.num_key_value_heads or self.num_attention_heads
  87. self.head_dim = self.hidden_size // self.num_attention_heads
  88. self.intermediate_size = self.intermediate_size or int(8 * self.hidden_size / 3)
  89. self.tie_word_embeddings = False # Force-set to False for BC
  90. super().__post_init__(**kwargs)
  91. @auto_docstring(checkpoint="itazap/blt-1b-hf")
  92. @strict
  93. class BltGlobalTransformerConfig(PreTrainedConfig):
  94. model_type = "blt_global_transformer"
  95. default_theta = 500000.0
  96. hidden_size: int = 2048
  97. num_attention_heads: int = 16
  98. num_key_value_heads: int | None = None
  99. num_hidden_layers: int = 25
  100. rms_norm_eps: float = 1e-5
  101. dropout: float | int | None = 0.0
  102. max_position_embeddings: int = 4096
  103. rope_parameters: RopeParameters | dict | None = None
  104. hidden_act: str = "silu"
  105. intermediate_size: int = 5632
  106. initializer_range: float = 0.02
  107. tie_word_embeddings: bool = False
  108. def __post_init__(self, **kwargs):
  109. self.num_key_value_heads = self.num_key_value_heads or self.num_attention_heads
  110. self.head_dim = self.hidden_size // self.num_attention_heads
  111. self.intermediate_size = self.intermediate_size or int(8 * self.hidden_size / 3)
  112. self.tie_word_embeddings = False
  113. super().__post_init__(**kwargs)
  114. @auto_docstring(checkpoint="itazap/blt-1b-hf")
  115. @strict
  116. class BltPatcherConfig(PreTrainedConfig):
  117. model_type = "blt_patcher"
  118. vocab_size: int = 260
  119. hidden_size: int = 768
  120. num_hidden_layers: int = 14
  121. num_attention_heads: int = 12
  122. num_key_value_heads: int | None = None
  123. max_position_embeddings: int = 8192
  124. rms_norm_eps: float = 1e-5
  125. dropout: float | int | None = 0.0
  126. intermediate_size: int = 2048
  127. rope_parameters: RopeParameters | dict | None = None
  128. initializer_range: float = 0.02
  129. tie_word_embeddings: bool = False
  130. def __post_init__(self, **kwargs):
  131. self.num_key_value_heads = self.num_key_value_heads or self.num_attention_heads
  132. self.head_dim = self.hidden_size // self.num_attention_heads
  133. self.intermediate_size = self.intermediate_size or int(8 * self.hidden_size / 3)
  134. self.tie_word_embeddings = False
  135. self.hidden_act = "silu" # Blt uses silu activation
  136. super().__post_init__(**kwargs)
  137. @auto_docstring(checkpoint="itazap/blt-1b-hf")
  138. @strict
  139. class BltConfig(PreTrainedConfig):
  140. r"""
  141. patch_in_forward (`bool`, *optional*, defaults to `True`):
  142. Whether to perform patching during the forward pass.
  143. patch_size (`int`, *optional*, defaults to 4):
  144. Size of the patches used in the patching mechanism.
  145. patching_mode (`str`, *optional*, defaults to `"entropy"`):
  146. The mode used for patching, such as entropy-based patching.
  147. patching_threshold (`float`, *optional*, defaults to 1.34):
  148. Threshold value used for determining when to apply patches.
  149. patching_batch_size (`int`, *optional*, defaults to 1):
  150. Batch size used during the patching process.
  151. max_patch_length (`int`, *optional*):
  152. Maximum length of patches that can be generated.
  153. cross_attn_k (`int`, *optional*, defaults to 2):
  154. Number of cross-attention heads used in the model.
  155. encoder_hash_byte_group_size (`list`, *optional*):
  156. List of byte group sizes used in the encoder hash function.
  157. encoder_hash_byte_group_vocab (`int`, *optional*, defaults to 500002):
  158. Vocabulary size for the encoder hash byte groups.
  159. encoder_hash_byte_group_nb_functions (`int`, *optional*, defaults to 1):
  160. Number of hash functions used in the encoder byte grouping.
  161. patcher_config (`BltPatcherConfig`, *optional*):
  162. Configuration for the patcher component of the model.
  163. global_config (`BltGlobalTransformerConfig`, *optional*):
  164. Configuration for the global transformer component of the model.
  165. Example:
  166. ```python
  167. >>> from transformers import BltModel, BltConfig
  168. >>> # Initializing a Blt configuration
  169. >>> configuration = BltConfig()
  170. >>> # Initializing a model from the configuration
  171. >>> model = BltModel(configuration)
  172. >>> # Accessing the model configuration
  173. >>> configuration = model.config
  174. ```"""
  175. model_type = "blt"
  176. keys_to_ignore_at_inference = ["past_key_values"]
  177. default_theta = 500000.0
  178. sub_configs = {
  179. "patcher_config": BltPatcherConfig,
  180. "encoder_config": BltLocalEncoderConfig,
  181. "decoder_config": BltLocalDecoderConfig,
  182. "global_config": BltGlobalTransformerConfig,
  183. }
  184. vocab_size: int = 260
  185. max_position_embeddings: int = 4096
  186. patch_in_forward: bool | None = True
  187. patch_size: int | None = 4
  188. patching_mode: str | None = "entropy"
  189. patching_threshold: float | None = 1.335442066192627
  190. patching_batch_size: int | None = 1
  191. max_patch_length: int | None = None
  192. cross_attn_k: int | None = 2
  193. encoder_hash_byte_group_size: list[int] | None = None
  194. encoder_hash_byte_group_vocab: int | None = 500002
  195. encoder_hash_byte_group_nb_functions: int | None = 1
  196. patcher_config: dict | PreTrainedConfig | None = None
  197. encoder_config: dict | PreTrainedConfig | None = None
  198. decoder_config: dict | PreTrainedConfig | None = None
  199. global_config: dict | PreTrainedConfig | None = None
  200. tie_word_embeddings: bool = False
  201. pad_token_id: int | None = None
  202. bos_token_id: int | None = None
  203. eos_token_id: int | list[int] | None = None
  204. initializer_range: float = 0.02
  205. rope_parameters: RopeParameters | dict | None = None
  206. def __post_init__(self, **kwargs):
  207. self.encoder_hash_byte_group_size = self.encoder_hash_byte_group_size or [3, 4, 5, 6, 7, 8]
  208. # Initialize component configurations
  209. if self.patcher_config is None:
  210. self.patcher_config = BltPatcherConfig(initializer_range=self.initializer_range)
  211. logger.info("patcher_config is None, using default Blt patcher config")
  212. elif isinstance(self.patcher_config, dict):
  213. self.patcher_config.setdefault("initializer_range", self.initializer_range)
  214. self.patcher_config = BltPatcherConfig(**self.patcher_config)
  215. if self.encoder_config is None:
  216. self.encoder_config = BltLocalEncoderConfig(initializer_range=self.initializer_range)
  217. logger.info("encoder_config is None, using default Blt encoder config")
  218. elif isinstance(self.encoder_config, dict):
  219. self.encoder_config.setdefault("initializer_range", self.initializer_range)
  220. self.encoder_config = BltLocalEncoderConfig(**self.encoder_config)
  221. if self.decoder_config is None:
  222. self.decoder_config = BltLocalDecoderConfig(initializer_range=self.initializer_range)
  223. logger.info("decoder_config is None, using default Blt decoder config")
  224. elif isinstance(self.decoder_config, dict):
  225. self.decoder_config.setdefault("initializer_range", self.initializer_range)
  226. self.decoder_config = BltLocalDecoderConfig(**self.decoder_config)
  227. if self.global_config is None:
  228. self.global_config = BltGlobalTransformerConfig(initializer_range=self.initializer_range)
  229. logger.info("global_config is None, using default Blt global config")
  230. elif isinstance(self.global_config, dict):
  231. self.global_config.setdefault("initializer_range", self.initializer_range)
  232. self.global_config = BltGlobalTransformerConfig(**self.global_config)
  233. # Determine if token embedding projection is needed based on dimension mismatch (7b)
  234. encoder_cross_output_size = self.encoder_config.hidden_size * self.cross_attn_k
  235. self.global_config.encoder_cross_output_size = (
  236. encoder_cross_output_size if encoder_cross_output_size != self.global_config.hidden_size else None
  237. )
  238. super().__post_init__(**kwargs)
  239. __all__ = [
  240. "BltConfig",
  241. "BltPatcherConfig",
  242. "BltLocalEncoderConfig",
  243. "BltLocalDecoderConfig",
  244. "BltGlobalTransformerConfig",
  245. ]