FiendFlb commited on
Commit
bd92a3c
·
verified ·
1 Parent(s): ba4cdd2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -16
app.py CHANGED
@@ -13,7 +13,6 @@ def load_and_preprocess_data():
13
 
14
  # Preprocess the dataset: tokenize inputs
15
  def preprocess_function(examples):
16
- # Assuming 'examples' is a batch of examples
17
  max_length = 500 # Half of 1000 for each segment
18
  inputs = {
19
  'input_ids': [],
@@ -36,7 +35,7 @@ def load_and_preprocess_data():
36
 
37
  combined_input_ids = chosen_tokenized['input_ids'] + rejected_tokenized['input_ids']
38
  combined_attention_mask = chosen_tokenized['attention_mask'] + rejected_tokenized['attention_mask']
39
-
40
  # Pad or truncate to ensure length is 1000
41
  if len(combined_input_ids) > 1000:
42
  combined_input_ids = combined_input_ids[:1000]
@@ -45,14 +44,20 @@ def load_and_preprocess_data():
45
  padding_length = 1000 - len(combined_input_ids)
46
  combined_input_ids += [tokenizer.pad_token_id] * padding_length
47
  combined_attention_mask += [0] * padding_length
48
-
49
  inputs['input_ids'].append(combined_input_ids)
50
  inputs['attention_mask'].append(combined_attention_mask)
51
  inputs['labels'].append([1] * 500 + [0] * 500) # Adjust based on your label structure
52
-
 
 
 
 
 
53
  return inputs
 
54
  # Apply preprocessing to the dataset
55
- dataset = dataset.map(preprocess_function, batched=True)
56
 
57
  # Convert dataset to PyTorch format
58
  dataset.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'])
@@ -66,17 +71,27 @@ def train_model(dataset):
66
 
67
  # Define training arguments
68
  training_args = TrainingArguments(
69
- output_dir='./results', # Output directory for model checkpoints
70
- evaluation_strategy="epoch", # Evaluation at the end of each epoch
71
- learning_rate=2e-5, # Learning rate
72
- per_device_train_batch_size=4, # Reduced batch size due to longer sequences
73
- per_device_eval_batch_size=4, # Reduced batch size for evaluation
74
- num_train_epochs=3, # Number of training epochs
75
- weight_decay=0.01, # Strength of weight decay
76
  )
77
 
 
 
 
 
 
 
 
 
 
 
78
  # Initialize the Trainer
79
- trainer = Trainer(
80
  model=model,
81
  args=training_args,
82
  train_dataset=dataset,
@@ -91,7 +106,7 @@ def train_model(dataset):
91
  # Gradio Interface function to predict
92
  def predict(text):
93
  # Tokenize the input text
94
- inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=4096)
95
  # Perform inference
96
  outputs = model(**inputs)
97
  prediction = torch.argmax(outputs.logits, dim=-1).item() # Get the class with the highest score
@@ -105,5 +120,4 @@ if __name__ == "__main__":
105
  # Train the model
106
  model = train_model(dataset)
107
 
108
- # Create a Gradio interface for prediction
109
- gr.Interface(fn=predict, inputs=gr.Textbox(), outputs="text").launch()
 
13
 
14
  # Preprocess the dataset: tokenize inputs
15
  def preprocess_function(examples):
 
16
  max_length = 500 # Half of 1000 for each segment
17
  inputs = {
18
  'input_ids': [],
 
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
  # Pad or truncate to ensure length is 1000
40
  if len(combined_input_ids) > 1000:
41
  combined_input_ids = combined_input_ids[:1000]
 
44
  padding_length = 1000 - len(combined_input_ids)
45
  combined_input_ids += [tokenizer.pad_token_id] * padding_length
46
  combined_attention_mask += [0] * padding_length
47
+
48
  inputs['input_ids'].append(combined_input_ids)
49
  inputs['attention_mask'].append(combined_attention_mask)
50
  inputs['labels'].append([1] * 500 + [0] * 500) # Adjust based on your label structure
51
+
52
+ # Convert lists to tensors for each batch
53
+ inputs['input_ids'] = torch.tensor(inputs['input_ids'])
54
+ inputs['attention_mask'] = torch.tensor(inputs['attention_mask'])
55
+ inputs['labels'] = torch.tensor(inputs['labels'])
56
+
57
  return inputs
58
+
59
  # Apply preprocessing to the dataset
60
+ dataset = dataset.map(preprocess_function, batched=True, remove_columns=dataset.column_names)
61
 
62
  # Convert dataset to PyTorch format
63
  dataset.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'])
 
71
 
72
  # Define training arguments
73
  training_args = TrainingArguments(
74
+ output_dir='./results',
75
+ eval_strategy="epoch", # Updated from evaluation_strategy
76
+ learning_rate=2e-5,
77
+ per_device_train_batch_size=4,
78
+ per_device_eval_batch_size=4,
79
+ num_train_epochs=3,
80
+ weight_decay=0.01,
81
  )
82
 
83
+ # Initialize the Trainer with custom compute_loss to verify shapes
84
+ class CustomTrainer(Trainer):
85
+ def compute_loss(self, model, inputs, return_outputs=False):
86
+ outputs = model(**inputs)
87
+ logits = outputs.logits
88
+ labels = inputs['labels']
89
+ print(f"Logits shape: {logits.shape}, Labels shape: {labels.shape}") # Debugging
90
+ loss = self.loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
91
+ return (loss, outputs) if return_outputs else loss
92
+
93
  # Initialize the Trainer
94
+ trainer = CustomTrainer(
95
  model=model,
96
  args=training_args,
97
  train_dataset=dataset,
 
106
  # Gradio Interface function to predict
107
  def predict(text):
108
  # Tokenize the input text
109
+ inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=1000) # Adjust max_length to match preprocessing
110
  # Perform inference
111
  outputs = model(**inputs)
112
  prediction = torch.argmax(outputs.logits, dim=-1).item() # Get the class with the highest score
 
120
  # Train the model
121
  model = train_model(dataset)
122
 
123
+ # Create