forked from qinyiwei/longCOT-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdpo.py
242 lines (171 loc) · 7.88 KB
/
dpo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import streamlit as st
import pandas as pd
import json
import re
from utils import *
import tiktoken
KEY_WORDS = ["verify", "check", "identify", "summarize", "note that", "notice that", "recall that", "wait"]
enc = tiktoken.encoding_for_model("gpt-4o")
correctness_map = {
"✅": True,
"❌": False,
"None": "None"
}
def calculate_overall_accuracy(df):
correct_count = df['result'].sum()
overall_count = len(df)
return correct_count / overall_count if overall_count > 0 else 0
def calculate_token(df):
total_token_count = 0
total_problem_count = 0
for _, row in df.iterrows():
text = row['response']
total_token_count += len(enc.encode(text))
total_problem_count += 1
st.subheader(f"Average Token:{total_token_count/total_problem_count}")
def statistics_key_words(df):
key_word_count = {}
for key_word in KEY_WORDS:
key_word_count[key_word] = 0
for key_word in KEY_WORDS:
for _, row in df.iterrows():
if key_word in row['response'].lower():
if key_word not in key_word_count:
key_word_count[key_word] = 0
key_word_count[key_word] += 1
fig, ax = plt.subplots(figsize=(10, 6))
bars = ax.bar(key_word_count.keys(), key_word_count.values())
ax.bar(key_word_count.keys(), key_word_count.values())
ax.set_xlabel('Key Words')
ax.set_ylabel('Count')
ax.set_title('Keyword Occurrences')
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
for bar in bars:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2., height,
f'{int(height)}', ha='center', va='bottom')
st.pyplot(fig)
def display_baseline(result_dir):
accuracy_list = []
for file in os.listdir(result_dir):
if file.endswith('.jsonl'):
file_path = os.path.join(result_dir, file)
result_df = load_data(file_path)
accuracy = calculate_overall_accuracy(result_df)
accuracy_list.append((os.path.splitext(file)[0], accuracy))
accuracy_df = pd.DataFrame(accuracy_list, columns=['File Name', 'Accuracy']).sort_values(by='Accuracy').reset_index(drop=True)
st.dataframe(accuracy_df)
def get_common_rows(df1, df2):
common_idx = pd.merge(df1[['idx']], df2[['idx']], on='idx').sort_values(by='idx')
new_df1 = df1[df1['idx'].isin(common_idx['idx'])].set_index('idx')
new_df2 = df2[df2['idx'].isin(common_idx['idx'])].set_index('idx')
new_df1 = new_df1.loc[common_idx['idx']].reset_index()
new_df2 = new_df2.loc[common_idx['idx']].reset_index()
return new_df1, new_df2
class Filter:
def filter_correct_problems_1(df):
correctness = st.selectbox("Select correctness", ["None", "✅", "❌"])
if correctness == "None":
return df
matching_indices = []
for idx in df.index:
if df.at[idx, 'result'] == correctness_map[correctness]:
matching_indices.append(idx)
filtered_df = df.loc[matching_indices]
return filtered_df
def filter_correct_problems_2(df1, df2):
left, right = st.columns(2)
with left:
correctness1 = st.selectbox("Select correctness for the first file", ["None", "✅", "❌"])
with right:
correctness2 = st.selectbox("Select correctness for the second file", ["None", "✅", "❌"])
matching_indices = []
for idx in df1.index:
assert df1.at[idx, 'id'] == df2.at[idx, 'id']
result1 = df1.at[idx, 'result']
result2 = df2.at[idx, 'result']
if ((correctness1 == "None" or result1 == correctness_map[correctness1]) and
(correctness2 == "None" or result2 == correctness_map[correctness2])):
matching_indices.append(idx)
filtered_df1 = df1.loc[matching_indices]
filtered_df2 = df2.loc[matching_indices]
return filtered_df1, filtered_df2
def visualize_dpo():
# Load the data based on user choice
file_type = st.sidebar.selectbox("Choose File Type", ["Results"])
if file_type == "Results":
folder_path = './data/dpo/results'
show_baseline = st.checkbox("Show Baseline")
if show_baseline:
display_baseline(folder_path)
file_choice = st.multiselect("Choose 1 or 2 Files", sorted([os.path.splitext(file)[0] for file in os.listdir(folder_path) if file.endswith('.jsonl')]), max_selections=2)
st.subheader('Filtering ("None" means no filtering)')
if len(file_choice) == 1:
df = load_data(os.path.join(folder_path, f'{file_choice[0]}.jsonl'))
count_total = len(df)
df = Filter.filter_correct_problems_1(df)
elif len(file_choice) == 2:
df = load_data(os.path.join(folder_path, f'{file_choice[0]}.jsonl'))
count_total = len(df)
df_compare = load_data(os.path.join(folder_path, f'{file_choice[1]}.jsonl'))
df, df_compare = Filter.filter_correct_problems_2(df, df_compare)
else:
st.warning("Please select at least 1 file to continue.")
st.stop()
count_after_filter = len(df)
if df.empty:
st.warning("No data available to display.")
st.stop()
if 'selected_example' not in st.session_state:
st.session_state.selected_example = 1
examples = []
for _, row in df.iterrows():
try:
examples.append(row["idx"])
except:
examples.append(row["id"])
st.subheader(f"Select Example **(Count: {count_after_filter}/{count_total})**")
selected_example = st.selectbox(f"Select Example", examples)
st.session_state.selected_example = selected_example
if file_type == "Synthetic longCoT":
row = df[df['idx'] == st.session_state.selected_example].iloc[0]
if len(file_choice) == 2:
row_compare = df_compare[df_compare['idx'] == st.session_state.selected_example].iloc[0]
elif file_type == "Results":
row = df[df['id'] == st.session_state.selected_example].iloc[0]
if len(file_choice) == 2:
row_compare = df_compare[df_compare['id'] == st.session_state.selected_example].iloc[0]
def show_statistics(df):
st.subheader("Statistics")
calculate_token(df)
statistics_key_words(df)
if len(file_choice) == 1:
show_statistics(df)
elif len(file_choice) == 2:
left, right = st.columns(2)
with left:
show_statistics(df)
with right:
show_statistics(df_compare)
st.header(f"Idx: {st.session_state.selected_example}")
st.subheader("Question")
st.markdown(row['question'].replace("\n", "<br>"), unsafe_allow_html=True)
if file_type == "Results":
def show_pred_result(row, model_name):
if row['result']:
st.subheader(f"Pred of {model_name} ✅")
else:
st.subheader(f"Pred of {model_name} ❌")
st.subheader(f"Token: {len(enc.encode(row['response']))}")
response = row['response'].replace("\n", "<br>")
st.markdown(highlight_key_words(response, KEY_WORDS), unsafe_allow_html=True)
st.subheader("Model's Prediction")
if len(file_choice) == 2:
left, right = st.columns(2)
with left.container(height=800):
show_pred_result(row, file_choice[0])
with right.container(height=800):
show_pred_result(row_compare, file_choice[1])
elif len(file_choice) == 1:
show_pred_result(row, file_choice[0])