zxdu20 commited on
Commit
812f43f
1 Parent(s): 220f772

Add p-tuning v2

Browse files
Files changed (2) hide show
  1. configuration_chatglm.py +4 -0
  2. modeling_chatglm.py +73 -2
configuration_chatglm.py CHANGED
@@ -70,6 +70,8 @@ class ChatGLMConfig(PretrainedConfig):
70
  max_sequence_length=2048,
71
  inner_hidden_size=16384,
72
  position_encoding_2d=True,
 
 
73
  **kwargs
74
  ):
75
  self.num_layers = num_layers
@@ -84,6 +86,8 @@ class ChatGLMConfig(PretrainedConfig):
84
  self.eos_token_id = eos_token_id
85
  self.pad_token_id = pad_token_id
86
  self.position_encoding_2d = position_encoding_2d
 
 
87
  super().__init__(
88
  pad_token_id=pad_token_id,
89
  bos_token_id=bos_token_id,
 
70
  max_sequence_length=2048,
71
  inner_hidden_size=16384,
72
  position_encoding_2d=True,
73
+ pre_seq_len=None,
74
+ prefix_projection=False,
75
  **kwargs
76
  ):
77
  self.num_layers = num_layers
 
86
  self.eos_token_id = eos_token_id
87
  self.pad_token_id = pad_token_id
88
  self.position_encoding_2d = position_encoding_2d
89
+ self.pre_seq_len = pre_seq_len
90
+ self.prefix_projection = prefix_projection
91
  super().__init__(
92
  pad_token_id=pad_token_id,
93
  bos_token_id=bos_token_id,
modeling_chatglm.py CHANGED
@@ -129,6 +129,35 @@ def load_tf_weights_in_chatglm_6b(model, config, tf_checkpoint_path):
129
  return model
130
 
131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  @torch.jit.script
133
  def gelu_impl(x):
134
  """OpenAI's gelu implementation."""
@@ -719,6 +748,8 @@ class ChatGLMModel(ChatGLMPreTrainedModel):
719
  self.inner_hidden_size = config.inner_hidden_size
720
  self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
721
  self.position_encoding_2d = config.position_encoding_2d
 
 
722
 
723
  self.word_embeddings = skip_init(
724
  torch.nn.Embedding,
@@ -747,12 +778,41 @@ class ChatGLMModel(ChatGLMPreTrainedModel):
747
  # Final layer norm before output.
748
  self.final_layernorm = LayerNorm(self.hidden_size, eps=self.layernorm_epsilon)
749
 
 
 
 
 
 
 
 
 
 
 
 
750
  def get_input_embeddings(self):
751
  return self.word_embeddings
752
 
753
  def set_input_embeddings(self, new_embeddings: torch.Tensor):
754
  self.word_embeddings = new_embeddings
755
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
756
  @staticmethod
757
  def get_masks(seq, device):
758
  context_length = seq.index(150004) + 1
@@ -822,7 +882,10 @@ class ChatGLMModel(ChatGLMPreTrainedModel):
822
  raise ValueError("You have to specify either input_ids or inputs_embeds")
823
 
824
  if past_key_values is None:
825
- past_key_values = tuple([None] * len(self.layers))
 
 
 
826
 
827
  MASK, gMASK = 150000, 150001
828
  mask_token = MASK if MASK in input_ids else gMASK
@@ -837,6 +900,11 @@ class ChatGLMModel(ChatGLMPreTrainedModel):
837
  device=input_ids.device
838
  )
839
 
 
 
 
 
 
840
  if position_ids is None:
841
  position_ids = self.get_position_ids(
842
  seq=seq,
@@ -1125,18 +1193,21 @@ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
1125
  if "eos_token_id" not in kwargs:
1126
  kwargs["eos_token_id"] = eos
1127
 
 
 
1128
  stop = False
1129
 
1130
  return_seqs = []
1131
 
1132
  while True:
1133
  output_ids = super().generate(**kwargs)
1134
-
1135
  return_seqs = []
1136
  max_length = 0
1137
 
1138
  for i in range(output_ids.shape[0]):
1139
  output_seq = output_ids[i].tolist()
 
 
1140
  mask_token = MASK if MASK in output_seq else gMASK
1141
  mask_position = output_seq.index(mask_token)
1142
  bos_position = output_seq.index(bos)
 
129
  return model
130
 
131
 
132
+ class PrefixEncoder(torch.nn.Module):
133
+ r'''
134
+ The torch.nn model to encode the prefix
135
+ Input shape: (batch-size, prefix-length)
136
+ Output shape: (batch-size, prefix-length, 2*layers*hidden)
137
+ '''
138
+ def __init__(self, config):
139
+ super().__init__()
140
+ self.prefix_projection = config.prefix_projection
141
+ if self.prefix_projection:
142
+ # Use a two-layer MLP to encode the prefix
143
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, config.hidden_size)
144
+ self.trans = torch.nn.Sequential(
145
+ torch.nn.Linear(config.hidden_size, config.hidden_size),
146
+ torch.nn.Tanh(),
147
+ torch.nn.Linear(config.hidden_size, config.num_layers * config.hidden_size * 2)
148
+ )
149
+ else:
150
+ self.embedding = torch.nn.Embedding(config.pre_seq_len, config.num_layers * config.hidden_size * 2)
151
+
152
+ def forward(self, prefix: torch.Tensor):
153
+ if self.prefix_projection:
154
+ prefix_tokens = self.embedding(prefix)
155
+ past_key_values = self.trans(prefix_tokens)
156
+ else:
157
+ past_key_values = self.embedding(prefix)
158
+ return past_key_values
159
+
160
+
161
  @torch.jit.script
162
  def gelu_impl(x):
163
  """OpenAI's gelu implementation."""
 
748
  self.inner_hidden_size = config.inner_hidden_size
749
  self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
750
  self.position_encoding_2d = config.position_encoding_2d
751
+ self.pre_seq_len = config.pre_seq_len
752
+ self.prefix_projection = config.prefix_projection
753
 
754
  self.word_embeddings = skip_init(
755
  torch.nn.Embedding,
 
778
  # Final layer norm before output.
779
  self.final_layernorm = LayerNorm(self.hidden_size, eps=self.layernorm_epsilon)
780
 
781
+ if self.pre_seq_len is not None:
782
+ for param in self.parameters():
783
+ param.requires_grad = False
784
+ self.prefix_tokens = torch.arange(self.pre_seq_len).long()
785
+ self.prefix_encoder = PrefixEncoder(config)
786
+ self.dropout = torch.nn.Dropout(0.1)
787
+
788
+ # total_params = sum(p.numel() for p in self.parameters())
789
+ # trainable_params = sum(p.numel() for p in self.parameters() if p.requires_grad)
790
+ # print("Using p-tuning v2: # trainable_params = {} / {}".format(trainable_params, total_params))
791
+
792
  def get_input_embeddings(self):
793
  return self.word_embeddings
794
 
795
  def set_input_embeddings(self, new_embeddings: torch.Tensor):
796
  self.word_embeddings = new_embeddings
797
 
798
+ def get_prompt(self, batch_size, device):
799
+ prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(device)
800
+ past_key_values = self.prefix_encoder(prefix_tokens).half()
801
+ past_key_values = past_key_values.view(
802
+ batch_size,
803
+ self.pre_seq_len,
804
+ self.num_layers * 2,
805
+ self.num_attention_heads,
806
+ self.hidden_size // self.num_attention_heads
807
+ )
808
+ #seq_len, b, nh, hidden_size
809
+ past_key_values = self.dropout(past_key_values)
810
+ past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(2)
811
+ past_key_values = [(v[0], v[1]) for v in past_key_values]
812
+ # past_key_values = past_key_values.permute([2, 1, 0, 3, 4]).split(self.num_layers)
813
+ # past_key_values = [(v1,v2) for v1, v2 in zip(past_key_values[0], past_key_values[1])]
814
+ return past_key_values
815
+
816
  @staticmethod
817
  def get_masks(seq, device):
818
  context_length = seq.index(150004) + 1
 
882
  raise ValueError("You have to specify either input_ids or inputs_embeds")
883
 
884
  if past_key_values is None:
885
+ if self.pre_seq_len is not None:
886
+ past_key_values = self.get_prompt(batch_size=input_ids.shape[0], device=input_ids.device)
887
+ else:
888
+ past_key_values = tuple([None] * len(self.layers))
889
 
890
  MASK, gMASK = 150000, 150001
891
  mask_token = MASK if MASK in input_ids else gMASK
 
900
  device=input_ids.device
901
  )
902
 
903
+ if self.pre_seq_len is not None:
904
+ prefix_attention_mask = torch.ones(1, 1, len(seq), self.pre_seq_len).to(attention_mask.device)
905
+ prefix_attention_mask = (prefix_attention_mask < 0.5).bool()
906
+ attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=3)
907
+
908
  if position_ids is None:
909
  position_ids = self.get_position_ids(
910
  seq=seq,
 
1193
  if "eos_token_id" not in kwargs:
1194
  kwargs["eos_token_id"] = eos
1195
 
1196
+ truncate = kwargs.pop("truncate") if "truncate" in kwargs else False
1197
+
1198
  stop = False
1199
 
1200
  return_seqs = []
1201
 
1202
  while True:
1203
  output_ids = super().generate(**kwargs)
 
1204
  return_seqs = []
1205
  max_length = 0
1206
 
1207
  for i in range(output_ids.shape[0]):
1208
  output_seq = output_ids[i].tolist()
1209
+ if truncate:
1210
+ output_seq = output_seq[len(kwargs["input_ids"][i]) - 2:]
1211
  mask_token = MASK if MASK in output_seq else gMASK
1212
  mask_position = output_seq.index(mask_token)
1213
  bos_position = output_seq.index(bos)