nemotron.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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 PygmalionAi team.
  5. # Copyright 2023 The vLLM team.
  6. # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
  7. #
  8. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  9. # and OPT implementations in this library. It has been modified from its
  10. # original forms to accommodate minor architectural differences compared
  11. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  12. #
  13. # Licensed under the Apache License, Version 2.0 (the "License");
  14. # you may not use this file except in compliance with the License.
  15. # You may obtain a copy of the License at
  16. #
  17. # http://www.apache.org/licenses/LICENSE-2.0
  18. #
  19. # Unless required by applicable law or agreed to in writing, software
  20. # distributed under the License is distributed on an "AS IS" BASIS,
  21. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. # See the License for the specific language governing permissions and
  23. # limitations under the License.
  24. """Inference-only Nemotron model compatible with HuggingFace weights."""
  25. from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
  26. import torch
  27. from torch import nn
  28. from transformers import NemotronConfig
  29. from aphrodite.attention import Attention, AttentionMetadata
  30. from aphrodite.common.config import CacheConfig, LoRAConfig
  31. from aphrodite.common.sequence import IntermediateTensors, SamplerOutput
  32. from aphrodite.common.utils import progress_bar
  33. from aphrodite.distributed import (get_pp_group,
  34. get_tensor_model_parallel_world_size)
  35. from aphrodite.modeling.layers.activation import get_act_fn
  36. from aphrodite.modeling.layers.linear import (ColumnParallelLinear,
  37. QKVParallelLinear,
  38. RowParallelLinear)
  39. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  40. from aphrodite.modeling.layers.rotary_embedding import get_rope
  41. from aphrodite.modeling.layers.sampler import Sampler
  42. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  43. DEFAULT_VOCAB_PADDING_SIZE, ParallelLMHead, VocabParallelEmbedding)
  44. from aphrodite.modeling.model_loader.weight_utils import (
  45. default_weight_loader, maybe_remap_kv_scale_name)
  46. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  47. from aphrodite.quantization.base_config import QuantizationConfig
  48. from .interfaces import SupportsLoRA
  49. from .utils import PPMissingLayer, is_pp_missing_parameter, make_layers
  50. # The architecture is pretty similar to Llama, with these changes:
  51. # - There is no gate_proj, just up_proj
  52. # - Normal LayerNorm (with a +1 to the weights) instead of RMSNorm
  53. # - Squared ReLU instead of SwiGLU
  54. # - Adds a rotary_percent to RoPE
  55. def _cast_if_autocast_enabled(*args):
  56. if not torch.is_autocast_enabled():
  57. return args
  58. else:
  59. return torch.cuda.amp.autocast_mode._cast(
  60. args, torch.get_autocast_gpu_dtype())
  61. class NemotronLayerNorm1P(nn.LayerNorm):
  62. def __init__(self,
  63. normalized_shape: Union[int, List[int], torch.Size],
  64. eps: float = 1e-5,
  65. elementwise_affine: bool = True,
  66. bias: bool = True,
  67. device=None,
  68. dtype=None):
  69. super().__init__(normalized_shape, eps, elementwise_affine, bias,
  70. device, dtype)
  71. def forward(
  72. self,
  73. x: torch.Tensor,
  74. residual: Optional[torch.Tensor] = None,
  75. ) -> torch.Tensor:
  76. if residual is not None:
  77. x = x + residual
  78. residual = x
  79. args = _cast_if_autocast_enabled(x, self.normalized_shape,
  80. self.weight + 1, self.bias, self.eps)
  81. with torch.cuda.amp.autocast(enabled=False):
  82. x = torch.nn.functional.layer_norm(*args)
  83. return x if residual is None else (x, residual)
  84. class NemotronMLP(nn.Module):
  85. def __init__(
  86. self,
  87. hidden_size: int,
  88. intermediate_size: int,
  89. hidden_act: str,
  90. quant_config: Optional[QuantizationConfig] = None,
  91. bias: bool = False,
  92. prefix: str = "",
  93. ) -> None:
  94. super().__init__()
  95. self.up_proj = ColumnParallelLinear(input_size=hidden_size,
  96. output_size=intermediate_size,
  97. bias=bias,
  98. quant_config=quant_config,
  99. prefix=f"{prefix}.up_proj")
  100. self.down_proj = RowParallelLinear(input_size=intermediate_size,
  101. output_size=hidden_size,
  102. bias=bias,
  103. quant_config=quant_config,
  104. prefix=f"{prefix}.down_proj")
  105. self.act_fn = get_act_fn(hidden_act)
  106. def forward(self, x):
  107. up, _ = self.up_proj(x)
  108. x = self.act_fn(up)
  109. x, _ = self.down_proj(x)
  110. return x
  111. class NemotronAttention(nn.Module):
  112. def __init__(
  113. self,
  114. config: NemotronConfig,
  115. hidden_size: int,
  116. num_heads: int,
  117. num_kv_heads: int,
  118. rope_theta: float = 10000,
  119. rope_scaling: Optional[Dict[str, Any]] = None,
  120. max_position_embeddings: int = 8192,
  121. quant_config: Optional[QuantizationConfig] = None,
  122. bias: bool = False,
  123. cache_config: Optional[CacheConfig] = None,
  124. prefix: str = "",
  125. ) -> None:
  126. super().__init__()
  127. self.hidden_size = hidden_size
  128. tp_size = get_tensor_model_parallel_world_size()
  129. self.total_num_heads = num_heads
  130. assert self.total_num_heads % tp_size == 0
  131. self.num_heads = self.total_num_heads // tp_size
  132. self.total_num_kv_heads = num_kv_heads
  133. if self.total_num_kv_heads >= tp_size:
  134. # Number of KV heads is greater than TP size, so we partition
  135. # the KV heads across multiple tensor parallel GPUs.
  136. assert self.total_num_kv_heads % tp_size == 0
  137. else:
  138. # Number of KV heads is less than TP size, so we replicate
  139. # the KV heads across multiple tensor parallel GPUs.
  140. assert tp_size % self.total_num_kv_heads == 0
  141. self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
  142. # MistralConfig has an optional head_dim introduced by Mistral-Nemo
  143. self.head_dim = getattr(config, "head_dim",
  144. self.hidden_size // self.total_num_heads)
  145. self.q_size = self.num_heads * self.head_dim
  146. self.kv_size = self.num_kv_heads * self.head_dim
  147. self.scaling = self.head_dim**-0.5
  148. self.rope_theta = rope_theta
  149. self.rotary_percent = config.partial_rotary_factor
  150. self.max_position_embeddings = max_position_embeddings
  151. self.qkv_proj = QKVParallelLinear(
  152. hidden_size=hidden_size,
  153. head_size=self.head_dim,
  154. total_num_heads=self.total_num_heads,
  155. total_num_kv_heads=self.total_num_kv_heads,
  156. bias=bias,
  157. quant_config=quant_config,
  158. prefix=f"{prefix}.qkv_proj",
  159. )
  160. self.o_proj = RowParallelLinear(
  161. input_size=self.total_num_heads * self.head_dim,
  162. output_size=hidden_size,
  163. bias=bias,
  164. quant_config=quant_config,
  165. prefix=f"{prefix}.o_proj",
  166. )
  167. self.rotary_emb = get_rope(
  168. self.head_dim,
  169. rotary_dim=self.head_dim,
  170. max_position=max_position_embeddings,
  171. base=rope_theta,
  172. rope_scaling=rope_scaling,
  173. rotary_percent=self.rotary_percent,
  174. )
  175. self.attn = Attention(self.num_heads,
  176. self.head_dim,
  177. self.scaling,
  178. num_kv_heads=self.num_kv_heads,
  179. cache_config=cache_config,
  180. quant_config=quant_config)
  181. def forward(
  182. self,
  183. positions: torch.Tensor,
  184. hidden_states: torch.Tensor,
  185. kv_cache: torch.Tensor,
  186. attn_metadata: AttentionMetadata,
  187. ) -> torch.Tensor:
  188. qkv, _ = self.qkv_proj(hidden_states)
  189. q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
  190. q, k = self.rotary_emb(positions, q, k)
  191. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  192. output, _ = self.o_proj(attn_output)
  193. return output
  194. class NemotronDecoderLayer(nn.Module):
  195. def __init__(
  196. self,
  197. config: NemotronConfig,
  198. cache_config: Optional[CacheConfig] = None,
  199. quant_config: Optional[QuantizationConfig] = None,
  200. prefix: str = "",
  201. ) -> None:
  202. super().__init__()
  203. self.hidden_size = config.hidden_size
  204. rope_theta = getattr(config, "rope_theta", 10000)
  205. rope_scaling = getattr(config, "rope_scaling", None)
  206. if rope_scaling is not None and getattr(
  207. config, "original_max_position_embeddings", None):
  208. rope_scaling["original_max_position_embeddings"] = (
  209. config.original_max_position_embeddings)
  210. max_position_embeddings = getattr(config, "max_position_embeddings",
  211. 8192)
  212. # Support abacusai/Smaug-72B-v0.1 with attention_bias
  213. # Support internlm/internlm-7b with bias
  214. attention_bias = getattr(config, "attention_bias", False) or getattr(
  215. config, "bias", False)
  216. self.self_attn = NemotronAttention(
  217. config=config,
  218. hidden_size=self.hidden_size,
  219. num_heads=config.num_attention_heads,
  220. num_kv_heads=getattr(config, "num_key_value_heads",
  221. config.num_attention_heads),
  222. rope_theta=rope_theta,
  223. rope_scaling=rope_scaling,
  224. max_position_embeddings=max_position_embeddings,
  225. quant_config=quant_config,
  226. bias=attention_bias,
  227. cache_config=cache_config,
  228. prefix=f"{prefix}.self_attn",
  229. )
  230. self.mlp = NemotronMLP(
  231. hidden_size=self.hidden_size,
  232. intermediate_size=config.intermediate_size,
  233. hidden_act=config.hidden_act,
  234. quant_config=quant_config,
  235. bias=getattr(config, "mlp_bias", False),
  236. prefix=f"{prefix}.mlp",
  237. )
  238. self.input_layernorm = NemotronLayerNorm1P(config.hidden_size,
  239. eps=config.norm_eps)
  240. self.post_attention_layernorm = NemotronLayerNorm1P(
  241. config.hidden_size, eps=config.norm_eps)
  242. def forward(
  243. self,
  244. positions: torch.Tensor,
  245. hidden_states: torch.Tensor,
  246. kv_cache: torch.Tensor,
  247. attn_metadata: AttentionMetadata,
  248. residual: Optional[torch.Tensor],
  249. ) -> Tuple[torch.Tensor, torch.Tensor]:
  250. # Self Attention
  251. if residual is None:
  252. residual = hidden_states
  253. hidden_states = self.input_layernorm(hidden_states)
  254. else:
  255. hidden_states, residual = self.input_layernorm(
  256. hidden_states, residual)
  257. hidden_states = self.self_attn(
  258. positions=positions,
  259. hidden_states=hidden_states,
  260. kv_cache=kv_cache,
  261. attn_metadata=attn_metadata,
  262. )
  263. # Fully Connected
  264. hidden_states, residual = self.post_attention_layernorm(
  265. hidden_states, residual)
  266. hidden_states = self.mlp(hidden_states)
  267. return hidden_states, residual
  268. class NemotronModel(nn.Module):
  269. def __init__(
  270. self,
  271. config: NemotronConfig,
  272. cache_config: Optional[CacheConfig] = None,
  273. quant_config: Optional[QuantizationConfig] = None,
  274. lora_config: Optional[LoRAConfig] = None,
  275. prefix: str = "",
  276. ) -> None:
  277. super().__init__()
  278. self.config = config
  279. self.padding_idx = config.pad_token_id
  280. lora_vocab = (lora_config.lora_extra_vocab_size *
  281. (lora_config.max_loras or 1)) if lora_config else 0
  282. self.vocab_size = config.vocab_size + lora_vocab
  283. self.org_vocab_size = config.vocab_size
  284. if get_pp_group().is_first_rank or (config.tie_word_embeddings
  285. and get_pp_group().is_last_rank):
  286. self.embed_tokens = VocabParallelEmbedding(
  287. self.vocab_size,
  288. config.hidden_size,
  289. org_num_embeddings=config.vocab_size,
  290. )
  291. else:
  292. self.embed_tokens = PPMissingLayer()
  293. self.start_layer, self.end_layer, self.layers = make_layers(
  294. config.num_hidden_layers,
  295. lambda prefix: NemotronDecoderLayer(config=config,
  296. cache_config=cache_config,
  297. quant_config=quant_config,
  298. prefix=prefix),
  299. prefix=f"{prefix}.layers")
  300. if get_pp_group().is_last_rank:
  301. self.norm = NemotronLayerNorm1P(config.hidden_size,
  302. eps=config.norm_eps)
  303. else:
  304. self.norm = PPMissingLayer()
  305. def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
  306. return self.embed_tokens(input_ids)
  307. def forward(
  308. self,
  309. input_ids: Optional[torch.Tensor],
  310. positions: torch.Tensor,
  311. kv_caches: List[torch.Tensor],
  312. attn_metadata: AttentionMetadata,
  313. intermediate_tensors: Optional[IntermediateTensors],
  314. inputs_embeds: Optional[torch.Tensor] = None,
  315. ) -> Union[torch.Tensor, IntermediateTensors]:
  316. if get_pp_group().is_first_rank:
  317. if inputs_embeds is not None:
  318. hidden_states = inputs_embeds
  319. else:
  320. hidden_states = self.get_input_embeddings(input_ids)
  321. residual = None
  322. else:
  323. assert intermediate_tensors is not None
  324. hidden_states = intermediate_tensors["hidden_states"]
  325. residual = intermediate_tensors["residual"]
  326. for i in range(self.start_layer, self.end_layer):
  327. layer = self.layers[i]
  328. hidden_states, residual = layer(
  329. positions,
  330. hidden_states,
  331. kv_caches[i - self.start_layer],
  332. attn_metadata,
  333. residual,
  334. )
  335. if not get_pp_group().is_last_rank:
  336. return IntermediateTensors({
  337. "hidden_states": hidden_states,
  338. "residual": residual
  339. })
  340. hidden_states, _ = self.norm(hidden_states, residual)
  341. return hidden_states
  342. class NemotronForCausalLM(nn.Module, SupportsLoRA):
  343. packed_modules_mapping = {
  344. "qkv_proj": [
  345. "q_proj",
  346. "k_proj",
  347. "v_proj",
  348. ],
  349. }
  350. # LoRA specific attributes
  351. supported_lora_modules = [
  352. "qkv_proj", "o_proj", "up_proj", "down_proj", "embed_tokens", "lm_head"
  353. ]
  354. embedding_modules = {
  355. "embed_tokens": "input_embeddings",
  356. "lm_head": "output_embeddings",
  357. }
  358. embedding_padding_modules = ["lm_head"]
  359. bitsandbytes_stacked_params_mapping = {
  360. # shard_name, weight_name, index
  361. "q_proj": ("qkv_proj", 0),
  362. "k_proj": ("qkv_proj", 1),
  363. "v_proj": ("qkv_proj", 2),
  364. }
  365. def __init__(
  366. self,
  367. config: NemotronConfig,
  368. cache_config: Optional[CacheConfig] = None,
  369. quant_config: Optional[QuantizationConfig] = None,
  370. lora_config: Optional[LoRAConfig] = None,
  371. ) -> None:
  372. super().__init__()
  373. assert isinstance(config, NemotronConfig)
  374. self.config = config
  375. self.lora_config = lora_config
  376. self.model = NemotronModel(config,
  377. cache_config,
  378. quant_config,
  379. lora_config=lora_config,
  380. prefix="model")
  381. if get_pp_group().is_last_rank:
  382. self.unpadded_vocab_size = config.vocab_size
  383. if lora_config:
  384. self.unpadded_vocab_size += lora_config.lora_extra_vocab_size
  385. self.lm_head = ParallelLMHead(
  386. self.unpadded_vocab_size,
  387. config.hidden_size,
  388. org_num_embeddings=config.vocab_size,
  389. padding_size=DEFAULT_VOCAB_PADDING_SIZE
  390. # We need bigger padding if using lora for kernel
  391. # compatibility
  392. if not lora_config else lora_config.lora_vocab_padding_size,
  393. quant_config=quant_config,
  394. )
  395. if config.tie_word_embeddings:
  396. self.lm_head.weight = self.model.embed_tokens.weight
  397. logit_scale = getattr(config, "logit_scale", 1.0)
  398. self.logits_processor = LogitsProcessor(self.unpadded_vocab_size,
  399. config.vocab_size,
  400. logit_scale)
  401. self.sampler = Sampler()
  402. else:
  403. self.lm_head = PPMissingLayer()
  404. def forward(
  405. self,
  406. input_ids: torch.Tensor,
  407. positions: torch.Tensor,
  408. kv_caches: List[torch.Tensor],
  409. attn_metadata: AttentionMetadata,
  410. intermediate_tensors: Optional[IntermediateTensors] = None,
  411. ) -> Union[torch.Tensor, IntermediateTensors]:
  412. model_output = self.model(input_ids, positions, kv_caches,
  413. attn_metadata, intermediate_tensors)
  414. return model_output
  415. def compute_logits(
  416. self,
  417. hidden_states: torch.Tensor,
  418. sampling_metadata: SamplingMetadata,
  419. ) -> Optional[torch.Tensor]:
  420. logits = self.logits_processor(self.lm_head, hidden_states,
  421. sampling_metadata)
  422. return logits
  423. def sample(
  424. self,
  425. logits: torch.Tensor,
  426. sampling_metadata: SamplingMetadata,
  427. ) -> Optional[SamplerOutput]:
  428. next_tokens = self.sampler(logits, sampling_metadata)
  429. return next_tokens
  430. def make_empty_intermediate_tensors(
  431. self, batch_size: int, dtype: torch.dtype,
  432. device: torch.device) -> IntermediateTensors:
  433. return IntermediateTensors({
  434. "hidden_states":
  435. torch.zeros((batch_size, self.config.hidden_size),
  436. dtype=dtype,
  437. device=device),
  438. "residual":
  439. torch.zeros((batch_size, self.config.hidden_size),
  440. dtype=dtype,
  441. device=device),
  442. })
  443. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  444. stacked_params_mapping = [
  445. # (param_name, shard_name, shard_id)
  446. (".qkv_proj", ".q_proj", "q"),
  447. (".qkv_proj", ".k_proj", "k"),
  448. (".qkv_proj", ".v_proj", "v"),
  449. ]
  450. params_dict = dict(self.named_parameters())
  451. weights_list = list(weights)
  452. for name, loaded_weight in progress_bar(weights_list,
  453. desc="Loading modules..."):
  454. if "rotary_emb.inv_freq" in name:
  455. continue
  456. if ("rotary_emb.cos_cached" in name
  457. or "rotary_emb.sin_cached" in name):
  458. # Models trained using ColossalAI may include these tensors in
  459. # the checkpoint. Skip them.
  460. continue
  461. for (param_name, weight_name, shard_id) in stacked_params_mapping:
  462. if weight_name not in name:
  463. continue
  464. name = name.replace(weight_name, param_name)
  465. # Skip loading extra bias for GPTQ models.
  466. if name.endswith(".bias") and name not in params_dict:
  467. continue
  468. if is_pp_missing_parameter(name, self):
  469. continue
  470. param = params_dict[name]
  471. weight_loader = param.weight_loader
  472. weight_loader(param, loaded_weight, shard_id)
  473. break
  474. else:
  475. # Skip loading extra bias for GPTQ models.
  476. if name.endswith(".bias") and name not in params_dict:
  477. continue
  478. # Remapping the name of FP8 kv-scale.
  479. name = maybe_remap_kv_scale_name(name, params_dict)
  480. if name is None:
  481. continue
  482. if is_pp_missing_parameter(name, self):
  483. continue
  484. param = params_dict[name]
  485. weight_loader = getattr(param, "weight_loader",
  486. default_weight_loader)
  487. weight_loader(param, loaded_weight)