Imvikram99 commited on
Commit
bc8c903
1 Parent(s): 067109c
.history/app_20240217161705.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
+ import torch
4
+
5
+ # Load the trained model and tokenizer
6
+ model_path = "path/to/save/model"
7
+ tokenizer_path = "path/to/save/tokenizer"
8
+
9
+ model = AutoModelForSequenceClassification.from_pretrained(model_path)
10
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
11
+ model.eval() # Set model to evaluation mode
12
+
13
+ def predict_paraphrase(sentence1, sentence2):
14
+ # Tokenize the input sentences
15
+ inputs = tokenizer(sentence1, sentence2, return_tensors="pt", padding=True, truncation=True)
16
+ with torch.no_grad():
17
+ outputs = model(**inputs)
18
+
19
+ # Get probabilities
20
+ probs = torch.nn.functional.softmax(outputs.logits, dim=-1).tolist()[0]
21
+
22
+ # Assuming the first class (index 0) is 'not paraphrase' and the second class (index 1) is 'paraphrase'
23
+ return {"Not Paraphrase": probs[0], "Paraphrase": probs[1]}
24
+
25
+ # Create Gradio interface
26
+ iface = gr.Interface(
27
+ fn=predict_paraphrase,
28
+ inputs=[gr.inputs.Textbox(lines=2, placeholder="Enter Sentence 1 Here..."),
29
+ gr.inputs.Textbox(lines=2, placeholder="Enter Sentence 2 Here...")],
30
+ outputs=gr.outputs.Label(num_top_classes=2),
31
+ title="Paraphrase Identification",
32
+ description="This model predicts whether two sentences are paraphrases of each other."
33
+ )
34
+
35
+ iface.launch()
.history/app_20240217161710.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
+ import torch
4
+
5
+ # Load the trained model and tokenizer
6
+ model_path = "path/to/save/model"
7
+ tokenizer_path = "path/to/save/tokenizer"
8
+
9
+ model = AutoModelForSequenceClassification.from_pretrained(model_path)
10
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
11
+ model.eval() # Set model to evaluation mode
12
+
13
+ def predict_paraphrase(sentence1, sentence2):
14
+ # Tokenize the input sentences
15
+ inputs = tokenizer(sentence1, sentence2, return_tensors="pt", padding=True, truncation=True)
16
+ with torch.no_grad():
17
+ outputs = model(**inputs)
18
+
19
+ # Get probabilities
20
+ probs = torch.nn.functional.softmax(outputs.logits, dim=-1).tolist()[0]
21
+
22
+ # Assuming the first class (index 0) is 'not paraphrase' and the second class (index 1) is 'paraphrase'
23
+ return {"Not Paraphrase": probs[0], "Paraphrase": probs[1]}
24
+
25
+ # Create Gradio interface
26
+ iface = gr.Interface(
27
+ fn=predict_paraphrase,
28
+ inputs=[gr.inputs.Textbox(lines=2, placeholder="Enter Sentence 1 Here..."),
29
+ gr.inputs.Textbox(lines=2, placeholder="Enter Sentence 2 Here...")],
30
+ outputs=gr.outputs.Label(num_top_classes=2),
31
+ title="Paraphrase Identification",
32
+ description="This model predicts whether two sentences are paraphrases of each other."
33
+ )
34
+
35
+ iface.launch()
.history/trainml_20240217161632.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # First, we grab tools from our toolbox. These tools help us with different tasks like reading books (datasets),
2
+ # learning new languages (tokenization), and solving puzzles (models).
3
+ from datasets import load_dataset # This tool helps us get our book, where the puzzles are.
4
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, AdamW, get_scheduler # These help us understand and solve puzzles.
5
+ from transformers import DataCollatorWithPadding # This makes sure all puzzle pieces are the same size.
6
+ from torch.utils.data import DataLoader # This helps us handle one page of puzzles at a time.
7
+ import torch # This is like the brain of our operations, helping us think through puzzles.
8
+ from tqdm.auto import tqdm # This is our progress bar, showing us how far we've come in solving the book.
9
+ import evaluate # This tells us how well we did in solving puzzles.
10
+ from accelerate import Accelerator # This makes everything go super fast, like a rocket!
11
+
12
+ # Now, let's pick up the book we're going to solve today.
13
+ raw_datasets = load_dataset("glue", "mrpc") # This is a book filled with puzzles about matching sentences.
14
+
15
+ # Before we start solving puzzles, we need to understand the language they're written in.
16
+ checkpoint = "bert-base-uncased" # This is a guidebook to help us understand the puzzles' language.
17
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint) # This tool helps us read and understand the language in our book.
18
+
19
+ # To solve puzzles, we need to make sure we understand each sentence properly.
20
+ def tokenize_function(example): # This is like reading each sentence carefully and understanding each word.
21
+ return tokenizer(example["sentence1"], example["sentence2"], truncation=True)
22
+
23
+ # We prepare all puzzles in the book so they're ready to solve.
24
+ tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) # This is like marking all the important parts of the sentences.
25
+
26
+ # Puzzles can be different sizes, but our puzzle solver works best when all puzzles are the same size.
27
+ data_collator = DataCollatorWithPadding(tokenizer=tokenizer) # This adds extra paper to smaller puzzles to make them all the same size.
28
+
29
+ # We're setting up our puzzle pages, making sure we're ready to solve them one by one.
30
+ tokenized_datasets = tokenized_datasets.remove_columns(["sentence1", "sentence2", "idx"]) # We remove stuff we don't need.
31
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels") # We make sure the puzzle answers are labeled correctly.
32
+ tokenized_datasets.set_format("torch") # We make sure our puzzles are in the right format for our brain to understand.
33
+
34
+ # Now, we're ready to start solving puzzles, one page at a time.
35
+ train_dataloader = DataLoader(
36
+ tokenized_datasets["train"], shuffle=True, batch_size=8, collate_fn=data_collator
37
+ ) # This is our training puzzles.
38
+ eval_dataloader = DataLoader(
39
+ tokenized_datasets["validation"], batch_size=8, collate_fn=data_collator
40
+ ) # These are puzzles we use to check our progress.
41
+
42
+ # We need a puzzle solver, which is specially trained to solve these types of puzzles.
43
+ model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) # This is our puzzle-solving robot.
44
+
45
+ # Our robot needs instructions on how to get better at solving puzzles.
46
+ optimizer = AdamW(model.parameters(), lr=5e-5) # This tells our robot how to improve.
47
+ num_epochs = 3 # This is how many times we'll go through the whole book of puzzles.
48
+ num_training_steps = num_epochs * len(train_dataloader) # This is the total number of puzzles we'll solve.
49
+ lr_scheduler = get_scheduler(
50
+ "linear",
51
+ optimizer=optimizer,
52
+ num_warmup_steps=0,
53
+ num_training_steps=num_training_steps,
54
+ ) # This adjusts how quickly our robot learns over time.
55
+
56
+ # To solve puzzles super fast, we're going to use a rocket!
57
+ accelerator = Accelerator() # This is our rocket that makes everything go faster.
58
+ model, optimizer, train_dataloader, eval_dataloader = accelerator.prepare(
59
+ model, optimizer, train_dataloader, eval_dataloader
60
+ ) # We make sure our robot, our puzzles, and our instructions are all ready for the rocket.
61
+
62
+ # It's time to start solving puzzles!
63
+ progress_bar = tqdm(range(num_training_steps)) # This shows us our progress.
64
+ model.train() # We tell our robot it's time to start learning.
65
+ for epoch in range(num_epochs): # We go through our book of puzzles multiple times to get really good.
66
+ for batch in train_dataloader: # Each time, we take a page of puzzles to solve.
67
+ outputs = model(**batch) # Our robot tries to solve the puzzles.
68
+ loss = outputs.loss # We check how many mistakes it made.
69
+ accelerator.backward(loss) # We give feedback to our robot so it can learn from its mistakes.
70
+ optimizer.step() # We update our robot's puzzle-solving strategy.
71
+ lr_scheduler.step() # We adjust how quickly our robot is learning.
72
+ optimizer.zero_grad() # We reset some settings to make sure our robot is ready for the next page.
73
+ progress_bar.update(1) # We update our progress bar to show how many puzzles we've solved.
74
+
75
+ # After all that practice, it's time to test how good our robot has become at solving puzzles.
76
+ metric = evaluate.load("glue", "mrpc") # This is like the answer key to check our robot's work.
77
+ model.eval() # We tell our robot it's time to show what it's learned.
78
+ for batch in eval_dataloader: # We take a page of puzzles we haven't solved yet.
79
+ with torch.no_grad(): # We make sure we're just testing, not learning anymore.
80
+ outputs = model(**batch) # Our robot solves the puzzles.
81
+ logits = outputs.logits # We look at our robot's answers.
82
+ predictions = torch.argmax(logits, dim=-1) # We decide which answer our robot thinks is right.
83
+ metric.add_batch(predictions=predictions, references=batch["labels"]) # We compare our robot's answers to the correct answers.
84
+
85
+ final_score = metric.compute() # We calculate how well our robot did.
86
+ print(final_score) # We print out the score to see how well our robot solved the puzzles!
87
+
88
+ model.save_pretrained("path/to/save/model")
89
+ tokenizer.save_pretrained("path/to/save/tokenizer")
.history/trainml_20240217161633.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # First, we grab tools from our toolbox. These tools help us with different tasks like reading books (datasets),
2
+ # learning new languages (tokenization), and solving puzzles (models).
3
+ from datasets import load_dataset # This tool helps us get our book, where the puzzles are.
4
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, AdamW, get_scheduler # These help us understand and solve puzzles.
5
+ from transformers import DataCollatorWithPadding # This makes sure all puzzle pieces are the same size.
6
+ from torch.utils.data import DataLoader # This helps us handle one page of puzzles at a time.
7
+ import torch # This is like the brain of our operations, helping us think through puzzles.
8
+ from tqdm.auto import tqdm # This is our progress bar, showing us how far we've come in solving the book.
9
+ import evaluate # This tells us how well we did in solving puzzles.
10
+ from accelerate import Accelerator # This makes everything go super fast, like a rocket!
11
+
12
+ # Now, let's pick up the book we're going to solve today.
13
+ raw_datasets = load_dataset("glue", "mrpc") # This is a book filled with puzzles about matching sentences.
14
+
15
+ # Before we start solving puzzles, we need to understand the language they're written in.
16
+ checkpoint = "bert-base-uncased" # This is a guidebook to help us understand the puzzles' language.
17
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint) # This tool helps us read and understand the language in our book.
18
+
19
+ # To solve puzzles, we need to make sure we understand each sentence properly.
20
+ def tokenize_function(example): # This is like reading each sentence carefully and understanding each word.
21
+ return tokenizer(example["sentence1"], example["sentence2"], truncation=True)
22
+
23
+ # We prepare all puzzles in the book so they're ready to solve.
24
+ tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) # This is like marking all the important parts of the sentences.
25
+
26
+ # Puzzles can be different sizes, but our puzzle solver works best when all puzzles are the same size.
27
+ data_collator = DataCollatorWithPadding(tokenizer=tokenizer) # This adds extra paper to smaller puzzles to make them all the same size.
28
+
29
+ # We're setting up our puzzle pages, making sure we're ready to solve them one by one.
30
+ tokenized_datasets = tokenized_datasets.remove_columns(["sentence1", "sentence2", "idx"]) # We remove stuff we don't need.
31
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels") # We make sure the puzzle answers are labeled correctly.
32
+ tokenized_datasets.set_format("torch") # We make sure our puzzles are in the right format for our brain to understand.
33
+
34
+ # Now, we're ready to start solving puzzles, one page at a time.
35
+ train_dataloader = DataLoader(
36
+ tokenized_datasets["train"], shuffle=True, batch_size=8, collate_fn=data_collator
37
+ ) # This is our training puzzles.
38
+ eval_dataloader = DataLoader(
39
+ tokenized_datasets["validation"], batch_size=8, collate_fn=data_collator
40
+ ) # These are puzzles we use to check our progress.
41
+
42
+ # We need a puzzle solver, which is specially trained to solve these types of puzzles.
43
+ model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2) # This is our puzzle-solving robot.
44
+
45
+ # Our robot needs instructions on how to get better at solving puzzles.
46
+ optimizer = AdamW(model.parameters(), lr=5e-5) # This tells our robot how to improve.
47
+ num_epochs = 3 # This is how many times we'll go through the whole book of puzzles.
48
+ num_training_steps = num_epochs * len(train_dataloader) # This is the total number of puzzles we'll solve.
49
+ lr_scheduler = get_scheduler(
50
+ "linear",
51
+ optimizer=optimizer,
52
+ num_warmup_steps=0,
53
+ num_training_steps=num_training_steps,
54
+ ) # This adjusts how quickly our robot learns over time.
55
+
56
+ # To solve puzzles super fast, we're going to use a rocket!
57
+ accelerator = Accelerator() # This is our rocket that makes everything go faster.
58
+ model, optimizer, train_dataloader, eval_dataloader = accelerator.prepare(
59
+ model, optimizer, train_dataloader, eval_dataloader
60
+ ) # We make sure our robot, our puzzles, and our instructions are all ready for the rocket.
61
+
62
+ # It's time to start solving puzzles!
63
+ progress_bar = tqdm(range(num_training_steps)) # This shows us our progress.
64
+ model.train() # We tell our robot it's time to start learning.
65
+ for epoch in range(num_epochs): # We go through our book of puzzles multiple times to get really good.
66
+ for batch in train_dataloader: # Each time, we take a page of puzzles to solve.
67
+ outputs = model(**batch) # Our robot tries to solve the puzzles.
68
+ loss = outputs.loss # We check how many mistakes it made.
69
+ accelerator.backward(loss) # We give feedback to our robot so it can learn from its mistakes.
70
+ optimizer.step() # We update our robot's puzzle-solving strategy.
71
+ lr_scheduler.step() # We adjust how quickly our robot is learning.
72
+ optimizer.zero_grad() # We reset some settings to make sure our robot is ready for the next page.
73
+ progress_bar.update(1) # We update our progress bar to show how many puzzles we've solved.
74
+
75
+ # After all that practice, it's time to test how good our robot has become at solving puzzles.
76
+ metric = evaluate.load("glue", "mrpc") # This is like the answer key to check our robot's work.
77
+ model.eval() # We tell our robot it's time to show what it's learned.
78
+ for batch in eval_dataloader: # We take a page of puzzles we haven't solved yet.
79
+ with torch.no_grad(): # We make sure we're just testing, not learning anymore.
80
+ outputs = model(**batch) # Our robot solves the puzzles.
81
+ logits = outputs.logits # We look at our robot's answers.
82
+ predictions = torch.argmax(logits, dim=-1) # We decide which answer our robot thinks is right.
83
+ metric.add_batch(predictions=predictions, references=batch["labels"]) # We compare our robot's answers to the correct answers.
84
+
85
+ final_score = metric.compute() # We calculate how well our robot did.
86
+ print(final_score) # We print out the score to see how well our robot solved the puzzles!
87
+
88
+ model.save_pretrained("path/to/save/model")
89
+ tokenizer.save_pretrained("path/to/save/tokenizer")
.lh/app.py.json CHANGED
@@ -3,11 +3,19 @@
3
  "activeCommit": 0,
4
  "commits": [
5
  {
6
- "activePatchIndex": 0,
7
  "patches": [
8
  {
9
  "date": 1708166138917,
10
  "content": "Index: \n===================================================================\n--- \n+++ \n"
 
 
 
 
 
 
 
 
11
  }
12
  ],
13
  "date": 1708166138917,
 
3
  "activeCommit": 0,
4
  "commits": [
5
  {
6
+ "activePatchIndex": 2,
7
  "patches": [
8
  {
9
  "date": 1708166138917,
10
  "content": "Index: \n===================================================================\n--- \n+++ \n"
11
+ },
12
+ {
13
+ "date": 1708166825700,
14
+ "content": "Index: \n===================================================================\n--- \n+++ \n@@ -1,7 +1,35 @@\n import gradio as gr\n+from transformers import AutoTokenizer, AutoModelForSequenceClassification\n+import torch\n \n-def greet(name):\n- return \"Hello \" + name + \"!!\"\n+# Load the trained model and tokenizer\n\\n+model_path = \"path/to/save/model\"\n+tokenizer_path = \"path/to/save/tokenizer\"\n \n-iface = gr.Interface(fn=greet, inputs=\"text\", outputs=\"text\")\n-iface.launch()\n+model = AutoModelForSequenceClassification.from_pretrained(model_path)\n+tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)\n+model.eval() # Set model to evaluation mode\n+\n+def predict_paraphrase(sentence1, sentence2):\n+ # Tokenize the input sentences\n+ inputs = tokenizer(sentence1, sentence2, return_tensors=\"pt\", padding=True, truncation=True)\n+ with torch.no_grad():\n+ outputs = model(**inputs)\n+ \n+ # Get probabilities\n+ probs = torch.nn.functional.softmax(outputs.logits, dim=-1).tolist()[0]\n+ \n+ # Assuming the first class (index 0) is 'not paraphrase' and the second class (index 1) is 'paraphrase'\n+ return {\"Not Paraphrase\": probs[0], \"Paraphrase\": probs[1]}\n+\n+# Create Gradio interface\n+iface = gr.Interface(\n+ fn=predict_paraphrase,\n+ inputs=[gr.inputs.Textbox(lines=2, placeholder=\"Enter Sentence 1 Here...\"),\n+ gr.inputs.Textbox(lines=2, placeholder=\"Enter Sentence 2 Here...\")],\n+ outputs=gr.outputs.Label(num_top_classes=2),\n+ title=\"Paraphrase Identification\",\n+ description=\"This model predicts whether two sentences are paraphrases of each other.\"\n+)\n+\n+iface.launch()\n"
15
+ },
16
+ {
17
+ "date": 1708166830798,
18
+ "content": "Index: \n===================================================================\n--- \n+++ \n@@ -31,5 +31,5 @@\n title=\"Paraphrase Identification\",\n description=\"This model predicts whether two sentences are paraphrases of each other.\"\n )\n \n-iface.launch()\n\\n+iface.launch()\n"
19
  }
20
  ],
21
  "date": 1708166138917,
.lh/trainml.py.json CHANGED
@@ -3,11 +3,15 @@
3
  "activeCommit": 0,
4
  "commits": [
5
  {
6
- "activePatchIndex": 0,
7
  "patches": [
8
  {
9
  "date": 1708166375103,
10
  "content": "Index: \n===================================================================\n--- \n+++ \n"
 
 
 
 
11
  }
12
  ],
13
  "date": 1708166375103,
 
3
  "activeCommit": 0,
4
  "commits": [
5
  {
6
+ "activePatchIndex": 1,
7
  "patches": [
8
  {
9
  "date": 1708166375103,
10
  "content": "Index: \n===================================================================\n--- \n+++ \n"
11
+ },
12
+ {
13
+ "date": 1708166792627,
14
+ "content": "Index: \n===================================================================\n--- \n+++ \n@@ -83,4 +83,7 @@\n metric.add_batch(predictions=predictions, references=batch[\"labels\"]) # We compare our robot's answers to the correct answers.\n \n final_score = metric.compute() # We calculate how well our robot did.\n print(final_score) # We print out the score to see how well our robot solved the puzzles!\n+\n+model.save_pretrained(\"path/to/save/model\")\n+tokenizer.save_pretrained(\"path/to/save/tokenizer\")\n\\n"
15
  }
16
  ],
17
  "date": 1708166375103,
app.py CHANGED
@@ -1,7 +1,35 @@
1
  import gradio as gr
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
5
 
6
- iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
+ import torch
4
 
5
+ # Load the trained model and tokenizer
6
+ model_path = "path/to/save/model"
7
+ tokenizer_path = "path/to/save/tokenizer"
8
 
9
+ model = AutoModelForSequenceClassification.from_pretrained(model_path)
10
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
11
+ model.eval() # Set model to evaluation mode
12
+
13
+ def predict_paraphrase(sentence1, sentence2):
14
+ # Tokenize the input sentences
15
+ inputs = tokenizer(sentence1, sentence2, return_tensors="pt", padding=True, truncation=True)
16
+ with torch.no_grad():
17
+ outputs = model(**inputs)
18
+
19
+ # Get probabilities
20
+ probs = torch.nn.functional.softmax(outputs.logits, dim=-1).tolist()[0]
21
+
22
+ # Assuming the first class (index 0) is 'not paraphrase' and the second class (index 1) is 'paraphrase'
23
+ return {"Not Paraphrase": probs[0], "Paraphrase": probs[1]}
24
+
25
+ # Create Gradio interface
26
+ iface = gr.Interface(
27
+ fn=predict_paraphrase,
28
+ inputs=[gr.inputs.Textbox(lines=2, placeholder="Enter Sentence 1 Here..."),
29
+ gr.inputs.Textbox(lines=2, placeholder="Enter Sentence 2 Here...")],
30
+ outputs=gr.outputs.Label(num_top_classes=2),
31
+ title="Paraphrase Identification",
32
+ description="This model predicts whether two sentences are paraphrases of each other."
33
+ )
34
+
35
+ iface.launch()
trainml.py CHANGED
@@ -84,3 +84,6 @@ for batch in eval_dataloader: # We take a page of puzzles we haven't solved yet
84
 
85
  final_score = metric.compute() # We calculate how well our robot did.
86
  print(final_score) # We print out the score to see how well our robot solved the puzzles!
 
 
 
 
84
 
85
  final_score = metric.compute() # We calculate how well our robot did.
86
  print(final_score) # We print out the score to see how well our robot solved the puzzles!
87
+
88
+ model.save_pretrained("path/to/save/model")
89
+ tokenizer.save_pretrained("path/to/save/tokenizer")