modeling_chatglm.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  1. """ PyTorch ChatGLM model. """
  2. import json
  3. import math
  4. import copy
  5. import warnings
  6. import re
  7. import sys
  8. import torch
  9. import torch.utils.checkpoint
  10. import torch.nn.functional as F
  11. from torch import nn
  12. from torch.nn import CrossEntropyLoss, LayerNorm, MSELoss, BCEWithLogitsLoss
  13. from torch.nn.utils import skip_init
  14. from typing import Optional, Tuple, Union, List, Callable, Dict, Any
  15. from copy import deepcopy
  16. from transformers.modeling_outputs import (
  17. BaseModelOutputWithPast,
  18. CausalLMOutputWithPast,
  19. SequenceClassifierOutputWithPast,
  20. )
  21. from transformers.modeling_utils import PreTrainedModel
  22. from transformers.utils import logging
  23. from transformers.generation.logits_process import LogitsProcessor
  24. from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
  25. from configuration_chatglm import ChatGLMConfig
  26. # flags required to enable jit fusion kernels
  27. if sys.platform != 'darwin':
  28. torch._C._jit_set_profiling_mode(False)
  29. torch._C._jit_set_profiling_executor(False)
  30. torch._C._jit_override_can_fuse_on_cpu(True)
  31. torch._C._jit_override_can_fuse_on_gpu(True)
  32. logger = logging.get_logger(__name__)
  33. _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM"
  34. _CONFIG_FOR_DOC = "ChatGLMConfig"
  35. def default_init(cls, *args, **kwargs):
  36. return cls(*args, **kwargs)
  37. class InvalidScoreLogitsProcessor(LogitsProcessor):
  38. def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
  39. if torch.isnan(scores).any() or torch.isinf(scores).any():
  40. scores.zero_()
  41. scores[..., 198] = 5e4
  42. return scores
  43. def split_tensor_along_last_dim(
  44. tensor: torch.Tensor,
  45. num_partitions: int,
  46. contiguous_split_chunks: bool = False,
  47. ) -> List[torch.Tensor]:
  48. """Split a tensor along its last dimension.
  49. Arguments:
  50. tensor: input tensor.
  51. num_partitions: number of partitions to split the tensor
  52. contiguous_split_chunks: If True, make each chunk contiguous
  53. in memory.
  54. Returns:
  55. A list of Tensors
  56. """
  57. # Get the size and dimension.
  58. last_dim = tensor.dim() - 1
  59. last_dim_size = tensor.size()[last_dim] // num_partitions
  60. # Split.
  61. tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
  62. # Note: torch.split does not create contiguous tensors by default.
  63. if contiguous_split_chunks:
  64. return tuple(chunk.contiguous() for chunk in tensor_list)
  65. return tensor_list
  66. class RotaryEmbedding(nn.Module):
  67. def __init__(self, dim, rope_ratio=1, original_impl=False, device=None, dtype=None):
  68. super().__init__()
  69. inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device).to(dtype=dtype) / dim))
  70. self.register_buffer("inv_freq", inv_freq)
  71. self.dim = dim
  72. self.original_impl = original_impl
  73. self.rope_ratio = rope_ratio
  74. def forward_impl(
  75. self, seq_len: int, n_elem: int, dtype: torch.dtype, device: torch.device, base: int = 10000
  76. ):
  77. """Enhanced Transformer with Rotary Position Embedding.
  78. Derived from: https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/
  79. transformers/rope/__init__.py. MIT License:
  80. https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/license.
  81. """
  82. # $\Theta = {\theta_i = 10000^{\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
  83. base = base * self.rope_ratio
  84. theta = 1.0 / (base ** (torch.arange(0, n_elem, 2, dtype=torch.float, device=device) / n_elem))
  85. # Create position indexes `[0, 1, ..., seq_len - 1]`
  86. seq_idx = torch.arange(seq_len, dtype=torch.float, device=device)
  87. # Calculate the product of position index and $\theta_i$
  88. idx_theta = torch.outer(seq_idx, theta).float()
  89. cache = torch.stack([torch.cos(idx_theta), torch.sin(idx_theta)], dim=-1)
  90. # this is to mimic the behaviour of complex32, else we will get different results
  91. if dtype in (torch.float16, torch.bfloat16, torch.int8):
  92. cache = cache.bfloat16() if dtype == torch.bfloat16 else cache.half()
  93. return cache
  94. def forward(self, max_seq_len, offset=0):
  95. return self.forward_impl(
  96. max_seq_len, self.dim, dtype=self.inv_freq.dtype, device=self.inv_freq.device
  97. )
  98. @torch.jit.script
  99. def apply_rotary_pos_emb(x: torch.Tensor, rope_cache: torch.Tensor) -> torch.Tensor:
  100. # x: [b, np, sq, hn]
  101. b, np, sq, hn = x.size(0), x.size(1), x.size(2), x.size(3)
  102. rot_dim = rope_cache.shape[-2] * 2
  103. x, x_pass = x[..., :rot_dim], x[..., rot_dim:]
  104. # truncate to support variable sizes
  105. rope_cache = rope_cache[:, :sq]
  106. xshaped = x.reshape(b, np, sq, rot_dim // 2, 2)
  107. rope_cache = rope_cache.view(-1, 1, sq, xshaped.size(3), 2)
  108. x_out2 = torch.stack(
  109. [
  110. xshaped[..., 0] * rope_cache[..., 0] - xshaped[..., 1] * rope_cache[..., 1],
  111. xshaped[..., 1] * rope_cache[..., 0] + xshaped[..., 0] * rope_cache[..., 1],
  112. ],
  113. -1,
  114. )
  115. x_out2 = x_out2.flatten(3)
  116. return torch.cat((x_out2, x_pass), dim=-1)
  117. class RMSNorm(torch.nn.Module):
  118. def __init__(self, normalized_shape, eps=1e-5, device=None, dtype=None, **kwargs):
  119. super().__init__()
  120. self.weight = torch.nn.Parameter(torch.empty(normalized_shape, device=device, dtype=dtype))
  121. self.eps = eps
  122. def forward(self, hidden_states: torch.Tensor):
  123. input_dtype = hidden_states.dtype
  124. variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
  125. hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
  126. return (self.weight * hidden_states).to(input_dtype)
  127. class CoreAttention(torch.nn.Module):
  128. def __init__(self, config: ChatGLMConfig, layer_number):
  129. super(CoreAttention, self).__init__()
  130. self.apply_query_key_layer_scaling = config.apply_query_key_layer_scaling
  131. self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
  132. if self.apply_query_key_layer_scaling:
  133. self.attention_softmax_in_fp32 = True
  134. self.layer_number = max(1, layer_number)
  135. projection_size = config.kv_channels * config.num_attention_heads
  136. # Per attention head and per partition values.
  137. self.hidden_size_per_partition = projection_size
  138. self.hidden_size_per_attention_head = projection_size // config.num_attention_heads
  139. self.num_attention_heads_per_partition = config.num_attention_heads
  140. coeff = None
  141. self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
  142. if self.apply_query_key_layer_scaling:
  143. coeff = self.layer_number
  144. self.norm_factor *= coeff
  145. self.coeff = coeff
  146. self.attention_dropout = torch.nn.Dropout(config.attention_dropout)
  147. def forward(self, query_layer, key_layer, value_layer, attention_mask):
  148. pytorch_major_version = int(torch.__version__.split('.')[0])
  149. if pytorch_major_version >= 2:
  150. if attention_mask is None and query_layer.shape[2] == key_layer.shape[2]:
  151. context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
  152. is_causal=True)
  153. else:
  154. if attention_mask is not None:
  155. attention_mask = ~attention_mask
  156. context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
  157. attention_mask)
  158. context_layer = context_layer.transpose(1, 2).contiguous()
  159. new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
  160. context_layer = context_layer.reshape(*new_context_layer_shape)
  161. else:
  162. # Raw attention scores
  163. # [b, np, sq, sk]
  164. output_size = (query_layer.size(0), query_layer.size(1), query_layer.size(2), key_layer.size(2))
  165. # [b, np, sq, hn] -> [b * np, sq, hn]
  166. query_layer = query_layer.view(output_size[0] * output_size[1], output_size[2], -1)
  167. # [b, np, sk, hn] -> [b * np, sk, hn]
  168. key_layer = key_layer.view(output_size[0] * output_size[1], output_size[3], -1)
  169. # preallocting input tensor: [b * np, sq, sk]
  170. matmul_input_buffer = torch.empty(
  171. output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype,
  172. device=query_layer.device
  173. )
  174. # Raw attention scores. [b * np, sq, sk]
  175. matmul_result = torch.baddbmm(
  176. matmul_input_buffer,
  177. query_layer, # [b * np, sq, hn]
  178. key_layer.transpose(1, 2), # [b * np, hn, sk]
  179. beta=0.0,
  180. alpha=(1.0 / self.norm_factor),
  181. )
  182. # change view to [b, np, sq, sk]
  183. attention_scores = matmul_result.view(*output_size)
  184. # ===========================
  185. # Attention probs and dropout
  186. # ===========================
  187. # attention scores and attention mask [b, np, sq, sk]
  188. if self.attention_softmax_in_fp32:
  189. attention_scores = attention_scores.float()
  190. if self.coeff is not None:
  191. attention_scores = attention_scores * self.coeff
  192. if attention_mask is None and attention_scores.shape[2] == attention_scores.shape[3]:
  193. attention_mask = torch.ones(output_size[0], 1, output_size[2], output_size[3],
  194. device=attention_scores.device, dtype=torch.bool)
  195. attention_mask.tril_()
  196. attention_mask = ~attention_mask
  197. if attention_mask is not None:
  198. attention_scores = attention_scores.masked_fill(attention_mask, float("-inf"))
  199. attention_probs = F.softmax(attention_scores, dim=-1)
  200. attention_probs = attention_probs.type_as(value_layer)
  201. # This is actually dropping out entire tokens to attend to, which might
  202. # seem a bit unusual, but is taken from the original Transformer paper.
  203. attention_probs = self.attention_dropout(attention_probs)
  204. # query layer shape: [b * np, sq, hn]
  205. # value layer shape: [b, np, sk, hn]
  206. # attention shape: [b, np, sq, sk]
  207. # context layer shape: [b, np, sq, hn]
  208. output_size = (value_layer.size(0), value_layer.size(1), query_layer.size(1), value_layer.size(3))
  209. # change view [b * np, sk, hn]
  210. value_layer = value_layer.view(output_size[0] * output_size[1], value_layer.size(2), -1)
  211. # change view [b * np, sq, sk]
  212. attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
  213. # matmul: [b * np, sq, hn]
  214. context_layer = torch.bmm(attention_probs, value_layer)
  215. # change view [b, np, sq, hn]
  216. context_layer = context_layer.view(*output_size)
  217. # [b, np, sq, hn] --> [b, sq, np, hn]
  218. context_layer = context_layer.transpose(1, 2).contiguous()
  219. # [b, sq, np, hn] --> [b, sq, hp]
  220. new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,)
  221. context_layer = context_layer.reshape(*new_context_layer_shape)
  222. return context_layer
  223. class SelfAttention(torch.nn.Module):
  224. """Parallel self-attention layer abstract class.
  225. Self-attention layer takes input with size [s, b, h]
  226. and returns output of the same size.
  227. """
  228. def __init__(self, config: ChatGLMConfig, layer_number, device=None):
  229. super(SelfAttention, self).__init__()
  230. self.layer_number = max(1, layer_number)
  231. self.projection_size = config.kv_channels * config.num_attention_heads
  232. # Per attention head and per partition values.
  233. self.hidden_size_per_attention_head = self.projection_size // config.num_attention_heads
  234. self.num_attention_heads_per_partition = config.num_attention_heads
  235. self.multi_query_attention = config.multi_query_attention
  236. self.qkv_hidden_size = 3 * self.projection_size
  237. if self.multi_query_attention:
  238. self.num_multi_query_groups_per_partition = config.multi_query_group_num
  239. self.qkv_hidden_size = (
  240. self.projection_size + 2 * self.hidden_size_per_attention_head * config.multi_query_group_num
  241. )
  242. self.query_key_value = nn.Linear(config.hidden_size, self.qkv_hidden_size,
  243. bias=config.add_bias_linear or config.add_qkv_bias,
  244. device=device, **_config_to_kwargs(config)
  245. )
  246. self.core_attention = CoreAttention(config, self.layer_number)
  247. # Output.
  248. self.dense = nn.Linear(self.projection_size, config.hidden_size, bias=config.add_bias_linear,
  249. device=device, **_config_to_kwargs(config)
  250. )
  251. def _allocate_memory(self, inference_max_sequence_len, batch_size, device=None, dtype=None):
  252. if self.multi_query_attention:
  253. num_attention_heads = self.num_multi_query_groups_per_partition
  254. else:
  255. num_attention_heads = self.num_attention_heads_per_partition
  256. return torch.empty(
  257. inference_max_sequence_len,
  258. batch_size,
  259. num_attention_heads,
  260. self.hidden_size_per_attention_head,
  261. dtype=dtype,
  262. device=device,
  263. )
  264. def forward(
  265. self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True
  266. ):
  267. # hidden_states: [b, sq, h]
  268. # =================================================
  269. # Pre-allocate memory for key-values for inference.
  270. # =================================================
  271. # =====================
  272. # Query, Key, and Value
  273. # =====================
  274. # Attention heads [b, sq, h] --> [b, sq, (np * 3 * hn)]
  275. mixed_x_layer = self.query_key_value(hidden_states)
  276. if self.multi_query_attention:
  277. (query_layer, key_layer, value_layer) = mixed_x_layer.split(
  278. [
  279. self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,
  280. self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
  281. self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
  282. ],
  283. dim=-1,
  284. )
  285. query_layer = query_layer.view(
  286. query_layer.size()[:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
  287. )
  288. key_layer = key_layer.view(
  289. key_layer.size()[:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
  290. )
  291. value_layer = value_layer.view(
  292. value_layer.size()[:-1]
  293. + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
  294. )
  295. else:
  296. new_tensor_shape = mixed_x_layer.size()[:-1] + \
  297. (self.num_attention_heads_per_partition,
  298. 3 * self.hidden_size_per_attention_head)
  299. mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
  300. # [b, sq, np, 3 * hn] --> 3 [b, sq, np, hn]
  301. (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
  302. # [b, sq, np, hn] -> [b, np, sq, hn]
  303. query_layer, key_layer, value_layer = [k.transpose(1, 2) for k in [query_layer, key_layer, value_layer]]
  304. # apply relative positional encoding (rotary embedding)
  305. if rotary_pos_emb is not None:
  306. query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)
  307. key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)
  308. # adjust key and value for inference
  309. if kv_cache is not None:
  310. cache_k, cache_v = kv_cache
  311. key_layer = torch.cat((cache_k, key_layer), dim=2)
  312. value_layer = torch.cat((cache_v, value_layer), dim=2)
  313. if use_cache:
  314. if kv_cache is None:
  315. kv_cache = torch.cat((key_layer.unsqueeze(0).unsqueeze(0), value_layer.unsqueeze(0).unsqueeze(0)), dim=1)
  316. else:
  317. kv_cache = (key_layer, value_layer)
  318. else:
  319. kv_cache = None
  320. if self.multi_query_attention:
  321. key_layer = key_layer.unsqueeze(2)
  322. key_layer = key_layer.expand(
  323. -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1, -1
  324. )
  325. key_layer = key_layer.contiguous().view(
  326. key_layer.size()[:1] + (self.num_attention_heads_per_partition,) + key_layer.size()[3:]
  327. )
  328. value_layer = value_layer.unsqueeze(2)
  329. value_layer = value_layer.expand(
  330. -1, -1, self.num_attention_heads_per_partition // self.num_multi_query_groups_per_partition, -1, -1
  331. )
  332. value_layer = value_layer.contiguous().view(
  333. value_layer.size()[:1] + (self.num_attention_heads_per_partition,) + value_layer.size()[3:]
  334. )
  335. # ==================================
  336. # core attention computation
  337. # ==================================
  338. context_layer = self.core_attention(query_layer, key_layer, value_layer, attention_mask)
  339. # =================
  340. # Output. [sq, b, h]
  341. # =================
  342. output = self.dense(context_layer)
  343. return output, kv_cache
  344. def _config_to_kwargs(args):
  345. common_kwargs = {
  346. "dtype": args.torch_dtype,
  347. }
  348. return common_kwargs
  349. class MLP(torch.nn.Module):
  350. """MLP.
  351. MLP will take the input with h hidden state, project it to 4*h
  352. hidden dimension, perform nonlinear transformation, and project the
  353. state back into h hidden dimension.
  354. """
  355. def __init__(self, config: ChatGLMConfig, device=None):
  356. super(MLP, self).__init__()
  357. self.add_bias = config.add_bias_linear
  358. # Project to 4h. If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf
  359. self.dense_h_to_4h = nn.Linear(
  360. config.hidden_size,
  361. config.ffn_hidden_size * 2,
  362. bias=self.add_bias,
  363. device=device,
  364. **_config_to_kwargs(config)
  365. )
  366. def swiglu(x):
  367. x = torch.chunk(x, 2, dim=-1)
  368. return F.silu(x[0]) * x[1]
  369. self.activation_func = swiglu
  370. # Project back to h.
  371. self.dense_4h_to_h = nn.Linear(
  372. config.ffn_hidden_size,
  373. config.hidden_size,
  374. bias=self.add_bias,
  375. device=device,
  376. **_config_to_kwargs(config)
  377. )
  378. def forward(self, hidden_states):
  379. # [s, b, 4hp]
  380. intermediate_parallel = self.dense_h_to_4h(hidden_states)
  381. intermediate_parallel = self.activation_func(intermediate_parallel)
  382. # [s, b, h]
  383. output = self.dense_4h_to_h(intermediate_parallel)
  384. return output
  385. class GLMBlock(torch.nn.Module):
  386. """A single transformer layer.
  387. Transformer layer takes input with size [s, b, h] and returns an
  388. output of the same size.
  389. """
  390. def __init__(self, config: ChatGLMConfig, layer_number, device=None):
  391. super(GLMBlock, self).__init__()
  392. self.layer_number = layer_number
  393. self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
  394. self.fp32_residual_connection = config.fp32_residual_connection
  395. LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
  396. # Layernorm on the input data.
  397. self.input_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
  398. dtype=config.torch_dtype)
  399. # Self attention.
  400. self.self_attention = SelfAttention(config, layer_number, device=device)
  401. self.hidden_dropout = config.hidden_dropout
  402. # Layernorm on the attention output
  403. self.post_attention_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
  404. dtype=config.torch_dtype)
  405. # MLP
  406. self.mlp = MLP(config, device=device)
  407. def forward(
  408. self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True,
  409. ):
  410. # hidden_states: [s, b, h]
  411. # Layer norm at the beginning of the transformer layer.
  412. layernorm_output = self.input_layernorm(hidden_states)
  413. # Self attention.
  414. attention_output, kv_cache = self.self_attention(
  415. layernorm_output,
  416. attention_mask,
  417. rotary_pos_emb,
  418. kv_cache=kv_cache,
  419. use_cache=use_cache
  420. )
  421. # Residual connection.
  422. if self.apply_residual_connection_post_layernorm:
  423. residual = layernorm_output
  424. else:
  425. residual = hidden_states
  426. layernorm_input = torch.nn.functional.dropout(attention_output, p=self.hidden_dropout, training=self.training)
  427. layernorm_input = residual + layernorm_input
  428. # Layer norm post the self attention.
  429. layernorm_output = self.post_attention_layernorm(layernorm_input)
  430. # MLP.
  431. mlp_output = self.mlp(layernorm_output)
  432. # Second residual connection.
  433. if self.apply_residual_connection_post_layernorm:
  434. residual = layernorm_output
  435. else:
  436. residual = layernorm_input
  437. output = torch.nn.functional.dropout(mlp_output, p=self.hidden_dropout, training=self.training)
  438. output = residual + output
  439. return output, kv_cache
  440. class GLMTransformer(torch.nn.Module):
  441. """Transformer class."""
  442. def __init__(self, config: ChatGLMConfig, device=None):
  443. super(GLMTransformer, self).__init__()
  444. self.fp32_residual_connection = config.fp32_residual_connection
  445. self.post_layer_norm = config.post_layer_norm
  446. # Number of layers.
  447. self.num_layers = config.num_layers
  448. # Transformer layers.
  449. def build_layer(layer_number):
  450. return GLMBlock(config, layer_number, device=device)
  451. self.layers = torch.nn.ModuleList([build_layer(i + 1) for i in range(self.num_layers)])
  452. if self.post_layer_norm:
  453. LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm
  454. # Final layer norm before output.
  455. self.final_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device,
  456. dtype=config.torch_dtype)
  457. self.gradient_checkpointing = False
  458. def _get_layer(self, layer_number):
  459. return self.layers[layer_number]
  460. def forward(
  461. self, hidden_states, attention_mask, rotary_pos_emb, kv_caches=None,
  462. use_cache: Optional[bool] = True,
  463. output_hidden_states: Optional[bool] = False,
  464. ):
  465. if not kv_caches:
  466. kv_caches = [None for _ in range(self.num_layers)]
  467. presents = () if use_cache else None
  468. if self.gradient_checkpointing and self.training:
  469. if use_cache:
  470. logger.warning_once(
  471. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  472. )
  473. use_cache = False
  474. all_self_attentions = None
  475. all_hidden_states = () if output_hidden_states else None
  476. for index in range(self.num_layers):
  477. if output_hidden_states:
  478. all_hidden_states = all_hidden_states + (hidden_states,)
  479. layer = self._get_layer(index)
  480. if self.gradient_checkpointing and self.training:
  481. layer_ret = torch.utils.checkpoint.checkpoint(
  482. layer,
  483. hidden_states,
  484. attention_mask,
  485. rotary_pos_emb,
  486. kv_caches[index],
  487. use_cache,
  488. use_reentrant=False
  489. )
  490. else:
  491. layer_ret = layer(
  492. hidden_states,
  493. attention_mask,
  494. rotary_pos_emb,
  495. kv_cache=kv_caches[index],
  496. use_cache=use_cache
  497. )
  498. hidden_states, kv_cache = layer_ret
  499. if use_cache:
  500. # token by token decoding, use tuple format
  501. if kv_caches[0] is not None:
  502. presents = presents + (kv_cache,)
  503. # prefilling in decoding, use tensor format to save cuda memory
  504. else:
  505. if len(presents) == 0:
  506. presents = kv_cache
  507. else:
  508. presents = torch.cat((presents, kv_cache.to(presents.device)), dim=0)
  509. if output_hidden_states:
  510. all_hidden_states = all_hidden_states + (hidden_states,)
  511. # Final layer norm.
  512. if self.post_layer_norm:
  513. hidden_states = self.final_layernorm(hidden_states)
  514. return hidden_states, presents, all_hidden_states, all_self_attentions
  515. class ChatGLMPreTrainedModel(PreTrainedModel):
  516. """
  517. An abstract class to handle weights initialization and
  518. a simple interface for downloading and loading pretrained models.
  519. """
  520. is_parallelizable = False
  521. supports_gradient_checkpointing = True
  522. config_class = ChatGLMConfig
  523. base_model_prefix = "transformer"
  524. _no_split_modules = ["GLMBlock"]
  525. def _init_weights(self, module: nn.Module):
  526. """Initialize the weights."""
  527. return
  528. def get_masks(self, input_ids, past_key_values, padding_mask=None):
  529. batch_size, seq_length = input_ids.shape
  530. full_attention_mask = torch.ones(batch_size, seq_length, seq_length, device=input_ids.device)
  531. full_attention_mask.tril_()
  532. past_length = 0
  533. if past_key_values:
  534. past_length = past_key_values[0][0].shape[2]
  535. if past_length:
  536. full_attention_mask = torch.cat((torch.ones(batch_size, seq_length, past_length,
  537. device=input_ids.device), full_attention_mask), dim=-1)
  538. if padding_mask is not None:
  539. full_attention_mask = full_attention_mask * padding_mask.unsqueeze(1)
  540. if not past_length and padding_mask is not None:
  541. full_attention_mask -= padding_mask.unsqueeze(-1) - 1
  542. full_attention_mask = (full_attention_mask < 0.5).bool()
  543. full_attention_mask.unsqueeze_(1)
  544. return full_attention_mask
  545. def get_position_ids(self, input_ids, device):
  546. batch_size, seq_length = input_ids.shape
  547. position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1)
  548. return position_ids
  549. def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
  550. if not self.supports_gradient_checkpointing:
  551. raise ValueError(f"{self.__class__.__name__} does not support gradient checkpointing.")
  552. class Embedding(torch.nn.Module):
  553. """Language model embeddings."""
  554. def __init__(self, config: ChatGLMConfig, device=None):
  555. super(Embedding, self).__init__()
  556. self.hidden_size = config.hidden_size
  557. # Word embeddings (parallel).
  558. self.word_embeddings = nn.Embedding(
  559. config.padded_vocab_size,
  560. self.hidden_size,
  561. dtype=config.torch_dtype,
  562. device=device
  563. )
  564. self.fp32_residual_connection = config.fp32_residual_connection
  565. def forward(self, input_ids):
  566. # Embeddings.
  567. words_embeddings = self.word_embeddings(input_ids)
  568. embeddings = words_embeddings
  569. # If the input flag for fp32 residual connection is set, convert for float.
  570. if self.fp32_residual_connection:
  571. embeddings = embeddings.float()
  572. return embeddings
  573. class ChatGLMModel(ChatGLMPreTrainedModel):
  574. def __init__(self, config: ChatGLMConfig, device=None, empty_init=True):
  575. super().__init__(config)
  576. if empty_init:
  577. init_method = skip_init
  578. else:
  579. init_method = default_init
  580. init_kwargs = {}
  581. if device is not None:
  582. init_kwargs["device"] = device
  583. self.embedding = init_method(Embedding, config, **init_kwargs)
  584. self.num_layers = config.num_layers
  585. self.multi_query_group_num = config.multi_query_group_num
  586. self.kv_channels = config.kv_channels
  587. # Rotary positional embeddings
  588. self.seq_length = config.seq_length
  589. rotary_dim = (
  590. config.hidden_size // config.num_attention_heads if config.kv_channels is None else config.kv_channels
  591. )
  592. self.rotary_pos_emb = RotaryEmbedding(rotary_dim // 2, rope_ratio=config.rope_ratio, original_impl=config.original_rope,
  593. device=device, dtype=config.torch_dtype)
  594. self.encoder = init_method(GLMTransformer, config, **init_kwargs)
  595. self.output_layer = init_method(nn.Linear, config.hidden_size, config.padded_vocab_size, bias=False,
  596. dtype=config.torch_dtype, **init_kwargs)
  597. def get_input_embeddings(self):
  598. return self.embedding.word_embeddings
  599. def set_input_embeddings(self, value):
  600. self.embedding.word_embeddings = value
  601. def forward(
  602. self,
  603. input_ids,
  604. position_ids: Optional[torch.Tensor] = None,
  605. attention_mask: Optional[torch.BoolTensor] = None,
  606. full_attention_mask: Optional[torch.BoolTensor] = None,
  607. past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
  608. inputs_embeds: Optional[torch.Tensor] = None,
  609. use_cache: Optional[bool] = None,
  610. output_hidden_states: Optional[bool] = None,
  611. return_dict: Optional[bool] = None,
  612. ):
  613. output_hidden_states = (
  614. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  615. )
  616. use_cache = use_cache if use_cache is not None else self.config.use_cache
  617. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  618. batch_size, seq_length = input_ids.shape
  619. if inputs_embeds is None:
  620. inputs_embeds = self.embedding(input_ids)
  621. if full_attention_mask is None:
  622. if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
  623. full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask)
  624. # Rotary positional embeddings
  625. rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
  626. if position_ids is not None:
  627. rotary_pos_emb = rotary_pos_emb[position_ids]
  628. else:
  629. rotary_pos_emb = rotary_pos_emb[None, :seq_length]
  630. # Run encoder.
  631. hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
  632. inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb,
  633. kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
  634. )
  635. if presents is not None and type(presents) is torch.Tensor:
  636. presents = presents.split(1, dim=0)
  637. presents = list(presents)
  638. presents = [list(x.squeeze(0).split(1, dim=0)) for x in presents]
  639. presents = [tuple([x.squeeze(0) for x in y]) for y in presents]
  640. presents = tuple(presents)
  641. if not return_dict:
  642. return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
  643. return BaseModelOutputWithPast(
  644. last_hidden_state=hidden_states,
  645. past_key_values=presents,
  646. hidden_states=all_hidden_states,
  647. attentions=all_self_attentions,
  648. )
  649. class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
  650. def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
  651. super().__init__(config)
  652. self.max_sequence_length = config.max_length
  653. self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
  654. self.config = config
  655. def _update_model_kwargs_for_generation(
  656. self,
  657. outputs: ModelOutput,
  658. model_kwargs: Dict[str, Any],
  659. is_encoder_decoder: bool = False,
  660. standardize_cache_format: bool = False,
  661. ) -> Dict[str, Any]:
  662. # update past_key_values
  663. model_kwargs["past_key_values"] = self._extract_past_from_model_output(
  664. outputs, standardize_cache_format=standardize_cache_format
  665. )
  666. # update attention mask
  667. if "attention_mask" in model_kwargs:
  668. attention_mask = model_kwargs["attention_mask"]
  669. model_kwargs["attention_mask"] = torch.cat(
  670. [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
  671. )
  672. # update position ids
  673. if "position_ids" in model_kwargs:
  674. position_ids = model_kwargs["position_ids"]
  675. new_position_id = position_ids[..., -1:].clone()
  676. new_position_id += 1
  677. model_kwargs["position_ids"] = torch.cat(
  678. [position_ids, new_position_id], dim=-1
  679. )
  680. model_kwargs["is_first_forward"] = False
  681. return model_kwargs
  682. def prepare_inputs_for_generation(
  683. self,
  684. input_ids: torch.LongTensor,
  685. past_key_values: Optional[torch.Tensor] = None,
  686. attention_mask: Optional[torch.Tensor] = None,
  687. position_ids: Optional[torch.Tensor] = None,
  688. use_cache: Optional[bool] = None,
  689. is_first_forward: bool = True,
  690. **kwargs
  691. ) -> dict:
  692. # only last token for input_ids if past is not None
  693. if position_ids is None:
  694. position_ids = self.get_position_ids(input_ids, device=input_ids.device)
  695. if not is_first_forward:
  696. if past_key_values is not None:
  697. position_ids = position_ids[..., -1:]
  698. input_ids = input_ids[:, -1:]
  699. return {
  700. "input_ids": input_ids,
  701. "past_key_values": past_key_values,
  702. "position_ids": position_ids,
  703. "attention_mask": attention_mask,
  704. "return_last_logit": True,
  705. "use_cache": use_cache
  706. }
  707. def forward(
  708. self,
  709. input_ids: Optional[torch.Tensor] = None,
  710. position_ids: Optional[torch.Tensor] = None,
  711. attention_mask: Optional[torch.Tensor] = None,
  712. past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
  713. inputs_embeds: Optional[torch.Tensor] = None,
  714. labels: Optional[torch.Tensor] = None,
  715. use_cache: Optional[bool] = None,
  716. output_attentions: Optional[bool] = None,
  717. output_hidden_states: Optional[bool] = None,
  718. return_dict: Optional[bool] = None,
  719. return_last_logit: Optional[bool] = False,
  720. ):
  721. use_cache = use_cache if use_cache is not None else self.config.use_cache
  722. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  723. transformer_outputs = self.transformer(
  724. input_ids=input_ids,
  725. position_ids=position_ids,
  726. attention_mask=attention_mask,
  727. past_key_values=past_key_values,
  728. inputs_embeds=inputs_embeds,
  729. use_cache=use_cache,
  730. output_hidden_states=output_hidden_states,
  731. return_dict=return_dict,
  732. )
  733. hidden_states = transformer_outputs[0]
  734. if return_last_logit:
  735. hidden_states = hidden_states[:, -1:]
  736. lm_logits = self.transformer.output_layer(hidden_states)
  737. loss = None
  738. if labels is not None:
  739. lm_logits = lm_logits.to(torch.float32)
  740. # Shift so that tokens < n predict n
  741. shift_logits = lm_logits[..., :-1, :].contiguous()
  742. shift_labels = labels[..., 1:].contiguous()
  743. # Flatten the tokens
  744. loss_fct = CrossEntropyLoss(ignore_index=-100)
  745. loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
  746. lm_logits = lm_logits.to(hidden_states.dtype)
  747. loss = loss.to(hidden_states.dtype)
  748. if not return_dict:
  749. output = (lm_logits,) + transformer_outputs[1:]
  750. return ((loss,) + output) if loss is not None else output
  751. return CausalLMOutputWithPast(
  752. loss=loss,
  753. logits=lm_logits,
  754. past_key_values=transformer_outputs.past_key_values,
  755. hidden_states=transformer_outputs.hidden_states,
  756. attentions=transformer_outputs.attentions,
  757. )
  758. @staticmethod
  759. def _reorder_cache(
  760. past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
  761. ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
  762. """
  763. This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
  764. [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
  765. beam_idx at every generation step.
  766. Output shares the same memory storage as `past`.
  767. """
  768. return tuple(
  769. (
  770. layer_past[0].index_select(0, beam_idx.to(layer_past[0].device)),
  771. layer_past[1].index_select(0, beam_idx.to(layer_past[1].device)),
  772. )
  773. for layer_past in past
  774. )
  775. def process_response(self, output, history):
  776. content = ""
  777. history = deepcopy(history)
  778. for response in output.split("<|assistant|>"):
  779. if "\n" in response:
  780. metadata, content = response.split("\n", maxsplit=1)
  781. else:
  782. metadata, content = "", response
  783. if not metadata.strip():
  784. content = content.strip()
  785. history.append({"role": "assistant", "metadata": metadata, "content": content})
  786. content = content.replace("[[训练时间]]", "2023年")
  787. else:
  788. history.append({"role": "assistant", "metadata": metadata, "content": content})
  789. if history[0]["role"] == "system" and "tools" in history[0]:
  790. parameters = json.loads(content)
  791. content = {"name": metadata.strip(), "parameters": parameters}
  792. else:
  793. content = {"name": metadata.strip(), "content": content}
  794. return content, history
  795. @torch.inference_mode()
  796. def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user",
  797. max_length: int = 8192, num_beams=1, do_sample=True, top_p=0.8, temperature=0.8, logits_processor=None,
  798. **kwargs):
  799. if history is None:
  800. history = []
  801. if logits_processor is None:
  802. logits_processor = LogitsProcessorList()
  803. logits_processor.append(InvalidScoreLogitsProcessor())
  804. gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
  805. "temperature": temperature, "logits_processor": logits_processor, **kwargs}
  806. history.append({"role": role, "content": query})
  807. inputs = tokenizer.apply_chat_template(history, add_generation_prompt=True, tokenize=True,
  808. return_tensors="pt", return_dict=True)
  809. inputs = inputs.to(self.device)
  810. eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|user|>"),
  811. tokenizer.convert_tokens_to_ids("<|observation|>")]
  812. outputs = self.generate(**inputs, **gen_kwargs, eos_token_id=eos_token_id)
  813. outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
  814. response = tokenizer.decode(outputs)
  815. response, history = self.process_response(response, history)
  816. return response, history
  817. @torch.inference_mode()
  818. def stream_chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user",
  819. past_key_values=None, max_length: int = 8192, do_sample=True, top_p=0.8, temperature=0.8,
  820. logits_processor=None, return_past_key_values=False, **kwargs):
  821. if history is None:
  822. history = []
  823. if logits_processor is None:
  824. logits_processor = LogitsProcessorList()
  825. logits_processor.append(InvalidScoreLogitsProcessor())
  826. eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|user|>"),
  827. tokenizer.convert_tokens_to_ids("<|observation|>")]
  828. gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,
  829. "temperature": temperature, "logits_processor": logits_processor, **kwargs}
  830. if past_key_values is None:
  831. inputs = tokenizer.apply_chat_template(history + [{"role": role, "content": query}],
  832. add_generation_prompt=True, tokenize=True, return_tensors="pt",
  833. return_dict=True)
  834. else:
  835. inputs = tokenizer.apply_chat_template([{"role": role, "content": query}], add_special_tokens=False,
  836. add_generation_prompt=True, tokenize=True, return_tensors="pt",
  837. return_dict=True)
  838. inputs = inputs.to(self.device)
  839. if past_key_values is not None:
  840. past_length = past_key_values[0][0].shape[2]
  841. inputs.position_ids += past_length
  842. attention_mask = inputs.attention_mask
  843. attention_mask = torch.cat((attention_mask.new_ones(1, past_length), attention_mask), dim=1)
  844. inputs['attention_mask'] = attention_mask
  845. history.append({"role": role, "content": query})
  846. for outputs in self.stream_generate(**inputs, past_key_values=past_key_values,
  847. eos_token_id=eos_token_id, return_past_key_values=return_past_key_values,
  848. **gen_kwargs):
  849. if return_past_key_values:
  850. outputs, past_key_values = outputs
  851. outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
  852. response = tokenizer.decode(outputs)
  853. if response and response[-1] != "�":
  854. response, new_history = self.process_response(response, history)
  855. if return_past_key_values:
  856. yield response, new_history, past_key_values
  857. else:
  858. yield response, new_history
  859. @torch.inference_mode()
  860. def stream_generate(
  861. self,
  862. input_ids,
  863. generation_config: Optional[GenerationConfig] = None,
  864. logits_processor: Optional[LogitsProcessorList] = None,
  865. stopping_criteria: Optional[StoppingCriteriaList] = None,
  866. prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
  867. return_past_key_values=False,
  868. **kwargs,
  869. ):
  870. batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
  871. if generation_config is None:
  872. generation_config = self.generation_config
  873. generation_config = copy.deepcopy(generation_config)
  874. model_kwargs = generation_config.update(**kwargs)
  875. model_kwargs["use_cache"] = generation_config.use_cache
  876. bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
  877. if isinstance(eos_token_id, int):
  878. eos_token_id = [eos_token_id]
  879. eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None
  880. has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
  881. if has_default_max_length and generation_config.max_new_tokens is None:
  882. warnings.warn(
  883. f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
  884. "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
  885. " recommend using `max_new_tokens` to control the maximum length of the generation.",
  886. UserWarning,
  887. )
  888. elif generation_config.max_new_tokens is not None:
  889. generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
  890. if not has_default_max_length:
  891. logger.warn(
  892. f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
  893. f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
  894. "Please refer to the documentation for more information. "
  895. "(https://hf-mirror.com/docs/transformers/main/en/main_classes/text_generation)",
  896. UserWarning,
  897. )
  898. if input_ids_seq_length >= generation_config.max_length:
  899. input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
  900. logger.warning(
  901. f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
  902. f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
  903. " increasing `max_new_tokens`."
  904. )
  905. # 2. Set generation parameters if not already defined
  906. logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
  907. stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
  908. logits_processor = self._get_logits_processor(
  909. generation_config=generation_config,
  910. input_ids_seq_length=input_ids_seq_length,
  911. encoder_input_ids=input_ids,
  912. prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
  913. logits_processor=logits_processor,
  914. )
  915. stopping_criteria = self._get_stopping_criteria(
  916. generation_config=generation_config, stopping_criteria=stopping_criteria
  917. )
  918. logits_warper = self._get_logits_warper(generation_config)
  919. unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
  920. scores = None
  921. while True:
  922. model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
  923. # forward pass to get next token
  924. outputs = self(
  925. **model_inputs,
  926. return_dict=True,
  927. output_attentions=False,
  928. output_hidden_states=False,
  929. )
  930. next_token_logits = outputs.logits[:, -1, :]
  931. # pre-process distribution
  932. next_token_scores = logits_processor(input_ids, next_token_logits)
  933. next_token_scores = logits_warper(input_ids, next_token_scores)
  934. # sample
  935. probs = nn.functional.softmax(next_token_scores, dim=-1)
  936. if generation_config.do_sample:
  937. next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
  938. else:
  939. next_tokens = torch.argmax(probs, dim=-1)
  940. # update generated ids, model inputs, and length for next step
  941. input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
  942. model_kwargs = self._update_model_kwargs_for_generation(
  943. outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
  944. )
  945. unfinished_sequences = unfinished_sequences.mul(
  946. next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
  947. )
  948. if return_past_key_values:
  949. yield input_ids, outputs.past_key_values
  950. else:
  951. yield input_ids
  952. # stop when each sentence is finished, or if we exceed the maximum length
  953. if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
  954. break
  955. class ChatGLMForSequenceClassification(ChatGLMPreTrainedModel):
  956. def __init__(self, config: ChatGLMConfig, empty_init=True, device=None):
  957. super().__init__(config)
  958. self.num_labels = config.num_labels
  959. self.transformer = ChatGLMModel(config, empty_init=empty_init, device=device)
  960. self.classifier_head = nn.Linear(config.hidden_size, config.num_labels, bias=True, dtype=torch.half)
  961. if config.classifier_dropout is not None:
  962. self.dropout = nn.Dropout(config.classifier_dropout)
  963. else:
  964. self.dropout = None
  965. self.config = config
  966. def forward(
  967. self,
  968. input_ids: Optional[torch.LongTensor] = None,
  969. position_ids: Optional[torch.LongTensor] = None,
  970. attention_mask: Optional[torch.Tensor] = None,
  971. full_attention_mask: Optional[torch.Tensor] = None,
  972. past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
  973. inputs_embeds: Optional[torch.LongTensor] = None,
  974. labels: Optional[torch.LongTensor] = None,
  975. use_cache: Optional[bool] = None,
  976. output_hidden_states: Optional[bool] = None,
  977. return_dict: Optional[bool] = None,
  978. ) -> Union[Tuple[torch.Tensor, ...], SequenceClassifierOutputWithPast]:
  979. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  980. transformer_outputs = self.transformer(
  981. input_ids=input_ids,
  982. position_ids=position_ids,
  983. attention_mask=attention_mask,
  984. full_attention_mask=full_attention_mask,
  985. past_key_values=past_key_values,
  986. inputs_embeds=inputs_embeds,
  987. use_cache=use_cache,
  988. output_hidden_states=output_hidden_states,
  989. return_dict=return_dict,
  990. )
  991. hidden_states = transformer_outputs[0]
  992. pooled_hidden_states = hidden_states[:, -1]
  993. if self.dropout is not None:
  994. pooled_hidden_states = self.dropout(pooled_hidden_states)
  995. logits = self.classifier_head(pooled_hidden_states)
  996. loss = None
  997. if labels is not None:
  998. if self.config.problem_type is None:
  999. if self.num_labels == 1:
  1000. self.config.problem_type = "regression"
  1001. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  1002. self.config.problem_type = "single_label_classification"
  1003. else:
  1004. self.config.problem_type = "multi_label_classification"
  1005. if self.config.problem_type == "regression":
  1006. loss_fct = MSELoss()
  1007. if self.num_labels == 1:
  1008. loss = loss_fct(logits.squeeze().float(), labels.squeeze())
  1009. else:
  1010. loss = loss_fct(logits.float(), labels)
  1011. elif self.config.problem_type == "single_label_classification":
  1012. loss_fct = CrossEntropyLoss()
  1013. loss = loss_fct(logits.view(-1, self.num_labels).float(), labels.view(-1))
  1014. elif self.config.problem_type == "multi_label_classification":
  1015. loss_fct = BCEWithLogitsLoss()
  1016. loss = loss_fct(logits.float(), labels.view(-1, self.num_labels))
  1017. if not return_dict:
  1018. output = (logits,) + transformer_outputs[1:]
  1019. return ((loss,) + output) if loss is not None else output
  1020. return SequenceClassifierOutputWithPast(
  1021. loss=loss,
  1022. logits=logits,
  1023. past_key_values=transformer_outputs.past_key_values,
  1024. hidden_states=transformer_outputs.hidden_states,
  1025. attentions=transformer_outputs.attentions,
  1026. )