olmo.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. # coding=utf-8
  2. # Adapted from
  3. # https://github.com/huggingface/transformers/blob/v4.40.1/src/transformers/models/olmo/modeling_olmo.py
  4. # Copyright 2024 The vLLM team.
  5. # Copyright 2024 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 OLMo model compatible with HuggingFace weights."""
  24. from typing import Iterable, List, Optional, Tuple
  25. import torch
  26. from torch import nn
  27. from transformers import OlmoConfig
  28. from aphrodite.attention import Attention, AttentionMetadata
  29. from aphrodite.common.config import CacheConfig
  30. from aphrodite.common.sequence import IntermediateTensors
  31. from aphrodite.distributed import get_tensor_model_parallel_world_size
  32. from aphrodite.modeling.layers.activation import SiluAndMul
  33. from aphrodite.modeling.layers.linear import (MergedColumnParallelLinear,
  34. QKVParallelLinear,
  35. RowParallelLinear)
  36. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  37. from aphrodite.modeling.layers.rotary_embedding import get_rope
  38. from aphrodite.modeling.layers.sampler import Sampler, SamplerOutput
  39. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  40. ParallelLMHead, VocabParallelEmbedding)
  41. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  42. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  43. from aphrodite.quantization.base_config import QuantizationConfig
  44. class OlmoAttention(nn.Module):
  45. """
  46. This is the attention block where the output is computed as
  47. ``Attention(LN(x))`` in ``MLP(LN(x + Attention(LN(x))))``
  48. (plus another skip connection).
  49. """
  50. def __init__(
  51. self,
  52. config: OlmoConfig,
  53. cache_config: Optional[CacheConfig] = None,
  54. quant_config: Optional[QuantizationConfig] = None,
  55. ):
  56. super().__init__()
  57. self.config = config
  58. self.hidden_size = config.hidden_size
  59. tensor_model_parallel_world_size = (
  60. get_tensor_model_parallel_world_size())
  61. self.total_num_heads = config.num_attention_heads
  62. assert self.hidden_size % self.total_num_heads == 0
  63. assert self.total_num_heads % tensor_model_parallel_world_size == 0
  64. self.num_heads = (self.total_num_heads //
  65. tensor_model_parallel_world_size)
  66. self.head_dim = self.hidden_size // self.total_num_heads
  67. self.max_position_embeddings = config.max_position_embeddings
  68. self.rope_theta = config.rope_theta
  69. self.clip_qkv = config.clip_qkv
  70. # Attention input projection. Projects x -> (q, k, v)
  71. self.qkv_proj = QKVParallelLinear(
  72. self.hidden_size,
  73. self.head_dim,
  74. self.total_num_heads,
  75. bias=config.attention_bias,
  76. quant_config=quant_config,
  77. )
  78. # Rotary embeddings.
  79. self.rotary_emb = get_rope(
  80. self.head_dim,
  81. rotary_dim=self.head_dim,
  82. max_position=self.max_position_embeddings,
  83. base=self.rope_theta,
  84. )
  85. self.scaling = self.head_dim**-0.5
  86. self.attn = Attention(self.num_heads,
  87. self.head_dim,
  88. scale=self.scaling,
  89. cache_config=cache_config,
  90. quant_config=quant_config)
  91. # Attention output projection.
  92. self.o_proj = RowParallelLinear(
  93. self.hidden_size,
  94. self.hidden_size,
  95. bias=config.attention_bias,
  96. quant_config=quant_config,
  97. )
  98. def forward(
  99. self,
  100. positions: torch.Tensor,
  101. hidden_states: torch.Tensor,
  102. kv_cache: torch.Tensor,
  103. attn_metadata: AttentionMetadata,
  104. ) -> torch.Tensor:
  105. qkv, _ = self.qkv_proj(hidden_states)
  106. if self.clip_qkv is not None:
  107. qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
  108. q, k, v = qkv.chunk(chunks=3, dim=-1)
  109. q, k = self.rotary_emb(positions, q, k)
  110. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  111. output, _ = self.o_proj(attn_output)
  112. return output
  113. class OlmoMLP(nn.Module):
  114. """
  115. This is the MLP block where the output is computed as
  116. ``MLP(LN(x))`` in ``MLP(LN(x + Attention(LN(x))))``
  117. (plus another skip connection).
  118. """
  119. def __init__(
  120. self,
  121. config: OlmoConfig,
  122. quant_config: Optional[QuantizationConfig] = None,
  123. ):
  124. super().__init__()
  125. self.config = config
  126. self.hidden_size = config.hidden_size
  127. self.intermediate_size = config.intermediate_size
  128. # Feed-forward input projection.
  129. self.gate_up_proj = MergedColumnParallelLinear(
  130. self.hidden_size,
  131. [self.intermediate_size] * 2,
  132. bias=False,
  133. quant_config=quant_config,
  134. )
  135. # Activation function.
  136. self.act_fn = SiluAndMul()
  137. # Feed-forward output projection.
  138. self.down_proj = RowParallelLinear(
  139. self.intermediate_size,
  140. self.hidden_size,
  141. bias=False,
  142. quant_config=quant_config,
  143. )
  144. def forward(
  145. self,
  146. x: torch.Tensor,
  147. ) -> torch.Tensor:
  148. gate_up, _ = self.gate_up_proj(x)
  149. x = self.act_fn(gate_up)
  150. x, _ = self.down_proj(x)
  151. return x
  152. class OlmoDecoderLayer(nn.Module):
  153. """
  154. This is a typical transformer block where the output is
  155. computed as ``MLP(LN(x + Attention(LN(x))))``
  156. (plus another skip connection).
  157. """
  158. def __init__(self,
  159. config: OlmoConfig,
  160. cache_config: Optional[CacheConfig] = None,
  161. quant_config: Optional[QuantizationConfig] = None):
  162. super().__init__()
  163. # Attention block.
  164. self.self_attn = OlmoAttention(config, cache_config, quant_config)
  165. # MLP block.
  166. self.mlp = OlmoMLP(config, quant_config)
  167. # LayerNorm
  168. self.input_layernorm = nn.LayerNorm(config.hidden_size,
  169. elementwise_affine=False,
  170. bias=False)
  171. self.post_attention_layernorm = nn.LayerNorm(config.hidden_size,
  172. elementwise_affine=False,
  173. bias=False)
  174. def forward(
  175. self,
  176. positions: torch.Tensor,
  177. hidden_states: torch.Tensor,
  178. kv_cache: torch.Tensor,
  179. attn_metadata: AttentionMetadata,
  180. ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
  181. # Attention block.
  182. residual = hidden_states
  183. hidden_states = self.input_layernorm(hidden_states)
  184. hidden_states = self.self_attn(positions, hidden_states, kv_cache,
  185. attn_metadata)
  186. hidden_states = hidden_states + residual
  187. # MLP block.
  188. residual = hidden_states
  189. hidden_states = self.post_attention_layernorm(hidden_states)
  190. hidden_states = self.mlp(hidden_states)
  191. hidden_states = residual + hidden_states
  192. return hidden_states
  193. class OlmoModel(nn.Module):
  194. def __init__(self,
  195. config: OlmoConfig,
  196. cache_config: Optional[CacheConfig] = None,
  197. quant_config: Optional[QuantizationConfig] = None):
  198. super().__init__()
  199. self.config = config
  200. self.embed_tokens = VocabParallelEmbedding(config.vocab_size,
  201. config.hidden_size)
  202. self.layers = nn.ModuleList([
  203. OlmoDecoderLayer(config, cache_config, quant_config)
  204. for layer_idx in range(config.num_hidden_layers)
  205. ])
  206. self.norm = nn.LayerNorm(config.hidden_size,
  207. elementwise_affine=False,
  208. bias=False)
  209. def forward(
  210. self,
  211. input_ids: torch.Tensor,
  212. positions: torch.Tensor,
  213. kv_caches: List[torch.Tensor],
  214. attn_metadata: AttentionMetadata,
  215. ) -> torch.Tensor:
  216. """
  217. :param input_ids: A tensor of shape `(batch_size, seq_len)`.
  218. """
  219. # Get embeddings of input.
  220. # shape: (batch_size, seq_len, d_model)
  221. inputs_embeds = self.embed_tokens(input_ids)
  222. # embed positions
  223. hidden_states = inputs_embeds
  224. # Apply blocks one-by-one.
  225. for layer_idx, decoder_layer in enumerate(self.layers):
  226. # shape: (batch_size, seq_len, d_model)
  227. hidden_states = decoder_layer(
  228. positions,
  229. hidden_states,
  230. kv_caches[layer_idx],
  231. attn_metadata,
  232. )
  233. # Apply final layer norm.
  234. # shape: (batch_size, seq_len or 1, d_model)
  235. hidden_states = self.norm(hidden_states)
  236. return hidden_states
  237. class OlmoForCausalLM(nn.Module):
  238. """
  239. Extremely barebones HF model wrapper.
  240. """
  241. def __init__(self,
  242. config: OlmoConfig,
  243. cache_config: Optional[CacheConfig] = None,
  244. quant_config: Optional[QuantizationConfig] = None):
  245. super().__init__()
  246. self.config = config
  247. self.model = OlmoModel(config, cache_config, quant_config)
  248. if config.tie_word_embeddings:
  249. self.lm_head = self.model.embed_tokens
  250. else:
  251. self.unpadded_vocab_size = config.vocab_size
  252. self.lm_head = ParallelLMHead(
  253. self.unpadded_vocab_size,
  254. config.hidden_size,
  255. org_num_embeddings=config.vocab_size,
  256. quant_config=quant_config,
  257. )
  258. self.logits_processor = LogitsProcessor(config.vocab_size)
  259. self.sampler = Sampler()
  260. def forward(
  261. self,
  262. input_ids: torch.Tensor,
  263. positions: torch.Tensor,
  264. kv_caches: List[torch.Tensor],
  265. attn_metadata: AttentionMetadata,
  266. intermediate_tensors: Optional[IntermediateTensors] = None,
  267. ) -> torch.Tensor:
  268. hidden_states = self.model(
  269. input_ids=input_ids,
  270. positions=positions,
  271. kv_caches=kv_caches,
  272. attn_metadata=attn_metadata,
  273. )
  274. return hidden_states
  275. def compute_logits(
  276. self,
  277. hidden_states: torch.Tensor,
  278. sampling_metadata: SamplingMetadata,
  279. ) -> Optional[torch.Tensor]:
  280. logits = self.logits_processor(self.lm_head, hidden_states,
  281. sampling_metadata)
  282. return logits
  283. def sample(
  284. self,
  285. logits: torch.Tensor,
  286. sampling_metadata: SamplingMetadata,
  287. ) -> Optional[SamplerOutput]:
  288. next_tokens = self.sampler(logits, sampling_metadata)
  289. return next_tokens
  290. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  291. stacked_params_mapping = [
  292. # (param_name, shard_name, shard_id)
  293. ("qkv_proj", "q_proj", "q"),
  294. ("qkv_proj", "k_proj", "k"),
  295. ("qkv_proj", "v_proj", "v"),
  296. ("gate_up_proj", "gate_proj", 0),
  297. ("gate_up_proj", "up_proj", 1),
  298. ]
  299. params_dict = dict(self.named_parameters(remove_duplicate=False))
  300. for name, loaded_weight in weights:
  301. if "rotary_emb.inv_freq" in name:
  302. continue
  303. if ("rotary_emb.cos_cached" in name
  304. or "rotary_emb.sin_cached" in name):
  305. # Models trained using ColossalAI may include these tensors in
  306. # the checkpoint. Skip them.
  307. continue
  308. # With tie_word_embeddings, we can skip lm_head.weight
  309. # The weight might appear unnecessarily in the files if the model is
  310. # processed with quantization, LoRA, fine-tuning, etc.
  311. if self.config.tie_word_embeddings and "lm_head.weight" in name:
  312. continue
  313. for (param_name, weight_name, shard_id) in stacked_params_mapping:
  314. if weight_name not in name:
  315. continue
  316. name = name.replace(weight_name, param_name)
  317. # Skip loading extra bias for GPTQ models.
  318. if name.endswith(".bias") and name not in params_dict:
  319. continue
  320. param = params_dict[name]
  321. weight_loader = param.weight_loader
  322. weight_loader(param, loaded_weight, shard_id)
  323. break
  324. else:
  325. # Skip loading extra bias for GPTQ models.
  326. if name.endswith(".bias") and name not in params_dict:
  327. continue
  328. param = params_dict[name]
  329. weight_loader = getattr(param, "weight_loader",
  330. default_weight_loader)
  331. weight_loader(param, loaded_weight)