Update app.py
Browse files
app.py
CHANGED
|
@@ -5,13 +5,10 @@ import torch
|
|
| 5 |
|
| 6 |
# Load and preprocess dataset
|
| 7 |
def load_and_preprocess_data():
|
| 8 |
-
|
| 9 |
-
dataset = load_dataset('json', data_files='data.json')['train'] # Assuming single split
|
| 10 |
|
| 11 |
-
# Load the tokenizer
|
| 12 |
tokenizer = LongformerTokenizer.from_pretrained('allenai/longformer-base-4096')
|
| 13 |
|
| 14 |
-
# Preprocess the dataset: tokenize inputs
|
| 15 |
def preprocess_function(examples):
|
| 16 |
inputs = {
|
| 17 |
'input_ids': [],
|
|
@@ -19,101 +16,70 @@ def load_and_preprocess_data():
|
|
| 19 |
'labels': []
|
| 20 |
}
|
| 21 |
for example in examples['prompt']:
|
| 22 |
-
# Tokenize
|
| 23 |
-
|
| 24 |
example,
|
| 25 |
truncation=True,
|
| 26 |
padding='max_length',
|
| 27 |
-
max_length=
|
| 28 |
)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
)
|
| 35 |
-
|
| 36 |
-
combined_input_ids = chosen_tokenized['input_ids'] + rejected_tokenized['input_ids']
|
| 37 |
-
combined_attention_mask = chosen_tokenized['attention_mask'] + rejected_tokenized['attention_mask']
|
| 38 |
-
|
| 39 |
-
label_length = len(combined_input_ids)
|
| 40 |
-
# Ensure labels match the exact length of input_ids
|
| 41 |
-
inputs['input_ids'].append(combined_input_ids)
|
| 42 |
-
inputs['attention_mask'].append(combined_attention_mask)
|
| 43 |
-
inputs['labels'].append(torch.tensor([1] * (label_length // 16) + [0] * (label_length - label_length // 16)))
|
| 44 |
-
|
| 45 |
-
# Convert lists to tensors for each batch
|
| 46 |
inputs['input_ids'] = torch.tensor(inputs['input_ids'], dtype=torch.long)
|
| 47 |
inputs['attention_mask'] = torch.tensor(inputs['attention_mask'], dtype=torch.long)
|
| 48 |
-
inputs['labels'] = torch.
|
| 49 |
-
|
| 50 |
-
# Debugging
|
| 51 |
-
print(f"Input_ids shape: {inputs['input_ids'].shape}, Labels shape: {inputs['labels'].shape}")
|
| 52 |
-
|
| 53 |
return inputs
|
| 54 |
-
# Apply preprocessing to the dataset
|
| 55 |
-
dataset = dataset.map(preprocess_function, batched=True, remove_columns=dataset.column_names)
|
| 56 |
|
| 57 |
-
|
| 58 |
dataset.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'])
|
| 59 |
|
| 60 |
return dataset, tokenizer
|
| 61 |
|
| 62 |
# Define and train the model
|
| 63 |
def train_model(dataset):
|
| 64 |
-
# Load the Longformer model for sequence classification
|
| 65 |
model = LongformerForSequenceClassification.from_pretrained('allenai/longformer-base-4096', num_labels=2)
|
| 66 |
|
| 67 |
-
# Define training arguments
|
| 68 |
training_args = TrainingArguments(
|
| 69 |
-
output_dir='./results',
|
| 70 |
-
|
| 71 |
-
learning_rate=2e-5,
|
| 72 |
-
per_device_train_batch_size=4,
|
| 73 |
-
per_device_eval_batch_size=4,
|
| 74 |
-
num_train_epochs=3,
|
| 75 |
-
weight_decay=0.01,
|
| 76 |
)
|
| 77 |
|
| 78 |
-
# Initialize the Trainer with custom compute_loss to verify shapes
|
| 79 |
class CustomTrainer(Trainer):
|
| 80 |
-
def compute_loss(self, model, inputs, return_outputs=False
|
|
|
|
| 81 |
outputs = model(**inputs)
|
| 82 |
logits = outputs.logits
|
| 83 |
-
|
| 84 |
-
print(f"Logits shape: {logits.shape}, Labels shape: {labels.shape}") # Debugging
|
| 85 |
-
loss = self.loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 86 |
return (loss, outputs) if return_outputs else loss
|
| 87 |
|
| 88 |
-
# Initialize the Trainer
|
| 89 |
trainer = CustomTrainer(
|
| 90 |
model=model,
|
| 91 |
args=training_args,
|
| 92 |
train_dataset=dataset,
|
| 93 |
-
eval_dataset=dataset,
|
| 94 |
)
|
| 95 |
|
| 96 |
-
# Train the model
|
| 97 |
trainer.train()
|
| 98 |
-
|
| 99 |
return model
|
| 100 |
|
| 101 |
# Gradio Interface function to predict
|
| 102 |
def predict(text):
|
| 103 |
-
|
| 104 |
-
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=32) # Adjust max_length to match preprocessing
|
| 105 |
-
# Perform inference
|
| 106 |
outputs = model(**inputs)
|
| 107 |
-
prediction = torch.argmax(outputs.logits, dim=-1).item()
|
| 108 |
return f"Prediction: {'chosen' if prediction == 1 else 'rejected'}"
|
| 109 |
|
| 110 |
-
# Main script
|
| 111 |
if __name__ == "__main__":
|
| 112 |
-
# Load and preprocess the data
|
| 113 |
dataset, tokenizer = load_and_preprocess_data()
|
| 114 |
-
|
| 115 |
-
# Train the model
|
| 116 |
model = train_model(dataset)
|
| 117 |
-
|
| 118 |
-
# Create a Gradio interface for prediction
|
| 119 |
-
gr.Interface(fn=predict, inputs=gr.Textbox(), outputs="text").launch()
|
|
|
|
| 5 |
|
| 6 |
# Load and preprocess dataset
|
| 7 |
def load_and_preprocess_data():
|
| 8 |
+
dataset = load_dataset('json', data_files='data.json')['train']
|
|
|
|
| 9 |
|
|
|
|
| 10 |
tokenizer = LongformerTokenizer.from_pretrained('allenai/longformer-base-4096')
|
| 11 |
|
|
|
|
| 12 |
def preprocess_function(examples):
|
| 13 |
inputs = {
|
| 14 |
'input_ids': [],
|
|
|
|
| 16 |
'labels': []
|
| 17 |
}
|
| 18 |
for example in examples['prompt']:
|
| 19 |
+
# Tokenize input
|
| 20 |
+
tokenized = tokenizer(
|
| 21 |
example,
|
| 22 |
truncation=True,
|
| 23 |
padding='max_length',
|
| 24 |
+
max_length=128 # Increase max_length to suit model needs
|
| 25 |
)
|
| 26 |
+
|
| 27 |
+
inputs['input_ids'].append(tokenized['input_ids'])
|
| 28 |
+
inputs['attention_mask'].append(tokenized['attention_mask'])
|
| 29 |
+
inputs['labels'].append(1 if "chosen" in example else 0) # Assign binary labels
|
| 30 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
inputs['input_ids'] = torch.tensor(inputs['input_ids'], dtype=torch.long)
|
| 32 |
inputs['attention_mask'] = torch.tensor(inputs['attention_mask'], dtype=torch.long)
|
| 33 |
+
inputs['labels'] = torch.tensor(inputs['labels'], dtype=torch.long)
|
| 34 |
+
|
|
|
|
|
|
|
|
|
|
| 35 |
return inputs
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
dataset = dataset.map(preprocess_function, batched=True)
|
| 38 |
dataset.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'])
|
| 39 |
|
| 40 |
return dataset, tokenizer
|
| 41 |
|
| 42 |
# Define and train the model
|
| 43 |
def train_model(dataset):
|
|
|
|
| 44 |
model = LongformerForSequenceClassification.from_pretrained('allenai/longformer-base-4096', num_labels=2)
|
| 45 |
|
|
|
|
| 46 |
training_args = TrainingArguments(
|
| 47 |
+
output_dir='./results',
|
| 48 |
+
evaluation_strategy="epoch",
|
| 49 |
+
learning_rate=2e-5,
|
| 50 |
+
per_device_train_batch_size=4,
|
| 51 |
+
per_device_eval_batch_size=4,
|
| 52 |
+
num_train_epochs=3,
|
| 53 |
+
weight_decay=0.01,
|
| 54 |
)
|
| 55 |
|
|
|
|
| 56 |
class CustomTrainer(Trainer):
|
| 57 |
+
def compute_loss(self, model, inputs, return_outputs=False):
|
| 58 |
+
labels = inputs.pop("labels")
|
| 59 |
outputs = model(**inputs)
|
| 60 |
logits = outputs.logits
|
| 61 |
+
loss = torch.nn.CrossEntropyLoss()(logits.view(-1, model.config.num_labels), labels.view(-1))
|
|
|
|
|
|
|
| 62 |
return (loss, outputs) if return_outputs else loss
|
| 63 |
|
|
|
|
| 64 |
trainer = CustomTrainer(
|
| 65 |
model=model,
|
| 66 |
args=training_args,
|
| 67 |
train_dataset=dataset,
|
| 68 |
+
eval_dataset=dataset,
|
| 69 |
)
|
| 70 |
|
|
|
|
| 71 |
trainer.train()
|
|
|
|
| 72 |
return model
|
| 73 |
|
| 74 |
# Gradio Interface function to predict
|
| 75 |
def predict(text):
|
| 76 |
+
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=128)
|
|
|
|
|
|
|
| 77 |
outputs = model(**inputs)
|
| 78 |
+
prediction = torch.argmax(outputs.logits, dim=-1).item()
|
| 79 |
return f"Prediction: {'chosen' if prediction == 1 else 'rejected'}"
|
| 80 |
|
| 81 |
+
# Main script
|
| 82 |
if __name__ == "__main__":
|
|
|
|
| 83 |
dataset, tokenizer = load_and_preprocess_data()
|
|
|
|
|
|
|
| 84 |
model = train_model(dataset)
|
| 85 |
+
gr.Interface(fn=predict, inputs=gr.Textbox(), outputs="text").launch()
|
|
|
|
|
|