model.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. class RMSNorm(torch.nn.Module):
  13. def __init__(self, dim: int, eps: float):
  14. super().__init__()
  15. self.eps = eps
  16. self.weight = nn.Parameter(torch.ones(dim))
  17. def _norm(self, x):
  18. return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
  19. def forward(self, x):
  20. output = self._norm(x.float()).type_as(x)
  21. return output * self.weight
  22. def precompute_pos_cis(dim: int, end: int, theta: float = 10000.0):
  23. freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
  24. t = torch.arange(end, device=freqs.device) # type: ignore
  25. freqs = torch.outer(t, freqs).float() # type: ignore
  26. pos_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
  27. return pos_cis
  28. def apply_rotary_emb(xq, xk, pos_cis):
  29. def unite_shape(pos_cis, x):
  30. ndim = x.ndim
  31. assert 0 <= 1 < ndim
  32. assert pos_cis.shape == (x.shape[1], x.shape[-1])
  33. shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
  34. return pos_cis.view(*shape)
  35. xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
  36. xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
  37. pos_cis = unite_shape(pos_cis, xq_)
  38. xq_out = torch.view_as_real(xq_ * pos_cis).flatten(3)
  39. xk_out = torch.view_as_real(xk_ * pos_cis).flatten(3)
  40. return xq_out.type_as(xq), xk_out.type_as(xk)
  41. def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
  42. """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
  43. bs, slen, n_kv_heads, head_dim = x.shape
  44. if n_rep == 1:
  45. return x
  46. return (
  47. x[:, :, :, None, :]
  48. .expand(bs, slen, n_kv_heads, n_rep, head_dim)
  49. .reshape(bs, slen, n_kv_heads * n_rep, head_dim)
  50. )
  51. class Attention(nn.Module):
  52. def __init__(self, args: LMConfig):
  53. super().__init__()
  54. self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
  55. assert args.n_heads % self.n_kv_heads == 0
  56. model_parallel_size = 1
  57. self.n_local_heads = args.n_heads // model_parallel_size
  58. self.n_local_kv_heads = self.n_kv_heads // model_parallel_size
  59. self.n_rep = self.n_local_heads // self.n_local_kv_heads
  60. self.head_dim = args.dim // args.n_heads
  61. self.wq = nn.Linear(args.dim, args.n_heads * self.head_dim, bias=False)
  62. self.wk = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
  63. self.wv = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
  64. self.wo = nn.Linear(args.n_heads * self.head_dim, args.dim, bias=False)
  65. self.attn_dropout = nn.Dropout(args.dropout)
  66. self.resid_dropout = nn.Dropout(args.dropout)
  67. self.dropout = args.dropout
  68. # use flash attention or a manual implementation?
  69. self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn
  70. if not self.flash:
  71. # print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
  72. mask = torch.full((1, 1, args.max_seq_len, args.max_seq_len), float("-inf"))
  73. mask = torch.triu(mask, diagonal=1)
  74. self.register_buffer("mask", mask)
  75. def forward(
  76. self,
  77. x: torch.Tensor,
  78. pos_cis: torch.Tensor,
  79. use_kv_cache: bool = False,
  80. past_kv: Tuple[torch.Tensor] = None
  81. ):
  82. bsz, seqlen, _ = x.shape
  83. # QKV
  84. # inference
  85. if use_kv_cache:
  86. # 只计算最后一个token的Q
  87. current_token = x[:, -1:, :]
  88. if not past_kv:
  89. xq = self.wq(x)
  90. xk, xv = self.wk(x), self.wv(x)
  91. else:
  92. past_key, past_value = past_kv
  93. xq = torch.cat((torch.zeros_like(x[:, :-1, :]), self.wq(current_token)), dim=1)
  94. xk = torch.cat((past_key, self.wk(current_token)), dim=1)
  95. xv = torch.cat((past_value, self.wv(current_token)), dim=1)
  96. past_kv = (xk, xv)
  97. else:
  98. xq = self.wq(x)
  99. xk, xv = self.wk(x), self.wv(x)
  100. xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
  101. xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
  102. xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
  103. # RoPE relative positional embeddings
  104. xq, xk = apply_rotary_emb(xq, xk, pos_cis)
  105. # grouped multiquery attention: expand out keys and values
  106. xk = repeat_kv(xk, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
  107. xv = repeat_kv(xv, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
  108. # make heads into a batch dimension
  109. xq = xq.transpose(1, 2) # (bs, n_local_heads, seqlen, head_dim)
  110. xk = xk.transpose(1, 2)
  111. xv = xv.transpose(1, 2)
  112. # flash implementation
  113. if self.flash:
  114. output = torch.nn.functional.scaled_dot_product_attention(xq, xk, xv, attn_mask=None,
  115. dropout_p=self.dropout if self.training else 0.0,
  116. is_causal=True)
  117. else:
  118. # manual implementation
  119. scores = torch.matmul(xq, xk.transpose(2, 3)) / math.sqrt(self.head_dim)
  120. assert hasattr(self, 'mask')
  121. scores = scores + self.mask[:, :, :seqlen, :seqlen] # (bs, n_local_heads, seqlen, cache_len + seqlen)
  122. scores = F.softmax(scores.float(), dim=-1).type_as(xq)
  123. scores = self.attn_dropout(scores)
  124. output = torch.matmul(scores, xv) # (bs, n_local_heads, seqlen, head_dim)
  125. # restore time as batch dimension and concat heads
  126. output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
  127. # final projection into the residual stream
  128. output = self.wo(output)
  129. output = self.resid_dropout(output)
  130. return output, past_kv
  131. class FeedForward(nn.Module):
  132. def __init__(self, dim: int, hidden_dim: int, multiple_of: int, dropout: float):
  133. super().__init__()
  134. if hidden_dim is None:
  135. hidden_dim = 4 * dim
  136. hidden_dim = int(2 * hidden_dim / 3)
  137. hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
  138. self.w1 = nn.Linear(dim, hidden_dim, bias=False)
  139. self.w2 = nn.Linear(hidden_dim, dim, bias=False)
  140. self.w3 = nn.Linear(dim, hidden_dim, bias=False)
  141. self.dropout = nn.Dropout(dropout)
  142. def forward(self, x):
  143. return self.dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
  144. class MoEGate(nn.Module):
  145. def __init__(self, config: LMConfig):
  146. super().__init__()
  147. self.config = config
  148. self.top_k = config.num_experts_per_tok
  149. self.n_routed_experts = config.n_routed_experts
  150. self.scoring_func = config.scoring_func
  151. self.alpha = config.aux_loss_alpha
  152. self.seq_aux = config.seq_aux
  153. # topk selection algorithm
  154. self.norm_topk_prob = config.norm_topk_prob
  155. self.gating_dim = config.dim
  156. self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
  157. self.reset_parameters()
  158. def reset_parameters(self) -> None:
  159. import torch.nn.init as init
  160. init.kaiming_uniform_(self.weight, a=math.sqrt(5))
  161. def forward(self, hidden_states):
  162. bsz, seq_len, h = hidden_states.shape
  163. ### compute gating score
  164. hidden_states = hidden_states.view(-1, h)
  165. logits = F.linear(hidden_states, self.weight, None)
  166. if self.scoring_func == 'softmax':
  167. scores = logits.softmax(dim=-1)
  168. else:
  169. raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
  170. ### select top-k experts
  171. topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
  172. ### norm gate to sum 1
  173. if self.top_k > 1 and self.norm_topk_prob:
  174. denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
  175. topk_weight = topk_weight / denominator
  176. ### expert-level computation auxiliary loss
  177. if self.training and self.alpha > 0.0:
  178. scores_for_aux = scores
  179. aux_topk = self.top_k
  180. # always compute aux loss based on the naive greedy topk method
  181. topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
  182. if self.seq_aux:
  183. scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
  184. ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
  185. ce.scatter_add_(1, topk_idx_for_aux_loss,
  186. torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)).div_(
  187. seq_len * aux_topk / self.n_routed_experts)
  188. aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
  189. else:
  190. mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
  191. ce = mask_ce.float().mean(0)
  192. Pi = scores_for_aux.mean(0)
  193. fi = ce * self.n_routed_experts
  194. aux_loss = (Pi * fi).sum() * self.alpha
  195. else:
  196. aux_loss = None
  197. return topk_idx, topk_weight, aux_loss
  198. class MOEFeedForward(nn.Module):
  199. def __init__(self, config: LMConfig):
  200. super().__init__()
  201. self.config = config
  202. self.experts = nn.ModuleList([
  203. FeedForward(
  204. dim=config.dim,
  205. hidden_dim=config.hidden_dim,
  206. multiple_of=config.multiple_of,
  207. dropout=config.dropout,
  208. )
  209. for _ in range(config.n_routed_experts)
  210. ])
  211. self.gate = MoEGate(config)
  212. if config.n_shared_experts is not None:
  213. self.shared_experts = FeedForward(
  214. dim=config.dim,
  215. hidden_dim=config.hidden_dim,
  216. multiple_of=config.multiple_of,
  217. dropout=config.dropout,
  218. )
  219. def forward(self, x):
  220. identity = x
  221. orig_shape = x.shape
  222. bsz, seq_len, _ = x.shape
  223. # 使用门控机制选择专家
  224. topk_idx, topk_weight, aux_loss = self.gate(x)
  225. x = x.view(-1, x.shape[-1])
  226. flat_topk_idx = topk_idx.view(-1)
  227. if self.training:
  228. # 训练模式下,重复输入数据
  229. x = x.repeat_interleave(self.config.num_experts_per_tok, dim=0)
  230. y = torch.empty_like(x, dtype=torch.float16)
  231. for i, expert in enumerate(self.experts):
  232. y[flat_topk_idx == i] = expert(x[flat_topk_idx == i])
  233. y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
  234. y = y.view(*orig_shape)
  235. else:
  236. # 推理模式下,只选择最优专家
  237. y = self.moe_infer(x, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
  238. if self.config.n_shared_experts is not None:
  239. y = y + self.shared_experts(identity)
  240. return y
  241. @torch.no_grad()
  242. def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
  243. expert_cache = torch.zeros_like(x)
  244. idxs = flat_expert_indices.argsort()
  245. tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
  246. token_idxs = idxs // self.config.num_experts_per_tok
  247. # 例如当tokens_per_expert=[6, 15, 20, 26, 33, 38, 46, 52]
  248. # 当token_idxs=[3, 7, 19, 21, 24, 25, 4, 5, 6, 10, 11, 12...]
  249. # 意味着当token_idxs[:6] -> [3, 7, 19, 21, 24, 25, 4]位置的token都由专家0处理,token_idxs[6:15]位置的token都由专家1处理......
  250. for i, end_idx in enumerate(tokens_per_expert):
  251. start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
  252. if start_idx == end_idx:
  253. continue
  254. expert = self.experts[i]
  255. exp_token_idx = token_idxs[start_idx:end_idx]
  256. expert_tokens = x[exp_token_idx]
  257. expert_out = expert(expert_tokens)
  258. expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
  259. # 使用 scatter_add_ 进行 sum 操作
  260. expert_cache.scatter_add_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out)
  261. return expert_cache
  262. class TransformerBlock(nn.Module):
  263. def __init__(self, layer_id: int, args: LMConfig):
  264. super().__init__()
  265. self.n_heads = args.n_heads
  266. self.dim = args.dim
  267. self.head_dim = args.dim // args.n_heads
  268. self.attention = Attention(args)
  269. self.layer_id = layer_id
  270. self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
  271. self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)
  272. if args.use_moe:
  273. self.feed_forward = MOEFeedForward(args)
  274. else:
  275. self.feed_forward = FeedForward(
  276. dim=args.dim,
  277. hidden_dim=args.hidden_dim,
  278. multiple_of=args.multiple_of,
  279. dropout=args.dropout,
  280. )
  281. def forward(self, x, pos_cis, use_kv_cache=False, past_kv: Tuple[torch.Tensor] = None):
  282. attn_res, past_kv = self.attention(self.attention_norm(x), pos_cis, use_kv_cache, past_kv)
  283. h = x + attn_res
  284. out = h + self.feed_forward(self.ffn_norm(h))
  285. return out, past_kv
  286. class Transformer(PreTrainedModel):
  287. config_class = LMConfig
  288. last_loss: Optional[torch.Tensor]
  289. def __init__(self, params: LMConfig = None):
  290. super().__init__(params)
  291. if not params:
  292. params = LMConfig()
  293. self.params = params
  294. self.vocab_size = params.vocab_size
  295. self.n_layers = params.n_layers
  296. self.tok_embeddings = nn.Embedding(params.vocab_size, params.dim)
  297. self.dropout = nn.Dropout(params.dropout)
  298. self.layers = torch.nn.ModuleList()
  299. for layer_id in range(self.n_layers):
  300. self.layers.append(TransformerBlock(layer_id, params))
  301. self.norm = RMSNorm(params.dim, eps=params.norm_eps)
  302. self.output = nn.Linear(params.dim, params.vocab_size, bias=False)
  303. # share the unembedding parameters with the embedding parameters
  304. self.tok_embeddings.weight = self.output.weight # https://paperswithcode.com/method/weight-tying
  305. # some useful precompute for the RoPE relative positional embeddings
  306. pos_cis = precompute_pos_cis(self.params.dim // self.params.n_heads, self.params.max_seq_len)
  307. self.register_buffer("pos_cis", pos_cis, persistent=False)
  308. # init all weights
  309. self.apply(self._init_weights)
  310. # apply special scaled init to the residual projections, per GPT-2 paper
  311. for pn, p in self.named_parameters():
  312. if pn.endswith('w3.weight') or pn.endswith('wo.weight'):
  313. torch.nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * params.n_layers))
  314. # Initialize attribute for the loss of the last forward call. This will be set if the forward is called with a targets tensor.
  315. self.last_loss = None
  316. self.OUT = CausalLMOutputWithPast()
  317. def _init_weights(self, module):
  318. if isinstance(module, nn.Linear):
  319. torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
  320. if module.bias is not None:
  321. torch.nn.init.zeros_(module.bias)
  322. elif isinstance(module, nn.Embedding):
  323. torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
  324. def forward(self, tokens: Optional[torch.Tensor] = None,
  325. targets: Optional[torch.Tensor] = None,
  326. use_kv_cache=False, past_kvs=None, **keyargs):
  327. if past_kvs is None:
  328. past_kvs = [None for _ in range(self.n_layers)]
  329. if 'input_ids' in keyargs:
  330. tokens = keyargs['input_ids']
  331. if 'attention_mask' in keyargs:
  332. targets = keyargs['attention_mask']
  333. _bsz, seqlen = tokens.shape
  334. h = self.tok_embeddings(tokens)
  335. h = self.dropout(h)
  336. pos_cis = self.pos_cis[:seqlen]
  337. for idx, layer in enumerate(self.layers):
  338. h, past_kvs[idx] = layer(h, pos_cis, use_kv_cache, past_kvs[idx])
  339. h = self.norm(h)
  340. if targets is not None:
  341. # if we are given some desired targets also calculate the loss
  342. logits = self.output(h)
  343. self.last_loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
  344. else:
  345. # inference-time mini-optimization: only forward the output on the very last position
  346. logits = self.output(h[:, [-1], :]) # note: using list [-1] to preserve the time dim
  347. self.last_loss = None
  348. self.OUT.__setitem__('logits', logits)
  349. self.OUT.__setitem__('last_loss', self.last_loss)
  350. if use_kv_cache:
  351. return self.OUT, past_kvs
  352. return self.OUT
  353. @torch.inference_mode()
  354. def generate(self, idx, eos, max_new_tokens, temperature=0.7, top_k=None, stream=True, repetition_penalty=1.):
  355. index = idx.shape[1]
  356. use_kv_cache = True
  357. past_kvs = [None for _ in range(self.n_layers)]
  358. while idx.shape[1] < max_new_tokens - 1:
  359. # if the sequence context is growing too long we must crop it at block_size
  360. idx_cond = idx # if idx.size(1) <= self.params.max_seq_len else idx[:, -self.params.max_seq_len:]
  361. # forward the model to get the logits for the index in the sequence
  362. inference_res = self(idx_cond, use_kv_cache=use_kv_cache, past_kvs=past_kvs)
  363. if use_kv_cache:
  364. logits, past_kvs = inference_res[0].logits, inference_res[1]
  365. else:
  366. logits = inference_res.logits
  367. logits = logits[:, -1, :] # crop to just the final time step
  368. # Apply repetition penalty
  369. for token in set(idx.tolist()[0]):
  370. logits[:, token] /= repetition_penalty
  371. if temperature == 0.0:
  372. # "sample" the single most likely index
  373. __, idx_next = torch.topk(logits, k=1, dim=-1)
  374. else:
  375. # pluck the logits at the final step and scale by desired temperature
  376. logits = logits / temperature
  377. # optionally crop the logits to only the top k options
  378. if top_k is not None:
  379. v, __ = torch.topk(logits, min(top_k, logits.size(-1)))
  380. logits[logits < v[:, [-1]]] = -float('Inf')
  381. # apply softmax to convert logits to (normalized) probabilities
  382. probs = F.softmax(logits, dim=-1)
  383. idx_next = torch.multinomial(probs, num_samples=1, generator=None)
  384. # append sampled index to the running sequence and continue
  385. if idx_next == eos:
  386. break
  387. idx = torch.cat((idx, idx_next), dim=1)
  388. if stream:
  389. yield idx[:, index:]
  390. if not stream:
  391. yield idx[:, index:]
  392. @torch.inference_mode()
  393. def eval_answer(self, idx):
  394. # if the sequence context is growing too long we must crop it at block_size
  395. idx_cond = idx if idx.size(1) <= self.params.max_seq_len else idx[:, -self.params.max_seq_len:]
  396. # forward the model to get the logits for the index in the sequence
  397. past_kvs = [None for _ in range(self.n_layers)]
  398. inference_res = self(idx_cond, use_kv_cache=False, past_kvs=past_kvs)
  399. logits = inference_res.logits
  400. logits = logits[:, -1, :]
  401. return logits
  402. def export(self, filepath='model.bin'):
  403. """export the model weights in fp32 into .bin file to be read from C"""
  404. f = open(filepath, 'wb')
  405. def serialize(t):
  406. d = t.detach().cpu().view(-1).numpy().astype(np.float32)
  407. b = struct.pack(f'{len(d)}f', *d)
  408. f.write(b)
  409. # first write out the header
  410. hidden_dim = self.layers[0].feed_forward.w1.weight.shape[0]
  411. p = self.params
  412. n_kv_heads = p.n_heads if p.n_kv_heads is None else p.n_kv_heads
  413. header = struct.pack('iiiiiii', p.dim, hidden_dim, p.n_layers, p.n_heads,
  414. n_kv_heads, p.vocab_size, p.max_seq_len)
  415. f.write(header)
  416. # next write out the embedding weights
  417. serialize(self.tok_embeddings.weight)
  418. # now all the layers
  419. # attention weights
  420. for layer in self.layers:
  421. serialize(layer.attention_norm.weight)
  422. for layer in self.layers:
  423. serialize(layer.attention.wq.weight)
  424. for layer in self.layers:
  425. serialize(layer.attention.wk.weight)
  426. for layer in self.layers:
  427. serialize(layer.attention.wv.weight)
  428. for layer in self.layers:
  429. serialize(layer.attention.wo.weight)
  430. # ffn weights
  431. for layer in self.layers:
  432. serialize(layer.ffn_norm.weight)
  433. for layer in self.layers:
  434. serialize(layer.feed_forward.w1.weight)
  435. for layer in self.layers:
  436. serialize(layer.feed_forward.w2.weight)
  437. for layer in self.layers:
  438. serialize(layer.feed_forward.w3.weight)
  439. # final rmsnorm
  440. serialize(self.norm.weight)
  441. # note: no need to write final classifier weights due to weight sharing
  442. # pos_cis
  443. serialize(self.freqs_cos[:p.max_seq_len])
  444. serialize(self.freqs_sin[:p.max_seq_len])
  445. # write to binary file
  446. f.close()
  447. print(f"wrote {filepath}")