FiendFlb commited on
Commit
03e8a0d
·
verified ·
1 Parent(s): be3e3bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -34
app.py CHANGED
@@ -1,64 +1,63 @@
1
  import gradio as gr
2
- from datasets import load_dataset, Dataset
3
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
4
  import torch
5
 
 
6
  def load_and_preprocess_data():
7
  # Load the dataset from the uploaded JSON file
8
- dataset = load_dataset('json', data_files='data.json')
9
-
10
- # Extract "prompt" and "chosen"/"rejected" as input-output pairs
11
- def process_row(example):
12
- prompts = []
13
- chosen_responses = []
14
- rejected_responses = []
15
-
16
- for row in example['rows']:
17
- prompts.append(row['row']['prompt'])
18
- chosen_responses.append(row['row']['chosen'])
19
- rejected_responses.append(row['row']['rejected'])
20
-
21
- return {
22
- 'prompt': prompts,
23
- 'chosen': chosen_responses,
24
- 'rejected': rejected_responses
25
- }
26
-
27
- # Apply the processing function to the dataset
28
- dataset = dataset.map(process_row, batched=True)
29
 
 
30
  # Load the tokenizer
31
  tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
32
 
33
  # Preprocess the dataset: tokenize inputs
34
- def preprocess_function(examples):
35
- return tokenizer(examples['prompt'], truncation=True, padding='max_length', max_length=512)
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  # Apply preprocessing to the dataset
38
  dataset = dataset.map(preprocess_function, batched=True)
39
 
 
 
 
40
  return dataset, tokenizer
 
 
41
  def train_model(dataset):
42
  # Load the model (BERT-based for sequence classification)
43
- model = AutoModelForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2) # Change num_labels if needed
44
 
45
  # Define training arguments
46
  training_args = TrainingArguments(
47
  output_dir='./results', # Output directory for model checkpoints
48
- evaluation_strategy="epoch", # Evaluation at the end of each epoch
49
- learning_rate=2e-5, # Learning rate
50
- per_device_train_batch_size=8, # Batch size for training
51
- per_device_eval_batch_size=8, # Batch size for evaluation
52
- num_train_epochs=3, # Number of training epochs
53
- weight_decay=0.01, # Strength of weight decay
54
  )
55
 
56
  # Initialize the Trainer
57
  trainer = Trainer(
58
  model=model,
59
  args=training_args,
60
- train_dataset=dataset['train'],
61
- eval_dataset=dataset['test'], # If you have a test split, otherwise just use train for both
62
  )
63
 
64
  # Train the model
@@ -68,10 +67,12 @@ def train_model(dataset):
68
 
69
  # Gradio Interface function to predict
70
  def predict(text):
 
71
  inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
 
72
  outputs = model(**inputs)
73
  prediction = torch.argmax(outputs.logits, dim=-1).item() # Get the class with the highest score
74
- return f"Prediction: {prediction}"
75
 
76
  # Main script to run training
77
  if __name__ == "__main__":
 
1
  import gradio as gr
2
+ from datasets import load_dataset
3
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
4
  import torch
5
 
6
+ # Load and preprocess dataset
7
  def load_and_preprocess_data():
8
  # Load the dataset from the uploaded JSON file
9
+ dataset = load_dataset('json', data_files='data.json')['train'] # Assuming single split
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ # The dataset already has 'prompt', 'chosen', and 'rejected'. We can preprocess directly.
12
  # Load the tokenizer
13
  tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
14
 
15
  # Preprocess the dataset: tokenize inputs
16
+ def preprocess_function(example):
17
+ inputs = tokenizer(
18
+ example['prompt'],
19
+ truncation=True,
20
+ padding='max_length',
21
+ max_length=512
22
+ )
23
+ # Assume binary classification: 1 for chosen, 0 for rejected
24
+ inputs['labels'] = [1] * len(example['chosen']) + [0] * len(example['rejected'])
25
+ inputs['input_ids'] = (
26
+ inputs['input_ids'][:len(example['chosen'])] +
27
+ inputs['input_ids'][len(example['chosen']):]
28
+ )
29
+ return inputs
30
 
31
  # Apply preprocessing to the dataset
32
  dataset = dataset.map(preprocess_function, batched=True)
33
 
34
+ # Convert dataset to PyTorch format
35
+ dataset.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'])
36
+
37
  return dataset, tokenizer
38
+
39
+ # Define and train the model
40
  def train_model(dataset):
41
  # Load the model (BERT-based for sequence classification)
42
+ model = AutoModelForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2)
43
 
44
  # Define training arguments
45
  training_args = TrainingArguments(
46
  output_dir='./results', # Output directory for model checkpoints
47
+ evaluation_strategy="epoch", # Evaluation at the end of each epoch
48
+ learning_rate=2e-5, # Learning rate
49
+ per_device_train_batch_size=8, # Batch size for training
50
+ per_device_eval_batch_size=8, # Batch size for evaluation
51
+ num_train_epochs=3, # Number of training epochs
52
+ weight_decay=0.01, # Strength of weight decay
53
  )
54
 
55
  # Initialize the Trainer
56
  trainer = Trainer(
57
  model=model,
58
  args=training_args,
59
+ train_dataset=dataset,
60
+ eval_dataset=dataset, # You can split the dataset for evaluation if needed
61
  )
62
 
63
  # Train the model
 
67
 
68
  # Gradio Interface function to predict
69
  def predict(text):
70
+ # Tokenize the input text
71
  inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
72
+ # Perform inference
73
  outputs = model(**inputs)
74
  prediction = torch.argmax(outputs.logits, dim=-1).item() # Get the class with the highest score
75
+ return f"Prediction: {'chosen' if prediction == 1 else 'rejected'}"
76
 
77
  # Main script to run training
78
  if __name__ == "__main__":