aneeshm44 commited on
Commit
e561485
·
verified ·
1 Parent(s): 3479e56

Upload model_tools.py

Browse files
Files changed (1) hide show
  1. arcdata/model_tools.py +209 -0
arcdata/model_tools.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Daniel Franzen and Jan Disselhoff
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import json
17
+ import torch
18
+ from tokenizers import Tokenizer
19
+ import peft
20
+ from huggingface_hub import snapshot_download
21
+ from trl import DataCollatorForCompletionOnlyLM
22
+
23
+
24
+ class InputMaskingDataCollator(DataCollatorForCompletionOnlyLM):
25
+ def __init__(self, mask_first_n_examples=0, **kwargs):
26
+ super().__init__(**kwargs)
27
+ self.mask_first_n_examples = mask_first_n_examples
28
+
29
+ def torch_call(self, examples):
30
+ batch = super().torch_call(examples) # call super, masking all inputs
31
+ for i in range(len(batch['labels'])):
32
+ for _ in range(self.mask_first_n_examples):
33
+ # mask first still unmasked output block
34
+ beg_pos = ((batch['labels'][i] != -100).nonzero().min()).item()
35
+ mid_pos = ((batch['labels'][i][beg_pos:] == -100).nonzero().min()).item() + beg_pos
36
+ end_pos = ((batch['labels'][i] != -100).nonzero().max()).item() + 1
37
+ if mid_pos < end_pos:
38
+ batch['labels'][i][beg_pos:mid_pos] = -100
39
+ return batch
40
+
41
+
42
+ def load_unsloth_4bit(model_path):
43
+ from unsloth import FastLanguageModel
44
+ model, tokenizer = FastLanguageModel.from_pretrained(
45
+ model_name=model_path,
46
+ dtype=None,
47
+ load_in_4bit=True,
48
+ local_files_only=True
49
+ )
50
+ if model.max_seq_length == 2048 < model.generation_config.max_length:
51
+ print(f'CHANGING MAX_SEQ_LENGTH {model.max_seq_length} -> {model.generation_config.max_length} (unsloth bug?)')
52
+ to_fix = model
53
+ while to_fix is not None:
54
+ to_fix.max_seq_length = model.generation_config.max_length
55
+ to_fix = getattr(to_fix, 'model', None)
56
+ return model, tokenizer
57
+
58
+
59
+ def save_model_and_tokenizer(store_path, model, tokenizer):
60
+ model.save_pretrained(store_path)
61
+ tokenizer.save_pretrained(store_path)
62
+ to_delete = os.path.join(store_path, 'tokenizer.model') # delete file, as it interferes with token removal
63
+ if os.path.isfile(to_delete):
64
+ os.remove(to_delete)
65
+
66
+
67
+ def fix_dtypes(model, fix_weights=True, fix_quant_states=True):
68
+ # fix some data types (workaround for unsloth)
69
+ for module in model.modules():
70
+ weight = getattr(module, 'weight', None)
71
+ if weight is not None:
72
+ if torch.is_floating_point(weight):
73
+ if fix_weights and weight.dtype != model.dtype:
74
+ module.to(model.dtype)
75
+ else:
76
+ qs = getattr(weight, 'quant_state', None)
77
+ if qs is not None:
78
+ if fix_quant_states and qs.dtype != model.dtype:
79
+ qs.dtype = model.dtype
80
+ return model
81
+
82
+
83
+ def is_peft_model(model):
84
+ return hasattr(model, 'peft_type')
85
+
86
+
87
+ def merge_peft_into_base(model):
88
+ assert is_peft_model(model)
89
+ return fix_dtypes(model.merge_and_unload())
90
+
91
+
92
+ def get_and_fix_peft_weights(store):
93
+ # change some keys (workaround for added 'modules_to_save')
94
+ state_dict = peft.load_peft_weights(store)
95
+ for k in list(state_dict.keys()):
96
+ if 'modules_to_save' in k:
97
+ del state_dict[k]
98
+ original_module_key = k.replace('.modules_to_save.', '.original_module.')
99
+ if original_module_key in state_dict: del state_dict[original_module_key]
100
+ assert k.replace('.modules_to_save.', '.') in state_dict
101
+ return state_dict
102
+
103
+
104
+ def set_peft_weights(model, state_dict):
105
+ res = peft.set_peft_model_state_dict(model, state_dict)
106
+ assert not res.unexpected_keys, 'error loading weights - some keys not available in model'
107
+
108
+
109
+ def load_peft_state(model, store):
110
+ # convenience method to load peft weights from file and set them for model
111
+ set_peft_weights(model, get_and_fix_peft_weights(store))
112
+
113
+
114
+ def get_or_map_special_tokens(data, mapping=None):
115
+ tokens = set()
116
+ if isinstance(data, dict):
117
+ special = data.get('special_tokens')
118
+ if special is not None: # find and/or update special token mappings
119
+ for v in special.values():
120
+ tokens.update(v['ids'])
121
+ if mapping is not None:
122
+ v['ids'] = [mapping.get(i) for i in v['ids'] if i in mapping]
123
+ for v in data.values(): # recursively process dict values
124
+ tokens.update(get_or_map_special_tokens(v, mapping))
125
+ if isinstance(data, list):
126
+ for v in data: # recursively process lists
127
+ tokens.update(get_or_map_special_tokens(v, mapping))
128
+ return tokens
129
+
130
+
131
+ def remove_tokenizer_normalizer(tokenizer):
132
+ assert tokenizer.is_fast
133
+ tokenizer_json = json.loads(tokenizer._tokenizer.to_str())
134
+ if tokenizer_json.get('normalizer') is not None:
135
+ tokenizer_json['normalizer'] = None
136
+ tokenizer._tokenizer = Tokenizer.from_str(json.dumps(tokenizer_json))
137
+
138
+
139
+ def shrink_tokenizer_vocab(tokenizer, keep_indices, keep_special=True, remove_unk=False):
140
+ assert tokenizer.is_fast
141
+ tok_json = json.loads(tokenizer._tokenizer.to_str())
142
+ assert tok_json['model']['type'] == "BPE"
143
+
144
+ if keep_special: # get special tokens to keep
145
+ keep_indices.update(tokenizer.all_special_ids)
146
+ keep_indices.update(get_or_map_special_tokens(tok_json.get('post_processor')))
147
+
148
+ if remove_unk: # remove unknown token
149
+ keep_indices -= {tokenizer.unk_token_id}
150
+
151
+ # build mapping from old to new id
152
+ mapping = {old: new for new, old in enumerate(sorted(keep_indices))}
153
+
154
+ # update tokenizer info
155
+ tok_json['model']['vocab'] = {k: mapping[v] for k, v in tok_json['model']['vocab'].items() if v in mapping}
156
+ tok_json['model']['merges'] = []
157
+ tok_json['added_tokens'] = [{**t, 'id': mapping[t['id']]} for t in tok_json['added_tokens'] if t['id'] in mapping]
158
+ tok_json['added_tokens'] = sorted(tok_json['added_tokens'], key=lambda t: t['id'])
159
+ get_or_map_special_tokens(tok_json.get('post_processor'), mapping)
160
+
161
+ tokenizer._tokenizer = Tokenizer.from_str(json.dumps(tok_json)) # reload json, modifying tokenizer in-place
162
+
163
+ if remove_unk:
164
+ tokenizer.unk_token = None
165
+
166
+ return mapping # token mapping to be used later
167
+
168
+
169
+ def shrink_model_embeddings(model, mapping):
170
+ with torch.no_grad():
171
+ # copy embeddings to keep
172
+ row_select = torch.tensor([x[0] for x in sorted(mapping.items(), key=lambda x: x[1])])
173
+ row_select = row_select.to(model.get_input_embeddings().weight.data.device)
174
+ new_embed_t = torch.index_select(model.get_input_embeddings().weight.data, 0, row_select)
175
+ row_select = row_select.to(model.get_output_embeddings().weight.data.device)
176
+ new_lm_head = torch.index_select(model.get_output_embeddings().weight.data, 0, row_select)
177
+
178
+ # resize model embeddings
179
+ model.resize_token_embeddings(len(row_select))
180
+
181
+ # set to copied values
182
+ model.get_input_embeddings().weight.data[:] = new_embed_t
183
+ model.get_output_embeddings().weight.data[:] = new_lm_head
184
+
185
+ # map model tokens to new id
186
+ for config in [model.config, model.generation_config]:
187
+ for k, v in list(config.to_dict().items()):
188
+ if k.endswith('token_id'):
189
+ setattr(config, k, [mapping.get(t) for t in v] if isinstance(v, list) else mapping.get(v))
190
+
191
+
192
+ def keep_single_char_tokens(model, tokenizer, keep=None, keep_norm=False, keep_model_tok=True, **kwargs):
193
+ if not keep_norm:
194
+ remove_tokenizer_normalizer(tokenizer) # required for some models
195
+ if keep is None: # keep all single_length tokens
196
+ keep_indices = set(v for k, v in tokenizer.vocab.items() if len(k) == 1)
197
+ else: # keep tokens that were passed
198
+ keep_indices = set(tokenizer.vocab[t] for t in keep)
199
+ if keep_model_tok: # keep tokens used by model
200
+ for config in [model.config, model.generation_config]:
201
+ for k, v in config.to_dict().items():
202
+ if k.endswith('token_id'):
203
+ keep_indices.update(v if isinstance(v, list) else [v])
204
+ keep_indices -= {None}
205
+ mapping = shrink_tokenizer_vocab(tokenizer, keep_indices, **kwargs)
206
+ shrink_model_embeddings(model, mapping)
207
+ return mapping
208
+
209
+