Text Generation
English
crayon
language-technologies
Pascrayon commited on
Commit
a62cfe2
1 Parent(s): 191a87e

Update README.md

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