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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
from unsloth import FastLanguageModel, is_bfloat16_supported
|
| 4 |
+
import torch
|
| 5 |
+
from trl import SFTTrainer
|
| 6 |
+
from transformers import TrainingArguments
|
| 7 |
+
|
| 8 |
+
from dotenv import find_dotenv, load_dotenv
|
| 9 |
+
from llm_toolkit.logical_reasoning_utils import *
|
| 10 |
+
from llm_toolkit.llm_utils import *
|
| 11 |
+
|
| 12 |
+
found_dotenv = find_dotenv(".env")
|
| 13 |
+
|
| 14 |
+
if len(found_dotenv) == 0:
|
| 15 |
+
found_dotenv = find_dotenv(".env.example")
|
| 16 |
+
print(f"loading env vars from: {found_dotenv}")
|
| 17 |
+
load_dotenv(found_dotenv, override=False)
|
| 18 |
+
|
| 19 |
+
path = os.path.dirname(found_dotenv)
|
| 20 |
+
print(f"Adding {path} to sys.path")
|
| 21 |
+
sys.path.append(path)
|
| 22 |
+
|
| 23 |
+
model_name = os.getenv("MODEL_NAME")
|
| 24 |
+
token = os.getenv("HF_TOKEN") or None
|
| 25 |
+
load_in_4bit = os.getenv("LOAD_IN_4BIT") == "true"
|
| 26 |
+
local_model = os.getenv("LOCAL_MODEL")
|
| 27 |
+
hub_model = os.getenv("HUB_MODEL")
|
| 28 |
+
num_train_epochs = int(os.getenv("NUM_TRAIN_EPOCHS") or 0)
|
| 29 |
+
data_path = os.getenv("LOGICAL_REASONING_DATA_PATH")
|
| 30 |
+
results_path = os.getenv("LOGICAL_REASONING_RESULTS_PATH")
|
| 31 |
+
|
| 32 |
+
print(model_name, load_in_4bit, data_path, results_path)
|
| 33 |
+
|
| 34 |
+
max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
|
| 35 |
+
dtype = (
|
| 36 |
+
None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
max_seq_length = 4096 # Choose any! We auto support RoPE Scaling internally!
|
| 41 |
+
dtype = (
|
| 42 |
+
None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
gpu_stats = torch.cuda.get_device_properties(0)
|
| 46 |
+
start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
|
| 47 |
+
max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
|
| 48 |
+
print(f"(1) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
|
| 49 |
+
print(f"{start_gpu_memory} GB of memory reserved.")
|
| 50 |
+
|
| 51 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
| 52 |
+
model_name=model_name,
|
| 53 |
+
max_seq_length=max_seq_length,
|
| 54 |
+
dtype=dtype,
|
| 55 |
+
load_in_4bit=load_in_4bit,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
gpu_stats = torch.cuda.get_device_properties(0)
|
| 59 |
+
start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
|
| 60 |
+
max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
|
| 61 |
+
print(f"(2) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
|
| 62 |
+
print(f"{start_gpu_memory} GB of memory reserved.")
|
| 63 |
+
|
| 64 |
+
model = FastLanguageModel.get_peft_model(
|
| 65 |
+
model,
|
| 66 |
+
r=16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
|
| 67 |
+
target_modules=[
|
| 68 |
+
"q_proj",
|
| 69 |
+
"k_proj",
|
| 70 |
+
"v_proj",
|
| 71 |
+
"o_proj",
|
| 72 |
+
"gate_proj",
|
| 73 |
+
"up_proj",
|
| 74 |
+
"down_proj",
|
| 75 |
+
],
|
| 76 |
+
lora_alpha=16,
|
| 77 |
+
lora_dropout=0, # Supports any, but = 0 is optimized
|
| 78 |
+
bias="none", # Supports any, but = "none" is optimized
|
| 79 |
+
# [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
|
| 80 |
+
use_gradient_checkpointing="unsloth", # True or "unsloth" for very long context
|
| 81 |
+
random_state=3407,
|
| 82 |
+
use_rslora=False, # We support rank stabilized LoRA
|
| 83 |
+
loftq_config=None, # And LoftQ
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
gpu_stats = torch.cuda.get_device_properties(0)
|
| 87 |
+
start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
|
| 88 |
+
max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
|
| 89 |
+
print(f"(3) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
|
| 90 |
+
print(f"{start_gpu_memory} GB of memory reserved.")
|
| 91 |
+
|
| 92 |
+
dataset = load_logical_reasoning_dataset(data_path, tokenizer=tokenizer, using_p1=False)
|
| 93 |
+
print_row_details(dataset["train"].to_pandas())
|
| 94 |
+
|
| 95 |
+
trainer = SFTTrainer(
|
| 96 |
+
model=model,
|
| 97 |
+
tokenizer=tokenizer,
|
| 98 |
+
train_dataset=dataset["train"],
|
| 99 |
+
dataset_text_field="train_text",
|
| 100 |
+
max_seq_length=max_seq_length,
|
| 101 |
+
dataset_num_proc=2,
|
| 102 |
+
packing=False, # Can make training 5x faster for short sequences.
|
| 103 |
+
args=TrainingArguments(
|
| 104 |
+
per_device_train_batch_size=2,
|
| 105 |
+
gradient_accumulation_steps=4,
|
| 106 |
+
warmup_steps=5,
|
| 107 |
+
max_steps=20000,
|
| 108 |
+
learning_rate=2e-4,
|
| 109 |
+
fp16=not is_bfloat16_supported(),
|
| 110 |
+
bf16=is_bfloat16_supported(),
|
| 111 |
+
logging_steps=100,
|
| 112 |
+
optim="adamw_8bit",
|
| 113 |
+
weight_decay=0.01,
|
| 114 |
+
lr_scheduler_type="linear",
|
| 115 |
+
seed=3407,
|
| 116 |
+
output_dir="outputs",
|
| 117 |
+
),
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
gpu_stats = torch.cuda.get_device_properties(0)
|
| 121 |
+
start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
|
| 122 |
+
max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
|
| 123 |
+
print(f"(4) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
|
| 124 |
+
print(f"{start_gpu_memory} GB of memory reserved.")
|
| 125 |
+
|
| 126 |
+
trainer_stats = trainer.train()
|
| 127 |
+
|
| 128 |
+
# @title Show final memory and time stats
|
| 129 |
+
used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
|
| 130 |
+
used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
|
| 131 |
+
used_percentage = round(used_memory / max_memory * 100, 3)
|
| 132 |
+
lora_percentage = round(used_memory_for_lora / max_memory * 100, 3)
|
| 133 |
+
print(f"(5) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
|
| 134 |
+
print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
|
| 135 |
+
print(
|
| 136 |
+
f"{round(trainer_stats.metrics['train_runtime']/60, 2)} minutes used for training."
|
| 137 |
+
)
|
| 138 |
+
print(f"Peak reserved memory = {used_memory} GB.")
|
| 139 |
+
print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
|
| 140 |
+
print(f"Peak reserved memory % of max memory = {used_percentage} %.")
|
| 141 |
+
print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")
|
| 142 |
+
|
| 143 |
+
print("Evaluating fine-tuned model: " + model_name)
|
| 144 |
+
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
|
| 145 |
+
predictions = eval_model(model, tokenizer, datasets["test"])
|
| 146 |
+
|
| 147 |
+
gpu_stats = torch.cuda.get_device_properties(0)
|
| 148 |
+
start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
|
| 149 |
+
max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
|
| 150 |
+
print(f"(6) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
|
| 151 |
+
print(f"{start_gpu_memory} GB of memory reserved.")
|
| 152 |
+
|
| 153 |
+
save_results(
|
| 154 |
+
model_name + "(unsloth_finetuned)",
|
| 155 |
+
results_path,
|
| 156 |
+
datasets["test"],
|
| 157 |
+
predictions,
|
| 158 |
+
debug=True,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
metrics = calc_metrics(datasets["test"]["label"], predictions, debug=True)
|
| 162 |
+
print(metrics)
|