model.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import math
  2. import struct
  3. import inspect
  4. from .LMConfig import LMConfig
  5. from typing import Any, Optional, Tuple
  6. import numpy as np
  7. import torch
  8. import torch.nn.functional as F
  9. from torch import nn
  10. from transformers import PreTrainedModel
  11. from transformers.modeling_outputs import CausalLMOutputWithPast
  12. # 定义 RMSNorm 类,实现一种归一化方法,类似于 LayerNorm,但计算方式不同
  13. class RMSNorm(torch.nn.Module):
  14. def __init__(self, dim: int, eps: float):
  15. super().__init__()
  16. self.eps = eps # 设置 epsilon,防止除零错误
  17. self.weight = nn.Parameter(torch.ones(dim)) # 初始化权重参数
  18. def _norm(self, x):
  19. return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) # 计算 RMSNorm
  20. def forward(self, x):
  21. output = self._norm(x.float()).type_as(x) # 应用 RMSNorm
  22. return output * self.weight # 乘以权重参数
  23. # 定义 precompute_pos_cis 函数,用于预计算位置编码的复数形式
  24. def precompute_pos_cis(dim: int, end: int, theta: float = 10000.0):
  25. freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) # 计算频率
  26. t = torch.arange(end, device=freqs.device) # 生成时间序列
  27. freqs = torch.outer(t, freqs).float() # 计算外积
  28. pos_cis = torch.polar(torch.ones_like(freqs), freqs) # 计算复数形式的位置编码
  29. return pos_cis
  30. # 定义 apply_rotary_emb 函数,用于应用旋转位置编码
  31. def apply_rotary_emb(xq, xk, pos_cis):
  32. def unite_shape(pos_cis, x):
  33. ndim = x.ndim
  34. assert 0 <= 1 < ndim
  35. assert pos_cis.shape == (x.shape[1], x.shape[-1])
  36. shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
  37. return pos_cis.view(*shape)
  38. xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2)) # 将 xq 转换为复数形式
  39. xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2)) # 将 xk 转换为复数形式
  40. pos_cis = unite_shape(pos_cis, xq_) # 调整 pos_cis 的形状
  41. xq_out = torch.view_as_real(xq_ * pos_cis).flatten(3) # 应用旋转位置编码
  42. xk_out = torch.view_as_real(xk_ * pos_cis).flatten(3) # 应用旋转位置编码
  43. return xq_out.type_as(xq), xk_out.type_as(xk) # 返回结果
  44. # 定义 repeat_kv 函数,用于重复 KV 头的值
  45. def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
  46. """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
  47. bs, slen, n_kv_heads, head_dim = x.shape
  48. if n_rep == 1:
  49. return x
  50. return (
  51. x[:, :, :, None, :]
  52. .expand(bs, slen, n_kv_heads, n_rep, head_dim)
  53. .reshape(bs, slen, n_kv_heads * n_rep, head_dim)
  54. )
  55. # 定义 Attention 类,实现自注意力机制
  56. class Attention(nn.Module):
  57. def __init__(self, args: LMConfig):
  58. super().__init__()
  59. self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads # 设置 KV 头的数量
  60. assert args.n_heads % self.n_kv_heads == 0 # 确保 KV 头的数量是总头数的因数
  61. self.n_local_heads = args.n_heads # 设置本地头的数量
  62. self.n_local_kv_heads = self.n_kv_heads # 设置本地 KV 头的数量
  63. self.n_rep = self.n_local_heads // self.n_local_kv_heads # 计算重复次数
  64. self.head_dim = args.dim // args.n_heads # 计算每个头的维度
  65. self.wq = nn.Linear(args.dim, args.n_heads * self.head_dim, bias=False) # 初始化 Q 矩阵
  66. self.wk = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False) # 初始化 K 矩阵
  67. self.wv = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False) # 初始化 V 矩阵
  68. self.wo = nn.Linear(args.n_heads * self.head_dim, args.dim, bias=False) # 初始化输出矩阵
  69. self.k_cache, self.v_cache = None, None # 初始化 KV 缓存
  70. self.attn_dropout = nn.Dropout(args.dropout) # 初始化注意力 dropout
  71. self.resid_dropout = nn.Dropout(args.dropout) # 初始化残差 dropout
  72. self.dropout = args.dropout # 设置 dropout 概率
  73. self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn # 判断是否使用 Flash Attention
  74. if not self.flash:
  75. # print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
  76. mask = torch.full((1, 1, args.max_seq_len, args.max_seq_len), float("-inf")) # 初始化掩码
  77. mask = torch.triu(mask, diagonal=1) # 生成上三角掩码
  78. self.register_buffer("mask", mask) # 注册掩码
  79. def forward(self, x: torch.Tensor, pos_cis: torch.Tensor, use_kv_cache=False):
  80. bsz, seqlen, _ = x.shape
  81. if use_kv_cache and self.eval(): # 如果使用 KV 缓存且在评估模式下
  82. if self.k_cache is None or self.k_cache.shape[1] != x.shape[1] - 1:
  83. xq, xk, xv = self.wq(x), self.wk(x), self.wv(x) # 计算 Q, K, V
  84. else:
  85. token = x[:, -1:, :] # 获取最后一个 token
  86. xq = torch.cat((torch.zeros_like(x[:, :-1, :]), self.wq(token)), dim=1) # 更新 Q
  87. xk = torch.cat((self.k_cache, self.wk(token)), dim=1) # 更新 K
  88. xv = torch.cat((self.v_cache, self.wv(token)), dim=1) # 更新 V
  89. self.k_cache, self.v_cache = xk, xv # 更新 KV 缓存
  90. else:
  91. xq, xk, xv = self.wq(x), self.wk(x), self.wv(x) # 计算 Q, K, V
  92. xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim) # 调整 Q 的形状
  93. xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim) # 调整 K 的形状
  94. xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim) # 调整 V 的形状
  95. xq, xk = apply_rotary_emb(xq, xk, pos_cis) # 应用旋转位置编码
  96. xk = repeat_kv(xk, self.n_rep) # 重复 K 的值
  97. xv = repeat_kv(xv, self.n_rep) # 重复 V 的值
  98. xq = xq.transpose(1, 2) # 调整 Q 的形状
  99. xk = xk.transpose(1, 2) # 调整 K 的形状
  100. xv = xv.transpose(1, 2) # 调整 V 的形状
  101. if self.flash:
  102. output = torch.nn.functional.scaled_dot_product_attention(xq, xk, xv, attn_mask=None,
  103. dropout_p=self.dropout if self.training else 0.0,
  104. is_causal=True) # 使用 Flash Attention
  105. else:
  106. scores = torch.matmul(xq, xk.transpose(2, 3)) / math.sqrt(self.head_dim) # 计算注意力分数
  107. assert hasattr(self, 'mask')
  108. scores = scores + self.mask[:, :, :seqlen, :seqlen] # 应用掩码
  109. scores = F.softmax(scores.float(), dim=-1).type_as(xq) # 计算 softmax
  110. scores = self.attn_dropout(scores) # 应用注意力 dropout
  111. output = torch.matmul(scores, xv) # 计算输出
  112. output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1) # 调整输出的形状
  113. output = self.wo(output) # 应用输出矩阵
  114. output = self.resid_dropout(output) # 应用残差 dropout
  115. return output # 返回输出
  116. # 定义 FeedForward 类,实现前馈神经网络
  117. class FeedForward(nn.Module):
  118. def __init__(self, dim: int, hidden_dim: int, multiple_of: int, dropout: float):
  119. super().__init__()
  120. if hidden_dim is None:
  121. hidden_dim = 4 * dim # 设置隐藏层维度
  122. hidden_dim = int(2 * hidden_dim / 3) # 调整隐藏层维度
  123. hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of) # 调整隐藏层维度
  124. self.w1 = nn.Linear(dim, hidden_dim, bias=False) # 初始化第一层线性变换
  125. self.w2 = nn.Linear(hidden_dim, dim, bias=False) # 初始化第二层线性变换
  126. self.w3 = nn.Linear(dim, hidden_dim, bias=False) # 初始化第三层线性变换
  127. self.dropout = nn.Dropout(dropout) # 初始化 dropout
  128. def forward(self, x):
  129. return self.dropout(self.w2(F.silu(self.w1(x)) * self.w3(x))) # 前向传播
  130. # 定义 MoEGate 类,实现专家混合(MoE)的门控机制
  131. class MoEGate(nn.Module):
  132. def __init__(self, config: LMConfig):
  133. super().__init__()
  134. self.config = config
  135. self.top_k = config.num_experts_per_tok # 设置每个 token 选择的专家数量
  136. self.n_routed_experts = config.n_routed_experts # 设置路由专家的数量
  137. self.scoring_func = config.scoring_func # 设置评分函数
  138. self.alpha = config.aux_loss_alpha # 设置辅助损失的权重
  139. self.seq_aux = config.seq_aux # 设置序列辅助损失
  140. self.norm_topk_prob = config.norm_topk_prob # 设置是否归一化 top-k 概率
  141. self.gating_dim = config.dim # 设置门控维度
  142. self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim))) # 初始化权重参数
  143. self.reset_parameters() # 重置参数
  144. def reset_parameters(self) -> None:
  145. import torch.nn.init as init
  146. init.kaiming_uniform_(self.weight, a=math.sqrt(5)) # 使用 Kaiming 初始化权重
  147. def forward(self, hidden_states):
  148. bsz, seq_len, h = hidden_states.shape
  149. hidden_states = hidden_states.view(-1, h) # 调整隐藏状态的形状
  150. logits = F.linear(hidden_states, self.weight, None) # 计算 logits
  151. if self.scoring_func == 'softmax':
  152. scores = logits.softmax(dim=-1) # 计算 softmax 评分
  153. else:
  154. raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
  155. topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False) # 选择 top-k 专家
  156. if self.top_k > 1 and self.norm_topk_prob:
  157. denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20 # 计算归一化分母
  158. topk_weight = topk_weight / denominator # 归一化 top-k 概率
  159. if self.training and self.alpha > 0.0:
  160. scores_for_aux = scores
  161. aux_topk = self.top_k
  162. topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
  163. if self.seq_aux:
  164. scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
  165. ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
  166. ce.scatter_add_(1, topk_idx_for_aux_loss,
  167. torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)).div_(
  168. seq_len * aux_topk / self.n_routed_experts)
  169. aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
  170. else:
  171. mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
  172. ce = mask_ce.float().mean(0)
  173. Pi = scores_for_aux.mean(0)
  174. fi = ce * self.n_routed_experts
  175. aux_loss = (Pi * fi).sum() * self.alpha
  176. else:
  177. aux_loss = None
  178. return topk_idx, topk_weight, aux_loss # 返回 top-k 专家索引、权重和辅助损失
  179. # 定义 MOEFeedForward 类,实现专家混合(MoE)的前馈神经网络
  180. class MOEFeedForward(nn.Module):
  181. def __init__(self, config: LMConfig):
  182. super().__init__()
  183. self.config = config
  184. self.experts = nn.ModuleList([
  185. FeedForward(
  186. dim=config.dim,
  187. hidden_dim=config.hidden_dim,
  188. multiple_of=config.multiple_of,
  189. dropout=config.dropout,
  190. )
  191. for _ in range(config.n_routed_experts)
  192. ]) # 初始化专家列表
  193. self.gate = MoEGate(config) # 初始化门控机制
  194. if config.n_shared_experts is not None:
  195. self.shared_experts = FeedForward(
  196. dim=config.dim,
  197. hidden_dim=config.hidden_dim,
  198. multiple_of=config.multiple_of,
  199. dropout=config.dropout,
  200. ) # 初始化共享专家
  201. def forward(self, x):
  202. identity = x
  203. orig_shape = x.shape
  204. bsz, seq_len, _ = x.shape
  205. # 使用门控机制选择专家
  206. topk_idx, topk_weight, aux_loss = self.gate(x)
  207. x = x.view(-1, x.shape[-1])
  208. flat_topk_idx = topk_idx.view(-1)
  209. if self.training:
  210. # 训练模式下,重复输入数据
  211. x = x.repeat_interleave(self.config.num_experts_per_tok, dim=0)
  212. y = torch.empty_like(x, dtype=torch.float16)
  213. for i, expert in enumerate(self.experts):
  214. y[flat_topk_idx == i] = expert(x[flat_topk_idx == i])
  215. y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
  216. y = y.view(*orig_shape)
  217. else:
  218. # 推理模式下,只选择最优专家
  219. y = self.moe_infer(x, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
  220. if self.config.n_shared_experts is not None:
  221. y = y + self.shared_experts(identity)
  222. return y
  223. @torch.no_grad()
  224. def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
  225. expert_cache = torch.zeros_like(x)
  226. idxs = flat_expert_indices.argsort()
  227. tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
  228. token_idxs = idxs // self.config.num_experts_per_tok
  229. # 例如当tokens_per_expert=[6, 15, 20, 26, 33, 38, 46, 52]
  230. # 当token_idxs=[3, 7, 19, 21, 24, 25, 4, 5, 6, 10, 11, 12...]
  231. # 意味着当token_idxs[:6] -> [3, 7, 19, 21, 24, 25, 4]位置的token都由专家0处理,token_idxs[6:15]位置的token都由专家1处理......
  232. for i, end_idx in enumerate(tokens_per_expert):
  233. start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
  234. if start_idx == end_idx:
  235. continue
  236. expert = self.experts[i]
  237. exp_token_idx = token_idxs[start_idx:end_idx]
  238. expert_tokens = x[exp_token_idx]
  239. expert_out = expert(expert_tokens)
  240. expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
  241. # 使用 scatter_add_ 进行 sum 操作
  242. expert_cache.scatter_add_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out)
  243. return expert_cache
  244. # 定义 TransformerBlock 类,实现 Transformer 的一个块,包括自注意力和前馈神经网络
  245. class TransformerBlock(nn.Module):
  246. def __init__(self, layer_id: int, args: LMConfig):
  247. super().__init__()
  248. self.n_heads = args.n_heads
  249. self.dim = args.dim
  250. self.head_dim = args.dim // args.n_heads
  251. self.attention = Attention(args) # 初始化自注意力机制
  252. self.layer_id = layer_id
  253. self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps) # 初始化注意力归一化
  254. self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps) # 初始化前馈神经网络归一化
  255. if args.use_moe:
  256. self.feed_forward = MOEFeedForward(args) # 初始化专家混合前馈神经网络
  257. else:
  258. self.feed_forward = FeedForward(
  259. dim=args.dim,
  260. hidden_dim=args.hidden_dim,
  261. multiple_of=args.multiple_of,
  262. dropout=args.dropout,
  263. ) # 初始化前馈神经网络
  264. def forward(self, x, pos_cis, use_kv_cache=False):
  265. h = x + self.attention(self.attention_norm(x), pos_cis, use_kv_cache) # 计算自注意力
  266. out = h + self.feed_forward(self.ffn_norm(h)) # 计算前馈神经网络
  267. return out # 返回输出
  268. # 定义 Transformer 类,实现整个 Transformer 模型
  269. class Transformer(PreTrainedModel):
  270. config_class = LMConfig
  271. last_loss: Optional[torch.Tensor]
  272. def __init__(self, params: LMConfig = None):
  273. super().__init__(params)
  274. if not params:
  275. params = LMConfig()
  276. self.params = params
  277. self.vocab_size = params.vocab_size
  278. self.n_layers = params.n_layers
  279. class Transformer(PreTrainedModel):
  280. config_class = LMConfig
  281. last_loss: Optional[torch.Tensor]
  282. def __init__(self, params: LMConfig = None):
  283. super().__init__(params)
  284. if not params:
  285. params = LMConfig()
  286. self.params = params
  287. self.vocab_size = params.vocab_size
  288. self.n_layers = params.n_layers
  289. self.tok_embeddings = nn.Embedding(params.vocab_size, params.dim) # 初始化词嵌入层
  290. self.dropout = nn.Dropout(params.dropout) # 初始化 dropout 层
  291. self.layers = torch.nn.ModuleList() # 初始化 Transformer 块列表
  292. for layer_id in range(self.n_layers):
  293. self.layers.append(TransformerBlock(layer_id, params)) # 添加 Transformer 块
  294. self.norm = RMSNorm(params.dim, eps=params.norm_eps) # 初始化归一化层
  295. self.output = nn.Linear(params.dim, params.vocab_size, bias=False) # 初始化输出层
  296. self.tok_embeddings.weight = self.output.weight # 共享词嵌入和输出层的权重
  297. pos_cis = precompute_pos_cis(self.params.dim // self.params.n_heads, self.params.max_seq_len) # 预计算位置编码
  298. self.register_buffer("pos_cis", pos_cis, persistent=False) # 注册位置编码缓冲区
  299. self.apply(self._init_weights) # 初始化模型权重
  300. for pn, p in self.named_parameters():
  301. if pn.endswith('w3.weight') or pn.endswith('wo.weight'):
  302. torch.nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * params.n_layers)) # 对特定权重进行初始化
  303. self.last_loss = None # 初始化最后一个损失
  304. self.OUT = CausalLMOutputWithPast() # 初始化输出对象
  305. def _init_weights(self, module):
  306. if isinstance(module, nn.Linear):
  307. torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) # 初始化线性层的权重
  308. if module.bias is not None:
  309. torch.nn.init.zeros_(module.bias) # 初始化线性层的偏置
  310. elif isinstance(module, nn.Embedding):
  311. torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) # 初始化嵌入层的权重
  312. def forward(self, tokens: Optional[torch.Tensor] = None, targets: Optional[torch.Tensor] = None,
  313. use_kv_cache=False, **keyargs):
  314. if 'input_ids' in keyargs:
  315. tokens = keyargs['input_ids'] # 如果传入了 input_ids,则使用 input_ids
  316. if 'attention_mask' in keyargs:
  317. targets = keyargs['attention_mask'] # 如果传入了 attention_mask,则使用 attention_mask
  318. _bsz, seqlen = tokens.shape # 获取批量大小和序列长度
  319. h = self.tok_embeddings(tokens) # 获取词嵌入
  320. h = self.dropout(h) # 应用 dropout
  321. pos_cis = self.pos_cis[:seqlen] # 获取对应序列长度的位置编码
  322. for idx, layer in enumerate(self.layers):
  323. h = layer(h, pos_cis, use_kv_cache) # 逐层应用 Transformer 块
  324. h = self.norm(h) # 应用归一化
  325. if targets is not None:
  326. logits = self.output(h) # 计算 logits
  327. self.last_loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1) # 计算交叉熵损失
  328. else:
  329. logits = self.output(h[:, [-1], :]) # 计算最后一个 token 的 logits
  330. self.last_loss = None # 没有目标时,损失为 None
  331. self.OUT.__setitem__('logits', logits) # 设置输出对象的 logits
  332. self.OUT.__setitem__('last_loss', self.last_loss) # 设置输出对象的 last_loss
  333. return self.OUT # 返回输出对象
  334. @torch.inference_mode() # 推理模式
  335. def generate(self, idx, eos, max_new_tokens, temperature=0.7, top_k=None, stream=True, repetition_penalty=1.,
  336. use_kv_cache=True):
  337. index = idx.shape[1] # 获取当前序列长度
  338. while idx.shape[1] < max_new_tokens - 1: # 当生成的 token 数量小于最大数量时
  339. inference_res = self(idx, use_kv_cache=use_kv_cache) # 进行前向传播
  340. logits = inference_res.logits # 获取 logits
  341. logits = logits[:, -1, :] # 获取最后一个 token 的 logits
  342. for token in set(idx.tolist()[0]): # 对重复 token 进行惩罚
  343. logits[:, token] /= repetition_penalty
  344. if temperature == 0.0: # 如果温度为 0,直接选择概率最高的 token
  345. _, idx_next = torch.topk(logits, k=1, dim=-1)
  346. else:
  347. logits = logits / temperature # 调整 logits
  348. if top_k is not None: # 如果设置了 top-k 采样
  349. v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
  350. logits[logits < v[:, [-1]]] = -float('Inf') # 将小于 top-k 的 logits 设为负无穷
  351. probs = F.softmax(logits, dim=-1) # 计算概率
  352. idx_next = torch.multinomial(probs, num_samples=1, generator=None) # 采样下一个 token
  353. if idx_next == eos: # 如果生成的 token 是结束符,停止生成
  354. break
  355. idx = torch.cat((idx, idx_next), dim=1) # 将生成的 token 添加到序列中
  356. if stream: # 如果需要流式输出
  357. yield idx[:, index:] # 返回生成的 token
  358. if not stream: # 如果不需要流式输出
  359. yield idx[:, index:] # 返回生成的 token
  360. @torch.inference_mode() # 推理模式
  361. def eval_answer(self, idx):
  362. idx_cond = idx if idx.size(1) <= self.params.max_seq_len else idx[:, -self.params.max_seq_len:] # 截取序列
  363. inference_res = self(idx_cond) # 进行前向传播
  364. logits = inference_res.logits # 获取 logits
  365. logits = logits[:, -1, :] # 获取最后一个 token 的 logits
  366. return logits # 返回 logits