nemotron.py 21 KB

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