namednil commited on
Commit
b0e8c81
·
verified ·
1 Parent(s): ee6cd0c

Upload 2 files

Browse files
Files changed (2) hide show
  1. config.json +69 -0
  2. step_finetune.py +124 -0
config.json ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "STEPFinetuningModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "step_finetune.STEPFinetuningModelConfig",
7
+ "AutoModel": "step_finetune.STEPFinetuningModel",
8
+ "AutoModelForSeq2SeqLM": "step_finetune.STEPFinetuningModel"
9
+ },
10
+ "classifier_dropout": 0.0,
11
+ "d_ff": 3072,
12
+ "d_kv": 64,
13
+ "d_model": 768,
14
+ "decoder_start_token_id": 0,
15
+ "dense_act_fn": "relu",
16
+ "dropout_rate": 0.1,
17
+ "eos_token_id": 1,
18
+ "feed_forward_proj": "relu",
19
+ "initializer_factor": 1.0,
20
+ "is_encoder_decoder": true,
21
+ "is_gated_act": false,
22
+ "layer_norm_epsilon": 1e-06,
23
+ "model_type": "STEP_finetuning",
24
+ "n_positions": 512,
25
+ "num_decoder_layers": 12,
26
+ "num_heads": 12,
27
+ "num_layers": 12,
28
+ "output_past": true,
29
+ "pad_token_id": 0,
30
+ "relative_attention_max_distance": 128,
31
+ "relative_attention_num_buckets": 32,
32
+ "task_specific_params": {
33
+ "summarization": {
34
+ "early_stopping": true,
35
+ "length_penalty": 2.0,
36
+ "max_length": 200,
37
+ "min_length": 30,
38
+ "no_repeat_ngram_size": 3,
39
+ "num_beams": 4,
40
+ "prefix": "summarize: "
41
+ },
42
+ "translation_en_to_de": {
43
+ "early_stopping": true,
44
+ "max_length": 300,
45
+ "num_beams": 4,
46
+ "prefix": "translate English to German: "
47
+ },
48
+ "translation_en_to_fr": {
49
+ "early_stopping": true,
50
+ "max_length": 300,
51
+ "num_beams": 4,
52
+ "prefix": "translate English to French: "
53
+ },
54
+ "translation_en_to_ro": {
55
+ "early_stopping": true,
56
+ "max_length": 300,
57
+ "num_beams": 4,
58
+ "prefix": "translate English to Romanian: "
59
+ }
60
+ },
61
+ "transformers_version": "4.38.1",
62
+ "use_cache": true,
63
+ "vocab_size": 32128,
64
+ "num_precomputed_examples": 1000,
65
+ "num_examples": 512,
66
+ "prefix_length": 10,
67
+ "prefix_max_init_length": 20,
68
+ "random_selection": true
69
+ }
step_finetune.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoTokenizer, PretrainedConfig, T5Config, PreTrainedModel, T5ForConditionalGeneration, \
3
+ AutoModelForSeq2SeqLM, Adafactor
4
+
5
+ from typing import Optional, List, Callable, Mapping, Any, Union
6
+ import os
7
+
8
+ class STEPFinetuningModelConfig(T5Config):
9
+ model_type = "STEP_finetune"
10
+
11
+ def __init__(self,
12
+ num_examples: int = 512,
13
+ prefix_length: int = 10,
14
+ random_selection: bool = True,
15
+ # don't change these unless you change what the prefix of the model is initialized with:
16
+ prefix_max_init_length: int = 20,
17
+ num_precomputed_examples: int = 1000,
18
+ **kwargs):
19
+ # These are all about the initialization of the prefix.
20
+ self.num_examples = num_examples
21
+ self.prefix_length = prefix_length
22
+ self.random_selection = random_selection
23
+ self.prefix_max_init_length = prefix_max_init_length
24
+ self.num_precomputed_examples = num_precomputed_examples
25
+ super().__init__(**kwargs)
26
+
27
+
28
+
29
+ class STEPFinetuningModel(PreTrainedModel):
30
+ config_class = STEPFinetuningModelConfig
31
+
32
+ def __init__(self, config: STEPFinetuningModelConfig):
33
+ super().__init__(config)
34
+
35
+ self.model = T5ForConditionalGeneration(config)
36
+
37
+ # Initialize the prefix with NaNs.
38
+ self.register_buffer("prefix_init_tensor", torch.zeros(config.num_precomputed_examples, config.prefix_max_init_length, config.d_model))
39
+
40
+ # There are two cases: (1) we initialize the model after STEP-pretraining, i.e. the tunable prefix is not set
41
+ # and (2) the model has been fine-tuned on downstream data, and hence there is meaningful data in the tunable prefix
42
+
43
+ # Initialize the prefix with NaNs. If we initialize from STEP-pretraining, this will not be overwritten by a custom version of from_pretrained
44
+ # if we initialize after fine-tuning, the NaNs will be overwritten anyway.
45
+
46
+ self.prefix_embedding = torch.nn.Parameter(torch.nan + torch.zeros((1, self.config.prefix_length, self.config.d_model)))
47
+ self.prefix_has_been_initialized = False
48
+
49
+ def _initialize_prefix(self):
50
+ prefix_init_tensor = self.prefix_init_tensor
51
+ if self.config.random_selection:
52
+ # randomize selection of FSTs to average for initialization the prefix.
53
+ prefix_init_tensor = prefix_init_tensor[torch.randperm(prefix_init_tensor.shape[0]), :, :]
54
+
55
+ prefix_init_tensor = prefix_init_tensor[:self.config.num_examples, :self.config.prefix_length,
56
+ :] # shape (num ex, prefix length, d model)
57
+ self.prefix_embedding.data.copy_(prefix_init_tensor.mean(dim=0, keepdims=True))
58
+
59
+ @classmethod
60
+ def from_pretrained(
61
+ cls,
62
+ pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
63
+ *model_args,
64
+ **kwargs,
65
+ ):
66
+ model = super(STEPFinetuningModel, cls).from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
67
+ if torch.all(model.prefix_embedding.isnan()):
68
+ model._initialize_prefix()
69
+ return model
70
+
71
+
72
+ def prepare_input(self, kwargs):
73
+ """
74
+ Prepends the prefix to the given input.
75
+ :param kwargs:
76
+ :return:
77
+ """
78
+ input_ids = kwargs["input_ids"]
79
+
80
+ embedded_inputs = self.model.get_input_embeddings()(input_ids)
81
+
82
+ batch_size = input_ids.shape[0]
83
+
84
+ prefix = torch.repeat_interleave(self.prefix_embedding, batch_size, 0) #shape (batch, prefix length, embed dim)
85
+
86
+ kwargs = dict(kwargs)
87
+
88
+ embedded_inputs = torch.cat([prefix, embedded_inputs], dim=1) # shape (batch, prefix + seq length, embed dim)
89
+
90
+ del kwargs["input_ids"]
91
+ kwargs["inputs_embeds"] = embedded_inputs
92
+
93
+ if "attention_mask" in kwargs:
94
+ ones = torch.ones((batch_size, self.config.prefix_length), device=embedded_inputs.device, dtype=kwargs["attention_mask"].dtype)
95
+ input_mask = torch.cat([ones, kwargs["attention_mask"]], dim=1)
96
+ kwargs["attention_mask"] = input_mask
97
+
98
+ return kwargs
99
+
100
+ def forward(self, **kwargs):
101
+ return self.model(**self.prepare_input(kwargs))
102
+
103
+ def generate(self, **kwargs):
104
+ return self.model.generate(**self.prepare_input(kwargs))
105
+
106
+
107
+ def get_optimizer(self, optimizer: Callable[..., torch.optim.Optimizer] = None, prefix_lr:float = 10.0, **kwargs) -> torch.optim.Optimizer:
108
+ """
109
+ Return an optimizer that uses a different learning rate (typically higher) for the prefix than for the rest of the model.
110
+ """
111
+
112
+ prefix_params = []
113
+ other_params = []
114
+ for name, param in self.named_parameters():
115
+ if name == "prefix_embedding":
116
+ prefix_params.append(param)
117
+ else:
118
+ other_params.append(param)
119
+ if optimizer is None:
120
+ # The optimizer used in the paper.
121
+ hparams = {"scale_parameter": False, "relative_step": False, "warmup_init": False, "lr": 1e-4}
122
+ return Adafactor(params=[{"params": prefix_params, "lr": prefix_lr}, {"params": other_params}], **(hparams | kwargs))
123
+ return optimizer(params=[{"params": prefix_params, "lr": prefix_lr}, {"params": other_params}], **kwargs)
124
+