|
a |
|
b/t5_train.py |
|
|
1 |
from datasets import Dataset, DatasetDict |
|
|
2 |
import torch |
|
|
3 |
from random import randrange, sample |
|
|
4 |
from transformers import DataCollatorForSeq2Seq |
|
|
5 |
import pandas as pd |
|
|
6 |
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM |
|
|
7 |
from peft import LoraConfig, get_peft_model, prepare_model_for_int8_training, TaskType |
|
|
8 |
from transformers import DataCollatorForSeq2Seq |
|
|
9 |
from transformers import Seq2SeqTrainer, Seq2SeqTrainingArguments |
|
|
10 |
import argparse |
|
|
11 |
import numpy as np |
|
|
12 |
from transformers import T5Tokenizer, T5ForConditionalGeneration |
|
|
13 |
import os |
|
|
14 |
from collections import Counter |
|
|
15 |
os.environ["CUDA_VISIBLE_DEVICES"] = "0" |
|
|
16 |
|
|
|
17 |
parser = argparse.ArgumentParser() |
|
|
18 |
parser.add_argument('--model_path', type=str, help='path to save fine-tuned t5 model') |
|
|
19 |
parser.add_argument('--model', type=str, help='pretrained t5', default='google/flan-t5-xl') |
|
|
20 |
parser.add_argument('--synthetic_data', type=str, help='path to synthetic data file') |
|
|
21 |
parser.add_argument('--adverse', action='store_true', help='only add adverse labels') |
|
|
22 |
parser.add_argument('--prompt', type=str, help='prepend string to prompt T5 model', default='summarize: ') |
|
|
23 |
parser.add_argument('--undersample', type=float, help='amount to keep', default=0.0) |
|
|
24 |
parser.add_argument('--gold', type=float, help='amount fo REAL data to keep', default=0.0) |
|
|
25 |
args = parser.parse_args() |
|
|
26 |
device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu") |
|
|
27 |
|
|
|
28 |
if args.adverse: |
|
|
29 |
LABELS = {'TRANSPORTATION_distance', 'TRANSPORTATION_resource', |
|
|
30 |
'TRANSPORTATION_other', 'HOUSING_poor', 'HOUSING_undomiciled','HOUSING_other', |
|
|
31 |
'RELATIONSHIP_divorced', 'RELATIONSHIP_widowed', 'RELATIONSHIP_single', |
|
|
32 |
'PARENT','EMPLOYMENT_underemployed','EMPLOYMENT_unemployed', 'EMPLOYMENT_disability','SUPPORT_minus'} |
|
|
33 |
else: |
|
|
34 |
LABELS = {'TRANSPORTATION_distance', 'TRANSPORTATION_resource', |
|
|
35 |
'TRANSPORTATION_other', 'HOUSING_poor', 'HOUSING_undomiciled', |
|
|
36 |
'HOUSING_other', 'RELATIONSHIP_married', 'RELATIONSHIP_partnered', |
|
|
37 |
'RELATIONSHIP_divorced', 'RELATIONSHIP_widowed', 'RELATIONSHIP_single', |
|
|
38 |
'PARENT','EMPLOYMENT_employed', 'EMPLOYMENT_underemployed', |
|
|
39 |
'EMPLOYMENT_unemployed', 'EMPLOYMENT_disability', 'EMPLOYMENT_retired', |
|
|
40 |
'EMPLOYMENT_student', 'SUPPORT_plus', 'SUPPORT_minus'} |
|
|
41 |
|
|
|
42 |
BROAD_LABELS = {lab.split('_')[0] for lab in LABELS} |
|
|
43 |
BROAD_LABELS.add('<NO_SDOH>') |
|
|
44 |
|
|
|
45 |
LABEL_BROAD_NARROW = LABELS.union(BROAD_LABELS) |
|
|
46 |
|
|
|
47 |
MODEL_ID= args.model |
|
|
48 |
TOKENIZER = AutoTokenizer.from_pretrained(MODEL_ID) |
|
|
49 |
|
|
|
50 |
MAX_S_LEN = 100 |
|
|
51 |
MAX_T_LEN = 40 |
|
|
52 |
|
|
|
53 |
|
|
|
54 |
def undersample(df, label, keep_percent): |
|
|
55 |
""" |
|
|
56 |
Undersamples the majority class in a Pandas dataframe to balance the classes. |
|
|
57 |
|
|
|
58 |
Parameters: |
|
|
59 |
df (pandas.DataFrame): The dataframe to undersample. |
|
|
60 |
keep_percent (float): The percentage of the majority class to keep. |
|
|
61 |
|
|
|
62 |
Returns: |
|
|
63 |
pandas.DataFrame: The undersampled dataframe. |
|
|
64 |
""" |
|
|
65 |
# Find the majority class based on the labels column |
|
|
66 |
counts = df[label].value_counts() |
|
|
67 |
majority_class = counts.idxmax() |
|
|
68 |
|
|
|
69 |
# Get the indices of rows in the majority class |
|
|
70 |
majority_indices = df[df[label] == majority_class].index |
|
|
71 |
|
|
|
72 |
# Calculate the number of majority class rows to keep |
|
|
73 |
num_majority_keep = int(keep_percent * counts[majority_class]) |
|
|
74 |
|
|
|
75 |
# Get a random subset of the majority class rows to keep |
|
|
76 |
majority_keep_indices = np.random.choice(majority_indices, num_majority_keep, replace=False) |
|
|
77 |
|
|
|
78 |
# Get the indices of rows in the minority class |
|
|
79 |
minority_indices = df[df[label] != majority_class].index |
|
|
80 |
|
|
|
81 |
# Combine the majority class subset and the minority class rows |
|
|
82 |
undersampled_indices = np.concatenate([majority_keep_indices, minority_indices]) |
|
|
83 |
|
|
|
84 |
# Return the undersampled dataframe |
|
|
85 |
return df.loc[undersampled_indices] |
|
|
86 |
|
|
|
87 |
|
|
|
88 |
def filter_rows_by_label_percentage(df, percentage): |
|
|
89 |
# Calculate the number of rows to keep for '<NO_SDOH>' label |
|
|
90 |
no_sdoh_rows = int(len(df[df['LABEL'] == '<NO_SDOH>']) * percentage) |
|
|
91 |
|
|
|
92 |
# Calculate the number of rows to keep for other label values |
|
|
93 |
other_rows = int(len(df[df['LABEL'] != '<NO_SDOH>']) * percentage) |
|
|
94 |
|
|
|
95 |
# Filter rows with '<NO_SDOH>' label and sample |
|
|
96 |
no_sdoh_data = df[df['LABEL'] == '<NO_SDOH>'].sample(n=no_sdoh_rows) |
|
|
97 |
|
|
|
98 |
# Filter rows with other label values and sample |
|
|
99 |
other_data = df[df['LABEL'] != '<NO_SDOH>'].sample(n=other_rows) |
|
|
100 |
|
|
|
101 |
# Concatenate the two filtered DataFrames |
|
|
102 |
filtered_df = pd.concat([no_sdoh_data, other_data]) |
|
|
103 |
|
|
|
104 |
filtered_df.reset_index(inplace=True, drop=True) |
|
|
105 |
|
|
|
106 |
return filtered_df |
|
|
107 |
|
|
|
108 |
|
|
|
109 |
def generate_label_list(row: pd.DataFrame) -> str: |
|
|
110 |
""" |
|
|
111 |
Generate a label list based on the given row from a Pandas DataFrame. |
|
|
112 |
|
|
|
113 |
Args: |
|
|
114 |
row (pd.DataFrame): A row from a Pandas DataFrame. |
|
|
115 |
|
|
|
116 |
Returns: |
|
|
117 |
str: A comma-separated string of labels extracted from the row. |
|
|
118 |
|
|
|
119 |
Examples: |
|
|
120 |
>>> df = pd.DataFrame({'label1_1': [1], 'label2_0': [0], 'label3_1': [1]}) |
|
|
121 |
>>> generate_label_list(df.iloc[0]) |
|
|
122 |
'label1,label3' |
|
|
123 |
|
|
|
124 |
>>> df = pd.DataFrame({'label2_0': [0], 'label3_0': [0]}) |
|
|
125 |
>>> generate_label_list(df.iloc[0]) |
|
|
126 |
'<NO_SDOH>' |
|
|
127 |
""" |
|
|
128 |
labels = set() |
|
|
129 |
for col_name, value in row.items(): |
|
|
130 |
if col_name in LABELS and value == 1: |
|
|
131 |
labels.add(col_name.split('_')[0]) |
|
|
132 |
if len(labels) == 0: |
|
|
133 |
labels.add('<NO_SDOH>') |
|
|
134 |
return ','.join(list(labels)) |
|
|
135 |
|
|
|
136 |
|
|
|
137 |
def preprocess_function(sample,padding="max_length"): |
|
|
138 |
# add prefix to the input for t5 |
|
|
139 |
inputs = [args.prompt + item for item in sample["text"]] |
|
|
140 |
# tokenize inputs |
|
|
141 |
model_inputs = TOKENIZER(inputs, max_length=MAX_S_LEN, padding=padding, truncation=True) |
|
|
142 |
|
|
|
143 |
# Tokenize targets with the `text_target` keyword argument |
|
|
144 |
labels = TOKENIZER(text_target=sample["SDOHlabels"], max_length=MAX_T_LEN, padding=padding, truncation=True) |
|
|
145 |
|
|
|
146 |
# If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore |
|
|
147 |
# padding in the loss. |
|
|
148 |
if padding == "max_length": |
|
|
149 |
labels["input_ids"] = [ |
|
|
150 |
[(l if l != TOKENIZER.pad_token_id else -100) for l in label] for label in labels["input_ids"] |
|
|
151 |
] |
|
|
152 |
model_inputs["labels"] = labels["input_ids"] |
|
|
153 |
return model_inputs |
|
|
154 |
|
|
|
155 |
|
|
|
156 |
if __name__ == '__main__': |
|
|
157 |
train_data = pd.read_csv('../data/train_sents.csv') |
|
|
158 |
train_data.fillna(value={'text':''}, inplace=True) |
|
|
159 |
train_data['LABEL'] = train_data.apply(generate_label_list, axis=1).tolist() |
|
|
160 |
|
|
|
161 |
if args.undersample: |
|
|
162 |
train_data = undersample(train_data, label='LABEL', keep_percent=args.undersample) |
|
|
163 |
if args.gold: |
|
|
164 |
train_data = filter_rows_by_label_percentage(train_data, args.gold) |
|
|
165 |
|
|
|
166 |
train_text = train_data['text'].tolist() |
|
|
167 |
train_labels = train_data['LABEL'].tolist() |
|
|
168 |
|
|
|
169 |
if args.synthetic_data: |
|
|
170 |
synthetic_data = pd.read_csv(args.synthetic_data) |
|
|
171 |
synthetic_data = synthetic_data[synthetic_data['label'].isin(BROAD_LABELS)] |
|
|
172 |
if args.adverse: |
|
|
173 |
synthetic_data = synthetic_data[synthetic_data['adverse']=='adverse'] |
|
|
174 |
synthetic_data.reset_index(inplace=True, drop=True) |
|
|
175 |
binary_synthetic = pd.get_dummies(synthetic_data['label']) |
|
|
176 |
binary_synthetic['text'] = synthetic_data['text'] |
|
|
177 |
synth_labels = binary_synthetic.apply(generate_label_list, axis=1).tolist() |
|
|
178 |
synth_text = synthetic_data['text'].tolist() |
|
|
179 |
|
|
|
180 |
train_text.extend(synth_text) |
|
|
181 |
train_labels.extend(synth_labels) |
|
|
182 |
|
|
|
183 |
train_t5 = pd.DataFrame({'text':train_text, 'SDOHlabels':train_labels}) |
|
|
184 |
train_dataset = Dataset.from_pandas(train_t5) |
|
|
185 |
|
|
|
186 |
|
|
|
187 |
dataset = DatasetDict() |
|
|
188 |
dataset['train'] = train_dataset |
|
|
189 |
print(f"Train dataset size: {len(dataset['train'])}") |
|
|
190 |
tokenized_dataset = dataset.map(preprocess_function, batched=True, remove_columns=["text", "SDOHlabels"]) |
|
|
191 |
|
|
|
192 |
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_ID, load_in_8bit=True, device_map={"":0}) #{"":1} |
|
|
193 |
|
|
|
194 |
# Define LoRA Config |
|
|
195 |
lora_config = LoraConfig( |
|
|
196 |
r=16, |
|
|
197 |
lora_alpha=32, |
|
|
198 |
target_modules=["q", "v"], |
|
|
199 |
lora_dropout=0.05, |
|
|
200 |
bias="none", |
|
|
201 |
task_type=TaskType.SEQ_2_SEQ_LM |
|
|
202 |
) |
|
|
203 |
# prepare int-8 model for training |
|
|
204 |
model = prepare_model_for_int8_training(model) |
|
|
205 |
|
|
|
206 |
# add LoRA adaptor |
|
|
207 |
model = get_peft_model(model, lora_config) |
|
|
208 |
model.print_trainable_parameters() |
|
|
209 |
|
|
|
210 |
# we want to ignore tokenizer pad token in the loss |
|
|
211 |
label_pad_token_id = -100 |
|
|
212 |
# Data collator |
|
|
213 |
data_collator = DataCollatorForSeq2Seq( |
|
|
214 |
TOKENIZER, |
|
|
215 |
model=model, |
|
|
216 |
label_pad_token_id=label_pad_token_id, |
|
|
217 |
pad_to_multiple_of=8 |
|
|
218 |
) |
|
|
219 |
|
|
|
220 |
peft_model_id = args.model_path |
|
|
221 |
output_dir = peft_model_id |
|
|
222 |
training_args = Seq2SeqTrainingArguments( |
|
|
223 |
output_dir=output_dir, |
|
|
224 |
per_device_train_batch_size=32, |
|
|
225 |
learning_rate=1e-3, # higher learning rate |
|
|
226 |
num_train_epochs=3, |
|
|
227 |
logging_dir=f"{output_dir}/logs", |
|
|
228 |
logging_strategy="steps", |
|
|
229 |
logging_steps=500, |
|
|
230 |
save_strategy="no", |
|
|
231 |
# report_to="tensorboard", |
|
|
232 |
) |
|
|
233 |
|
|
|
234 |
trainer = Seq2SeqTrainer( |
|
|
235 |
model=model, |
|
|
236 |
args=training_args, |
|
|
237 |
data_collator=data_collator, |
|
|
238 |
train_dataset=tokenized_dataset["train"], |
|
|
239 |
) |
|
|
240 |
model.config.use_cache = False # silence the warnings. Please re-enable for inference! |
|
|
241 |
|
|
|
242 |
# train model |
|
|
243 |
trainer.train() |
|
|
244 |
# Save our LoRA model & TOKENIZER results |
|
|
245 |
trainer.model.save_pretrained(output_dir) |
|
|
246 |
TOKENIZER.save_pretrained(output_dir) |