1
0

gemma.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. # coding=utf-8
  2. # Copyright 2023 The vLLM team.
  3. # Copyright (c) Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Inference-only Gemma model compatible with HuggingFace weights."""
  17. from functools import lru_cache
  18. from typing import Iterable, List, Optional, Tuple
  19. import torch
  20. from loguru import logger
  21. from torch import nn
  22. from transformers import GemmaConfig
  23. from aphrodite.attention import Attention, AttentionMetadata
  24. from aphrodite.common.config import CacheConfig, LoRAConfig
  25. from aphrodite.common.sequence import SamplerOutput
  26. from aphrodite.distributed import get_tensor_model_parallel_world_size
  27. from aphrodite.modeling.layers.activation import GeluAndMul
  28. from aphrodite.modeling.layers.layernorm import RMSNorm
  29. from aphrodite.modeling.layers.linear import (MergedColumnParallelLinear,
  30. QKVParallelLinear,
  31. RowParallelLinear)
  32. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  33. from aphrodite.modeling.layers.rotary_embedding import get_rope
  34. from aphrodite.modeling.layers.sampler import Sampler
  35. from aphrodite.modeling.layers.vocab_parallel_embedding import \
  36. VocabParallelEmbedding
  37. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  38. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  39. from aphrodite.quantization.base_config import QuantizationConfig
  40. @lru_cache(maxsize=None)
  41. def _get_gemma_act_fn(
  42. hidden_act: Optional[str],
  43. hidden_activation: Optional[str],
  44. ) -> nn.Module:
  45. if hidden_activation is None:
  46. if hidden_act is not None:
  47. logger.warning(
  48. "Gemma's activation function was incorrectly set to exact GeLU "
  49. "in the config JSON file when it was initially released. "
  50. "Changing the activation function to approximate GeLU "
  51. "(`gelu_pytorch_tanh`). If you want to use the legacy "
  52. f"`{hidden_act}`, edit the config JSON to set "
  53. f"`hidden_activation={hidden_act}` instead of `hidden_act`. "
  54. "See https://github.com/huggingface/transformers/pull/29402 "
  55. "for more details.")
  56. return GeluAndMul(approximate="tanh")
  57. elif hidden_activation == "gelu_pytorch_tanh":
  58. return GeluAndMul(approximate="tanh")
  59. elif hidden_activation == "gelu":
  60. return GeluAndMul(approximate="none")
  61. else:
  62. raise ValueError(f"Activation function {hidden_act} is not "
  63. "supported for Gemma models.")
  64. class GemmaMLP(nn.Module):
  65. def __init__(
  66. self,
  67. hidden_size: int,
  68. intermediate_size: int,
  69. hidden_act: Optional[str] = None,
  70. hidden_activation: Optional[str] = None,
  71. quant_config: Optional[QuantizationConfig] = None,
  72. ) -> None:
  73. super().__init__()
  74. self.gate_up_proj = MergedColumnParallelLinear(
  75. hidden_size, [intermediate_size] * 2,
  76. bias=False,
  77. quant_config=quant_config)
  78. self.down_proj = RowParallelLinear(intermediate_size,
  79. hidden_size,
  80. bias=False,
  81. quant_config=quant_config)
  82. self.act_fn = _get_gemma_act_fn(hidden_act, hidden_activation)
  83. def forward(self, x):
  84. gate_up, _ = self.gate_up_proj(x)
  85. x = self.act_fn(gate_up)
  86. x, _ = self.down_proj(x)
  87. return x
  88. class GemmaAttention(nn.Module):
  89. def __init__(self,
  90. hidden_size: int,
  91. num_heads: int,
  92. num_kv_heads: int,
  93. head_dim: int,
  94. max_position_embeddings: int = 8192,
  95. rope_theta: float = 10000,
  96. cache_config: Optional[CacheConfig] = None,
  97. quant_config: Optional[QuantizationConfig] = None) -> None:
  98. super().__init__()
  99. self.hidden_size = hidden_size
  100. tp_size = get_tensor_model_parallel_world_size()
  101. self.total_num_heads = num_heads
  102. assert self.total_num_heads % tp_size == 0
  103. self.num_heads = self.total_num_heads // tp_size
  104. self.total_num_kv_heads = num_kv_heads
  105. if self.total_num_kv_heads >= tp_size:
  106. # Number of KV heads is greater than TP size, so we partition
  107. # the KV heads across multiple tensor parallel GPUs.
  108. assert self.total_num_kv_heads % tp_size == 0
  109. else:
  110. # Number of KV heads is less than TP size, so we replicate
  111. # the KV heads across multiple tensor parallel GPUs.
  112. assert tp_size % self.total_num_kv_heads == 0
  113. self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
  114. self.head_dim = head_dim
  115. self.q_size = self.num_heads * self.head_dim
  116. self.kv_size = self.num_kv_heads * self.head_dim
  117. self.scaling = self.head_dim**-0.5
  118. self.rope_theta = rope_theta
  119. self.qkv_proj = QKVParallelLinear(
  120. hidden_size,
  121. self.head_dim,
  122. self.total_num_heads,
  123. self.total_num_kv_heads,
  124. bias=False,
  125. quant_config=quant_config,
  126. )
  127. self.o_proj = RowParallelLinear(
  128. self.total_num_heads * self.head_dim,
  129. hidden_size,
  130. bias=False,
  131. quant_config=quant_config,
  132. )
  133. self.rotary_emb = get_rope(
  134. self.head_dim,
  135. rotary_dim=self.head_dim,
  136. max_position=max_position_embeddings,
  137. base=self.rope_theta,
  138. is_neox_style=True,
  139. )
  140. self.attn = Attention(self.num_heads,
  141. self.head_dim,
  142. self.scaling,
  143. num_kv_heads=self.num_kv_heads,
  144. cache_config=cache_config,
  145. quant_config=quant_config)
  146. def forward(
  147. self,
  148. positions: torch.Tensor,
  149. hidden_states: torch.Tensor,
  150. kv_cache: torch.Tensor,
  151. attn_metadata: AttentionMetadata,
  152. ) -> torch.Tensor:
  153. qkv, _ = self.qkv_proj(hidden_states)
  154. q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
  155. q, k = self.rotary_emb(positions, q, k)
  156. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  157. output, _ = self.o_proj(attn_output)
  158. return output
  159. class GemmaDecoderLayer(nn.Module):
  160. def __init__(
  161. self,
  162. config: GemmaConfig,
  163. cache_config: Optional[CacheConfig] = None,
  164. quant_config: Optional[QuantizationConfig] = None,
  165. ) -> None:
  166. super().__init__()
  167. self.hidden_size = config.hidden_size
  168. self.self_attn = GemmaAttention(
  169. hidden_size=self.hidden_size,
  170. num_heads=config.num_attention_heads,
  171. num_kv_heads=config.num_key_value_heads,
  172. head_dim=config.head_dim,
  173. max_position_embeddings=config.max_position_embeddings,
  174. rope_theta=config.rope_theta,
  175. cache_config=cache_config,
  176. quant_config=quant_config,
  177. )
  178. self.mlp = GemmaMLP(
  179. hidden_size=self.hidden_size,
  180. intermediate_size=config.intermediate_size,
  181. hidden_act=config.hidden_act,
  182. hidden_activation=getattr(config, "hidden_activation", None),
  183. quant_config=quant_config,
  184. )
  185. self.input_layernorm = RMSNorm(config.hidden_size,
  186. eps=config.rms_norm_eps)
  187. self.post_attention_layernorm = RMSNorm(config.hidden_size,
  188. eps=config.rms_norm_eps)
  189. def forward(
  190. self,
  191. positions: torch.Tensor,
  192. hidden_states: torch.Tensor,
  193. kv_cache: torch.Tensor,
  194. attn_metadata: AttentionMetadata,
  195. residual: Optional[torch.Tensor],
  196. ) -> Tuple[torch.Tensor, torch.Tensor]:
  197. # Self Attention
  198. if residual is None:
  199. residual = hidden_states
  200. hidden_states = self.input_layernorm(hidden_states)
  201. else:
  202. hidden_states, residual = self.input_layernorm(
  203. hidden_states, residual)
  204. hidden_states = self.self_attn(
  205. positions=positions,
  206. hidden_states=hidden_states,
  207. kv_cache=kv_cache,
  208. attn_metadata=attn_metadata,
  209. )
  210. # Fully Connected
  211. hidden_states, residual = self.post_attention_layernorm(
  212. hidden_states, residual)
  213. hidden_states = self.mlp(hidden_states)
  214. return hidden_states, residual
  215. class GemmaModel(nn.Module):
  216. def __init__(
  217. self,
  218. config: GemmaConfig,
  219. cache_config: Optional[CacheConfig] = None,
  220. quant_config: Optional[QuantizationConfig] = None,
  221. ) -> None:
  222. super().__init__()
  223. self.config = config
  224. self.embed_tokens = VocabParallelEmbedding(
  225. config.vocab_size,
  226. config.hidden_size,
  227. )
  228. self.layers = nn.ModuleList([
  229. GemmaDecoderLayer(config, cache_config, quant_config)
  230. for _ in range(config.num_hidden_layers)
  231. ])
  232. self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  233. # Normalize the embedding by sqrt(hidden_size)
  234. # The normalizer's data type should be downcasted to the model's
  235. # data type such as bfloat16, not float32.
  236. # See https://github.com/huggingface/transformers/pull/29402
  237. normalizer = self.config.hidden_size**0.5
  238. self.register_buffer("normalizer", torch.tensor(normalizer))
  239. def forward(
  240. self,
  241. input_ids: torch.Tensor,
  242. positions: torch.Tensor,
  243. kv_caches: List[torch.Tensor],
  244. attn_metadata: AttentionMetadata,
  245. ) -> torch.Tensor:
  246. hidden_states = self.embed_tokens(input_ids)
  247. hidden_states *= self.normalizer
  248. residual = None
  249. for i in range(len(self.layers)):
  250. layer = self.layers[i]
  251. hidden_states, residual = layer(
  252. positions,
  253. hidden_states,
  254. kv_caches[i],
  255. attn_metadata,
  256. residual,
  257. )
  258. hidden_states, _ = self.norm(hidden_states, residual)
  259. return hidden_states
  260. class GemmaForCausalLM(nn.Module):
  261. packed_modules_mapping = {
  262. "qkv_proj": [
  263. "q_proj",
  264. "k_proj",
  265. "v_proj",
  266. ],
  267. "gate_up_proj": [
  268. "gate_proj",
  269. "up_proj",
  270. ],
  271. }
  272. # LoRA specific attributes
  273. supported_lora_modules = [
  274. "qkv_proj",
  275. "o_proj",
  276. "gate_up_proj",
  277. "down_proj",
  278. ]
  279. # Gemma does not apply LoRA to the embedding layer.
  280. embedding_modules = {}
  281. embedding_padding_modules = []
  282. def __init__(
  283. self,
  284. config: GemmaConfig,
  285. cache_config: Optional[CacheConfig] = None,
  286. quant_config: Optional[QuantizationConfig] = None,
  287. lora_config: Optional[LoRAConfig] = None,
  288. ) -> None:
  289. del lora_config # Unused.
  290. super().__init__()
  291. self.config = config
  292. self.quant_config = quant_config
  293. self.model = GemmaModel(config, cache_config, quant_config)
  294. self.logits_processor = LogitsProcessor(config.vocab_size)
  295. self.sampler = Sampler()
  296. @torch.no_grad()
  297. def forward(
  298. self,
  299. input_ids: torch.Tensor,
  300. positions: torch.Tensor,
  301. kv_caches: List[torch.Tensor],
  302. attn_metadata: AttentionMetadata,
  303. ) -> torch.Tensor:
  304. hidden_states = self.model(input_ids, positions, kv_caches,
  305. attn_metadata)
  306. return hidden_states
  307. def compute_logits(self, hidden_states: torch.Tensor,
  308. sampling_metadata: SamplingMetadata) -> torch.Tensor:
  309. logits = self.logits_processor(self.model.embed_tokens.weight,
  310. hidden_states, sampling_metadata)
  311. return logits
  312. def sample(
  313. self,
  314. logits: torch.Tensor,
  315. sampling_metadata: SamplingMetadata,
  316. ) -> Optional[SamplerOutput]:
  317. next_tokens = self.sampler(logits, sampling_metadata)
  318. return next_tokens
  319. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  320. stacked_params_mapping = [
  321. # (param_name, shard_name, shard_id)
  322. ("qkv_proj", "q_proj", "q"),
  323. ("qkv_proj", "k_proj", "k"),
  324. ("qkv_proj", "v_proj", "v"),
  325. ("gate_up_proj", "gate_proj", 0),
  326. ("gate_up_proj", "up_proj", 1),
  327. ]
  328. params_dict = dict(self.named_parameters())
  329. loaded_params = set()
  330. for name, loaded_weight in weights:
  331. for (param_name, shard_name, shard_id) in stacked_params_mapping:
  332. if shard_name not in name:
  333. continue
  334. name = name.replace(shard_name, param_name)
  335. # Skip loading extra bias for GPTQ models.
  336. if name.endswith(".bias") and name not in params_dict:
  337. continue
  338. param = params_dict[name]
  339. weight_loader = param.weight_loader
  340. weight_loader(param, loaded_weight, shard_id)
  341. break
  342. else:
  343. # lm_head is not used in vllm as it is tied with embed_token.
  344. # To prevent errors, skip loading lm_head.weight.
  345. if "lm_head.weight" in name:
  346. continue
  347. # Skip loading extra bias for GPTQ models.
  348. if name.endswith(".bias") and name not in params_dict:
  349. continue
  350. # GemmaRMSNorm is different from Llama's in that it multiplies
  351. # (1 + weight) to the output, instead of just weight.
  352. if "norm.weight" in name:
  353. loaded_weight += 1.0
  354. param = params_dict[name]
  355. weight_loader = getattr(param, "weight_loader",
  356. default_weight_loader)
  357. weight_loader(param, loaded_weight)
  358. loaded_params.add(name)
  359. unloaded_params = params_dict.keys() - loaded_params
  360. if unloaded_params:
  361. raise RuntimeError(
  362. "Some weights are not initialized from checkpoints: "
  363. f"{unloaded_params}")