Repository navigation
Expand file tree
/
Copy pathplot_and_eval.py
More file actions
1806 lines (1516 loc) · 94.6 KB
/
Copy pathplot_and_eval.py
File metadata and controls
1806 lines (1516 loc) · 94.6 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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Set JAX memory allocation to grow as needed
import os
os.environ['XLA_PYTHON_CLIENT_PREALLOCATE'] = 'false'
os.environ['XLA_PYTHON_CLIENT_ALLOCATOR'] = 'platform'
# Set PyTorch to use expandable segments to avoid memory fragmentation
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'
import torch
torch.multiprocessing.set_start_method('spawn')
import gc
if torch.cuda.is_available():
torch.cuda.empty_cache()
gc.collect()
from transformers import AutoModelForCausalLM, AutoTokenizer
import argparse
import msgpack
import flax
import jax.numpy as jnp
import jax
import numpy as np
import random
import matplotlib.pyplot as plt
import seaborn as sns
from tqdm import tqdm
from environment import state_to_image_jit, AutomaticityEnv, State
import optax
from flax.training import train_state
from flax import struct
import pandas as pd
import imageio.v2 as imageio
from baselines.BC import BCNet
from agent import AgentExecutionFramework
import time
from io import BytesIO
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description="Train baseline models for automaticity.")
parser.add_argument(
"--baseline_model",
type=str,
default="ROTE",
help="Baseline model to train."
)
parser.add_argument(
"--data_path",
type=str,
default="data",
help="Path to the dataset folders."
)
parser.add_argument(
"--group",
type=bool,
default=False,
help="Whether to use joint-planner data."
)
parser.add_argument('--num_agents_to_sample', type=int, default=1, help='Number of agents to sample from the dataset.')
parser.add_argument('--num_datapoints_per_agent_to_sample', type=int, default=3, help='Number of datapoints per agent to sample from the dataset.')
parser.add_argument('--num_agents', type=int, default=1, help='Number of agents in the dataset.')
parser.add_argument('--num_datapoints_per_agent', type=int, default=5, help='Number of datapoints per agent in the dataset.')
parser.add_argument('--num_steps', type=int, default=50, help='Number of steps in the dataset.')
parser.add_argument('--env_size', type=int, default=7, help='Size of the environment.')
# parser.add_argument('--num_blocks', type=int, default=10, help='Number of blocks in the dataset.')
# parser.add_argument('--num_walls', type=int, default=10, help='Number of walls in the dataset.')
parser.add_argument('--as_images', type=bool, default=False, help='Whether to load the data as images.')
parser.add_argument('--learning_rate', type=float, default=1e-2, help='Learning rate for the optimizer.')
parser.add_argument('--num_epochs', type=int, default=100, help='Number of training epochs.')
parser.add_argument('--save_path', type=str, default='models', help='Path to save the model.')
parser.add_argument('--seed', type=int, default=12, help='Random seed.')
parser.add_argument('--n_hypothesis', type=int, default=30, help='Number of hypothesis for thought trace.')
parser.add_argument('--model_name', type=str, default="deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct", help='Name of the model to use.') # deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct or meta-llama/Llama-3.1-8B-Instruct or deepseek-ai/DeepSeek-V2-Lite
parser.add_argument('--tensor_parallel_size', type=int, default=1, help='Number of tensor parallel size.')
parser.add_argument('--dtype', type=str, default="float16", help='Data type.')
parser.add_argument('--gpu_memory_utilization', type=float, default=0.9, help='GPU memory utilization.')
parser.add_argument('--overfit', type=bool, default=False, help='Whether to overfit on a single environment.')
parser.add_argument('--bootstrap', action='store_true', help='Whether to use bootstrapping for hypothesis evaluation')
parser.add_argument('--two_stage', action='store_true', help='Whether to use two-stage approach for ROTE reasoning')
parser.add_argument('--structured', type=str, default="False", choices=["False", "p1", "p2"],
help='Structured prompting type for ROTE reasoning: False, p1, or p2')
parser.add_argument('--rejuvenation', action='store_true', help='Use rejuvenation for ROTE model')
parser.add_argument('--plot_gifs', action='store_true', help='Plot gifs for ROTE model')
parser.add_argument('--rejuvenation_threshold', type=float, default=1, help='Threshold for rejuvenation')
parser.add_argument('--max_rejuvenation_attempts', type=int, default=2, help='Maximum number of rejuvenation attempts')
parser.add_argument('--top_k', type=int, default=0, help='If > 0, only average over the top k most likely hypotheses')
parser.add_argument('--multi_step_eval', type=bool, default=True, help='Perform multi-step evaluation for ROTE')
parser.add_argument('--num_steps_to_predict', type=int, default=20, help='Number of future steps to predict in multi-step eval')
parser.add_argument('--flip_quarter', type=bool, default=True, help='reset the environment after 30 steps')
parser.add_argument('--human_data', type=bool, default=False, help='Use human data')
args = parser.parse_args()
# Check if the selected baseline model is implemented
if args.baseline_model not in ['BC', 'AutoToM', 'ROTE', 'NLLM', 'Oracle']:
raise NotImplementedError(f"Baseline model '{args.baseline_model}' is not implemented.")
if args.baseline_model == 'AutoToM':
os.environ['CURRENT_MODEL_NAME'] = args.model_name
return args
def initialize_environment(num_agents: int, num_blocks: int, num_walls: int, size: int = 10, max_steps: int = 100):
env = AutomaticityEnv(num_agents=num_agents, size=size, max_steps=max_steps, num_blocks=num_blocks, num_walls=num_walls)
return env
def make_dataloader_human(args, num_agents_to_sample: int = 2, num_datapoints_per_agent_to_sample: int = 20, overfit: bool = False, training: bool = False, epoch: int = 0):
"""Load data from the dataset folders."""
data_path = args.data_path
as_images = args.as_images
data_folder = f"{data_path}/human_data_fix"
from human_dataloader import load_and_stack_human_gameplay_data
human_dataloader = load_and_stack_human_gameplay_data(data_folder)
human_data = None
try:
for j in range(epoch+1):
human_data, human_actions, agent_id, filename, task = next(human_dataloader)
current_data_loaded = epoch
except StopIteration:
print("Reached end of human data, exiting successfully")
exit(0)
i = epoch
while True:
'''
actions is (num_agents to sample, num_datapoints per agent, traj_length, 1)
agent ids is (num_agents_to_sample, num_datapoints per_agent, traj_length) where each value for agent is the task number
states is (num_agents_to_sample, num_datapoints per agent, traj_length, *state_shape)
'''
human_states = human_data
# Add two dimensions of length 1 to each leaf in human_states
human_states = jax.tree.map(
lambda x: x[None, None, :, ...] if isinstance(x, (jnp.ndarray, np.ndarray)) else x,
human_states
)
human_actions = human_actions[None, None, :, None]
human_agent_id = jnp.array([agent_id])[None, None, :] # (1, 1, 1)
# Repeat agent_id to match length of human_actions
human_agent_id = jnp.repeat(human_agent_id, human_actions.shape[2], axis=2) # (1, 1, traj_length)
sampled_states = human_states
sampled_data = {
'states': sampled_states,
'actions': human_actions,
'agent_ids': human_agent_id,
# 'filename': filename,
# 'task': task
}
# Reshape all arrays to (-1, *original_shape[3:])
reshaped_state = jax.tree.map(
lambda x: jnp.array(x).reshape(-1, *x.shape[3:]) if (isinstance(x, jnp.ndarray) or isinstance(x, np.ndarray)) else x,
sampled_states
)
# Process images in smaller batches to reduce memory usage
batch_size = 100 # Process images in smaller batches
num_samples = reshaped_state['agent_locations'].shape[0]
all_images = []
for start_idx in range(0, num_samples, batch_size):
end_idx = min(start_idx + batch_size, num_samples)
batch_indices = jnp.arange(start_idx, end_idx)
batch_state = jax.tree.map(lambda x: x[batch_indices] if isinstance(x, (jnp.ndarray, np.ndarray)) else x, reshaped_state)
def convert_to_image(index, stacked_state):
indexed_state = jax.tree.map(lambda x: x[index], stacked_state)
img_size = args.env_size * 7
tile_size = 7
grid_size = args.env_size
img_gen_fn = jax.jit(state_to_image_jit, static_argnums=(1, 2, 3))
render_fn = lambda x: img_gen_fn(x, img_size, grid_size, tile_size)
return render_fn(indexed_state)
batch_images = jax.vmap(convert_to_image, in_axes=(0, None))(jnp.arange(len(batch_indices)), batch_state)
all_images.append(batch_images)
# Concatenate all batches
stacked_images = jnp.concatenate(all_images, axis=0)
del reshaped_state, all_images
if as_images:
sampled_data['states'] = stacked_images.reshape(1, 1, -1, *stacked_images.shape[1:])
sampled_data['images'] = stacked_images.reshape(1, 1, -1, *stacked_images.shape[1:])
else:
sampled_data['states'] = sampled_states
sampled_data['images'] = stacked_images.reshape(1, 1, -1, *stacked_images.shape[1:])
yield sampled_data
del sampled_data
try:
human_data, human_actions, agent_id, filename, task = next(human_dataloader)
current_data_loaded += 1
except StopIteration:
print("Reached end of human data, exiting successfully")
exit(0)
def make_dataloader(args, num_agents_to_sample: int = 2, num_datapoints_per_agent_to_sample: int = 20, overfit: bool = False, training: bool = False, epoch: int = 0):
"""Load data from the dataset folders."""
data_path = args.data_path
as_images = args.as_images
i = epoch
while True:
if not overfit:
i += 1
num_blocks = random.choice(list(range(3,8,1)))
num_walls = random.choice(list(range(1, 5, 1)))
else:
num_blocks = 4
num_walls = 1
data_folder = f"{data_path}/num_blocks{num_blocks}/num_walls{num_walls}"
extension = "_group" if args.group else ""
if args.flip_quarter:
extension += "_flip_quarter"
data_file = f"{data_folder}/gt_fsm{extension}_traj_data_{args.num_agents}agents.msgpack"
# print(f"Loading data from {data_file}")
# Load data in chunks to reduce memory usage
with open(data_file, "rb") as f:
serialized_data = f.read()
# Create target structure with correct shapes
action_target = jnp.zeros((20, args.num_datapoints_per_agent, args.num_steps, 1))
agent_id_target = jnp.zeros((20, args.num_datapoints_per_agent, args.num_steps))
state_target = {
'agent_id': agent_id_target,
'agent_locations': jnp.zeros((20, args.num_datapoints_per_agent, args.num_steps, 1, 2)),
'agent_inventory': jnp.zeros((20, args.num_datapoints_per_agent, args.num_steps, 1)),
'agent_inventory_colors': jnp.zeros((20, args.num_datapoints_per_agent, args.num_steps, 1, 3)),
'block_colors': jnp.zeros((20, args.num_datapoints_per_agent, args.num_steps, num_blocks, 3)),
'block_locations': jnp.zeros((20, args.num_datapoints_per_agent, args.num_steps, num_blocks, 2)),
'time': jnp.zeros((20, args.num_datapoints_per_agent, args.num_steps)),
'terminal': jnp.zeros((20, args.num_datapoints_per_agent, args.num_steps)),
'wall_locations': jnp.zeros((20, args.num_datapoints_per_agent, args.num_steps, num_walls + 2 * (args.env_size * 2 - 1) + 2, 2)),
}
target = {
'states': state_target,
'actions': action_target,
'agent_ids': agent_id_target,
}
loaded_data = flax.serialization.from_bytes(target, serialized_data)
del serialized_data # Free memory immediately
# Validate shapes match target
for key in target['states'].keys():
if loaded_data['states'][key].shape != target['states'][key].shape:
continue
# print(f"Loaded data from {data_file}")
# Sample only what we need
if overfit:
agent_indices = jax.random.randint(jax.random.PRNGKey(i), (num_agents_to_sample,), minval=1, maxval=2)
else:
agent_indices = jax.random.randint(jax.random.PRNGKey(i), (num_agents_to_sample,), minval=0, maxval=loaded_data['states']['agent_locations'].shape[0])
i += 1
if training: # for creating held out set
batch_floor = 0
batch_limit = int(loaded_data['states']['agent_locations'].shape[1] * 0.8)
else:
batch_floor = int(loaded_data['states']['agent_locations'].shape[1] * 0.8)
batch_limit = loaded_data['states']['agent_locations'].shape[1]
batch_indices = jax.random.randint(jax.random.PRNGKey(i), (num_datapoints_per_agent_to_sample,), minval=batch_floor, maxval=batch_limit)
i += 1
# Process data in smaller chunks to reduce memory usage
sampled_data = {}
sampled_data['actions'] = loaded_data['actions'][agent_indices][:, batch_indices][:, :, :]
sampled_data['agent_ids'] = loaded_data['agent_ids'][agent_indices][:, batch_indices][:, :, :]
# Process states separately to reduce peak memory usage
sampled_states = {}
for key in loaded_data['states']:
sampled_states[key] = loaded_data['states'][key][agent_indices][:, batch_indices][:, :, :]
# Free memory
del loaded_data
# Reshape all arrays to (-1, *original_shape[3:])
reshaped_state = jax.tree.map(
lambda x: jnp.array(x).reshape(-1, *x.shape[3:]) if (isinstance(x, jnp.ndarray) or isinstance(x, np.ndarray)) else x,
sampled_states
)
# Process images in smaller batches to reduce memory usage
batch_size = 100 # Process images in smaller batches
num_samples = reshaped_state['agent_locations'].shape[0]
all_images = []
for start_idx in range(0, num_samples, batch_size):
end_idx = min(start_idx + batch_size, num_samples)
batch_indices = jnp.arange(start_idx, end_idx)
batch_state = jax.tree.map(lambda x: x[batch_indices] if isinstance(x, (jnp.ndarray, np.ndarray)) else x, reshaped_state)
def convert_to_image(index, stacked_state):
indexed_state = jax.tree.map(lambda x: x[index], stacked_state)
img_size = args.env_size * 7
tile_size = 7
grid_size = args.env_size
img_gen_fn = jax.jit(state_to_image_jit, static_argnums=(1, 2, 3))
render_fn = lambda x: img_gen_fn(x, img_size, grid_size, tile_size)
return render_fn(indexed_state)
batch_images = jax.vmap(convert_to_image, in_axes=(0, None))(jnp.arange(len(batch_indices)), batch_state)
all_images.append(batch_images)
# Concatenate all batches
stacked_images = jnp.concatenate(all_images, axis=0)
# Free memory
del reshaped_state, all_images
if as_images:
sampled_data['states'] = stacked_images.reshape(num_agents_to_sample, num_datapoints_per_agent_to_sample, args.num_steps, *stacked_images.shape[1:])
sampled_data['images'] = stacked_images.reshape(num_agents_to_sample, num_datapoints_per_agent_to_sample, -1, *stacked_images.shape[1:])
else:
sampled_data['states'] = sampled_states
sampled_data['images'] = stacked_images.reshape(num_agents_to_sample, num_datapoints_per_agent_to_sample, -1, *stacked_images.shape[1:])
yield sampled_data
del sampled_data
def eval_autoToM(args, dataloader, model, episode_id: int = 0):
if args.multi_step_eval:
# --- Multi-Step Evaluation Logic ---
num_future_steps = args.num_steps_to_predict
num_correct = 0
num_total = 0
total_prediction_time = 0
num_predictions = 0
first_step_correct = 0
first_step_total = 0
correct_after_flip = 0
total_after_flip = 0
# Process just one datapoint (one epoch) at a time
datapoint = next(dataloader)
# Initialize environment (parameters will be set per datapoint)
env_size = 10
env_max_steps = num_future_steps + 5 # Sufficiently large
for a_idx in tqdm(range(args.num_agents_to_sample), desc="Multi-step Eval Samples"):
data_sample = jax.tree.map(lambda x: x[a_idx, -1, :20+num_future_steps], datapoint)
initial_states_traj = jax.tree.map(lambda x: x[:20], data_sample['states'])
initial_actions_traj = jax.tree.map(lambda x: x[:20], data_sample['actions'])
gt_agent_script_id = int(initial_states_traj['agent_id'][0])
avg_matching_states, mean_equal_actions = get_matching_states_and_actions(initial_states_traj, initial_actions_traj)
gt_future_actions = data_sample['actions'][19:] # Shape (num_future_steps, num_env_agents) or (num_future_steps, 1)
num_env_agents = 4 if args.group else 1
# Infer num_blocks and num_walls from the state
state_at_t19 = jax.tree.map(lambda x: x[19], initial_states_traj)
# Handle different possible shapes for block_locations
if isinstance(state_at_t19['block_locations'], (np.ndarray, jnp.ndarray)):
if state_at_t19['block_locations'].ndim == 1:
num_blocks = 1
elif state_at_t19['block_locations'].ndim == 2:
num_blocks = state_at_t19['block_locations'].shape[0]
else:
num_blocks = 0
else:
num_blocks = 0
num_walls = state_at_t19['wall_locations'].shape[0]
env = AutomaticityEnv(num_agents=num_env_agents, size=env_size, max_steps=env_max_steps,
num_blocks=num_blocks, num_walls=num_walls)
# Initialize simulation state from the last observed state
current_sim_state_pytree = state_at_t19
current_sim_state_pytree = State(
wall_locations=current_sim_state_pytree['wall_locations'],
agent_locations=current_sim_state_pytree['agent_locations'],
block_locations=current_sim_state_pytree['block_locations'],
agent_inventory=current_sim_state_pytree['agent_inventory'],
agent_inventory_colors=current_sim_state_pytree['agent_inventory_colors'],
block_colors=current_sim_state_pytree['block_colors'],
time=current_sim_state_pytree['time'],
terminal=False,
agent_id=-1
)
# Simulate future steps
for step_idx in range(num_future_steps):
if step_idx >= gt_future_actions.shape[0]:
break
step_prediction_start = time.time()
# For each agent in the environment
for agent_id in range(num_env_agents):
if step_idx < 10:
num_total += 1
if step_idx == 0:
first_step_total += 1
else:
total_after_flip += 1
# Create a trajectory for this specific prediction
if step_idx == 0:
# First prediction uses the initial trajectory
pred_states = initial_states_traj
pred_actions = initial_actions_traj
else:
# Subsequent predictions use updated trajectory with previous predictions
# Process each updated state individually to get observations
updated_obs = []
for t in range(step_idx):
# obs_t = env.get_observation(updated_states[t])[0]
obs_t = updated_states[t]
updated_obs.append(obs_t)
# Stack observations into a sequence
stacked_obs = jax.tree.map(lambda *xs: jnp.stack(xs), *updated_obs)
# Concatenate with initial trajectory
pred_states = jax.tree.map(lambda x, y: jnp.concatenate([x[:20], y], axis=0),
initial_states_traj, stacked_obs)
pred_actions = jnp.concatenate([initial_actions_traj,
jnp.array(action_history[:step_idx])], axis=0)
# Get model prediction for this step and agent
try:
predicted_action, predicted_probs = model.predict_action(pred_states, pred_actions,
agent_id=agent_id, timestep=19+step_idx)
# Compare with ground truth
gt_action = gt_future_actions[step_idx][agent_id] if args.group else gt_future_actions[step_idx][0]
if predicted_action == gt_action:
if step_idx < 10:
num_correct += 1
if step_idx == 0:
first_step_correct += 1
else:
correct_after_flip += 1
except Exception as e:
print(f"Error predicting action for agent {agent_id}, step {step_idx}: {e}")
continue
step_prediction_time = time.time() - step_prediction_start
total_prediction_time += step_prediction_time
num_predictions += 1
# Collect actions for all agents to update environment
action_to_take_in_env_list = []
for agent_id in range(num_env_agents):
try:
predicted_action, _ = model.predict_action(pred_states, pred_actions,
agent_id=agent_id, timestep=19+step_idx)
action_to_take_in_env_list.append(predicted_action)
except:
# If prediction fails, use ground truth (to keep simulation going)
gt_action = gt_future_actions[step_idx][agent_id] if args.group else gt_future_actions[step_idx][0]
action_to_take_in_env_list.append(gt_action)
# Store actions for next iteration
if step_idx == 0:
action_history = [action_to_take_in_env_list]
updated_states = []
else:
action_history.append(action_to_take_in_env_list)
# Simulate environment step
current_sim_state_pytree = jax.tree.map(lambda x: x[19+step_idx+1], data_sample['states'])
updated_states.append(jax.tree.map(lambda x: x, current_sim_state_pytree))
accuracy = num_correct / num_total if num_total > 0 else 0
avg_prediction_time = total_prediction_time / num_predictions if num_predictions > 0 else 0
first_step_accuracy = first_step_correct / first_step_total if first_step_total > 0 else 0
accuracy_after_flip = correct_after_flip / total_after_flip if total_after_flip > 0 else 0
print(f"AutoToM Multi-Step Accuracy: {accuracy:.4f} ({num_correct}/{num_total})")
print(f"First Step Accuracy: {first_step_accuracy:.4f} ({first_step_correct}/{first_step_total})")
print(f"Accuracy After Flip: {accuracy_after_flip:.4f} ({correct_after_flip}/{total_after_flip})")
print(f"Average prediction time per step: {avg_prediction_time:.4f} seconds")
return accuracy, avg_prediction_time, first_step_accuracy, gt_agent_script_id, accuracy_after_flip, avg_matching_states, mean_equal_actions
else:
# Original single-step evaluation
num_correct = 0
num_total = 0
# Process just one datapoint (one epoch) at a time
datapoint = next(dataloader)
for a in tqdm(range(args.num_agents_to_sample)):
data = jax.tree.map(lambda x: x[a, -1, :15], datapoint)
states = data['states']
actions = data['actions'] # (20, n) # 20 timesteps, n agent actions
agent_ids = data['agent_ids']
for agent_id in tqdm(range(actions.shape[1])):
tries = 0
gt_action = actions[-1, agent_id]
num_total += 1
try:
predicted_final_action, predicted_probs = model.predict_action(states, actions, agent_id=agent_id, episode_id=episode_id)
final_action_prob = predicted_probs[gt_action]
if final_action_prob >= np.max(predicted_probs):
num_correct += 1
except Exception as e:
continue
print(f"Accuracy: {num_correct / num_total}")
return num_correct / num_total, 0.0 # Return 0.0 as placeholder for avg_prediction_time
def get_matching_states_and_actions(states, actions):
# Get all state indices
state_indices = list(np.arange(states['agent_locations'].shape[0]))
# Track groups of matching states
matching_groups = []
used_indices = set()
# Compare each state with every other state
for i in state_indices:
if i in used_indices:
continue
current_group = {i}
used_indices.add(i)
# Compare with remaining states
for j in state_indices:
if j in used_indices:
continue
# Check if all state components match using jnp.all
states_match = True
for key in states.keys():
if key in ['time', 'terminal']:
continue
if not jnp.all(states[key][i] == states[key][j]):
states_match = False
break
if states_match:
current_group.add(j)
used_indices.add(j)
matching_groups.append(len(current_group))
# Calculate average size of matching groups
avg_matching_states = sum(matching_groups) / len(matching_groups) if matching_groups else 1
print(f"Average size of matching state groups: {avg_matching_states:.2f}")
next_time_actions = actions[1:]
old_time_actions = actions[:-1]
action_equal = jnp.all(next_time_actions == old_time_actions, axis=1)
mean_equal_actions = jnp.mean(action_equal)
return avg_matching_states, mean_equal_actions
def eval_naive_llm(args, dataloader, model, episode_id: int = 0):
if args.multi_step_eval:
# --- Multi-Step Evaluation Logic ---
num_future_steps = args.num_steps_to_predict
num_correct = 0
num_total = 0
total_prediction_time = 0
num_predictions = 0
first_step_correct = 0
first_step_total = 0
correct_after_flip = 0
total_after_flip = 0
# Process just one datapoint (one epoch) at a time
datapoint = next(dataloader)
# Initialize environment (parameters will be set per datapoint)
env_size = 7
env_max_steps = num_future_steps + 5 # Sufficiently large
for a_idx in tqdm(range(args.num_agents_to_sample), desc="Multi-step Eval Samples"):
data_sample = jax.tree.map(lambda x: x[a_idx, -1, :20+num_future_steps], datapoint)
initial_states_traj = jax.tree.map(lambda x: x[:20], data_sample['states'])
initial_actions_traj = jax.tree.map(lambda x: x[:20], data_sample['actions'])
gt_agent_script_id = int(initial_states_traj['agent_id'][0])
avg_matching_states, mean_equal_actions = get_matching_states_and_actions(initial_states_traj, initial_actions_traj)
gt_future_actions = data_sample['actions'][19:] # Shape (num_future_steps, num_env_agents) or (num_future_steps, 1)
num_env_agents = 4 if args.group else 1
# Infer num_blocks and num_walls from the state
state_at_t19 = jax.tree.map(lambda x: x[19], initial_states_traj)
# Handle different possible shapes for block_locations
if isinstance(state_at_t19['block_locations'], (np.ndarray, jnp.ndarray)):
if state_at_t19['block_locations'].ndim == 1:
num_blocks = 1
elif state_at_t19['block_locations'].ndim == 2:
num_blocks = state_at_t19['block_locations'].shape[0]
else:
num_blocks = 0
else:
num_blocks = 0
num_walls = state_at_t19['wall_locations'].shape[0]
env = AutomaticityEnv(num_agents=num_env_agents, size=env_size, max_steps=env_max_steps,
num_blocks=num_blocks, num_walls=num_walls)
# Initialize simulation state from the last observed state
current_sim_state_pytree = state_at_t19
current_sim_state_pytree = State(
wall_locations=current_sim_state_pytree['wall_locations'],
agent_locations=current_sim_state_pytree['agent_locations'],
block_locations=current_sim_state_pytree['block_locations'],
agent_inventory=current_sim_state_pytree['agent_inventory'],
agent_inventory_colors=current_sim_state_pytree['agent_inventory_colors'],
block_colors=current_sim_state_pytree['block_colors'],
time=current_sim_state_pytree['time'],
terminal=False,
agent_id=-1
)
# Simulate future steps
for step_idx in range(num_future_steps):
if step_idx >= gt_future_actions.shape[0]:
break
step_prediction_start = time.time()
# For each agent in the environment
for agent_id in range(num_env_agents):
if step_idx < 10:
num_total += 1
else:
total_after_flip += 1
# Create a trajectory for this specific prediction
if step_idx == 0:
# First prediction uses the initial trajectory
pred_states = initial_states_traj
pred_actions = initial_actions_traj
first_step_total += 1
else:
# Subsequent predictions use updated trajectory with previous predictions
# Process each updated state individually to get observations
updated_obs = []
for t in range(step_idx):
# obs_t = env.get_observation(updated_states[t])[0]
obs_t = updated_states[t]
updated_obs.append(obs_t)
# Stack observations into a sequence
stacked_obs = jax.tree.map(lambda *xs: jnp.stack(xs), *updated_obs)
# Concatenate with initial trajectory
pred_states = jax.tree.map(lambda x, y: jnp.concatenate([x[:20], y], axis=0),
initial_states_traj, stacked_obs)
pred_actions = jnp.concatenate([initial_actions_traj,
jnp.array(action_history[:step_idx])], axis=0)
# Get model prediction for this step and agent
try:
predicted_probs = model.predict_action(pred_states, pred_actions,
agent_id=agent_id, timestep=14+step_idx)
# Get the predicted action (highest probability)
predicted_action = np.argmax(predicted_probs)
# Compare with ground truth
gt_action = gt_future_actions[step_idx][agent_id] if args.group else gt_future_actions[step_idx][0]
if predicted_action == gt_action:
if step_idx < 10:
num_correct += 1
if step_idx == 0:
first_step_correct += 1
else:
correct_after_flip += 1
except Exception as e:
print(f"Error predicting action for agent {agent_id}, step {step_idx}: {e}")
continue
step_prediction_time = time.time() - step_prediction_start
total_prediction_time += step_prediction_time
num_predictions += 1
# Collect actions for all agents to update environment
action_to_take_in_env_list = []
for agent_id in range(num_env_agents):
try:
predicted_probs = model.predict_action(pred_states, pred_actions,
agent_id=agent_id, timestep=19+step_idx)
action_to_take_in_env_list.append(np.argmax(predicted_probs))
except:
# If prediction fails, use ground truth (to keep simulation going)
gt_action = gt_future_actions[step_idx][agent_id] if args.group else gt_future_actions[step_idx][0]
action_to_take_in_env_list.append(gt_action)
# Store actions for next iteration
if step_idx == 0:
action_history = [action_to_take_in_env_list]
updated_states = []
else:
action_history.append(action_to_take_in_env_list)
current_sim_state_pytree = jax.tree.map(lambda x: x[19+step_idx+1], data_sample['states'])
updated_states.append(jax.tree.map(lambda x: x, current_sim_state_pytree))
accuracy = num_correct / num_total if num_total > 0 else 0
accuracy_after_flip = correct_after_flip / total_after_flip if total_after_flip > 0 else 0
avg_prediction_time = total_prediction_time / num_predictions if num_predictions > 0 else 0
first_step_accuracy = first_step_correct / first_step_total if first_step_total > 0 else 0
print(f"NLLM Multi-Step Accuracy: {accuracy:.4f} ({num_correct}/{num_total})")
print(f"Average prediction time per step: {avg_prediction_time:.4f} seconds")
return accuracy, avg_prediction_time, first_step_accuracy, gt_agent_script_id, accuracy_after_flip, avg_matching_states, mean_equal_actions
else:
# Original single-step evaluation
num_correct = 0
num_total = 0
# Process just one datapoint (one epoch) at a time
datapoint = next(dataloader)
for a in tqdm(range(args.num_agents_to_sample)):
data = jax.tree.map(lambda x: x[a, -1, :15], datapoint)
states = data['states']
actions = data['actions'] # (20, 1) # 20 timesteps, 1 action
agent_ids = data['agent_ids']
for agent_id in tqdm(range(actions.shape[1])):
num_total += 1
tries = 0
gt_action = actions[-1, agent_id]
try:
predicted_probs = model.predict_action(states, actions, agent_id=agent_id)
final_action_prob = predicted_probs[gt_action]
if final_action_prob >= np.max(predicted_probs):
num_correct += 1
except Exception as e:
tries += 1
print(f"Accuracy: {num_correct / num_total}")
return num_correct / num_total
def load_bc_models(args):
"""Load BC models from multiple seeds."""
states = []
# Define the learning rate to use
lr = args.learning_rate
# Initialize model
if args.group:
num_to_predict = 4
else:
num_to_predict = 1
model = BCNet(output_size=6, hidden_size=32, num_to_predict=num_to_predict)
for seed in range(6):
# Construct the path pattern similar to what's used in train_baselines.py
model_path = f"baselines/BC/{args.save_path}/nagents{args.num_agents_to_sample}_ndatapoints{args.num_datapoints_per_agent_to_sample}_seed{seed}_lr{lr}_group{args.group}"
# Look for the latest checkpoint
checkpoint_dir = os.path.dirname(model_path)
if not os.path.exists(checkpoint_dir):
print(f"Directory {checkpoint_dir} does not exist, skipping seed {seed}")
continue
checkpoint_files = [f for f in os.listdir(checkpoint_dir)
if os.path.basename(model_path) in f and "checkpoint" in f]
if not checkpoint_files:
# Try looking for final model
final_model = f"{model_path}_final.msgpack"
if os.path.exists(final_model):
checkpoint_path = final_model
else:
print(f"No checkpoint found for seed {seed}, skipping")
continue
else:
# Find the most recent checkpoint
checkpoint_epochs = [int(f.split("epoch")[-1].split(".")[0]) for f in checkpoint_files]
if 2500 in checkpoint_epochs:
most_recent_epoch = 2500
else:
most_recent_epoch = max(checkpoint_epochs)
most_recent_checkpoint = [f for f in checkpoint_files if f"epoch{most_recent_epoch}" in f][0]
checkpoint_path = os.path.join(checkpoint_dir, most_recent_checkpoint)
print(f"Loading BC model from seed {seed}: {checkpoint_path}")
# Load checkpoint
with open(checkpoint_path, 'rb') as f:
checkpoint_bytes = f.read()
# Create a dummy state to get the structure right
rng_key = jax.random.PRNGKey(0)
dummy_states = jnp.zeros((args.num_datapoints_per_agent_to_sample, 20, args.env_size*7, args.env_size*7, 3))
dummy_actions = jnp.zeros((args.num_datapoints_per_agent_to_sample, 20, 1))
variables = model.init(rng_key, dummy_states, dummy_actions)
# Create target structure for deserialization
target = {
'params': variables['params'],
'batch_stats': variables.get('batch_stats', flax.core.FrozenDict()),
'epoch': 0,
'loss': 0.0
}
# Deserialize checkpoint
checkpoint = flax.serialization.from_bytes(target, checkpoint_bytes)
states.append({
'params': checkpoint['params'],
'batch_stats': checkpoint['batch_stats']
})
# Stack all parameters from different seeds into a single state
stacked_state = {
'params': jax.tree.map(lambda *xs: jnp.stack(xs), *[s['params'] for s in states]),
'batch_stats': jax.tree.map(lambda *xs: jnp.stack(xs), *[s['batch_stats'] for s in states])
}
return model, stacked_state
img_gen_fn = jax.jit(state_to_image_jit, static_argnums=(1, 2, 3))
def eval_bc(args, dataloader, model, states, episode_id: int = 0, env=None):
"""Evaluate BC models."""
if args.multi_step_eval:
# --- Multi-Step Evaluation Logic ---
num_future_steps = args.num_steps_to_predict
num_correct = 0
num_total = 0
total_prediction_time = 0
num_predictions = 0
first_step_correct = 0
first_step_total = 0
correct_after_flip = 0
total_after_flip = 0
# Process just one datapoint (one epoch) at a time
datapoint = next(dataloader)
env_size = 7
env_max_steps = num_future_steps + 5 # Sufficiently large
for a_idx in tqdm(range(args.num_agents_to_sample), desc="Multi-step Eval Samples"):
data_sample = jax.tree.map(lambda x: x[a_idx, -1, :20+num_future_steps], datapoint)
initial_states_traj = jax.tree.map(lambda x: x[:20], data_sample['states'])
initial_actions_traj = jax.tree.map(lambda x: x[:20], data_sample['actions'])
gt_agent_script_id = int(initial_states_traj['agent_id'][0])
avg_matching_states, mean_equal_actions = get_matching_states_and_actions(initial_states_traj, initial_actions_traj)
gt_future_actions = data_sample['actions'][19:] # Shape (num_future_steps, num_env_agents) or (num_future_steps, 1)
num_env_agents = 4 if args.group else 1
# Infer num_blocks and num_walls from the state
state_at_t19 = jax.tree.map(lambda x: x[19], initial_states_traj)
# Handle different possible shapes for block_locations
if isinstance(state_at_t19['block_locations'], (np.ndarray, jnp.ndarray)):
if state_at_t19['block_locations'].ndim == 1:
num_blocks = 1
elif state_at_t19['block_locations'].ndim == 2:
num_blocks = state_at_t19['block_locations'].shape[0]
else:
num_blocks = 0
else:
num_blocks = 0
num_walls = state_at_t19['wall_locations'].shape[0]
if env is None:
env = AutomaticityEnv(num_agents=num_env_agents, size=env_size, max_steps=env_max_steps,
num_blocks=num_blocks, num_walls=num_walls)
# Initialize simulation state from the last observed state
current_sim_state_pytree = state_at_t19
def convert_to_state(state_t):
return State(
wall_locations=state_t['wall_locations'],
agent_locations=state_t['agent_locations'],
block_locations=state_t['block_locations'],
agent_inventory=state_t['agent_inventory'],
agent_inventory_colors=state_t['agent_inventory_colors'],
block_colors=state_t['block_colors'],
time=state_t['time'],
terminal=False,
agent_id=-1
)
current_sim_state_pytree = convert_to_state(current_sim_state_pytree)
# Convert initial states to images for BC model
initial_states_images = []
for t in range(20):
state_t = jax.tree.map(lambda x: x[t], initial_states_traj)
img_size = args.env_size * 7
tile_size = 7
grid_size = args.env_size
try:
image_t = img_gen_fn(state_t, img_size, grid_size, tile_size)
initial_states_images.append(image_t)
except Exception as e:
print(f"Error generating image for state {state_t} at time {t}: {e}")
initial_states_images = jnp.stack(initial_states_images)
# Simulate future steps
for step_idx in range(num_future_steps):
try:
current_sim_state_pytree = convert_to_state(current_sim_state_pytree)
except Exception as e:
pass
if step_idx >= gt_future_actions.shape[0]:
break
# For each agent in the environment
for agent_id in range(num_env_agents):
if step_idx < 10:
num_total += 1
if step_idx == 0:
first_step_total += 1
else:
total_after_flip += 1
# Create a trajectory for this specific prediction
if step_idx == 0:
# First prediction uses the initial trajectory
pred_states_images = initial_states_images
pred_actions = initial_actions_traj
else:
# Convert updated states to images
updated_states_images = []
for t in range(step_idx):
state_t = updated_states[t]
try:
state_t = convert_to_state(state_t)
except Exception as e:
pass
img_size = args.env_size * 7
tile_size = 7
grid_size = args.env_size
try:
obs = jax.tree.map(lambda x: jnp.array(x), env.get_observation(state_t)[0])
except Exception as e:
breakpoint()
image_t = img_gen_fn(obs, img_size, grid_size, tile_size)
updated_states_images.append(image_t)
# Concatenate with initial images
pred_states_images = jnp.concatenate([initial_states_images, jnp.stack(updated_states_images)], axis=0)
pred_actions = jnp.concatenate([initial_actions_traj, jnp.array(action_history[:step_idx])], axis=0)
# Get model prediction for this step and agent
try:
# Reshape for batch prediction
pred_states_batch = jnp.expand_dims(pred_states_images, axis=0) # Add batch dimension
pred_actions_batch = jnp.expand_dims(pred_actions, axis=0) # Add batch dimension
# Apply model to get predictions
def single_agent_pred(param_state, data_states, data_actions):
variables = {'params': param_state['params'], 'batch_stats': param_state['batch_stats']}
res = model.apply(variables, data_states, data_actions, training=False)
return res
step_prediction_start = time.time()
# Get predictions from all ensemble models
action_preds = jax.vmap(single_agent_pred, in_axes=(0, None, None))(
states, pred_states_batch, pred_actions_batch)
step_prediction_time = time.time() - step_prediction_start
total_prediction_time += step_prediction_time
# action_preds shape: [num_models, num_to_predict, batch*timesteps, 6]
# We want the prediction for the last timestep
action_preds = action_preds[:, agent_id, -1, :] # [num_models, 6]
# Average predictions across ensemble
def single_network_acc(action_pred, gt_action):
max_action_prob = jnp.max(action_pred)