Delta-Vector commited on
Commit
cb796b9
·
verified ·
1 Parent(s): 0fa76e5

Upload t.py

Browse files
Files changed (1) hide show
  1. t.py +292 -0
t.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unsloth import FastModel
2
+ import torch
3
+
4
+ fourbit_models = [
5
+ # 4bit dynamic quants for superior accuracy and low memory use
6
+ "unsloth/gemma-3-1b-it-unsloth-bnb-4bit",
7
+ "unsloth/gemma-3-4b-it-unsloth-bnb-4bit",
8
+ "unsloth/gemma-3-12b-it-unsloth-bnb-4bit",
9
+ "unsloth/gemma-3-27b-it-unsloth-bnb-4bit",
10
+
11
+ # Other popular models!
12
+ "unsloth/Llama-3.1-8B",
13
+ "unsloth/Llama-3.2-3B",
14
+ "unsloth/Llama-3.3-70B",
15
+ "unsloth/mistral-7b-instruct-v0.3",
16
+ "unsloth/Phi-4",
17
+ ] # More models at https://huggingface.co/unsloth
18
+
19
+ model, tokenizer = FastModel.from_pretrained(
20
+ model_name = "NewEden/Gemma-LN-merged",
21
+ max_seq_length = 8192, # Choose any for long context!
22
+ load_in_4bit = False, # 4 bit quantization to reduce memory
23
+ load_in_8bit = False, # [NEW!] A bit more accurate, uses 2x memory
24
+ full_finetuning = False, # [NEW!] We have full finetuning now!
25
+ # token = "hf_...", # use one if using gated models
26
+ )
27
+
28
+ """We now add LoRA adapters so we only need to update a small amount of parameters!"""
29
+
30
+ model = FastModel.get_peft_model(
31
+ model,
32
+ finetune_vision_layers = False, # Turn off for just text!
33
+ finetune_language_layers = True, # Should leave on!
34
+ finetune_attention_modules = True, # Attention good for GRPO
35
+ finetune_mlp_modules = True, # SHould leave on always!
36
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
37
+ "gate_proj", "up_proj", "down_proj",],
38
+ r = 64, # Larger = higher accuracy, but might overfit
39
+ lora_alpha = 32, # Recommended alpha == r at least
40
+ lora_dropout = 0.1,
41
+ bias = "none",
42
+
43
+ random_state = 3407,
44
+ )
45
+
46
+
47
+ from unsloth.chat_templates import get_chat_template
48
+ tokenizer = get_chat_template(
49
+ tokenizer,
50
+ chat_template = "gemma-3",
51
+ )
52
+
53
+ from datasets import load_dataset
54
+ dataset = load_dataset("NewEden/Light-Novels-Roleplay-Logs-Books-Oh-My-duplicate-turns-removed", split = "train")
55
+
56
+ """We now use `standardize_data_formats` to try converting datasets to the correct format for finetuning purposes!"""
57
+
58
+ from unsloth.chat_templates import standardize_data_formats
59
+ dataset = standardize_data_formats(dataset)
60
+
61
+ """Let's see how row 100 looks like!"""
62
+
63
+ dataset[100]
64
+
65
+ """We now have to apply the chat template for `Gemma-3` onto the conversations, and save it to `text`"""
66
+
67
+ def apply_chat_template(examples):
68
+ texts = tokenizer.apply_chat_template(examples["conversations"])
69
+ return { "text" : texts }
70
+ pass
71
+ dataset = dataset.map(apply_chat_template, batched = True)
72
+
73
+ """Let's see how the chat template did! Notice `Gemma-3` default adds a `<bos>`!"""
74
+
75
+ dataset[100]["text"]
76
+
77
+ """<a name="Train"></a>
78
+ ### Train the model
79
+ Now let's use Huggingface TRL's `SFTTrainer`! More docs here: [TRL SFT docs](https://huggingface.co/docs/trl/sft_trainer). We do 60 steps to speed things up, but you can set `num_train_epochs=1` for a full run, and turn off `max_steps=None`.
80
+ """
81
+
82
+ from trl import SFTTrainer, SFTConfig
83
+
84
+ trainer = SFTTrainer(
85
+ model=model,
86
+ tokenizer=tokenizer,
87
+ train_dataset=dataset,
88
+ eval_dataset=None,
89
+ args=SFTConfig(
90
+ dataset_text_field="text",
91
+ per_device_train_batch_size=1,
92
+ gradient_accumulation_steps=4,
93
+ warmup_steps=50,
94
+ num_train_epochs=2,
95
+ learning_rate=1e-5,
96
+ max_grad_norm=0.2,
97
+ logging_steps=1,
98
+ optim="paged_adamw_8bit",
99
+ weight_decay=0.01,
100
+ lr_scheduler_type="cosine",
101
+ seed=3407,
102
+ report_to="wandb",
103
+ save_strategy="epoch",
104
+ ),
105
+ )
106
+
107
+ """We also use Unsloth's `train_on_completions` method to only train on the assistant outputs and ignore the loss on the user's inputs. This helps increase accuracy of finetunes!"""
108
+
109
+ from unsloth.chat_templates import train_on_responses_only
110
+ trainer = train_on_responses_only(
111
+ trainer,
112
+ instruction_part = "<start_of_turn>user\n",
113
+ response_part = "<start_of_turn>model\n",
114
+ )
115
+
116
+ """Let's verify masking the instruction part is done! Let's print the 100th row again:"""
117
+
118
+ tokenizer.decode(trainer.train_dataset[100]["input_ids"])
119
+
120
+ """Now let's print the masked out example - you should see only the answer is present:"""
121
+
122
+ tokenizer.decode([tokenizer.pad_token_id if x == -100 else x for x in trainer.train_dataset[100]["labels"]]).replace(tokenizer.pad_token, " ")
123
+
124
+ # @title Show current memory stats
125
+ gpu_stats = torch.cuda.get_device_properties(0)
126
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
127
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
128
+ print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
129
+ print(f"{start_gpu_memory} GB of memory reserved.")
130
+
131
+ """Let's train the model! To resume a training run, set `trainer.train(resume_from_checkpoint = True)`"""
132
+
133
+ trainer_stats = trainer.train()
134
+
135
+ # @title Show final memory and time stats
136
+ used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
137
+ used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
138
+ used_percentage = round(used_memory / max_memory * 100, 3)
139
+ lora_percentage = round(used_memory_for_lora / max_memory * 100, 3)
140
+ print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
141
+ print(
142
+ f"{round(trainer_stats.metrics['train_runtime']/60, 2)} minutes used for training."
143
+ )
144
+ print(f"Peak reserved memory = {used_memory} GB.")
145
+ print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
146
+ print(f"Peak reserved memory % of max memory = {used_percentage} %.")
147
+ print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")
148
+
149
+ """<a name="Inference"></a>
150
+ ### Inference
151
+ Let's run the model via Unsloth native inference! According to the `Gemma-3` team, the recommended settings for inference are `temperature = 1.0, top_p = 0.95, top_k = 64`
152
+ """
153
+
154
+ from unsloth.chat_templates import get_chat_template
155
+ tokenizer = get_chat_template(
156
+ tokenizer,
157
+ chat_template = "gemma-3",
158
+ )
159
+ messages = [{
160
+ "role": "user",
161
+ "content": [{
162
+ "type" : "text",
163
+ "text" : "Continue the sequence: 1, 1, 2, 3, 5, 8,",
164
+ }]
165
+ }]
166
+ text = tokenizer.apply_chat_template(
167
+ messages,
168
+ add_generation_prompt = True, # Must add for generation
169
+ )
170
+ outputs = model.generate(
171
+ **tokenizer([text], return_tensors = "pt").to("cuda"),
172
+ max_new_tokens = 64, # Increase for longer outputs!
173
+ # Recommended Gemma-3 settings!
174
+ temperature = 1.0, top_p = 0.95, top_k = 64,
175
+ )
176
+ tokenizer.batch_decode(outputs)
177
+
178
+ """ You can also use a `TextStreamer` for continuous inference - so you can see the generation token by token, instead of waiting the whole time!"""
179
+
180
+ messages = [{
181
+ "role": "user",
182
+ "content": [{"type" : "text", "text" : "Why is the sky blue?",}]
183
+ }]
184
+ text = tokenizer.apply_chat_template(
185
+ messages,
186
+ add_generation_prompt = True, # Must add for generation
187
+ )
188
+
189
+ from transformers import TextStreamer
190
+ _ = model.generate(
191
+ **tokenizer([text], return_tensors = "pt").to("cuda"),
192
+ max_new_tokens = 64, # Increase for longer outputs!
193
+ # Recommended Gemma-3 settings!
194
+ temperature = 1.0, top_p = 0.95, top_k = 64,
195
+ streamer = TextStreamer(tokenizer, skip_prompt = True),
196
+ )
197
+
198
+ """<a name="Save"></a>
199
+ ### Saving, loading finetuned models
200
+ To save the final model as LoRA adapters, either use Huggingface's `push_to_hub` for an online save or `save_pretrained` for a local save.
201
+
202
+ **[NOTE]** This ONLY saves the LoRA adapters, and not the full model. To save to 16bit or GGUF, scroll down!
203
+ """
204
+
205
+ model.save_pretrained("gemma-3") # Local saving
206
+ tokenizer.save_pretrained("gemma-3")
207
+ # model.push_to_hub("HF_ACCOUNT/gemma-3", token = "...") # Online saving
208
+ # tokenizer.push_to_hub("HF_ACCOUNT/gemma-3", token = "...") # Online saving
209
+
210
+ """Now if you want to load the LoRA adapters we just saved for inference, set `False` to `True`:"""
211
+
212
+ if False:
213
+ from unsloth import FastModel
214
+ model, tokenizer = FastModel.from_pretrained(
215
+ model_name = "lora_model", # YOUR MODEL YOU USED FOR TRAINING
216
+ max_seq_length = 2048,
217
+ load_in_4bit = True,
218
+ )
219
+
220
+ messages = [{
221
+ "role": "user",
222
+ "content": [{"type" : "text", "text" : "What is Gemma-3?",}]
223
+ }]
224
+ text = tokenizer.apply_chat_template(
225
+ messages,
226
+ add_generation_prompt = True, # Must add for generation
227
+ )
228
+
229
+ from transformers import TextStreamer
230
+ _ = model.generate(
231
+ **tokenizer([text], return_tensors = "pt").to("cuda"),
232
+ max_new_tokens = 64, # Increase for longer outputs!
233
+ # Recommended Gemma-3 settings!
234
+ temperature = 1.0, top_p = 0.95, top_k = 64,
235
+ streamer = TextStreamer(tokenizer, skip_prompt = True),
236
+ )
237
+
238
+ """### Saving to float16 for VLLM
239
+
240
+ We also support saving to `float16` directly for deployment! We save it in the folder `gemma-3-finetune`. Set `if False` to `if True` to let it run!
241
+ """
242
+
243
+ if False: # Change to True to save finetune!
244
+ model.save_pretrained_merged("gemma-3-finetune", tokenizer)
245
+
246
+ """If you want to upload / push to your Hugging Face account, set `if False` to `if True` and add your Hugging Face token and upload location!"""
247
+
248
+ if False: # Change to True to upload finetune
249
+ model.push_to_hub_merged(
250
+ "HF_ACCOUNT/gemma-3-finetune", tokenizer,
251
+ token = "hf_..."
252
+ )
253
+
254
+ """### GGUF / llama.cpp Conversion
255
+ To save to `GGUF` / `llama.cpp`, we support it natively now for all models! For now, you can convert easily to `Q8_0, F16 or BF16` precision. `Q4_K_M` for 4bit will come later!
256
+ """
257
+
258
+ if False: # Change to True to save to GGUF
259
+ model.save_pretrained_gguf(
260
+ "gemma-3-finetune",
261
+ quantization_type = "Q8_0", # For now only Q8_0, BF16, F16 supported
262
+ )
263
+
264
+ """Likewise, if you want to instead push to GGUF to your Hugging Face account, set `if False` to `if True` and add your Hugging Face token and upload location!"""
265
+
266
+ if False: # Change to True to upload GGUF
267
+ model.push_to_hub_gguf(
268
+ "gemma-3-finetune",
269
+ quantization_type = "Q8_0", # Only Q8_0, BF16, F16 supported
270
+ repo_id = "HF_ACCOUNT/gemma-finetune-gguf",
271
+ token = "hf_...",
272
+ )
273
+
274
+ """Now, use the `gemma-3-finetune.gguf` file or `gemma-3-finetune-Q4_K_M.gguf` file in llama.cpp or a UI based system like Jan or Open WebUI. You can install Jan [here](https://github.com/janhq/jan) and Open WebUI [here](https://github.com/open-webui/open-webui)
275
+
276
+ And we're done! If you have any questions on Unsloth, we have a [Discord](https://discord.gg/unsloth) channel! If you find any bugs or want to keep updated with the latest LLM stuff, or need help, join projects etc, feel free to join our Discord!
277
+
278
+ Some other links:
279
+ 1. Train your own reasoning model - Llama GRPO notebook [Free Colab](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Llama3.1_(8B)-GRPO.ipynb)
280
+ 2. Saving finetunes to Ollama. [Free notebook](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Llama3_(8B)-Ollama.ipynb)
281
+ 3. Llama 3.2 Vision finetuning - Radiography use case. [Free Colab](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Llama3.2_(11B)-Vision.ipynb)
282
+ 6. See notebooks for DPO, ORPO, Continued pretraining, conversational finetuning and more on our [documentation](https://docs.unsloth.ai/get-started/unsloth-notebooks)!
283
+
284
+ <div class="align-center">
285
+ <a href="https://unsloth.ai"><img src="https://github.com/unslothai/unsloth/raw/main/images/unsloth%20new%20logo.png" width="115"></a>
286
+ <a href="https://discord.gg/unsloth"><img src="https://github.com/unslothai/unsloth/raw/main/images/Discord.png" width="145"></a>
287
+ <a href="https://docs.unsloth.ai/"><img src="https://github.com/unslothai/unsloth/blob/main/images/documentation%20green%20button.png?raw=true" width="125"></a>
288
+
289
+ Join Discord if you need help + ⭐️ <i>Star us on <a href="https://github.com/unslothai/unsloth">Github</a> </i> ⭐️
290
+ </div>
291
+
292
+ """