forked from nwayt001/atari-gpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_experiments.py
316 lines (224 loc) · 11 KB
/
run_experiments.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
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
import gymnasium as gym
import time
import json
from llms import Agent
import cv2
import csv
import os
import sys
import pickle
from gymnasium.wrappers import RecordVideo, OrderEnforcing
import numpy as np
# Custom wrapper to prevent video closing on reset
class ContinuousRecordVideo(RecordVideo):
def step(self, action):
observation, reward, terminated, truncated, info = self.env.step(action)
self.video_recorder.capture_frame()
return observation, reward, terminated, truncated, info
def reset(self, **kwargs):
observation, info = self.env.reset(**kwargs)
if self.video_recorder:
self.video_recorder.capture_frame()
return observation, info
class run():
def __init__(self, env_name, prompt, model):
self.model_name = model
self.rewards = 0
self.cum_rewards = []
self.action_list = []
self.header = ["actions", "cumulative_rewards"]
self.MODELS = {"OpenAI": ["gpt-4-turbo", "gpt-4o", "gpt-3.5-turbo"],
"Anthropic": ["claude-3-opus-20240229", "claude-3-sonnet-20240229", "claude-3-haiku-20240307", "claude-3.5-sonnet", "max-tokens-3-5-sonnet-2024-07-15"],
"Google": ["gemini-1.5-pro-latest", "gemini-pro", "gemini-pro-vision", "gemini-1.5-flash-latest"],
"Meta": ["llama3-70b-8192", "llama3-8b-8192"]
}
self.states = []
self.steps_taken = 0
# System prompt
self.sys_prompt = prompt
self.env_name = env_name
# Get rid of ALE/ for creating folder
if "ALE/" in env_name:
self.temp_env_name = env_name[4:]
else:
self.temp_env_name = env_name
if self.temp_env_name == 'Frogger':
self.pause = 130
self.buffer_pause = 134
else:
self.pause = 15
self.buffer_pause = 19
# Total number of timesteps
self.num_timesteps = 1000
# Create new experiment folders path with model name
self.new_dir = "./experiments/" + self.temp_env_name[:-3] + '_'+ model +'/'
# Create folders if they do not exist
os.makedirs(os.path.dirname(self.new_dir), exist_ok=True)
# Check if the environment state is saved
if os.path.exists(self.new_dir + 'env_' + self.temp_env_name[:-3]+ '_state.pkl'):
print('\n\nEnvironment Results Already Exist, Going to Next Environment...\n\n')
return
# Create Environment
temp_env = gym.make(env_name, render_mode="rgb_array")
# Apply the OrderEnforcer wrapper
temp_env = OrderEnforcing(temp_env, disable_render_order_enforcing=True)
# Reset the environment before any rendering
temp_env.reset()
# Record video
self.env = ContinuousRecordVideo(env=temp_env, video_folder=self.new_dir, name_prefix=self.temp_env_name[:-3]+"_rollout")
if self.model_name == 'rand':
self.rand_rollout()
elif self.model_name == 'gpt4':
self.model = Agent(model_name=self.MODELS["OpenAI"][0], model = self.model_name, system_message=self.sys_prompt, env=self.env)
elif self.model_name == 'gpt4o':
self.model = Agent(model_name=self.MODELS["OpenAI"][1], model = self.model_name, system_message=self.sys_prompt, env=self.env)
elif self.model_name == 'gemini':
self.model = Agent(model_name=self.MODELS["Google"][3], model = self.model_name, system_message=self.sys_prompt, env=self.env)
elif self.model_name == 'claude':
self.model = Agent(model_name=self.MODELS["Anthropic"][2], model = self.model_name, system_message=self.sys_prompt, env=self.env)
if self.model_name != 'rand':
self.model_rollout()
with open(self.new_dir + 'actions_rewards.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(self.header)
for action, cum_reward in zip(self.action_list, self.cum_rewards):
writer.writerow([action, cum_reward])
def save_states(self, rewards, action):
# Save the environment's
state = self.env.ale.cloneState()
# Save the environment's random state
random_state = self.env.np_random if hasattr(self.env, 'np_random') else self.env.unwrapped.np_random
self.states.append((state, random_state, rewards, self.steps_taken, action))
# Save the state to pkl file
with open(self.new_dir + 'env_' + self.temp_env_name[:-3]+ '_state.pkl', 'wb') as f:
pickle.dump(self.states, f)
def rand_rollout(self):
# Start the recorder
self.env.start_video_recorder()
observation, info = self.env.reset()
# Save the initial state
self.save_states(self.rewards, 0)
for n in range(self.num_timesteps-self.steps_taken):
observation = cv2.resize(observation, (512, 512))
if n < self.pause:
action = 0
self.action_list.append(action)
observation, reward, terminated, truncated, info = self.env.step(action)
# Save the state once the action has been performed
self.save_states(self.rewards, action)
self.rewards += reward
self.cum_rewards.append(self.rewards)
elif n % 2 == 1:
# image buffer
action = self.env.action_space.sample()
self.action_list.append(action)
observation, reward, terminated, truncated, info = self.env.step(action)
# Save the state once the action has been performed
self.save_states(self.rewards, action)
self.rewards += reward
self.cum_rewards.append(self.rewards)
if terminated or truncated:
observation, info = self.env.reset()
else:
action = 0
self.action_list.append(action)
observation, reward, terminated, truncated, info = self.env.step(action)
self.env.render()
# Save the state once the action has been performed
self.save_states(self.rewards, action)
self.rewards += reward
self.cum_rewards.append(self.rewards)
if terminated or truncated:
observation, info = self.env.reset()
self.steps_taken += 1
print('The reward for ' + self.env_name + ' is: ' + str(self.rewards))
# Close the environment recorder
self.env.close_video_recorder()
# Close the environment
self.env.close()
def model_rollout(self):
usr_msg1 = 'What should I do? Provide output as a json structured as {reasoning: reasoning for actions and why to choose an action, action: The environment action which would provide the best next state}'
# Start the recorder
self.env.start_video_recorder()
observation, info = self.env.reset()
# Save the initial state
self.save_states(self.rewards, 0)
for n in range(self.num_timesteps-self.steps_taken):
# resize cv2 512x512
observation = cv2.resize(observation, (512, 512))
if n < self.pause:
# Perform no-op action
action = 0
# Save action
self.action_list.append(action)
# Perform Action
observation, reward, terminated, truncated, info = self.env.step(action)
self.env.render()
# Sum reward and save
self.rewards += reward
self.cum_rewards.append(self.rewards)
# Check done condition
if terminated or truncated:
observation, info = self.env.reset()
elif n % 2 == 1:
# Create buffer of 4 frames
if n < self.buffer_pause:
# Add frame and reason
self.model.add_user_message(observation, usr_msg1)
# Get response from model with action
action, full_response = self.model.generate_response(self.new_dir)
# Add models reasoning to context
self.model.add_assistant_message()
# Save action
self.action_list.append(action)
# Perform Action
observation, reward, terminated, truncated, info = self.env.step(action)
self.env.render()
# Sum reward and save
self.rewards += reward
self.cum_rewards.append(self.rewards)
# Check done condition
if terminated or truncated:
observation, info = self.env.reset()
else:
# Add frame and reason
self.model.add_user_message(observation, usr_msg1)
# Have model reason from the given image
action, full_response = self.model.generate_response(self.new_dir)
# Add models reasoning to context
self.model.add_assistant_message()
# Save action
self.action_list.append(action)
# Perform Action
observation, reward, terminated, truncated, info = self.env.step(action)
self.env.render()
# Sum reward and save
self.rewards += reward
self.cum_rewards.append(self.rewards)
# Context buffer of only the 4 most recent frames
# delete oldest context
self.model.delete_messages()
# Check done condition
if terminated or truncated:
observation, info = self.env.reset()
else:
# Perform no-op action
action = 0
# Save action
self.action_list.append(action)
# Perform Action
observation, reward, terminated, truncated, info = self.env.step(action)
self.env.render()
# Sum reward and save
self.rewards += reward
self.cum_rewards.append(self.rewards)
# Check done condition
if terminated or truncated:
observation, info = self.env.reset()
# Save the state once the action has been performed
self.save_states(self.rewards, action)
self.steps_taken += 1
# Close the environment recorder
self.env.close_video_recorder()
# Close the environment
self.env.close()