Spaces:
Runtime error
Runtime error
create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from unsloth import FastLanguageModel
|
3 |
+
import torch
|
4 |
+
import pandas as pd
|
5 |
+
from datasets import Dataset
|
6 |
+
import numpy as np
|
7 |
+
from sklearn.model_selection import train_test_split
|
8 |
+
from trl import SFTTrainer
|
9 |
+
from transformers import TrainingArguments
|
10 |
+
from unsloth import is_bfloat16_supported
|
11 |
+
|
12 |
+
max_seq_length = 4096 # Choose any! We auto support RoPE Scaling internally!
|
13 |
+
dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
|
14 |
+
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
|
15 |
+
|
16 |
+
|
17 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
18 |
+
model_name = "unsloth/tinyllama-bnb-4bit", # "unsloth/tinyllama" for 16bit loading
|
19 |
+
max_seq_length = max_seq_length,
|
20 |
+
dtype = dtype,
|
21 |
+
load_in_4bit = load_in_4bit,
|
22 |
+
)
|
23 |
+
|
24 |
+
model = FastLanguageModel.get_peft_model(
|
25 |
+
model,
|
26 |
+
r = 32, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
|
27 |
+
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
|
28 |
+
"gate_proj", "up_proj", "down_proj",],
|
29 |
+
lora_alpha = 32,
|
30 |
+
lora_dropout = 0, # Currently only supports dropout = 0
|
31 |
+
bias = "none", # Currently only supports bias = "none"
|
32 |
+
use_gradient_checkpointing = False, # @@@ IF YOU GET OUT OF MEMORY - set to True @@@
|
33 |
+
random_state = 3407,
|
34 |
+
use_rslora = False, # We support rank stabilized LoRA
|
35 |
+
loftq_config = None, # And LoftQ
|
36 |
+
)
|
37 |
+
|
38 |
+
alpaca_prompt = """Below is an instruction that describes a task, paired with an output that provides correct output for that task. Write a response that produces correct solution to the problem
|
39 |
+
|
40 |
+
### Instruction:
|
41 |
+
{}
|
42 |
+
|
43 |
+
### Input:
|
44 |
+
{}
|
45 |
+
|
46 |
+
### Response:
|
47 |
+
{}"""
|
48 |
+
|
49 |
+
EOS_TOKEN = tokenizer.eos_token
|
50 |
+
def formatting_prompts_func(examples):
|
51 |
+
instructions = "The problem has the following answer. Understand step-by-step how it is solved to produce the correct solution and then produce the correct solution"
|
52 |
+
inputs = examples["Riddle"]
|
53 |
+
outputs = examples["Answer"]
|
54 |
+
texts = []
|
55 |
+
for instruction, input, output in zip(instructions, inputs, outputs):
|
56 |
+
# Must add EOS_TOKEN, otherwise your generation will go on forever!
|
57 |
+
text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN
|
58 |
+
texts.append(text)
|
59 |
+
return { "text" : texts, }
|
60 |
+
|
61 |
+
|
62 |
+
|
63 |
+
df = pd.read_csv('math_riddles.csv')
|
64 |
+
train, test = train_test_split(df, test_size=0.2, random_state=42)
|
65 |
+
train_ds = Dataset.from_pandas(train)
|
66 |
+
test_ds = Dataset.from_pandas(test)
|
67 |
+
|
68 |
+
tokenized_train = train_ds.map(formatting_prompts_func, batched=True,
|
69 |
+
remove_columns=['Riddle', 'Answer', '__index_level_0__']) # Removing features
|
70 |
+
|
71 |
+
tokenized_test = test_ds.map(formatting_prompts_func, batched=True,
|
72 |
+
remove_columns=['Riddle', 'Answer']) # Removing features
|
73 |
+
|
74 |
+
|
75 |
+
|
76 |
+
trainer = SFTTrainer(
|
77 |
+
model = model,
|
78 |
+
tokenizer = tokenizer,
|
79 |
+
train_dataset = tokenized_train,
|
80 |
+
dataset_text_field = "text",
|
81 |
+
max_seq_length = max_seq_length,
|
82 |
+
dataset_num_proc = 24,
|
83 |
+
packing = True, # Packs short sequences together to save time!
|
84 |
+
args = TrainingArguments(
|
85 |
+
per_device_train_batch_size = 2,
|
86 |
+
gradient_accumulation_steps = 1,
|
87 |
+
warmup_ratio = 0.1,
|
88 |
+
num_train_epochs = 3,
|
89 |
+
learning_rate = 2e-5,
|
90 |
+
fp16 = not is_bfloat16_supported(),
|
91 |
+
bf16 = is_bfloat16_supported(),
|
92 |
+
logging_steps = 1,
|
93 |
+
optim = "adamw_8bit",
|
94 |
+
weight_decay = 0.1,
|
95 |
+
lr_scheduler_type = "linear",
|
96 |
+
seed = 3407,
|
97 |
+
output_dir = "outputs",
|
98 |
+
report_to = "none", # Use this for WandB etc
|
99 |
+
),
|
100 |
+
)
|
101 |
+
|
102 |
+
trainer_stats = trainer.train()
|
103 |
+
|
104 |
+
# Define inference function
|
105 |
+
def inference(instruction, user_input):
|
106 |
+
prompt = alpaca_prompt.format(
|
107 |
+
instruction,
|
108 |
+
user_input,
|
109 |
+
"" # Leave output blank for generation
|
110 |
+
)
|
111 |
+
|
112 |
+
inputs = tokenizer([prompt], return_tensors="pt").to("cuda")
|
113 |
+
|
114 |
+
outputs = model.generate(
|
115 |
+
**inputs,
|
116 |
+
max_new_tokens=64,
|
117 |
+
use_cache=True
|
118 |
+
)
|
119 |
+
|
120 |
+
# Fix: Define result before printing it
|
121 |
+
result = tokenizer.batch_decode(outputs)[0]
|
122 |
+
print(result) # Now you can print it
|
123 |
+
|
124 |
+
# Extract just the generated response (after the prompt)
|
125 |
+
response_prefix = "### Response:"
|
126 |
+
if response_prefix in result:
|
127 |
+
result = result.split(response_prefix)[1].strip()
|
128 |
+
|
129 |
+
return result
|
130 |
+
|
131 |
+
# Create Gradio interface
|
132 |
+
import gradio as gr
|
133 |
+
demo = gr.Interface(
|
134 |
+
fn=inference,
|
135 |
+
inputs=[
|
136 |
+
gr.Textbox(label="Instruction", value="Solve the problem"),
|
137 |
+
gr.Textbox(label="Input", value="There is a three digit number.The second digit is four times as big as the third digit, while the first digit is three less than the second digit.What is the number?")
|
138 |
+
],
|
139 |
+
outputs="text",
|
140 |
+
title="Language Model Interface",
|
141 |
+
description="Enter an instruction and input to generate a response from the model."
|
142 |
+
)
|
143 |
+
|
144 |
+
|
145 |
+
demo.launch(share=True)
|