-
Notifications
You must be signed in to change notification settings - Fork 305
/
transformers.py
2369 lines (1932 loc) · 82.8 KB
/
transformers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import abc
import argparse
import gc
import itertools
import os
from typing import List, Optional
import numpy as np
try:
import huggingface_hub
import torch
import transformers
except ImportError:
pass
from ctranslate2.converters import utils
from ctranslate2.converters.converter import Converter
from ctranslate2.specs import (
attention_spec,
common_spec,
model_spec,
transformer_spec,
wav2vec2_spec,
whisper_spec,
)
_SUPPORTED_ACTIVATIONS = {
"gelu": common_spec.Activation.GELU,
"gelu_fast": common_spec.Activation.GELUTanh,
"gelu_new": common_spec.Activation.GELUTanh,
"gelu_python": common_spec.Activation.GELU,
"gelu_pytorch_tanh": common_spec.Activation.GELUTanh,
"quick_gelu": common_spec.Activation.GELUSigmoid,
"relu": common_spec.Activation.RELU,
"silu": common_spec.Activation.SWISH,
"swish": common_spec.Activation.SWISH,
}
_SUPPORTED_ROPE_SCALING = {
"linear": attention_spec.RotaryScalingType.Linear,
"su": attention_spec.RotaryScalingType.Su,
}
_MODEL_LOADERS = {}
def register_loader(config_name):
"""Registers a model loader for this configuration name."""
def decorator(cls):
_MODEL_LOADERS[config_name] = cls()
return cls
return decorator
class TransformersConverter(Converter):
"""Converts models from Hugging Face Transformers."""
def __init__(
self,
model_name_or_path: str,
activation_scales: Optional[str] = None,
copy_files: Optional[List[str]] = None,
load_as_float16: bool = False,
revision: Optional[str] = None,
low_cpu_mem_usage: bool = False,
trust_remote_code: bool = False,
):
"""Initializes the converter.
Arguments:
model_name_or_path: Name of the pretrained model to download, or path to the
directory containing the pretrained model.
activation_scales: Path to the pre-computed activation scales. Models may
use them to rescale some weights to smooth the intermediate activations
and improve the quantization accuracy. See
https://github.com/mit-han-lab/smoothquant.
copy_files: List of filenames to copy from the Hugging Face model to the
converted model directory.
load_as_float16: Load the model weights as float16. More precisely, the model
will be loaded with ``from_pretrained(..., torch_dtype=torch.float16)``.
revision: Revision of the model to download from the Hugging Face Hub.
low_cpu_mem_usage: Enable the flag ``low_cpu_mem_usage`` when loading the model
with ``from_pretrained``.
trust_remote_code: Allow converting models using custom code.
"""
self._model_name_or_path = model_name_or_path
self._activation_scales = activation_scales
self._copy_files = copy_files
self._load_as_float16 = load_as_float16
self._revision = revision
self._low_cpu_mem_usage = low_cpu_mem_usage
self._trust_remote_code = trust_remote_code
def _load(self):
with torch.no_grad():
config = transformers.AutoConfig.from_pretrained(
self._model_name_or_path, trust_remote_code=self._trust_remote_code
)
config_name = config.__class__.__name__
loader = _MODEL_LOADERS.get(config_name)
if loader is None:
raise ValueError(
"No conversion is registered for the model configuration %s "
"(supported configurations are: %s)"
% (config_name, ", ".join(sorted(_MODEL_LOADERS.keys())))
)
model_class = getattr(transformers, loader.architecture_name)
tokenizer_class = transformers.AutoTokenizer
kwargs = {
"torch_dtype": (
torch.float16
if self._load_as_float16
else getattr(config, "torch_dtype", None)
)
}
if self._revision:
kwargs["revision"] = self._revision
if self._low_cpu_mem_usage:
kwargs["low_cpu_mem_usage"] = self._low_cpu_mem_usage
if self._trust_remote_code:
kwargs["trust_remote_code"] = self._trust_remote_code
model = self.load_model(model_class, self._model_name_or_path, **kwargs)
tokenizer_kwargs = {}
if self._trust_remote_code:
tokenizer_kwargs["trust_remote_code"] = self._trust_remote_code
tokenizer = self.load_tokenizer(
tokenizer_class, self._model_name_or_path, **tokenizer_kwargs
)
spec = loader(model, tokenizer)
if self._activation_scales:
activation_scales = torch.load(
self._activation_scales, map_location="cpu"
)
loader.smooth_activation(spec, activation_scales)
if self._copy_files:
for filename in self._copy_files:
spec.register_file(self.get_model_file(filename))
return spec
def load_model(self, model_class, model_name_or_path, **kwargs):
return model_class.from_pretrained(model_name_or_path, **kwargs)
def load_tokenizer(self, tokenizer_class, model_name_or_path, **kwargs):
return tokenizer_class.from_pretrained(model_name_or_path, **kwargs)
def get_model_file(self, filename):
if os.path.isdir(self._model_name_or_path):
path = os.path.join(self._model_name_or_path, filename)
else:
try:
path = huggingface_hub.hf_hub_download(
repo_id=self._model_name_or_path, filename=filename
)
except huggingface_hub.utils.EntryNotFoundError:
path = None
if path is None or not os.path.isfile(path):
raise ValueError(
"File %s does not exist in model %s"
% (filename, self._model_name_or_path)
)
return path
class ModelLoader(abc.ABC):
"""Base class for loading Transformers models into a CTranslate2 model specification."""
@property
def architecture_name(self):
return None
@abc.abstractmethod
def get_model_spec(self, model):
raise NotImplementedError()
def __call__(self, model, tokenizer):
spec = self.get_model_spec(model)
self.set_config(spec.config, model, tokenizer)
tokens = self.get_vocabulary(model, tokenizer)
self.set_vocabulary(spec, tokens)
return spec
def get_vocabulary(self, model, tokenizer):
return [
token
for token, _ in sorted(
tokenizer.get_vocab().items(), key=lambda item: item[1]
)
]
def set_vocabulary(self, spec, tokens):
pass
def set_config(self, config, model, tokenizer):
pass
def set_layer_norm(self, spec, module):
spec.gamma = module.weight
spec.beta = module.bias
def set_linear(self, spec, module):
spec.weight = module.weight
if isinstance(module, transformers.Conv1D):
spec.weight = spec.weight.transpose(0, 1)
if module.bias is not None:
spec.bias = module.bias
def set_embeddings(self, spec, module):
spec.weight = module.weight
def set_position_encodings(self, spec, module):
spec.encodings = module.weight
offset = getattr(module, "offset", 0)
if offset > 0:
spec.encodings = spec.encodings[offset:]
def smooth_activation(self, spec, activation_scales):
raise NotImplementedError(
"No activation smoothing logic is defined for this model"
)
@register_loader("BartConfig")
class BartLoader(ModelLoader):
@property
def architecture_name(self):
return "BartForConditionalGeneration"
def get_model_spec(self, model):
spec = transformer_spec.TransformerSpec.from_config(
(model.config.encoder_layers, model.config.decoder_layers),
model.config.encoder_attention_heads,
pre_norm=model.config.normalize_before,
activation=_SUPPORTED_ACTIVATIONS[model.config.activation_function],
layernorm_embedding=getattr(model.config, "normalize_embedding", True),
)
self.set_encoder(spec.encoder, model.model.encoder)
self.set_decoder(spec.decoder, model.model.decoder)
self.set_linear(spec.decoder.projection, model.lm_head)
final_logits_bias = getattr(model, "final_logits_bias", None)
if final_logits_bias is not None and final_logits_bias.nonzero().numel() != 0:
spec.decoder.projection.bias = final_logits_bias.squeeze()
return spec
def get_vocabulary(self, model, tokenizer):
tokens = super().get_vocabulary(model, tokenizer)
if model.config.vocab_size < len(tokens):
tokens = tokens[: model.config.vocab_size]
return tokens
def set_vocabulary(self, spec, tokens):
spec.register_source_vocabulary(tokens)
spec.register_target_vocabulary(tokens)
def set_config(self, config, model, tokenizer):
config.bos_token = tokenizer.bos_token
config.eos_token = tokenizer.eos_token
config.unk_token = tokenizer.unk_token
config.decoder_start_token = tokenizer.convert_ids_to_tokens(
model.config.decoder_start_token_id
)
def set_encoder(self, spec, encoder):
self.set_common_layers(spec, encoder)
for layer_spec, layer in zip(spec.layer, encoder.layers):
self.set_attention(
layer_spec.self_attention,
layer.self_attn,
self_attention=True,
)
self.set_layer_norm(
layer_spec.self_attention.layer_norm,
layer.self_attn_layer_norm,
)
self.set_linear(layer_spec.ffn.linear_0, layer.fc1)
self.set_linear(layer_spec.ffn.linear_1, layer.fc2)
self.set_layer_norm(layer_spec.ffn.layer_norm, layer.final_layer_norm)
def set_decoder(self, spec, decoder):
self.set_common_layers(spec, decoder)
for layer_spec, layer in zip(spec.layer, decoder.layers):
self.set_attention(
layer_spec.self_attention,
layer.self_attn,
self_attention=True,
)
self.set_layer_norm(
layer_spec.self_attention.layer_norm,
layer.self_attn_layer_norm,
)
if hasattr(layer, "encoder_attn"):
self.set_attention(
layer_spec.attention,
layer.encoder_attn,
self_attention=False,
)
self.set_layer_norm(
layer_spec.attention.layer_norm,
layer.encoder_attn_layer_norm,
)
self.set_linear(layer_spec.ffn.linear_0, layer.fc1)
self.set_linear(layer_spec.ffn.linear_1, layer.fc2)
self.set_layer_norm(layer_spec.ffn.layer_norm, layer.final_layer_norm)
def set_attention(self, spec, attention, self_attention=False):
split_layers = [common_spec.LinearSpec() for _ in range(3)]
self.set_linear(split_layers[0], attention.q_proj)
self.set_linear(split_layers[1], attention.k_proj)
self.set_linear(split_layers[2], attention.v_proj)
if self_attention:
utils.fuse_linear(spec.linear[0], split_layers)
else:
utils.fuse_linear(spec.linear[0], split_layers[:1])
utils.fuse_linear(spec.linear[1], split_layers[1:])
self.set_linear(spec.linear[-1], attention.out_proj)
def set_common_layers(self, spec, module):
spec.scale_embeddings = module.embed_scale
self.set_position_encodings(spec.position_encodings, module.embed_positions)
self.set_embeddings(
(
spec.embeddings[0]
if isinstance(spec.embeddings, list)
else spec.embeddings
),
module.embed_tokens,
)
if hasattr(module, "layer_norm"):
self.set_layer_norm(spec.layer_norm, module.layer_norm)
if hasattr(module, "layernorm_embedding"):
self.set_layer_norm(spec.layernorm_embedding, module.layernorm_embedding)
@register_loader("MarianConfig")
class MarianMTLoader(BartLoader):
@property
def architecture_name(self):
return "MarianMTModel"
def get_model_spec(self, model):
model.config.normalize_before = False
model.config.normalize_embedding = False
spec = super().get_model_spec(model)
self._remove_pad_weights(spec)
return spec
def set_config(self, config, model, tokenizer):
config.eos_token = tokenizer.eos_token
config.unk_token = tokenizer.unk_token
# The decoder start token can be any token because the decoder always starts
# from a zero embedding.
config.decoder_start_token = tokenizer.eos_token
def set_decoder(self, spec, decoder):
spec.start_from_zero_embedding = True
super().set_decoder(spec, decoder)
def get_vocabulary(self, model, tokenizer):
# The <pad> token is added by Transformers to start the decoder from a zero embedding,
# but we already have a dedicated option "start_from_zero_embedding". We remove this token
# to match the original Marian vocabulary and prevent this token from being generated.
tokens = super().get_vocabulary(model, tokenizer)
if tokens[-1] == "<pad>":
tokens.pop()
return tokens
def _remove_pad_weights(self, spec):
vocab_specs = [
spec.encoder.embeddings[0],
spec.decoder.embeddings,
spec.decoder.projection,
]
# Weights may be shared so we check against the expected size to prevent
# updating the same weight multiple times.
new_vocab_size = vocab_specs[0].weight.shape[0] - 1
for vocab_spec in vocab_specs:
if vocab_spec.weight.shape[0] == new_vocab_size + 1:
vocab_spec.weight = vocab_spec.weight[:-1]
if (
isinstance(vocab_spec, common_spec.LinearSpec)
and vocab_spec.has_bias()
and vocab_spec.bias.shape[0] == new_vocab_size + 1
):
vocab_spec.bias = vocab_spec.bias[:-1]
@register_loader("M2M100Config")
class M2M100Loader(BartLoader):
@property
def architecture_name(self):
return "M2M100ForConditionalGeneration"
def get_model_spec(self, model):
model.config.normalize_before = True
model.config.normalize_embedding = False
return super().get_model_spec(model)
def set_position_encodings(self, spec, module):
spec.encodings = module.weights[module.offset :]
def get_vocabulary(self, model, tokenizer):
tokens = super().get_vocabulary(model, tokenizer)
# Workaround for issue https://github.com/OpenNMT/CTranslate2/issues/1039.
if tokens[-1] == tokenizer.unk_token:
tokens.insert(tokenizer.unk_token_id, tokens.pop())
for token in tokenizer.additional_special_tokens:
if token not in tokens:
tokens.append(token)
num_madeup_words = getattr(
tokenizer, "num_madeup_words", model.config.vocab_size - len(tokens)
)
if num_madeup_words > 0:
tokens += ["madeupword%d" % i for i in range(num_madeup_words)]
return tokens
@register_loader("MBartConfig")
class MBartLoader(BartLoader):
@property
def architecture_name(self):
return "MBartForConditionalGeneration"
def set_config(self, config, model, tokenizer):
config.bos_token = tokenizer.bos_token
config.eos_token = tokenizer.eos_token
config.unk_token = tokenizer.unk_token
# MBart-25 passes the language code as the decoder start token.
if model.config.tokenizer_class in ("MBartTokenizer", None):
config.decoder_start_token = None
else:
config.decoder_start_token = tokenizer.eos_token
@register_loader("PegasusConfig")
class PegasusLoader(BartLoader):
@property
def architecture_name(self):
return "PegasusForConditionalGeneration"
def set_config(self, config, model, tokenizer):
config.bos_token = tokenizer.pad_token
config.eos_token = tokenizer.eos_token
config.unk_token = tokenizer.unk_token
config.decoder_start_token = tokenizer.pad_token
@register_loader("OPTConfig")
class OPTLoader(BartLoader):
@property
def architecture_name(self):
return "OPTForCausalLM"
def get_model_spec(self, model):
spec = transformer_spec.TransformerDecoderModelSpec.from_config(
model.config.num_hidden_layers,
model.config.num_attention_heads,
pre_norm=model.config.do_layer_norm_before,
activation=_SUPPORTED_ACTIVATIONS[model.config.activation_function],
project_in_out=model.config.word_embed_proj_dim != model.config.hidden_size,
)
self.set_decoder(spec.decoder, model.model.decoder)
self.set_linear(spec.decoder.projection, model.lm_head)
return spec
def smooth_activation(self, spec, activation_scales):
for i, layer in enumerate(spec.decoder.layer):
layer_scope = "model.decoder.layers.%d" % i
utils.smooth_activation(
layer.self_attention.layer_norm,
layer.self_attention.linear[0],
activation_scales["%s.self_attn.q_proj" % layer_scope],
)
utils.smooth_activation(
layer.ffn.layer_norm,
layer.ffn.linear_0,
activation_scales["%s.fc1" % layer_scope],
)
def set_vocabulary(self, spec, tokens):
spec.register_vocabulary(tokens)
def set_config(self, config, model, tokenizer):
config.bos_token = tokenizer.bos_token
config.eos_token = tokenizer.eos_token
config.unk_token = tokenizer.unk_token
def set_decoder(self, spec, decoder):
super().set_decoder(spec, decoder)
if decoder.project_in is not None:
self.set_linear(spec.project_in, decoder.project_in)
if decoder.project_out is not None:
self.set_linear(spec.project_out, decoder.project_out)
if decoder.final_layer_norm is not None:
self.set_layer_norm(spec.layer_norm, decoder.final_layer_norm)
def set_common_layers(self, spec, module):
spec.scale_embeddings = False
self.set_position_encodings(spec.position_encodings, module.embed_positions)
self.set_embeddings(spec.embeddings, module.embed_tokens)
def get_vocabulary(self, model, tokenizer):
tokens = super().get_vocabulary(model, tokenizer)
i = 0
while len(tokens) % 8 != 0:
symbol = "madeupword{:04d}".format(i)
if symbol not in tokens:
tokens.append(symbol)
i += 1
return tokens
@register_loader("GPTBigCodeConfig")
class GPTBigCodeMHALoader(ModelLoader):
@property
def architecture_name(self):
return "GPTBigCodeForCausalLM"
def get_model_spec(self, model):
spec = transformer_spec.TransformerDecoderModelSpec.from_config(
model.config.n_layer,
model.config.n_head,
pre_norm=True,
activation=_SUPPORTED_ACTIVATIONS[model.config.activation_function],
multi_query_attention=True,
)
self.set_decoder(spec.decoder, model.transformer)
self.set_linear(spec.decoder.projection, model.lm_head)
return spec
def set_vocabulary(self, spec, tokens):
spec.register_vocabulary(tokens)
def get_vocabulary(self, model, tokenizer):
tokens = super().get_vocabulary(model, tokenizer)
extra_ids = model.config.vocab_size - len(tokens)
for i in range(extra_ids):
tokens.append("<extra_id_%d>" % i)
return tokens
def set_config(self, config, model, tokenizer):
config.bos_token = tokenizer.bos_token
config.eos_token = tokenizer.eos_token
config.unk_token = tokenizer.unk_token
def set_decoder(self, spec, module):
spec.scale_embeddings = False
self.set_embeddings(spec.embeddings, module.wte)
self.set_position_encodings(spec.position_encodings, module.wpe)
self.set_layer_norm(spec.layer_norm, module.ln_f)
for layer_spec, layer in zip(spec.layer, module.h):
self.set_layer_norm(layer_spec.self_attention.layer_norm, layer.ln_1)
self.set_linear(layer_spec.self_attention.linear[0], layer.attn.c_attn)
self.set_linear(layer_spec.self_attention.linear[1], layer.attn.c_proj)
self.set_layer_norm(layer_spec.ffn.layer_norm, layer.ln_2)
self.set_linear(layer_spec.ffn.linear_0, layer.mlp.c_fc)
self.set_linear(layer_spec.ffn.linear_1, layer.mlp.c_proj)
@register_loader("GPT2Config")
class GPT2Loader(ModelLoader):
@property
def architecture_name(self):
return "GPT2LMHeadModel"
def get_model_spec(self, model):
spec = transformer_spec.TransformerDecoderModelSpec.from_config(
model.config.n_layer,
model.config.n_head,
pre_norm=True,
activation=_SUPPORTED_ACTIVATIONS[model.config.activation_function],
)
self.set_decoder(spec.decoder, model.transformer)
self.set_linear(spec.decoder.projection, model.lm_head)
return spec
def set_vocabulary(self, spec, tokens):
spec.register_vocabulary(tokens)
def set_config(self, config, model, tokenizer):
config.bos_token = tokenizer.bos_token
config.eos_token = tokenizer.eos_token
config.unk_token = tokenizer.unk_token
def set_decoder(self, spec, module):
spec.scale_embeddings = False
self.set_embeddings(spec.embeddings, module.wte)
self.set_position_encodings(spec.position_encodings, module.wpe)
self.set_layer_norm(spec.layer_norm, module.ln_f)
for layer_spec, layer in zip(spec.layer, module.h):
self.set_layer_norm(layer_spec.self_attention.layer_norm, layer.ln_1)
self.set_linear(layer_spec.self_attention.linear[0], layer.attn.c_attn)
self.set_linear(layer_spec.self_attention.linear[1], layer.attn.c_proj)
self.set_layer_norm(layer_spec.ffn.layer_norm, layer.ln_2)
self.set_linear(layer_spec.ffn.linear_0, layer.mlp.c_fc)
self.set_linear(layer_spec.ffn.linear_1, layer.mlp.c_proj)
@register_loader("GPTJConfig")
class GPTJLoader(ModelLoader):
@property
def architecture_name(self):
return "GPTJForCausalLM"
def get_model_spec(self, model):
spec = transformer_spec.TransformerDecoderModelSpec.from_config(
model.config.n_layer,
model.config.n_head,
pre_norm=True,
activation=_SUPPORTED_ACTIVATIONS[model.config.activation_function],
rotary_dim=model.config.rotary_dim,
rotary_interleave=False,
parallel_residual=True,
shared_layer_norm=True,
)
self.set_decoder(
spec.decoder,
model.transformer,
model.config.rotary_dim,
model.config.n_head,
)
self.set_linear(spec.decoder.projection, model.lm_head)
return spec
def set_vocabulary(self, spec, tokens):
spec.register_vocabulary(tokens)
def set_config(self, config, model, tokenizer):
config.bos_token = tokenizer.bos_token
config.eos_token = tokenizer.eos_token
config.unk_token = tokenizer.unk_token
def set_decoder(self, spec, module, rotary_dim, num_heads):
spec.scale_embeddings = False
self.set_embeddings(spec.embeddings, module.wte)
self.set_layer_norm(spec.layer_norm, module.ln_f)
for layer_spec, layer in zip(spec.layer, module.h):
self.set_layer_norm(layer_spec.shared_layer_norm, layer.ln_1)
qw = layer.attn.q_proj.weight
kw = layer.attn.k_proj.weight
vw = layer.attn.v_proj.weight
qw = utils.permute_for_sliced_rotary(qw, num_heads, rotary_dim)
kw = utils.permute_for_sliced_rotary(kw, num_heads, rotary_dim)
layer_spec.self_attention.linear[0].weight = torch.cat((qw, kw, vw))
self.set_linear(layer_spec.self_attention.linear[1], layer.attn.out_proj)
self.set_linear(layer_spec.ffn.linear_0, layer.mlp.fc_in)
self.set_linear(layer_spec.ffn.linear_1, layer.mlp.fc_out)
@register_loader("CodeGenConfig")
class CodeGenLoader(ModelLoader):
@property
def architecture_name(self):
return "CodeGenForCausalLM"
def get_model_spec(self, model):
spec = transformer_spec.TransformerDecoderModelSpec.from_config(
model.config.n_layer,
model.config.n_head,
pre_norm=True,
activation=_SUPPORTED_ACTIVATIONS[model.config.activation_function],
rotary_dim=model.config.rotary_dim,
rotary_interleave=False,
parallel_residual=True,
shared_layer_norm=True,
)
mp_num = 4
if hasattr(model.config, "head_dim") and model.config.head_dim in [128, 256]:
# models forked from "Salesforce/codegen2-1B" and "Salesforce/codegen2-3_7B"
# use a special setting of mp_num=8, all other using 4
# these model.config's use a special setting of head_dim
mp_num = 8
self.set_decoder(
spec.decoder,
model.transformer,
model.config.rotary_dim,
model.config.n_head,
model.config.n_embd,
mp_num=mp_num,
)
self.set_linear(spec.decoder.projection, model.lm_head)
return spec
def get_vocabulary(self, model, tokenizer):
tokens = super().get_vocabulary(model, tokenizer)
extra_ids = model.config.vocab_size - len(tokens)
for i in range(extra_ids):
# fix for additional vocab, see GPTNeoX Converter
tokens.append("<extra_id_%d>" % i)
return tokens
def set_vocabulary(self, spec, tokens):
spec.register_vocabulary(tokens)
def set_config(self, config, model, tokenizer):
config.bos_token = tokenizer.bos_token
config.eos_token = tokenizer.eos_token
config.unk_token = tokenizer.unk_token
def set_decoder(self, spec, module, rotary_dim, num_heads, embed_dim, mp_num):
spec.scale_embeddings = False
self.set_embeddings(spec.embeddings, module.wte)
self.set_layer_norm(spec.layer_norm, module.ln_f)
base_permutation = np.arange(0, mp_num * 3).reshape(-1, 3).T.flatten().tolist()
local_dim = embed_dim // mp_num
permutation = torch.cat(
[torch.arange(i * local_dim, (i + 1) * local_dim) for i in base_permutation]
)
for layer_spec, layer in zip(spec.layer, module.h):
self.set_layer_norm(layer_spec.shared_layer_norm, layer.ln_1)
# [start convert CodeGen to GPT-J format]
# see https://github.com/fauxpilot/fauxpilot/blob/fb4073a9078dd001ebeb7dfefb8cb2ecc8a88f4b/converter/codegen_gptj_convert.py # noqa
qkv_proj = layer.attn.qkv_proj.weight
# GPT-J and CodeGen slice up the qkv projection slightly differently.
# the following permutation brings Codegen 'qkv_proj'
# in GPT-J order of qw, vw, kw
# we permute the *rows* here because the computation is xA.T
new_qkv_proj = qkv_proj[permutation, :]
# the name QKV is misleading here; they are actually stored in QVK
qw, vw, kw = new_qkv_proj.chunk(3, dim=0)
# [end convert CodeGen to GPT-J.]
qw = utils.permute_for_sliced_rotary(qw, num_heads, rotary_dim)
kw = utils.permute_for_sliced_rotary(kw, num_heads, rotary_dim)
layer_spec.self_attention.linear[0].weight = torch.cat((qw, kw, vw))
self.set_linear(layer_spec.self_attention.linear[1], layer.attn.out_proj)
self.set_linear(layer_spec.ffn.linear_0, layer.mlp.fc_in)
self.set_linear(layer_spec.ffn.linear_1, layer.mlp.fc_out)
@register_loader("GPTNeoXConfig")
class GPTNeoXLoader(ModelLoader):
@property
def architecture_name(self):
return "GPTNeoXForCausalLM"
def get_model_spec(self, model):
spec = transformer_spec.TransformerDecoderModelSpec.from_config(
model.config.num_hidden_layers,
model.config.num_attention_heads,
pre_norm=True,
activation=_SUPPORTED_ACTIVATIONS[model.config.hidden_act],
rotary_dim=int(
model.config.rotary_pct
* (model.config.hidden_size // model.config.num_attention_heads)
),
rotary_interleave=False,
parallel_residual=model.config.use_parallel_residual,
shared_layer_norm=False,
)
self.set_decoder(spec.decoder, model.gpt_neox, model.config.num_attention_heads)
self.set_linear(spec.decoder.projection, model.embed_out)
return spec
def get_vocabulary(self, model, tokenizer):
tokens = super().get_vocabulary(model, tokenizer)
extra_ids = model.config.vocab_size - len(tokens)
for i in range(extra_ids):
tokens.append("<extra_id_%d>" % i)
return tokens
def set_vocabulary(self, spec, tokens):
spec.register_vocabulary(tokens)
def set_config(self, config, model, tokenizer):
config.bos_token = tokenizer.bos_token
config.eos_token = tokenizer.eos_token
config.unk_token = tokenizer.unk_token
def set_decoder(self, spec, module, num_heads):
spec.scale_embeddings = False
self.set_embeddings(spec.embeddings, module.embed_in)
self.set_layer_norm(spec.layer_norm, module.final_layer_norm)
for layer_spec, layer in zip(spec.layer, module.layers):
if hasattr(layer_spec, "input_layer_norm"): # Use parallel residual.
self.set_layer_norm(layer_spec.input_layer_norm, layer.input_layernorm)
self.set_layer_norm(
layer_spec.post_attention_layer_norm, layer.post_attention_layernorm
)
else:
self.set_layer_norm(
layer_spec.self_attention.layer_norm, layer.input_layernorm
)
self.set_layer_norm(
layer_spec.ffn.layer_norm, layer.post_attention_layernorm
)
qkv_w = layer.attention.query_key_value.weight
qkv_b = layer.attention.query_key_value.bias
qkv_w = (
qkv_w.reshape(num_heads, 3, -1, qkv_w.shape[-1])
.swapaxes(0, 1)
.reshape(-1, qkv_w.shape[-1])
)
qkv_b = qkv_b.reshape(num_heads, 3, -1).swapaxes(0, 1).reshape(-1)
layer_spec.self_attention.linear[0].weight = qkv_w
layer_spec.self_attention.linear[0].bias = qkv_b
self.set_linear(layer_spec.self_attention.linear[1], layer.attention.dense)
self.set_linear(layer_spec.ffn.linear_0, layer.mlp.dense_h_to_4h)
self.set_linear(layer_spec.ffn.linear_1, layer.mlp.dense_4h_to_h)
@register_loader("WhisperConfig")
class WhisperLoader(BartLoader):
@property
def architecture_name(self):
return "WhisperForConditionalGeneration"
def get_model_spec(self, model):
spec = whisper_spec.WhisperSpec(
model.config.encoder_layers,
model.config.encoder_attention_heads,
model.config.decoder_layers,
model.config.decoder_attention_heads,
)
self.set_encoder(spec.encoder, model.model.encoder)
self.set_decoder(spec.decoder, model.model.decoder)
self.set_linear(spec.decoder.projection, model.proj_out)
return spec
def _get_lang_ids_from_tokenizer(self, tokenizer):
non_lang_special_tokens = [
"<|endoftext|>",
"<|startoftranscript|>",
"<|translate|>",
"<|transcribe|>",
"<|startoflm|>",
"<|startofprev|>",
"<|nocaptions|>",
"<|notimestamps|>",
]
return [
token_id
for token_id, token in zip(
tokenizer.additional_special_tokens_ids,
tokenizer.additional_special_tokens,
)
if token not in non_lang_special_tokens
]
def set_config(self, config, model, tokenizer):
gen_config = getattr(model, "generation_config", None)
if gen_config is not None:
config.suppress_ids = gen_config.suppress_tokens
config.suppress_ids_begin = gen_config.begin_suppress_tokens
if hasattr(gen_config, "alignment_heads"):
config.alignment_heads = gen_config.alignment_heads
if hasattr(gen_config, "lang_to_id"):
config.lang_ids = sorted(gen_config.lang_to_id.values())
else:
config.suppress_ids = model.config.suppress_tokens
config.suppress_ids_begin = model.config.begin_suppress_tokens
config.alignment_heads = _WHISPER_ALIGNMENT_HEADS.get(model.name_or_path)
if getattr(config, "lang_ids", None) is None:
config.lang_ids = self._get_lang_ids_from_tokenizer(tokenizer)
if config.alignment_heads is None:
# Use the last half layers for alignment by default.
num_layers = model.config.decoder_layers
num_heads = model.config.decoder_attention_heads
config.alignment_heads = list(
itertools.product(
range(num_layers // 2, num_layers),
range(num_heads),
)
)
def get_vocabulary(self, model, tokenizer):
tokens = super().get_vocabulary(model, tokenizer)
# Add timestamp tokens.
tokens.extend(
"<|%.2f|>" % (i * 0.02)
for i in range(model.config.vocab_size - len(tokens))
)
return tokens
def set_vocabulary(self, spec, tokens):
spec.register_vocabulary(tokens)
def set_encoder(self, spec, encoder):
self.set_conv1d(spec.conv1, encoder.conv1)
self.set_conv1d(spec.conv2, encoder.conv2)
super().set_encoder(spec, encoder)
def set_decoder(self, spec, decoder):
self.set_embeddings(spec.embeddings, decoder.embed_tokens)
super().set_decoder(spec, decoder)
def set_common_layers(self, spec, module):
self.set_position_encodings(spec.position_encodings, module.embed_positions)
self.set_layer_norm(spec.layer_norm, module.layer_norm)
def set_conv1d(self, spec, module):
spec.weight = module.weight
spec.bias = module.bias
@register_loader("Wav2Vec2Config")
class Wav2Vec2Loader(BartLoader):
@property
def architecture_name(self):
return "Wav2Vec2ForCTC"
def get_model_spec(self, model):
# Wav2Vec2 encoder Wav2Vec2PositionalConvEmbedding conv1d has groups 16
# that doesn't look available here so we make Wav2Vec2 encoder layers only
spec = wav2vec2_spec.Wav2Vec2Spec(
model.wav2vec2.encoder.config.num_hidden_layers,
model.wav2vec2.encoder.config.num_attention_heads,
)
# layer component name matching (no duplications saving)
for layer in model.wav2vec2.encoder.layers:
layer.self_attn = layer.attention
layer.self_attn_layer_norm = layer.layer_norm
layer.activation_fn = layer.feed_forward.intermediate_act_fn
layer.fc1 = layer.feed_forward.intermediate_dense
layer.fc2 = layer.feed_forward.output_dense
self.set_encoder(spec.encoder, model.wav2vec2.encoder)
self.set_linear(spec.lm_head, model.lm_head)
# only for Wav2Vec2Spec.get_vocabulary_size()