commandr.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. # coding=utf-8
  2. # Copyright 2024 Cohere and the HuggingFace Inc. team. All rights reserved.
  3. #
  4. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  5. # and OPT implementations in this library. It has been modified from its
  6. # original forms to accommodate minor architectural differences compared
  7. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  8. #
  9. # Licensed under the Apache License, Version 2.0 (the "License");
  10. # you may not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http://www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS,
  17. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. # This file is based on the LLama model definition file in transformers
  21. """PyTorch Cohere model."""
  22. from typing import Iterable, List, Optional, Tuple
  23. import torch
  24. import torch.utils.checkpoint
  25. from torch import nn
  26. from transformers import CohereConfig
  27. from aphrodite.attention import Attention, AttentionMetadata
  28. from aphrodite.common.config import CacheConfig, LoRAConfig
  29. from aphrodite.common.sequence import IntermediateTensors
  30. from aphrodite.distributed import get_tensor_model_parallel_world_size
  31. from aphrodite.modeling.layers.activation import SiluAndMul
  32. from aphrodite.modeling.layers.linear import (MergedColumnParallelLinear,
  33. QKVParallelLinear,
  34. RowParallelLinear)
  35. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  36. from aphrodite.modeling.layers.rotary_embedding import get_rope
  37. from aphrodite.modeling.layers.sampler import Sampler, SamplerOutput
  38. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  39. VocabParallelEmbedding)
  40. from aphrodite.modeling.model_loader.weight_utils import (
  41. default_weight_loader, row_parallel_weight_loader)
  42. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  43. from aphrodite.modeling.utils import set_weight_attrs
  44. from aphrodite.quantization.base_config import QuantizationConfig
  45. from .interfaces import SupportsLoRA
  46. @torch.compile
  47. def layer_norm_func(hidden_states, weight, variance_epsilon):
  48. input_dtype = hidden_states.dtype
  49. hidden_states = hidden_states.to(torch.float32)
  50. mean = hidden_states.mean(-1, keepdim=True)
  51. variance = (hidden_states - mean).pow(2).mean(-1, keepdim=True)
  52. hidden_states = (hidden_states - mean) * torch.rsqrt(variance +
  53. variance_epsilon)
  54. hidden_states = weight.to(torch.float32) * hidden_states
  55. return hidden_states.to(input_dtype)
  56. class LayerNorm(nn.Module):
  57. def __init__(self, param_shape=None, eps=1e-5):
  58. super().__init__()
  59. self.weight = nn.Parameter(torch.ones(param_shape))
  60. self.variance_epsilon = eps
  61. set_weight_attrs(self.weight,
  62. {"weight_loader": row_parallel_weight_loader})
  63. def forward(self, hidden_states, residuals=None):
  64. hidden_states = layer_norm_func(hidden_states, self.weight,
  65. self.variance_epsilon)
  66. return hidden_states, residuals
  67. # Copied from transformers.models.llama.modeling_llama.LlamaMLP Llama->Cohere
  68. class CohereMLP(nn.Module):
  69. def __init__(
  70. self,
  71. config,
  72. quant_config: Optional[QuantizationConfig] = None,
  73. ):
  74. super().__init__()
  75. self.config = config
  76. self.hidden_size = config.hidden_size
  77. self.intermediate_size = config.intermediate_size
  78. self.gate_up_proj = MergedColumnParallelLinear(
  79. self.hidden_size,
  80. [self.intermediate_size] * 2,
  81. bias=False,
  82. quant_config=quant_config,
  83. )
  84. self.down_proj = RowParallelLinear(
  85. self.intermediate_size,
  86. self.hidden_size,
  87. bias=False,
  88. quant_config=quant_config,
  89. )
  90. self.act_fn = SiluAndMul()
  91. def forward(self, x):
  92. gate_up, _ = self.gate_up_proj(x)
  93. x = self.act_fn(gate_up)
  94. x, _ = self.down_proj(x)
  95. return x
  96. class CohereAttention(nn.Module):
  97. def __init__(
  98. self,
  99. config: CohereConfig,
  100. cache_config: Optional[CacheConfig] = None,
  101. quant_config: Optional[QuantizationConfig] = None,
  102. ):
  103. super().__init__()
  104. tp_size = get_tensor_model_parallel_world_size()
  105. self.config = config
  106. self.attention_dropout = config.attention_dropout
  107. self.hidden_size = config.hidden_size
  108. self.total_num_heads = config.num_attention_heads
  109. self.num_heads = self.total_num_heads // tp_size
  110. self.head_dim = self.hidden_size // self.total_num_heads
  111. self.total_num_kv_heads = config.num_key_value_heads
  112. if self.total_num_kv_heads >= tp_size:
  113. # Number of KV heads is greater than TP size, so we partition
  114. # the KV heads across multiple tensor parallel GPUs.
  115. assert self.total_num_kv_heads % tp_size == 0
  116. else:
  117. # Number of KV heads is less than TP size, so we replicate
  118. # the KV heads across multiple tensor parallel GPUs.
  119. assert tp_size % self.total_num_kv_heads == 0
  120. self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
  121. self.q_size = self.num_heads * self.head_dim
  122. self.kv_size = self.num_kv_heads * self.head_dim
  123. self.scaling = self.head_dim**-0.5
  124. self.max_position_embeddings = getattr(
  125. config, "model_max_length", None) or getattr(
  126. config, "max_position_embeddings", 8192)
  127. self.rope_theta = config.rope_theta
  128. self.rope_scaling = getattr(config, "rope_scaling", None)
  129. self.use_qk_norm = getattr(config, "use_qk_norm", False)
  130. self.qkv_proj = QKVParallelLinear(
  131. self.hidden_size,
  132. self.head_dim,
  133. self.total_num_heads,
  134. self.total_num_kv_heads,
  135. bias=False,
  136. quant_config=quant_config,
  137. )
  138. self.o_proj = RowParallelLinear(
  139. self.total_num_heads * self.head_dim,
  140. self.hidden_size,
  141. bias=False,
  142. quant_config=quant_config,
  143. )
  144. self.rotary_emb = get_rope(
  145. self.head_dim,
  146. rotary_dim=self.head_dim,
  147. max_position=self.max_position_embeddings,
  148. base=self.rope_theta,
  149. rope_scaling=self.rope_scaling,
  150. is_neox_style=False,
  151. )
  152. self.attn = Attention(self.num_heads,
  153. self.head_dim,
  154. self.scaling,
  155. num_kv_heads=self.num_kv_heads,
  156. cache_config=cache_config,
  157. quant_config=quant_config)
  158. if self.use_qk_norm:
  159. self.q_norm = LayerNorm(param_shape=(self.num_heads,
  160. self.head_dim),
  161. eps=config.layer_norm_eps)
  162. self.k_norm = LayerNorm(param_shape=(self.num_kv_heads,
  163. self.head_dim),
  164. eps=config.layer_norm_eps)
  165. def _apply_qk_norm(self, q, k):
  166. q = q.view(*q.shape[:-1], -1, self.head_dim)
  167. k = k.view(*k.shape[:-1], -1, self.head_dim)
  168. q, _ = self.q_norm(q)
  169. k, _ = self.k_norm(k)
  170. q = q.view(*q.shape[:-2], -1)
  171. k = k.view(*k.shape[:-2], -1)
  172. return q, k
  173. def forward(
  174. self,
  175. positions: torch.Tensor,
  176. hidden_states: torch.Tensor,
  177. kv_cache: torch.Tensor,
  178. attn_metadata: AttentionMetadata,
  179. ) -> torch.Tensor:
  180. qkv, _ = self.qkv_proj(hidden_states)
  181. q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
  182. if self.use_qk_norm:
  183. q, k = self._apply_qk_norm(q, k)
  184. q, k = self.rotary_emb(positions, q, k)
  185. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  186. output, _ = self.o_proj(attn_output)
  187. return output
  188. class CohereDecoderLayer(nn.Module):
  189. def __init__(self,
  190. config: CohereConfig,
  191. cache_config: Optional[CacheConfig] = None,
  192. quant_config: Optional[QuantizationConfig] = None):
  193. super().__init__()
  194. self.hidden_size = config.hidden_size
  195. self.self_attn = CohereAttention(config,
  196. cache_config,
  197. quant_config=quant_config)
  198. self.mlp = CohereMLP(config, quant_config=quant_config)
  199. self.input_layernorm = LayerNorm(param_shape=(config.hidden_size),
  200. eps=config.layer_norm_eps)
  201. def forward(
  202. self,
  203. positions: torch.Tensor,
  204. hidden_states: torch.Tensor,
  205. kv_cache: torch.Tensor,
  206. attn_metadata: AttentionMetadata,
  207. residual: Optional[torch.Tensor],
  208. ) -> Tuple[torch.Tensor, torch.Tensor]:
  209. # Self Attention
  210. residual = hidden_states
  211. hidden_states, residual = self.input_layernorm(hidden_states, residual)
  212. hidden_states_attention = self.self_attn(
  213. positions=positions,
  214. hidden_states=hidden_states,
  215. kv_cache=kv_cache,
  216. attn_metadata=attn_metadata,
  217. )
  218. hidden_states_mlp = self.mlp(hidden_states)
  219. # Add everything together
  220. hidden_states = residual + hidden_states_attention + hidden_states_mlp
  221. return hidden_states, residual
  222. class CohereModel(nn.Module):
  223. def __init__(
  224. self,
  225. config: CohereConfig,
  226. cache_config: Optional[CacheConfig] = None,
  227. quant_config: Optional[QuantizationConfig] = None,
  228. lora_config: Optional[LoRAConfig] = None,
  229. ):
  230. super().__init__()
  231. self.config = config
  232. lora_vocab = (lora_config.lora_extra_vocab_size *
  233. (lora_config.max_loras or 1)) if lora_config else 0
  234. self.vocab_size = config.vocab_size + lora_vocab
  235. self.org_vocab_size = config.vocab_size
  236. self.embed_tokens = VocabParallelEmbedding(config.vocab_size,
  237. config.hidden_size)
  238. self.layers = nn.ModuleList([
  239. CohereDecoderLayer(config, cache_config, quant_config=quant_config)
  240. for _ in range(config.num_hidden_layers)
  241. ])
  242. self.norm = LayerNorm(param_shape=(config.hidden_size),
  243. eps=config.layer_norm_eps)
  244. def forward(
  245. self,
  246. input_ids: torch.Tensor,
  247. positions: torch.Tensor,
  248. kv_caches: List[torch.Tensor],
  249. attn_metadata: AttentionMetadata,
  250. ) -> torch.Tensor:
  251. hidden_states = self.embed_tokens(input_ids)
  252. residual = None
  253. for i in range(len(self.layers)):
  254. layer = self.layers[i]
  255. hidden_states, residual = layer(
  256. positions,
  257. hidden_states,
  258. kv_caches[i],
  259. attn_metadata,
  260. residual,
  261. )
  262. hidden_states, _ = self.norm(hidden_states, residual)
  263. return hidden_states
  264. class CohereForCausalLM(nn.Module, SupportsLoRA):
  265. packed_modules_mapping = {
  266. "qkv_proj": [
  267. "q_proj",
  268. "k_proj",
  269. "v_proj",
  270. ],
  271. "gate_up_proj": [
  272. "gate_proj",
  273. "up_proj",
  274. ],
  275. }
  276. # LoRA specific attributes
  277. supported_lora_modules = [
  278. "qkv_proj", "o_proj", "gate_up_proj", "down_proj", "embed_tokens"
  279. ]
  280. embedding_modules = {"embed_tokens": "input_embeddings"}
  281. embedding_padding_modules = []
  282. def __init__(
  283. self,
  284. config: CohereConfig,
  285. cache_config: Optional[CacheConfig] = None,
  286. quant_config: Optional[QuantizationConfig] = None,
  287. lora_config: Optional[LoRAConfig] = None,
  288. ) -> None:
  289. super().__init__()
  290. self.config = config
  291. self.unpadded_vocab_size = config.vocab_size
  292. if lora_config:
  293. self.unpadded_vocab_size += lora_config.lora_extra_vocab_size
  294. self.quant_config = quant_config
  295. self.logits_processor = LogitsProcessor(self.unpadded_vocab_size,
  296. config.vocab_size,
  297. scale=config.logit_scale)
  298. self.model = CohereModel(config,
  299. cache_config,
  300. quant_config,
  301. lora_config=lora_config)
  302. self.sampler = Sampler()
  303. @torch.no_grad()
  304. def forward(
  305. self,
  306. input_ids: torch.Tensor,
  307. positions: torch.Tensor,
  308. kv_caches: List[torch.Tensor],
  309. attn_metadata: AttentionMetadata,
  310. intermediate_tensors: Optional[IntermediateTensors] = None,
  311. ) -> torch.Tensor:
  312. hidden_states = self.model(input_ids, positions, kv_caches,
  313. attn_metadata)
  314. return hidden_states
  315. def compute_logits(
  316. self,
  317. hidden_states: torch.Tensor,
  318. sampling_metadata: SamplingMetadata,
  319. ) -> Optional[torch.Tensor]:
  320. is_not_lora = hasattr(self.model.embed_tokens, 'weight')
  321. if is_not_lora:
  322. logits = self.logits_processor(self.model.embed_tokens,
  323. hidden_states, sampling_metadata)
  324. else:
  325. logits = self.logits_processor(self.model.embed_tokens.base_layer,
  326. hidden_states, sampling_metadata)
  327. return logits
  328. def sample(
  329. self,
  330. logits: torch.Tensor,
  331. sampling_metadata: SamplingMetadata,
  332. ) -> Optional[SamplerOutput]:
  333. next_tokens = self.sampler(logits, sampling_metadata)
  334. return next_tokens
  335. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  336. stacked_params_mapping = [
  337. # (param_name, shard_name, shard_id)
  338. ("qkv_proj", "q_proj", "q"),
  339. ("qkv_proj", "k_proj", "k"),
  340. ("qkv_proj", "v_proj", "v"),
  341. ("gate_up_proj", "gate_proj", 0),
  342. ("gate_up_proj", "up_proj", 1),
  343. ]
  344. params_dict = dict(self.named_parameters())
  345. loaded_params = set()
  346. for name, loaded_weight in weights:
  347. for param_name, shard_name, shard_id in stacked_params_mapping:
  348. if shard_name not in name:
  349. continue
  350. name = name.replace(shard_name, param_name)
  351. # Skip loading extra bias for GPTQ models.
  352. if name.endswith(".bias") and name not in params_dict:
  353. continue
  354. param = params_dict[name]
  355. weight_loader = param.weight_loader
  356. weight_loader(param, loaded_weight, shard_id)
  357. break
  358. else:
  359. # lm_head is not used in vllm as it is tied with embed_token.
  360. # To prevent errors, skip loading lm_head.weight.
  361. if "lm_head.weight" in name:
  362. continue
  363. # Skip loading extra bias for GPTQ models.
  364. if name.endswith(".bias") and name not in params_dict:
  365. continue
  366. param = params_dict[name]
  367. weight_loader = getattr(param, "weight_loader",
  368. default_weight_loader)
  369. weight_loader(param, loaded_weight)
  370. loaded_params.add(name)