llama.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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, 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 LoRAConfig
  30. from aphrodite.common.sequence import SamplerOutput
  31. from aphrodite.common.utils import is_hip
  32. from aphrodite.modeling.hf_downloader import (default_weight_loader,
  33. hf_model_weights_iterator,
  34. kv_cache_scales_loader)
  35. from aphrodite.modeling.layers.activation import SiluAndMul
  36. from aphrodite.modeling.layers.layernorm import RMSNorm
  37. from aphrodite.modeling.layers.linear import (ColumnParallelLinear,
  38. LinearMethodBase,
  39. MergedColumnParallelLinear,
  40. QKVParallelLinear,
  41. RowParallelLinear)
  42. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  43. from aphrodite.modeling.layers.rotary_embedding import get_rope
  44. from aphrodite.modeling.layers.sampler import Sampler
  45. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  46. DEFAULT_VOCAB_PADDING_SIZE, ParallelLMHead, VocabParallelEmbedding)
  47. from aphrodite.distributed import (get_tensor_model_parallel_rank,
  48. get_tensor_model_parallel_world_size)
  49. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  50. class LlamaMLP(nn.Module):
  51. def __init__(
  52. self,
  53. hidden_size: int,
  54. intermediate_size: int,
  55. hidden_act: str,
  56. linear_method: Optional[LinearMethodBase] = None,
  57. ) -> None:
  58. super().__init__()
  59. if (linear_method is not None
  60. and not linear_method.quant_config.merge_weight()):
  61. self.merge_weight = False
  62. self.gate_proj = ColumnParallelLinear(
  63. hidden_size,
  64. intermediate_size,
  65. bias=False,
  66. linear_method=linear_method,
  67. )
  68. self.up_proj = ColumnParallelLinear(
  69. hidden_size,
  70. intermediate_size,
  71. bias=False,
  72. linear_method=linear_method,
  73. )
  74. else:
  75. self.merge_weight = True
  76. self.gate_up_proj = MergedColumnParallelLinear(
  77. hidden_size,
  78. [intermediate_size] * 2,
  79. bias=False,
  80. linear_method=linear_method,
  81. )
  82. self.down_proj = RowParallelLinear(
  83. intermediate_size,
  84. hidden_size,
  85. bias=False,
  86. linear_method=linear_method,
  87. )
  88. if hidden_act != "silu":
  89. raise ValueError(f"Unsupported activation: {hidden_act}. "
  90. "Only silu is supported for now.")
  91. self.act_fn = SiluAndMul()
  92. def forward(self, x):
  93. if self.merge_weight:
  94. gate_up, _ = self.gate_up_proj(x)
  95. else:
  96. up, _ = self.up_proj(x)
  97. gate, _ = self.gate_proj(x)
  98. gate_up = torch.cat([gate, up], dim=-1)
  99. x = self.act_fn(gate_up)
  100. x, _ = self.down_proj(x)
  101. return x
  102. class LlamaAttention(nn.Module):
  103. def __init__(
  104. self,
  105. hidden_size: int,
  106. num_heads: int,
  107. num_kv_heads: int,
  108. rope_theta: float = 10000,
  109. rope_scaling: Optional[Dict[str, Any]] = None,
  110. max_position_embeddings: int = 8192,
  111. linear_method: Optional[LinearMethodBase] = None,
  112. bias: bool = False,
  113. sliding_window: Optional[int] = None,
  114. ) -> None:
  115. super().__init__()
  116. self.hidden_size = hidden_size
  117. tp_size = get_tensor_model_parallel_world_size()
  118. self.total_num_heads = num_heads
  119. assert self.total_num_heads % tp_size == 0
  120. self.num_heads = self.total_num_heads // tp_size
  121. self.total_num_kv_heads = num_kv_heads
  122. if self.total_num_kv_heads >= tp_size:
  123. # Number of KV heads is greater than TP size, so we partition
  124. # the KV heads across multiple tensor parallel GPUs.
  125. assert self.total_num_kv_heads % tp_size == 0
  126. else:
  127. # Number of KV heads is less than TP size, so we replicate
  128. # the KV heads across multiple tensor parallel GPUs.
  129. assert tp_size % self.total_num_kv_heads == 0
  130. self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
  131. self.head_dim = hidden_size // self.total_num_heads
  132. self.q_size = self.num_heads * self.head_dim
  133. self.kv_size = self.num_kv_heads * self.head_dim
  134. self.scaling = self.head_dim**-0.5
  135. self.rope_theta = rope_theta
  136. self.max_position_embeddings = max_position_embeddings
  137. # This will be overwritten by model initialization if we are using it.
  138. # N.B. currently we only support per tensor scalar scaling factors
  139. # & only applicable to ROCm (AMD GPU).
  140. # The scaling factor convention we are assuming is
  141. # quantized_value * scaling_factor ~= true_value
  142. # which is consistent with the practice of setting
  143. # scaling_factor = tensor_amax / FPtype_max
  144. self.kv_scale = 1.0
  145. if (linear_method is not None
  146. and not linear_method.quant_config.merge_weight()):
  147. self.merge_weight = False
  148. self.q_proj = ColumnParallelLinear(
  149. hidden_size,
  150. self.total_num_heads * self.head_dim,
  151. bias=bias,
  152. linear_method=linear_method,
  153. )
  154. self.k_proj = ColumnParallelLinear(
  155. hidden_size,
  156. self.total_num_kv_heads * self.head_dim,
  157. bias=bias,
  158. linear_method=linear_method,
  159. )
  160. self.v_proj = ColumnParallelLinear(
  161. hidden_size,
  162. self.total_num_kv_heads * self.head_dim,
  163. bias=bias,
  164. linear_method=linear_method,
  165. )
  166. else:
  167. self.merge_weight = True
  168. self.qkv_proj = QKVParallelLinear(
  169. hidden_size,
  170. self.head_dim,
  171. self.total_num_heads,
  172. self.total_num_kv_heads,
  173. bias=bias,
  174. linear_method=linear_method,
  175. )
  176. self.o_proj = RowParallelLinear(
  177. self.total_num_heads * self.head_dim,
  178. hidden_size,
  179. bias=bias,
  180. linear_method=linear_method,
  181. )
  182. self.rotary_emb = get_rope(
  183. self.head_dim,
  184. rotary_dim=self.head_dim,
  185. max_position=max_position_embeddings,
  186. base=rope_theta,
  187. rope_scaling=rope_scaling,
  188. is_neox_style=True,
  189. )
  190. self.attn = Attention(
  191. self.num_heads,
  192. self.head_dim,
  193. self.scaling,
  194. num_kv_heads=self.num_kv_heads,
  195. sliding_window=sliding_window,
  196. )
  197. def forward(
  198. self,
  199. positions: torch.Tensor,
  200. hidden_states: torch.Tensor,
  201. kv_cache: torch.Tensor,
  202. attn_metadata: AttentionMetadata,
  203. # kv_quant_param: List[float],
  204. ) -> torch.Tensor:
  205. if self.merge_weight:
  206. qkv, _ = self.qkv_proj(hidden_states)
  207. q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size],
  208. dim=-1)
  209. else:
  210. q, _ = self.q_proj(hidden_states)
  211. k, _ = self.k_proj(hidden_states)
  212. v, _ = self.v_proj(hidden_states)
  213. q, k = self.rotary_emb(positions, q, k)
  214. attn_output = self.attn(q, k, v, kv_cache, attn_metadata,
  215. self.kv_scale)
  216. output, _ = self.o_proj(attn_output)
  217. return output
  218. class LlamaDecoderLayer(nn.Module):
  219. def __init__(
  220. self,
  221. config: LlamaConfig,
  222. linear_method: Optional[LinearMethodBase] = None,
  223. ) -> None:
  224. super().__init__()
  225. self.hidden_size = config.hidden_size
  226. rope_theta = getattr(config, "rope_theta", 10000)
  227. rope_scaling = getattr(config, "rope_scaling", None)
  228. max_position_embeddings = getattr(config, "max_position_embeddings",
  229. 8192)
  230. sliding_window = getattr(config, "sliding_window", None)
  231. # Support abacusai/Smaug-72B-v0.1 with attention_bias
  232. # Support internlm/internlm-7b with bias
  233. attention_bias = getattr(config, "attention_bias", False) or getattr(
  234. config, "bias", False)
  235. self.self_attn = LlamaAttention(
  236. hidden_size=self.hidden_size,
  237. num_heads=config.num_attention_heads,
  238. num_kv_heads=getattr(config, "num_key_value_heads",
  239. config.num_attention_heads),
  240. rope_theta=rope_theta,
  241. rope_scaling=rope_scaling,
  242. max_position_embeddings=max_position_embeddings,
  243. linear_method=linear_method,
  244. bias=attention_bias,
  245. sliding_window=sliding_window,
  246. )
  247. self.mlp = LlamaMLP(
  248. hidden_size=self.hidden_size,
  249. intermediate_size=config.intermediate_size,
  250. hidden_act=config.hidden_act,
  251. linear_method=linear_method,
  252. )
  253. self.input_layernorm = RMSNorm(config.hidden_size,
  254. eps=config.rms_norm_eps)
  255. self.post_attention_layernorm = RMSNorm(config.hidden_size,
  256. eps=config.rms_norm_eps)
  257. if config.model_type == "Yi":
  258. # Some old Yi finetunes and quants have not been llama-fied
  259. self.ln1 = self.input_layernorm
  260. self.ln2 = self.post_attention_layernorm
  261. def forward(
  262. self,
  263. positions: torch.Tensor,
  264. hidden_states: torch.Tensor,
  265. kv_cache: torch.Tensor,
  266. attn_metadata: AttentionMetadata,
  267. residual: Optional[torch.Tensor],
  268. # kv_quant_param: List[float],
  269. ) -> Tuple[torch.Tensor, torch.Tensor]:
  270. # Self Attention
  271. if residual is None:
  272. residual = hidden_states
  273. hidden_states = self.input_layernorm(hidden_states)
  274. else:
  275. hidden_states, residual = self.input_layernorm(
  276. hidden_states, residual)
  277. hidden_states = self.self_attn(
  278. positions=positions,
  279. hidden_states=hidden_states,
  280. kv_cache=kv_cache,
  281. attn_metadata=attn_metadata,
  282. # kv_quant_param=kv_quant_param,
  283. )
  284. # Fully Connected
  285. hidden_states, residual = self.post_attention_layernorm(
  286. hidden_states, residual)
  287. hidden_states = self.mlp(hidden_states)
  288. return hidden_states, residual
  289. class LlamaModel(nn.Module):
  290. def __init__(
  291. self,
  292. config: LlamaConfig,
  293. linear_method: Optional[LinearMethodBase] = None,
  294. lora_config: Optional[LoRAConfig] = None,
  295. ) -> None:
  296. super().__init__()
  297. self.config = config
  298. self.padding_idx = config.pad_token_id
  299. lora_vocab = ((lora_config.lora_extra_vocab_size *
  300. (lora_config.max_loras or 1)) if lora_config else 0)
  301. self.vocab_size = config.vocab_size + lora_vocab
  302. self.org_vocab_size = config.vocab_size
  303. self.embed_tokens = VocabParallelEmbedding(
  304. self.vocab_size,
  305. config.hidden_size,
  306. linear_method=linear_method,
  307. org_num_embeddings=config.vocab_size,
  308. )
  309. self.layers = nn.ModuleList([
  310. LlamaDecoderLayer(config, linear_method)
  311. for _ in range(config.num_hidden_layers)
  312. ])
  313. self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  314. def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
  315. return self.embed_tokens(input_ids)
  316. def forward(
  317. self,
  318. input_ids: Optional[torch.Tensor],
  319. positions: torch.Tensor,
  320. kv_caches: List[torch.Tensor],
  321. attn_metadata: AttentionMetadata,
  322. inputs_embeds: Optional[torch.Tensor] = None,
  323. ) -> torch.Tensor:
  324. if inputs_embeds is not None:
  325. hidden_states = inputs_embeds
  326. else:
  327. hidden_states = self.get_input_embeddings(input_ids)
  328. residual = None
  329. for i in range(len(self.layers)):
  330. layer = self.layers[i]
  331. hidden_states, residual = layer(
  332. positions,
  333. hidden_states,
  334. kv_caches[i],
  335. attn_metadata,
  336. residual,
  337. # attn_metadata.kv_quant_params[i]
  338. # if attn_metadata.kv_quant_params is not None else None,
  339. )
  340. hidden_states, _ = self.norm(hidden_states, residual)
  341. return hidden_states
  342. class LlamaForCausalLM(nn.Module):
  343. packed_modules_mapping = {
  344. "qkv_proj": [
  345. "q_proj",
  346. "k_proj",
  347. "v_proj",
  348. ],
  349. "gate_up_proj": [
  350. "gate_proj",
  351. "up_proj",
  352. ],
  353. }
  354. # LoRA specific attributes
  355. supported_lora_modules = [
  356. "qkv_proj",
  357. "o_proj",
  358. "gate_up_proj",
  359. "down_proj",
  360. "embed_tokens",
  361. "lm_head",
  362. ]
  363. embedding_modules = {
  364. "embed_tokens": "input_embeddings",
  365. "lm_head": "output_embeddings",
  366. }
  367. embedding_padding_modules = ["lm_head"]
  368. def __init__(
  369. self,
  370. config: LlamaConfig,
  371. linear_method: Optional[LinearMethodBase] = None,
  372. lora_config: Optional[LoRAConfig] = None,
  373. ) -> None:
  374. super().__init__()
  375. self.config = config
  376. self.linear_method = linear_method
  377. self.model = LlamaModel(config, linear_method, lora_config=lora_config)
  378. self.unpadded_vocab_size = config.vocab_size
  379. if lora_config:
  380. self.unpadded_vocab_size += lora_config.lora_extra_vocab_size
  381. self.lm_head = ParallelLMHead(
  382. self.unpadded_vocab_size,
  383. config.hidden_size,
  384. org_num_embeddings=config.vocab_size,
  385. linear_method=linear_method,
  386. padding_size=DEFAULT_VOCAB_PADDING_SIZE
  387. # We need bigger padding if using lora for kernel
  388. # compatibility
  389. if not lora_config else lora_config.lora_vocab_padding_size,
  390. )
  391. logit_scale = getattr(config, "logit_scale", 1.0)
  392. self.logits_processor = LogitsProcessor(self.unpadded_vocab_size,
  393. config.vocab_size, logit_scale)
  394. self.sampler = Sampler()
  395. def forward(
  396. self,
  397. input_ids: torch.Tensor,
  398. positions: torch.Tensor,
  399. kv_caches: List[torch.Tensor],
  400. attn_metadata: AttentionMetadata,
  401. ) -> torch.Tensor:
  402. hidden_states = self.model(input_ids, positions, kv_caches,
  403. attn_metadata)
  404. return hidden_states
  405. def compute_logits(self, hidden_states: torch.Tensor,
  406. sampling_metadata: SamplingMetadata) -> torch.Tensor:
  407. logits = self.logits_processor(self.lm_head, hidden_states,
  408. sampling_metadata)
  409. return logits
  410. def sample(
  411. self,
  412. logits: torch.Tensor,
  413. sampling_metadata: SamplingMetadata,
  414. ) -> Optional[SamplerOutput]:
  415. next_tokens = self.sampler(logits, sampling_metadata)
  416. return next_tokens
  417. def load_weights(
  418. self,
  419. model_name_or_path: str,
  420. cache_dir: Optional[str] = None,
  421. load_format: str = "auto",
  422. revision: Optional[str] = None,
  423. ):
  424. stacked_params_mapping = [
  425. # (param_name, shard_name, shard_id)
  426. ("qkv_proj", "q_proj", "q"),
  427. ("qkv_proj", "k_proj", "k"),
  428. ("qkv_proj", "v_proj", "v"),
  429. ("gate_up_proj", "gate_proj", 0),
  430. ("gate_up_proj", "up_proj", 1),
  431. ]
  432. if (self.linear_method is not None
  433. and not self.linear_method.quant_config.merge_weight()):
  434. stacked_params_mapping = []
  435. params_dict = dict(self.named_parameters())
  436. for name, loaded_weight in hf_model_weights_iterator(
  437. model_name_or_path, cache_dir, load_format, revision,
  438. self.config):
  439. if "rotary_emb.inv_freq" in name:
  440. continue
  441. if ("rotary_emb.cos_cached" in name
  442. or "rotary_emb.sin_cached" in name):
  443. # Models trained using ColossalAI may include these tensors in
  444. # the checkpoint. Skip them.
  445. continue
  446. for param_name, weight_name, shard_id in stacked_params_mapping:
  447. if weight_name not in name:
  448. continue
  449. name = name.replace(weight_name, param_name)
  450. # Skip loading extra bias for GPTQ models.
  451. if name.endswith(".bias") and name not in params_dict:
  452. continue
  453. param = params_dict[name]
  454. weight_loader = param.weight_loader
  455. weight_loader(param, loaded_weight, shard_id)
  456. break
  457. else:
  458. # Skip loading extra bias for GPTQ models.
  459. if name.endswith(".bias") and name not in params_dict:
  460. continue
  461. param = params_dict[name]
  462. weight_loader = getattr(param, "weight_loader",
  463. default_weight_loader)
  464. weight_loader(param, loaded_weight)
  465. # If this function is called, it should always initialize KV cache scale
  466. # factors (or else raise an exception). Thus, handled exceptions should
  467. # make sure to leave KV cache scale factors in a known good (dummy) state
  468. def load_kv_cache_scales(self, quantization_param_path: str) -> None:
  469. tp_size = get_tensor_model_parallel_world_size()
  470. tp_rank = get_tensor_model_parallel_rank()
  471. for layer_idx, scaling_factor in kv_cache_scales_loader(
  472. quantization_param_path, tp_rank, tp_size,
  473. self.config.num_hidden_layers,
  474. self.config.__class__.model_type):
  475. layer_self_attn = self.model.layers[layer_idx].self_attn
  476. if is_hip():
  477. # The scaling factor convention we are assuming is
  478. # quantized_value * scaling_factor ~= true_value
  479. # which is consistent with the practice of setting
  480. # scaling_factor = tensor_amax / FPtype_max
  481. scaling_factor *= 2
  482. if hasattr(layer_self_attn, "kv_scale"):
  483. layer_self_attn.kv_scale = scaling_factor
  484. else:
  485. raise RuntimeError("Self attention has no KV cache scaling "
  486. "factor attribute!")