llama.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. # coding=utf-8
  2. # Adapted from
  3. # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/llama/modeling_llama.py
  4. # Copyright 2023 The vLLM team.
  5. # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
  6. #
  7. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  8. # and OPT implementations in this library. It has been modified from its
  9. # original forms to accommodate minor architectural differences compared
  10. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  11. #
  12. # Licensed under the Apache License, Version 2.0 (the "License");
  13. # you may not use this file except in compliance with the License.
  14. # You may obtain a copy of the License at
  15. #
  16. # http://www.apache.org/licenses/LICENSE-2.0
  17. #
  18. # Unless required by applicable law or agreed to in writing, software
  19. # distributed under the License is distributed on an "AS IS" BASIS,
  20. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. # See the License for the specific language governing permissions and
  22. # limitations under the License.
  23. """Inference-only LLaMA model compatible with HuggingFace weights."""
  24. from typing import Any, Dict, Iterable, List, Optional, Tuple
  25. import torch
  26. from torch import nn
  27. from transformers import LlamaConfig
  28. from aphrodite.attention import Attention, AttentionMetadata
  29. from aphrodite.common.config import CacheConfig, LoRAConfig
  30. from aphrodite.common.sequence import SamplerOutput
  31. from aphrodite.distributed import (get_tensor_model_parallel_rank,
  32. get_tensor_model_parallel_world_size)
  33. from aphrodite.modeling.layers.activation import SiluAndMul
  34. from aphrodite.modeling.layers.layernorm import RMSNorm
  35. from aphrodite.modeling.layers.linear import (MergedColumnParallelLinear,
  36. QKVParallelLinear,
  37. RowParallelLinear)
  38. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  39. from aphrodite.modeling.layers.rotary_embedding import get_rope
  40. from aphrodite.modeling.layers.sampler import Sampler
  41. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  42. DEFAULT_VOCAB_PADDING_SIZE, ParallelLMHead, VocabParallelEmbedding)
  43. from aphrodite.modeling.model_loader.weight_utils import (
  44. default_weight_loader, kv_cache_scales_loader)
  45. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  46. from aphrodite.quantization.base_config import QuantizationConfig
  47. from aphrodite.common.utils import is_hip, print_warning_once
  48. class LlamaMLP(nn.Module):
  49. def __init__(
  50. self,
  51. hidden_size: int,
  52. intermediate_size: int,
  53. hidden_act: str,
  54. quant_config: Optional[QuantizationConfig] = None,
  55. bias: bool = False,
  56. ) -> None:
  57. super().__init__()
  58. self.gate_up_proj = MergedColumnParallelLinear(
  59. input_size=hidden_size,
  60. output_sizes=[intermediate_size] * 2,
  61. bias=bias,
  62. quant_config=quant_config)
  63. self.down_proj = RowParallelLinear(input_size=intermediate_size,
  64. output_size=hidden_size,
  65. bias=bias,
  66. quant_config=quant_config)
  67. if hidden_act != "silu":
  68. raise ValueError(f"Unsupported activation: {hidden_act}. "
  69. "Only silu is supported for now.")
  70. self.act_fn = SiluAndMul()
  71. def forward(self, x):
  72. gate_up, _ = self.gate_up_proj(x)
  73. x = self.act_fn(gate_up)
  74. x, _ = self.down_proj(x)
  75. return x
  76. class LlamaAttention(nn.Module):
  77. def __init__(
  78. self,
  79. config: LlamaConfig,
  80. hidden_size: int,
  81. num_heads: int,
  82. num_kv_heads: int,
  83. rope_theta: float = 10000,
  84. rope_scaling: Optional[Dict[str, Any]] = None,
  85. max_position_embeddings: int = 8192,
  86. quant_config: Optional[QuantizationConfig] = None,
  87. bias: bool = False,
  88. sliding_window: Optional[int] = None,
  89. cache_config: Optional[CacheConfig] = None,
  90. ) -> None:
  91. super().__init__()
  92. self.hidden_size = hidden_size
  93. tp_size = get_tensor_model_parallel_world_size()
  94. self.total_num_heads = num_heads
  95. assert self.total_num_heads % tp_size == 0
  96. self.num_heads = self.total_num_heads // tp_size
  97. self.total_num_kv_heads = num_kv_heads
  98. if self.total_num_kv_heads >= tp_size:
  99. # Number of KV heads is greater than TP size, so we partition
  100. # the KV heads across multiple tensor parallel GPUs.
  101. assert self.total_num_kv_heads % tp_size == 0
  102. else:
  103. # Number of KV heads is less than TP size, so we replicate
  104. # the KV heads across multiple tensor parallel GPUs.
  105. assert tp_size % self.total_num_kv_heads == 0
  106. self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
  107. # MistralConfig has an optional head_dim introduced by Mistral-Nemo
  108. self.head_dim = getattr(config, "head_dim",
  109. self.hidden_size // self.total_num_heads)
  110. self.q_size = self.num_heads * self.head_dim
  111. self.kv_size = self.num_kv_heads * self.head_dim
  112. self.scaling = self.head_dim**-0.5
  113. self.rope_theta = rope_theta
  114. self.max_position_embeddings = max_position_embeddings
  115. self.qkv_proj = QKVParallelLinear(
  116. hidden_size=hidden_size,
  117. head_size=self.head_dim,
  118. total_num_heads=self.total_num_heads,
  119. total_num_kv_heads=self.total_num_kv_heads,
  120. bias=bias,
  121. quant_config=quant_config,
  122. )
  123. self.o_proj = RowParallelLinear(
  124. input_size=self.total_num_heads * self.head_dim,
  125. output_size=hidden_size,
  126. bias=bias,
  127. quant_config=quant_config,
  128. )
  129. self.rotary_emb = get_rope(
  130. self.head_dim,
  131. rotary_dim=self.head_dim,
  132. max_position=max_position_embeddings,
  133. base=rope_theta,
  134. rope_scaling=rope_scaling,
  135. )
  136. self.attn = Attention(self.num_heads,
  137. self.head_dim,
  138. self.scaling,
  139. num_kv_heads=self.num_kv_heads,
  140. sliding_window=sliding_window,
  141. cache_config=cache_config,
  142. quant_config=quant_config)
  143. def forward(
  144. self,
  145. positions: torch.Tensor,
  146. hidden_states: torch.Tensor,
  147. kv_cache: torch.Tensor,
  148. attn_metadata: AttentionMetadata,
  149. ) -> torch.Tensor:
  150. qkv, _ = self.qkv_proj(hidden_states)
  151. q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
  152. q, k = self.rotary_emb(positions, q, k)
  153. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  154. output, _ = self.o_proj(attn_output)
  155. return output
  156. class LlamaDecoderLayer(nn.Module):
  157. def __init__(
  158. self,
  159. config: LlamaConfig,
  160. cache_config: Optional[CacheConfig] = None,
  161. quant_config: Optional[QuantizationConfig] = None,
  162. ) -> None:
  163. super().__init__()
  164. self.hidden_size = config.hidden_size
  165. rope_theta = getattr(config, "rope_theta", 10000)
  166. rope_scaling = getattr(config, "rope_scaling", None)
  167. if rope_scaling is not None and getattr(
  168. config, "original_max_position_embeddings", None):
  169. rope_scaling["original_max_position_embeddings"] = (
  170. config.original_max_position_embeddings)
  171. max_position_embeddings = getattr(config, "max_position_embeddings",
  172. 8192)
  173. sliding_window = getattr(config, "sliding_window", None)
  174. # Support abacusai/Smaug-72B-v0.1 with attention_bias
  175. # Support internlm/internlm-7b with bias
  176. attention_bias = getattr(config, "attention_bias", False) or getattr(
  177. config, "bias", False)
  178. self.self_attn = LlamaAttention(
  179. config=config,
  180. hidden_size=self.hidden_size,
  181. num_heads=config.num_attention_heads,
  182. num_kv_heads=getattr(config, "num_key_value_heads",
  183. config.num_attention_heads),
  184. rope_theta=rope_theta,
  185. rope_scaling=rope_scaling,
  186. max_position_embeddings=max_position_embeddings,
  187. quant_config=quant_config,
  188. bias=attention_bias,
  189. sliding_window=sliding_window,
  190. cache_config=cache_config,
  191. )
  192. self.mlp = LlamaMLP(
  193. hidden_size=self.hidden_size,
  194. intermediate_size=config.intermediate_size,
  195. hidden_act=config.hidden_act,
  196. quant_config=quant_config,
  197. bias=getattr(config, "mlp_bias", False),
  198. )
  199. self.input_layernorm = RMSNorm(config.hidden_size,
  200. eps=config.rms_norm_eps)
  201. self.post_attention_layernorm = RMSNorm(config.hidden_size,
  202. eps=config.rms_norm_eps)
  203. def forward(
  204. self,
  205. positions: torch.Tensor,
  206. hidden_states: torch.Tensor,
  207. kv_cache: torch.Tensor,
  208. attn_metadata: AttentionMetadata,
  209. residual: Optional[torch.Tensor],
  210. ) -> Tuple[torch.Tensor, torch.Tensor]:
  211. # Self Attention
  212. if residual is None:
  213. residual = hidden_states
  214. hidden_states = self.input_layernorm(hidden_states)
  215. else:
  216. hidden_states, residual = self.input_layernorm(
  217. hidden_states, residual)
  218. hidden_states = self.self_attn(
  219. positions=positions,
  220. hidden_states=hidden_states,
  221. kv_cache=kv_cache,
  222. attn_metadata=attn_metadata,
  223. )
  224. # Fully Connected
  225. hidden_states, residual = self.post_attention_layernorm(
  226. hidden_states, residual)
  227. hidden_states = self.mlp(hidden_states)
  228. return hidden_states, residual
  229. class LlamaModel(nn.Module):
  230. def __init__(
  231. self,
  232. config: LlamaConfig,
  233. cache_config: Optional[CacheConfig] = None,
  234. quant_config: Optional[QuantizationConfig] = None,
  235. lora_config: Optional[LoRAConfig] = None,
  236. ) -> None:
  237. super().__init__()
  238. self.config = config
  239. self.padding_idx = config.pad_token_id
  240. lora_vocab = (lora_config.lora_extra_vocab_size *
  241. (lora_config.max_loras or 1)) if lora_config else 0
  242. self.vocab_size = config.vocab_size + lora_vocab
  243. self.org_vocab_size = config.vocab_size
  244. self.embed_tokens = VocabParallelEmbedding(
  245. self.vocab_size,
  246. config.hidden_size,
  247. org_num_embeddings=config.vocab_size,
  248. )
  249. self.layers = nn.ModuleList([
  250. LlamaDecoderLayer(config=config,
  251. cache_config=cache_config,
  252. quant_config=quant_config)
  253. for idx in range(config.num_hidden_layers)
  254. ])
  255. self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  256. def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
  257. return self.embed_tokens(input_ids)
  258. def forward(
  259. self,
  260. input_ids: Optional[torch.Tensor],
  261. positions: torch.Tensor,
  262. kv_caches: List[torch.Tensor],
  263. attn_metadata: AttentionMetadata,
  264. inputs_embeds: Optional[torch.Tensor] = None,
  265. ) -> torch.Tensor:
  266. if inputs_embeds is not None:
  267. hidden_states = inputs_embeds
  268. else:
  269. hidden_states = self.get_input_embeddings(input_ids)
  270. residual = None
  271. for i in range(len(self.layers)):
  272. layer = self.layers[i]
  273. hidden_states, residual = layer(
  274. positions,
  275. hidden_states,
  276. kv_caches[i],
  277. attn_metadata,
  278. residual,
  279. )
  280. hidden_states, _ = self.norm(hidden_states, residual)
  281. return hidden_states
  282. class LlamaForCausalLM(nn.Module):
  283. packed_modules_mapping = {
  284. "qkv_proj": [
  285. "q_proj",
  286. "k_proj",
  287. "v_proj",
  288. ],
  289. "gate_up_proj": [
  290. "gate_proj",
  291. "up_proj",
  292. ],
  293. }
  294. # LoRA specific attributes
  295. supported_lora_modules = [
  296. "qkv_proj", "o_proj", "gate_up_proj", "down_proj", "embed_tokens",
  297. "lm_head"
  298. ]
  299. embedding_modules = {
  300. "embed_tokens": "input_embeddings",
  301. "lm_head": "output_embeddings",
  302. }
  303. embedding_padding_modules = ["lm_head"]
  304. def __init__(
  305. self,
  306. config: LlamaConfig,
  307. cache_config: Optional[CacheConfig] = None,
  308. quant_config: Optional[QuantizationConfig] = None,
  309. lora_config: Optional[LoRAConfig] = None,
  310. ) -> None:
  311. super().__init__()
  312. self.config = config
  313. self.model = LlamaModel(config,
  314. cache_config,
  315. quant_config,
  316. lora_config=lora_config)
  317. self.unpadded_vocab_size = config.vocab_size
  318. if lora_config:
  319. self.unpadded_vocab_size += lora_config.lora_extra_vocab_size
  320. self.lm_head = ParallelLMHead(
  321. self.unpadded_vocab_size,
  322. config.hidden_size,
  323. org_num_embeddings=config.vocab_size,
  324. padding_size=DEFAULT_VOCAB_PADDING_SIZE
  325. # We need bigger padding if using lora for kernel
  326. # compatibility
  327. if not lora_config else lora_config.lora_vocab_padding_size,
  328. )
  329. if config.tie_word_embeddings:
  330. self.lm_head.weight = self.model.embed_tokens.weight
  331. logit_scale = getattr(config, "logit_scale", 1.0)
  332. self.logits_processor = LogitsProcessor(self.unpadded_vocab_size,
  333. config.vocab_size, logit_scale)
  334. self.sampler = Sampler()
  335. def forward(
  336. self,
  337. input_ids: torch.Tensor,
  338. positions: torch.Tensor,
  339. kv_caches: List[torch.Tensor],
  340. attn_metadata: AttentionMetadata,
  341. ) -> torch.Tensor:
  342. hidden_states = self.model(input_ids, positions, kv_caches,
  343. attn_metadata)
  344. return hidden_states
  345. def compute_logits(self, hidden_states: torch.Tensor,
  346. sampling_metadata: SamplingMetadata) -> torch.Tensor:
  347. logits = self.logits_processor(self.lm_head.weight, hidden_states,
  348. sampling_metadata)
  349. return logits
  350. def sample(
  351. self,
  352. logits: torch.Tensor,
  353. sampling_metadata: SamplingMetadata,
  354. ) -> Optional[SamplerOutput]:
  355. next_tokens = self.sampler(logits, sampling_metadata)
  356. return next_tokens
  357. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  358. stacked_params_mapping = [
  359. # (param_name, shard_name, shard_id)
  360. (".qkv_proj", ".q_proj", "q"),
  361. (".qkv_proj", ".k_proj", "k"),
  362. (".qkv_proj", ".v_proj", "v"),
  363. (".gate_up_proj", ".gate_proj", 0),
  364. (".gate_up_proj", ".up_proj", 1),
  365. ]
  366. params_dict = dict(self.named_parameters())
  367. for name, loaded_weight in weights:
  368. if "rotary_emb.inv_freq" in name:
  369. continue
  370. if ("rotary_emb.cos_cached" in name
  371. or "rotary_emb.sin_cached" in name):
  372. # Models trained using ColossalAI may include these tensors in
  373. # the checkpoint. Skip them.
  374. continue
  375. for (param_name, weight_name, shard_id) in stacked_params_mapping:
  376. if weight_name not in name:
  377. continue
  378. name = name.replace(weight_name, param_name)
  379. # Skip loading extra bias for GPTQ models.
  380. if name.endswith(".bias") and name not in params_dict:
  381. continue
  382. param = params_dict[name]
  383. weight_loader = param.weight_loader
  384. weight_loader(param, loaded_weight, shard_id)
  385. break
  386. else:
  387. # Skip loading extra bias for GPTQ models.
  388. if name.endswith(".bias") and name not in params_dict:
  389. continue
  390. # Remapping the name of FP8 kv-scale.
  391. if name.endswith("kv_scale"):
  392. remapped_kv_scale_name = name.replace(
  393. ".kv_scale", ".attn.kv_scale")
  394. if remapped_kv_scale_name not in params_dict:
  395. print_warning_once(
  396. f"Found kv scale in the checkpoint (e.g. {name}), "
  397. "but not found the expected name in the model "
  398. f"(e.g. {remapped_kv_scale_name}). kv-scale is "
  399. "not loaded.")
  400. continue
  401. else:
  402. name = remapped_kv_scale_name
  403. param = params_dict[name]
  404. weight_loader = getattr(param, "weight_loader",
  405. default_weight_loader)
  406. weight_loader(param, loaded_weight)
  407. # If this function is called, it should always initialize KV cache scale
  408. # factors (or else raise an exception). Thus, handled exceptions should
  409. # make sure to leave KV cache scale factors in a known good (dummy) state
  410. def load_kv_cache_scales(self, quantization_param_path: str) -> None:
  411. tp_size = get_tensor_model_parallel_world_size()
  412. tp_rank = get_tensor_model_parallel_rank()
  413. for layer_idx, scaling_factor in kv_cache_scales_loader(
  414. quantization_param_path, tp_rank, tp_size,
  415. self.config.num_hidden_layers,
  416. self.config.__class__.model_type):
  417. layer_self_attn = self.model.layers[layer_idx].self_attn
  418. if is_hip():
  419. # The scaling factor convention we are assuming is
  420. # quantized_value * scaling_factor ~= true_value
  421. # which is consistent with the practice of setting
  422. # scaling_factor = tensor_amax / FPtype_max
  423. scaling_factor *= 2
  424. if hasattr(layer_self_attn, "kv_scale"):
  425. layer_self_attn.attn._kv_scale = scaling_factor
  426. else:
  427. raise RuntimeError("Self attention has no KV cache scaling "
  428. "factor attribute!")