Views
No views yet

1from unsloth import FastLanguageModel
2from unsloth import PatchFastRL
3PatchFastRL("GRPO", FastLanguageModel)
4import torch
5max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
6dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
7load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
8
9alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
10
11### Instruction:
12{}
13
14### Input:
15{}
16
17### Response:
18{}"""
19
20model, tokenizer = FastLanguageModel.from_pretrained(
21 model_name = "./Llama-3.2-3B-Instruct-lyrics", # or choose "unsloth/Llama-3.2-1B-Instruct"
22 max_seq_length = max_seq_length,
23 dtype = dtype,
24 # load_in_4bit = load_in_4bit,
25 # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
26)
27
28# alpaca_prompt = You MUST copy from above!
29
30inputs = tokenizer(
31[
32 alpaca_prompt.format(
33 "", # instruction
34 """ new write a pop love song.
35 song name:
36 Style of Music(five components: genre, instrument, mood, gender, and timbre. ):
37 [Intro]
38 [Verse 1]
39 [Chorus]
40 [Verse 2]
41 [Chorus]
42 [Bridge]
43 [Chorus]
44 [Outro] """, # input
45 "", # output - leave this blank for generation!
46 )
47], return_tensors = "pt").to("cuda")
48
49from transformers import TextStreamer
50text_streamer = TextStreamer(tokenizer)
51_ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 1024)
52
53 1from unsloth import FastLanguageModel
2import torch
3max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
4dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
5load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
6
7# 4bit pre quantized models we support for 4x faster downloading + no OOMs.
8fourbit_models = [
9 "unsloth/Meta-Llama-3.1-8B-bnb-4bit", # Llama-3.1 2x faster
10 "unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit",
11 "unsloth/Meta-Llama-3.1-70B-bnb-4bit",
12 "unsloth/Meta-Llama-3.1-405B-bnb-4bit", # 4bit for 405b!
13 "unsloth/Mistral-Small-Instruct-2409", # Mistral 22b 2x faster!
14 "unsloth/mistral-7b-instruct-v0.3-bnb-4bit",
15 "unsloth/Phi-3.5-mini-instruct", # Phi-3.5 2x faster!
16 "unsloth/Phi-3-medium-4k-instruct",
17 "unsloth/gemma-2-9b-bnb-4bit",
18 "unsloth/gemma-2-27b-bnb-4bit", # Gemma 2x faster!
19
20 "unsloth/Llama-3.2-1B-bnb-4bit", # NEW! Llama 3.2 models
21 "unsloth/Llama-3.2-1B-Instruct-bnb-4bit",
22 "unsloth/Llama-3.2-3B-bnb-4bit",
23 "unsloth/Llama-3.2-3B-Instruct-bnb-4bit",
24
25 "unsloth/Llama-3.3-70B-Instruct-bnb-4bit" # NEW! Llama 3.3 70B!
26] # More models at https://huggingface.co/unsloth
27
28model, tokenizer = FastLanguageModel.from_pretrained(
29 model_name = "./Llama-3.2-3B-Instruct-unsloth-bnb-4bit", # or choose "unsloth/Llama-3.2-1B-Instruct"
30 max_seq_length = max_seq_length,
31 dtype = dtype,
32 load_in_4bit = load_in_4bit,
33 # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
34)
35
36model = FastLanguageModel.get_peft_model(
37 model,
38 r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
39 target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
40 "gate_proj", "up_proj", "down_proj",],
41 lora_alpha = 16,
42 lora_dropout = 0, # Supports any, but = 0 is optimized
43 bias = "none", # Supports any, but = "none" is optimized
44 # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
45 use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
46 random_state = 3407,
47 use_rslora = False, # We support rank stabilized LoRA
48 loftq_config = None, # And LoftQ
49)
50
51from unsloth.chat_templates import get_chat_template
52
53tokenizer = get_chat_template(
54 tokenizer,
55 chat_template = "llama-3.2",
56)
57
58alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
59
60### Instruction:
61{}
62
63### Input:
64{}
65
66### Response:
67{}"""
68
69EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN
70def formatting_prompts_func(examples):
71 instructions = examples["instruction"]
72 inputs = examples["input"]
73 outputs = examples["output"]
74 texts = []
75 for instruction, input, output in zip(instructions, inputs, outputs):
76 # Must add EOS_TOKEN, otherwise your generation will go on forever!
77 text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN
78 texts.append(text)
79 return { "text" : texts, }
80pass
81
82from datasets import load_dataset
83dataset = load_dataset("Koyd111/alpaca-hiphop-lyrics", split = "train")
84dataset = dataset.map(formatting_prompts_func, batched = True,)
85print(dataset[5])
86
87from trl import SFTTrainer
88from transformers import TrainingArguments, DataCollatorForSeq2Seq
89from unsloth import is_bfloat16_supported
90
91trainer = SFTTrainer(
92 model = model,
93 tokenizer = tokenizer,
94 train_dataset = dataset,
95 dataset_text_field = "text",
96 max_seq_length = max_seq_length,
97 dataset_num_proc = 16,
98 packing = False, # Can make training 5x faster for short sequences.
99 args = TrainingArguments(
100 per_device_train_batch_size = 2,
101 gradient_accumulation_steps = 4,
102 warmup_steps = 5,
103 # num_train_epochs = 1, # Set this for 1 full training run.
104 max_steps = 60,
105 learning_rate = 2e-4,
106 fp16 = not is_bfloat16_supported(),
107 bf16 = is_bfloat16_supported(),
108 logging_steps = 1,
109 optim = "adamw_8bit",
110 weight_decay = 0.01,
111 lr_scheduler_type = "linear",
112 seed = 3407,
113 output_dir = "outputs",
114 report_to = "none", # Use this for WandB etc
115 ),
116)
117
118trainer_stats = trainer.train()
119
120# alpaca_prompt = Copied from above
121FastLanguageModel.for_inference(model) # Enable native 2x faster inference
122inputs = tokenizer(
123[
124 alpaca_prompt.format(
125 "Continue the fibonnaci sequence.", # instruction
126 "1, 1, 2, 3, 5, 8", # input
127 "", # output - leave this blank for generation!
128 )
129], return_tensors = "pt").to("cuda")
130
131# alpaca_prompt = Copied from above
132FastLanguageModel.for_inference(model) # Enable native 2x faster inference
133inputs = tokenizer(
134[
135 alpaca_prompt.format(
136 "Continue the fibonnaci sequence.", # instruction
137 "1, 1, 2, 3, 5, 8", # input
138 "", # output - leave this blank for generation!
139 )
140], return_tensors = "pt").to("cuda")
141
142from transformers import TextStreamer
143text_streamer = TextStreamer(tokenizer)
144_ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 128)
145
146outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
147tokenizer.batch_decode(outputs)
148
149model.save_pretrained("Llama-3.2-3B-Instruct-lyrics-lora") # Local saving
150tokenizer.save_pretrained("Llama-3.2-3B-Instruct-lyrics-lora")
151model.save_pretrained_merged("Llama-3.2-3B-Instruct-lyrics", tokenizer)