-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsprout_problem_model.py
More file actions
366 lines (320 loc) · 15.7 KB
/
sprout_problem_model.py
File metadata and controls
366 lines (320 loc) · 15.7 KB
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import pickle
import random
import numpy as np
import pandas as pd
from scipy.stats import norm
from tqdm import tqdm
from sentence_transformers import SentenceTransformer
import json
import os
import sprout_loader
from Arm import Arm
from ProblemModel import ProblemModel
from Reward import Reward
"""
This file contains code for the SPROUT problem model. The SPROUTProblemModel class has functions to
provide available arms, play the arms, calculate regret, and etc.
"""
saved_df_name = 'sprout_simulation_df.pkl' # file where the saved simulation-ready dataframe will be saved
embeddings_df_name = 'sprout_embeddings_df.pkl' # file where the embeddings will be saved
# Set up cache directory in the virtual environment
cache_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'model_cache')
os.makedirs(cache_dir, exist_ok=True)
def log_progress(current, total, prefix=""):
"""Log progress for every 1% completed"""
percentage = (current / total) * 100
# Log every time we've completed another 1% of total, regardless of whether total is a multiple of 100
if total > 0 and current % max(1, total // 100) == 0:
print(f"{prefix}Progress: {percentage:.1f}% ({current}/{total})")
class SPROUTProblemModel(ProblemModel):
def __init__(self, num_rounds, budget, use_saved, embedding_config=None):
self.num_rounds = num_rounds
self.embedding_config = embedding_config or {
'model_name': 'all-MiniLM-L6-v2',
'dimensions': 384,
'suffix': ''
}
if not use_saved:
self.df = self.initialize_df()
self.df.set_index('time', inplace=True)
with open(saved_df_name, 'wb') as output:
pickle.dump(self.df, output, pickle.HIGHEST_PROTOCOL)
else:
with open(saved_df_name, 'rb') as input_file:
self.df = pickle.load(input_file)
def get_size(self):
"""
Calculate the total number of arms across all time steps.
Returns:
int: Total number of arms in the problem model
"""
return len(self.df)
def get_available_arms(self, t):
# Construct a list of Arm objects
arm_list = []
for _, row in self.df.loc[t].iterrows():
arm_list.append(Arm(len(arm_list), row['context'], row['true_mean']))
return arm_list
def get_regret(self, t, budget, slate):
df = self.df.loc[t]
# TODO incorporate budget
# Get all possible rewards for this timestep
true_all_rewards = [Reward(Arm(i, row['context'], row['true_mean']), row['true_mean'])
for i, (_, row) in enumerate(df.iterrows())]
true_highest_possible_reward = self.get_total_reward(true_all_rewards)
# Get rewards for selected slate
true_slate_rewards = [Reward(arm, df.iloc[arm.unique_id]['true_mean']) for arm in slate]
true_highest_slate_reward = self.get_total_reward(true_slate_rewards)
return true_highest_possible_reward - true_highest_slate_reward
def get_total_reward(self, rewards):
# TODO: try other reward models
max_reward = max(reward.quality for reward in rewards)
return max_reward
def play_arms(self, t, slate):
reward_list = []
df = self.df.loc[t]
for arm in slate:
# TODO: use LLM as judge to observe quality
quality = df.iloc[arm.unique_id]['true_mean']
reward_list.append(Reward(arm, quality))
return reward_list
def oracle(self, K, g_list):
g_list = np.array(g_list)
# Add a small random tie-breaker
noise = np.random.rand(len(g_list)) * 1e-8
randomized_g_list = g_list + noise
return np.argsort(randomized_g_list)[-K:]
def normalize_embedding(self, embedding):
"""
Normalize an embedding vector to unit length.
Args:
embedding: numpy array of embedding vector
Returns:
Normalized embedding vector
"""
norm = np.linalg.norm(embedding)
if norm == 0:
return embedding
return embedding / norm
def combine_embeddings(self, task_embedding, agent_embedding, operation='cosine'):
"""
Combine task and agent embeddings using various meaningful operations.
Args:
task_embedding: numpy array of task embedding
agent_embedding: numpy array of agent card embedding
operation: One of ['cosine', 'concatenate', 'hadamard', 'sum', 'subtract']
Returns:
Combined embedding vector
"""
# Ensure embeddings are normalized
task_embedding = self.normalize_embedding(task_embedding)
agent_embedding = self.normalize_embedding(agent_embedding)
if operation == 'cosine':
# Cosine similarity between task and agent
return np.dot(task_embedding, agent_embedding)
elif operation == 'concatenate':
# Concatenate the embeddings to preserve all information
return np.concatenate([task_embedding, agent_embedding])
elif operation == 'hadamard':
# Element-wise multiplication (Hadamard product)
return task_embedding * agent_embedding
elif operation == 'sum':
# Sum of embeddings
return task_embedding + agent_embedding
elif operation == 'subtract':
# Difference between task and agent embeddings
return task_embedding - agent_embedding
else:
raise ValueError("Operation must be one of ['cosine', 'concatenate', 'hadamard', 'sum', 'subtract']")
def initialize_df(self):
agentKeys=["aws-claude-3-5-sonnet-v1",
"aws-titan-text-premier-v1",
"openai-gpt-4o",
"openai-gpt-4o-mini",
"wxai-granite-3-2b-instruct-8k-max-tokens",
"wxai-granite-3-8b-instruct-8k-max-tokens",
"wxai-llama-3-1-70b-instruct",
"wxai-llama-3-1-8b-instruct",
"wxai-llama-3-2-1b-instruct",
"wxai-llama-3-2-3b-instruct",
"wxai-llama-3-3-70b-instruct",
"wxai-llama-3-405b-instruct",
"wxai-mixtral-8x7b-instruct-v01"]
# Try to load the saved embeddings first
try:
print("Loading saved embeddings...")
with open(embeddings_df_name, 'rb') as f:
df = pickle.load(f)
# Truncate embeddings here
task_embedding_col = f'task_embedding'
if task_embedding_col in df.columns:
# Create embeddings for prompts by truncating the dimensions of existing embeddings
print("Chopping existing embeddings...")
# Initialize the sentence transformer model for computing agent embeddings
print(f"Loading embedding model: {self.embedding_config['model_name']}...")
model = SentenceTransformer(
self.embedding_config['model_name'],
device='cpu',
trust_remote_code=True,
truncate_dim=self.embedding_config['dimensions'],
cache_folder=cache_dir
)
# Truncate task embeddings
df[task_embedding_col + self.embedding_config["suffix"]] = df[task_embedding_col].apply(
lambda x: x[:self.embedding_config["dimensions"]]
)
for key in agentKeys:
print(f"Creating task contexts for {key}...")
# Load the model card JSON file for this agent
with open(f'model_cards/{key}.json', 'r') as f:
agent_card = json.load(f)
# Convert JSON to string before encoding
agent_card_str = json.dumps(agent_card)
# Compute and truncate agent embeddings
agent_embedding = model.encode(
agent_card_str,
convert_to_tensor=False,
normalize_embeddings=True,
show_progress_bar=False
)
df[key + '_task_context'] = df.apply(
lambda row: self.combine_embeddings(
row[task_embedding_col + self.embedding_config["suffix"]],
agent_embedding,
operation='concatenate'
),
axis=1
)
# Save the dataframe with new embeddings
print("Saving embeddings...")
with open(embeddings_df_name, 'wb') as f:
pickle.dump(df, f)
# Check if we need to generate new embeddings
task_embedding_col = f'task_embedding{self.embedding_config["suffix"]}'
if task_embedding_col not in df.columns:
print(f"Required embedding column {task_embedding_col} not found. Adding new embeddings...")
# Initialize the sentence transformer model
print(f"Loading embedding model: {self.embedding_config['model_name']}...")
model = SentenceTransformer(
self.embedding_config['model_name'],
device='cpu',
trust_remote_code=True,
truncate_dim=self.embedding_config['dimensions'],
cache_folder=cache_dir
)
# Create embeddings for prompts
print("Creating new embeddings...")
df[task_embedding_col] = df["prompt"].apply(
lambda x, idx=df.index.get_loc(df["prompt"].name): (
log_progress(idx + 1, total_prompts, "Prompts: "),
model.encode(
x,
convert_to_tensor=False,
normalize_embeddings=True,
show_progress_bar=False
)
)[1]
)
for key in agentKeys:
print(f"Creating task contexts for {key}...")
# Load the model card JSON file for this agent
with open(f'model_cards/{key}.json', 'r') as f:
agent_card = json.load(f)
# Convert JSON to string before encoding
agent_card_str = json.dumps(agent_card)
agent_embedding = model.encode(
agent_card_str,
convert_to_tensor=False,
normalize_embeddings=True,
show_progress_bar=False
)
df[key + '_task_context'] = df.apply(
lambda row: self.combine_embeddings(
row[task_embedding_col],
agent_embedding,
operation='concatenate'
),
axis=1
)
# Save the dataframe with new embeddings
print("Saving embeddings...")
with open(embeddings_df_name, 'wb') as f:
pickle.dump(df, f)
except FileNotFoundError:
print("No saved embeddings found. Computing new embeddings...")
df = sprout_loader.load_sprout_data()
print("Dataset columns:", df.columns.tolist())
# Initialize the sentence transformer model
print(f"Loading embedding model: {self.embedding_config['model_name']}...")
model = SentenceTransformer(
self.embedding_config['model_name'],
device='cpu',
trust_remote_code=True,
truncate_dim=self.embedding_config['dimensions'],
cache_folder=cache_dir
)
# Create embeddings for prompts
print("Creating embeddings...")
task_embedding_col = f'task_embedding{self.embedding_config["suffix"]}'
total_prompts = len(df)
df[task_embedding_col] = df["prompt"].apply(
lambda x, idx=df.index.get_loc(df["prompt"].name): (
log_progress(idx + 1, total_prompts, "Prompts: "),
model.encode(
x,
convert_to_tensor=False,
normalize_embeddings=True,
show_progress_bar=False
)
)[1]
)
for key in agentKeys:
print("Creating task contexts...")
# Load the model card JSON file for this agent
with open(f'model_cards/{key}.json', 'r') as f:
agent_card = json.load(f)
# Convert JSON to string before encoding
agent_card_str = json.dumps(agent_card)
agent_embedding = model.encode(
agent_card_str,
convert_to_tensor=False,
normalize_embeddings=True,
show_progress_bar=False
)
df[key + '_task_context'] = df.apply(
lambda row: self.combine_embeddings(
row[task_embedding_col],
agent_embedding,
operation='concatenate'
),
axis=1
)
# Create new columns for each agent
df[key + '_score'] = df[key].apply(lambda x: float(x['score']) if isinstance(x, dict) else None)
df[key + '_num_input_tokens'] = df[key].apply(lambda x: int(x['num_input_tokens']) if isinstance(x, dict) else None)
df[key + '_num_output_tokens'] = df[key].apply(lambda x: int(x['num_output_tokens']) if isinstance(x, dict) else None)
df[key + '_judge_response'] = df[key].apply(lambda x: x.get('judge_response', None) if isinstance(x, dict) else None)
df[key + '_response'] = df[key].apply(lambda x: x.get('response', None) if isinstance(x, dict) else None)
df['time'] = range(1, len(df) + 1)
print(df.head(2))
print(df.describe())
# Save the dataframe with embeddings
print("Saving embeddings...")
with open(embeddings_df_name, 'wb') as f:
pickle.dump(df, f)
# Create the final dataframe for the problem model
print("Creating final dataframe...")
row_list = []
num_rounds = min(self.num_rounds, len(df))
total_rows = num_rounds * len(agentKeys)
current_row = 0
for time in tqdm(range(1, num_rounds + 1)):
num_available_arms = len(agentKeys)
for i in range(num_available_arms):
available_agent = agentKeys[i]
context = df.loc[time, available_agent + '_task_context']
true_mean = df.loc[time, available_agent + '_score']
row_list.append((time, context, true_mean))
current_row += 1
log_progress(current_row, total_rows, "Final dataframe: ")
return pd.DataFrame(row_list, columns=['time', 'context', 'true_mean'])