Schmadge commited on
Commit
91f62d5
·
1 Parent(s): c0cbc84

Create hf_prefixlm_converter.py

Browse files
Files changed (1) hide show
  1. hf_prefixlm_converter.py +393 -0
hf_prefixlm_converter.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Converts Huggingface Causal LM to Prefix LM.
2
+ Conversion does lightweight surgery on a HuggingFace
3
+ Causal LM to convert it to a Prefix LM.
4
+ Prefix LMs accepts a `bidirectional_mask` input in `forward`
5
+ and treat the input prompt as the prefix in `generate`.
6
+ """
7
+ import math
8
+ import warnings
9
+ from types import MethodType
10
+ from typing import Any, Dict, List, Optional, Tuple, Union
11
+ import torch
12
+ from transformers.models.bloom.modeling_bloom import BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLoss
13
+ from transformers.models.bloom.modeling_bloom import _expand_mask as _expand_mask_bloom
14
+ from transformers.models.bloom.modeling_bloom import _make_causal_mask as _make_causal_mask_bloom
15
+ from transformers.models.bloom.modeling_bloom import logging
16
+ from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
17
+ from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM
18
+ from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM
19
+ from transformers.models.gptj.modeling_gptj import GPTJForCausalLM
20
+ from transformers.models.opt.modeling_opt import OPTForCausalLM
21
+ from transformers.models.opt.modeling_opt import _expand_mask as _expand_mask_opt
22
+ from transformers.models.opt.modeling_opt import _make_causal_mask as _make_causal_mask_opt
23
+ logger = logging.get_logger(__name__)
24
+ _SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM)
25
+ CAUSAL_GPT_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]
26
+
27
+ def _convert_gpt_causal_lm_to_prefix_lm(model: CAUSAL_GPT_TYPES) -> CAUSAL_GPT_TYPES:
28
+ """Converts a GPT-style Causal LM to a Prefix LM.
29
+ Supported HuggingFace model classes:
30
+ - `GPT2LMHeadModel`
31
+ - `GPTNeoForCausalLM`
32
+ - `GPTNeoXForCausalLM`
33
+ - `GPTJForCausalLM`
34
+ See `convert_hf_causal_lm_to_prefix_lm` for more details.
35
+ """
36
+ if hasattr(model, '_prefix_lm_converted'):
37
+ return model
38
+ assert isinstance(model, _SUPPORTED_GPT_MODELS)
39
+ assert model.config.add_cross_attention == False, 'Only supports GPT-style decoder-only models'
40
+
41
+ def _get_attn_modules(model: CAUSAL_GPT_TYPES) -> List[torch.nn.Module]:
42
+ """Helper that gets a list of the model's attention modules.
43
+ Each module has a `bias` buffer used for causal masking. The Prefix LM
44
+ conversion adds logic to dynamically manipulate these biases to support
45
+ Prefix LM attention masking.
46
+ """
47
+ attn_modules = []
48
+ if isinstance(model, GPTNeoXForCausalLM):
49
+ blocks = model.gpt_neox.layers
50
+ else:
51
+ blocks = model.transformer.h
52
+ for block in blocks:
53
+ if isinstance(model, GPTNeoForCausalLM):
54
+ if block.attn.attention_type != 'global':
55
+ continue
56
+ attn_module = block.attn.attention
57
+ elif isinstance(model, GPTNeoXForCausalLM):
58
+ attn_module = block.attention
59
+ else:
60
+ attn_module = block.attn
61
+ attn_modules.append(attn_module)
62
+ return attn_modules
63
+ setattr(model, '_original_forward', getattr(model, 'forward'))
64
+ setattr(model, '_original_generate', getattr(model, 'generate'))
65
+
66
+ def forward(self: CAUSAL_GPT_TYPES, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]]=None, attention_mask: Optional[torch.FloatTensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, token_type_ids: Optional[torch.LongTensor]=None, position_ids: Optional[torch.LongTensor]=None, head_mask: Optional[torch.FloatTensor]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
67
+ """Wraps original forward to enable PrefixLM attention."""
68
+
69
+ def call_og_forward():
70
+ if isinstance(self, GPTNeoXForCausalLM):
71
+ return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
72
+ else:
73
+ return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
74
+ if bidirectional_mask is None:
75
+ return call_og_forward()
76
+ assert isinstance(bidirectional_mask, torch.Tensor)
77
+ attn_modules = _get_attn_modules(model)
78
+ (b, s) = bidirectional_mask.shape
79
+ max_length = attn_modules[0].bias.shape[-1]
80
+ if s > max_length:
81
+ raise ValueError(f'bidirectional_mask sequence length (={s}) exceeds the ' + f'max length allowed by the model ({max_length}).')
82
+ assert s <= max_length
83
+ if s < max_length:
84
+ pad = torch.zeros((int(b), int(max_length - s)), dtype=bidirectional_mask.dtype, device=bidirectional_mask.device)
85
+ bidirectional_mask = torch.cat([bidirectional_mask, pad], dim=1)
86
+ bidirectional = bidirectional_mask.unsqueeze(1).unsqueeze(1)
87
+ for attn_module in attn_modules:
88
+ attn_module.bias.data = torch.logical_or(attn_module.bias.data, bidirectional)
89
+ output = call_og_forward()
90
+ for attn_module in attn_modules:
91
+ attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
92
+ return output
93
+
94
+ def generate(self: CAUSAL_GPT_TYPES, *args: tuple, **kwargs: Dict[str, Any]):
95
+ """Wraps original generate to enable PrefixLM attention."""
96
+ attn_modules = _get_attn_modules(model)
97
+ for attn_module in attn_modules:
98
+ attn_module.bias.data[:] = 1
99
+ output = self._original_generate(*args, **kwargs)
100
+ for attn_module in attn_modules:
101
+ attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
102
+ return output
103
+ setattr(model, 'forward', MethodType(forward, model))
104
+ setattr(model, 'generate', MethodType(generate, model))
105
+ setattr(model, '_prefix_lm_converted', True)
106
+ return model
107
+
108
+ def _convert_bloom_causal_lm_to_prefix_lm(model: BloomForCausalLM) -> BloomForCausalLM:
109
+ """Converts a BLOOM Causal LM to a Prefix LM.
110
+ Supported HuggingFace model classes:
111
+ - `BloomForCausalLM`
112
+ See `convert_hf_causal_lm_to_prefix_lm` for more details.
113
+ """
114
+ if hasattr(model, '_prefix_lm_converted'):
115
+ return model
116
+ assert isinstance(model, BloomForCausalLM)
117
+ assert model.config.add_cross_attention == False, 'Only supports BLOOM decoder-only models'
118
+
119
+ def _prepare_attn_mask(self: BloomModel, attention_mask: torch.Tensor, bidirectional_mask: Optional[torch.Tensor], input_shape: Tuple[int, int], past_key_values_length: int) -> torch.BoolTensor:
120
+ combined_attention_mask = None
121
+ device = attention_mask.device
122
+ (_, src_length) = input_shape
123
+ if src_length > 1:
124
+ combined_attention_mask = _make_causal_mask_bloom(input_shape, device=device, past_key_values_length=past_key_values_length)
125
+ if bidirectional_mask is not None:
126
+ assert attention_mask.shape == bidirectional_mask.shape
127
+ expanded_bidirectional_mask = _expand_mask_bloom(bidirectional_mask, tgt_length=src_length)
128
+ combined_attention_mask = torch.logical_and(combined_attention_mask, expanded_bidirectional_mask)
129
+ expanded_attn_mask = _expand_mask_bloom(attention_mask, tgt_length=src_length)
130
+ combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask
131
+ return combined_attention_mask
132
+
133
+ def _build_alibi_tensor(self: BloomModel, batch_size: int, query_length: int, key_length: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
134
+ num_heads = self.config.n_head
135
+ closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
136
+ base = torch.tensor(2 ** (-2 ** (-(math.log2(closest_power_of_2) - 3))), device=device, dtype=torch.float32)
137
+ powers = torch.arange(1, 1 + closest_power_of_2, device=device, dtype=torch.int32)
138
+ slopes = torch.pow(base, powers)
139
+ if closest_power_of_2 != num_heads:
140
+ extra_base = torch.tensor(2 ** (-2 ** (-(math.log2(2 * closest_power_of_2) - 3))), device=device, dtype=torch.float32)
141
+ num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
142
+ extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32)
143
+ slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
144
+ qa = torch.arange(query_length, device=device, dtype=torch.int32).view(-1, 1)
145
+ ka = torch.arange(key_length, device=device, dtype=torch.int32).view(1, -1)
146
+ diffs = qa - ka + key_length - query_length
147
+ diffs = -diffs.abs()
148
+ alibi = slopes.view(1, num_heads, 1, 1) * diffs.view(1, 1, query_length, key_length)
149
+ alibi = alibi.expand(batch_size, -1, -1, -1).reshape(-1, query_length, key_length)
150
+ return alibi.to(dtype)
151
+ KeyValueT = Tuple[torch.Tensor, torch.Tensor]
152
+
153
+ def forward(self: BloomModel, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.LongTensor]=None, inputs_embeds: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
154
+ if deprecated_arguments.pop('position_ids', False) is not False:
155
+ warnings.warn('`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. ' + 'You can safely ignore passing `position_ids`.', FutureWarning)
156
+ if len(deprecated_arguments) > 0:
157
+ raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
158
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
159
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
160
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
161
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
162
+ if input_ids is not None and inputs_embeds is not None:
163
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
164
+ elif input_ids is not None:
165
+ (batch_size, seq_length) = input_ids.shape
166
+ elif inputs_embeds is not None:
167
+ (batch_size, seq_length, _) = inputs_embeds.shape
168
+ else:
169
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
170
+ if past_key_values is None:
171
+ past_key_values = tuple([None] * len(self.h))
172
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
173
+ if inputs_embeds is None:
174
+ inputs_embeds = self.word_embeddings(input_ids)
175
+ hidden_states = self.word_embeddings_layernorm(inputs_embeds)
176
+ presents = () if use_cache else None
177
+ all_self_attentions = () if output_attentions else None
178
+ all_hidden_states = () if output_hidden_states else None
179
+ seq_length_with_past = seq_length
180
+ past_key_values_length = 0
181
+ if past_key_values[0] is not None:
182
+ tmp = past_key_values[0][0]
183
+ past_key_values_length = tmp.shape[2]
184
+ seq_length_with_past = seq_length_with_past + past_key_values_length
185
+ if attention_mask is None:
186
+ attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
187
+ else:
188
+ attention_mask = attention_mask.to(hidden_states.device)
189
+ alibi = self._build_alibi_tensor(batch_size=batch_size, query_length=seq_length, key_length=seq_length_with_past, dtype=hidden_states.dtype, device=hidden_states.device)
190
+ causal_mask = self._prepare_attn_mask(attention_mask, bidirectional_mask, input_shape=(batch_size, seq_length), past_key_values_length=past_key_values_length)
191
+ for (i, (block, layer_past)) in enumerate(zip(self.h, past_key_values)):
192
+ if output_hidden_states:
193
+ hst = (hidden_states,)
194
+ all_hidden_states = all_hidden_states + hst
195
+ if self.gradient_checkpointing and self.training:
196
+ if use_cache:
197
+ logger.warning('`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...')
198
+ use_cache = False
199
+
200
+ def create_custom_forward(module):
201
+
202
+ def custom_forward(*inputs):
203
+ return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
204
+ return custom_forward
205
+ outputs = torch.utils.checkpoint.checkpoint(create_custom_forward(block), hidden_states, alibi, causal_mask, head_mask[i])
206
+ else:
207
+ outputs = block(hidden_states, layer_past=layer_past, attention_mask=causal_mask, head_mask=head_mask[i], use_cache=use_cache, output_attentions=output_attentions, alibi=alibi)
208
+ hidden_states = outputs[0]
209
+ if use_cache is True:
210
+ presents = presents + (outputs[1],)
211
+ if output_attentions:
212
+ oa = (outputs[2 if use_cache else 1],)
213
+ all_self_attentions = all_self_attentions + oa
214
+ hidden_states = self.ln_f(hidden_states)
215
+ if output_hidden_states:
216
+ hst = (hidden_states,)
217
+ all_hidden_states = all_hidden_states + hst
218
+ if not return_dict:
219
+ return tuple((v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None))
220
+ return BaseModelOutputWithPastAndCrossAttentions(last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions)
221
+ setattr(model.transformer, '_prepare_attn_mask', MethodType(_prepare_attn_mask, model.transformer))
222
+ setattr(model.transformer, '_build_alibi_tensor', MethodType(_build_alibi_tensor, model.transformer))
223
+ setattr(model.transformer, 'forward', MethodType(forward, model.transformer))
224
+ KeyValueT = Tuple[torch.Tensor, torch.Tensor]
225
+
226
+ def forward(self: BloomForCausalLM, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
227
+ """Replacement forward method for BloomCausalLM."""
228
+ if deprecated_arguments.pop('position_ids', False) is not False:
229
+ warnings.warn('`position_ids` have no functionality in BLOOM and will be removed ' + 'in v5.0.0. You can safely ignore passing `position_ids`.', FutureWarning)
230
+ if len(deprecated_arguments) > 0:
231
+ raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
232
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
233
+ transformer_outputs = self.transformer(input_ids, past_key_values=past_key_values, attention_mask=attention_mask, bidirectional_mask=bidirectional_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
234
+ hidden_states = transformer_outputs[0]
235
+ lm_logits = self.lm_head(hidden_states)
236
+ loss = None
237
+ if labels is not None:
238
+ shift_logits = lm_logits[..., :-1, :].contiguous()
239
+ shift_labels = labels[..., 1:].contiguous()
240
+ (batch_size, seq_length, vocab_size) = shift_logits.shape
241
+ loss_fct = CrossEntropyLoss()
242
+ loss = loss_fct(shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length))
243
+ if not return_dict:
244
+ output = (lm_logits,) + transformer_outputs[1:]
245
+ return (loss,) + output if loss is not None else output
246
+ return CausalLMOutputWithCrossAttentions(loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions)
247
+
248
+ def prepare_inputs_for_generation(self: BloomForCausalLM, input_ids: torch.LongTensor, past: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, **kwargs) -> dict:
249
+ if past:
250
+ input_ids = input_ids[:, -1].unsqueeze(-1)
251
+ bidirectional_mask = None
252
+ if past[0][0].shape[0] == input_ids.shape[0]:
253
+ past = self._convert_to_bloom_cache(past)
254
+ else:
255
+ bidirectional_mask = torch.ones_like(input_ids)
256
+ return {'input_ids': input_ids, 'past_key_values': past, 'use_cache': True, 'attention_mask': attention_mask, 'bidirectional_mask': bidirectional_mask}
257
+ setattr(model, 'forward', MethodType(forward, model))
258
+ setattr(model, 'prepare_inputs_for_generation', MethodType(prepare_inputs_for_generation, model))
259
+ setattr(model, '_prefix_lm_converted', True)
260
+ return model
261
+
262
+ def _convert_opt_causal_lm_to_prefix_lm(model: OPTForCausalLM) -> OPTForCausalLM:
263
+ """Converts an OPT Causal LM to a Prefix LM.
264
+ Supported HuggingFace model classes:
265
+ - `OPTForCausalLM`
266
+ See `convert_hf_causal_lm_to_prefix_lm` for more details.
267
+ """
268
+ if hasattr(model, '_prefix_lm_converted'):
269
+ return model
270
+ assert isinstance(model, OPTForCausalLM)
271
+ assert model.config.add_cross_attention == False, 'Only supports OPT decoder-only models'
272
+ setattr(model, '_original_forward', getattr(model, 'forward'))
273
+ setattr(model, '_original_generate', getattr(model, 'generate'))
274
+ model.model.decoder.bidirectional_mask = None
275
+
276
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
277
+ combined_attention_mask = None
278
+ if input_shape[-1] > 1:
279
+ if self.bidirectional_mask == 'g':
280
+ (bsz, src_length) = input_shape
281
+ combined_attention_mask = torch.zeros((bsz, 1, src_length, src_length + past_key_values_length), dtype=inputs_embeds.dtype, device=inputs_embeds.device)
282
+ else:
283
+ combined_attention_mask = _make_causal_mask_opt(input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length).to(inputs_embeds.device)
284
+ if self.bidirectional_mask is not None:
285
+ assert attention_mask.shape == self.bidirectional_mask.shape
286
+ expanded_bidirectional_mask = _expand_mask_opt(self.bidirectional_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
287
+ combined_attention_mask = torch.maximum(expanded_bidirectional_mask, combined_attention_mask)
288
+ if attention_mask is not None:
289
+ expanded_attn_mask = _expand_mask_opt(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
290
+ combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
291
+ return combined_attention_mask
292
+ setattr(model.model.decoder, '_prepare_decoder_attention_mask', MethodType(_prepare_decoder_attention_mask, model.model.decoder))
293
+
294
+ def forward(self: OPTForCausalLM, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.ByteTensor]=None, head_mask: Optional[torch.Tensor]=None, past_key_values: Optional[List[torch.FloatTensor]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
295
+
296
+ def call_og_forward():
297
+ return self._original_forward(input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
298
+ if bidirectional_mask is None:
299
+ return call_og_forward()
300
+ self.model.decoder.bidirectional_mask = bidirectional_mask
301
+ try:
302
+ outputs = call_og_forward()
303
+ except:
304
+ self.model.decoder.bidirectional_mask = None
305
+ raise
306
+ self.model.decoder.bidirectional_mask = None
307
+ return outputs
308
+
309
+ def generate(self: OPTForCausalLM, *args: tuple, **kwargs: Dict[str, Any]):
310
+ """Wraps original generate to enable PrefixLM-style attention."""
311
+ self.model.decoder.bidirectional_mask = 'g'
312
+ try:
313
+ output = self._original_generate(*args, **kwargs)
314
+ except:
315
+ self.model.decoder.bidirectional_mask = None
316
+ raise
317
+ self.model.decoder.bidirectional_mask = None
318
+ return output
319
+ setattr(model, 'forward', MethodType(forward, model))
320
+ setattr(model, 'generate', MethodType(generate, model))
321
+ setattr(model, '_prefix_lm_converted', True)
322
+ return model
323
+ _SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELS + (BloomForCausalLM, OPTForCausalLM)
324
+ CAUSAL_LM_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM, BloomForCausalLM, OPTForCausalLM]
325
+
326
+ def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:
327
+ """Converts a HuggingFace Causal LM to a Prefix LM.
328
+ Supported HuggingFace model classes:
329
+ - `GPT2LMHeadModel`
330
+ - `GPTNeoForCausalLM`
331
+ - `GPTNeoXForCausalLM`
332
+ - `GPTJForCausalLM`
333
+ - `BloomForCausalLM`
334
+ - `OPTForCausalLM`
335
+ Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the
336
+ `generate` method and/or select underlying methods depending on the model class.
337
+ These changes preserve the model API, but add a new input to `forward`: "bidirectional_mask".
338
+ Notes on training:
339
+ To actually train the converted model as a Prefix LM, training batches will need to indicate
340
+ the prefix/target structure by including `bidirectional_mask` as part of the batch inputs.
341
+ **This is not a standard input and requires custom layers either within or after your dataloader.**
342
+ In addition to adding `bidirectional_mask` to the batch, this custom code should modify `labels`
343
+ such that `batch['labels'][batch['bidirectional_mask'] == 1] == -100`.
344
+ That is, the prefix portion of the sequence should not generate any loss. Loss should only be
345
+ generated by the target portion of the sequence.
346
+ Notes on `GPTNeoForCausalLM`:
347
+ To simplify the implementation, "global" and "local" attention layers are handled differently.
348
+ For "global" layers, we handle conversion as described above. For "local" layers, which use a
349
+ causal attention mask within a restricted local window, we do not alter the masking.
350
+ Notes on `forward` method conversion:
351
+ After conversion, the `forward` method will handle a new input, `bidirectional_mask`,
352
+ which should be a [batch_size, seq_length] byte tensor, where 1 indicates token positions
353
+ belonging to the prefix (prefix tokens can attend to one another bidirectionally), and
354
+ 0 indicates token positions belonging to the target.
355
+ The new `forward` method will incorporate `bidirectional_mask` (if supplied) into the existing
356
+ causal mask, call the original `forward` method, and (if the causal mask is a buffer) reset
357
+ the causal masks before returning the result.
358
+ Notes on `generate` method conversion:
359
+ After conversion, the `generate` method will have the same signature but will internally
360
+ convert all causal masks to be purely bidirectional, call the original `generate` method, and
361
+ (where appropriate) reset the causal masks before returning the result.
362
+ This works thanks to the logic of the HuggingFace `generate` API, which first encodes the token
363
+ "prompt" passed to `generate` (which is treated as the prefix) and then sequentially generates
364
+ each new token. Encodings are cached as generation happens, so all prefix tokens can attend to one
365
+ another (as expected in a Prefix LM) and generated tokens can only attend to prefix tokens and
366
+ previously-generated tokens (also as expected in a Prefix LM).
367
+ To preserve the API, the original methods are renamed to `_original_forward` and
368
+ `_original_generate`, and replaced with new `forward` and `generate` methods that wrap
369
+ them, respectively. Although implementation details vary by model class.
370
+ """
371
+ if isinstance(model, _SUPPORTED_GPT_MODELS):
372
+ return _convert_gpt_causal_lm_to_prefix_lm(model)
373
+ elif isinstance(model, BloomForCausalLM):
374
+ return _convert_bloom_causal_lm_to_prefix_lm(model)
375
+ elif isinstance(model, OPTForCausalLM):
376
+ return _convert_opt_causal_lm_to_prefix_lm(model)
377
+ else:
378
+ raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}')
379
+
380
+ def add_bidirectional_mask_if_missing(batch: Dict[str, Any]):
381
+ """Attempts to add bidirectional_mask to batch if missing.
382
+ Raises:
383
+ KeyError if bidirectional_mask is missing and can't be inferred
384
+ """
385
+ if 'bidirectional_mask' not in batch:
386
+ if batch.get('mode', None) == 'icl_task':
387
+ batch['bidirectional_mask'] = batch['attention_mask'].clone()
388
+ for (i, continuation_indices) in enumerate(batch['continuation_indices']):
389
+ batch['bidirectional_mask'][i, continuation_indices] = 0
390
+ elif 'labels' in batch and 'attention_mask' in batch:
391
+ batch['bidirectional_mask'] = torch.logical_and(torch.eq(batch['attention_mask'], 1), torch.eq(batch['labels'], -100)).type_as(batch['attention_mask'])
392
+ else:
393
+ raise KeyError('No bidirectional_mask in batch and not sure how to construct one.')