1
0

grok.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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 2024 The X-AI team.
  5. # Copyright 2024 The PygmalionAI team.
  6. # Copyright 2023 The vLLM team.
  7. # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
  8. #
  9. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  10. # and OPT implementations in this library. It has been modified from its
  11. # original forms to accommodate minor architectural differences compared
  12. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  13. #
  14. # Licensed under the Apache License, Version 2.0 (the "License");
  15. # you may not use this file except in compliance with the License.
  16. # You may obtain a copy of the License at
  17. #
  18. # http://www.apache.org/licenses/LICENSE-2.0
  19. #
  20. # Unless required by applicable law or agreed to in writing, software
  21. # distributed under the License is distributed on an "AS IS" BASIS,
  22. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. # See the License for the specific language governing permissions and
  24. # limitations under the License.
  25. """Inference-only Grok model."""
  26. from typing import List, Optional, Tuple
  27. import numpy as np
  28. import torch
  29. import torch.nn.functional as F
  30. from torch import nn
  31. from aphrodite.modeling.metadata import InputMetadata
  32. from aphrodite.modeling.layers.attention import PagedAttention
  33. from aphrodite.modeling.layers.layernorm import RMSNorm
  34. from aphrodite.modeling.layers.linear import (
  35. LinearMethodBase,
  36. ReplicatedLinear,
  37. QKVParallelLinear,
  38. RowParallelLinear,
  39. ColumnParallelLinear,
  40. )
  41. from aphrodite.modeling.layers.rotary_embedding import get_rope
  42. from aphrodite.modeling.layers.sampler import Sampler, QuantSampler
  43. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  44. VocabParallelEmbedding,
  45. ParallelLMHead,
  46. )
  47. from aphrodite.modeling.megatron.communication_op import (
  48. tensor_model_parallel_all_reduce, )
  49. from aphrodite.modeling.megatron.parallel_state import (
  50. get_tensor_model_parallel_rank,
  51. get_tensor_model_parallel_world_size,
  52. )
  53. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  54. from aphrodite.modeling.hf_downloader import (
  55. default_weight_loader,
  56. hf_model_weights_iterator,
  57. )
  58. from aphrodite.common.sequence import SamplerOutput
  59. from aphrodite.transformers_utils.configs import GrokConfig
  60. KVCache = Tuple[torch.Tensor, torch.Tensor]
  61. class GrokMLP(nn.Module):
  62. def __init__(
  63. self,
  64. num_experts: int,
  65. hidden_size: int,
  66. intermediate_size: int,
  67. linear_method: Optional[LinearMethodBase] = None,
  68. ) -> None:
  69. super().__init__()
  70. self.num_experts = num_experts
  71. self.ffn_dim = intermediate_size
  72. self.hidden_dim = hidden_size
  73. self.linear = ReplicatedLinear(
  74. self.hidden_dim,
  75. self.ffn_dim,
  76. bias=False,
  77. linear_method=linear_method,
  78. )
  79. self.linear_1 = ReplicatedLinear(
  80. self.ffn_dim,
  81. self.hidden_dim,
  82. bias=False,
  83. linear_method=linear_method,
  84. )
  85. self.linear_v = ReplicatedLinear(
  86. self.hidden_dim,
  87. self.ffn_dim,
  88. bias=False,
  89. linear_method=linear_method,
  90. )
  91. # TODO: Use Aphrodite's SiluAndMul
  92. self.act_fn = nn.SiLU()
  93. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  94. linear_out, _ = self.linear(hidden_states)
  95. linear_out = self.act_fn(linear_out)
  96. linear_v_out, _ = self.linear_v(hidden_states)
  97. current_hidden_states = linear_out * linear_v_out
  98. current_hidden_states, _ = self.linear_1(current_hidden_states)
  99. return current_hidden_states
  100. class GrokMoE(nn.Module):
  101. def __init__(
  102. self,
  103. config: GrokConfig,
  104. linear_method: Optional[LinearMethodBase] = None,
  105. ):
  106. super().__init__()
  107. self.config = config
  108. self.rank = get_tensor_model_parallel_rank()
  109. self.tp_size = get_tensor_model_parallel_world_size()
  110. self.num_total_experts = config.num_local_experts
  111. self.top_k = config.num_experts_per_tok
  112. if self.tp_size > self.num_total_experts:
  113. raise ValueError(
  114. f"Tensor parallel size {self.tp_size} is greater than "
  115. f"the number of experts {self.num_total_experts}.")
  116. # Split experts equally between ranks
  117. self.expert_indicies = np.array_split(range(
  118. self.num_total_experts), self.tp_size)[self.rank].tolist()
  119. if not self.expert_indicies:
  120. raise ValueError(
  121. f"Rank {self.rank} has no experts assigned to it.")
  122. self.experts = nn.ModuleList([
  123. GrokMLP(
  124. self.num_total_experts,
  125. config.hidden_size,
  126. config.intermediate_size,
  127. linear_method=linear_method,
  128. ) if idx in self.expert_indicies else None
  129. for idx in range(self.num_total_experts)
  130. ])
  131. self.gate = ReplicatedLinear(
  132. config.hidden_size,
  133. self.num_total_experts,
  134. bias=False,
  135. linear_method=None,
  136. )
  137. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  138. batch_size, sequence_length, hidden_dim = hidden_states.shape
  139. hidden_states = hidden_states.view(-1, hidden_dim)
  140. # router_logits: (batch * sequence_length, n_experts)
  141. router_logits, _ = self.gate(hidden_states)
  142. routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
  143. routing_weights, selected_experts = torch.topk(routing_weights,
  144. self.top_k,
  145. dim=-1)
  146. routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
  147. final_hidden_states = None
  148. for expert_idx in self.expert_indicies:
  149. expert_layer = self.experts[expert_idx]
  150. expert_mask = selected_experts == expert_idx
  151. expert_weights = (routing_weights * expert_mask).sum(dim=-1,
  152. keepdim=True)
  153. current_hidden_states = expert_layer(hidden_states).mul_(
  154. expert_weights)
  155. if final_hidden_states is None:
  156. final_hidden_states = current_hidden_states
  157. else:
  158. final_hidden_states.add_(current_hidden_states)
  159. return tensor_model_parallel_all_reduce(final_hidden_states).view(
  160. batch_size, sequence_length, hidden_dim)
  161. class GrokAttention(nn.Module):
  162. def __init__(
  163. self,
  164. hidden_size: int,
  165. num_heads: int,
  166. num_kv_heads: int,
  167. max_position: int = 4096 * 2,
  168. rope_theta: float = 10000,
  169. linear_method: Optional[LinearMethodBase] = None,
  170. sliding_window: Optional[int] = None,
  171. ) -> None:
  172. super().__init__()
  173. self.hidden_size = hidden_size
  174. tp_size = get_tensor_model_parallel_world_size()
  175. self.total_num_heads = num_heads
  176. assert self.total_num_heads % tp_size == 0
  177. self.num_heads = self.total_num_heads // tp_size
  178. self.total_num_kv_heads = num_kv_heads
  179. if self.total_num_kv_heads >= tp_size:
  180. # Number of KV heads is greater than TP size, so we partition
  181. # the KV heads across multiple tensor parallel GPUs.
  182. assert self.total_num_kv_heads % tp_size == 0
  183. else:
  184. # Number of KV heads is less than TP size, so we replicate
  185. # the KV heads across multiple tensor parallel GPUs.
  186. assert tp_size % self.total_num_kv_heads == 0
  187. self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
  188. self.head_dim = hidden_size // self.total_num_heads
  189. self.q_size = self.num_heads * self.head_dim
  190. self.kv_size = self.num_kv_heads * self.head_dim
  191. self.scaling = self.head_dim**-0.5
  192. self.rope_theta = rope_theta
  193. self.sliding_window = sliding_window
  194. if (linear_method is not None
  195. and not linear_method.quant_config.merge_weight()):
  196. self.merge_weight = False
  197. self.query = ColumnParallelLinear(
  198. hidden_size,
  199. self.q_size,
  200. bias=False,
  201. linear_method=linear_method,
  202. )
  203. self.key = ColumnParallelLinear(
  204. hidden_size,
  205. self.kv_size,
  206. bias=False,
  207. linear_method=linear_method,
  208. )
  209. self.value = ColumnParallelLinear(
  210. hidden_size,
  211. self.kv_size,
  212. bias=False,
  213. linear_method=linear_method,
  214. )
  215. else:
  216. self.merge_weight = True
  217. self.qkv_proj = QKVParallelLinear(
  218. hidden_size,
  219. self.head_dim,
  220. self.total_num_heads,
  221. self.total_num_kv_heads,
  222. bias=False,
  223. linear_method=linear_method,
  224. )
  225. self.linear = RowParallelLinear(
  226. self.total_num_heads * self.head_dim,
  227. hidden_size,
  228. bias=False,
  229. linear_method=linear_method,
  230. )
  231. self.rotary_emb = get_rope(
  232. self.head_dim,
  233. rotary_dim=self.head_dim,
  234. max_position=max_position,
  235. base=int(self.rope_theta),
  236. is_neox_style=True,
  237. )
  238. self.attn = PagedAttention(
  239. self.num_heads,
  240. self.head_dim,
  241. self.scaling,
  242. num_kv_heads=self.num_kv_heads,
  243. sliding_window=self.sliding_window,
  244. )
  245. def forward(
  246. self,
  247. positions: torch.Tensor,
  248. hidden_states: torch.Tensor,
  249. kv_cache: KVCache,
  250. input_metadata: InputMetadata,
  251. ) -> torch.Tensor:
  252. if self.merge_weight:
  253. qkv, _ = self.qkv_proj(hidden_states)
  254. q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size],
  255. dim=-1)
  256. else:
  257. q, _ = self.query(hidden_states)
  258. k, _ = self.key(hidden_states)
  259. v, _ = self.value(hidden_states)
  260. q, k = self.rotary_emb(positions, q, k)
  261. k_cache, v_cache = kv_cache
  262. attn_output = self.attn(q, k, v, k_cache, v_cache, input_metadata)
  263. # NOTE: This is a hack, figure out a better way to do this.
  264. attn_output = 30 * torch.tanh(attn_output / 30)
  265. output, _ = self.linear(attn_output)
  266. return output
  267. class GrokDecoderLayer(nn.Module):
  268. def __init__(
  269. self,
  270. config: GrokConfig,
  271. linear_method: Optional[LinearMethodBase] = None,
  272. ) -> None:
  273. super().__init__()
  274. self.hidden_size = config.hidden_size
  275. # Requires transformers > 4.32.0
  276. rope_theta = getattr(config, "rope_theta", 10000)
  277. self.self_attn = GrokAttention(
  278. hidden_size=self.hidden_size,
  279. num_heads=config.num_attention_heads,
  280. max_position=config.max_position_embeddings,
  281. num_kv_heads=config.num_key_value_heads,
  282. rope_theta=rope_theta,
  283. sliding_window=config.sliding_window,
  284. linear_method=linear_method,
  285. )
  286. self.block_sparse_moe = GrokMoE(config=config,
  287. linear_method=linear_method)
  288. self.input_layernorm = RMSNorm(config.hidden_size,
  289. eps=config.rms_norm_eps)
  290. self.post_attention_layernorm = RMSNorm(config.hidden_size,
  291. eps=config.rms_norm_eps)
  292. def forward(
  293. self,
  294. positions: torch.Tensor,
  295. hidden_states: torch.Tensor,
  296. kv_cache: KVCache,
  297. input_metadata: InputMetadata,
  298. residual: Optional[torch.Tensor],
  299. ) -> torch.Tensor:
  300. # Self Attention
  301. if residual is None:
  302. residual = hidden_states
  303. hidden_states = self.input_layernorm(hidden_states)
  304. else:
  305. hidden_states, residual = self.input_layernorm(
  306. hidden_states, residual)
  307. hidden_states = self.self_attn(
  308. positions=positions,
  309. hidden_states=hidden_states,
  310. kv_cache=kv_cache,
  311. input_metadata=input_metadata,
  312. )
  313. # Fully Connected
  314. hidden_states, residual = self.post_attention_layernorm(
  315. hidden_states, residual)
  316. hidden_states = self.block_sparse_moe(hidden_states)
  317. return hidden_states, residual
  318. class GrokModel(nn.Module):
  319. def __init__(
  320. self,
  321. config: GrokConfig,
  322. linear_method: Optional[LinearMethodBase] = None,
  323. ) -> None:
  324. super().__init__()
  325. self.padding_idx = config.pad_token_id
  326. self.vocab_size = config.vocab_size
  327. self.embed_tokens = VocabParallelEmbedding(
  328. config.vocab_size,
  329. config.hidden_size,
  330. linear_method=linear_method,
  331. )
  332. self.layers = nn.ModuleList([
  333. GrokDecoderLayer(config, linear_method=linear_method)
  334. for _ in range(config.num_hidden_layers)
  335. ])
  336. self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  337. def forward(
  338. self,
  339. input_ids: torch.Tensor,
  340. positions: torch.Tensor,
  341. kv_caches: List[KVCache],
  342. input_metadata: InputMetadata,
  343. ) -> torch.Tensor:
  344. hidden_states = self.embed_tokens(input_ids)
  345. residual = None
  346. for i in range(len(self.layers)):
  347. layer = self.layers[i]
  348. hidden_states, residual = layer(positions, hidden_states,
  349. kv_caches[i], input_metadata,
  350. residual)
  351. hidden_states, _ = self.norm(hidden_states, residual)
  352. return hidden_states
  353. class GrokForCausalLM(nn.Module):
  354. def __init__(
  355. self,
  356. config: GrokConfig,
  357. linear_method: Optional[LinearMethodBase] = None,
  358. ) -> None:
  359. super().__init__()
  360. self.config = config
  361. self.linear_method = linear_method
  362. self.model = GrokModel(config, linear_method)
  363. self.lm_head = ParallelLMHead(
  364. config.vocab_size,
  365. config.hidden_size,
  366. linear_method=linear_method,
  367. )
  368. self.sampler = Sampler(config.vocab_size)
  369. self.quant_sampler = QuantSampler(config.vocab_size)
  370. def forward(
  371. self,
  372. input_ids: torch.Tensor,
  373. positions: torch.Tensor,
  374. kv_caches: List[KVCache],
  375. input_metadata: InputMetadata,
  376. ) -> torch.Tensor:
  377. hidden_states = self.model(input_ids, positions, kv_caches,
  378. input_metadata)
  379. return hidden_states
  380. def sample(
  381. self,
  382. hidden_states: Optional[torch.Tensor],
  383. sampling_metadata: SamplingMetadata,
  384. ) -> Optional[SamplerOutput]:
  385. if (self.linear_method is not None
  386. and not self.linear_method.quant_config.merge_weight()):
  387. next_tokens = self.quant_sampler(self.lm_head(hidden_states),
  388. sampling_metadata)
  389. else:
  390. next_tokens = self.sampler(self.lm_head.weight, hidden_states,
  391. sampling_metadata)
  392. return next_tokens
  393. def load_weights(
  394. self,
  395. model_name_or_path: str,
  396. cache_dir: Optional[str] = None,
  397. load_format: str = "auto",
  398. revision: Optional[str] = None,
  399. ):
  400. stacked_params_mapping = [
  401. # (param_name, shard_name, shard_id)
  402. ("qkv_proj", "query", "q"),
  403. ("qkv_proj", "key", "k"),
  404. ("qkv_proj", "value", "v"),
  405. ]
  406. if (self.linear_method is not None
  407. and not self.linear_method.quant_config.merge_weight()):
  408. stacked_params_mapping = []
  409. params_dict = dict(self.named_parameters())
  410. for name, loaded_weight in hf_model_weights_iterator(
  411. model_name_or_path,
  412. cache_dir,
  413. load_format,
  414. revision,
  415. self.config,
  416. fall_back_to_pt=False,
  417. ):
  418. if "rotary_emb.inv_freq" in name:
  419. continue
  420. for param_name, weight_name, shard_id in stacked_params_mapping:
  421. if weight_name not in name:
  422. continue
  423. name = name.replace(weight_name, param_name)
  424. # Skip loading extra bias for GPTQ models.
  425. if name.endswith(".bias") and name not in params_dict:
  426. continue
  427. param = params_dict[name]
  428. weight_loader = param.weight_loader
  429. weight_loader(param, loaded_weight, shard_id)
  430. break
  431. else:
  432. # Skip loading extra bias for GPTQ models.
  433. if name.endswith(".bias") and name not in params_dict:
  434. continue
  435. # Skip experts that are not assigned to this worker.
  436. if ("moe." in name and name not in params_dict):
  437. continue
  438. param = params_dict[name]
  439. weight_loader = getattr(param, "weight_loader",
  440. default_weight_loader)
  441. weight_loader(param, loaded_weight)