1
0

bloom.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. # coding=utf-8
  2. # Adapted from
  3. # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/bloom/modeling_bloom.py
  4. # Copyright 2023 The vLLM team.
  5. # Copyright 2022 HuggingFace Inc. team and BigScience workshop.
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. """Inference-only BLOOM model compatible with HuggingFace weights."""
  19. import math
  20. from typing import Iterable, List, Optional, Tuple
  21. import torch
  22. from torch import nn
  23. from transformers import BloomConfig
  24. from aphrodite.attention import Attention, AttentionMetadata
  25. from aphrodite.common.sequence import SamplerOutput
  26. from aphrodite.distributed import (get_tensor_model_parallel_rank,
  27. get_tensor_model_parallel_world_size)
  28. from aphrodite.modeling.layers.activation import get_act_fn
  29. from aphrodite.modeling.layers.linear import (ColumnParallelLinear,
  30. QKVParallelLinear,
  31. RowParallelLinear)
  32. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  33. from aphrodite.modeling.layers.sampler import Sampler
  34. from aphrodite.modeling.layers.vocab_parallel_embedding import \
  35. VocabParallelEmbedding
  36. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  37. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  38. from aphrodite.quantization.base_config import QuantizationConfig
  39. def _get_alibi_slopes(total_num_heads: int) -> torch.Tensor:
  40. closest_power_of_2 = 2**math.floor(math.log2(total_num_heads))
  41. base = torch.tensor(
  42. 2**(-(2**-(math.log2(closest_power_of_2) - 3))),
  43. dtype=torch.float32,
  44. )
  45. powers = torch.arange(1, 1 + closest_power_of_2, dtype=torch.int32)
  46. slopes = torch.pow(base, powers)
  47. if closest_power_of_2 != total_num_heads:
  48. extra_base = torch.tensor(
  49. 2**(-(2**-(math.log2(2 * closest_power_of_2) - 3))),
  50. dtype=torch.float32,
  51. )
  52. num_remaining_heads = min(closest_power_of_2,
  53. total_num_heads - closest_power_of_2)
  54. extra_powers = torch.arange(start=1,
  55. end=1 + 2 * num_remaining_heads,
  56. step=2,
  57. dtype=torch.int32)
  58. slopes = torch.cat(
  59. [slopes, torch.pow(extra_base, extra_powers)], dim=0)
  60. return slopes
  61. class BloomAttention(nn.Module):
  62. def __init__(
  63. self,
  64. config: BloomConfig,
  65. quant_config: Optional[QuantizationConfig] = None,
  66. ):
  67. super().__init__()
  68. self.hidden_size = config.hidden_size
  69. self.total_num_heads = config.n_head
  70. self.head_dim = self.hidden_size // self.total_num_heads
  71. assert self.head_dim * self.total_num_heads == self.hidden_size
  72. tp_world_size = get_tensor_model_parallel_world_size()
  73. assert self.total_num_heads % tp_world_size == 0
  74. self.num_heads = self.total_num_heads // tp_world_size
  75. self.query_key_value = QKVParallelLinear(
  76. self.hidden_size,
  77. self.head_dim,
  78. self.total_num_heads,
  79. bias=True,
  80. quant_config=quant_config,
  81. )
  82. self.dense = RowParallelLinear(
  83. self.hidden_size,
  84. self.hidden_size,
  85. bias=True,
  86. quant_config=quant_config,
  87. )
  88. # Create the alibi slopes and slice them.
  89. tp_rank = get_tensor_model_parallel_rank()
  90. head_start = tp_rank * self.num_heads
  91. head_end = (tp_rank + 1) * self.num_heads
  92. alibi_slopes = _get_alibi_slopes(self.total_num_heads)
  93. alibi_slopes = alibi_slopes[head_start:head_end].tolist()
  94. scaling = self.head_dim**-0.5
  95. self.attn = Attention(self.num_heads,
  96. self.head_dim,
  97. scaling,
  98. alibi_slopes=alibi_slopes)
  99. def forward(
  100. self,
  101. position_ids: torch.Tensor,
  102. hidden_states: torch.Tensor,
  103. kv_cache: torch.Tensor,
  104. attn_metadata: AttentionMetadata,
  105. ) -> torch.Tensor:
  106. del position_ids # Unused.
  107. qkv, _ = self.query_key_value(hidden_states)
  108. q, k, v = qkv.chunk(chunks=3, dim=-1)
  109. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  110. output, _ = self.dense(attn_output)
  111. return output
  112. class BloomMLP(nn.Module):
  113. def __init__(
  114. self,
  115. config: BloomConfig,
  116. quant_config: Optional[QuantizationConfig] = None,
  117. ):
  118. super().__init__()
  119. hidden_size = config.hidden_size
  120. self.dense_h_to_4h = ColumnParallelLinear(
  121. hidden_size,
  122. 4 * hidden_size,
  123. quant_config=quant_config,
  124. )
  125. quant_config = getattr(quant_config, "quant_config", None)
  126. self.gelu_impl = get_act_fn("gelu", quant_config, 4 * hidden_size)
  127. self.dense_4h_to_h = RowParallelLinear(
  128. 4 * hidden_size,
  129. hidden_size,
  130. quant_config=quant_config,
  131. )
  132. def forward(self, x: torch.Tensor) -> torch.Tensor:
  133. x, _ = self.dense_h_to_4h(x)
  134. x = self.gelu_impl(x)
  135. x, _ = self.dense_4h_to_h(x)
  136. return x
  137. class BloomBlock(nn.Module):
  138. def __init__(
  139. self,
  140. config: BloomConfig,
  141. quant_config: Optional[QuantizationConfig] = None,
  142. ):
  143. super().__init__()
  144. hidden_size = config.hidden_size
  145. self.input_layernorm = nn.LayerNorm(hidden_size,
  146. eps=config.layer_norm_epsilon)
  147. self.self_attention = BloomAttention(config, quant_config)
  148. self.post_attention_layernorm = nn.LayerNorm(
  149. hidden_size, eps=config.layer_norm_epsilon)
  150. self.mlp = BloomMLP(config, quant_config)
  151. self.apply_residual_connection_post_layernorm = (
  152. config.apply_residual_connection_post_layernorm)
  153. def forward(
  154. self,
  155. position_ids: torch.Tensor,
  156. hidden_states: torch.Tensor,
  157. kv_cache: torch.Tensor,
  158. attn_metadata: AttentionMetadata,
  159. ) -> torch.Tensor:
  160. # Layer norm at the beginning of the transformer layer.
  161. layernorm_output = self.input_layernorm(hidden_states)
  162. # Layer norm post the self attention.
  163. if self.apply_residual_connection_post_layernorm:
  164. residual = layernorm_output
  165. else:
  166. residual = hidden_states
  167. # Self attention.
  168. attention_output = self.self_attention(
  169. position_ids=position_ids,
  170. hidden_states=layernorm_output,
  171. kv_cache=kv_cache,
  172. attn_metadata=attn_metadata,
  173. )
  174. attention_output = attention_output + residual
  175. layernorm_output = self.post_attention_layernorm(attention_output)
  176. # Get residual
  177. if self.apply_residual_connection_post_layernorm:
  178. residual = layernorm_output
  179. else:
  180. residual = attention_output
  181. # MLP.
  182. output = self.mlp(layernorm_output) + residual
  183. return output
  184. class BloomModel(nn.Module):
  185. def __init__(
  186. self,
  187. config: BloomConfig,
  188. quant_config: Optional[QuantizationConfig] = None,
  189. ):
  190. super().__init__()
  191. self.embed_dim = config.hidden_size
  192. # Embedding + LN Embedding
  193. self.word_embeddings = VocabParallelEmbedding(
  194. config.vocab_size,
  195. self.embed_dim,
  196. )
  197. self.word_embeddings_layernorm = nn.LayerNorm(
  198. self.embed_dim, eps=config.layer_norm_epsilon)
  199. # Transformer blocks
  200. self.h = nn.ModuleList([
  201. BloomBlock(config, quant_config)
  202. for _ in range(config.num_hidden_layers)
  203. ])
  204. # Final Layer Norm
  205. self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
  206. def forward(
  207. self,
  208. input_ids: torch.Tensor,
  209. position_ids: torch.Tensor,
  210. kv_caches: List[torch.Tensor],
  211. attn_metadata: AttentionMetadata,
  212. ) -> torch.Tensor:
  213. hidden_states = self.word_embeddings(input_ids)
  214. hidden_states = self.word_embeddings_layernorm(hidden_states)
  215. for i in range(len(self.h)):
  216. layer = self.h[i]
  217. hidden_states = layer(
  218. position_ids,
  219. hidden_states,
  220. kv_caches[i],
  221. attn_metadata,
  222. )
  223. hidden_states = self.ln_f(hidden_states)
  224. return hidden_states
  225. class BloomForCausalLM(nn.Module):
  226. def __init__(
  227. self,
  228. config: BloomConfig,
  229. quant_config: Optional[QuantizationConfig] = None,
  230. ):
  231. super().__init__()
  232. self.config = config
  233. self.quant_config = quant_config
  234. self.transformer = BloomModel(config, quant_config)
  235. self.lm_head_weight = self.transformer.word_embeddings.weight
  236. self.logits_processor = LogitsProcessor(config.vocab_size)
  237. self.sampler = Sampler()
  238. def forward(
  239. self,
  240. input_ids: torch.Tensor,
  241. positions: torch.Tensor,
  242. kv_caches: List[torch.Tensor],
  243. attn_metadata: AttentionMetadata,
  244. ) -> torch.Tensor:
  245. hidden_states = self.transformer(input_ids, positions, kv_caches,
  246. attn_metadata)
  247. return hidden_states
  248. def compute_logits(self, hidden_states: torch.Tensor,
  249. sampling_metadata: SamplingMetadata) -> torch.Tensor:
  250. logits = self.logits_processor(self.lm_head_weight, hidden_states,
  251. sampling_metadata)
  252. return logits
  253. def sample(
  254. self,
  255. logits: torch.Tensor,
  256. sampling_metadata: SamplingMetadata,
  257. ) -> Optional[SamplerOutput]:
  258. next_tokens = self.sampler(logits, sampling_metadata)
  259. return next_tokens
  260. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  261. params_dict = dict(self.named_parameters(remove_duplicate=False))
  262. for name, loaded_weight in weights:
  263. if name == "lm_head.weight":
  264. continue
  265. if not name.startswith("transformer."):
  266. name = "transformer." + name
  267. param = params_dict[name]
  268. if "query_key_value" in name:
  269. # NOTE: BLOOM's fused QKV's output_dim has the shape of
  270. # (num_heads * 3 * head_size), while the
  271. # required shape is (3 * num_heads * head_size).
  272. # Thus, we need weight conversion.
  273. output_dim = getattr(param, "output_dim", None)
  274. num_heads = self.config.num_attention_heads
  275. if output_dim is not None:
  276. loaded_weight_shape = loaded_weight.shape
  277. loaded_weight = loaded_weight.view(
  278. loaded_weight_shape[:output_dim] + (num_heads, 3, -1) +
  279. loaded_weight_shape[output_dim + 1:])
  280. loaded_weight = loaded_weight.transpose(
  281. output_dim, output_dim + 1)
  282. loaded_weight = loaded_weight.reshape(loaded_weight_shape)
  283. weight_loader = getattr(param, "weight_loader",
  284. default_weight_loader)
  285. weight_loader(param, loaded_weight)