Spaces:
Running
Running
Commit
·
badcb49
1
Parent(s):
da7dbd0
Edit the demo
Browse files- application.py +10 -10
- src/application/content_detection.py +12 -4
- src/texts/SimLLM/Refactor/bart_score.py +0 -205
- src/texts/SimLLM/Refactor/config.py +0 -115
- src/texts/SimLLM/Refactor/evaluation.py +0 -84
- src/texts/SimLLM/Refactor/main_text.py +0 -106
- src/texts/SimLLM/Refactor/models.py +0 -842
- src/texts/SimLLM/Refactor/proofreading.py +0 -354
- src/texts/SimLLM/Refactor/readme.md +0 -67
- src/texts/SimLLM/Refactor/utils.py +0 -527
- src/texts/SimLLM/SimLLM.py +0 -1667
- src/texts/SimLLM/bart_score.py +0 -136
application.py
CHANGED
@@ -4,7 +4,7 @@ import gradio as gr
|
|
4 |
import requests
|
5 |
from PIL import Image
|
6 |
|
7 |
-
from src.application.content_detection import
|
8 |
from src.application.url_reader import URLReader
|
9 |
from src.application.content_generation import generate_fake_image, generate_fake_text, replace_text
|
10 |
|
@@ -46,16 +46,16 @@ def generate_analysis_report(news_title:str, news_content: str, news_image: Imag
|
|
46 |
news_analysis.load_news(news_title, news_content, news_image)
|
47 |
return news_analysis.generate_analysis_report(), news_analysis.analyze_details()
|
48 |
|
49 |
-
news_analysis =
|
50 |
# Define the GUI
|
51 |
with gr.Blocks() as demo:
|
52 |
-
gr.Markdown("#
|
53 |
|
54 |
with gr.Row():
|
55 |
# SETTINGS
|
56 |
with gr.Column(scale=1):
|
57 |
with gr.Accordion("Settings"):
|
58 |
-
gr.Markdown("
|
59 |
|
60 |
with gr.Accordion("1. Enter a URL"):
|
61 |
url_input = gr.Textbox(
|
@@ -65,14 +65,14 @@ with gr.Blocks() as demo:
|
|
65 |
)
|
66 |
load_button = gr.Button("Load URL")
|
67 |
|
68 |
-
with gr.Accordion("2. Select content-generation models", open=True):
|
69 |
with gr.Row():
|
70 |
text_generation_model = gr.Dropdown(choices=AZURE_TEXT_MODEL, label="Text-generation model")
|
71 |
image_generation_model = gr.Dropdown(choices=AZURE_IMAGE_MODEL, label="Image-generation model")
|
72 |
generate_text_button = gr.Button("Generate text")
|
73 |
generate_image_button = gr.Button("Generate image")
|
74 |
|
75 |
-
with gr.Accordion("3. Replace any terms", open=True):
|
76 |
replace_df = gr.Dataframe(
|
77 |
headers=["Find what:", "Replace with:"],
|
78 |
datatype=["str", "str"],
|
@@ -84,15 +84,15 @@ with gr.Blocks() as demo:
|
|
84 |
|
85 |
# GENERATED CONTENT
|
86 |
with gr.Column(scale=1):
|
87 |
-
with gr.Accordion("
|
88 |
news_title = gr.Textbox(label="Title", value="")
|
89 |
news_image = gr.Image(label="Image", type="filepath")
|
90 |
news_content = gr.Textbox(label="Content", value="", lines=12)
|
91 |
|
92 |
-
#
|
93 |
with gr.Column(scale=1):
|
94 |
-
with gr.Accordion("
|
95 |
-
detection_button = gr.Button("
|
96 |
analyzed_information = gr.HTML()
|
97 |
with gr.Accordion("Detailed information"):
|
98 |
detailed_analysis = gr.HTML()
|
|
|
4 |
import requests
|
5 |
from PIL import Image
|
6 |
|
7 |
+
from src.application.content_detection import NewsVerification
|
8 |
from src.application.url_reader import URLReader
|
9 |
from src.application.content_generation import generate_fake_image, generate_fake_text, replace_text
|
10 |
|
|
|
46 |
news_analysis.load_news(news_title, news_content, news_image)
|
47 |
return news_analysis.generate_analysis_report(), news_analysis.analyze_details()
|
48 |
|
49 |
+
news_analysis = NewsVerification()
|
50 |
# Define the GUI
|
51 |
with gr.Blocks() as demo:
|
52 |
+
gr.Markdown("# NEWS VERIFICATION")
|
53 |
|
54 |
with gr.Row():
|
55 |
# SETTINGS
|
56 |
with gr.Column(scale=1):
|
57 |
with gr.Accordion("Settings"):
|
58 |
+
gr.Markdown("Give an URL or fill in news by yourself")
|
59 |
|
60 |
with gr.Accordion("1. Enter a URL"):
|
61 |
url_input = gr.Textbox(
|
|
|
65 |
)
|
66 |
load_button = gr.Button("Load URL")
|
67 |
|
68 |
+
with gr.Accordion("2. Select content-generation models", open=True, visible=False):
|
69 |
with gr.Row():
|
70 |
text_generation_model = gr.Dropdown(choices=AZURE_TEXT_MODEL, label="Text-generation model")
|
71 |
image_generation_model = gr.Dropdown(choices=AZURE_IMAGE_MODEL, label="Image-generation model")
|
72 |
generate_text_button = gr.Button("Generate text")
|
73 |
generate_image_button = gr.Button("Generate image")
|
74 |
|
75 |
+
with gr.Accordion("3. Replace any terms", open=True, visible=False):
|
76 |
replace_df = gr.Dataframe(
|
77 |
headers=["Find what:", "Replace with:"],
|
78 |
datatype=["str", "str"],
|
|
|
84 |
|
85 |
# GENERATED CONTENT
|
86 |
with gr.Column(scale=1):
|
87 |
+
with gr.Accordion("Input News"):
|
88 |
news_title = gr.Textbox(label="Title", value="")
|
89 |
news_image = gr.Image(label="Image", type="filepath")
|
90 |
news_content = gr.Textbox(label="Content", value="", lines=12)
|
91 |
|
92 |
+
# NEWS ANALYSIS REPORT
|
93 |
with gr.Column(scale=1):
|
94 |
+
with gr.Accordion("News Analysis"):
|
95 |
+
detection_button = gr.Button("Verify news")
|
96 |
analyzed_information = gr.HTML()
|
97 |
with gr.Accordion("Detailed information"):
|
98 |
detailed_analysis = gr.HTML()
|
src/application/content_detection.py
CHANGED
@@ -4,7 +4,7 @@ from src.application.text.model_detection import detect_text_by_ai_model
|
|
4 |
from src.application.text.search_detection import check_human, detect_text_by_relative_search
|
5 |
|
6 |
|
7 |
-
class
|
8 |
def __init__(self):
|
9 |
self.news_text = ""
|
10 |
self.news_title = ""
|
@@ -156,13 +156,21 @@ class NewsAnalysis():
|
|
156 |
if self.text_referent_url is None:
|
157 |
referred_news = "<li>No referent information</li>"
|
158 |
else:
|
159 |
-
|
160 |
-
|
|
|
|
|
|
|
|
|
161 |
|
162 |
if self.image_referent_url is None:
|
163 |
referred_image = "<li>No referent information</li>"
|
164 |
else:
|
165 |
-
|
|
|
|
|
|
|
|
|
166 |
|
167 |
html_template = f"""
|
168 |
<div>
|
|
|
4 |
from src.application.text.search_detection import check_human, detect_text_by_relative_search
|
5 |
|
6 |
|
7 |
+
class NewsVerification():
|
8 |
def __init__(self):
|
9 |
self.news_text = ""
|
10 |
self.news_title = ""
|
|
|
156 |
if self.text_referent_url is None:
|
157 |
referred_news = "<li>No referent information</li>"
|
158 |
else:
|
159 |
+
if len(self.text_referent_url) > 40:
|
160 |
+
url_max_length = 40
|
161 |
+
else:
|
162 |
+
url_max_length = len(self.text_referent_url)
|
163 |
+
|
164 |
+
referred_news = f"""<li><a href="{self.text_referent_url}" target="_blank">{"Referred news: " + self.text_referent_url[:url_max_length] + "..."}</a></li>"""
|
165 |
|
166 |
if self.image_referent_url is None:
|
167 |
referred_image = "<li>No referent information</li>"
|
168 |
else:
|
169 |
+
if len(self.image_referent_url) > 40:
|
170 |
+
url_max_length = 40
|
171 |
+
else:
|
172 |
+
url_max_length = len(self.text_referent_url)
|
173 |
+
referred_image = f"""<li><a href="{self.image_referent_url}" target="_blank">{"Referred news: " + self.image_referent_url[:url_max_length] + "..."}</a></li>"""
|
174 |
|
175 |
html_template = f"""
|
176 |
<div>
|
src/texts/SimLLM/Refactor/bart_score.py
DELETED
@@ -1,205 +0,0 @@
|
|
1 |
-
# %%
|
2 |
-
import traceback
|
3 |
-
from typing import List
|
4 |
-
|
5 |
-
import numpy as np
|
6 |
-
import torch
|
7 |
-
import torch.nn as nn
|
8 |
-
from transformers import (
|
9 |
-
BartForConditionalGeneration,
|
10 |
-
BartTokenizer,
|
11 |
-
)
|
12 |
-
|
13 |
-
from texts.config import (
|
14 |
-
BATCH_SIZE,
|
15 |
-
bart_scorer,
|
16 |
-
)
|
17 |
-
from texts.utils import normalize_text
|
18 |
-
|
19 |
-
|
20 |
-
class BARTScorer:
|
21 |
-
def __init__(
|
22 |
-
self,
|
23 |
-
device="cuda:0",
|
24 |
-
max_length=1024,
|
25 |
-
checkpoint="facebook/bart-large-cnn",
|
26 |
-
):
|
27 |
-
# Set up model
|
28 |
-
self.device = device
|
29 |
-
self.max_length = max_length
|
30 |
-
self.tokenizer = BartTokenizer.from_pretrained(checkpoint)
|
31 |
-
self.model = BartForConditionalGeneration.from_pretrained(checkpoint)
|
32 |
-
self.model.eval()
|
33 |
-
self.model.to(device)
|
34 |
-
|
35 |
-
# Set up loss
|
36 |
-
self.loss_fct = nn.NLLLoss(
|
37 |
-
reduction="none",
|
38 |
-
ignore_index=self.model.config.pad_token_id,
|
39 |
-
)
|
40 |
-
self.lsm = nn.LogSoftmax(dim=1)
|
41 |
-
|
42 |
-
def load(self, path=None):
|
43 |
-
"""Load model from paraphrase finetuning"""
|
44 |
-
if path is None:
|
45 |
-
path = "./bart.pth"
|
46 |
-
|
47 |
-
self.model.load_state_dict(torch.load(path, map_location=self.device))
|
48 |
-
|
49 |
-
def score(self, srcs, tgts, batch_size=16):
|
50 |
-
"""Score a batch of examples"""
|
51 |
-
score_list = []
|
52 |
-
for i in range(0, len(srcs), batch_size):
|
53 |
-
src_list = srcs[i : i + batch_size]
|
54 |
-
tgt_list = tgts[i : i + batch_size]
|
55 |
-
try:
|
56 |
-
with torch.no_grad():
|
57 |
-
encoded_src = self.tokenizer(
|
58 |
-
src_list,
|
59 |
-
max_length=self.max_length,
|
60 |
-
truncation=True,
|
61 |
-
padding=True,
|
62 |
-
return_tensors="pt",
|
63 |
-
)
|
64 |
-
encoded_tgt = self.tokenizer(
|
65 |
-
tgt_list,
|
66 |
-
max_length=self.max_length,
|
67 |
-
truncation=True,
|
68 |
-
padding=True,
|
69 |
-
return_tensors="pt",
|
70 |
-
)
|
71 |
-
src_tokens = encoded_src["input_ids"].to(self.device)
|
72 |
-
src_mask = encoded_src["attention_mask"].to(self.device)
|
73 |
-
|
74 |
-
tgt_tokens = encoded_tgt["input_ids"].to(self.device)
|
75 |
-
tgt_mask = encoded_tgt["attention_mask"]
|
76 |
-
tgt_len = tgt_mask.sum(dim=1).to(self.device)
|
77 |
-
|
78 |
-
output = self.model(
|
79 |
-
input_ids=src_tokens,
|
80 |
-
attention_mask=src_mask,
|
81 |
-
labels=tgt_tokens,
|
82 |
-
)
|
83 |
-
logits = output.logits.view(
|
84 |
-
-1,
|
85 |
-
self.model.config.vocab_size,
|
86 |
-
)
|
87 |
-
loss = self.loss_fct(self.lsm(logits), tgt_tokens.view(-1))
|
88 |
-
loss = loss.view(tgt_tokens.shape[0], -1)
|
89 |
-
loss = loss.sum(dim=1) / tgt_len
|
90 |
-
curr_score_list = [-x.item() for x in loss]
|
91 |
-
score_list += curr_score_list
|
92 |
-
|
93 |
-
except RuntimeError:
|
94 |
-
traceback.print_exc()
|
95 |
-
print(f"source: {src_list}")
|
96 |
-
print(f"target: {tgt_list}")
|
97 |
-
exit(0)
|
98 |
-
return score_list
|
99 |
-
|
100 |
-
def multi_ref_score(
|
101 |
-
self,
|
102 |
-
srcs,
|
103 |
-
tgts: List[List[str]],
|
104 |
-
agg="mean",
|
105 |
-
batch_size=4,
|
106 |
-
):
|
107 |
-
# Assert we have the same number of references
|
108 |
-
ref_nums = [len(x) for x in tgts]
|
109 |
-
if len(set(ref_nums)) > 1:
|
110 |
-
raise Exception(
|
111 |
-
"You have different number of references per test sample.",
|
112 |
-
)
|
113 |
-
|
114 |
-
ref_num = len(tgts[0])
|
115 |
-
score_matrix = []
|
116 |
-
for i in range(ref_num):
|
117 |
-
curr_tgts = [x[i] for x in tgts]
|
118 |
-
scores = self.score(srcs, curr_tgts, batch_size)
|
119 |
-
score_matrix.append(scores)
|
120 |
-
if agg == "mean":
|
121 |
-
score_list = np.mean(score_matrix, axis=0)
|
122 |
-
elif agg == "max":
|
123 |
-
score_list = np.max(score_matrix, axis=0)
|
124 |
-
else:
|
125 |
-
raise NotImplementedError
|
126 |
-
return list(score_list)
|
127 |
-
|
128 |
-
def test(self, batch_size=3):
|
129 |
-
"""Test"""
|
130 |
-
src_list = [
|
131 |
-
"This is a very good idea. Although simple, but very insightful.",
|
132 |
-
"Can I take a look?",
|
133 |
-
"Do not trust him, he is a liar.",
|
134 |
-
]
|
135 |
-
|
136 |
-
tgt_list = [
|
137 |
-
"That's stupid.",
|
138 |
-
"What's the problem?",
|
139 |
-
"He is trustworthy.",
|
140 |
-
]
|
141 |
-
|
142 |
-
print(self.score(src_list, tgt_list, batch_size))
|
143 |
-
|
144 |
-
|
145 |
-
def bart_score(text_1, text_2):
|
146 |
-
"""
|
147 |
-
Computes the BART score between two texts.
|
148 |
-
|
149 |
-
Parameters:
|
150 |
-
text_1 (str): The first text.
|
151 |
-
text_2 (str): The second text.
|
152 |
-
|
153 |
-
Returns:
|
154 |
-
float: The BART score.
|
155 |
-
"""
|
156 |
-
score = bart_scorer.score([text_1], [text_2])
|
157 |
-
return score
|
158 |
-
|
159 |
-
|
160 |
-
def check_bart_score(input_text, raw_text):
|
161 |
-
"""
|
162 |
-
Checks if the BART score between input_text and raw_text is above
|
163 |
-
a threshold.
|
164 |
-
|
165 |
-
Parameters:
|
166 |
-
input_text (str): The input text.
|
167 |
-
raw_text (str): The raw text to compare against.
|
168 |
-
|
169 |
-
Returns:
|
170 |
-
bool: True if the score is above the threshold, False otherwise.
|
171 |
-
"""
|
172 |
-
THRESHOLD = -2.459
|
173 |
-
normalized_text = normalize_text(raw_text)
|
174 |
-
score = bart_score(input_text, normalized_text)[0]
|
175 |
-
return score >= THRESHOLD
|
176 |
-
|
177 |
-
|
178 |
-
def bart_score_in_batch(text_1, text_2):
|
179 |
-
"""
|
180 |
-
Calculates the BART score for pairs of texts in batches.
|
181 |
-
|
182 |
-
Args:
|
183 |
-
text_1 (list of str): The first list of texts.
|
184 |
-
text_2 (list of str): The second list of texts.
|
185 |
-
|
186 |
-
Returns:
|
187 |
-
list: A list of BART scores for each pair of texts.
|
188 |
-
"""
|
189 |
-
return bart_scorer.score(text_1, text_2, batch_size=BATCH_SIZE)
|
190 |
-
|
191 |
-
|
192 |
-
def extract_feature_in_batch(text_1, text_2, feature_kind):
|
193 |
-
"""
|
194 |
-
Extracts features for pairs of texts using BART scores.
|
195 |
-
|
196 |
-
Args:
|
197 |
-
text_1 (list of str): The first list of texts.
|
198 |
-
text_2 (list of str): The second list of texts.
|
199 |
-
feature_kind (str): The type of feature to extract.
|
200 |
-
|
201 |
-
Returns:
|
202 |
-
list: A list of extracted features.
|
203 |
-
"""
|
204 |
-
features = bart_score_in_batch(text_1, text_2)
|
205 |
-
return features
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/texts/SimLLM/Refactor/config.py
DELETED
@@ -1,115 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import configparser
|
3 |
-
|
4 |
-
import google.generativeai as genai
|
5 |
-
import nltk
|
6 |
-
from datasets import load_metric
|
7 |
-
from langchain.chat_models import ChatOpenAI
|
8 |
-
from transformers import AutoTokenizer
|
9 |
-
|
10 |
-
from texts.bart_score import BARTScorer
|
11 |
-
|
12 |
-
|
13 |
-
# Constants
|
14 |
-
# TODO: move to .env
|
15 |
-
env = configparser.ConfigParser()
|
16 |
-
env.read(".env") # An example environment: .sample-env
|
17 |
-
|
18 |
-
# Get API key
|
19 |
-
OPENAI_API_KEY = env["API_KEY"]["OPENAI_API_KEY"]
|
20 |
-
GEMINI_API_KEY = env["API_KEY"]["GEMINI_API_KEY"]
|
21 |
-
TOGETHER_API_KEY = env["API_KEY"]["TOGETHER_API_KEY"]
|
22 |
-
|
23 |
-
# Environment setup
|
24 |
-
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
|
25 |
-
os.environ["GEMINI_API_KEY"] = GEMINI_API_KEY
|
26 |
-
os.environ["TOGETHER_API_KEY"] = TOGETHER_API_KEY
|
27 |
-
os.environ["CURL_CA_BUNDLE"] = ""
|
28 |
-
os.environ["REQUESTS_CA_BUNDLE"] = ""
|
29 |
-
|
30 |
-
# File Path
|
31 |
-
LOG_FILE = "data/99_log.txt"
|
32 |
-
OUTPUT_FILE = "data/result.txt"
|
33 |
-
METRIC_NAME = "roc_auc"
|
34 |
-
|
35 |
-
# Training and Model Parameters
|
36 |
-
TRAIN_RATIO = 0.8
|
37 |
-
VAL_RATIO = 0.1
|
38 |
-
NUMBER_OF_MAX_EPOCH_WITH_EARLY_STOPPING = 10
|
39 |
-
PATIENCE = 3
|
40 |
-
BATCH_SIZE = 64
|
41 |
-
OPTIMIZED_METRIC = "roc_auc"
|
42 |
-
SEED = 0
|
43 |
-
TEMPERATURE = 0.0
|
44 |
-
IS_OUTPUT_NORMALIZATION = False
|
45 |
-
RATIO = 0.9
|
46 |
-
HUMAN_LABEL = 0
|
47 |
-
MACHINE_LABEL = 1
|
48 |
-
BART = "bart"
|
49 |
-
|
50 |
-
# Model Options
|
51 |
-
MULTIMODEL = "multimodel"
|
52 |
-
SINGLE_FROM_MULTIMODEL = "single_from_multimodel"
|
53 |
-
|
54 |
-
# Downloading the NLTK "punkt" only if it's not already downloaded
|
55 |
-
nltk.download("punkt", quiet=True)
|
56 |
-
|
57 |
-
# API Models
|
58 |
-
# TODO: consider using an enum
|
59 |
-
API_ERROR = "API_ERROR"
|
60 |
-
IGNORE_BY_API_ERROR = "IGNORE_BY_API_ERROR"
|
61 |
-
CHATGPT = "ChatGPT"
|
62 |
-
GEMINI = "Gemini"
|
63 |
-
# LLAMA_2_70_CHAT_TEMP_0 = "LLaMa"
|
64 |
-
|
65 |
-
# Initialize BARTScorer
|
66 |
-
# TODO: consider loading model lazily
|
67 |
-
bart_scorer = BARTScorer(device="cuda:0", checkpoint="facebook/bart-large-cnn")
|
68 |
-
|
69 |
-
# Generative AI configuration
|
70 |
-
OPENAI_MODEL_NAME = "gpt-3.5-turbo-0125"
|
71 |
-
GEMINI_MODEL_NAME = "gemini-pro"
|
72 |
-
|
73 |
-
genai.configure(api_key=GEMINI_API_KEY, transport="rest")
|
74 |
-
GEMINI_MODEL = genai.GenerativeModel(
|
75 |
-
GEMINI_MODEL_NAME,
|
76 |
-
generation_config={"temperature": TEMPERATURE},
|
77 |
-
)
|
78 |
-
OPENAI_MODEL = ChatOpenAI(
|
79 |
-
temperature=TEMPERATURE,
|
80 |
-
model_name=OPENAI_MODEL_NAME,
|
81 |
-
)
|
82 |
-
|
83 |
-
# Model paths
|
84 |
-
MODEL_PATHS = {
|
85 |
-
"LLaMa": "meta-llama/Llama-2-70b-chat-hf",
|
86 |
-
"QWEN": "Qwen/Qwen1.5-72B-Chat",
|
87 |
-
"Yi": "NousResearch/Nous-Hermes-2-Yi-34B",
|
88 |
-
"Mixtral": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
89 |
-
"OLMo": "allenai/OLMo-7B-Instruct",
|
90 |
-
"Phi": "microsoft/phi-2",
|
91 |
-
"OpenChat": "openchat/openchat-3.5-1210",
|
92 |
-
"WizardLM": "WizardLM/WizardLM-13B-V1.2",
|
93 |
-
"Vicuna": "lmsys/vicuna-13b-v1.5",
|
94 |
-
}
|
95 |
-
|
96 |
-
TOGETHER_PATH = "https://api.together.xyz"
|
97 |
-
|
98 |
-
# Roberta model configurations
|
99 |
-
ROBERTA_BASE = "roberta-base"
|
100 |
-
ROBERTA_LARGE = "roberta-large"
|
101 |
-
ROBERTA_MODEL_PATHS = {
|
102 |
-
ROBERTA_BASE: "roberta-base",
|
103 |
-
ROBERTA_LARGE: "roberta-large",
|
104 |
-
}
|
105 |
-
LEARNING_RATES = {
|
106 |
-
ROBERTA_BASE: 2e-5,
|
107 |
-
ROBERTA_LARGE: 8e-6,
|
108 |
-
}
|
109 |
-
MODEL_NAME = ROBERTA_BASE
|
110 |
-
|
111 |
-
# Tokenizer initialization
|
112 |
-
tokenizer = AutoTokenizer.from_pretrained(ROBERTA_MODEL_PATHS[MODEL_NAME])
|
113 |
-
|
114 |
-
# Metric loading
|
115 |
-
metric = load_metric(METRIC_NAME)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/texts/SimLLM/Refactor/evaluation.py
DELETED
@@ -1,84 +0,0 @@
|
|
1 |
-
import nltk
|
2 |
-
import numpy as np
|
3 |
-
from config import metric
|
4 |
-
from utils import refine_candidate_text
|
5 |
-
|
6 |
-
from texts.bart_score import (
|
7 |
-
bart_score,
|
8 |
-
check_bart_score,
|
9 |
-
)
|
10 |
-
|
11 |
-
|
12 |
-
def compute_metrics(evaluation_predictions):
|
13 |
-
"""
|
14 |
-
Function to compute evaluation metrics for model predictions.
|
15 |
-
|
16 |
-
Parameters:
|
17 |
-
evaluation_predictions (tuple): A tuple containing two elements:
|
18 |
-
- predictions (array-like): The raw prediction scores from the model.
|
19 |
-
- labels (array-like): The true labels for the evaluation data.
|
20 |
-
|
21 |
-
Returns:
|
22 |
-
dict: A dictionary containing the computed evaluation metrics.
|
23 |
-
"""
|
24 |
-
# Unpack predictions and labels from the input tuple
|
25 |
-
raw_predictions, true_labels = evaluation_predictions
|
26 |
-
|
27 |
-
# Convert raw prediction scores to predicted class labels
|
28 |
-
predicted_labels = np.argmax(raw_predictions, axis=1)
|
29 |
-
|
30 |
-
# Compute and return the evaluation metrics
|
31 |
-
return metric.compute(
|
32 |
-
prediction_scores=predicted_labels,
|
33 |
-
references=true_labels,
|
34 |
-
average="macro",
|
35 |
-
)
|
36 |
-
|
37 |
-
|
38 |
-
def extract_by_best_similarity(input_text, raw_text):
|
39 |
-
"""
|
40 |
-
Extracts the best candidate string from the raw text based on the highest
|
41 |
-
similarity score compared to the input text. The similarity score is
|
42 |
-
calculated using the BART score.
|
43 |
-
|
44 |
-
Args:
|
45 |
-
input_text (str): The original text.
|
46 |
-
raw_text (str): The raw text containing multiple candidate strings.
|
47 |
-
|
48 |
-
Returns:
|
49 |
-
str: The best candidate string with the highest similarity score.
|
50 |
-
Returns the input text if no suitable candidate is found.
|
51 |
-
"""
|
52 |
-
|
53 |
-
# Refine the raw text
|
54 |
-
refined_raw_text = refine_candidate_text(input_text, raw_text)
|
55 |
-
|
56 |
-
# Tokenize the refined raw text into sentences
|
57 |
-
raw_candidates = nltk.sent_tokenize(refined_raw_text)
|
58 |
-
|
59 |
-
# Split sentences further by newlines to get individual candidates
|
60 |
-
candidate_list = []
|
61 |
-
for sentence in raw_candidates:
|
62 |
-
candidate_list.extend(sentence.split("\n"))
|
63 |
-
|
64 |
-
# Initialize variables to track the best similarity score
|
65 |
-
# and the best candidate
|
66 |
-
best_similarity = -9999
|
67 |
-
best_candidate = ""
|
68 |
-
|
69 |
-
# Iterate over each candidate to find the best one based on the BART score
|
70 |
-
for candidate in candidate_list:
|
71 |
-
refined_candidate = refine_candidate_text(input_text, candidate)
|
72 |
-
if check_bart_score(input_text, refined_candidate):
|
73 |
-
score = bart_score(input_text, refined_candidate)[0]
|
74 |
-
if score > best_similarity:
|
75 |
-
best_similarity = score
|
76 |
-
best_candidate = refined_candidate
|
77 |
-
|
78 |
-
# Print the best candidate found
|
79 |
-
print(f"best_candidate = {best_candidate}")
|
80 |
-
|
81 |
-
# Return the best candidate if found, otherwise return the input text
|
82 |
-
if best_candidate == "":
|
83 |
-
return input_text
|
84 |
-
return best_candidate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/texts/SimLLM/Refactor/main_text.py
DELETED
@@ -1,106 +0,0 @@
|
|
1 |
-
import argparse
|
2 |
-
|
3 |
-
from texts.config import CHATGPT
|
4 |
-
from texts.models import process_multi_models_with_validation
|
5 |
-
from texts.proofreading import generate_new_data_with_best_similarity
|
6 |
-
from texts.utils import generate_file_name
|
7 |
-
|
8 |
-
|
9 |
-
def main():
|
10 |
-
"""
|
11 |
-
Main function to handle argument parsing and execute the sequence of
|
12 |
-
operations including data generation and processing with multiple
|
13 |
-
models.
|
14 |
-
"""
|
15 |
-
parser = argparse.ArgumentParser(description="SimLLM.")
|
16 |
-
|
17 |
-
# Argument for specifying the list of large language models
|
18 |
-
parser.add_argument(
|
19 |
-
"--LLMs",
|
20 |
-
nargs="+",
|
21 |
-
default=[CHATGPT, "Yi", "OpenChat"],
|
22 |
-
help="List of large language models",
|
23 |
-
)
|
24 |
-
|
25 |
-
# Argument for specifying the list of training indexes
|
26 |
-
parser.add_argument(
|
27 |
-
"--train_indexes",
|
28 |
-
type=int,
|
29 |
-
default=[0, 1, 2],
|
30 |
-
nargs="+",
|
31 |
-
help="List of training indexes",
|
32 |
-
)
|
33 |
-
|
34 |
-
# Argument for specifying the list of testing indexes
|
35 |
-
parser.add_argument(
|
36 |
-
"--test_indexes",
|
37 |
-
type=int,
|
38 |
-
default=[0],
|
39 |
-
nargs="+",
|
40 |
-
help="List of testing indexes",
|
41 |
-
)
|
42 |
-
|
43 |
-
# Argument for specifying the number of samples
|
44 |
-
parser.add_argument(
|
45 |
-
"--num_samples",
|
46 |
-
type=int,
|
47 |
-
default=5000,
|
48 |
-
help="Number of samples",
|
49 |
-
)
|
50 |
-
|
51 |
-
# Parse the command-line arguments
|
52 |
-
args = parser.parse_args()
|
53 |
-
|
54 |
-
# Static dataset parameters
|
55 |
-
# dataset_name = "xsum"
|
56 |
-
# column_name = "document"
|
57 |
-
# num_samples = args.num_samples
|
58 |
-
output_file = "data/human.csv"
|
59 |
-
|
60 |
-
# Generate human data with shuffle
|
61 |
-
# generate_human_with_shuffle(
|
62 |
-
# dataset_name,
|
63 |
-
# column_name,
|
64 |
-
# num_samples,
|
65 |
-
# output_file,
|
66 |
-
# )
|
67 |
-
|
68 |
-
# Existing data parameters
|
69 |
-
existing_data_file = output_file
|
70 |
-
existing_kinds = []
|
71 |
-
|
72 |
-
# New kinds of models to generate data with
|
73 |
-
new_kinds = args.LLMs
|
74 |
-
|
75 |
-
# Generate new data with best similarity
|
76 |
-
generate_new_data_with_best_similarity(
|
77 |
-
existing_data_file,
|
78 |
-
existing_kinds,
|
79 |
-
new_kinds,
|
80 |
-
)
|
81 |
-
|
82 |
-
# Generate a filename for the multimodel CSV file
|
83 |
-
multimodel_csv_file = generate_file_name(
|
84 |
-
existing_data_file,
|
85 |
-
existing_kinds,
|
86 |
-
new_kinds,
|
87 |
-
)
|
88 |
-
|
89 |
-
# Number of samples to process (-1 means process all samples)
|
90 |
-
num_samples_to_process = -1
|
91 |
-
|
92 |
-
# Training and testing indexes from arguments
|
93 |
-
training_indexes = args.train_indexes
|
94 |
-
testing_indexes = args.test_indexes
|
95 |
-
|
96 |
-
# Process multiple models with validation
|
97 |
-
process_multi_models_with_validation(
|
98 |
-
multimodel_csv_file,
|
99 |
-
training_indexes,
|
100 |
-
testing_indexes,
|
101 |
-
num_samples_to_process,
|
102 |
-
)
|
103 |
-
|
104 |
-
|
105 |
-
if __name__ == "__main__":
|
106 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/texts/SimLLM/Refactor/models.py
DELETED
@@ -1,842 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import shutil
|
3 |
-
from copy import deepcopy
|
4 |
-
|
5 |
-
import numpy as np
|
6 |
-
from config import (
|
7 |
-
BART,
|
8 |
-
BATCH_SIZE,
|
9 |
-
HUMAN_LABEL,
|
10 |
-
LEARNING_RATES,
|
11 |
-
MACHINE_LABEL,
|
12 |
-
MODEL_NAME,
|
13 |
-
MULTIMODEL,
|
14 |
-
NUMBER_OF_MAX_EPOCH_WITH_EARLY_STOPPING,
|
15 |
-
OPTIMIZED_METRIC,
|
16 |
-
PATIENCE,
|
17 |
-
ROBERTA_MODEL_PATHS,
|
18 |
-
SINGLE_FROM_MULTIMODEL,
|
19 |
-
TRAIN_RATIO,
|
20 |
-
VAL_RATIO,
|
21 |
-
tokenizer,
|
22 |
-
)
|
23 |
-
from datasets import Dataset
|
24 |
-
from sklearn.base import accuracy_score
|
25 |
-
from sklearn.metrics import roc_auc_score
|
26 |
-
from sklearn.neural_network import MLPClassifier
|
27 |
-
from transformers import (
|
28 |
-
AutoModelForSequenceClassification,
|
29 |
-
DataCollatorWithPadding,
|
30 |
-
EarlyStoppingCallback,
|
31 |
-
Trainer,
|
32 |
-
TrainerCallback,
|
33 |
-
TrainingArguments,
|
34 |
-
)
|
35 |
-
|
36 |
-
from texts.bart_score import (
|
37 |
-
bart_score_in_batch,
|
38 |
-
extract_feature_in_batch,
|
39 |
-
)
|
40 |
-
from texts.config import OUTPUT_FILE
|
41 |
-
from texts.evaluation import compute_metrics
|
42 |
-
from texts.utils import (
|
43 |
-
check_error,
|
44 |
-
combine_text_with_BERT_format,
|
45 |
-
parse_multimodal_data,
|
46 |
-
write_to_file,
|
47 |
-
)
|
48 |
-
|
49 |
-
|
50 |
-
class TextDetector:
|
51 |
-
def __init__(self) -> None:
|
52 |
-
self.model = None
|
53 |
-
self.multimodel = None
|
54 |
-
self.train_data = None
|
55 |
-
self.val_data = None
|
56 |
-
self.test_data = None
|
57 |
-
self.train_features = None
|
58 |
-
self.val_features = None
|
59 |
-
self.test_features
|
60 |
-
|
61 |
-
def text_analysis(text: str) -> float:
|
62 |
-
score = 0.0
|
63 |
-
return score
|
64 |
-
|
65 |
-
|
66 |
-
class CustomCallback(TrainerCallback):
|
67 |
-
"""
|
68 |
-
Custom callback to evaluate the training dataset at the end of each epoch.
|
69 |
-
"""
|
70 |
-
|
71 |
-
def __init__(self, trainer) -> None:
|
72 |
-
super().__init__()
|
73 |
-
self._trainer = trainer
|
74 |
-
|
75 |
-
def on_epoch_end(self, args, state, control, **kwargs):
|
76 |
-
"""
|
77 |
-
At the end of each epoch, evaluate the training dataset.
|
78 |
-
"""
|
79 |
-
if control.should_evaluate:
|
80 |
-
control_copy = deepcopy(control)
|
81 |
-
self._trainer.evaluate(
|
82 |
-
eval_dataset=self._trainer.train_dataset,
|
83 |
-
metric_key_prefix="train",
|
84 |
-
)
|
85 |
-
return control_copy
|
86 |
-
|
87 |
-
|
88 |
-
def abstract_train(features, labels):
|
89 |
-
"""
|
90 |
-
Trains a model using the given features and labels.
|
91 |
-
|
92 |
-
Args:
|
93 |
-
features (list): The input features for training.
|
94 |
-
labels (list): The target labels for training.
|
95 |
-
|
96 |
-
Returns:
|
97 |
-
object: The trained model.
|
98 |
-
"""
|
99 |
-
model = MLPClassifier()
|
100 |
-
model.fit(features, labels)
|
101 |
-
return model
|
102 |
-
|
103 |
-
|
104 |
-
def evaluate_model(model, features, labels):
|
105 |
-
"""
|
106 |
-
Evaluates the model's performance using accuracy and ROC AUC scores.
|
107 |
-
|
108 |
-
Args:
|
109 |
-
model (object): The trained model to evaluate.
|
110 |
-
features (list): The input features for evaluation.
|
111 |
-
labels (list): The target labels for evaluation.
|
112 |
-
|
113 |
-
Returns:
|
114 |
-
None
|
115 |
-
"""
|
116 |
-
predictions = model.predict(features)
|
117 |
-
rounded_predictions = [round(value) for value in predictions]
|
118 |
-
|
119 |
-
accuracy = accuracy_score(labels, rounded_predictions)
|
120 |
-
write_to_file(OUTPUT_FILE, f"Accuracy: {accuracy * 100.0:.1f}%\n")
|
121 |
-
|
122 |
-
roc_auc = roc_auc_score(labels, rounded_predictions)
|
123 |
-
write_to_file(OUTPUT_FILE, f"ROC AUC: {roc_auc * 100.0:.1f}%\n")
|
124 |
-
|
125 |
-
|
126 |
-
def preprocess_function_multimodel(sample):
|
127 |
-
"""
|
128 |
-
Preprocesses a given sample for a multi-model setup by calculating
|
129 |
-
BART scores and formatting the text for BERT input.
|
130 |
-
|
131 |
-
Args:
|
132 |
-
sample (dict): A dictionary containing a key "text", which is a list of
|
133 |
-
lists of strings.
|
134 |
-
|
135 |
-
Returns:
|
136 |
-
dict: A dictionary containing tokenized and preprocessed text data.
|
137 |
-
"""
|
138 |
-
num_texts = len(sample["text"][0]) # Number of texts in each sub-sample
|
139 |
-
texts_grouped_by_index = [
|
140 |
-
[] for _ in range(num_texts)
|
141 |
-
] # Initialize empty lists for grouping texts by index
|
142 |
-
|
143 |
-
# Group texts by their index across sub-samples
|
144 |
-
for sub_sample in sample["text"]:
|
145 |
-
for i in range(num_texts):
|
146 |
-
texts_grouped_by_index[i].append(sub_sample[i])
|
147 |
-
|
148 |
-
# Calculate BART scores for each text pair (text[0] with text[i])
|
149 |
-
bart_scores = [
|
150 |
-
bart_score_in_batch(
|
151 |
-
texts_grouped_by_index[0],
|
152 |
-
texts_grouped_by_index[i],
|
153 |
-
)
|
154 |
-
for i in range(1, num_texts)
|
155 |
-
]
|
156 |
-
|
157 |
-
combined_texts = []
|
158 |
-
|
159 |
-
# Process each sub-sample for BERT input
|
160 |
-
for index, sub_sample in enumerate(sample["text"]):
|
161 |
-
text_array = [sub_sample[0]] # Start with the input text
|
162 |
-
score_generation_pairs = []
|
163 |
-
|
164 |
-
# Pair scores with their corresponding generations
|
165 |
-
for i in range(1, num_texts):
|
166 |
-
generation_text = sub_sample[i]
|
167 |
-
generation_score = bart_scores[i - 1][index]
|
168 |
-
score_generation_pairs.append((generation_score, generation_text))
|
169 |
-
|
170 |
-
# Sort pairs by score in descending order
|
171 |
-
sorted_pairs = sorted(score_generation_pairs, reverse=True)
|
172 |
-
|
173 |
-
# Append sorted texts to text_array
|
174 |
-
for _, sorted_text in sorted_pairs:
|
175 |
-
text_array.append(sorted_text)
|
176 |
-
|
177 |
-
# Combine texts into a single BERT-formatted string
|
178 |
-
combined_text = combine_text_with_BERT_format(text_array)
|
179 |
-
combined_texts.append(combined_text)
|
180 |
-
|
181 |
-
# Tokenize the combined texts for BERT
|
182 |
-
return tokenizer(combined_texts, add_special_tokens=False, truncation=True)
|
183 |
-
|
184 |
-
|
185 |
-
def preprocess_function_single_from_multimodel(sample):
|
186 |
-
"""
|
187 |
-
Extracts the first text from each sub-sample in a multi-model sample and
|
188 |
-
tokenizes it.
|
189 |
-
|
190 |
-
Args:
|
191 |
-
sample (dict): A dictionary containing a key "text", which is a list of
|
192 |
-
lists of strings.
|
193 |
-
|
194 |
-
Returns:
|
195 |
-
dict: A dictionary containing tokenized text data.
|
196 |
-
"""
|
197 |
-
combined_texts = []
|
198 |
-
|
199 |
-
# Iterate through each sub-sample
|
200 |
-
for sub_sample in sample["text"]:
|
201 |
-
input_text = sub_sample[
|
202 |
-
0
|
203 |
-
] # Extract the first text from the sub-sample
|
204 |
-
combined_texts.append(
|
205 |
-
input_text,
|
206 |
-
) # Append it to the list of combined texts
|
207 |
-
|
208 |
-
# Tokenize the combined texts
|
209 |
-
return tokenizer(combined_texts, truncation=True)
|
210 |
-
|
211 |
-
|
212 |
-
def train_only_by_transformer_with_test_evaluation_early_stop(
|
213 |
-
train_data,
|
214 |
-
test_data,
|
215 |
-
input_type,
|
216 |
-
num_classes=2,
|
217 |
-
):
|
218 |
-
"""
|
219 |
-
Trains a transformer model using the provided training and testing
|
220 |
-
datasets with early stopping.
|
221 |
-
|
222 |
-
Args:
|
223 |
-
train_data (Dataset): The training dataset.
|
224 |
-
test_data (Dataset): The testing dataset.
|
225 |
-
input_type (str): The type of input data, either MULTIMODEL or
|
226 |
-
SINGLE_FROM_MULTIMODEL.
|
227 |
-
num_classes (int, optional): The number of classes for classification.
|
228 |
-
Defaults to 2.
|
229 |
-
|
230 |
-
Returns:
|
231 |
-
Trainer: The trained model wrapped in a Trainer object.
|
232 |
-
"""
|
233 |
-
# Preprocess datasets based on the input type
|
234 |
-
if input_type == MULTIMODEL:
|
235 |
-
train_data = train_data.map(
|
236 |
-
preprocess_function_multimodel,
|
237 |
-
batched=True,
|
238 |
-
)
|
239 |
-
test_data = test_data.map(preprocess_function_multimodel, batched=True)
|
240 |
-
elif input_type == SINGLE_FROM_MULTIMODEL:
|
241 |
-
train_data = train_data.map(
|
242 |
-
preprocess_function_single_from_multimodel,
|
243 |
-
batched=True,
|
244 |
-
)
|
245 |
-
test_data = test_data.map(
|
246 |
-
preprocess_function_single_from_multimodel,
|
247 |
-
batched=True,
|
248 |
-
)
|
249 |
-
|
250 |
-
# Data collator to pad inputs
|
251 |
-
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
|
252 |
-
|
253 |
-
# Load appropriate model based on number of classes
|
254 |
-
if num_classes == 3:
|
255 |
-
model = AutoModelForSequenceClassification.from_pretrained(
|
256 |
-
"pretrained_model/roberta-base_num_labels_3",
|
257 |
-
num_labels=num_classes,
|
258 |
-
)
|
259 |
-
else:
|
260 |
-
model = AutoModelForSequenceClassification.from_pretrained(
|
261 |
-
ROBERTA_MODEL_PATHS[MODEL_NAME],
|
262 |
-
num_labels=num_classes,
|
263 |
-
)
|
264 |
-
|
265 |
-
learning_rate = LEARNING_RATES[MODEL_NAME]
|
266 |
-
output_folder = "training_with_callbacks"
|
267 |
-
|
268 |
-
# Remove the output folder if it already exists
|
269 |
-
if os.path.exists(output_folder):
|
270 |
-
shutil.rmtree(output_folder)
|
271 |
-
|
272 |
-
# Training arguments
|
273 |
-
training_args = TrainingArguments(
|
274 |
-
output_dir=output_folder,
|
275 |
-
evaluation_strategy="epoch",
|
276 |
-
logging_strategy="epoch",
|
277 |
-
save_strategy="epoch",
|
278 |
-
learning_rate=learning_rate,
|
279 |
-
per_device_train_batch_size=BATCH_SIZE,
|
280 |
-
per_device_eval_batch_size=BATCH_SIZE,
|
281 |
-
num_train_epochs=NUMBER_OF_MAX_EPOCH_WITH_EARLY_STOPPING,
|
282 |
-
weight_decay=0.01,
|
283 |
-
push_to_hub=False,
|
284 |
-
metric_for_best_model=OPTIMIZED_METRIC,
|
285 |
-
load_best_model_at_end=True,
|
286 |
-
)
|
287 |
-
|
288 |
-
# Create Trainer object
|
289 |
-
trainer = Trainer(
|
290 |
-
model=model,
|
291 |
-
args=training_args,
|
292 |
-
train_dataset=train_data,
|
293 |
-
eval_dataset=test_data,
|
294 |
-
tokenizer=tokenizer,
|
295 |
-
data_collator=data_collator,
|
296 |
-
compute_metrics=compute_metrics,
|
297 |
-
callbacks=[EarlyStoppingCallback(early_stopping_patience=PATIENCE)],
|
298 |
-
)
|
299 |
-
|
300 |
-
# Add custom callback
|
301 |
-
trainer.add_callback(CustomCallback(trainer))
|
302 |
-
|
303 |
-
# Start training
|
304 |
-
trainer.train()
|
305 |
-
|
306 |
-
return trainer
|
307 |
-
|
308 |
-
|
309 |
-
def create_pair_sample(data_item, training_indices):
|
310 |
-
"""
|
311 |
-
Creates pair samples for training by comparing human data with
|
312 |
-
machine-generated data.
|
313 |
-
|
314 |
-
Args:
|
315 |
-
data_item (dict): A dictionary containing 'human', 'single',
|
316 |
-
and 'pair' data.
|
317 |
-
training_indices (list): A list of indices used for training.
|
318 |
-
|
319 |
-
Returns:
|
320 |
-
list: A list of dictionaries, each containing a 'text' array
|
321 |
-
and a 'label'.
|
322 |
-
"""
|
323 |
-
# Initialize the result list
|
324 |
-
result_samples = []
|
325 |
-
|
326 |
-
# Check if there is any error in the data_item
|
327 |
-
if check_error(data_item):
|
328 |
-
return result_samples
|
329 |
-
|
330 |
-
# Create machine samples
|
331 |
-
for train_idx in training_indices:
|
332 |
-
if data_item["human"] != data_item["single"][train_idx]:
|
333 |
-
text_array = []
|
334 |
-
machine_text = data_item["single"][train_idx]
|
335 |
-
text_array.append(machine_text)
|
336 |
-
|
337 |
-
for sub_idx in training_indices:
|
338 |
-
text_array.append(data_item["pair"][train_idx][sub_idx])
|
339 |
-
|
340 |
-
sample = {
|
341 |
-
"text": text_array,
|
342 |
-
"label": MACHINE_LABEL,
|
343 |
-
}
|
344 |
-
result_samples.append(sample)
|
345 |
-
|
346 |
-
# Create human samples
|
347 |
-
text_array = [data_item["human"]]
|
348 |
-
|
349 |
-
for train_idx in training_indices:
|
350 |
-
text_array.append(data_item["single"][train_idx])
|
351 |
-
|
352 |
-
human_sample = {
|
353 |
-
"text": text_array,
|
354 |
-
"label": HUMAN_LABEL,
|
355 |
-
}
|
356 |
-
|
357 |
-
# Append human samples for each machine sample
|
358 |
-
num_machine_samples = len(result_samples)
|
359 |
-
for _ in range(num_machine_samples):
|
360 |
-
result_samples.append(human_sample)
|
361 |
-
|
362 |
-
return result_samples
|
363 |
-
|
364 |
-
|
365 |
-
def create_pair_test_sample(data_item, training_indices, testing_indices):
|
366 |
-
"""
|
367 |
-
Creates pair test samples by comparing human data with
|
368 |
-
machine-generated data.
|
369 |
-
|
370 |
-
Args:
|
371 |
-
data_item (dict): A dictionary containing 'human', 'single', and
|
372 |
-
'pair' data.
|
373 |
-
training_indices (list): A list of indices used for training.
|
374 |
-
testing_indices (list): A list of indices used for testing.
|
375 |
-
|
376 |
-
Returns:
|
377 |
-
list: A list of dictionaries, each containing a 'text' array and a
|
378 |
-
'label'.
|
379 |
-
"""
|
380 |
-
# Initialize the result list
|
381 |
-
result_samples = []
|
382 |
-
|
383 |
-
# Check if there is any error in the data_item
|
384 |
-
if check_error(data_item):
|
385 |
-
return result_samples
|
386 |
-
|
387 |
-
# Create machine samples based on testing indices
|
388 |
-
for test_idx in testing_indices:
|
389 |
-
if data_item["human"] != data_item["single"][test_idx]:
|
390 |
-
text_array = []
|
391 |
-
machine_text = data_item["single"][test_idx]
|
392 |
-
text_array.append(machine_text)
|
393 |
-
|
394 |
-
for train_idx in training_indices:
|
395 |
-
text_array.append(data_item["pair"][test_idx][train_idx])
|
396 |
-
|
397 |
-
sample = {
|
398 |
-
"text": text_array,
|
399 |
-
"label": MACHINE_LABEL,
|
400 |
-
}
|
401 |
-
result_samples.append(sample)
|
402 |
-
|
403 |
-
# Create human sample
|
404 |
-
text_array = [data_item["human"]]
|
405 |
-
|
406 |
-
for train_idx in training_indices:
|
407 |
-
text_array.append(data_item["single"][train_idx])
|
408 |
-
|
409 |
-
human_sample = {
|
410 |
-
"text": text_array,
|
411 |
-
"label": HUMAN_LABEL,
|
412 |
-
}
|
413 |
-
|
414 |
-
# Append the human sample for each machine sample
|
415 |
-
num_machine_samples = len(result_samples)
|
416 |
-
for _ in range(num_machine_samples):
|
417 |
-
result_samples.append(human_sample)
|
418 |
-
|
419 |
-
return result_samples
|
420 |
-
|
421 |
-
|
422 |
-
def create_train_val_sample(data, training_indices):
|
423 |
-
"""
|
424 |
-
Creates training and validation samples from the provided data.
|
425 |
-
|
426 |
-
Args:
|
427 |
-
data (list): A list of data items, each to be processed.
|
428 |
-
training_indices (list): A list of indices used for training.
|
429 |
-
|
430 |
-
Returns:
|
431 |
-
list: A list of training and validation samples created from the data.
|
432 |
-
"""
|
433 |
-
# Initialize the result list
|
434 |
-
result_samples = []
|
435 |
-
|
436 |
-
# Process each item in the data
|
437 |
-
for data_item in data:
|
438 |
-
# Create pair samples for the current item
|
439 |
-
sub_samples = create_pair_sample(data_item, training_indices)
|
440 |
-
|
441 |
-
# Extend the result list with the created sub-samples
|
442 |
-
result_samples.extend(sub_samples)
|
443 |
-
|
444 |
-
return result_samples
|
445 |
-
|
446 |
-
|
447 |
-
def create_test_sample(data, training_indices, testing_indices):
|
448 |
-
"""
|
449 |
-
Creates test samples from the provided data by comparing human data with
|
450 |
-
machine-generated data.
|
451 |
-
|
452 |
-
Args:
|
453 |
-
data (list): A list of data items, each to be processed.
|
454 |
-
training_indices (list): A list of indices used for training.
|
455 |
-
testing_indices (list): A list of indices used for testing.
|
456 |
-
|
457 |
-
Returns:
|
458 |
-
list: A list of test samples created from the data.
|
459 |
-
"""
|
460 |
-
# Initialize the result list
|
461 |
-
result_samples = []
|
462 |
-
|
463 |
-
# Process each item in the data
|
464 |
-
for data_item in data:
|
465 |
-
# Create pair test samples for the current item
|
466 |
-
sub_samples = create_pair_test_sample(
|
467 |
-
data_item,
|
468 |
-
training_indices,
|
469 |
-
testing_indices,
|
470 |
-
)
|
471 |
-
|
472 |
-
# Extend the result list with the created sub-samples
|
473 |
-
result_samples.extend(sub_samples)
|
474 |
-
|
475 |
-
return result_samples
|
476 |
-
|
477 |
-
|
478 |
-
def distribute_data(data, train_indices, test_indices, train_ratio, val_ratio):
|
479 |
-
"""
|
480 |
-
Distributes the data into training, validation, and test samples.
|
481 |
-
|
482 |
-
Args:
|
483 |
-
data (list): A list of data items to be split and processed.
|
484 |
-
train_indices (list): A list of indices used for training.
|
485 |
-
test_indices (list): A list of indices used for testing.
|
486 |
-
train_ratio (float): The ratio of data to be used for training.
|
487 |
-
val_ratio (float): The ratio of data to be used for validation.
|
488 |
-
|
489 |
-
Returns:
|
490 |
-
tuple: A tuple containing lists of training, validation,
|
491 |
-
and test samples.
|
492 |
-
"""
|
493 |
-
# Split the data into training, validation, and test sets
|
494 |
-
train_data, val_data, test_data = split_train_val_test(
|
495 |
-
data,
|
496 |
-
train_ratio,
|
497 |
-
val_ratio,
|
498 |
-
)
|
499 |
-
|
500 |
-
# Create training samples
|
501 |
-
train_samples = create_train_val_sample(train_data, train_indices)
|
502 |
-
write_to_file(OUTPUT_FILE, f"train samples = {len(train_samples)}\n")
|
503 |
-
|
504 |
-
# Create validation samples
|
505 |
-
val_samples = create_train_val_sample(val_data, train_indices)
|
506 |
-
write_to_file(OUTPUT_FILE, f"val samples = {len(val_samples)}\n")
|
507 |
-
|
508 |
-
# Create test samples
|
509 |
-
test_samples = create_test_sample(test_data, train_indices, test_indices)
|
510 |
-
write_to_file(OUTPUT_FILE, f"test samples = {len(test_samples)}\n")
|
511 |
-
|
512 |
-
return train_samples, val_samples, test_samples
|
513 |
-
|
514 |
-
|
515 |
-
def convert_to_huggingface_with_multimodel(samples):
|
516 |
-
"""
|
517 |
-
Converts a list of samples to the Hugging Face Dataset format.
|
518 |
-
|
519 |
-
Args:
|
520 |
-
samples (list): A list of samples to be converted.
|
521 |
-
|
522 |
-
Returns:
|
523 |
-
Dataset: A Hugging Face Dataset object created from the samples.
|
524 |
-
"""
|
525 |
-
return Dataset.from_list(samples)
|
526 |
-
|
527 |
-
|
528 |
-
def train_by_transformer_with_multimodel_and_early_stop(
|
529 |
-
train_samples,
|
530 |
-
val_samples,
|
531 |
-
input_type,
|
532 |
-
):
|
533 |
-
"""
|
534 |
-
Trains a transformer model with multimodal data and early stopping.
|
535 |
-
|
536 |
-
Args:
|
537 |
-
train_samples (list): A list of training samples.
|
538 |
-
val_samples (list): A list of validation samples.
|
539 |
-
input_type (str): The type of input data (e.g., multimodal).
|
540 |
-
|
541 |
-
Returns:
|
542 |
-
object: The trained model with early stopping.
|
543 |
-
"""
|
544 |
-
# Convert training and validation samples to Hugging Face Dataset format
|
545 |
-
train_data = convert_to_huggingface_with_multimodel(train_samples)
|
546 |
-
val_data = convert_to_huggingface_with_multimodel(val_samples)
|
547 |
-
|
548 |
-
# Train the model with early stopping and return the trained model
|
549 |
-
return train_only_by_transformer_with_test_evaluation_early_stop(
|
550 |
-
train_data,
|
551 |
-
val_data,
|
552 |
-
input_type,
|
553 |
-
)
|
554 |
-
|
555 |
-
|
556 |
-
def test_by_transformer_with_multimodel(detector, test_samples, input_type):
|
557 |
-
"""
|
558 |
-
Tests a trained transformer model with multimodal data.
|
559 |
-
|
560 |
-
Args:
|
561 |
-
detector (object): The trained model to be evaluated.
|
562 |
-
test_samples (list): A list of test samples.
|
563 |
-
input_type (str): The type of input data (e.g., multimodal).
|
564 |
-
|
565 |
-
Returns:
|
566 |
-
None
|
567 |
-
"""
|
568 |
-
# Convert test samples to Hugging Face Dataset format
|
569 |
-
test_data = convert_to_huggingface_with_multimodel(test_samples)
|
570 |
-
|
571 |
-
# Apply the appropriate preprocessing function based on the input type
|
572 |
-
if input_type == MULTIMODEL:
|
573 |
-
test_data = test_data.map(preprocess_function_multimodel, batched=True)
|
574 |
-
elif input_type == SINGLE_FROM_MULTIMODEL:
|
575 |
-
test_data = test_data.map(
|
576 |
-
preprocess_function_single_from_multimodel,
|
577 |
-
batched=True,
|
578 |
-
)
|
579 |
-
|
580 |
-
# Evaluate the model on the test data
|
581 |
-
result = detector.evaluate(eval_dataset=test_data)
|
582 |
-
|
583 |
-
# Extract and log the ROC AUC score
|
584 |
-
roc_auc = result["eval_roc_auc"]
|
585 |
-
write_to_file(OUTPUT_FILE, "roc_auc: %.1f%%" % (roc_auc * 100.0) + "\n")
|
586 |
-
|
587 |
-
|
588 |
-
def extract_by_feature_kind(samples, feature_type):
|
589 |
-
"""
|
590 |
-
Extracts features from the given samples based on the specified feature
|
591 |
-
type.
|
592 |
-
|
593 |
-
Args:
|
594 |
-
samples (list): A list of samples where each sample is a dictionary
|
595 |
-
with 'text' and 'label' keys.
|
596 |
-
feature_type (str): The type of feature to extract.
|
597 |
-
|
598 |
-
Returns:
|
599 |
-
tuple: A tuple containing the extracted features and corresponding
|
600 |
-
labels.
|
601 |
-
"""
|
602 |
-
text_1_list = []
|
603 |
-
text_2_list = []
|
604 |
-
labels = []
|
605 |
-
|
606 |
-
for sample in samples:
|
607 |
-
text_1_list.append(sample["text"][0])
|
608 |
-
text_2_list.append(sample["text"][1])
|
609 |
-
labels.append(sample["label"])
|
610 |
-
|
611 |
-
# Extract features in batch based on the feature type
|
612 |
-
features = extract_feature_in_batch(text_1_list, text_2_list, feature_type)
|
613 |
-
|
614 |
-
return features, labels
|
615 |
-
|
616 |
-
|
617 |
-
def train_by_feature_kind(train_samples, feature_type):
|
618 |
-
"""
|
619 |
-
Trains a model using features extracted from the training samples based on
|
620 |
-
the specified feature type.
|
621 |
-
|
622 |
-
Args:
|
623 |
-
train_samples (list): A list of training samples where each sample is
|
624 |
-
a dictionary with 'text' and 'label' keys.
|
625 |
-
feature_type (str): The type of feature to extract for training.
|
626 |
-
|
627 |
-
Returns:
|
628 |
-
object: The trained model.
|
629 |
-
"""
|
630 |
-
# Extract features and labels from the training samples
|
631 |
-
features, labels = extract_by_feature_kind(train_samples, feature_type)
|
632 |
-
|
633 |
-
# Convert features to a numpy array and reshape for training
|
634 |
-
features = np.array(features)
|
635 |
-
features = features.reshape(-1, 1)
|
636 |
-
|
637 |
-
# Train the model using the extracted features and labels
|
638 |
-
model = abstract_train(features, labels)
|
639 |
-
|
640 |
-
return model
|
641 |
-
|
642 |
-
|
643 |
-
def test_by_feature_kind(detector, samples, feature_type):
|
644 |
-
"""
|
645 |
-
Tests a detector using features extracted from the provided samples based
|
646 |
-
on the specified feature type.
|
647 |
-
|
648 |
-
Args:
|
649 |
-
detector (object): The detector model to be evaluated.
|
650 |
-
samples (list): A list of samples where each sample is a dictionary
|
651 |
-
with 'text' and 'label' keys.
|
652 |
-
feature_type (str): The type of feature to extract for testing.
|
653 |
-
|
654 |
-
Returns:
|
655 |
-
None
|
656 |
-
"""
|
657 |
-
# Extract features and labels from the samples
|
658 |
-
features, labels = extract_by_feature_kind(samples, feature_type)
|
659 |
-
|
660 |
-
# Convert features to a numpy array and reshape for evaluation
|
661 |
-
features = np.array(features)
|
662 |
-
features = features.reshape(-1, 1)
|
663 |
-
|
664 |
-
# Evaluate the detector model using the extracted features and labels
|
665 |
-
evaluate_model(detector, features, labels)
|
666 |
-
|
667 |
-
|
668 |
-
def general_process_multimodels_train_val_test(
|
669 |
-
train_samples,
|
670 |
-
val_samples,
|
671 |
-
test_samples,
|
672 |
-
):
|
673 |
-
"""
|
674 |
-
General process for training, validating, and testing models using
|
675 |
-
multi-model and feature kind approaches.
|
676 |
-
|
677 |
-
Args:
|
678 |
-
train_samples (list): Training samples.
|
679 |
-
val_samples (list): Validation samples.
|
680 |
-
test_samples (list): Test samples.
|
681 |
-
|
682 |
-
Returns:
|
683 |
-
None
|
684 |
-
"""
|
685 |
-
# Multi-model approach
|
686 |
-
input_kind = MULTIMODEL
|
687 |
-
write_to_file(OUTPUT_FILE, "\nInput kind = {input_kind} \n")
|
688 |
-
|
689 |
-
# Train detector using multi-model with early stopping
|
690 |
-
detector = train_by_transformer_with_multimodel_and_early_stop(
|
691 |
-
train_samples,
|
692 |
-
val_samples,
|
693 |
-
input_kind,
|
694 |
-
)
|
695 |
-
|
696 |
-
# Evaluate on train set
|
697 |
-
write_to_file(OUTPUT_FILE, "EVALUATE ON TRAIN SET \n")
|
698 |
-
test_by_transformer_with_multimodel(detector, train_samples, input_kind)
|
699 |
-
|
700 |
-
# Evaluate on validation set
|
701 |
-
write_to_file(OUTPUT_FILE, "EVALUATE ON VALIDATION SET \n")
|
702 |
-
test_by_transformer_with_multimodel(detector, val_samples, input_kind)
|
703 |
-
|
704 |
-
# Evaluate on test set
|
705 |
-
write_to_file(OUTPUT_FILE, "EVALUATE ON TEST SET \n")
|
706 |
-
test_by_transformer_with_multimodel(detector, test_samples, input_kind)
|
707 |
-
|
708 |
-
# Single from multi-model approach
|
709 |
-
input_kind = SINGLE_FROM_MULTIMODEL
|
710 |
-
write_to_file(OUTPUT_FILE, "\nInput kind = {input_kind} \n")
|
711 |
-
|
712 |
-
# Train detector using single from multi-model with early stopping
|
713 |
-
detector = train_by_transformer_with_multimodel_and_early_stop(
|
714 |
-
train_samples,
|
715 |
-
val_samples,
|
716 |
-
input_kind,
|
717 |
-
)
|
718 |
-
|
719 |
-
# Evaluate on train set
|
720 |
-
write_to_file(OUTPUT_FILE, "EVALUATE ON TRAIN SET \n")
|
721 |
-
test_by_transformer_with_multimodel(detector, train_samples, input_kind)
|
722 |
-
|
723 |
-
# Evaluate on validation set
|
724 |
-
write_to_file(OUTPUT_FILE, "EVALUATE ON VALIDATION SET \n")
|
725 |
-
test_by_transformer_with_multimodel(detector, val_samples, input_kind)
|
726 |
-
|
727 |
-
# Evaluate on test set
|
728 |
-
write_to_file(OUTPUT_FILE, "EVALUATE ON TEST SET \n")
|
729 |
-
test_by_transformer_with_multimodel(detector, test_samples, input_kind)
|
730 |
-
|
731 |
-
# Feature kind approach
|
732 |
-
sample_length = len(train_samples[0]["text"])
|
733 |
-
if (
|
734 |
-
sample_length == 2
|
735 |
-
): # Check if the sample length is 2, indicating BART feature kind
|
736 |
-
feature_kind = BART
|
737 |
-
write_to_file(OUTPUT_FILE, "\nFeature kind = {feature_kind} \n")
|
738 |
-
|
739 |
-
# Train detector using feature kind
|
740 |
-
detector = train_by_feature_kind(train_samples, feature_kind)
|
741 |
-
|
742 |
-
# Evaluate on train set
|
743 |
-
write_to_file(OUTPUT_FILE, "EVALUATE ON TRAIN SET \n")
|
744 |
-
test_by_feature_kind(detector, train_samples, feature_kind)
|
745 |
-
|
746 |
-
# Evaluate on validation set
|
747 |
-
write_to_file(OUTPUT_FILE, "EVALUATE ON VALIDATION SET \n")
|
748 |
-
test_by_feature_kind(detector, val_samples, feature_kind)
|
749 |
-
|
750 |
-
# Evaluate on test set
|
751 |
-
write_to_file(OUTPUT_FILE, "EVALUATE ON TEST SET \n")
|
752 |
-
test_by_feature_kind(detector, test_samples, feature_kind)
|
753 |
-
|
754 |
-
|
755 |
-
def process_multi_models_with_validation(
|
756 |
-
multimodel_csv_file,
|
757 |
-
train_indices,
|
758 |
-
test_indices,
|
759 |
-
num_samples,
|
760 |
-
):
|
761 |
-
"""
|
762 |
-
Processes multi-model data with validation, training, and testing.
|
763 |
-
|
764 |
-
Args:
|
765 |
-
multimodel_csv_file (str): Path to the CSV file containing
|
766 |
-
multi-model data.
|
767 |
-
train_indices (list): Indices for the training data.
|
768 |
-
test_indices (list): Indices for the testing data.
|
769 |
-
num_samples (int): Number of samples to process.
|
770 |
-
|
771 |
-
Returns:
|
772 |
-
None
|
773 |
-
"""
|
774 |
-
# Log the details of the process
|
775 |
-
write_to_file(OUTPUT_FILE, f"PROCESSING FILE={multimodel_csv_file} \n")
|
776 |
-
write_to_file(OUTPUT_FILE, f"EXPERIMENT WITH {MODEL_NAME} model \n")
|
777 |
-
write_to_file(
|
778 |
-
OUTPUT_FILE,
|
779 |
-
f"NUMBER OF MAX EPOCHS WITH EARLY STOPPING =\
|
780 |
-
{NUMBER_OF_MAX_EPOCH_WITH_EARLY_STOPPING} \n",
|
781 |
-
)
|
782 |
-
write_to_file(OUTPUT_FILE, f"PATIENCE = {PATIENCE} \n")
|
783 |
-
write_to_file(OUTPUT_FILE, f"OPTIMIZED METRIC = {OPTIMIZED_METRIC} \n")
|
784 |
-
write_to_file(OUTPUT_FILE, f"BATCH SIZE = {BATCH_SIZE} \n")
|
785 |
-
write_to_file(OUTPUT_FILE, f"Number of samples = {num_samples} \n")
|
786 |
-
|
787 |
-
# Read multi-model data from the CSV file
|
788 |
-
data = parse_multimodal_data(multimodel_csv_file)
|
789 |
-
|
790 |
-
# Limit data to the specified number of samples
|
791 |
-
data = data[:num_samples]
|
792 |
-
|
793 |
-
# Distribute data into training, validation, and testing sets
|
794 |
-
train_samples, val_samples, test_samples = distribute_data(
|
795 |
-
data,
|
796 |
-
train_indices,
|
797 |
-
test_indices,
|
798 |
-
TRAIN_RATIO,
|
799 |
-
VAL_RATIO,
|
800 |
-
)
|
801 |
-
|
802 |
-
# Log the training and testing indices
|
803 |
-
write_to_file(
|
804 |
-
OUTPUT_FILE,
|
805 |
-
f"Multimodel training with train indices {train_indices},\
|
806 |
-
test with test indices {test_indices} \n",
|
807 |
-
)
|
808 |
-
|
809 |
-
# Process the multi-models for training, validation, and testing
|
810 |
-
general_process_multimodels_train_val_test(
|
811 |
-
train_samples,
|
812 |
-
val_samples,
|
813 |
-
test_samples,
|
814 |
-
)
|
815 |
-
|
816 |
-
|
817 |
-
def split_train_val_test(data, train_ratio, val_ratio):
|
818 |
-
"""
|
819 |
-
Splits the dataset into training, validation, and test sets based on
|
820 |
-
specified ratios.
|
821 |
-
|
822 |
-
Args:
|
823 |
-
data (list): The dataset to be split.
|
824 |
-
train_ratio (float): The ratio of the dataset to be used for training.
|
825 |
-
val_ratio (float): The ratio of the dataset to be used for validation.
|
826 |
-
|
827 |
-
Returns:
|
828 |
-
tuple: A tuple containing three lists
|
829 |
-
(train_data, val_data, test_data).
|
830 |
-
"""
|
831 |
-
# Calculate the number of samples for the training set
|
832 |
-
num_train_samples = int(len(data) * train_ratio)
|
833 |
-
|
834 |
-
# Calculate the number of samples for the validation set
|
835 |
-
num_val_samples = int(len(data) * val_ratio)
|
836 |
-
|
837 |
-
# Split the data into training, validation, and test sets
|
838 |
-
train_data = data[:num_train_samples]
|
839 |
-
val_data = data[num_train_samples : (num_train_samples + num_val_samples)]
|
840 |
-
test_data = data[(num_train_samples + num_val_samples) :]
|
841 |
-
|
842 |
-
return train_data, val_data, test_data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
-
from evaluation import extract_by_best_similarity
|
15 |
-
from openai import OpenAI
|
16 |
-
from utils import (
|
17 |
-
generate_column_names,
|
18 |
-
generate_file_name,
|
19 |
-
get_column,
|
20 |
-
normalize_text,
|
21 |
-
print_and_log,
|
22 |
-
read_csv_data,
|
23 |
-
write_new_data,
|
24 |
-
write_to_csv,
|
25 |
-
)
|
26 |
-
|
27 |
-
|
28 |
-
def abstract_proofread(model_path, temperature, base_url, api_key, prompt):
|
29 |
-
"""
|
30 |
-
Function to proofread an abstract using an AI language model.
|
31 |
-
|
32 |
-
Parameters:
|
33 |
-
model_path (str): The path or identifier of the AI model to use.
|
34 |
-
temperature (float): Sampling temperature for the model's output.
|
35 |
-
base_url (str): The base URL for the API endpoint.
|
36 |
-
api_key (str): The API key for authentication.
|
37 |
-
prompt (str): The text prompt to provide to the AI for proofreading.
|
38 |
-
|
39 |
-
Returns:
|
40 |
-
str: The proofread abstract generated by the AI model.
|
41 |
-
"""
|
42 |
-
# Initialize the AI client with the provided API key and base URL
|
43 |
-
ai_client = OpenAI(api_key=api_key, base_url=base_url)
|
44 |
-
|
45 |
-
# Create a chat completion request with the system message and user prompt
|
46 |
-
chat_completion = ai_client.chat.completions.create(
|
47 |
-
messages=[
|
48 |
-
{
|
49 |
-
"role": "system",
|
50 |
-
"content": "You are an AI assistant",
|
51 |
-
},
|
52 |
-
{
|
53 |
-
"role": "user",
|
54 |
-
"content": prompt,
|
55 |
-
},
|
56 |
-
],
|
57 |
-
model=model_path,
|
58 |
-
max_tokens=1024,
|
59 |
-
temperature=temperature,
|
60 |
-
)
|
61 |
-
|
62 |
-
# Return the content of the first choice's message
|
63 |
-
return chat_completion.choices[0].message.content
|
64 |
-
|
65 |
-
|
66 |
-
def proofread_by_model_name(model_name, input_text, normalize_output):
|
67 |
-
"""
|
68 |
-
Proofreads the given input text using the specified model.
|
69 |
-
|
70 |
-
Args:
|
71 |
-
model_name (str): The name of the model to use for proofreading.
|
72 |
-
input_text (str): The text to be proofread.
|
73 |
-
normalize_output (bool): Whether to normalize the output or not.
|
74 |
-
|
75 |
-
Returns:
|
76 |
-
str: The proofread text.
|
77 |
-
"""
|
78 |
-
# Constants for API access
|
79 |
-
base_url = TOGETHER_PATH
|
80 |
-
api_key = TOGETHER_API_KEY
|
81 |
-
temperature = TEMPERATURE
|
82 |
-
|
83 |
-
# Retrieve the model path from the dictionary
|
84 |
-
if model_name in MODEL_PATHS:
|
85 |
-
model_path = MODEL_PATHS[model_name]
|
86 |
-
else:
|
87 |
-
raise ValueError("Model name not found in the dictionary.")
|
88 |
-
|
89 |
-
# Formulate the prompt for the model
|
90 |
-
prompt = f"Proofreading for the text: ```{input_text}```"
|
91 |
-
|
92 |
-
# Apply output normalization if required
|
93 |
-
if normalize_output:
|
94 |
-
prompt = output_normalization(prompt)
|
95 |
-
|
96 |
-
# Debugging: Print the prompt
|
97 |
-
print(f"Prompt: {prompt}")
|
98 |
-
|
99 |
-
# Call the abstract proofreading function with the prepared parameters
|
100 |
-
return abstract_proofread(
|
101 |
-
model_path,
|
102 |
-
temperature,
|
103 |
-
base_url,
|
104 |
-
api_key,
|
105 |
-
prompt,
|
106 |
-
)
|
107 |
-
|
108 |
-
|
109 |
-
def gemini_proofread(input_text, normalize_output):
|
110 |
-
"""
|
111 |
-
Proofreads the given text using the GEMINI_MODEL.
|
112 |
-
|
113 |
-
Parameters:
|
114 |
-
input_text (str): The text to be proofread.
|
115 |
-
normalize_output (bool): Flag indicating whether to normalize the output.
|
116 |
-
|
117 |
-
Returns:
|
118 |
-
str: The proofread text.
|
119 |
-
"""
|
120 |
-
prompt = f"Proofreading for the text: ```{input_text}```"
|
121 |
-
if normalize_output:
|
122 |
-
prompt = output_normalization(prompt)
|
123 |
-
response = GEMINI_MODEL.generate_content(prompt)
|
124 |
-
return response.text
|
125 |
-
|
126 |
-
|
127 |
-
def chatGPT_proofread(input_text, normalize_output):
|
128 |
-
"""
|
129 |
-
Proofreads the given text using the chat_model.
|
130 |
-
|
131 |
-
Parameters:
|
132 |
-
input_text (str): The text to be proofread.
|
133 |
-
normalize_output (bool): Flag indicating whether to normalize the output.
|
134 |
-
|
135 |
-
Returns:
|
136 |
-
str: The proofread text.
|
137 |
-
"""
|
138 |
-
prompt = f"Proofreading for the text: ```{input_text}```"
|
139 |
-
if normalize_output:
|
140 |
-
prompt = output_normalization(prompt)
|
141 |
-
|
142 |
-
print(f"Starting API call with prompt: {prompt}")
|
143 |
-
result = OPENAI_MODEL.predict(prompt)
|
144 |
-
print(f"Ending API call with prompt: {prompt}")
|
145 |
-
|
146 |
-
return result
|
147 |
-
|
148 |
-
|
149 |
-
def output_normalization(prompt):
|
150 |
-
"""
|
151 |
-
Normalizes the output by appending a specific instruction to the prompt.
|
152 |
-
|
153 |
-
Parameters:
|
154 |
-
prompt (str): The initial prompt.
|
155 |
-
|
156 |
-
Returns:
|
157 |
-
str: The modified prompt.
|
158 |
-
"""
|
159 |
-
return (
|
160 |
-
prompt
|
161 |
-
+ " Please only output the proofread text without any explanation."
|
162 |
-
)
|
163 |
-
|
164 |
-
|
165 |
-
def proofread_with_best_similarity(input_text, model_kind):
|
166 |
-
"""
|
167 |
-
Proofreads the input text using the specified model and extracts the
|
168 |
-
best-corrected text based on similarity.
|
169 |
-
|
170 |
-
Args:
|
171 |
-
input_text (str): The original text to be proofread.
|
172 |
-
model_kind (str): The kind of model to use for proofreading
|
173 |
-
(e.g., CHATGPT, GEMINI).
|
174 |
-
|
175 |
-
Returns:
|
176 |
-
tuple: A tuple containing the raw proofread text and the
|
177 |
-
best-corrected text.
|
178 |
-
"""
|
179 |
-
|
180 |
-
# Normalize the input text
|
181 |
-
normalized_input_text = normalize_text(input_text)
|
182 |
-
print_and_log(f"INPUT = {normalized_input_text}")
|
183 |
-
|
184 |
-
result_text = ""
|
185 |
-
raw_text = ""
|
186 |
-
|
187 |
-
for i in range(
|
188 |
-
1,
|
189 |
-
): # Loop is redundant as it runs only once;
|
190 |
-
# consider removing if unnecessary
|
191 |
-
# Select the proofreading model based on model_kind
|
192 |
-
if model_kind == CHATGPT:
|
193 |
-
raw_text = chatGPT_proofread(
|
194 |
-
normalized_input_text,
|
195 |
-
normalize_output=IS_OUTPUT_NORMALIZATION,
|
196 |
-
)
|
197 |
-
elif model_kind == GEMINI:
|
198 |
-
raw_text = gemini_proofread(
|
199 |
-
normalized_input_text,
|
200 |
-
normalize_output=IS_OUTPUT_NORMALIZATION,
|
201 |
-
)
|
202 |
-
else:
|
203 |
-
raw_text = proofread_by_model_name(
|
204 |
-
model_kind,
|
205 |
-
normalized_input_text,
|
206 |
-
normalize_output=IS_OUTPUT_NORMALIZATION,
|
207 |
-
)
|
208 |
-
|
209 |
-
# Extract the best candidate text based on similarity
|
210 |
-
result_text = extract_by_best_similarity(
|
211 |
-
normalized_input_text,
|
212 |
-
raw_text,
|
213 |
-
)
|
214 |
-
|
215 |
-
# Log the raw and result texts
|
216 |
-
print_and_log(f"RAW_{i} = {raw_text}")
|
217 |
-
print
|
218 |
-
# Normalize the result text
|
219 |
-
result_text = normalize_text(result_text)
|
220 |
-
|
221 |
-
# If a valid result is obtained, return it
|
222 |
-
if result_text != "":
|
223 |
-
return raw_text, result_text
|
224 |
-
|
225 |
-
# Return the raw and result texts
|
226 |
-
return raw_text, result_text
|
227 |
-
|
228 |
-
|
229 |
-
def generate_new_data_with_best_similarity(
|
230 |
-
existing_data_file,
|
231 |
-
existing_kinds,
|
232 |
-
new_kinds,
|
233 |
-
):
|
234 |
-
"""
|
235 |
-
Generates new data with the best similarity based on existing and new
|
236 |
-
kinds, and writes the results to a CSV file.
|
237 |
-
|
238 |
-
Args:
|
239 |
-
existing_data_file (str): The path to the existing data file.
|
240 |
-
existing_kinds (list): A list of existing kinds.
|
241 |
-
new_kinds (list): A list of new kinds.
|
242 |
-
|
243 |
-
Returns:
|
244 |
-
None
|
245 |
-
"""
|
246 |
-
|
247 |
-
# Combine existing and new kinds into a single list
|
248 |
-
all_kinds = existing_kinds + new_kinds
|
249 |
-
|
250 |
-
# Generate column names for the CSV file
|
251 |
-
column_names = generate_column_names(all_kinds)
|
252 |
-
|
253 |
-
# Generate column names for existing kinds
|
254 |
-
existing_column_names = generate_column_names(existing_kinds)
|
255 |
-
|
256 |
-
# Generate the output file name
|
257 |
-
output_file = generate_file_name(
|
258 |
-
existing_data_file,
|
259 |
-
existing_kinds,
|
260 |
-
new_kinds,
|
261 |
-
)
|
262 |
-
|
263 |
-
# Create the output file with column names if it doesn't exist
|
264 |
-
if not os.path.exists(output_file):
|
265 |
-
write_to_csv(output_file, column_names)
|
266 |
-
|
267 |
-
# Read existing data from the file
|
268 |
-
existing_data = {
|
269 |
-
kind: get_column(existing_data_file, kind)
|
270 |
-
for kind in existing_column_names
|
271 |
-
}
|
272 |
-
|
273 |
-
# Read input data from the output file
|
274 |
-
input_data = read_csv_data(output_file)
|
275 |
-
start_index = len(input_data)
|
276 |
-
print(f"start_index = {start_index}")
|
277 |
-
|
278 |
-
num_rows = len(existing_data["human"])
|
279 |
-
global_generate_set = []
|
280 |
-
global_reuse = []
|
281 |
-
|
282 |
-
for index in range(start_index, num_rows):
|
283 |
-
# Initialize generation and reuse sets
|
284 |
-
generate_set = []
|
285 |
-
reuse_set = []
|
286 |
-
|
287 |
-
# Prepare the current generation dictionary
|
288 |
-
current_generation = {
|
289 |
-
kind: existing_data[kind][index] for kind in existing_column_names
|
290 |
-
}
|
291 |
-
print(f"current_generation before generation = {current_generation}")
|
292 |
-
|
293 |
-
human_text = current_generation["human"]
|
294 |
-
|
295 |
-
# Generate new kinds based on human text
|
296 |
-
for kind in new_kinds:
|
297 |
-
_, generated_text = proofread_with_best_similarity(
|
298 |
-
human_text,
|
299 |
-
kind,
|
300 |
-
)
|
301 |
-
current_generation[kind] = generated_text
|
302 |
-
generate_set.append(kind)
|
303 |
-
|
304 |
-
print(f"current_generation after generate one = {current_generation}")
|
305 |
-
|
306 |
-
# Generate combinations of kinds
|
307 |
-
for first_kind in all_kinds:
|
308 |
-
for second_kind in all_kinds:
|
309 |
-
combination_name = f"{first_kind}_{second_kind}"
|
310 |
-
|
311 |
-
if combination_name not in current_generation:
|
312 |
-
if (
|
313 |
-
first_kind in current_generation
|
314 |
-
and current_generation[first_kind] == human_text
|
315 |
-
):
|
316 |
-
generated_text = current_generation[second_kind]
|
317 |
-
reuse_set.append(
|
318 |
-
f"{combination_name} from {second_kind}",
|
319 |
-
)
|
320 |
-
else:
|
321 |
-
is_need_generation = True
|
322 |
-
for first_kind_2 in all_kinds:
|
323 |
-
if (
|
324 |
-
first_kind != first_kind_2
|
325 |
-
and current_generation[first_kind]
|
326 |
-
== current_generation[first_kind_2]
|
327 |
-
):
|
328 |
-
combination_name_2 = (
|
329 |
-
f"{first_kind_2}_{second_kind}"
|
330 |
-
)
|
331 |
-
if combination_name_2 in current_generation:
|
332 |
-
generated_text = current_generation[
|
333 |
-
combination_name_2
|
334 |
-
]
|
335 |
-
reuse_set.append(
|
336 |
-
f"{combination_name} from {combination_name_2}", # noqa: E501
|
337 |
-
)
|
338 |
-
is_need_generation = False
|
339 |
-
break
|
340 |
-
if is_need_generation:
|
341 |
-
_, generated_text = proofread_with_best_similarity(
|
342 |
-
current_generation[first_kind],
|
343 |
-
second_kind,
|
344 |
-
)
|
345 |
-
generate_set.append(f"{first_kind}_{second_kind}")
|
346 |
-
|
347 |
-
current_generation[combination_name] = generated_text
|
348 |
-
|
349 |
-
# Write the current generation to the output file
|
350 |
-
write_new_data(output_file, current_generation, column_names)
|
351 |
-
|
352 |
-
# Update global sets
|
353 |
-
global_generate_set.append(generate_set)
|
354 |
-
global_reuse
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/texts/SimLLM/Refactor/readme.md
DELETED
@@ -1,67 +0,0 @@
|
|
1 |
-
# [Text] SimLLM: Detecting Sentences Generated by Large Language Models Using Similarity between the Generation and its Re-Generation
|
2 |
-
|
3 |
-
## **Getting Started**
|
4 |
-
1. **Clone the repository:**
|
5 |
-
```bash
|
6 |
-
git clone https://github.com/Tokyo-Techies/prj-nict-ai-content-detection
|
7 |
-
```
|
8 |
-
|
9 |
-
2. **Set up the environment:**
|
10 |
-
Using virtual environment:
|
11 |
-
```bash
|
12 |
-
python -m venv .venv
|
13 |
-
source .venv/bin/activate
|
14 |
-
```
|
15 |
-
|
16 |
-
3. **Install dependencies:**
|
17 |
-
```bash
|
18 |
-
pip install -r requirements.txt
|
19 |
-
```
|
20 |
-
|
21 |
-
|
22 |
-
4. **API Keys** (optional)
|
23 |
-
- Obtain API keys for the corresponding models and insert them into the `SimLLM.py` file:
|
24 |
-
- ChatGPT: [OpenAI API](https://openai.com/index/openai-api/)
|
25 |
-
- Gemini: [Google Gemini API](https://ai.google.dev/gemini-api/docs/api-key)
|
26 |
-
- Other LLMs: [Together API](https://api.together.ai/)
|
27 |
-
|
28 |
-
|
29 |
-
5. **Run the project:**
|
30 |
-
```bash
|
31 |
-
main_text.py
|
32 |
-
```
|
33 |
-
|
34 |
-
### Parameters
|
35 |
-
|
36 |
-
- `LLMs`: List of large language models to use. Available models include 'ChatGPT', 'Yi', 'OpenChat', 'Gemini', 'LLaMa', 'Phi', 'Mixtral', 'QWen', 'OLMO', 'WizardLM', and 'Vicuna'. Default is `['ChatGPT', 'Yi', 'OpenChat']`.
|
37 |
-
- `train_indexes`: List of LLM indexes for training. Default is `[0, 1, 2]`.
|
38 |
-
- `test_indexes`: List of LLM indexes for testing. Default is `[0]`.
|
39 |
-
- `num_samples`: Number of samples. Default is 5000.
|
40 |
-
|
41 |
-
### Examples
|
42 |
-
|
43 |
-
- Running with default parameters:
|
44 |
-
`python SimLLM.py`
|
45 |
-
|
46 |
-
- Running with customized parameters:
|
47 |
-
`python SimLLM.py --LLMs ChatGPT --train_indexes 0 --test_indexes 0`
|
48 |
-
|
49 |
-
## Dataset
|
50 |
-
|
51 |
-
The `dataset.csv` file contains both human and generated texts from 12 large language models, including:
|
52 |
-
ChatGPT, GPT-4o, Yi, OpenChat, Gemini, LLaMa, Phi, Mixtral, QWen, OLMO, WizardLM, and Vicuna.
|
53 |
-
|
54 |
-
## Citation
|
55 |
-
|
56 |
-
```bibtex
|
57 |
-
@inproceedings{nguyen2024SimLLM,
|
58 |
-
title={SimLLM: Detecting Sentences Generated by Large Language Models Using Similarity between the Generation and its Re-generation},
|
59 |
-
author={Nguyen-Son, Hoang-Quoc and Dao, Minh-Son and Zettsu, Koji},
|
60 |
-
booktitle={The Conference on Empirical Methods in Natural Language Processing},
|
61 |
-
year={2024}
|
62 |
-
}
|
63 |
-
```
|
64 |
-
|
65 |
-
## Acknowledgements
|
66 |
-
|
67 |
-
- BARTScore: [BARTScore GitHub Repository](https://github.com/neulab/BARTScore)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/texts/SimLLM/Refactor/utils.py
DELETED
@@ -1,527 +0,0 @@
|
|
1 |
-
import csv
|
2 |
-
import logging
|
3 |
-
import os
|
4 |
-
import random
|
5 |
-
|
6 |
-
import nltk
|
7 |
-
import numpy as np
|
8 |
-
import pandas as pd
|
9 |
-
from config import ( # LOG_FILE,
|
10 |
-
API_ERROR,
|
11 |
-
IGNORE_BY_API_ERROR,
|
12 |
-
SEED,
|
13 |
-
)
|
14 |
-
from datasets import load_dataset
|
15 |
-
|
16 |
-
|
17 |
-
def print_and_log(message: str):
|
18 |
-
# TODO: redefine logging
|
19 |
-
"""
|
20 |
-
Log message.
|
21 |
-
|
22 |
-
Args:
|
23 |
-
message (str): The message to be printed and logged.
|
24 |
-
"""
|
25 |
-
logging.info(message)
|
26 |
-
|
27 |
-
|
28 |
-
def write_to_file(filename: str, content: str):
|
29 |
-
"""
|
30 |
-
Writes the given content to a specified file.
|
31 |
-
|
32 |
-
Args:
|
33 |
-
filename (str): The path to the file to write content.
|
34 |
-
content (str): The content to be written.
|
35 |
-
"""
|
36 |
-
print(content)
|
37 |
-
with open(filename, "a+", encoding="utf-8") as file:
|
38 |
-
file.write(content)
|
39 |
-
|
40 |
-
|
41 |
-
def write_new_data(
|
42 |
-
output_file: str,
|
43 |
-
current_data: dict,
|
44 |
-
column_names: list,
|
45 |
-
) -> None:
|
46 |
-
"""
|
47 |
-
Writes a new row of data to a CSV file.
|
48 |
-
|
49 |
-
Args:
|
50 |
-
output_file (str): The path to the output CSV file.
|
51 |
-
current_data (dict): A dictionary containing the data to be written.
|
52 |
-
column_names (list): A list of column names in the desired order.
|
53 |
-
|
54 |
-
Returns:
|
55 |
-
None
|
56 |
-
"""
|
57 |
-
# Extract data in the specified order based on column names
|
58 |
-
data_row = [current_data[column] for column in column_names]
|
59 |
-
|
60 |
-
# Write the data row to the CSV file
|
61 |
-
write_to_csv(output_file, data_row)
|
62 |
-
|
63 |
-
|
64 |
-
def write_to_csv(filename: str, row_data: list) -> None:
|
65 |
-
"""
|
66 |
-
Appends a row of data to a CSV file.
|
67 |
-
|
68 |
-
Args:
|
69 |
-
filename (str): The name of the CSV file.
|
70 |
-
row_data: A list of values to be written as a row.
|
71 |
-
|
72 |
-
Returns:
|
73 |
-
None
|
74 |
-
"""
|
75 |
-
# Open the CSV file in append mode, creating it if it doesn't exist
|
76 |
-
with open(filename, "a+", encoding="UTF8", newline="") as file:
|
77 |
-
writer = csv.writer(file)
|
78 |
-
writer.writerow(row_data)
|
79 |
-
|
80 |
-
|
81 |
-
def count_csv_lines(filename: str) -> int:
|
82 |
-
"""Counts the number of lines in a CSV file, excluding the header row.
|
83 |
-
|
84 |
-
Args:
|
85 |
-
filename (str): The path to the CSV file.
|
86 |
-
|
87 |
-
Returns:
|
88 |
-
int: The number of lines in the CSV file, excluding the header row.
|
89 |
-
"""
|
90 |
-
file_data = pd.read_csv(filename, sep=",").values
|
91 |
-
return len(file_data)
|
92 |
-
|
93 |
-
|
94 |
-
def read_csv_data(input_file: str) -> np.ndarray:
|
95 |
-
"""
|
96 |
-
Reads data from a specified CSV file.
|
97 |
-
|
98 |
-
Args:
|
99 |
-
file_path (str): The path to the CSV file.
|
100 |
-
|
101 |
-
Returns:
|
102 |
-
numpy.ndarray: The data from the CSV file.
|
103 |
-
"""
|
104 |
-
file_data = pd.read_csv(
|
105 |
-
input_file,
|
106 |
-
dtype="string",
|
107 |
-
keep_default_na=False,
|
108 |
-
sep=",",
|
109 |
-
).values
|
110 |
-
return file_data
|
111 |
-
|
112 |
-
|
113 |
-
def get_column(input_file: str, column_name: str) -> np.ndarray:
|
114 |
-
"""
|
115 |
-
Retrieves a specific column from a CSV file as a NumPy array.
|
116 |
-
|
117 |
-
Args:
|
118 |
-
input_file (str): The path to the CSV file.
|
119 |
-
column_name (str): The name of the column to extract.
|
120 |
-
|
121 |
-
Returns:
|
122 |
-
np.ndarray: Values from the specified column.
|
123 |
-
"""
|
124 |
-
# Read CSV, preserving string data types and handling missing values
|
125 |
-
df = pd.read_csv(
|
126 |
-
input_file,
|
127 |
-
dtype="string",
|
128 |
-
keep_default_na=False,
|
129 |
-
sep=",",
|
130 |
-
)
|
131 |
-
|
132 |
-
# Extract the specified column as a NumPy array
|
133 |
-
column_data = df[column_name].values
|
134 |
-
return column_data
|
135 |
-
|
136 |
-
|
137 |
-
def generate_column_names(categories: list) -> list:
|
138 |
-
"""
|
139 |
-
Generates column names for a pairwise comparison matrix.
|
140 |
-
|
141 |
-
Args:
|
142 |
-
categories (list): A list of categories.
|
143 |
-
|
144 |
-
Returns:
|
145 |
-
list: A list of column names,
|
146 |
-
including a 'human' column and pairwise combinations.
|
147 |
-
"""
|
148 |
-
column_names = ["human"]
|
149 |
-
|
150 |
-
# Add individual category names as column names
|
151 |
-
column_names.extend(categories)
|
152 |
-
|
153 |
-
# Add pairwise combinations of categories as column names
|
154 |
-
for i in categories:
|
155 |
-
for j in categories:
|
156 |
-
column_names.append(f"{i}_{j}")
|
157 |
-
|
158 |
-
# TODO: improve?
|
159 |
-
# for i in range(len(categories)):
|
160 |
-
# for j in range(i + 1, len(categories)):
|
161 |
-
# column_names.append(f"{categories[i]}_{categories[j]}")
|
162 |
-
|
163 |
-
return column_names
|
164 |
-
|
165 |
-
|
166 |
-
def normalize_text(input_text: str) -> str:
|
167 |
-
"""
|
168 |
-
Normalizes the given text by removing unnecessary characters and
|
169 |
-
formatting it for better readability.
|
170 |
-
|
171 |
-
Args:
|
172 |
-
input_text (str): The input text to be normalized.
|
173 |
-
|
174 |
-
Returns:
|
175 |
-
The normalized text.
|
176 |
-
|
177 |
-
This function performs the following transformations:
|
178 |
-
1. Strips leading and trailing whitespace
|
179 |
-
2. Removes double asterisks (`**`)
|
180 |
-
3. Replaces newlines with spaces
|
181 |
-
4. Removes extra spaces
|
182 |
-
"""
|
183 |
-
processed_text = input_text.strip()
|
184 |
-
processed_text = processed_text.replace("**", "")
|
185 |
-
processed_text = processed_text.replace("\n", " ")
|
186 |
-
processed_text = processed_text.replace(" ", " ") # Remove extra spaces
|
187 |
-
# TODO: what if 3 or more spaces
|
188 |
-
return processed_text
|
189 |
-
|
190 |
-
|
191 |
-
def refine_candidate_text(input_text: str, candidate_text: str) -> str:
|
192 |
-
# TODO: how different with processing text
|
193 |
-
"""
|
194 |
-
Removes specific surrounding marks from the candidate text if they are
|
195 |
-
present in the input text with an excess of exactly two occurrences.
|
196 |
-
|
197 |
-
Args:
|
198 |
-
input_text (str): The original text.
|
199 |
-
candidate (str): The candidate text to be refined.
|
200 |
-
|
201 |
-
Returns:
|
202 |
-
str: The refined candidate text.
|
203 |
-
"""
|
204 |
-
|
205 |
-
# Create a copy of the candidate string and strip whitespace
|
206 |
-
refined_candidate = candidate_text.strip()
|
207 |
-
|
208 |
-
# Iterate through each mark
|
209 |
-
for mark in ["```", "'", '"']:
|
210 |
-
# Count occurrences of the mark in input_text and refined_candidate
|
211 |
-
count_input_text = input_text.count(mark)
|
212 |
-
count_refined_candidate = refined_candidate.count(mark)
|
213 |
-
|
214 |
-
# Check if the mark should be stripped
|
215 |
-
if (
|
216 |
-
count_refined_candidate == count_input_text + 2
|
217 |
-
and refined_candidate.startswith(mark)
|
218 |
-
and refined_candidate.endswith(mark)
|
219 |
-
):
|
220 |
-
# Strip the mark from both ends of the refined_candidate
|
221 |
-
refined_candidate = refined_candidate.strip(mark)
|
222 |
-
|
223 |
-
return refined_candidate
|
224 |
-
|
225 |
-
|
226 |
-
def generate_file_name(
|
227 |
-
existing_data_file: str,
|
228 |
-
existing_kinds: list,
|
229 |
-
new_kinds: list,
|
230 |
-
) -> str:
|
231 |
-
"""
|
232 |
-
Generates a new file name based on the path of an existing data file and a
|
233 |
-
combination of existing and new kinds.
|
234 |
-
|
235 |
-
Args:
|
236 |
-
existing_data_file (str): The path to the existing data file.
|
237 |
-
existing_kinds (list): A list of existing kinds.
|
238 |
-
new_kinds (list): A list of new kinds.
|
239 |
-
|
240 |
-
Returns:
|
241 |
-
str: The generated file name with the full path.
|
242 |
-
"""
|
243 |
-
|
244 |
-
# Combine existing and new kinds into a single list
|
245 |
-
combined_kinds = existing_kinds + new_kinds
|
246 |
-
|
247 |
-
# Get the directory path of the existing data file
|
248 |
-
directory_path = os.path.dirname(existing_data_file)
|
249 |
-
|
250 |
-
# Create a new file name by joining the kinds with underscores and adding
|
251 |
-
# a suffix
|
252 |
-
# TODO: move to config file
|
253 |
-
new_file_name = "_".join(combined_kinds) + "_with_best_similarity.csv"
|
254 |
-
|
255 |
-
# Combine the directory path with the new file name to get the full output
|
256 |
-
# file path
|
257 |
-
output_file_path = os.path.join(directory_path, new_file_name)
|
258 |
-
|
259 |
-
return output_file_path
|
260 |
-
|
261 |
-
|
262 |
-
def shuffle(data: list[list], seed: int) -> None:
|
263 |
-
"""
|
264 |
-
Shuffles the elements within each sublist of the given data structure.
|
265 |
-
|
266 |
-
Args:
|
267 |
-
data (list of lists): The array containing sublists to shuffle.
|
268 |
-
seed (int): The seed value for the random number generator.
|
269 |
-
|
270 |
-
Returns:
|
271 |
-
None
|
272 |
-
"""
|
273 |
-
for sublist in data:
|
274 |
-
random.Random(seed).shuffle(sublist)
|
275 |
-
|
276 |
-
|
277 |
-
def generate_human_with_shuffle(
|
278 |
-
dataset_name: str,
|
279 |
-
column_name: str,
|
280 |
-
num_samples: int,
|
281 |
-
output_file: str,
|
282 |
-
) -> None:
|
283 |
-
"""
|
284 |
-
Generates a shuffled list of sentences from the dataset and writes them to
|
285 |
-
a CSV file.
|
286 |
-
|
287 |
-
Args:
|
288 |
-
dataset_name (str): The name of the dataset to load.
|
289 |
-
column_name (str): The column name to extract sentences from.
|
290 |
-
num_samples (int): The number of samples to process.
|
291 |
-
output_file (str): The path to the output CSV file.
|
292 |
-
|
293 |
-
Returns:
|
294 |
-
None
|
295 |
-
"""
|
296 |
-
# Load the dataset
|
297 |
-
dataset = load_dataset(dataset_name)
|
298 |
-
data = dataset["train"]
|
299 |
-
|
300 |
-
lines = []
|
301 |
-
# Tokenize sentences and add to the lines list
|
302 |
-
for sample in data:
|
303 |
-
nltk_tokens = nltk.sent_tokenize(sample[column_name])
|
304 |
-
lines.extend(nltk_tokens)
|
305 |
-
|
306 |
-
# Filter out empty lines
|
307 |
-
filtered_lines = [line for line in lines if line != ""]
|
308 |
-
lines = filtered_lines
|
309 |
-
|
310 |
-
# Shuffle the lines
|
311 |
-
shuffle([lines], seed=SEED)
|
312 |
-
|
313 |
-
# Ensure the output file exists and write the header if it doesn't
|
314 |
-
if not os.path.exists(output_file):
|
315 |
-
header = ["human"]
|
316 |
-
write_to_csv(output_file, header)
|
317 |
-
|
318 |
-
# Get the number of lines already processed in the output file
|
319 |
-
number_of_processed_lines = count_csv_lines(output_file)
|
320 |
-
|
321 |
-
# Print the initial lines to be processed
|
322 |
-
print(f"Lines before processing: {lines[:num_samples]}")
|
323 |
-
|
324 |
-
# Slice the lines list to get the unprocessed lines
|
325 |
-
lines = lines[number_of_processed_lines:num_samples]
|
326 |
-
|
327 |
-
# Print the lines after slicing
|
328 |
-
print(f"Lines after slicing: {lines}")
|
329 |
-
|
330 |
-
# Process each line and write to the output file
|
331 |
-
for index, human in enumerate(lines):
|
332 |
-
normalized_text = normalize_text(human)
|
333 |
-
output_data = [normalized_text]
|
334 |
-
write_to_csv(output_file, output_data)
|
335 |
-
print(
|
336 |
-
f"Processed {index + 1} / {len(lines)};\
|
337 |
-
Total processed:\
|
338 |
-
{number_of_processed_lines + index + 1} / {num_samples}",
|
339 |
-
)
|
340 |
-
|
341 |
-
|
342 |
-
def split_data(data: list, train_ratio: float) -> list[list, list]:
|
343 |
-
"""
|
344 |
-
Splits a dataset into training and testing sets.
|
345 |
-
|
346 |
-
Args:
|
347 |
-
data (list): The input dataset.
|
348 |
-
train_ratio (float): The proportion of data to use for training.
|
349 |
-
|
350 |
-
Returns:
|
351 |
-
The training and testing sets.
|
352 |
-
"""
|
353 |
-
|
354 |
-
# Calculate the number of samples for training
|
355 |
-
train_size = int(len(data) * train_ratio)
|
356 |
-
|
357 |
-
# Split the data into training and testing sets
|
358 |
-
train_data = data[:train_size]
|
359 |
-
test_data = data[train_size:]
|
360 |
-
|
361 |
-
return train_data, test_data
|
362 |
-
|
363 |
-
|
364 |
-
def combine_text_with_BERT_format(text_list: list[str]) -> str:
|
365 |
-
"""
|
366 |
-
Formats a list of texts into a single string suitable for BERT input.
|
367 |
-
|
368 |
-
Args:
|
369 |
-
text_list (list[str]): A list of text strings.
|
370 |
-
|
371 |
-
Returns:
|
372 |
-
str: A single string formatted with BERT's special tokens.
|
373 |
-
"""
|
374 |
-
# TODO: simplify this function
|
375 |
-
# combined_text = f"<s>{text_list[0]}</s>"
|
376 |
-
# for i in range(1, len(text_list)):
|
377 |
-
# combined_text += f"</s>{text_list[i]}</s>"
|
378 |
-
# return combined_text
|
379 |
-
|
380 |
-
formatted_text = "<s>" + "</s><s>".join(text_list) + "</s>"
|
381 |
-
return formatted_text
|
382 |
-
|
383 |
-
|
384 |
-
def check_api_error(data: list):
|
385 |
-
"""
|
386 |
-
Checks if the given data contains an API error or an indication to ignore
|
387 |
-
an API error.
|
388 |
-
|
389 |
-
Args:
|
390 |
-
data (list): A list of items to check.
|
391 |
-
|
392 |
-
Returns:
|
393 |
-
bool: True if an API error or ignore indication is found,
|
394 |
-
False otherwise.
|
395 |
-
"""
|
396 |
-
for item in data:
|
397 |
-
# Check for API error indicators
|
398 |
-
if item in (API_ERROR, IGNORE_BY_API_ERROR):
|
399 |
-
return True # Return True if at least an error indicator is found
|
400 |
-
return False # Return False if no error indicators are found
|
401 |
-
|
402 |
-
|
403 |
-
def calculate_required_models(num_columns: int) -> int:
|
404 |
-
"""
|
405 |
-
Calculates the minimum number of models required to generate the specified number of columns.
|
406 |
-
|
407 |
-
Args:
|
408 |
-
num_columns (int): The total number of columns to generate.
|
409 |
-
|
410 |
-
Returns:
|
411 |
-
int: The minimum number of models required.
|
412 |
-
|
413 |
-
Raises:
|
414 |
-
ValueError: If the number of columns cannot be achieved with the current model configuration.
|
415 |
-
"""
|
416 |
-
|
417 |
-
num_models = 0
|
418 |
-
count_human = 1 # Initial count representing human input
|
419 |
-
|
420 |
-
# TODO: simplify this function
|
421 |
-
while True:
|
422 |
-
count_single = num_models # Single model count
|
423 |
-
count_pair = num_models * num_models # Pair model count
|
424 |
-
|
425 |
-
total_count = count_human + count_single + count_pair
|
426 |
-
|
427 |
-
if total_count == num_columns:
|
428 |
-
return num_models
|
429 |
-
elif total_count > num_columns:
|
430 |
-
raise Exception(
|
431 |
-
"Cannot calculate the number of models to match the number of columns", # noqa: E501
|
432 |
-
)
|
433 |
-
|
434 |
-
num_models += 1
|
435 |
-
|
436 |
-
|
437 |
-
def parse_multimodal_data(multimodel_csv_file: list) -> list:
|
438 |
-
"""
|
439 |
-
Parses multimodal data from a CSV file into a structured format.
|
440 |
-
|
441 |
-
Args:
|
442 |
-
multimodel_csv_file (str): Path to the CSV file.
|
443 |
-
|
444 |
-
Returns:
|
445 |
-
list: A list of dictionaries, each containing 'human', 'single', and
|
446 |
-
'pair' keys.
|
447 |
-
|
448 |
-
Raises:
|
449 |
-
Exception: If there is an error in reading the CSV file or processing
|
450 |
-
the data.
|
451 |
-
"""
|
452 |
-
# TODO: simplify this function
|
453 |
-
|
454 |
-
# Read CSV data into a list of lists
|
455 |
-
input_data = read_csv_data(multimodel_csv_file)
|
456 |
-
|
457 |
-
# Initialize the result list
|
458 |
-
structured_data = []
|
459 |
-
|
460 |
-
# Calculate the number of models based on the number of columns in the first row # noqa: E501
|
461 |
-
num_models = calculate_required_models(len(input_data[0]))
|
462 |
-
|
463 |
-
# Process each row in the input data
|
464 |
-
for row in input_data:
|
465 |
-
row_data = {}
|
466 |
-
index = 0
|
467 |
-
|
468 |
-
# Extract human data
|
469 |
-
row_data["human"] = row[index]
|
470 |
-
index += 1
|
471 |
-
|
472 |
-
# Extract single model data
|
473 |
-
single_model_data = []
|
474 |
-
for _ in range(num_models):
|
475 |
-
single_model_data.append(row[index])
|
476 |
-
index += 1
|
477 |
-
row_data["single"] = single_model_data
|
478 |
-
|
479 |
-
# Extract pair model data
|
480 |
-
pair_model_data = []
|
481 |
-
for _ in range(num_models):
|
482 |
-
sub_pair_data = []
|
483 |
-
for _ in range(num_models):
|
484 |
-
sub_pair_data.append(row[index])
|
485 |
-
index += 1
|
486 |
-
pair_model_data.append(sub_pair_data)
|
487 |
-
row_data["pair"] = pair_model_data
|
488 |
-
|
489 |
-
# Append the structured row data to the result list
|
490 |
-
structured_data.append(row_data)
|
491 |
-
|
492 |
-
return structured_data
|
493 |
-
|
494 |
-
|
495 |
-
def check_error(data_item: dict) -> bool:
|
496 |
-
"""
|
497 |
-
Checks if the given data item contains any API errors.
|
498 |
-
An API error is indicated by a specific error message
|
499 |
-
or code within the text.
|
500 |
-
|
501 |
-
Args:
|
502 |
-
data_item (dict): A dictionary containing 'human', 'single',
|
503 |
-
and 'pair' fields.
|
504 |
-
|
505 |
-
Returns:
|
506 |
-
bool: True if an API error is found, otherwise False.
|
507 |
-
"""
|
508 |
-
# Check for API error in the 'human' field
|
509 |
-
if check_api_error(data_item["human"]):
|
510 |
-
return True
|
511 |
-
|
512 |
-
# Check for API error in the 'single' model data
|
513 |
-
for single_text in data_item["single"]:
|
514 |
-
if check_api_error(single_text):
|
515 |
-
return True
|
516 |
-
|
517 |
-
# Get the number of models from the 'single' model data
|
518 |
-
num_models = len(data_item["single"])
|
519 |
-
|
520 |
-
# Check for API error in the 'pair' model data
|
521 |
-
for i in range(num_models):
|
522 |
-
for j in range(num_models):
|
523 |
-
if check_api_error(data_item["pair"][i][j]):
|
524 |
-
return True
|
525 |
-
|
526 |
-
# No errors found
|
527 |
-
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/texts/SimLLM/SimLLM.py
DELETED
@@ -1,1667 +0,0 @@
|
|
1 |
-
|
2 |
-
import os
|
3 |
-
import shutil
|
4 |
-
import random
|
5 |
-
import pandas as pd
|
6 |
-
import numpy as np
|
7 |
-
import nltk
|
8 |
-
import google.generativeai as genai
|
9 |
-
import csv
|
10 |
-
from transformers import (
|
11 |
-
AutoTokenizer,
|
12 |
-
DataCollatorWithPadding,
|
13 |
-
AutoModelForSequenceClassification,
|
14 |
-
EarlyStoppingCallback,
|
15 |
-
TrainerCallback,
|
16 |
-
TrainingArguments,
|
17 |
-
Trainer
|
18 |
-
)
|
19 |
-
from openai import OpenAI
|
20 |
-
from sklearn.neural_network import MLPClassifier
|
21 |
-
from sklearn.metrics import roc_auc_score, accuracy_score
|
22 |
-
from os.path import join
|
23 |
-
from langchain.chat_models import ChatOpenAI
|
24 |
-
from datasets import load_metric, load_dataset, Dataset
|
25 |
-
from copy import deepcopy
|
26 |
-
from bart_score import BARTScorer
|
27 |
-
import argparse
|
28 |
-
|
29 |
-
# Constants
|
30 |
-
TOGETHER_API_KEY = "your_together_api_key"
|
31 |
-
OPENAI_API_KEY = "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"
|
32 |
-
GEMINI_API_KEY = "your_gemini_key"
|
33 |
-
LOG_FILE = "data/99_log.txt"
|
34 |
-
OUTPUT_FILE = "data/result.txt"
|
35 |
-
METRIC_NAME = "roc_auc"
|
36 |
-
|
37 |
-
TRAIN_RATIO = 0.8
|
38 |
-
VAL_RATIO = 0.1
|
39 |
-
NUMBER_OF_MAX_EPOCH_WITH_EARLY_STOPPING = 10
|
40 |
-
PATIENCE = 3
|
41 |
-
BATCH_SIZE = 8
|
42 |
-
OPTIMIZED_METRIC = "roc_auc"
|
43 |
-
SEED = 0
|
44 |
-
TEMPERATURE = 0.0
|
45 |
-
IS_OUTPUT_NORMALIZATION = False
|
46 |
-
RATIO = 0.9
|
47 |
-
HUMAN_LABEL = 0
|
48 |
-
MACHINE_LABEL = 1
|
49 |
-
BART = "bart"
|
50 |
-
|
51 |
-
MULTIMODEL = "multimodel"
|
52 |
-
SINGLE_FROM_MULTIMODEL = "single_from_multimodel"
|
53 |
-
|
54 |
-
# Environment setup
|
55 |
-
os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
|
56 |
-
os.environ['CURL_CA_BUNDLE'] = ''
|
57 |
-
os.environ['REQUESTS_CA_BUNDLE'] = ''
|
58 |
-
|
59 |
-
# Download necessary NLTK data
|
60 |
-
nltk.download('punkt')
|
61 |
-
nltk.download('punkt_tab')
|
62 |
-
|
63 |
-
# Chat model configurations
|
64 |
-
chat_model = ChatOpenAI(temperature=TEMPERATURE, model_name="gpt-3.5-turbo-0125")
|
65 |
-
|
66 |
-
# API Models and Paths
|
67 |
-
CHATGPT = "ChatGPT"
|
68 |
-
GEMINI = "Gemini"
|
69 |
-
# LLAMA_2_70_CHAT_TEMP_0 = "LLaMa"
|
70 |
-
API_ERROR = "API_ERROR"
|
71 |
-
IGNORE_BY_API_ERROR = "IGNORE_BY_API_ERROR"
|
72 |
-
|
73 |
-
# Initialize BARTScorer
|
74 |
-
bart_scorer = BARTScorer(device='cuda:0', checkpoint="facebook/bart-large-cnn")
|
75 |
-
|
76 |
-
# Generative AI configuration
|
77 |
-
genai.configure(api_key=GEMINI_API_KEY, transport='rest')
|
78 |
-
generation_config = {
|
79 |
-
"temperature": TEMPERATURE,
|
80 |
-
}
|
81 |
-
GEMINI_MODEL = genai.GenerativeModel('gemini-pro', generation_config=generation_config)
|
82 |
-
|
83 |
-
# Model paths
|
84 |
-
MODEL_PATHS = {
|
85 |
-
"LLaMa": "meta-llama/Llama-2-70b-chat-hf",
|
86 |
-
"QWEN": "Qwen/Qwen1.5-72B-Chat",
|
87 |
-
"Yi": "NousResearch/Nous-Hermes-2-Yi-34B",
|
88 |
-
"Mixtral": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
89 |
-
"OLMo": "allenai/OLMo-7B-Instruct",
|
90 |
-
"Phi": "microsoft/phi-2",
|
91 |
-
"OpenChat": "openchat/openchat-3.5-1210",
|
92 |
-
"WizardLM": "WizardLM/WizardLM-13B-V1.2",
|
93 |
-
"Vicuna": "lmsys/vicuna-13b-v1.5"
|
94 |
-
}
|
95 |
-
|
96 |
-
TOGETHER_PATH ='https://api.together.xyz'
|
97 |
-
|
98 |
-
# Roberta model configurations
|
99 |
-
ROBERTA_BASE = "roberta-base"
|
100 |
-
ROBERTA_LARGE = "roberta-large"
|
101 |
-
ROBERTA_MODEL_PATHS = {
|
102 |
-
ROBERTA_BASE: "roberta-base",
|
103 |
-
ROBERTA_LARGE: "roberta-large"
|
104 |
-
}
|
105 |
-
LEARNING_RATES = {
|
106 |
-
ROBERTA_BASE: 2e-5,
|
107 |
-
ROBERTA_LARGE: 8e-6
|
108 |
-
}
|
109 |
-
MODEL_NAME = ROBERTA_BASE
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
# Tokenizer initialization
|
114 |
-
tokenizer = AutoTokenizer.from_pretrained(ROBERTA_MODEL_PATHS[MODEL_NAME])
|
115 |
-
|
116 |
-
# Custom callback for Trainer
|
117 |
-
class CustomCallback(TrainerCallback):
|
118 |
-
"""
|
119 |
-
Custom callback to evaluate the training dataset at the end of each epoch.
|
120 |
-
"""
|
121 |
-
def __init__(self, trainer) -> None:
|
122 |
-
super().__init__()
|
123 |
-
self._trainer = trainer
|
124 |
-
|
125 |
-
def on_epoch_end(self, args, state, control, **kwargs):
|
126 |
-
"""
|
127 |
-
At the end of each epoch, evaluate the training dataset.
|
128 |
-
"""
|
129 |
-
if control.should_evaluate:
|
130 |
-
control_copy = deepcopy(control)
|
131 |
-
self._trainer.evaluate(eval_dataset=self._trainer.train_dataset, metric_key_prefix="train")
|
132 |
-
return control_copy
|
133 |
-
|
134 |
-
# Metric loading
|
135 |
-
metric = load_metric(METRIC_NAME)
|
136 |
-
|
137 |
-
def compute_metrics(evaluation_predictions):
|
138 |
-
"""
|
139 |
-
Function to compute evaluation metrics for model predictions.
|
140 |
-
|
141 |
-
Parameters:
|
142 |
-
evaluation_predictions (tuple): A tuple containing two elements:
|
143 |
-
- predictions (array-like): The raw prediction scores from the model.
|
144 |
-
- labels (array-like): The true labels for the evaluation data.
|
145 |
-
|
146 |
-
Returns:
|
147 |
-
dict: A dictionary containing the computed evaluation metrics.
|
148 |
-
"""
|
149 |
-
# Unpack predictions and labels from the input tuple
|
150 |
-
raw_predictions, true_labels = evaluation_predictions
|
151 |
-
|
152 |
-
# Convert raw prediction scores to predicted class labels
|
153 |
-
predicted_labels = np.argmax(raw_predictions, axis=1)
|
154 |
-
|
155 |
-
# Compute and return the evaluation metrics
|
156 |
-
return metric.compute(prediction_scores=predicted_labels, references=true_labels, average="macro")
|
157 |
-
|
158 |
-
|
159 |
-
def abstract_proofread(model_path, temperature, base_url, api_key, prompt):
|
160 |
-
"""
|
161 |
-
Function to proofread an abstract using an AI language model.
|
162 |
-
|
163 |
-
Parameters:
|
164 |
-
model_path (str): The path or identifier of the AI model to use.
|
165 |
-
temperature (float): Sampling temperature for the model's output.
|
166 |
-
base_url (str): The base URL for the API endpoint.
|
167 |
-
api_key (str): The API key for authentication.
|
168 |
-
prompt (str): The text prompt to provide to the AI for proofreading.
|
169 |
-
|
170 |
-
Returns:
|
171 |
-
str: The proofread abstract generated by the AI model.
|
172 |
-
"""
|
173 |
-
# Initialize the AI client with the provided API key and base URL
|
174 |
-
ai_client = OpenAI(api_key=api_key, base_url=base_url)
|
175 |
-
|
176 |
-
# Create a chat completion request with the system message and user prompt
|
177 |
-
chat_completion = ai_client.chat.completions.create(
|
178 |
-
messages=[
|
179 |
-
{
|
180 |
-
"role": "system",
|
181 |
-
"content": "You are an AI assistant",
|
182 |
-
},
|
183 |
-
{
|
184 |
-
"role": "user",
|
185 |
-
"content": prompt,
|
186 |
-
}
|
187 |
-
],
|
188 |
-
model=model_path,
|
189 |
-
max_tokens=1024,
|
190 |
-
temperature=temperature,
|
191 |
-
)
|
192 |
-
|
193 |
-
# Return the content of the first choice's message
|
194 |
-
return chat_completion.choices[0].message.content
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
def proofread_by_model_name(model_name, input_text, normalize_output):
|
199 |
-
"""
|
200 |
-
Proofreads the given input text using the specified model.
|
201 |
-
|
202 |
-
Args:
|
203 |
-
model_name (str): The name of the model to use for proofreading.
|
204 |
-
input_text (str): The text to be proofread.
|
205 |
-
normalize_output (bool): Whether to normalize the output or not.
|
206 |
-
|
207 |
-
Returns:
|
208 |
-
str: The proofread text.
|
209 |
-
"""
|
210 |
-
# Constants for API access
|
211 |
-
base_url = TOGETHER_PATH
|
212 |
-
api_key = TOGETHER_API_KEY
|
213 |
-
temperature = TEMPERATURE
|
214 |
-
|
215 |
-
# Retrieve the model path from the dictionary
|
216 |
-
if model_name in MODEL_PATHS:
|
217 |
-
model_path = MODEL_PATHS[model_name]
|
218 |
-
else:
|
219 |
-
raise ValueError("Model name not found in the dictionary.")
|
220 |
-
|
221 |
-
# Formulate the prompt for the model
|
222 |
-
prompt = f"Proofreading for the text: ```{input_text}```"
|
223 |
-
|
224 |
-
# Apply output normalization if required
|
225 |
-
if normalize_output:
|
226 |
-
prompt = output_normalization(prompt)
|
227 |
-
|
228 |
-
# Debugging: Print the prompt
|
229 |
-
print(f"Prompt: {prompt}")
|
230 |
-
|
231 |
-
# Call the abstract proofreading function with the prepared parameters
|
232 |
-
return abstract_proofread(model_path, temperature, base_url, api_key, prompt)
|
233 |
-
|
234 |
-
|
235 |
-
def gemini_proofread(input_text, normalize_output):
|
236 |
-
"""
|
237 |
-
Proofreads the given text using the GEMINI_MODEL.
|
238 |
-
|
239 |
-
Parameters:
|
240 |
-
input_text (str): The text to be proofread.
|
241 |
-
normalize_output (bool): Flag indicating whether to normalize the output.
|
242 |
-
|
243 |
-
Returns:
|
244 |
-
str: The proofread text.
|
245 |
-
"""
|
246 |
-
prompt = f"Proofreading for the text: ```{input_text}```"
|
247 |
-
if normalize_output:
|
248 |
-
prompt = output_normalization(prompt)
|
249 |
-
response = GEMINI_MODEL.generate_content(prompt)
|
250 |
-
return response.text
|
251 |
-
|
252 |
-
def print_and_log(message):
|
253 |
-
"""
|
254 |
-
Prints and logs the given message to a log file.
|
255 |
-
|
256 |
-
Parameters:
|
257 |
-
message (str): The message to be printed and logged.
|
258 |
-
"""
|
259 |
-
print(message)
|
260 |
-
with open(LOG_FILE, "a+", encoding='utf-8') as log_file:
|
261 |
-
log_file.write(message + "\n")
|
262 |
-
|
263 |
-
def write_to_file(filename, content):
|
264 |
-
"""
|
265 |
-
Writes the given content to a specified file.
|
266 |
-
|
267 |
-
Parameters:
|
268 |
-
filename (str): The name of the file to write to.
|
269 |
-
content (str): The content to be written.
|
270 |
-
"""
|
271 |
-
print(content)
|
272 |
-
with open(filename, "a+", encoding='utf-8') as file:
|
273 |
-
file.write(content)
|
274 |
-
|
275 |
-
def output_normalization(prompt):
|
276 |
-
"""
|
277 |
-
Normalizes the output by appending a specific instruction to the prompt.
|
278 |
-
|
279 |
-
Parameters:
|
280 |
-
prompt (str): The initial prompt.
|
281 |
-
|
282 |
-
Returns:
|
283 |
-
str: The modified prompt.
|
284 |
-
"""
|
285 |
-
return prompt + " Please only output the proofread text without any explanation."
|
286 |
-
|
287 |
-
def chatGPT_proofread(input_text, normalize_output):
|
288 |
-
"""
|
289 |
-
Proofreads the given text using the chat_model.
|
290 |
-
|
291 |
-
Parameters:
|
292 |
-
input_text (str): The text to be proofread.
|
293 |
-
normalize_output (bool): Flag indicating whether to normalize the output.
|
294 |
-
|
295 |
-
Returns:
|
296 |
-
str: The proofread text.
|
297 |
-
"""
|
298 |
-
prompt = f"Proofreading for the text: ```{input_text}```"
|
299 |
-
if normalize_output:
|
300 |
-
prompt = output_normalization(prompt)
|
301 |
-
|
302 |
-
print(f"Starting API call with prompt: {prompt}")
|
303 |
-
result = chat_model.predict(prompt)
|
304 |
-
print(f"Ending API call with prompt: {prompt}")
|
305 |
-
|
306 |
-
return result
|
307 |
-
|
308 |
-
def normalize_text(input_text):
|
309 |
-
"""
|
310 |
-
Normalizes the given text by removing certain characters and extra spaces.
|
311 |
-
|
312 |
-
Parameters:
|
313 |
-
input_text (str): The text to be normalized.
|
314 |
-
|
315 |
-
Returns:
|
316 |
-
str: The normalized text.
|
317 |
-
"""
|
318 |
-
result = input_text.strip()
|
319 |
-
result = result.replace("**", "")
|
320 |
-
result = result.replace("\n", " ")
|
321 |
-
result = result.replace(" ", " ") # Remove extra spaces
|
322 |
-
return result
|
323 |
-
|
324 |
-
def write_to_csv(filename, row_data):
|
325 |
-
"""
|
326 |
-
Writes a row of data to a specified CSV file.
|
327 |
-
|
328 |
-
Parameters:
|
329 |
-
filename (str): The name of the CSV file.
|
330 |
-
row_data (list): The row data to be written.
|
331 |
-
"""
|
332 |
-
with open(filename, 'a+', encoding='UTF8', newline='') as file:
|
333 |
-
writer = csv.writer(file)
|
334 |
-
writer.writerow(row_data)
|
335 |
-
|
336 |
-
def number_of_csv_lines(filename):
|
337 |
-
"""
|
338 |
-
Returns the number of lines in a specified CSV file.
|
339 |
-
|
340 |
-
Parameters:
|
341 |
-
filename (str): The name of the CSV file.
|
342 |
-
|
343 |
-
Returns:
|
344 |
-
int: The number of lines in the CSV file.
|
345 |
-
"""
|
346 |
-
file_data = pd.read_csv(filename, sep=',').values
|
347 |
-
return len(file_data)
|
348 |
-
|
349 |
-
def read_csv_data(input_file):
|
350 |
-
"""
|
351 |
-
Reads data from a specified CSV file.
|
352 |
-
|
353 |
-
Parameters:
|
354 |
-
input_file (str): The name of the CSV file.
|
355 |
-
|
356 |
-
Returns:
|
357 |
-
numpy.ndarray: The data read from the CSV file.
|
358 |
-
"""
|
359 |
-
file_data = pd.read_csv(input_file, dtype='string', keep_default_na=False, sep=',').values
|
360 |
-
return file_data
|
361 |
-
|
362 |
-
def bart_score(text_1, text_2):
|
363 |
-
"""
|
364 |
-
Computes the BART score between two texts.
|
365 |
-
|
366 |
-
Parameters:
|
367 |
-
text_1 (str): The first text.
|
368 |
-
text_2 (str): The second text.
|
369 |
-
|
370 |
-
Returns:
|
371 |
-
float: The BART score.
|
372 |
-
"""
|
373 |
-
score = bart_scorer.score([text_1], [text_2])
|
374 |
-
return score
|
375 |
-
|
376 |
-
def check_bart_score(input_text, raw_text):
|
377 |
-
"""
|
378 |
-
Checks if the BART score between input_text and raw_text is above a threshold.
|
379 |
-
|
380 |
-
Parameters:
|
381 |
-
input_text (str): The input text.
|
382 |
-
raw_text (str): The raw text to compare against.
|
383 |
-
|
384 |
-
Returns:
|
385 |
-
bool: True if the score is above the threshold, False otherwise.
|
386 |
-
"""
|
387 |
-
THRESHOLD = -2.459
|
388 |
-
normalized_text = normalize_text(raw_text)
|
389 |
-
score = bart_score(input_text, normalized_text)[0]
|
390 |
-
return score >= THRESHOLD
|
391 |
-
|
392 |
-
def get_column(input_file, column_name):
|
393 |
-
"""
|
394 |
-
Retrieves a specific column from a CSV file.
|
395 |
-
|
396 |
-
Parameters:
|
397 |
-
input_file (str): The name of the CSV file.
|
398 |
-
column_name (str): The name of the column to retrieve.
|
399 |
-
|
400 |
-
Returns:
|
401 |
-
numpy.ndarray: The values from the specified column.
|
402 |
-
"""
|
403 |
-
df = pd.read_csv(input_file, dtype='string', keep_default_na=False, sep=',')
|
404 |
-
column_data = df[column_name]
|
405 |
-
return column_data.values
|
406 |
-
|
407 |
-
def generate_column_names(categories):
|
408 |
-
"""
|
409 |
-
Generates a list of column names based on given categories.
|
410 |
-
|
411 |
-
Parameters:
|
412 |
-
categories (list): The list of categories.
|
413 |
-
|
414 |
-
Returns:
|
415 |
-
list: The generated list of column names.
|
416 |
-
"""
|
417 |
-
column_names = ['human']
|
418 |
-
for name in categories:
|
419 |
-
column_names.append(name)
|
420 |
-
for first in categories:
|
421 |
-
for second in categories:
|
422 |
-
column_names.append(f"{first}_{second}")
|
423 |
-
return column_names
|
424 |
-
|
425 |
-
def write_new_data(output_file, current_data, column_names):
|
426 |
-
"""
|
427 |
-
Writes new data to a CSV file based on current data and column names.
|
428 |
-
|
429 |
-
Parameters:
|
430 |
-
output_file (str): The name of the output CSV file.
|
431 |
-
current_data (dict): The current data to be written.
|
432 |
-
column_names (list): The list of column names.
|
433 |
-
"""
|
434 |
-
data_row = [current_data[column] for column in column_names]
|
435 |
-
write_to_csv(output_file, data_row)
|
436 |
-
|
437 |
-
def refine(input_text, candidate):
|
438 |
-
"""
|
439 |
-
Refines the candidate string by removing specific surrounding marks if they are present
|
440 |
-
in the input_text with a count difference of exactly 2.
|
441 |
-
|
442 |
-
Args:
|
443 |
-
input_text (str): The original text.
|
444 |
-
candidate (str): The candidate text to be refined.
|
445 |
-
|
446 |
-
Returns:
|
447 |
-
str: The refined candidate text.
|
448 |
-
"""
|
449 |
-
|
450 |
-
# Create a copy of the candidate string and strip whitespace
|
451 |
-
refined_candidate = candidate.strip()
|
452 |
-
|
453 |
-
# List of marks to check and potentially remove
|
454 |
-
marks = ["```", "'", '"']
|
455 |
-
|
456 |
-
# Iterate through each mark
|
457 |
-
for mark in marks:
|
458 |
-
# Count occurrences of the mark in input_text and refined_candidate
|
459 |
-
count_input_text = input_text.count(mark)
|
460 |
-
count_refined_candidate = refined_candidate.count(mark)
|
461 |
-
|
462 |
-
# Check if the mark should be stripped
|
463 |
-
if (count_refined_candidate == count_input_text + 2 and
|
464 |
-
refined_candidate.startswith(mark) and
|
465 |
-
refined_candidate.endswith(mark)):
|
466 |
-
# Strip the mark from both ends of the refined_candidate
|
467 |
-
refined_candidate = refined_candidate.strip(mark)
|
468 |
-
|
469 |
-
return refined_candidate
|
470 |
-
|
471 |
-
|
472 |
-
def extract_by_best_similarity(input_text, raw_text):
|
473 |
-
"""
|
474 |
-
Extracts the best candidate string from the raw text based on the highest similarity score
|
475 |
-
compared to the input text. The similarity score is calculated using the BART score.
|
476 |
-
|
477 |
-
Args:
|
478 |
-
input_text (str): The original text.
|
479 |
-
raw_text (str): The raw text containing multiple candidate strings.
|
480 |
-
|
481 |
-
Returns:
|
482 |
-
str: The best candidate string with the highest similarity score.
|
483 |
-
Returns the input text if no suitable candidate is found.
|
484 |
-
"""
|
485 |
-
|
486 |
-
# Refine the raw text
|
487 |
-
refined_raw_text = refine(input_text, raw_text)
|
488 |
-
|
489 |
-
# Tokenize the refined raw text into sentences
|
490 |
-
raw_candidates = nltk.sent_tokenize(refined_raw_text)
|
491 |
-
|
492 |
-
# Split sentences further by newlines to get individual candidates
|
493 |
-
candidate_list = []
|
494 |
-
for sentence in raw_candidates:
|
495 |
-
candidate_list.extend(sentence.split("\n"))
|
496 |
-
|
497 |
-
# Initialize variables to track the best similarity score and the best candidate
|
498 |
-
best_similarity = -9999
|
499 |
-
best_candidate = ""
|
500 |
-
|
501 |
-
# Iterate over each candidate to find the best one based on the BART score
|
502 |
-
for candidate in candidate_list:
|
503 |
-
refined_candidate = refine(input_text, candidate)
|
504 |
-
if check_bart_score(input_text, refined_candidate):
|
505 |
-
score = bart_score(input_text, refined_candidate)[0]
|
506 |
-
if score > best_similarity:
|
507 |
-
best_similarity = score
|
508 |
-
best_candidate = refined_candidate
|
509 |
-
|
510 |
-
# Print the best candidate found
|
511 |
-
print(f"best_candidate = {best_candidate}")
|
512 |
-
|
513 |
-
# Return the best candidate if found, otherwise return the input text
|
514 |
-
if best_candidate == "":
|
515 |
-
return input_text
|
516 |
-
return best_candidate
|
517 |
-
|
518 |
-
def proofread_with_best_similarity(input_text, model_kind):
|
519 |
-
"""
|
520 |
-
Proofreads the input text using the specified model and extracts the best-corrected text based on similarity.
|
521 |
-
|
522 |
-
Args:
|
523 |
-
input_text (str): The original text to be proofread.
|
524 |
-
model_kind (str): The kind of model to use for proofreading (e.g., CHATGPT, GEMINI).
|
525 |
-
|
526 |
-
Returns:
|
527 |
-
tuple: A tuple containing the raw proofread text and the best-corrected text.
|
528 |
-
"""
|
529 |
-
|
530 |
-
# Normalize the input text
|
531 |
-
normalized_input_text = normalize_text(input_text)
|
532 |
-
print_and_log(f"INPUT = {normalized_input_text}")
|
533 |
-
|
534 |
-
result_text = ""
|
535 |
-
raw_text = ""
|
536 |
-
|
537 |
-
for i in range(1): # Loop is redundant as it runs only once; consider removing if unnecessary
|
538 |
-
# Select the proofreading model based on model_kind
|
539 |
-
if model_kind == CHATGPT:
|
540 |
-
raw_text = chatGPT_proofread(normalized_input_text, normalize_output=IS_OUTPUT_NORMALIZATION)
|
541 |
-
elif model_kind == GEMINI:
|
542 |
-
raw_text = gemini_proofread(normalized_input_text, normalize_output=IS_OUTPUT_NORMALIZATION)
|
543 |
-
else:
|
544 |
-
raw_text = proofread_by_model_name(model_kind, normalized_input_text, normalize_output=IS_OUTPUT_NORMALIZATION)
|
545 |
-
|
546 |
-
# Extract the best candidate text based on similarity
|
547 |
-
result_text = extract_by_best_similarity(normalized_input_text, raw_text)
|
548 |
-
|
549 |
-
# Log the raw and result texts
|
550 |
-
print_and_log(f"RAW_{i} = {raw_text}")
|
551 |
-
print_and_log(f"RESULT_{i} = {result_text}")
|
552 |
-
|
553 |
-
# Normalize the result text
|
554 |
-
result_text = normalize_text(result_text)
|
555 |
-
|
556 |
-
# If a valid result is obtained, return it
|
557 |
-
if result_text != "":
|
558 |
-
return raw_text, result_text
|
559 |
-
|
560 |
-
# Return the raw and result texts
|
561 |
-
return raw_text, result_text
|
562 |
-
|
563 |
-
def generate_file_name(existing_data_file, existing_kinds, new_kinds):
|
564 |
-
"""
|
565 |
-
Generates a new file name based on the path of an existing data file and a combination of existing and new kinds.
|
566 |
-
|
567 |
-
Args:
|
568 |
-
existing_data_file (str): The path to the existing data file.
|
569 |
-
existing_kinds (list): A list of existing kinds.
|
570 |
-
new_kinds (list): A list of new kinds.
|
571 |
-
|
572 |
-
Returns:
|
573 |
-
str: The generated file name with the full path.
|
574 |
-
"""
|
575 |
-
|
576 |
-
# Combine existing and new kinds into a single list
|
577 |
-
combined_kinds = existing_kinds + new_kinds
|
578 |
-
|
579 |
-
# Get the directory path of the existing data file
|
580 |
-
directory_path = os.path.dirname(existing_data_file)
|
581 |
-
|
582 |
-
# Create a new file name by joining the kinds with underscores and adding a suffix
|
583 |
-
new_file_name = "_".join(combined_kinds) + "_with_best_similarity.csv"
|
584 |
-
|
585 |
-
# Combine the directory path with the new file name to get the full output file path
|
586 |
-
output_file_path = os.path.join(directory_path, new_file_name)
|
587 |
-
|
588 |
-
return output_file_path
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
def generate_new_data_with_best_similarity(existing_data_file, existing_kinds, new_kinds):
|
593 |
-
"""
|
594 |
-
Generates new data with the best similarity based on existing and new kinds, and writes the results to a CSV file.
|
595 |
-
|
596 |
-
Args:
|
597 |
-
existing_data_file (str): The path to the existing data file.
|
598 |
-
existing_kinds (list): A list of existing kinds.
|
599 |
-
new_kinds (list): A list of new kinds.
|
600 |
-
|
601 |
-
Returns:
|
602 |
-
None
|
603 |
-
"""
|
604 |
-
|
605 |
-
# Combine existing and new kinds into a single list
|
606 |
-
all_kinds = existing_kinds + new_kinds
|
607 |
-
|
608 |
-
# Generate column names for the CSV file
|
609 |
-
column_names = generate_column_names(all_kinds)
|
610 |
-
|
611 |
-
# Generate column names for existing kinds
|
612 |
-
existing_column_names = generate_column_names(existing_kinds)
|
613 |
-
|
614 |
-
# Generate the output file name
|
615 |
-
output_file = generate_file_name(existing_data_file, existing_kinds, new_kinds)
|
616 |
-
|
617 |
-
# Create the output file with column names if it doesn't exist
|
618 |
-
if not os.path.exists(output_file):
|
619 |
-
write_to_csv(output_file, column_names)
|
620 |
-
|
621 |
-
# Read existing data from the file
|
622 |
-
existing_data = {kind: get_column(existing_data_file, kind) for kind in existing_column_names}
|
623 |
-
|
624 |
-
# Read input data from the output file
|
625 |
-
input_data = read_csv_data(output_file)
|
626 |
-
start_index = len(input_data)
|
627 |
-
print(f"start_index = {start_index}")
|
628 |
-
|
629 |
-
num_rows = len(existing_data["human"])
|
630 |
-
global_generate_set = []
|
631 |
-
global_reuse = []
|
632 |
-
|
633 |
-
for index in range(start_index, num_rows):
|
634 |
-
# Initialize generation and reuse sets
|
635 |
-
generate_set = []
|
636 |
-
reuse_set = []
|
637 |
-
|
638 |
-
# Prepare the current generation dictionary
|
639 |
-
current_generation = {kind: existing_data[kind][index] for kind in existing_column_names}
|
640 |
-
print(f"current_generation before generation = {current_generation}")
|
641 |
-
|
642 |
-
human_text = current_generation["human"]
|
643 |
-
|
644 |
-
# Generate new kinds based on human text
|
645 |
-
for kind in new_kinds:
|
646 |
-
_, generated_text = proofread_with_best_similarity(human_text, kind)
|
647 |
-
current_generation[kind] = generated_text
|
648 |
-
generate_set.append(kind)
|
649 |
-
|
650 |
-
print(f"current_generation after generate one = {current_generation}")
|
651 |
-
|
652 |
-
# Generate combinations of kinds
|
653 |
-
for first_kind in all_kinds:
|
654 |
-
for second_kind in all_kinds:
|
655 |
-
combination_name = f"{first_kind}_{second_kind}"
|
656 |
-
|
657 |
-
if combination_name not in current_generation:
|
658 |
-
if first_kind in current_generation and current_generation[first_kind] == human_text:
|
659 |
-
generated_text = current_generation[second_kind]
|
660 |
-
reuse_set.append(f"{combination_name} from {second_kind}")
|
661 |
-
else:
|
662 |
-
is_need_generation = True
|
663 |
-
for first_kind_2 in all_kinds:
|
664 |
-
if first_kind != first_kind_2 and current_generation[first_kind] == current_generation[first_kind_2]:
|
665 |
-
combination_name_2 = f"{first_kind_2}_{second_kind}"
|
666 |
-
if combination_name_2 in current_generation:
|
667 |
-
generated_text = current_generation[combination_name_2]
|
668 |
-
reuse_set.append(f"{combination_name} from {combination_name_2}")
|
669 |
-
is_need_generation = False
|
670 |
-
break
|
671 |
-
if is_need_generation:
|
672 |
-
_, generated_text = proofread_with_best_similarity(current_generation[first_kind], second_kind)
|
673 |
-
generate_set.append(f"{first_kind}_{second_kind}")
|
674 |
-
|
675 |
-
current_generation[combination_name] = generated_text
|
676 |
-
|
677 |
-
# Write the current generation to the output file
|
678 |
-
write_new_data(output_file, current_generation, column_names)
|
679 |
-
|
680 |
-
# Update global sets
|
681 |
-
global_generate_set.append(generate_set)
|
682 |
-
global_reuse
|
683 |
-
|
684 |
-
def shuffle(array, seed):
|
685 |
-
"""
|
686 |
-
Shuffles the elements of each sublist in the given array using the specified seed.
|
687 |
-
|
688 |
-
Args:
|
689 |
-
array (list of lists): The array containing sublists to shuffle.
|
690 |
-
seed (int): The seed value for the random number generator.
|
691 |
-
|
692 |
-
Returns:
|
693 |
-
None
|
694 |
-
"""
|
695 |
-
for sublist in array:
|
696 |
-
random.Random(seed).shuffle(sublist)
|
697 |
-
|
698 |
-
def generate_human_with_shuffle(dataset_name, column_name, num_samples, output_file):
|
699 |
-
"""
|
700 |
-
Generates a shuffled list of sentences from the dataset and writes them to a CSV file.
|
701 |
-
|
702 |
-
Args:
|
703 |
-
dataset_name (str): The name of the dataset to load.
|
704 |
-
column_name (str): The column name to extract sentences from.
|
705 |
-
num_samples (int): The number of samples to process.
|
706 |
-
output_file (str): The path to the output CSV file.
|
707 |
-
|
708 |
-
Returns:
|
709 |
-
None
|
710 |
-
"""
|
711 |
-
# Load the dataset
|
712 |
-
dataset = load_dataset(dataset_name)
|
713 |
-
data = dataset['train']
|
714 |
-
|
715 |
-
lines = []
|
716 |
-
# Tokenize sentences and add to the lines list
|
717 |
-
for sample in data:
|
718 |
-
nltk_tokens = nltk.sent_tokenize(sample[column_name])
|
719 |
-
lines.extend(nltk_tokens)
|
720 |
-
|
721 |
-
# Filter out empty lines
|
722 |
-
filtered_lines = [line for line in lines if line != ""]
|
723 |
-
lines = filtered_lines
|
724 |
-
|
725 |
-
# Shuffle the lines
|
726 |
-
shuffle([lines], seed=SEED)
|
727 |
-
|
728 |
-
# Ensure the output file exists and write the header if it doesn't
|
729 |
-
if not os.path.exists(output_file):
|
730 |
-
header = ["human"]
|
731 |
-
write_to_csv(output_file, header)
|
732 |
-
|
733 |
-
# Get the number of lines already processed in the output file
|
734 |
-
number_of_processed_lines = number_of_csv_lines(output_file)
|
735 |
-
|
736 |
-
# Print the initial lines to be processed
|
737 |
-
print(f"Lines before processing: {lines[:num_samples]}")
|
738 |
-
|
739 |
-
# Slice the lines list to get the unprocessed lines
|
740 |
-
lines = lines[number_of_processed_lines:num_samples]
|
741 |
-
|
742 |
-
# Print the lines after slicing
|
743 |
-
print(f"Lines after slicing: {lines}")
|
744 |
-
|
745 |
-
# Process each line and write to the output file
|
746 |
-
for index, human in enumerate(lines):
|
747 |
-
normalized_text = normalize_text(human)
|
748 |
-
output_data = [normalized_text]
|
749 |
-
write_to_csv(output_file, output_data)
|
750 |
-
print(f"Processed {index + 1} / {len(lines)}; Total processed: {number_of_processed_lines + index + 1} / {num_samples}")
|
751 |
-
|
752 |
-
|
753 |
-
def split(data, ratio):
|
754 |
-
"""
|
755 |
-
Splits the data into training and testing sets based on the given ratio.
|
756 |
-
|
757 |
-
Args:
|
758 |
-
data (list): The dataset to split.
|
759 |
-
ratio (float): The ratio for splitting the data into training and testing sets.
|
760 |
-
|
761 |
-
Returns:
|
762 |
-
tuple: A tuple containing the training data and the testing data.
|
763 |
-
"""
|
764 |
-
train_size = int(len(data) * ratio)
|
765 |
-
train_data = data[:train_size]
|
766 |
-
test_data = data[train_size:]
|
767 |
-
return train_data, test_data
|
768 |
-
|
769 |
-
def bart_score_in_batch(text_1, text_2):
|
770 |
-
"""
|
771 |
-
Calculates the BART score for pairs of texts in batches.
|
772 |
-
|
773 |
-
Args:
|
774 |
-
text_1 (list of str): The first list of texts.
|
775 |
-
text_2 (list of str): The second list of texts.
|
776 |
-
|
777 |
-
Returns:
|
778 |
-
list: A list of BART scores for each pair of texts.
|
779 |
-
"""
|
780 |
-
return bart_scorer.score(text_1, text_2, batch_size=BATCH_SIZE)
|
781 |
-
|
782 |
-
def extract_feature_in_batch(text_1, text_2, feature_kind):
|
783 |
-
"""
|
784 |
-
Extracts features for pairs of texts using BART scores.
|
785 |
-
|
786 |
-
Args:
|
787 |
-
text_1 (list of str): The first list of texts.
|
788 |
-
text_2 (list of str): The second list of texts.
|
789 |
-
feature_kind (str): The type of feature to extract.
|
790 |
-
|
791 |
-
Returns:
|
792 |
-
list: A list of extracted features.
|
793 |
-
"""
|
794 |
-
features = bart_score_in_batch(text_1, text_2)
|
795 |
-
return features
|
796 |
-
|
797 |
-
def abstract_train(features, labels):
|
798 |
-
"""
|
799 |
-
Trains a model using the given features and labels.
|
800 |
-
|
801 |
-
Args:
|
802 |
-
features (list): The input features for training.
|
803 |
-
labels (list): The target labels for training.
|
804 |
-
|
805 |
-
Returns:
|
806 |
-
object: The trained model.
|
807 |
-
"""
|
808 |
-
model = MLPClassifier()
|
809 |
-
model.fit(features, labels)
|
810 |
-
return model
|
811 |
-
|
812 |
-
def evaluate_model(model, features, labels):
|
813 |
-
"""
|
814 |
-
Evaluates the model's performance using accuracy and ROC AUC scores.
|
815 |
-
|
816 |
-
Args:
|
817 |
-
model (object): The trained model to evaluate.
|
818 |
-
features (list): The input features for evaluation.
|
819 |
-
labels (list): The target labels for evaluation.
|
820 |
-
|
821 |
-
Returns:
|
822 |
-
None
|
823 |
-
"""
|
824 |
-
predictions = model.predict(features)
|
825 |
-
rounded_predictions = [round(value) for value in predictions]
|
826 |
-
|
827 |
-
accuracy = accuracy_score(labels, rounded_predictions)
|
828 |
-
write_to_file(OUTPUT_FILE, f"Accuracy: {accuracy * 100.0:.1f}%\n")
|
829 |
-
|
830 |
-
roc_auc = roc_auc_score(labels, rounded_predictions)
|
831 |
-
write_to_file(OUTPUT_FILE, f"ROC AUC: {roc_auc * 100.0:.1f}%\n")
|
832 |
-
|
833 |
-
def combine_text_with_BERT_format(text_list):
|
834 |
-
"""
|
835 |
-
Combines a list of texts into a single string formatted for BERT input.
|
836 |
-
|
837 |
-
Args:
|
838 |
-
text_list (list of str): The list of texts to combine.
|
839 |
-
|
840 |
-
Returns:
|
841 |
-
str: The combined text string formatted for BERT input.
|
842 |
-
"""
|
843 |
-
combined_text = f"<s>{text_list[0]}</s>"
|
844 |
-
for i in range(1, len(text_list)):
|
845 |
-
combined_text += f"</s>{text_list[i]}</s>"
|
846 |
-
return combined_text
|
847 |
-
|
848 |
-
|
849 |
-
def preprocess_function_multimodel(sample):
|
850 |
-
"""
|
851 |
-
Preprocesses a given sample for a multi-model setup by calculating BART scores
|
852 |
-
and formatting the text for BERT input.
|
853 |
-
|
854 |
-
Args:
|
855 |
-
sample (dict): A dictionary containing a key "text", which is a list of lists of strings.
|
856 |
-
|
857 |
-
Returns:
|
858 |
-
dict: A dictionary containing tokenized and preprocessed text data.
|
859 |
-
"""
|
860 |
-
num_texts = len(sample["text"][0]) # Number of texts in each sub-sample
|
861 |
-
texts_grouped_by_index = [[] for _ in range(num_texts)] # Initialize empty lists for grouping texts by index
|
862 |
-
|
863 |
-
# Group texts by their index across sub-samples
|
864 |
-
for sub_sample in sample["text"]:
|
865 |
-
for i in range(num_texts):
|
866 |
-
texts_grouped_by_index[i].append(sub_sample[i])
|
867 |
-
|
868 |
-
# Calculate BART scores for each text pair (text[0] with text[i])
|
869 |
-
bart_scores = [bart_score_in_batch(texts_grouped_by_index[0], texts_grouped_by_index[i]) for i in range(1, num_texts)]
|
870 |
-
|
871 |
-
combined_texts = []
|
872 |
-
|
873 |
-
# Process each sub-sample for BERT input
|
874 |
-
for index, sub_sample in enumerate(sample["text"]):
|
875 |
-
text_array = [sub_sample[0]] # Start with the input text
|
876 |
-
score_generation_pairs = []
|
877 |
-
|
878 |
-
# Pair scores with their corresponding generations
|
879 |
-
for i in range(1, num_texts):
|
880 |
-
generation_text = sub_sample[i]
|
881 |
-
generation_score = bart_scores[i-1][index]
|
882 |
-
score_generation_pairs.append((generation_score, generation_text))
|
883 |
-
|
884 |
-
# Sort pairs by score in descending order
|
885 |
-
sorted_pairs = sorted(score_generation_pairs, reverse=True)
|
886 |
-
|
887 |
-
# Append sorted texts to text_array
|
888 |
-
for _, sorted_text in sorted_pairs:
|
889 |
-
text_array.append(sorted_text)
|
890 |
-
|
891 |
-
# Combine texts into a single BERT-formatted string
|
892 |
-
combined_text = combine_text_with_BERT_format(text_array)
|
893 |
-
combined_texts.append(combined_text)
|
894 |
-
|
895 |
-
# Tokenize the combined texts for BERT
|
896 |
-
return tokenizer(combined_texts, add_special_tokens=False, truncation=True)
|
897 |
-
|
898 |
-
def preprocess_function_single_from_multimodel(sample):
|
899 |
-
"""
|
900 |
-
Extracts the first text from each sub-sample in a multi-model sample and tokenizes it.
|
901 |
-
|
902 |
-
Args:
|
903 |
-
sample (dict): A dictionary containing a key "text", which is a list of lists of strings.
|
904 |
-
|
905 |
-
Returns:
|
906 |
-
dict: A dictionary containing tokenized text data.
|
907 |
-
"""
|
908 |
-
combined_texts = []
|
909 |
-
|
910 |
-
# Iterate through each sub-sample
|
911 |
-
for sub_sample in sample["text"]:
|
912 |
-
input_text = sub_sample[0] # Extract the first text from the sub-sample
|
913 |
-
combined_texts.append(input_text) # Append it to the list of combined texts
|
914 |
-
|
915 |
-
# Tokenize the combined texts
|
916 |
-
return tokenizer(combined_texts, truncation=True)
|
917 |
-
|
918 |
-
|
919 |
-
def check_api_error(data):
|
920 |
-
"""
|
921 |
-
Checks if any item in the provided data indicates an API error.
|
922 |
-
|
923 |
-
Args:
|
924 |
-
data (list): A list of items to be checked for API errors.
|
925 |
-
|
926 |
-
Returns:
|
927 |
-
bool: True if an API error or ignore by API error is found, otherwise False.
|
928 |
-
"""
|
929 |
-
for item in data:
|
930 |
-
if item == API_ERROR or item == IGNORE_BY_API_ERROR: # Check for API error indicators
|
931 |
-
return True # Return True if an error indicator is found
|
932 |
-
return False # Return False if no error indicators are found
|
933 |
-
|
934 |
-
|
935 |
-
def train_only_by_transformer_with_test_evaluation_early_stop(train_data, test_data, input_type, num_classes=2):
|
936 |
-
"""
|
937 |
-
Trains a transformer model using the provided training and testing datasets with early stopping.
|
938 |
-
|
939 |
-
Args:
|
940 |
-
train_data (Dataset): The training dataset.
|
941 |
-
test_data (Dataset): The testing dataset.
|
942 |
-
input_type (str): The type of input data, either MULTIMODEL or SINGLE_FROM_MULTIMODEL.
|
943 |
-
num_classes (int, optional): The number of classes for classification. Defaults to 2.
|
944 |
-
|
945 |
-
Returns:
|
946 |
-
Trainer: The trained model wrapped in a Trainer object.
|
947 |
-
"""
|
948 |
-
# Preprocess datasets based on the input type
|
949 |
-
if input_type == MULTIMODEL:
|
950 |
-
train_data = train_data.map(preprocess_function_multimodel, batched=True)
|
951 |
-
test_data = test_data.map(preprocess_function_multimodel, batched=True)
|
952 |
-
elif input_type == SINGLE_FROM_MULTIMODEL:
|
953 |
-
train_data = train_data.map(preprocess_function_single_from_multimodel, batched=True)
|
954 |
-
test_data = test_data.map(preprocess_function_single_from_multimodel, batched=True)
|
955 |
-
|
956 |
-
# Data collator to pad inputs
|
957 |
-
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
|
958 |
-
|
959 |
-
# Load appropriate model based on number of classes
|
960 |
-
if num_classes == 3:
|
961 |
-
model = AutoModelForSequenceClassification.from_pretrained(
|
962 |
-
"pretrained_model/roberta-base_num_labels_3", num_labels=num_classes)
|
963 |
-
else:
|
964 |
-
model = AutoModelForSequenceClassification.from_pretrained(
|
965 |
-
ROBERTA_MODEL_PATHS[MODEL_NAME], num_labels=num_classes)
|
966 |
-
|
967 |
-
learning_rate = LEARNING_RATES[MODEL_NAME]
|
968 |
-
output_folder = "training_with_callbacks"
|
969 |
-
|
970 |
-
# Remove the output folder if it already exists
|
971 |
-
if os.path.exists(output_folder):
|
972 |
-
shutil.rmtree(output_folder)
|
973 |
-
|
974 |
-
# Training arguments
|
975 |
-
training_args = TrainingArguments(
|
976 |
-
output_dir=output_folder,
|
977 |
-
evaluation_strategy="epoch",
|
978 |
-
logging_strategy="epoch",
|
979 |
-
save_strategy="epoch",
|
980 |
-
learning_rate=learning_rate,
|
981 |
-
per_device_train_batch_size=BATCH_SIZE,
|
982 |
-
per_device_eval_batch_size=BATCH_SIZE,
|
983 |
-
num_train_epochs=NUMBER_OF_MAX_EPOCH_WITH_EARLY_STOPPING,
|
984 |
-
weight_decay=0.01,
|
985 |
-
push_to_hub=False,
|
986 |
-
metric_for_best_model=OPTIMIZED_METRIC,
|
987 |
-
load_best_model_at_end=True
|
988 |
-
)
|
989 |
-
|
990 |
-
# Create Trainer object
|
991 |
-
trainer = Trainer(
|
992 |
-
model=model,
|
993 |
-
args=training_args,
|
994 |
-
train_dataset=train_data,
|
995 |
-
eval_dataset=test_data,
|
996 |
-
tokenizer=tokenizer,
|
997 |
-
data_collator=data_collator,
|
998 |
-
compute_metrics=compute_metrics,
|
999 |
-
callbacks=[EarlyStoppingCallback(early_stopping_patience=PATIENCE)]
|
1000 |
-
)
|
1001 |
-
|
1002 |
-
# Add custom callback
|
1003 |
-
trainer.add_callback(CustomCallback(trainer))
|
1004 |
-
|
1005 |
-
# Start training
|
1006 |
-
trainer.train()
|
1007 |
-
|
1008 |
-
return trainer
|
1009 |
-
|
1010 |
-
|
1011 |
-
def calculate_number_of_models(num_columns):
|
1012 |
-
"""
|
1013 |
-
Calculates the number of models required based on the number of columns.
|
1014 |
-
|
1015 |
-
Args:
|
1016 |
-
num_columns (int): The total number of columns.
|
1017 |
-
|
1018 |
-
Returns:
|
1019 |
-
int: The number of models required.
|
1020 |
-
|
1021 |
-
Raises:
|
1022 |
-
Exception: If the number of models cannot be calculated to match the number of columns.
|
1023 |
-
"""
|
1024 |
-
num_models = 0
|
1025 |
-
count_human = 1 # Initial count representing human input
|
1026 |
-
|
1027 |
-
while True:
|
1028 |
-
count_single = num_models # Single model count
|
1029 |
-
count_pair = num_models * num_models # Pair model count
|
1030 |
-
|
1031 |
-
total_count = count_human + count_single + count_pair
|
1032 |
-
|
1033 |
-
if total_count == num_columns:
|
1034 |
-
return num_models
|
1035 |
-
elif total_count > num_columns:
|
1036 |
-
raise Exception("Cannot calculate the number of models to match the number of columns")
|
1037 |
-
|
1038 |
-
num_models += 1
|
1039 |
-
|
1040 |
-
|
1041 |
-
def read_multimodel_data_from_csv(multimodel_csv_file):
|
1042 |
-
"""
|
1043 |
-
Reads multimodel data from a CSV file and organizes it into a structured format.
|
1044 |
-
|
1045 |
-
Args:
|
1046 |
-
multimodel_csv_file (str): Path to the CSV file containing multimodel data.
|
1047 |
-
|
1048 |
-
Returns:
|
1049 |
-
list: A list of dictionaries, each containing 'human', 'single', and 'pair' data.
|
1050 |
-
|
1051 |
-
Raises:
|
1052 |
-
Exception: If there is an error in reading the CSV file or processing the data.
|
1053 |
-
"""
|
1054 |
-
# Read CSV data into a list of lists
|
1055 |
-
input_data = read_csv_data(multimodel_csv_file)
|
1056 |
-
|
1057 |
-
# Initialize the result list
|
1058 |
-
structured_data = []
|
1059 |
-
|
1060 |
-
# Calculate the number of models based on the number of columns in the first row
|
1061 |
-
num_models = calculate_number_of_models(len(input_data[0]))
|
1062 |
-
|
1063 |
-
# Process each row in the input data
|
1064 |
-
for row in input_data:
|
1065 |
-
row_data = {}
|
1066 |
-
index = 0
|
1067 |
-
|
1068 |
-
# Extract human data
|
1069 |
-
row_data["human"] = row[index]
|
1070 |
-
index += 1
|
1071 |
-
|
1072 |
-
# Extract single model data
|
1073 |
-
single_model_data = []
|
1074 |
-
for _ in range(num_models):
|
1075 |
-
single_model_data.append(row[index])
|
1076 |
-
index += 1
|
1077 |
-
row_data["single"] = single_model_data
|
1078 |
-
|
1079 |
-
# Extract pair model data
|
1080 |
-
pair_model_data = []
|
1081 |
-
for _ in range(num_models):
|
1082 |
-
sub_pair_data = []
|
1083 |
-
for _ in range(num_models):
|
1084 |
-
sub_pair_data.append(row[index])
|
1085 |
-
index += 1
|
1086 |
-
pair_model_data.append(sub_pair_data)
|
1087 |
-
row_data["pair"] = pair_model_data
|
1088 |
-
|
1089 |
-
# Append the structured row data to the result list
|
1090 |
-
structured_data.append(row_data)
|
1091 |
-
|
1092 |
-
return structured_data
|
1093 |
-
|
1094 |
-
|
1095 |
-
def check_error(data_item):
|
1096 |
-
"""
|
1097 |
-
Checks for errors in a data item by verifying the 'human', 'single', and 'pair' fields.
|
1098 |
-
|
1099 |
-
Args:
|
1100 |
-
data_item (dict): A dictionary containing 'human', 'single', and 'pair' data.
|
1101 |
-
|
1102 |
-
Returns:
|
1103 |
-
bool: True if any of the fields contain an error, otherwise False.
|
1104 |
-
"""
|
1105 |
-
# Check for API error in the 'human' field
|
1106 |
-
if check_api_error(data_item["human"]):
|
1107 |
-
return True
|
1108 |
-
|
1109 |
-
# Check for API error in the 'single' model data
|
1110 |
-
for single_text in data_item["single"]:
|
1111 |
-
if check_api_error(single_text):
|
1112 |
-
return True
|
1113 |
-
|
1114 |
-
# Get the number of models from the 'single' model data
|
1115 |
-
num_models = len(data_item["single"])
|
1116 |
-
|
1117 |
-
# Check for API error in the 'pair' model data
|
1118 |
-
for i in range(num_models):
|
1119 |
-
for j in range(num_models):
|
1120 |
-
if check_api_error(data_item["pair"][i][j]):
|
1121 |
-
return True
|
1122 |
-
|
1123 |
-
# No errors found
|
1124 |
-
return False
|
1125 |
-
|
1126 |
-
|
1127 |
-
|
1128 |
-
def create_pair_sample(data_item, training_indices):
|
1129 |
-
"""
|
1130 |
-
Creates pair samples for training by comparing human data with machine-generated data.
|
1131 |
-
|
1132 |
-
Args:
|
1133 |
-
data_item (dict): A dictionary containing 'human', 'single', and 'pair' data.
|
1134 |
-
training_indices (list): A list of indices used for training.
|
1135 |
-
|
1136 |
-
Returns:
|
1137 |
-
list: A list of dictionaries, each containing a 'text' array and a 'label'.
|
1138 |
-
"""
|
1139 |
-
# Initialize the result list
|
1140 |
-
result_samples = []
|
1141 |
-
|
1142 |
-
# Check if there is any error in the data_item
|
1143 |
-
if check_error(data_item):
|
1144 |
-
return result_samples
|
1145 |
-
|
1146 |
-
print(training_indices)
|
1147 |
-
print(data_item)
|
1148 |
-
# Create machine samples
|
1149 |
-
for train_idx in training_indices:
|
1150 |
-
if data_item["human"] != data_item["single"][train_idx]:
|
1151 |
-
text_array = []
|
1152 |
-
machine_text = data_item["single"][train_idx]
|
1153 |
-
text_array.append(machine_text)
|
1154 |
-
|
1155 |
-
for sub_idx in training_indices:
|
1156 |
-
text_array.append(data_item["pair"][train_idx][sub_idx])
|
1157 |
-
|
1158 |
-
sample = {
|
1159 |
-
"text": text_array,
|
1160 |
-
"label": MACHINE_LABEL
|
1161 |
-
}
|
1162 |
-
result_samples.append(sample)
|
1163 |
-
|
1164 |
-
# Create human samples
|
1165 |
-
text_array = [data_item["human"]]
|
1166 |
-
|
1167 |
-
for train_idx in training_indices:
|
1168 |
-
text_array.append(data_item["single"][train_idx])
|
1169 |
-
|
1170 |
-
human_sample = {
|
1171 |
-
"text": text_array,
|
1172 |
-
"label": HUMAN_LABEL
|
1173 |
-
}
|
1174 |
-
|
1175 |
-
# Append human samples for each machine sample
|
1176 |
-
num_machine_samples = len(result_samples)
|
1177 |
-
for _ in range(num_machine_samples):
|
1178 |
-
result_samples.append(human_sample)
|
1179 |
-
|
1180 |
-
return result_samples
|
1181 |
-
|
1182 |
-
|
1183 |
-
def create_pair_test_sample(data_item, training_indices, testing_indices):
|
1184 |
-
"""
|
1185 |
-
Creates pair test samples by comparing human data with machine-generated data.
|
1186 |
-
|
1187 |
-
Args:
|
1188 |
-
data_item (dict): A dictionary containing 'human', 'single', and 'pair' data.
|
1189 |
-
training_indices (list): A list of indices used for training.
|
1190 |
-
testing_indices (list): A list of indices used for testing.
|
1191 |
-
|
1192 |
-
Returns:
|
1193 |
-
list: A list of dictionaries, each containing a 'text' array and a 'label'.
|
1194 |
-
"""
|
1195 |
-
# Initialize the result list
|
1196 |
-
result_samples = []
|
1197 |
-
|
1198 |
-
# Check if there is any error in the data_item
|
1199 |
-
if check_error(data_item):
|
1200 |
-
return result_samples
|
1201 |
-
|
1202 |
-
# Create machine samples based on testing indices
|
1203 |
-
for test_idx in testing_indices:
|
1204 |
-
if data_item["human"] != data_item["single"][test_idx]:
|
1205 |
-
text_array = []
|
1206 |
-
machine_text = data_item["single"][test_idx]
|
1207 |
-
text_array.append(machine_text)
|
1208 |
-
|
1209 |
-
for train_idx in training_indices:
|
1210 |
-
text_array.append(data_item["pair"][test_idx][train_idx])
|
1211 |
-
|
1212 |
-
sample = {
|
1213 |
-
"text": text_array,
|
1214 |
-
"label": MACHINE_LABEL
|
1215 |
-
}
|
1216 |
-
result_samples.append(sample)
|
1217 |
-
|
1218 |
-
# Create human sample
|
1219 |
-
text_array = [data_item["human"]]
|
1220 |
-
|
1221 |
-
for train_idx in training_indices:
|
1222 |
-
text_array.append(data_item["single"][train_idx])
|
1223 |
-
|
1224 |
-
human_sample = {
|
1225 |
-
"text": text_array,
|
1226 |
-
"label": HUMAN_LABEL
|
1227 |
-
}
|
1228 |
-
|
1229 |
-
# Append the human sample for each machine sample
|
1230 |
-
num_machine_samples = len(result_samples)
|
1231 |
-
for _ in range(num_machine_samples):
|
1232 |
-
result_samples.append(human_sample)
|
1233 |
-
|
1234 |
-
return result_samples
|
1235 |
-
|
1236 |
-
|
1237 |
-
|
1238 |
-
def create_train_val_sample(data, training_indices):
|
1239 |
-
"""
|
1240 |
-
Creates training and validation samples from the provided data.
|
1241 |
-
|
1242 |
-
Args:
|
1243 |
-
data (list): A list of data items, each to be processed.
|
1244 |
-
training_indices (list): A list of indices used for training.
|
1245 |
-
|
1246 |
-
Returns:
|
1247 |
-
list: A list of training and validation samples created from the data.
|
1248 |
-
"""
|
1249 |
-
# Initialize the result list
|
1250 |
-
result_samples = []
|
1251 |
-
|
1252 |
-
# Process each item in the data
|
1253 |
-
for data_item in data:
|
1254 |
-
# Create pair samples for the current item
|
1255 |
-
sub_samples = create_pair_sample(data_item, training_indices)
|
1256 |
-
|
1257 |
-
# Extend the result list with the created sub-samples
|
1258 |
-
result_samples.extend(sub_samples)
|
1259 |
-
|
1260 |
-
return result_samples
|
1261 |
-
|
1262 |
-
|
1263 |
-
def create_test_sample(data, training_indices, testing_indices):
|
1264 |
-
"""
|
1265 |
-
Creates test samples from the provided data by comparing human data with machine-generated data.
|
1266 |
-
|
1267 |
-
Args:
|
1268 |
-
data (list): A list of data items, each to be processed.
|
1269 |
-
training_indices (list): A list of indices used for training.
|
1270 |
-
testing_indices (list): A list of indices used for testing.
|
1271 |
-
|
1272 |
-
Returns:
|
1273 |
-
list: A list of test samples created from the data.
|
1274 |
-
"""
|
1275 |
-
# Initialize the result list
|
1276 |
-
result_samples = []
|
1277 |
-
|
1278 |
-
# Process each item in the data
|
1279 |
-
for data_item in data:
|
1280 |
-
# Create pair test samples for the current item
|
1281 |
-
sub_samples = create_pair_test_sample(data_item, training_indices, testing_indices)
|
1282 |
-
|
1283 |
-
# Extend the result list with the created sub-samples
|
1284 |
-
result_samples.extend(sub_samples)
|
1285 |
-
|
1286 |
-
return result_samples
|
1287 |
-
|
1288 |
-
|
1289 |
-
def distribute_data(data, train_indices, test_indices, train_ratio, val_ratio):
|
1290 |
-
"""
|
1291 |
-
Distributes the data into training, validation, and test samples.
|
1292 |
-
|
1293 |
-
Args:
|
1294 |
-
data (list): A list of data items to be split and processed.
|
1295 |
-
train_indices (list): A list of indices used for training.
|
1296 |
-
test_indices (list): A list of indices used for testing.
|
1297 |
-
train_ratio (float): The ratio of data to be used for training.
|
1298 |
-
val_ratio (float): The ratio of data to be used for validation.
|
1299 |
-
|
1300 |
-
Returns:
|
1301 |
-
tuple: A tuple containing lists of training, validation, and test samples.
|
1302 |
-
"""
|
1303 |
-
# Split the data into training, validation, and test sets
|
1304 |
-
train_data, val_data, test_data = split_train_val_test(data, train_ratio, val_ratio)
|
1305 |
-
|
1306 |
-
# Create training samples
|
1307 |
-
train_samples = create_train_val_sample(train_data, train_indices)
|
1308 |
-
write_to_file(OUTPUT_FILE, f"train samples = {len(train_samples)}\n")
|
1309 |
-
|
1310 |
-
# Create validation samples
|
1311 |
-
val_samples = create_train_val_sample(val_data, train_indices)
|
1312 |
-
write_to_file(OUTPUT_FILE, f"val samples = {len(val_samples)}\n")
|
1313 |
-
|
1314 |
-
# Create test samples
|
1315 |
-
test_samples = create_test_sample(test_data, train_indices, test_indices)
|
1316 |
-
write_to_file(OUTPUT_FILE, f"test samples = {len(test_samples)}\n")
|
1317 |
-
|
1318 |
-
return train_samples, val_samples, test_samples
|
1319 |
-
|
1320 |
-
|
1321 |
-
def convert_to_huggingface_with_multimodel(samples):
|
1322 |
-
"""
|
1323 |
-
Converts a list of samples to the Hugging Face Dataset format.
|
1324 |
-
|
1325 |
-
Args:
|
1326 |
-
samples (list): A list of samples to be converted.
|
1327 |
-
|
1328 |
-
Returns:
|
1329 |
-
Dataset: A Hugging Face Dataset object created from the samples.
|
1330 |
-
"""
|
1331 |
-
return Dataset.from_list(samples)
|
1332 |
-
|
1333 |
-
|
1334 |
-
|
1335 |
-
def train_by_transformer_with_multimodel_and_early_stop(train_samples, val_samples, input_type):
|
1336 |
-
"""
|
1337 |
-
Trains a transformer model with multimodal data and early stopping.
|
1338 |
-
|
1339 |
-
Args:
|
1340 |
-
train_samples (list): A list of training samples.
|
1341 |
-
val_samples (list): A list of validation samples.
|
1342 |
-
input_type (str): The type of input data (e.g., multimodal).
|
1343 |
-
|
1344 |
-
Returns:
|
1345 |
-
object: The trained model with early stopping.
|
1346 |
-
"""
|
1347 |
-
# Convert training and validation samples to Hugging Face Dataset format
|
1348 |
-
train_data = convert_to_huggingface_with_multimodel(train_samples)
|
1349 |
-
val_data = convert_to_huggingface_with_multimodel(val_samples)
|
1350 |
-
|
1351 |
-
# Train the model with early stopping and return the trained model
|
1352 |
-
return train_only_by_transformer_with_test_evaluation_early_stop(train_data, val_data, input_type)
|
1353 |
-
|
1354 |
-
|
1355 |
-
def test_by_transformer_with_multimodel(detector, test_samples, input_type):
|
1356 |
-
"""
|
1357 |
-
Tests a trained transformer model with multimodal data.
|
1358 |
-
|
1359 |
-
Args:
|
1360 |
-
detector (object): The trained model to be evaluated.
|
1361 |
-
test_samples (list): A list of test samples.
|
1362 |
-
input_type (str): The type of input data (e.g., multimodal).
|
1363 |
-
|
1364 |
-
Returns:
|
1365 |
-
None
|
1366 |
-
"""
|
1367 |
-
# Convert test samples to Hugging Face Dataset format
|
1368 |
-
test_data = convert_to_huggingface_with_multimodel(test_samples)
|
1369 |
-
|
1370 |
-
# Apply the appropriate preprocessing function based on the input type
|
1371 |
-
if input_type == MULTIMODEL:
|
1372 |
-
test_data = test_data.map(preprocess_function_multimodel, batched=True)
|
1373 |
-
elif input_type == SINGLE_FROM_MULTIMODEL:
|
1374 |
-
test_data = test_data.map(preprocess_function_single_from_multimodel, batched=True)
|
1375 |
-
|
1376 |
-
print("Test data:", test_data)
|
1377 |
-
# Evaluate the model on the test data
|
1378 |
-
result = detector.evaluate(eval_dataset=test_data)
|
1379 |
-
print("Test result:", result)
|
1380 |
-
|
1381 |
-
# Extract and log the ROC AUC score
|
1382 |
-
roc_auc = result['eval_roc_auc']
|
1383 |
-
write_to_file(OUTPUT_FILE, "roc_auc: %.1f%%" % (roc_auc * 100.0) + "\n")
|
1384 |
-
|
1385 |
-
|
1386 |
-
|
1387 |
-
def extract_by_feature_kind(samples, feature_type):
|
1388 |
-
"""
|
1389 |
-
Extracts features from the given samples based on the specified feature type.
|
1390 |
-
|
1391 |
-
Args:
|
1392 |
-
samples (list): A list of samples where each sample is a dictionary with 'text' and 'label' keys.
|
1393 |
-
feature_type (str): The type of feature to extract.
|
1394 |
-
|
1395 |
-
Returns:
|
1396 |
-
tuple: A tuple containing the extracted features and corresponding labels.
|
1397 |
-
"""
|
1398 |
-
text_1_list = []
|
1399 |
-
text_2_list = []
|
1400 |
-
labels = []
|
1401 |
-
|
1402 |
-
for sample in samples:
|
1403 |
-
text_1_list.append(sample["text"][0])
|
1404 |
-
text_2_list.append(sample["text"][1])
|
1405 |
-
labels.append(sample["label"])
|
1406 |
-
|
1407 |
-
# Extract features in batch based on the feature type
|
1408 |
-
features = extract_feature_in_batch(text_1_list, text_2_list, feature_type)
|
1409 |
-
|
1410 |
-
return features, labels
|
1411 |
-
|
1412 |
-
|
1413 |
-
def train_by_feature_kind(train_samples, feature_type):
|
1414 |
-
"""
|
1415 |
-
Trains a model using features extracted from the training samples based on the specified feature type.
|
1416 |
-
|
1417 |
-
Args:
|
1418 |
-
train_samples (list): A list of training samples where each sample is a dictionary with 'text' and 'label' keys.
|
1419 |
-
feature_type (str): The type of feature to extract for training.
|
1420 |
-
|
1421 |
-
Returns:
|
1422 |
-
object: The trained model.
|
1423 |
-
"""
|
1424 |
-
# Extract features and labels from the training samples
|
1425 |
-
features, labels = extract_by_feature_kind(train_samples, feature_type)
|
1426 |
-
|
1427 |
-
# Convert features to a numpy array and reshape for training
|
1428 |
-
features = np.array(features)
|
1429 |
-
features = features.reshape(-1, 1)
|
1430 |
-
|
1431 |
-
# Train the model using the extracted features and labels
|
1432 |
-
model = abstract_train(features, labels)
|
1433 |
-
|
1434 |
-
return model
|
1435 |
-
|
1436 |
-
|
1437 |
-
def test_by_feature_kind(detector, samples, feature_type):
|
1438 |
-
"""
|
1439 |
-
Tests a detector using features extracted from the provided samples based on the specified feature type.
|
1440 |
-
|
1441 |
-
Args:
|
1442 |
-
detector (object): The detector model to be evaluated.
|
1443 |
-
samples (list): A list of samples where each sample is a dictionary with 'text' and 'label' keys.
|
1444 |
-
feature_type (str): The type of feature to extract for testing.
|
1445 |
-
|
1446 |
-
Returns:
|
1447 |
-
None
|
1448 |
-
"""
|
1449 |
-
# Extract features and labels from the samples
|
1450 |
-
features, labels = extract_by_feature_kind(samples, feature_type)
|
1451 |
-
|
1452 |
-
# Convert features to a numpy array and reshape for evaluation
|
1453 |
-
features = np.array(features)
|
1454 |
-
features = features.reshape(-1, 1)
|
1455 |
-
|
1456 |
-
# Evaluate the detector model using the extracted features and labels
|
1457 |
-
evaluate_model(detector, features, labels)
|
1458 |
-
|
1459 |
-
|
1460 |
-
def general_process_multimodels_train_val_test(train_samples, val_samples, test_samples):
|
1461 |
-
"""
|
1462 |
-
General process for training, validating, and testing models using multi-model and feature kind approaches.
|
1463 |
-
|
1464 |
-
Args:
|
1465 |
-
train_samples (list): Training samples.
|
1466 |
-
val_samples (list): Validation samples.
|
1467 |
-
test_samples (list): Test samples.
|
1468 |
-
|
1469 |
-
Returns:
|
1470 |
-
None
|
1471 |
-
"""
|
1472 |
-
# Multi-model approach
|
1473 |
-
input_kind = MULTIMODEL
|
1474 |
-
write_to_file(OUTPUT_FILE, f"\nInput kind = {input_kind} \n")
|
1475 |
-
|
1476 |
-
# Train detector using multi-model with early stopping
|
1477 |
-
detector = train_by_transformer_with_multimodel_and_early_stop(train_samples, val_samples, input_kind)
|
1478 |
-
detector.save_model("./models/multi_model_detector")
|
1479 |
-
|
1480 |
-
# Evaluate on train set
|
1481 |
-
write_to_file(OUTPUT_FILE, f"EVALUATE ON TRAIN SET \n")
|
1482 |
-
test_by_transformer_with_multimodel(detector, train_samples, input_kind)
|
1483 |
-
|
1484 |
-
# Evaluate on validation set
|
1485 |
-
write_to_file(OUTPUT_FILE, f"EVALUATE ON VALIDATION SET \n")
|
1486 |
-
test_by_transformer_with_multimodel(detector, val_samples, input_kind)
|
1487 |
-
|
1488 |
-
# Evaluate on test set
|
1489 |
-
write_to_file(OUTPUT_FILE, f"EVALUATE ON TEST SET \n")
|
1490 |
-
test_by_transformer_with_multimodel(detector, test_samples, input_kind)
|
1491 |
-
|
1492 |
-
# Single from multi-model approach
|
1493 |
-
input_kind = SINGLE_FROM_MULTIMODEL
|
1494 |
-
write_to_file(OUTPUT_FILE, f"\nInput kind = {input_kind} \n")
|
1495 |
-
|
1496 |
-
# Train detector using single from multi-model with early stopping
|
1497 |
-
detector = train_by_transformer_with_multimodel_and_early_stop(train_samples, val_samples, input_kind)
|
1498 |
-
detector.save_model("./models/single_model_detector_1")
|
1499 |
-
|
1500 |
-
# Evaluate on train set
|
1501 |
-
write_to_file(OUTPUT_FILE, f"EVALUATE ON TRAIN SET \n")
|
1502 |
-
test_by_transformer_with_multimodel(detector, train_samples, input_kind)
|
1503 |
-
|
1504 |
-
# Evaluate on validation set
|
1505 |
-
write_to_file(OUTPUT_FILE, f"EVALUATE ON VALIDATION SET \n")
|
1506 |
-
test_by_transformer_with_multimodel(detector, val_samples, input_kind)
|
1507 |
-
|
1508 |
-
# Evaluate on test set
|
1509 |
-
write_to_file(OUTPUT_FILE, f"EVALUATE ON TEST SET \n")
|
1510 |
-
test_by_transformer_with_multimodel(detector, test_samples, input_kind)
|
1511 |
-
|
1512 |
-
# Feature kind approach
|
1513 |
-
sample_length = len(train_samples[0]["text"])
|
1514 |
-
if sample_length == 2: # Check if the sample length is 2, indicating BART feature kind
|
1515 |
-
feature_kind = BART
|
1516 |
-
write_to_file(OUTPUT_FILE, f"\nFeature kind = {feature_kind} \n")
|
1517 |
-
|
1518 |
-
# Train detector using feature kind
|
1519 |
-
detector = train_by_feature_kind(train_samples, feature_kind)
|
1520 |
-
|
1521 |
-
# Evaluate on train set
|
1522 |
-
write_to_file(OUTPUT_FILE, f"EVALUATE ON TRAIN SET \n")
|
1523 |
-
test_by_feature_kind(detector, train_samples, feature_kind)
|
1524 |
-
|
1525 |
-
# Evaluate on validation set
|
1526 |
-
write_to_file(OUTPUT_FILE, f"EVALUATE ON VALIDATION SET \n")
|
1527 |
-
test_by_feature_kind(detector, val_samples, feature_kind)
|
1528 |
-
|
1529 |
-
# Evaluate on test set
|
1530 |
-
write_to_file(OUTPUT_FILE, f"EVALUATE ON TEST SET \n")
|
1531 |
-
test_by_feature_kind(detector, test_samples, feature_kind)
|
1532 |
-
|
1533 |
-
|
1534 |
-
def process_multi_models_with_validation(multimodel_csv_file, train_indices, test_indices, num_samples):
|
1535 |
-
"""
|
1536 |
-
Processes multi-model data with validation, training, and testing.
|
1537 |
-
|
1538 |
-
Args:
|
1539 |
-
multimodel_csv_file (str): Path to the CSV file containing multi-model data.
|
1540 |
-
train_indices (list): Indices for the training data.
|
1541 |
-
test_indices (list): Indices for the testing data.
|
1542 |
-
num_samples (int): Number of samples to process.
|
1543 |
-
|
1544 |
-
Returns:
|
1545 |
-
None
|
1546 |
-
"""
|
1547 |
-
# Log the details of the process
|
1548 |
-
write_to_file(OUTPUT_FILE, f"PROCESSING FILE={multimodel_csv_file} \n")
|
1549 |
-
write_to_file(OUTPUT_FILE, f"EXPERIMENT WITH {MODEL_NAME} model \n")
|
1550 |
-
write_to_file(OUTPUT_FILE, f"NUMBER OF MAX EPOCHS WITH EARLY STOPPING = {NUMBER_OF_MAX_EPOCH_WITH_EARLY_STOPPING} \n")
|
1551 |
-
write_to_file(OUTPUT_FILE, f"PATIENCE = {PATIENCE} \n")
|
1552 |
-
write_to_file(OUTPUT_FILE, f"OPTIMIZED METRIC = {OPTIMIZED_METRIC} \n")
|
1553 |
-
write_to_file(OUTPUT_FILE, f"BATCH SIZE = {BATCH_SIZE} \n")
|
1554 |
-
write_to_file(OUTPUT_FILE, f"Number of samples = {num_samples} \n")
|
1555 |
-
|
1556 |
-
# Read multi-model data from the CSV file
|
1557 |
-
data = read_multimodel_data_from_csv(multimodel_csv_file)
|
1558 |
-
|
1559 |
-
# Limit data to the specified number of samples
|
1560 |
-
data = data[:num_samples]
|
1561 |
-
|
1562 |
-
# Distribute data into training, validation, and testing sets
|
1563 |
-
train_samples, val_samples, test_samples = distribute_data(data, train_indices, test_indices, TRAIN_RATIO, VAL_RATIO)
|
1564 |
-
|
1565 |
-
# Log the training and testing indices
|
1566 |
-
write_to_file(OUTPUT_FILE, f"Multimodel training with train indices {train_indices}, test with test indices {test_indices} \n")
|
1567 |
-
|
1568 |
-
# Process the multi-models for training, validation, and testing
|
1569 |
-
general_process_multimodels_train_val_test(train_samples, val_samples, test_samples)
|
1570 |
-
|
1571 |
-
|
1572 |
-
|
1573 |
-
|
1574 |
-
def split_train_val_test(data, train_ratio, val_ratio):
|
1575 |
-
"""
|
1576 |
-
Splits the dataset into training, validation, and test sets based on specified ratios.
|
1577 |
-
|
1578 |
-
Args:
|
1579 |
-
data (list): The dataset to be split.
|
1580 |
-
train_ratio (float): The ratio of the dataset to be used for training.
|
1581 |
-
val_ratio (float): The ratio of the dataset to be used for validation.
|
1582 |
-
|
1583 |
-
Returns:
|
1584 |
-
tuple: A tuple containing three lists - (train_data, val_data, test_data).
|
1585 |
-
"""
|
1586 |
-
# Calculate the number of samples for the training set
|
1587 |
-
num_train_samples = int(len(data) * train_ratio)
|
1588 |
-
|
1589 |
-
# Calculate the number of samples for the validation set
|
1590 |
-
num_val_samples = int(len(data) * val_ratio)
|
1591 |
-
|
1592 |
-
# Split the data into training, validation, and test sets
|
1593 |
-
train_data = data[:num_train_samples]
|
1594 |
-
val_data = data[num_train_samples:(num_train_samples + num_val_samples)]
|
1595 |
-
test_data = data[(num_train_samples + num_val_samples):]
|
1596 |
-
|
1597 |
-
return train_data, val_data, test_data
|
1598 |
-
|
1599 |
-
|
1600 |
-
def main():
|
1601 |
-
"""
|
1602 |
-
Main function to handle argument parsing and execute the sequence of operations
|
1603 |
-
including data generation and processing with multiple models.
|
1604 |
-
"""
|
1605 |
-
parser = argparse.ArgumentParser(description='SimLLM.')
|
1606 |
-
|
1607 |
-
# Argument for specifying the list of large language models
|
1608 |
-
parser.add_argument('--LLMs', nargs="+", default=[CHATGPT],#, "Yi", "OpenChat"],
|
1609 |
-
help='List of large language models')
|
1610 |
-
|
1611 |
-
# Argument for specifying the list of training indexes
|
1612 |
-
parser.add_argument('--train_indexes', type=int, default=[0,1,2], nargs="+",
|
1613 |
-
help='List of training indexes')
|
1614 |
-
|
1615 |
-
# Argument for specifying the list of testing indexes
|
1616 |
-
parser.add_argument('--test_indexes', type=int, default=[0], nargs="+",
|
1617 |
-
help='List of testing indexes')
|
1618 |
-
|
1619 |
-
# Argument for specifying the number of samples
|
1620 |
-
parser.add_argument('--num_samples', type=int, default=5000,
|
1621 |
-
help='Number of samples')
|
1622 |
-
|
1623 |
-
# Argument for multimodel_csv_file
|
1624 |
-
parser.add_argument('--multimodel_csv_file', type=str, default="data/ChatGPT_Nous_Hermes_2_Yi_34B_openchat_3_5_1210_with_best_similarity.csv",
|
1625 |
-
help='multimodel_csv_file')
|
1626 |
-
|
1627 |
-
# Parse the command-line arguments
|
1628 |
-
args = parser.parse_args()
|
1629 |
-
|
1630 |
-
if args.multimodel_csv_file == "":
|
1631 |
-
# Static dataset parameters
|
1632 |
-
dataset_name = "xsum"
|
1633 |
-
column_name = "document"
|
1634 |
-
num_samples = args.num_samples
|
1635 |
-
output_file = "data/test.csv"
|
1636 |
-
|
1637 |
-
# Generate human data with shuffle
|
1638 |
-
# generate_human_with_shuffle(dataset_name, column_name, num_samples, output_file)
|
1639 |
-
|
1640 |
-
# Existing data parameters
|
1641 |
-
existing_data_file = output_file
|
1642 |
-
existing_kinds = []
|
1643 |
-
|
1644 |
-
# New kinds of models to generate data with
|
1645 |
-
new_kinds = args.LLMs
|
1646 |
-
|
1647 |
-
# Generate new data with best similarity
|
1648 |
-
generate_new_data_with_best_similarity(existing_data_file, existing_kinds, new_kinds)
|
1649 |
-
|
1650 |
-
# Generate a filename for the multimodel CSV file
|
1651 |
-
multimodel_csv_file = generate_file_name(existing_data_file, existing_kinds, new_kinds)
|
1652 |
-
|
1653 |
-
else:
|
1654 |
-
multimodel_csv_file = args.multimodel_csv_file
|
1655 |
-
|
1656 |
-
# Number of samples to process (-1 means process all samples)
|
1657 |
-
num_samples_to_process = -1
|
1658 |
-
|
1659 |
-
# Training and testing indexes from arguments
|
1660 |
-
training_indexes = args.train_indexes
|
1661 |
-
testing_indexes = args.test_indexes
|
1662 |
-
|
1663 |
-
# Process multiple models with validation
|
1664 |
-
process_multi_models_with_validation(multimodel_csv_file, training_indexes, testing_indexes, num_samples_to_process)
|
1665 |
-
|
1666 |
-
if __name__ == "__main__":
|
1667 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/texts/SimLLM/bart_score.py
DELETED
@@ -1,136 +0,0 @@
|
|
1 |
-
# %%
|
2 |
-
import traceback
|
3 |
-
from typing import List
|
4 |
-
|
5 |
-
import numpy as np
|
6 |
-
import torch
|
7 |
-
import torch.nn as nn
|
8 |
-
from transformers import (
|
9 |
-
BartForConditionalGeneration,
|
10 |
-
BartTokenizer,
|
11 |
-
)
|
12 |
-
|
13 |
-
|
14 |
-
class BARTScorer:
|
15 |
-
def __init__(
|
16 |
-
self,
|
17 |
-
device="cuda:0",
|
18 |
-
max_length=1024,
|
19 |
-
checkpoint="facebook/bart-large-cnn",
|
20 |
-
):
|
21 |
-
# Set up model
|
22 |
-
self.device = device
|
23 |
-
self.max_length = max_length
|
24 |
-
self.tokenizer = BartTokenizer.from_pretrained(checkpoint)
|
25 |
-
self.model = BartForConditionalGeneration.from_pretrained(checkpoint)
|
26 |
-
self.model.eval()
|
27 |
-
self.model.to(device)
|
28 |
-
|
29 |
-
# Set up loss
|
30 |
-
self.loss_fct = nn.NLLLoss(
|
31 |
-
reduction="none",
|
32 |
-
ignore_index=self.model.config.pad_token_id,
|
33 |
-
)
|
34 |
-
self.lsm = nn.LogSoftmax(dim=1)
|
35 |
-
|
36 |
-
def load(self, path=None):
|
37 |
-
"""Load model from paraphrase finetuning"""
|
38 |
-
if path is None:
|
39 |
-
path = "./bart.pth"
|
40 |
-
|
41 |
-
self.model.load_state_dict(torch.load(path, map_location=self.device))
|
42 |
-
|
43 |
-
def score(self, srcs, tgts, batch_size=16):
|
44 |
-
"""Score a batch of examples"""
|
45 |
-
score_list = []
|
46 |
-
for i in range(0, len(srcs), batch_size):
|
47 |
-
src_list = srcs[i : i + batch_size]
|
48 |
-
tgt_list = tgts[i : i + batch_size]
|
49 |
-
try:
|
50 |
-
with torch.no_grad():
|
51 |
-
encoded_src = self.tokenizer(
|
52 |
-
src_list,
|
53 |
-
max_length=self.max_length,
|
54 |
-
truncation=True,
|
55 |
-
padding=True,
|
56 |
-
return_tensors="pt",
|
57 |
-
)
|
58 |
-
encoded_tgt = self.tokenizer(
|
59 |
-
tgt_list,
|
60 |
-
max_length=self.max_length,
|
61 |
-
truncation=True,
|
62 |
-
padding=True,
|
63 |
-
return_tensors="pt",
|
64 |
-
)
|
65 |
-
src_tokens = encoded_src["input_ids"].to(self.device)
|
66 |
-
src_mask = encoded_src["attention_mask"].to(self.device)
|
67 |
-
|
68 |
-
tgt_tokens = encoded_tgt["input_ids"].to(self.device)
|
69 |
-
tgt_mask = encoded_tgt["attention_mask"]
|
70 |
-
tgt_len = tgt_mask.sum(dim=1).to(self.device)
|
71 |
-
|
72 |
-
output = self.model(
|
73 |
-
input_ids=src_tokens,
|
74 |
-
attention_mask=src_mask,
|
75 |
-
labels=tgt_tokens,
|
76 |
-
)
|
77 |
-
logits = output.logits.view(
|
78 |
-
-1,
|
79 |
-
self.model.config.vocab_size,
|
80 |
-
)
|
81 |
-
loss = self.loss_fct(self.lsm(logits), tgt_tokens.view(-1))
|
82 |
-
loss = loss.view(tgt_tokens.shape[0], -1)
|
83 |
-
loss = loss.sum(dim=1) / tgt_len
|
84 |
-
curr_score_list = [-x.item() for x in loss]
|
85 |
-
score_list += curr_score_list
|
86 |
-
|
87 |
-
except RuntimeError:
|
88 |
-
traceback.print_exc()
|
89 |
-
print(f"source: {src_list}")
|
90 |
-
print(f"target: {tgt_list}")
|
91 |
-
exit(0)
|
92 |
-
return score_list
|
93 |
-
|
94 |
-
def multi_ref_score(
|
95 |
-
self,
|
96 |
-
srcs,
|
97 |
-
tgts: List[List[str]],
|
98 |
-
agg="mean",
|
99 |
-
batch_size=4,
|
100 |
-
):
|
101 |
-
# Assert we have the same number of references
|
102 |
-
ref_nums = [len(x) for x in tgts]
|
103 |
-
if len(set(ref_nums)) > 1:
|
104 |
-
raise Exception(
|
105 |
-
"You have different number of references per test sample.",
|
106 |
-
)
|
107 |
-
|
108 |
-
ref_num = len(tgts[0])
|
109 |
-
score_matrix = []
|
110 |
-
for i in range(ref_num):
|
111 |
-
curr_tgts = [x[i] for x in tgts]
|
112 |
-
scores = self.score(srcs, curr_tgts, batch_size)
|
113 |
-
score_matrix.append(scores)
|
114 |
-
if agg == "mean":
|
115 |
-
score_list = np.mean(score_matrix, axis=0)
|
116 |
-
elif agg == "max":
|
117 |
-
score_list = np.max(score_matrix, axis=0)
|
118 |
-
else:
|
119 |
-
raise NotImplementedError
|
120 |
-
return list(score_list)
|
121 |
-
|
122 |
-
def test(self, batch_size=3):
|
123 |
-
"""Test"""
|
124 |
-
src_list = [
|
125 |
-
"This is a very good idea. Although simple, but very insightful.",
|
126 |
-
"Can I take a look?",
|
127 |
-
"Do not trust him, he is a liar.",
|
128 |
-
]
|
129 |
-
|
130 |
-
tgt_list = [
|
131 |
-
"That's stupid.",
|
132 |
-
"What's the problem?",
|
133 |
-
"He is trustworthy.",
|
134 |
-
]
|
135 |
-
|
136 |
-
print(self.score(src_list, tgt_list, batch_size))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|