Text Generation
English
crayon
language-technologies
Pascrayon commited on
Commit
9709a25
·
1 Parent(s): b7b8f57

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +332 -1
README.md CHANGED
@@ -1,3 +1,334 @@
1
  ---
2
- license: openrail
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ license: bigscience-bloom-rail-1.0
3
+ datasets:
4
+ - tatsu-lab/alpaca
5
+ language:
6
+ - en
7
+ pipeline_tag: text-generation
8
+ tags:
9
+ - crayon
10
+ - language-technologies
11
  ---
12
+
13
+ # BloomZ 560M Finetuned on Instructions
14
+
15
+ ## Credit
16
+
17
+ Code 99.99% copied from
18
+
19
+
20
+ *https://github.com/bofenghuang/vigogne*
21
+
22
+
23
+ *https://colab.research.google.com/drive/1jCkpikz0J2o20FBQmYmAGdiKmJGOMo-o?usp=sharing#scrollTo=DpYr24pR8T_0*
24
+
25
+ and refactored.
26
+
27
+
28
+ # Inference Code
29
+
30
+ ```python
31
+
32
+ from peft import PeftModel
33
+ from transformers import PreTrainedTokenizer, PreTrainedModel, AutoTokenizer, AutoModelForCausalLM
34
+ from peft import PeftModelForCausalLM, LoraConfig
35
+ from typing import Optional
36
+ from transformers import GenerationConfig
37
+ import torch
38
+
39
+ PROMPT_DICT = {
40
+ "prompt_input": (
41
+ "Below is a^n instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n\n"
42
+ "### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:\n"
43
+ ),
44
+ "prompt_no_input": (
45
+ "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n"
46
+ "### Instruction:\n{instruction}\n\n### Response:\n"
47
+ ),
48
+ }
49
+
50
+
51
+ def get_model(model_name_or_path: str, load_in_8bit: bool = True, device_map="auto",
52
+ cpu: bool = False) -> PreTrainedModel:
53
+ if cpu:
54
+ model = AutoModelForCausalLM.from_pretrained(model_name_or_path, device_map=device_map,
55
+ low_cpu_mem_usage=True)
56
+ else:
57
+ model = AutoModelForCausalLM.from_pretrained(model_name_or_path, load_in_8bit=load_in_8bit,
58
+ device_map=device_map, torch_dtype=torch.float16)
59
+
60
+ return model
61
+
62
+
63
+ def get_peft_model(model: PreTrainedModel, lora_model_name_or_path: Optional[str] = None) -> PeftModelForCausalLM:
64
+ model = PeftModel.from_pretrained(model, lora_model_name_or_path, torch_dtype=torch.float16)
65
+
66
+ return model
67
+
68
+
69
+ def get_tokenizer(model_name_or_path: str, max_input_len: int) -> PreTrainedTokenizer:
70
+ tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, model_max_length=max_input_len,
71
+ padding_side="right", use_fast=False)
72
+
73
+ return tokenizer
74
+
75
+
76
+ def get_llm_inference_model(base_model_name_or_path: str, lora_model_name_or_path: str, load_in_8bit: bool,
77
+ device_map) -> PeftModel:
78
+ cpu = True if not torch.cuda.is_available() else False
79
+
80
+ model = get_model(base_model_name_or_path, load_in_8bit, device_map, cpu=cpu)
81
+
82
+ model = get_peft_model(model, lora_model_name_or_path=lora_model_name_or_path)
83
+
84
+ if not load_in_8bit:
85
+ model.half()
86
+
87
+ model.eval()
88
+
89
+ if torch.__version__ >= "2":
90
+ model = torch.compile(model)
91
+
92
+ return model
93
+
94
+
95
+ def generate_prompt(example):
96
+ return (
97
+ PROMPT_DICT["prompt_input"].format_map(example)
98
+ if example["input"]
99
+ else PROMPT_DICT["prompt_no_input"].format_map(example)
100
+ )
101
+
102
+
103
+ def infer(instruction: str, input_text: Optional[str] = None, temperature: float = 0.1, top_p: float = 0.95,
104
+ max_new_tokens: int = 512, early_stopping: bool = True, do_sample: bool = True,
105
+ repetition_penalty: float = 2.5) -> str:
106
+ prompt = generate_prompt({"instruction": instruction, "input": input_text})
107
+
108
+ tokenized_inputs = tokenizer(prompt, return_tensors="pt")
109
+
110
+ device = "cuda" if torch.cuda.is_available() else "cpu"
111
+
112
+ input_ids = tokenized_inputs["input_ids"].to(device)
113
+
114
+ generation_config = GenerationConfig(temperature=temperature, top_p=top_p, do_sample=do_sample,
115
+ repetition_penalty=repetition_penalty, early_stopping=early_stopping)
116
+
117
+ with torch.inference_mode():
118
+ generation_output = model.generate(input_ids=input_ids, generation_config=generation_config,
119
+ return_dict_in_generate=True, max_new_tokens=max_new_tokens)
120
+
121
+ output = generation_output.sequences[0]
122
+
123
+ output = tokenizer.decode(output, skip_special_tokens=True)
124
+
125
+ return output.split("### Response:")[1].strip()
126
+
127
+
128
+ base_model_name_or_path = "bigscience/bloomz-560m"
129
+
130
+ lora_model_name_or_path = "crayon-coe/crayon-coe/laMini-Instruction-250K-bloomz-560m"
131
+
132
+ model = get_llm_inference_model(base_model_name_or_path, lora_model_name_or_path, True, "auto")
133
+
134
+ tokenizer = get_tokenizer(base_model_name_or_path, 512)
135
+
136
+ context = "Write a letter expressing your love for computers"
137
+
138
+ output = infer(context)
139
+
140
+ print(output)
141
+
142
+ # Output
143
+ # I am so grateful to have been able access this wonderful computer system and its amazing features, which I can now use daily with ease.
144
+ #
145
+ # My heartfelt thanks go out in advance of all my friends who are using it as well.
146
+ # Thank you again!
147
+
148
+ ```
149
+
150
+ # Training Parameters
151
+
152
+ ```json
153
+ {
154
+ "max_input_len": 512,
155
+ "load_in_8bit": True,
156
+ "model_name_or_path": "bigscience/bloomz-560m",
157
+ "device_map": "auto",
158
+ "bias": "none",
159
+ "lora_dropout": 0.05,
160
+ "lora_alpha": 32,
161
+ "target_modules": ["query_key_value"],
162
+ "task_type": "CAUSAL_LM",
163
+ "lora_r": 16,
164
+ "pad_to_multiple_of": 8,
165
+ "num_train_epochs": 3,
166
+ "learning_rate": 0.0003,
167
+ "gradient_accumulation_steps": 16,
168
+ "per_device_train_batch_size": 8,
169
+ "val_set_size": 500,
170
+ "save_steps": 200,
171
+ "eval_steps": 200,
172
+ "evaluation_strategy": "steps",
173
+ "save_strategy": "steps"
174
+ }
175
+ ```
176
+
177
+ # Training Code
178
+
179
+ ```python
180
+ # coding=utf-8
181
+ # Code 99.99% copied and adapted from:
182
+ # https://github.com/bofenghuang/vigogne
183
+ # https://colab.research.google.com/drive/1jCkpikz0J2o20FBQmYmAGdiKmJGOMo-o?usp=sharing#scrollTo=DpYr24pR8T_0
184
+
185
+
186
+ import os
187
+ import sys
188
+ from dataclasses import dataclass
189
+ from typing import Dict, List, Optional, Sequence
190
+
191
+ import bitsandbytes as bnb
192
+ import fire
193
+ import torch
194
+ import transformers
195
+ from datasets import load_dataset
196
+ from peft import LoraConfig, TaskType, get_peft_model, get_peft_model_state_dict, prepare_model_for_int8_training
197
+ from transformers import AutoModelForCausalLM, AutoTokenizer, LlamaTokenizer
198
+
199
+ IGNORE_INDEX = -100
200
+ DEFAULT_PAD_TOKEN = "[PAD]"
201
+
202
+ PROMPT_DICT = {
203
+ "prompt_input": (
204
+ "Below is a^n instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n\n"
205
+ "### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:\n"
206
+ ),
207
+ "prompt_no_input": (
208
+ "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n"
209
+ "### Instruction:\n{instruction}\n\n### Response:\n"
210
+ ),
211
+ }
212
+
213
+
214
+ def generate_prompt(example):
215
+ return (
216
+ PROMPT_DICT["prompt_input"].format_map(example)
217
+ if example["input"]
218
+ else PROMPT_DICT["prompt_no_input"].format_map(example)
219
+ )
220
+
221
+
222
+ # Modified from: https://github.com/bofenghuang/stanford_alpaca/blob/eb5b171d9b103a12a8e14e0edca9cbc45fe1d512/train.py#L166-L182
223
+ # Almost same to transformers.DataCollatorForSeq2Seq
224
+ @dataclass
225
+ class DataCollatorForSupervisedDataset(object):
226
+ """Collate examples for supervised fine-tuning."""
227
+
228
+ tokenizer: transformers.PreTrainedTokenizer
229
+ pad_to_multiple_of: Optional[int] = None
230
+
231
+ def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
232
+ # dtype = torch.long
233
+ # input_ids, labels = tuple([torch.LongTensor(instance[key]) for instance in instances] for key in ("input_ids", "labels"))
234
+ input_ids, labels = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels"))
235
+
236
+ if self.pad_to_multiple_of is not None:
237
+ max_length_index, max_length = max(enumerate([len(input_ids_) for input_ids_ in input_ids]),
238
+ key=lambda x: x[1])
239
+ # int(math.ceil
240
+ n_padding = ((max_length // self.pad_to_multiple_of) + 1) * self.pad_to_multiple_of - max_length
241
+ # Pad the longest example to pad_to_multiple_of * N
242
+ input_ids[max_length_index].extend([self.tokenizer.pad_token_id] * n_padding)
243
+ labels[max_length_index].extend([IGNORE_INDEX] * n_padding)
244
+
245
+ input_ids = [torch.LongTensor(input_ids_) for input_ids_ in input_ids]
246
+ labels = [torch.LongTensor(labels_) for labels_ in labels]
247
+
248
+ input_ids = torch.nn.utils.rnn.pad_sequence(input_ids, batch_first=True,
249
+ padding_value=self.tokenizer.pad_token_id)
250
+ labels = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX)
251
+
252
+ return dict(input_ids=input_ids, labels=labels, attention_mask=input_ids.ne(self.tokenizer.pad_token_id))
253
+
254
+
255
+ def train(model_name_or_path: str, output_dir: str, data_path: str, val_set_size: int = 500,
256
+ model_max_length: int = 512, lora_r: int = 16, lora_alpha: int = 32, lora_dropout: float = 0.05,
257
+ target_modules: List[str] = ["query_key_value"], num_train_epochs: int = 3, learning_rate: float = 0.0001,
258
+ per_device_train_batch_size: int = 8, gradient_accumulation_steps: int = 16, **kwargs):
259
+ device_map = "auto"
260
+
261
+ model = AutoModelForCausalLM.from_pretrained(model_name_or_path, load_in_8bit=True, device_map=device_map)
262
+
263
+ tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, model_max_length=model_max_length,
264
+ padding_side="right", use_fast=False)
265
+
266
+ model = prepare_model_for_int8_training(model)
267
+
268
+ lora_config = LoraConfig(r=lora_r, lora_alpha=lora_alpha, target_modules=target_modules, lora_dropout=lora_dropout,
269
+ bias="none", task_type=TaskType.CAUSAL_LM)
270
+
271
+ model = get_peft_model(model, lora_config)
272
+
273
+ model.print_trainable_parameters()
274
+
275
+ # Load data
276
+ data = load_dataset("json", data_files=data_path)
277
+
278
+ def preprocess_function(example):
279
+ # Format prompt
280
+ user_prompt = generate_prompt(example)
281
+
282
+ # Get prompt length for masking
283
+ len_user_prompt_tokens = len(tokenizer(user_prompt, truncation=True)["input_ids"])
284
+
285
+ input_ids = tokenizer(user_prompt + example["output"] + tokenizer.eos_token, truncation=True)["input_ids"]
286
+ labels = [IGNORE_INDEX] * len_user_prompt_tokens + input_ids[len_user_prompt_tokens:]
287
+
288
+ return {"input_ids": input_ids, "labels": labels}
289
+
290
+ if val_set_size > 0:
291
+ train_val = data["train"].train_test_split(test_size=val_set_size, shuffle=True, seed=42)
292
+ train_data = train_val["train"].shuffle().map(preprocess_function, remove_columns=data["train"].column_names)
293
+ val_data = train_val["test"].map(preprocess_function, remove_columns=data["train"].column_names)
294
+ else:
295
+ train_data = data["train"].shuffle().map(preprocess_function, remove_columns=data["train"].column_names)
296
+ val_data = None
297
+
298
+ trainer = transformers.Trainer(
299
+ model=model,
300
+ train_dataset=train_data,
301
+ eval_dataset=val_data,
302
+ args=transformers.TrainingArguments(
303
+ per_device_train_batch_size=per_device_train_batch_size,
304
+ gradient_accumulation_steps=gradient_accumulation_steps,
305
+ num_train_epochs=num_train_epochs,
306
+ learning_rate=learning_rate,
307
+ fp16=True,
308
+ output_dir=output_dir,
309
+ load_best_model_at_end=True if val_set_size > 0 else False,
310
+ **kwargs,
311
+ ),
312
+ data_collator=DataCollatorForSupervisedDataset(tokenizer=tokenizer, pad_to_multiple_of=8),
313
+ )
314
+ print(trainer.args)
315
+
316
+ # Silence the warnings. Please re-enable for inference!
317
+ model.config.use_cache = False
318
+
319
+ old_state_dict = model.state_dict
320
+ model.state_dict = (lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict())).__get__(model,
321
+ type(model))
322
+
323
+ if torch.__version__ >= "2" and sys.platform != "win32":
324
+ model = torch.compile(model)
325
+
326
+ trainer.train()
327
+
328
+ model.save_pretrained(output_dir)
329
+
330
+
331
+ if __name__ == "__main__":
332
+ fire.Fire(train)
333
+
334
+ ```