configuration_blt.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. # coding=utf-8
  2. # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Blt model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. class BltLocalEncoderConfig(PretrainedConfig):
  20. """
  21. Configuration class for the Blt Local Encoder component.
  22. """
  23. model_type = "blt_local_encoder"
  24. def __init__(
  25. self,
  26. vocab_size=260,
  27. cross_attn_all_layers=False,
  28. cross_attn_k=2,
  29. hidden_size_global=2048,
  30. hidden_size=1024,
  31. num_attention_heads=16,
  32. num_key_value_heads=None,
  33. num_hidden_layers=1,
  34. rms_norm_eps=1e-5,
  35. dropout=0.0,
  36. max_position_embeddings=24576,
  37. rope_theta=500000.0,
  38. rope_scaling=None,
  39. hidden_act="silu",
  40. intermediate_size=2816,
  41. initializer_range=0.02,
  42. **kwargs,
  43. ):
  44. self.vocab_size = vocab_size
  45. self.cross_attn_all_layers = cross_attn_all_layers
  46. self.cross_attn_k = cross_attn_k
  47. self.hidden_size_global = hidden_size_global
  48. self.hidden_size = hidden_size
  49. self.num_attention_heads = num_attention_heads
  50. self.num_key_value_heads = num_key_value_heads or num_attention_heads
  51. self.head_dim = hidden_size // num_attention_heads
  52. self.intermediate_size = intermediate_size or int(8 * hidden_size / 3)
  53. self.num_hidden_layers = num_hidden_layers
  54. self.rms_norm_eps = rms_norm_eps
  55. self.dropout = dropout
  56. self.max_position_embeddings = max_position_embeddings
  57. self.rope_theta = rope_theta
  58. self.rope_scaling = rope_scaling
  59. self.hidden_act = hidden_act
  60. self.initializer_range = initializer_range
  61. # Remove tie_word_embeddings from kwargs to avoid duplicate parameter error
  62. kwargs.pop("tie_word_embeddings", None)
  63. super().__init__(**kwargs, tie_word_embeddings=False)
  64. class BltLocalDecoderConfig(PretrainedConfig):
  65. """
  66. Configuration class for the Blt Local Decoder component.
  67. """
  68. model_type = "blt_local_decoder"
  69. def __init__(
  70. self,
  71. vocab_size=260,
  72. cross_attn_all_layers=True,
  73. cross_attn_k=2,
  74. hidden_size_global=2048,
  75. hidden_size=1024,
  76. num_attention_heads=16,
  77. num_key_value_heads=None,
  78. num_hidden_layers=9,
  79. rms_norm_eps=1e-5,
  80. dropout=0.0,
  81. max_position_embeddings=24576,
  82. rope_theta=500000.0,
  83. rope_scaling=None,
  84. hidden_act="silu",
  85. intermediate_size=2816,
  86. initializer_range=0.02,
  87. **kwargs,
  88. ):
  89. self.vocab_size = vocab_size
  90. self.cross_attn_all_layers = cross_attn_all_layers
  91. self.cross_attn_k = cross_attn_k
  92. self.hidden_size_global = hidden_size_global
  93. self.hidden_size = hidden_size
  94. self.num_attention_heads = num_attention_heads
  95. self.num_key_value_heads = num_key_value_heads or num_attention_heads
  96. self.head_dim = hidden_size // num_attention_heads
  97. self.intermediate_size = intermediate_size or int(8 * hidden_size / 3)
  98. self.num_hidden_layers = num_hidden_layers
  99. self.rms_norm_eps = rms_norm_eps
  100. self.dropout = dropout
  101. self.max_position_embeddings = max_position_embeddings
  102. self.rope_theta = rope_theta
  103. self.rope_scaling = rope_scaling
  104. self.hidden_act = hidden_act
  105. self.initializer_range = initializer_range
  106. # Remove tie_word_embeddings from kwargs to avoid duplicate parameter error
  107. kwargs.pop("tie_word_embeddings", None)
  108. super().__init__(**kwargs, tie_word_embeddings=False)
  109. class BltGlobalTransformerConfig(PretrainedConfig):
  110. """
  111. Configuration class for the Blt Global Transformer component.
  112. """
  113. model_type = "blt_global_transformer"
  114. def __init__(
  115. self,
  116. hidden_size=2048,
  117. num_attention_heads=16,
  118. num_key_value_heads=None,
  119. num_hidden_layers=25,
  120. rms_norm_eps=1e-5,
  121. dropout=0.0,
  122. max_position_embeddings=4096,
  123. rope_theta=500000.0,
  124. rope_scaling=None,
  125. hidden_act="silu",
  126. intermediate_size=5632,
  127. initializer_range=0.02,
  128. **kwargs,
  129. ):
  130. self.hidden_size = hidden_size
  131. self.num_attention_heads = num_attention_heads
  132. self.num_key_value_heads = num_key_value_heads or num_attention_heads
  133. self.head_dim = hidden_size // num_attention_heads
  134. self.intermediate_size = intermediate_size or int(8 * hidden_size / 3)
  135. self.num_hidden_layers = num_hidden_layers
  136. self.rms_norm_eps = rms_norm_eps
  137. self.dropout = dropout
  138. self.max_position_embeddings = max_position_embeddings
  139. self.rope_theta = rope_theta
  140. self.rope_scaling = rope_scaling
  141. self.hidden_act = hidden_act
  142. self.initializer_range = initializer_range
  143. # Remove tie_word_embeddings from kwargs to avoid duplicate parameter error
  144. kwargs.pop("tie_word_embeddings", None)
  145. super().__init__(**kwargs, tie_word_embeddings=False)
  146. class BltPatcherConfig(PretrainedConfig):
  147. r"""
  148. Configuration class for the Blt Patcher/Entropy model component.
  149. Args:
  150. vocab_size (`int`, *optional*, defaults to 260):
  151. Vocabulary size of the Blt patcher model. Defines the number of different tokens that can be represented by the
  152. `inputs_ids` passed when calling the patcher model.
  153. hidden_size (`int`, *optional*, defaults to 768):
  154. Dimension of the hidden representations.
  155. num_hidden_layers (`int`, *optional*, defaults to 14):
  156. Number of hidden layers in the Transformer decoder.
  157. num_attention_heads (`int`, *optional*, defaults to 12):
  158. Number of attention heads for each attention layer in the Transformer decoder.
  159. num_key_value_heads (`int`, *optional*):
  160. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  161. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  162. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  163. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  164. by meanpooling all the original heads within that group. For more details, check out [this
  165. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
  166. `num_attention_heads`.
  167. max_position_embeddings (`int`, *optional*, defaults to 8192):
  168. The maximum sequence length that this model might ever be used with.
  169. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  170. The epsilon used by the rms normalization layers.
  171. dropout (`float`, *optional*, defaults to 0.0):
  172. The dropout ratio for the attention probabilities.
  173. rope_theta (`float`, *optional*, defaults to 10000.0):
  174. The base period of the RoPE embeddings.
  175. intermediate_size (`int`, *optional*, defaults to 2048):
  176. Dimension of the MLP representations.
  177. rope_scaling (`dict`, *optional*):
  178. Dictionary containing the RoPE scaling configuration.
  179. initializer_range (`float`, *optional*, defaults to 0.02):
  180. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  181. """
  182. model_type = "blt_patcher"
  183. def __init__(
  184. self,
  185. vocab_size=260,
  186. hidden_size=768,
  187. num_hidden_layers=14,
  188. num_attention_heads=12,
  189. num_key_value_heads=None,
  190. max_position_embeddings=8192,
  191. rms_norm_eps=1e-5,
  192. dropout=0.0,
  193. rope_theta=10000.0,
  194. intermediate_size=2048,
  195. rope_scaling=None,
  196. initializer_range=0.02,
  197. **kwargs,
  198. ):
  199. self.vocab_size = vocab_size
  200. self.hidden_size = hidden_size
  201. self.num_hidden_layers = num_hidden_layers
  202. self.num_attention_heads = num_attention_heads
  203. self.head_dim = hidden_size // num_attention_heads
  204. self.num_key_value_heads = num_key_value_heads if num_key_value_heads is not None else num_attention_heads
  205. self.max_position_embeddings = max_position_embeddings
  206. self.rms_norm_eps = rms_norm_eps
  207. self.dropout = dropout
  208. self.rope_theta = rope_theta
  209. self.hidden_act = "silu" # Blt uses silu activation
  210. self.intermediate_size = intermediate_size or int(8 * self.hidden_size / 3)
  211. self.rope_scaling = rope_scaling
  212. self.initializer_range = initializer_range
  213. # Remove tie_word_embeddings from kwargs to avoid duplicate parameter error
  214. kwargs.pop("tie_word_embeddings", None)
  215. super().__init__(**kwargs, tie_word_embeddings=False)
  216. class BltConfig(PretrainedConfig):
  217. r"""
  218. This is the configuration class to store the configuration of a [`BltModel`]. It is used to instantiate a
  219. Blt model according to the specified arguments, defining the model architecture.
  220. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  221. documentation from [`PretrainedConfig`] for more information.
  222. Args:
  223. vocab_size (`int`, *optional*, defaults to 260):
  224. Vocabulary size of the Blt model. Defines the number of different tokens that can be represented by the
  225. `inputs_ids` passed when calling [`BltModel`].
  226. max_position_embeddings (`int`, *optional*, defaults to 4096):
  227. The maximum sequence length that this model might ever be used with.
  228. patch_in_forward (`bool`, *optional*, defaults to `True`):
  229. Whether to perform patching during the forward pass.
  230. patch_size (`int`, *optional*, defaults to 4):
  231. Size of the patches used in the patching mechanism.
  232. patching_mode (`str`, *optional*, defaults to `"entropy"`):
  233. The mode used for patching, such as entropy-based patching.
  234. patching_threshold (`float`, *optional*, defaults to 1.34):
  235. Threshold value used for determining when to apply patches.
  236. patching_batch_size (`int`, *optional*, defaults to 1):
  237. Batch size used during the patching process.
  238. max_patch_length (`int`, *optional*):
  239. Maximum length of patches that can be generated.
  240. cross_attn_k (`int`, *optional*, defaults to 2):
  241. Number of cross-attention heads used in the model.
  242. encoder_hash_byte_group_size (`list`, *optional*):
  243. List of byte group sizes used in the encoder hash function.
  244. encoder_hash_byte_group_vocab (`int`, *optional*, defaults to 500002):
  245. Vocabulary size for the encoder hash byte groups.
  246. encoder_hash_byte_group_nb_functions (`int`, *optional*, defaults to 1):
  247. Number of hash functions used in the encoder byte grouping.
  248. patcher_config (`BltPatcherConfig`, *optional*):
  249. Configuration for the patcher component of the model.
  250. encoder_config (`BltLocalEncoderConfig`, *optional*):
  251. Configuration for the local encoder component of the model.
  252. decoder_config (`BltLocalDecoderConfig`, *optional*):
  253. Configuration for the local decoder component of the model.
  254. global_config (`BltGlobalTransformerConfig`, *optional*):
  255. Configuration for the global transformer component of the model.
  256. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  257. Whether to tie weight embeddings.
  258. initializer_range (`float`, *optional*, defaults to 0.02):
  259. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  260. rope_theta (`float`, *optional*, defaults to 500000.0):
  261. The base period of the RoPE embeddings.
  262. rope_scaling (`dict`, *optional*):
  263. Dictionary containing the RoPE scaling configuration.
  264. ```python
  265. >>> from transformers import BltModel, BltConfig
  266. >>> # Initializing a Blt configuration
  267. >>> configuration = BltConfig()
  268. >>> # Initializing a model from the configuration
  269. >>> model = BltModel(configuration)
  270. >>> # Accessing the model configuration
  271. >>> configuration = model.config
  272. ```
  273. Checkpoint: [facebook/blt](https://huggingface.co/facebook/blt)
  274. """
  275. model_type = "blt"
  276. keys_to_ignore_at_inference = ["past_key_values"]
  277. sub_configs = {
  278. "patcher_config": BltPatcherConfig,
  279. "encoder_config": BltLocalEncoderConfig,
  280. "decoder_config": BltLocalDecoderConfig,
  281. "global_config": BltGlobalTransformerConfig,
  282. }
  283. def __init__(
  284. self,
  285. vocab_size=260,
  286. max_position_embeddings=4096,
  287. patch_in_forward=True,
  288. patch_size=4,
  289. patching_mode="entropy",
  290. patching_threshold=1.335442066192627,
  291. patching_batch_size=1,
  292. max_patch_length=None,
  293. cross_attn_k=2,
  294. encoder_hash_byte_group_size=None,
  295. encoder_hash_byte_group_vocab=500002,
  296. encoder_hash_byte_group_nb_functions=1,
  297. patcher_config=None,
  298. encoder_config=None,
  299. decoder_config=None,
  300. global_config=None,
  301. tie_word_embeddings=False,
  302. initializer_range=0.02,
  303. rope_theta=500000.0,
  304. rope_scaling=None,
  305. **kwargs,
  306. ):
  307. # Basic model configuration
  308. self.vocab_size = vocab_size
  309. self.max_position_embeddings = max_position_embeddings
  310. self.initializer_range = initializer_range
  311. self.rope_theta = rope_theta
  312. self.rope_scaling = rope_scaling
  313. # Patching configuration
  314. self.patch_in_forward = patch_in_forward
  315. self.patch_size = patch_size
  316. self.patching_mode = patching_mode
  317. self.patching_threshold = patching_threshold
  318. self.patching_batch_size = patching_batch_size
  319. self.max_patch_length = max_patch_length
  320. self.patching_device = kwargs.get("patching_device", "cuda")
  321. self.realtime_patching = kwargs.get("realtime_patching", True)
  322. self.patching_threshold_add = kwargs.get("patching_threshold_add")
  323. self.monotonicity = kwargs.get("monotonicity", False)
  324. # Cross attention configurations
  325. self.cross_attn_k = cross_attn_k
  326. # Encoder configurations
  327. self.encoder_hash_byte_group_size = encoder_hash_byte_group_size or [3, 4, 5, 6, 7, 8]
  328. self.encoder_hash_byte_group_vocab = encoder_hash_byte_group_vocab
  329. self.encoder_hash_byte_group_nb_functions = encoder_hash_byte_group_nb_functions
  330. # Initialize component configurations
  331. if patcher_config is None:
  332. self.patcher_config = BltPatcherConfig(initializer_range=initializer_range)
  333. logger.info("patcher_config is None, using default Blt patcher config")
  334. elif isinstance(patcher_config, dict):
  335. patcher_config.setdefault("initializer_range", initializer_range)
  336. self.patcher_config = BltPatcherConfig(**patcher_config)
  337. elif isinstance(patcher_config, BltPatcherConfig):
  338. self.patcher_config = patcher_config
  339. if encoder_config is None:
  340. self.encoder_config = BltLocalEncoderConfig(initializer_range=initializer_range)
  341. logger.info("encoder_config is None, using default Blt encoder config")
  342. elif isinstance(encoder_config, dict):
  343. encoder_config.setdefault("initializer_range", initializer_range)
  344. self.encoder_config = BltLocalEncoderConfig(**encoder_config)
  345. elif isinstance(encoder_config, BltLocalEncoderConfig):
  346. self.encoder_config = encoder_config
  347. if decoder_config is None:
  348. self.decoder_config = BltLocalDecoderConfig(initializer_range=initializer_range)
  349. logger.info("decoder_config is None, using default Blt decoder config")
  350. elif isinstance(decoder_config, dict):
  351. decoder_config.setdefault("initializer_range", initializer_range)
  352. self.decoder_config = BltLocalDecoderConfig(**decoder_config)
  353. elif isinstance(decoder_config, BltLocalDecoderConfig):
  354. self.decoder_config = decoder_config
  355. if global_config is None:
  356. self.global_config = BltGlobalTransformerConfig(initializer_range=initializer_range)
  357. logger.info("global_config is None, using default Blt global config")
  358. elif isinstance(global_config, dict):
  359. global_config.setdefault("initializer_range", initializer_range)
  360. self.global_config = BltGlobalTransformerConfig(**global_config)
  361. elif isinstance(global_config, BltGlobalTransformerConfig):
  362. self.global_config = global_config
  363. # Determine if token embedding projection is needed based on dimension mismatch (7b)
  364. encoder_cross_output_size = self.encoder_config.hidden_size * self.cross_attn_k
  365. self.global_config.encoder_cross_output_size = (
  366. encoder_cross_output_size if encoder_cross_output_size != self.global_config.hidden_size else None
  367. )
  368. # Remove tie_word_embeddings from kwargs to avoid duplicate parameter error
  369. kwargs.pop("tie_word_embeddings", None)
  370. super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
  371. __all__ = [
  372. "BltConfig",
  373. "BltPatcherConfig",
  374. "BltLocalEncoderConfig",
  375. "BltLocalDecoderConfig",
  376. "BltGlobalTransformerConfig",
  377. ]