model_minimind.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. # 📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘
  2. # MiniMind Config
  3. # 📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘
  4. from transformers import PretrainedConfig
  5. class MiniMindConfig(PretrainedConfig):
  6. model_type = "minimind"
  7. def __init__(
  8. self,
  9. dropout: float = 0.0,
  10. bos_token_id: int = 1,
  11. eos_token_id: int = 2,
  12. hidden_act: str = 'silu',
  13. hidden_size: int = 512,
  14. intermediate_size: int = None,
  15. max_position_embeddings: int = 32768,
  16. num_attention_heads: int = 8,
  17. num_hidden_layers: int = 8,
  18. num_key_value_heads: int = 2,
  19. vocab_size: int = 6400,
  20. rms_norm_eps: float = 1e-05,
  21. rope_theta: int = 1000000.0,
  22. inference_rope_scaling: bool = False,
  23. flash_attn: bool = True,
  24. ####################################################
  25. # Here are the specific configurations of MOE
  26. # When use_moe is false, the following is invalid
  27. ####################################################
  28. use_moe: bool = False,
  29. num_experts_per_tok: int = 2,
  30. n_routed_experts: int = 4,
  31. n_shared_experts: int = 1,
  32. scoring_func: str = 'softmax',
  33. aux_loss_alpha: float = 0.01,
  34. seq_aux: bool = True,
  35. norm_topk_prob: bool = True,
  36. **kwargs
  37. ):
  38. super().__init__(**kwargs)
  39. self.dropout = dropout
  40. self.bos_token_id = bos_token_id
  41. self.eos_token_id = eos_token_id
  42. self.hidden_act = hidden_act
  43. self.hidden_size = hidden_size
  44. self.intermediate_size = intermediate_size
  45. self.max_position_embeddings = max_position_embeddings
  46. self.num_attention_heads = num_attention_heads
  47. self.num_hidden_layers = num_hidden_layers
  48. self.num_key_value_heads = num_key_value_heads
  49. self.vocab_size = vocab_size
  50. self.rms_norm_eps = rms_norm_eps
  51. self.rope_theta = rope_theta
  52. self.inference_rope_scaling = inference_rope_scaling
  53. # 外推长度 = factor * original_max_position_embeddings = 32768
  54. self.rope_scaling = {
  55. "beta_fast": 32,
  56. "beta_slow": 1,
  57. "factor": 16,
  58. "original_max_position_embeddings": 2048,
  59. "attention_factor": 1.0,
  60. "type": "yarn"
  61. } if self.inference_rope_scaling else None
  62. self.flash_attn = flash_attn
  63. ####################################################
  64. # Here are the specific configurations of MOE
  65. # When use_moe is false, the following is invalid
  66. ####################################################
  67. self.use_moe = use_moe
  68. self.num_experts_per_tok = num_experts_per_tok # 每个token选择的专家数量
  69. self.n_routed_experts = n_routed_experts # 总的专家数量
  70. self.n_shared_experts = n_shared_experts # 共享专家
  71. self.scoring_func = scoring_func # 评分函数,默认为'softmax'
  72. self.aux_loss_alpha = aux_loss_alpha # 辅助损失的alpha参数
  73. self.seq_aux = seq_aux # 是否在序列级别上计算辅助损失
  74. self.norm_topk_prob = norm_topk_prob # 是否标准化top-k概率
  75. # 📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘
  76. # MiniMind Model
  77. # 📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘
  78. import math
  79. import torch
  80. import torch.nn.init as init
  81. import torch.nn.functional as F
  82. from torch import nn
  83. from transformers.activations import ACT2FN
  84. from typing import Optional, Tuple, List, Union
  85. from transformers import PreTrainedModel, GenerationMixin, PretrainedConfig
  86. from transformers.modeling_outputs import CausalLMOutputWithPast
  87. class RMSNorm(torch.nn.Module):
  88. def __init__(self, dim: int, eps: float = 1e-5):
  89. super().__init__()
  90. self.eps = eps
  91. self.weight = nn.Parameter(torch.ones(dim))
  92. def _norm(self, x):
  93. return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
  94. def forward(self, x):
  95. return self.weight * self._norm(x.float()).type_as(x)
  96. def precompute_freqs_cis(dim: int, end: int = int(32 * 1024), rope_base: float = 1e6,
  97. rope_scaling: Optional[dict] = None):
  98. freqs, attn_factor = 1.0 / (rope_base ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)), 1.0
  99. if rope_scaling is not None:
  100. orig_max, factor, beta_fast, beta_slow, attn_factor = (
  101. rope_scaling.get("original_max_position_embeddings", 2048), rope_scaling.get("factor", 16),
  102. rope_scaling.get("beta_fast", 32.0), rope_scaling.get("beta_slow", 1.0), rope_scaling.get("attention_factor", 1.0)
  103. )
  104. if end / orig_max > 1.0:
  105. # YaRN: f'(i) = f(i)((1-γ) + γ/s), where γ∈[0,1] is linear ramp
  106. inv_dim = lambda b: (dim * math.log(orig_max / (b * 2 * math.pi))) / (2 * math.log(rope_base))
  107. low, high = max(math.floor(inv_dim(beta_fast)), 0), min(math.ceil(inv_dim(beta_slow)), dim // 2 - 1)
  108. ramp = torch.clamp((torch.arange(dim // 2, device=freqs.device).float() - low) / max(high - low, 0.001), 0, 1)
  109. freqs = freqs * (1 - ramp + ramp / factor)
  110. t = torch.arange(end, device=freqs.device)
  111. freqs = torch.outer(t, freqs).float()
  112. freqs_cos = torch.cat([torch.cos(freqs), torch.cos(freqs)], dim=-1) * attn_factor
  113. freqs_sin = torch.cat([torch.sin(freqs), torch.sin(freqs)], dim=-1) * attn_factor
  114. return freqs_cos, freqs_sin
  115. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  116. def rotate_half(x):
  117. return torch.cat((-x[..., x.shape[-1] // 2:], x[..., : x.shape[-1] // 2]), dim=-1)
  118. q_embed = (q * cos.unsqueeze(unsqueeze_dim)) + (rotate_half(q) * sin.unsqueeze(unsqueeze_dim))
  119. k_embed = (k * cos.unsqueeze(unsqueeze_dim)) + (rotate_half(k) * sin.unsqueeze(unsqueeze_dim))
  120. return q_embed, k_embed
  121. def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
  122. """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
  123. bs, slen, num_key_value_heads, head_dim = x.shape
  124. if n_rep == 1:
  125. return x
  126. return (
  127. x[:, :, :, None, :].expand(bs, slen, num_key_value_heads, n_rep, head_dim).reshape(bs, slen, num_key_value_heads * n_rep, head_dim)
  128. )
  129. class Attention(nn.Module):
  130. def __init__(self, args: MiniMindConfig):
  131. super().__init__()
  132. self.num_key_value_heads = args.num_attention_heads if args.num_key_value_heads is None else args.num_key_value_heads
  133. assert args.num_attention_heads % self.num_key_value_heads == 0
  134. self.n_local_heads = args.num_attention_heads
  135. self.n_local_kv_heads = self.num_key_value_heads
  136. self.n_rep = self.n_local_heads // self.n_local_kv_heads
  137. self.head_dim = args.hidden_size // args.num_attention_heads
  138. self.q_proj = nn.Linear(args.hidden_size, args.num_attention_heads * self.head_dim, bias=False)
  139. self.k_proj = nn.Linear(args.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  140. self.v_proj = nn.Linear(args.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
  141. self.o_proj = nn.Linear(args.num_attention_heads * self.head_dim, args.hidden_size, bias=False)
  142. self.attn_dropout = nn.Dropout(args.dropout)
  143. self.resid_dropout = nn.Dropout(args.dropout)
  144. self.dropout = args.dropout
  145. self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn
  146. # print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
  147. def forward(self,
  148. x: torch.Tensor,
  149. position_embeddings: Tuple[torch.Tensor, torch.Tensor], # 修改为接收cos和sin
  150. past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
  151. use_cache=False,
  152. attention_mask: Optional[torch.Tensor] = None):
  153. bsz, seq_len, _ = x.shape
  154. xq, xk, xv = self.q_proj(x), self.k_proj(x), self.v_proj(x)
  155. xq = xq.view(bsz, seq_len, self.n_local_heads, self.head_dim)
  156. xk = xk.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
  157. xv = xv.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
  158. cos, sin = position_embeddings
  159. xq, xk = apply_rotary_pos_emb(xq, xk, cos[:seq_len], sin[:seq_len])
  160. # kv_cache实现
  161. if past_key_value is not None:
  162. xk = torch.cat([past_key_value[0], xk], dim=1)
  163. xv = torch.cat([past_key_value[1], xv], dim=1)
  164. past_kv = (xk, xv) if use_cache else None
  165. xq, xk, xv = (
  166. xq.transpose(1, 2),
  167. repeat_kv(xk, self.n_rep).transpose(1, 2),
  168. repeat_kv(xv, self.n_rep).transpose(1, 2)
  169. )
  170. if self.flash and seq_len > 1 and (attention_mask is None or torch.all(attention_mask == 1)):
  171. output = F.scaled_dot_product_attention(xq, xk, xv, dropout_p=self.dropout if self.training else 0.0, is_causal=True)
  172. else:
  173. scores = (xq @ xk.transpose(-2, -1)) / math.sqrt(self.head_dim)
  174. scores = scores + torch.triu(
  175. torch.full((seq_len, seq_len), float("-inf"), device=scores.device),
  176. diagonal=1
  177. ).unsqueeze(0).unsqueeze(0) # scores+mask
  178. if attention_mask is not None:
  179. extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
  180. extended_attention_mask = (1.0 - extended_attention_mask) * -1e9
  181. scores = scores + extended_attention_mask
  182. scores = F.softmax(scores.float(), dim=-1).type_as(xq)
  183. scores = self.attn_dropout(scores)
  184. output = scores @ xv
  185. output = output.transpose(1, 2).reshape(bsz, seq_len, -1)
  186. output = self.resid_dropout(self.o_proj(output))
  187. return output, past_kv
  188. class FeedForward(nn.Module):
  189. def __init__(self, config: MiniMindConfig):
  190. super().__init__()
  191. if config.intermediate_size is None:
  192. intermediate_size = int(config.hidden_size * 8 / 3)
  193. config.intermediate_size = 64 * ((intermediate_size + 64 - 1) // 64)
  194. self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
  195. self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
  196. self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
  197. self.dropout = nn.Dropout(config.dropout)
  198. self.act_fn = ACT2FN[config.hidden_act]
  199. def forward(self, x):
  200. return self.dropout(self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)))
  201. class MoEGate(nn.Module):
  202. def __init__(self, config: MiniMindConfig):
  203. super().__init__()
  204. self.config = config
  205. self.top_k = config.num_experts_per_tok
  206. self.n_routed_experts = config.n_routed_experts
  207. self.scoring_func = config.scoring_func
  208. self.alpha = config.aux_loss_alpha
  209. self.seq_aux = config.seq_aux
  210. self.norm_topk_prob = config.norm_topk_prob
  211. self.gating_dim = config.hidden_size
  212. self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
  213. self.reset_parameters()
  214. def reset_parameters(self) -> None:
  215. init.kaiming_uniform_(self.weight, a=math.sqrt(5))
  216. def forward(self, hidden_states):
  217. bsz, seq_len, h = hidden_states.shape
  218. hidden_states = hidden_states.view(-1, h)
  219. logits = F.linear(hidden_states, self.weight, None)
  220. if self.scoring_func == 'softmax':
  221. scores = logits.softmax(dim=-1)
  222. else:
  223. raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
  224. topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
  225. if self.top_k > 1 and self.norm_topk_prob:
  226. denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
  227. topk_weight = topk_weight / denominator
  228. if self.training and self.alpha > 0.0:
  229. scores_for_aux = scores
  230. aux_topk = self.top_k
  231. topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
  232. if self.seq_aux:
  233. scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
  234. ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
  235. ce.scatter_add_(1, topk_idx_for_aux_loss,
  236. torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)).div_(
  237. seq_len * aux_topk / self.n_routed_experts)
  238. aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
  239. else:
  240. mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
  241. ce = mask_ce.float().mean(0)
  242. Pi = scores_for_aux.mean(0)
  243. fi = ce * self.n_routed_experts
  244. aux_loss = (Pi * fi).sum() * self.alpha
  245. else:
  246. aux_loss = 0
  247. return topk_idx, topk_weight, aux_loss
  248. class MOEFeedForward(nn.Module):
  249. def __init__(self, config: MiniMindConfig):
  250. super().__init__()
  251. self.config = config
  252. self.experts = nn.ModuleList([
  253. FeedForward(config)
  254. for _ in range(config.n_routed_experts)
  255. ])
  256. self.gate = MoEGate(config)
  257. if config.n_shared_experts > 0:
  258. self.shared_experts = nn.ModuleList([
  259. FeedForward(config)
  260. for _ in range(config.n_shared_experts)
  261. ])
  262. def forward(self, x):
  263. identity = x
  264. orig_shape = x.shape
  265. bsz, seq_len, _ = x.shape
  266. # 使用门控机制选择专家
  267. topk_idx, topk_weight, aux_loss = self.gate(x)
  268. x = x.view(-1, x.shape[-1])
  269. flat_topk_idx = topk_idx.view(-1)
  270. if self.training:
  271. x = x.repeat_interleave(self.config.num_experts_per_tok, dim=0)
  272. y = torch.empty_like(x, dtype=x.dtype)
  273. for i, expert in enumerate(self.experts):
  274. expert_out = expert(x[flat_topk_idx == i])
  275. if expert_out.shape[0] > 0: y[flat_topk_idx == i] = expert_out.to(y.dtype)
  276. else: y[flat_topk_idx == i] = expert_out.to(y.dtype) + 0 * sum(p.sum() for p in expert.parameters())
  277. y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
  278. y = y.view(*orig_shape)
  279. else:
  280. y = self.moe_infer(x, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
  281. if self.config.n_shared_experts > 0:
  282. for expert in self.shared_experts:
  283. y = y + expert(identity)
  284. self.aux_loss = aux_loss
  285. return y
  286. @torch.no_grad()
  287. def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
  288. expert_cache = torch.zeros_like(x)
  289. idxs = flat_expert_indices.argsort()
  290. tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
  291. token_idxs = idxs // self.config.num_experts_per_tok
  292. # 当tokens_per_expert = [6, 15, 20, 26],tokens_per_expert.shape[0]即为专家数量(此时为4)
  293. # 且token_idxs = [3, 7, 19, 21, 24, 25, 4, 5, 6, 10, 11, 12...] 时
  294. # 意味token_idxs[:6] -> [3, 7, 19, 21, 24, 25]这6个位置属于专家0处理的token(每个token有可能被多个专家处理,这取决于num_experts_per_tok)
  295. # 接下来9个位置token_idxs[6:15] -> [4, 5, 6, 10, 11, 12...]属于专家1处理的token...依此类推
  296. for i, end_idx in enumerate(tokens_per_expert):
  297. start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
  298. if start_idx == end_idx:
  299. continue
  300. expert = self.experts[i]
  301. exp_token_idx = token_idxs[start_idx:end_idx]
  302. expert_tokens = x[exp_token_idx]
  303. expert_out = expert(expert_tokens).to(expert_cache.dtype)
  304. expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
  305. expert_cache.scatter_add_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out)
  306. return expert_cache
  307. class MiniMindBlock(nn.Module):
  308. def __init__(self, layer_id: int, config: MiniMindConfig):
  309. super().__init__()
  310. self.num_attention_heads = config.num_attention_heads
  311. self.hidden_size = config.hidden_size
  312. self.head_dim = config.hidden_size // config.num_attention_heads
  313. self.self_attn = Attention(config)
  314. self.layer_id = layer_id
  315. self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  316. self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  317. self.mlp = FeedForward(config) if not config.use_moe else MOEFeedForward(config)
  318. def forward(self, hidden_states, position_embeddings, past_key_value=None, use_cache=False, attention_mask=None):
  319. residual = hidden_states
  320. hidden_states, present_key_value = self.self_attn(
  321. self.input_layernorm(hidden_states), position_embeddings,
  322. past_key_value, use_cache, attention_mask
  323. )
  324. hidden_states += residual
  325. hidden_states = hidden_states + self.mlp(self.post_attention_layernorm(hidden_states))
  326. return hidden_states, present_key_value
  327. class MiniMindModel(nn.Module):
  328. def __init__(self, config: MiniMindConfig):
  329. super().__init__()
  330. self.config = config
  331. self.vocab_size, self.num_hidden_layers = config.vocab_size, config.num_hidden_layers
  332. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
  333. self.dropout = nn.Dropout(config.dropout)
  334. self.layers = nn.ModuleList([MiniMindBlock(l, config) for l in range(self.num_hidden_layers)])
  335. self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  336. freqs_cos, freqs_sin = precompute_freqs_cis(dim=config.hidden_size // config.num_attention_heads,
  337. end=config.max_position_embeddings, rope_base=config.rope_theta,
  338. rope_scaling=config.rope_scaling)
  339. self.register_buffer("freqs_cos", freqs_cos, persistent=False)
  340. self.register_buffer("freqs_sin", freqs_sin, persistent=False)
  341. def forward(self,
  342. input_ids: Optional[torch.Tensor] = None,
  343. attention_mask: Optional[torch.Tensor] = None,
  344. past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
  345. use_cache: bool = False,
  346. **kwargs):
  347. batch_size, seq_length = input_ids.shape
  348. if hasattr(past_key_values, 'layers'): past_key_values = None
  349. past_key_values = past_key_values or [None] * len(self.layers)
  350. start_pos = past_key_values[0][0].shape[1] if past_key_values[0] is not None else 0
  351. hidden_states = self.dropout(self.embed_tokens(input_ids))
  352. position_embeddings = (
  353. self.freqs_cos[start_pos:start_pos + seq_length],
  354. self.freqs_sin[start_pos:start_pos + seq_length]
  355. )
  356. presents = []
  357. for layer_idx, (layer, past_key_value) in enumerate(zip(self.layers, past_key_values)):
  358. hidden_states, present = layer(
  359. hidden_states,
  360. position_embeddings,
  361. past_key_value=past_key_value,
  362. use_cache=use_cache,
  363. attention_mask=attention_mask
  364. )
  365. presents.append(present)
  366. hidden_states = self.norm(hidden_states)
  367. aux_loss = sum(
  368. layer.mlp.aux_loss
  369. for layer in self.layers
  370. if isinstance(layer.mlp, MOEFeedForward)
  371. )
  372. return hidden_states, presents, aux_loss
  373. class MiniMindForCausalLM(PreTrainedModel, GenerationMixin):
  374. config_class = MiniMindConfig
  375. def __init__(self, config: MiniMindConfig = None):
  376. self.config = config or MiniMindConfig()
  377. super().__init__(self.config)
  378. self.model = MiniMindModel(self.config)
  379. self.lm_head = nn.Linear(self.config.hidden_size, self.config.vocab_size, bias=False)
  380. self.model.embed_tokens.weight = self.lm_head.weight
  381. def forward(self,
  382. input_ids: Optional[torch.Tensor] = None,
  383. attention_mask: Optional[torch.Tensor] = None,
  384. past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
  385. use_cache: bool = False,
  386. logits_to_keep: Union[int, torch.Tensor] = 0,
  387. **args):
  388. hidden_states, past_key_values, aux_loss = self.model(
  389. input_ids=input_ids,
  390. attention_mask=attention_mask,
  391. past_key_values=past_key_values,
  392. use_cache=use_cache,
  393. **args
  394. )
  395. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  396. logits = self.lm_head(hidden_states[:, slice_indices, :])
  397. output = CausalLMOutputWithPast(logits=logits, past_key_values=past_key_values, hidden_states=hidden_states)
  398. output.aux_loss = aux_loss
  399. return output