-
Notifications
You must be signed in to change notification settings - Fork 0
/
offline_batch_RL_policy_learning.py
1332 lines (1042 loc) · 70.5 KB
/
offline_batch_RL_policy_learning.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
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
"""
offline_batch_RL_policy_learning.py
Description:
Offline batch RL for learning a policy subject to constraints. The idea here is that we can utilize experiences from various
policies to learn a new policy that is optimal according to some objective function and also obeys some secondary constraints.
Curerntly, this algorithm expects that 2 SUMO-related policies are provided to use in generating a new policy. The first is a "speed limit" policy
and the other is a "queue length" policy.
This algorithm is essentially decentralized.
NOTE:
This file generates logs in .\batch_offline_RL_logs\<experiment>
Usage:
python offline_batch_RL_policy_learning.py -c experiments/sumo-2x2-ac-independent.config
References:
https://arxiv.org/pdf/1903.08738.pdf
"""
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from datetime import datetime
import random
import csv
import pickle
# SUMO dependencies
import sumo_rl
import sys
import os
from sumo_utils.sumo_custom.sumo_custom_observation import CustomObservationFunction
# Config Parser
from marl_utils.MARLConfigParser import MARLConfigParser
# Custom modules
from rl_core.actor_critic import Actor, QNetwork
from rl_core.fitted_q_evaluation import FittedQEvaluation
from rl_core.fitted_q_iteration import FittedQIteration
from rl_core.rollout import OfflineRollout, OnlineRollout
from marl_utils.dataset import Dataset, GenerateDataset
from sumo_utils.sumo_custom.calculate_speed_control import CalculateSpeedError
# Make sure SUMO env variable is set
if 'SUMO_HOME' in os.environ:
tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
sys.path.append(tools)
else:
sys.exit("Please declare the environment variable 'SUMO_HOME'")
def CalculateAverageRewardPerStep(queue_length_env:sumo_rl.parallel_env,
policies_to_use:dict,
reward_to_evaluate:str,
config_args) -> float:
"""
Run a rollout episode in the SUMO environment using a provided policy, calcualte and return a metric averaged per step across
all agents
# TODO: If a dataset was not provided and we have to generate a new dataset, this function should be part of that step
:param queue_length_env: The SUMO environment to execute the policy in, assumes that the reward has been set to "queue"
:param policies_to_use: Dictionary that maps agents to "actor" models to use for the evaluation
:param reward_to_evaluate: Either "queue" or "average-speed-limit", determines which metric to compute during the episode
:param config_args: Configuration arguments used to set up the experiment
:returns: Either average "queue" reward per step (averaged for all agents) or average "average speed error" reward per step
(averaged for all agents)
"""
# TODO: update function to support global observations
# Determine if a proper reward evaluation was requested
if (reward_to_evaluate != 'average-speed-limit') and (reward_to_evaluate != 'queue'):
print(f" > ERROR: Unrecognized reward evaluation '{reward_to_evaluate}' requested")
print(f" > Function only supports 'average-speed-limit' or 'queue'")
sys.exit(1)
# Define the speed limit used to evaluate the g1 constraint
SPEED_LIMIT = 7.0
agents = queue_length_env.possible_agents
# Define empty dictionary that maps agents to actions
actions = {agent: None for agent in agents}
# Maps each agent to its MAX SPEED OVERAGE for this step
episode_constraint_1 = {agent : 0.0 for agent in agents}
# Maps each agent to the accumulated NUBMER OF CARS STOPPED for episode
episode_constraint_2 = {agent : 0.0 for agent in agents}
# Initialize the env
obses, _ = queue_length_env.reset()
if config_args.parameter_sharing_model:
# Apply one-hot encoding to the initial observations
onehot_keys = {agent: i for i, agent in enumerate(agents)}
for agent in agents:
onehot = np.zeros(num_agents)
onehot[onehot_keys[agent]] = 1.0
obses[agent] = np.hstack([onehot, obses[agent]])
# Perform the rollout
for sumo_step in range(config_args.sumo_seconds):
# Populate the action dictionary
for agent in agents:
# Only use optimal actions according to the policy
action, _, _ = policies_to_use[agent].to(device).get_action(obses[agent])
actions[agent] = action.detach().cpu().numpy()
# Apply all actions to the env
next_obses, rewards, dones, truncated, info = queue_length_env.step(actions)
if np.prod(list(dones.values())):
break
if config_args.parameter_sharing_model:
# Apply one-hot encoding to the observations
onehot_keys = {agent: i for i, agent in enumerate(agents)}
for agent in agents:
onehot = np.zeros(num_agents)
onehot[onehot_keys[agent]] = 1.0
next_obses[agent] = np.hstack([onehot, next_obses[agent]])
# Accumulate the total episode reward and max speeds
for agent in agents:
max_speed_observed_by_agent = next_obses[agent][-1]
avg_speed_observed_by_agent = next_obses[agent][-2]
episode_constraint_1[agent] += CalculateSpeedError(speed=avg_speed_observed_by_agent,
speed_limit=SPEED_LIMIT,
lower_speed_limit=SPEED_LIMIT)
episode_constraint_2[agent] += rewards[agent] # NOTE That right now, the g2 constraint is the same as the 'queue' model
obses = next_obses
print(f" > Rollout complete after {sumo_step} steps")
print(f" > Constraint 1 total return: {sum(episode_constraint_1.values())}")
print(f" > Constraint 2 total return: {sum(episode_constraint_2.values())}")
for agent in agents:
print(f" > Agent '{agent}' constraint 1 return: {episode_constraint_1[agent]}")
print(f" > Agent '{agent}' constraint 2 return: {episode_constraint_2[agent]}")
if (reward_to_evaluate == 'average-speed-limit'):
# Average value per step for each agent
avg_g1s_per_step = [agent_g1_total_returns/sumo_step for agent_g1_total_returns in episode_constraint_1.values()]
print(f" > Average g1s per step for each agent: \n{avg_g1s_per_step}")
# Average value per step averaged across all agents
avg_g1_per_step_per_agent = np.mean(avg_g1s_per_step)
return avg_g1_per_step_per_agent
elif (reward_to_evaluate == 'queue'):
# Average value per step for each agent
avg_g2s_per_step = [agent_g2_total_returns/sumo_step for agent_g2_total_returns in episode_constraint_2.values()]
print(f" > Average g2s per step for each agent: \n{avg_g2s_per_step}")
# Average value per step averaged across all agents
avg_g2_per_step_per_agent = np.mean(avg_g2s_per_step)
return avg_g2_per_step_per_agent
def NormalizeDataset(dataset:dict,
constraint_ratio:float,
g1_upper_bound:float,
g1_lower_bound:float) -> dict:
"""
Function for normalizing the dataset so that the values of one constraint do not normalize the other
:param dataset: Dictionary that maps agents to a dataset of experience tuples
:param constraint_ratio: The ratio to use in the weight adjustment, used to determine where the g1 constraint
should be applied between the upper and lower bounds
:param g1_upper_bound: Upper bound to apply to g1 values in the dataset, should be the average reward per step
(avg of all agents) when evaluating the average speed policy according to the average speed reward
:param g2_lower_bound: Lower bound to apply to g1 values in the dataset, should be the average reward per step
(avg of all agents) when evaluating the queue policy according to the average speed reward
:returns Dictionary that maps agents to normalized datasets
"""
print(f" > Normalizing dataset constraint values")
normalized_dataset = {}
total_g1 = 0.0
total_g2 = 0.0
# Calculate constraint to be applied to g1 returns
c1 = ((g1_upper_bound - g1_lower_bound) * constraint_ratio) + g1_lower_bound
print(f" > Constraint for g1 (c1) = {c1}")
for agent in dataset.keys():
G_1 = 0.0
G_2 = 0.0
adjusted_g1s = []
adjusted_g2s = []
# Number of experience tuples for this agent
n = len(dataset[agent].buffer)
print(f" > Agent '{agent}' buffer size: {n} ")
normalized_dataset[agent] = Dataset(n)
for i in range(n):
s_obses, s_actions, s_next_obses, s_g1s, s_g2s, s_dones = dataset[agent].buffer[i]
# Apply constraint to g1
g1 = min(c1, s_g1s) - c1
adjusted_g1s.append(g1)
G_1 += g1
adjusted_g2s.append(s_g2s)
G_2 += s_g2s
for i in range(n):
s_obses, s_actions, s_next_obses, _, _, s_dones = dataset[agent].buffer[i]
# Calculate normalized g1 and g2
g1_n = adjusted_g1s[i]/abs(G_1)
if (g1_n > 0.0):
print(f" > ERROR: normalized g1 = {g1_n}, algorithm assumes g1 < 0")
sys.exit()
g2_n = adjusted_g2s[i]/abs(G_2)
if (g2_n > 0.0):
print(f" > ERROR: normalized g2 = {g2_n}, algorithm assumes g2 < 0")
sys.exit()
# Add it to the new dataset
normalized_dataset[agent].put((s_obses, s_actions, s_next_obses, g1_n, g2_n, s_dones))
total_g1 += G_1
total_g2 += G_2
print(f" > Agent: {agent}")
print(f" > G_1 = {G_1}")
print(f" > G_2 = {G_2}")
print(f" > total_g1 = {total_g1}")
print(f" > total_g2 = {total_g2}")
return normalized_dataset
def OfflineBatchRL(env:sumo_rl.parallel_env,
dataset: dict,
dataset_policies:list,
config_args,
nn_save_dir:str,
csv_save_dir:str,
max_num_rounds:int=10) -> tuple[dict, dict, list, list]:
"""
Perform offline batch reinforcement learning
Here we use a provided dataset to learn and evaluate a policy for a given number of "rounds"
Each round, a policy is learned and then evaluated (each of which involves solving an RL problem).
The provided constraint function defines how the "target" is calculated for each RL problem. At the end of the
round, the expected value of the polciy and the value function is calculated.
:param env: The SUMO environment that was used to generate the dataset
:param dataset: Dictionary that maps each agent to its experience tuple
:param dataset_policies: List of policies that were used to generate the dataset for this experiment (used for online evaluation)
:param config_args: Configuration arguments used to set up the experiment
:param nn_save_dir: Directory in which to save the models each round
:pram csv_save_dir: Directory in which to save the csv file
:param max_num_rounds: The number of rounds to perform (T)
:returns A dictionary that maps each agent to its mean learned policy,
a dictionary that maps each agent to the last learned policy,
a list of the final values for mean lambda 1 and mean lambda 2,
a list of the final values of lambda 1 and lambda 2
"""
print(f" > Performing batch offline reinforcement learning")
function_start_time = datetime.now()
# NOTE: These are the raw objects from the environment, they should not be modified for parameter sharing
# Dimensions of the observation space can be modified within sub-functions where necessary
agents = env.possible_agents
action_spaces = env.action_spaces
observation_spaces = env.observation_spaces
# There are two mean constraint value functions to track so create some strings to append to the corresponding file names for each constraint
mean_constraint_suffixes = ['g1', 'g2']
# Initialize csv files
# TODO: move these to respective functions
# with open(f"{csv_save_dir}/FQE_loss_{mean_constraint_suffixes[0]}.csv", "w", newline="") as csvfile:
# csv_writer = csv.DictWriter(csvfile, fieldnames=agents + ['Q(s,a) Sample','global_step'])
# csv_writer.writeheader()
# with open(f"{csv_save_dir}/FQE_loss_{mean_constraint_suffixes[1]}.csv", "w", newline="") as csvfile:
# csv_writer = csv.DictWriter(csvfile, fieldnames=agents + ['Q(s,a) Sample','global_step'])
# csv_writer.writeheader()
with open(f"{csv_save_dir}/FQI_actor_loss.csv", "w", newline="") as csvfile:
csv_writer = csv.DictWriter(csvfile, fieldnames=agents + ['Pi(a|s) Sample', 'global_step'])
csv_writer.writeheader()
with open(f"{csv_save_dir}/mean_policy_loss.csv", "w", newline="") as csvfile:
csv_writer = csv.DictWriter(csvfile, fieldnames=agents + ['global_step', 'round'])
csv_writer.writeheader()
with open(f"{csv_save_dir}/mean_constraint_loss_{mean_constraint_suffixes[0]}.csv", "w", newline="") as csvfile:
csv_writer = csv.DictWriter(csvfile, fieldnames=agents + ['global_step', 'round'])
csv_writer.writeheader()
with open(f"{csv_save_dir}/mean_constraint_loss_{mean_constraint_suffixes[1]}.csv", "w", newline="") as csvfile:
csv_writer = csv.DictWriter(csvfile, fieldnames=agents + ['global_step', 'round'])
csv_writer.writeheader()
with open(f"{csv_save_dir}/rollouts.csv", "w", newline="") as csvfile:
csv_writer = csv.DictWriter(csvfile, fieldnames=['round'] + [agent + '_return_g1' for agent in agents] +
['system_return_g1'] +
[agent + '_return_g2' for agent in agents] +
['system_return_g2'] +
[agent + '_threshold_policy_g1_return' for agent in agents] +
['threshold_policy_system_return_g1'] +
[agent + '_threshold_policy_g2_return' for agent in agents] +
['threshold_policy_system_return_g2'] +
[agent + '_queue_policy_g1_return' for agent in agents] +
['queue_policy_system_return_g1'] +
[agent + '_queue_policy_g2_return' for agent in agents] +
['queue_policy_system_return_g2'] +
['lambda_1', 'lambda_2', 'mean_lambda_1', 'mean_lambda_2'])
csv_writer.writeheader()
with open(f"{csv_save_dir}/online_rollouts.csv", "w", newline="") as csvfile:
csv_writer = csv.DictWriter(csvfile, fieldnames=['round'] +
[agent + '_mean_policy_g1_return' for agent in agents] +
['mean_policy_system_return_g1'] +
[agent + '_mean_policy_g2_return' for agent in agents] +
['mean_policy_system_return_g2'] +
[agent + '_current_policy_g1_return' for agent in agents] +
['current_policy_system_return_g1'] +
[agent + '_current_policy_g2_return' for agent in agents] +
['current_policy_system_return_g2'] +
[agent + '_threshold_policy_g1_return' for agent in agents] +
['threshold_policy_system_return_g1'] +
[agent + '_threshold_policy_g2_return' for agent in agents] +
['threshold_policy_system_return_g2'] +
[agent + '_queue_policy_g1_return' for agent in agents] +
['queue_policy_system_return_g1'] +
[agent + '_queue_policy_g2_return' for agent in agents] +
['queue_policy_system_return_g2'])
csv_writer.writeheader()
# Define a "mini" dataset to be used for offline rollouts (basically this will get passed through networks to evaluate them)
rollout_mini_dataset = {}
for agent in agents:
sample_size = len(dataset[agent].buffer)
rollout_mini_dataset[agent] = dataset[agent].sample(sample_size) # TODO: config, currently set to the same size as the dataset itself
# Define an "example" agent that can be used as a dictionary key when the specific agent doesn't matter
eg_agent = agents[0]
prev_mean_policies = {}
prev_g1_constraints = {}
prev_g2_constraints = {}
print(f" > Initializing neural networks")
num_agents = len(agents)
if config_args.parameter_sharing_model:
# Modify the observation space shape to include one-hot-encoding used for parameter sharing
print(f" > Parameter sharing enabled")
if config_args.global_obs:
print(f" > Global observations enabled")
observation_space_shape = tuple((shape+1) * (num_agents) for shape in observation_spaces[eg_agent].shape)
else:
print(f" > Global observations NOT enabled")
observation_space_shape = np.array(observation_spaces[eg_agent].shape).prod() + num_agents
else:
# Only need to modify the observation space shape if global observations are being used
print(f" > Parameter sharing NOT enabled")
if config_args.global_obs:
print(f" > Global observations enabled")
observation_space_shape = tuple(shape * num_agents for shape in observation_spaces[agent].shape)
else:
print(f" > Global observations NOT enabled")
observation_space_shape = observation_spaces[eg_agent].shape
# NOTE: When using parameter sharing, one network is needed for each object (policy and constraints). In this case, one network (per object) will be
# created and trained but to conform to the other functions, each agent will get it's own copy of that network (via dictionary)
#
# When not using parameter sharing, each agent gets its own unique policy and constraint networks and these will be trained independently
for agent in agents:
prev_mean_policies[agent] = Actor(observation_space_shape, action_spaces[agent].n).to(device)
prev_g1_constraints[agent] = QNetwork(observation_space_shape, action_spaces[agent].n).to(device)
prev_g2_constraints[agent] = QNetwork(observation_space_shape, action_spaces[agent].n).to(device)
# Initialize both lambdas equally
lambda_1 = 1.0/2.0
lambda_2 = 1.0/2.0
mean_lambda_1 = lambda_1
mean_lambda_2 = lambda_2
# for t=1:T
for t in range(1,max_num_rounds+1):
print(f" >> BEGINNING ROUND: {t} OF {max_num_rounds}")
round_start_time = datetime.now()
# Learn a policy that optimizes actions for the weighted sum of the g1 and g2 constraints
# This is essentially the "actor", policies here are represented as probability density functions of taking an action given a state
# NOTE: Regardless if parameter sharing is being used or not, the output here is a dictionary that maps each agent to its policy network
# when parameter sharing is being used, each network is identical (that does not mean each agent has identical policies)
policies = FittedQIteration(observation_spaces,
action_spaces,
agents,
dataset,
csv_save_dir,
config_args,
constraint="weighted_sum",
lambda_1=lambda_1,
lambda_2=lambda_2)
# Save the policy every round
# Format is policy_<round>-<agent>.pt
for a in agents:
torch.save(policies[a].state_dict(), f"{nn_save_dir}/policies/policy_{t}-{a}.pt")
# Evaluate the constraint value functions (these are essentially the "critics")
# Evaluate G_1^pi (the speed overage constraint)
# NOTE: Regardless if parameter sharing is being used or not, the output here is a dictionary that maps each agent to its constraint network
# when parameter sharing is being used, each network is identical (that does not mean each agent has identical constraint estimates)
G1_pi = FittedQEvaluation(observation_spaces,
action_spaces,
agents,
policies,
dataset,
csv_save_dir,
mean_constraint_suffixes[0], # Assumes order was [g1, g2]
config_args,
constraint="average-speed-limit")
# Save the value function every round
# Format is constraint_<round>-<agent>.pt
for a in agents:
torch.save(G1_pi[a].state_dict(), f"{nn_save_dir}/constraints/avg_speed_limit/constraint_{t}-{a}.pt")
# Evaluate G_2^pi
# NOTE: Regardless if parameter sharing is being used or not, the output here is a dictionary that maps each agent to its constraint network
# when parameter sharing is being used, each network is identical (that does not mean each agent has identical constraint estimates)
G2_pi = FittedQEvaluation(observation_spaces,
action_spaces,
agents,
policies,
dataset,
csv_save_dir,
mean_constraint_suffixes[1], # Assumes order was [g1, g2]
config_args,
constraint="queue")
# Save the value function every round
# Format is constraint_<round>-<agent>.pt
for a in agents:
torch.save(G2_pi[a].state_dict(), f"{nn_save_dir}/constraints/queue/constraint_{t}-{a}.pt")
# Calculate 1/t*(pi + t-1(E[pi])) for each agent
mean_policies = CalculateMeanPolicy(policies,
prev_mean_policies,
observation_spaces,
action_spaces,
agents,
t,
dataset,
csv_save_dir,
config_args)
# Save the mean policy each round
# Format is policy_<round>-<agent>.pt
for a in agents:
torch.save(mean_policies[a].state_dict(), f"{nn_save_dir}/policies/mean/policy_{t}-{a}.pt")
# Calculate 1/t*(g1 + t-1(E[g1])) for each agent
mean_g1_constraints = CalculateMeanConstraint(G1_pi,
prev_g1_constraints,
observation_spaces,
action_spaces,
agents,
t,
dataset,
csv_save_dir,
mean_constraint_suffixes[0], # Assumes order was [g1, g2]
config_args)
# Save the mean value function each round
# Format is constraint_<round>-<agent>.pt
for a in agents:
torch.save(mean_g1_constraints[a].state_dict(), f"{nn_save_dir}/constraints/avg_speed_limit/mean/constraint_{t}-{a}.pt")
# Calculate 1/t*(g2 + t-1(E[g2])) for each agent
mean_g2_constraints = CalculateMeanConstraint(G2_pi,
prev_g2_constraints,
observation_spaces,
action_spaces,
agents,
t,
dataset,
csv_save_dir,
mean_constraint_suffixes[1], # Assumes order was [g1, g2]
config_args)
# Save the mean value function each round
# Format is constraint_<round>-<agent>.pt
for a in agents:
torch.save(mean_g2_constraints[a].state_dict(), f"{nn_save_dir}/constraints/queue/mean/constraint_{t}-{a}.pt")
# Update mean networks for the next round
prev_mean_policies = mean_policies
prev_g2_constraints = mean_g2_constraints
prev_g1_constraints = mean_g1_constraints
# Perform offline rollouts using each value function and a small portion of the provided dataset
# NOTE: The returns here are dictionaries that map agents to their return
print(f" > EVALUATING G1_pi IN OFFLINE ROLLOUT")
g1_returns = OfflineRollout(G1_pi, policies, rollout_mini_dataset, device)
print(f" > EVALUATING G2_pi IN OFFLINE ROLLOUT")
g2_returns = OfflineRollout(G2_pi, policies, rollout_mini_dataset, device)
# Generate offline rollouts using the dataset policies as well so we can compare them to the current policy's results
print(f" > EVALUATING G1_pi IN OFFLINE ROLLOUT USING THRESHOLD POLICY")
offline_g1_returns_threshold_policy = OfflineRollout(G1_pi, dataset_policies[0], rollout_mini_dataset, device)
print(f" > EVALUATING G2_pi IN OFFLINE ROLLOUT USING THRESHOLD POLICY")
offline_g2_returns_threshold_policy = OfflineRollout(G2_pi, dataset_policies[0], rollout_mini_dataset, device)
print(f" > EVALUATING G1_pi IN OFFLINE ROLLOUT USING QUEUE POLICY")
offline_g1_returns_queue_policy = OfflineRollout(G1_pi, dataset_policies[1], rollout_mini_dataset, device)
print(f" > EVALUATING G2_pi IN OFFLINE ROLLOUT USING QUEUE POLICY")
offline_g2_returns_queue_policy = OfflineRollout(G2_pi, dataset_policies[1], rollout_mini_dataset, device)
# print(f" > OFFLINE ROLLOUT RESULTS:")
# print(f" > CURRENT POLICY G1_pi: {torch.sum(torch.tensor(list(g1_returns.values()))).detach().numpy()} ")
# print(f" > CURRENT POLICY G2_pi: {torch.sum(torch.tensor(list(g2_returns.values()))).detach().numpy()} ")
# print(f" > THRESHOLD POLICY G1_pi: {torch.sum(torch.tensor(list(offline_g1_returns_threshold_policy.values()))).detach().numpy()} ")
# print(f" > THRESHOLD POLICY G2_pi: {torch.sum(torch.tensor(list(offline_g2_returns_threshold_policy.values()))).detach().numpy()} ")
# print(f" > QUEUE POLICY G1_pi: {torch.sum(torch.tensor(list(offline_g1_returns_queue_policy.values()))).detach().numpy()} ")
# print(f" > QUEUE POLICY G2_pi: {torch.sum(torch.tensor(list(offline_g2_returns_queue_policy.values()))).detach().numpy()} ")
# NOTE: We are logging the lambda values produced by round X rather than the values used in
# round X
# Adjust lambda
if (t == 1):
# On the first round, use the normal lambda update because we need >2 rounds in order to calculate the lambda
# change rate
lambda_1, lambda_2, R_1, R_2 = OnlineLambdaLearning(lambda_1, lambda_2, g1_returns, g2_returns)
else:
# After the first round, use lambda change rate to update
lambda_1, lambda_2, R_1, R_2 = OnlineLambdaLearningByImprovementRate(lambda_1, lambda_2, g1_returns, g2_returns, R_1, R_2)
if (t > 1):
# On the first round, the expected value of lambda was set as the initial value of lambda
mean_lambda_1 = 1/t*(lambda_1 + ((t-1) * mean_lambda_1))
mean_lambda_2 = 1/t*(lambda_2 + ((t-1) * mean_lambda_2))
# Save the rollout returns and the updated lambdas
with open(f"{csv_save_dir}/rollouts.csv", "a", newline="") as csvfile:
csv_writer = csv.DictWriter(csvfile, fieldnames=['round'] +
[agent + '_return_g1' for agent in agents] +
['system_return_g1'] +
[agent + '_return_g2' for agent in agents] +
['system_return_g2'] +
[agent + '_threshold_policy_g1_return' for agent in agents] +
['threshold_policy_system_return_g1'] +
[agent + '_threshold_policy_g2_return' for agent in agents] +
['threshold_policy_system_return_g2'] +
[agent + '_queue_policy_g1_return' for agent in agents] +
['queue_policy_system_return_g1'] +
[agent + '_queue_policy_g2_return' for agent in agents] +
['queue_policy_system_return_g2'] +
['lambda_1', 'lambda_2', 'mean_lambda_1', 'mean_lambda_2'])
new_row = {}
new_row['round'] = t
for agent in agents:
new_row[agent + '_return_g1'] = g1_returns[agent].item()
new_row['system_return_g1'] = torch.sum(torch.tensor(list(g1_returns.values()))).detach().numpy() # TODO: update output of OfflineRollout to just be a dict rather than weird tensor thing
for agent in agents:
new_row[agent + '_return_g2'] = g2_returns[agent].item()
new_row['system_return_g2'] = torch.sum(torch.tensor(list(g2_returns.values()))).detach().numpy()
for agent in agents:
new_row[agent + '_threshold_policy_g1_return'] = offline_g1_returns_threshold_policy[agent].item()
new_row[agent + '_threshold_policy_g2_return'] = offline_g2_returns_threshold_policy[agent].item()
new_row[agent + '_queue_policy_g1_return'] = offline_g1_returns_queue_policy[agent].item()
new_row[agent + '_queue_policy_g2_return'] = offline_g2_returns_queue_policy[agent].item()
new_row['threshold_policy_system_return_g1'] = torch.sum(torch.tensor(list(offline_g1_returns_threshold_policy.values()))).detach().numpy()
new_row['threshold_policy_system_return_g2'] = torch.sum(torch.tensor(list(offline_g2_returns_threshold_policy.values()))).detach().numpy()
new_row['queue_policy_system_return_g1'] = torch.sum(torch.tensor(list(offline_g1_returns_queue_policy.values()))).detach().numpy()
new_row['queue_policy_system_return_g2'] = torch.sum(torch.tensor(list(offline_g2_returns_queue_policy.values()))).detach().numpy()
new_row['lambda_1'] = lambda_1
new_row['lambda_2'] = lambda_2
new_row['mean_lambda_1'] = mean_lambda_1
new_row['mean_lambda_2'] = mean_lambda_2
csv_writer.writerow({**new_row})
# Now run some online rollouts to compare performance between the learned policy and the dataset policies
print(f" > Performing online rollout for mean policy")
_, mean_policy_g1_return, mean_policy_g2_return = OnlineRollout(env, prev_mean_policies, config_args, device)
print(f" > Performing online rollout for current learned policy")
_, current_policy_g1_return, current_policy_g2_return = OnlineRollout(env, policies, config_args, device)
# TODO: make this more generic
threshold_policy = dataset_policies[0]
print(f" > Performing online rollout for average speed limit policy")
_, threshold_policy_g1_return, threshold_policy_g2_return = OnlineRollout(env, threshold_policy, config_args, device)
queue_policy = dataset_policies[1]
print(f" > Performing online rollout for queue policy")
_, queue_policy_g1_return, queue_policy_g2_return = OnlineRollout(env, queue_policy, config_args, device)
print(f" > Speed overage policy system g1 return: {sum(threshold_policy_g1_return.values())}")
print(f" > Speed overage policy system g2 return: {sum(threshold_policy_g2_return.values())}")
print(f" > Queue policy system g1 return: {sum(queue_policy_g1_return.values())}")
print(f" > Queue policy system g2 return: {sum(queue_policy_g2_return.values())}")
# Log the online rollout results
with open(f"{csv_save_dir}/online_rollouts.csv", "a", newline="") as csvfile:
csv_writer = csv.DictWriter(csvfile, fieldnames=['round'] +
[agent + '_mean_policy_g1_return' for agent in agents] +
['mean_policy_system_return_g1'] +
[agent + '_mean_policy_g2_return' for agent in agents] +
['mean_policy_system_return_g2'] +
[agent + '_current_policy_g1_return' for agent in agents] +
['current_policy_system_return_g1'] +
[agent + '_current_policy_g2_return' for agent in agents] +
['current_policy_system_return_g2'] +
[agent + '_threshold_policy_g1_return' for agent in agents] +
['threshold_policy_system_return_g1'] +
[agent + '_threshold_policy_g2_return' for agent in agents] +
['threshold_policy_system_return_g2'] +
[agent + '_queue_policy_g1_return' for agent in agents] +
['queue_policy_system_return_g1'] +
[agent + '_queue_policy_g2_return' for agent in agents] +
['queue_policy_system_return_g2'])
new_row = {}
new_row['round'] = t
for agent in agents:
new_row[agent + '_mean_policy_g1_return'] = mean_policy_g1_return[agent]
new_row[agent + '_mean_policy_g2_return'] = mean_policy_g2_return[agent]
new_row[agent + '_current_policy_g1_return'] = current_policy_g1_return[agent]
new_row[agent + '_current_policy_g2_return'] = current_policy_g2_return[agent]
new_row[agent + '_threshold_policy_g1_return'] = threshold_policy_g1_return[agent]
new_row[agent + '_threshold_policy_g2_return'] = threshold_policy_g2_return[agent]
new_row[agent + '_queue_policy_g1_return'] = queue_policy_g1_return[agent]
new_row[agent + '_queue_policy_g2_return'] = queue_policy_g2_return[agent]
new_row['mean_policy_system_return_g1'] = sum(mean_policy_g1_return.values())
new_row['mean_policy_system_return_g2'] = sum(mean_policy_g2_return.values())
new_row['current_policy_system_return_g1'] = sum(current_policy_g1_return.values())
new_row['current_policy_system_return_g2'] = sum(current_policy_g2_return.values())
new_row['threshold_policy_system_return_g1'] = sum(threshold_policy_g1_return.values())
new_row['threshold_policy_system_return_g2'] = sum(threshold_policy_g2_return.values())
new_row['queue_policy_system_return_g1'] = sum(queue_policy_g1_return.values())
new_row['queue_policy_system_return_g2'] = sum(queue_policy_g2_return.values())
csv_writer.writerow({**new_row})
# Capture the round execution time
round_completeion_time = datetime.now()
print(f" >> Round {t} of {max_num_rounds} complete!")
print(f" >> Round execution time: {round_completeion_time-round_start_time}")
function_stop_time = datetime.now()
print(f" > Batch offline reinforcement learning complete")
print(f" > Total execution time: {function_stop_time-function_start_time}")
lambdas = [lambda_1, lambda_2]
mean_lambdas = [mean_lambda_1, mean_lambda_2]
return mean_policies, policies, mean_lambdas, lambdas
def CalculateMeanPolicy(latest_learned_policy:dict,
previous_mean_policy:dict,
observation_spaces:dict,
action_spaces:dict,
agents:list,
round:int,
dataset:dict,
csv_save_dir:str,
config_args) -> dict:
"""
Calculate the "mean" policy using the the previous mean policy and the last learned policy
:param latest_learned_policy: Dictionary of policies that was just learned during this round
:param previous_mean_policy: The previously learned mean policy (i.e. the output of this function from the last round)
:param observation_spaces: Dictionary that maps agents to observations spaces
:param action_spaces: Dictionary that maps agents to action spaces
:param agents: List of agents in the environmnet
:param round: The current round of batch offline RL being performed
:param dataset: Dictionary that maps agents to a collection of experience tuples
:param csv_save_dir: Path to the directory being used to store CSV files for this experiment
:param config_args: Config arguments used to set up the experiment
:returns a Dictionary that maps each agent to its expectation E_t[pi] = 1/t*(pi_t + (t-1)*E_t-1[pi])
"""
print(f" >> Evaluating Mean Policy")
start_time = datetime.now()
losses = {agent: None for agent in agents} # Dictionary that maps each agent to the loss values for its network
num_agents = len(agents)
eg_agent = agents[0]
if config_args.parameter_sharing_model:
# Create a single network for the mean policy
if config_args.global_obs:
observation_space_shape = tuple((shape+1) * (num_agents) for shape in observation_spaces[eg_agent].shape)
else:
observation_space_shape = np.array(observation_spaces[eg_agent].shape).prod() + num_agents
mean_policy = Actor(observation_space_shape, action_spaces[eg_agent].n).to(device)
optimizer = optim.Adam(mean_policy.parameters(), lr=config_args.learning_rate)
else:
# Create a separate policy network for each agent
mean_policy = {} # Dictionary that maps agents to the "mean" policy for this round
optimizer = {} # Dictionary for storing optimizer for each agent's network
for agent in agents:
observation_space_shape = tuple(shape * num_agents for shape in observation_spaces[agent].shape) if config_args.global_obs else observation_spaces[agent].shape
mean_policy[agent] = Actor(observation_space_shape, action_spaces[agent].n).to(device)
# Initialize the mean policy using the previous one
mean_policy[agent].load_state_dict(previous_mean_policy[agent].state_dict())
optimizer[agent] = optim.Adam(mean_policy[agent].parameters(), lr=config_args.learning_rate) # All agents use the same optimizer for training
loss_fn = nn.MSELoss() # TODO: should this be MSE or Cross Entropy?
# For k = 1:K
for global_step in range(config_args.total_timesteps):
if (global_step % config_args.train_frequency == 0):
if config_args.parameter_sharing_model:
# Agent is randomly selected to be used for calculating the Q values and targets
random_agent = random.choice(agents)
# Sample data from the dataset
# NOTE: when using parameter sharing, the observations here should already have
# one hot encoding applied
s_obses, s_actions, s_next_obses, s_g1s, s_g2s, s_dones = dataset[random_agent].sample(config_args.batch_size)
with torch.no_grad():
# NOTE: when using parameter sharing, the latest_learned_policy dict should contain the same network
# for each agent (same for the previous_mean_policy)
# Get the action probability distribution from the latest learned policy
_, _, latest_learned_policy_probs = latest_learned_policy[random_agent].get_action(s_obses)
# Get the action probability distribution from the last mean policy
_, _, prev_mean_policy_probs = previous_mean_policy[random_agent].get_action(s_obses)
# Compute the target
target = 1/round*(latest_learned_policy_probs + (round - 1.0) * prev_mean_policy_probs)
# Get the action probability distribution from the previous state of the mean policy
_, _, old_policy_probs = mean_policy.get_action(s_obses)
# Calculate the loss between the "old" mean policy and the target
loss = loss_fn(target, old_policy_probs) # TODO: discuss loss function with chihui
losses[random_agent] = loss.item()
# Optimize the model
optimizer.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(list(mean_policy.parameters()), config_args.max_grad_norm)
optimizer.step()
else:
# No parameter sharing so need to train each agent
for agent in agents:
# Sample data from the dataset
s_obses, s_actions, s_next_obses, s_g1s, s_g2s, s_dones = dataset[agent].sample(config_args.batch_size)
with torch.no_grad():
# Get the action probability distribution from the latest learned policy
_, _, latest_learned_policy_probs = latest_learned_policy[agent].get_action(s_obses)
# Get the action probability distribution from the last mean policy
_, _, prev_mean_policy_probs = previous_mean_policy[agent].get_action(s_obses)
# Compute the target
target = 1/round*(latest_learned_policy_probs + (round - 1.0) * prev_mean_policy_probs)
# Get the action probability distribution from the previous state of the mean policy
_, _, old_policy_probs = mean_policy[agent].get_action(s_obses)
# Calculate the loss between the "old" mean policy and the target
loss = loss_fn(target, old_policy_probs) # TODO: discuss loss function with chihui
losses[agent] = loss.item()
# Optimize the model
optimizer[agent].zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(list(mean_policy[agent].parameters()), config_args.max_grad_norm)
optimizer[agent].step()
# Periodically log data to CSV
if (global_step % 1000 == 0):
with open(f"{csv_save_dir}/mean_policy_loss.csv", "a", newline="") as csvfile:
csv_writer = csv.DictWriter(csvfile, fieldnames=agents + ['global_step', 'round'])
csv_writer.writerow({**losses, **{'global_step' : global_step, 'round' : round}})
stop_time = datetime.now()
print(" >> Mean policy evaluation complete")
print(" >>> Total execution time: {}".format(stop_time-start_time))
# If we're using parameter sharing, there is only a single network so to conform to the rest of the code, return a dictionary that maps
# each agent to it's policy network
if config_args.parameter_sharing_model:
mean_policy = {agent: mean_policy for agent in agents}
return mean_policy
def CalculateMeanConstraint(latest_learned_constraint:dict,
previous_mean_constraint:dict,
observation_spaces:dict,
action_spaces:dict,
agents:list,
round:int,
dataset:dict,
csv_save_dir:str,
csv_file_suffix:str,
config_args) -> dict:
"""
Calculate the "mean" constraint value function using the previous mean constraint value function and the last
learned constraint value function
:param latest_learned_constraint: Dictionary of constraint value functions that was just learned during this round
:param previous_mean_constraint: The previously learned constraint value function (i.e. the output of this function from the last round)
:param observation_spaces: Dictionary that maps agents to observations spaces
:param action_spaces: Dictionary that maps agents to action spaces
:param agents: List of agents in the environmnet
:param round: The current round of batch offline RL being performed
:param dataset: Dictionary that maps agents to a collection of experience tuples
:param csv_save_dir: Path to the directory being used to store CSV files for this experiment
:param csv_file_suffix: String to append to the name of the csv file to differentiate between which mean constraint value function is being evaluated
:param config_args: Config arguments used to set up the experiment
:returns a Dictionary that maps each agent to its expectation E_t[g] = 1/t*(g_t + (t-1)*E_t-1[g])
"""
print(f" > Evaluating Mean Constraint: '{csv_file_suffix}'")
start_time = datetime.now()
losses = {agent: None for agent in agents} # Dictionary that maps each agent to the loss values for its network
num_agents = len(agents)
eg_agent = agents[0]
if config_args.parameter_sharing_model:
# Create a single network for the mean policy
if config_args.global_obs:
observation_space_shape = tuple((shape+1) * (num_agents) for shape in observation_spaces[eg_agent].shape)
else:
observation_space_shape = np.array(observation_spaces[eg_agent].shape).prod() + num_agents
mean_constraint = QNetwork(observation_space_shape, action_spaces[eg_agent].n).to(device)
optimizer = optim.Adam(mean_constraint.parameters(), lr=config_args.learning_rate)
else:
mean_constraint = {} # Dictionary that maps agents to the "mean" constraint value function for this round
optimizer = {} # Dictionary for storing optimizer for each agent's network
for agent in agents:
observation_space_shape = tuple(shape * num_agents for shape in observation_spaces[agent].shape) if config_args.global_obs else observation_spaces[agent].shape
mean_constraint[agent] = QNetwork(observation_space_shape, action_spaces[agent].n).to(device)
# Initialize the mean policy using the previous one
mean_constraint[agent].load_state_dict(previous_mean_constraint[agent].state_dict())
optimizer[agent] = optim.Adam(mean_constraint[agent].parameters(), lr=config_args.learning_rate) # All agents use the same optimizer for training
losses[agent] = None
loss_fn = nn.MSELoss() # TODO: should this be MSE or Cross Entropy?
# For k = 1:K
for global_step in range(config_args.total_timesteps):
# TODO: remove?
if (global_step % config_args.train_frequency == 0):
if config_args.parameter_sharing_model:
# Agent is randomly selected to be used for calculating the Q values and targets
random_agent = random.choice(agents)
# Sample data from the dataset
# NOTE: when using parameter sharing, the observations here should already have
# one hot encoding applied
s_obses, s_actions, s_next_obses, s_g1s, s_g2s, s_dones = dataset[random_agent].sample(config_args.batch_size)
with torch.no_grad():
# NOTE: when using parameter sharing, the latest_learned_constraint dict should contain the same network
# for each agent (same for the previous_mean_constraint)
# Get the action probability distribution from the latest learned value function
q_values_latest = latest_learned_constraint[random_agent].forward(s_obses).gather(1, torch.LongTensor(s_actions).view(-1,1).to(device)).squeeze()
# Get the action probability distribution from the last mean value function
q_values_prev_mean = previous_mean_constraint[random_agent].forward(s_obses).gather(1, torch.LongTensor(s_actions).view(-1,1).to(device)).squeeze()
# Compute the target
target = 1/round*(q_values_latest + (round - 1.0) * q_values_prev_mean)
# Get the action probability distribution from the previous state of the mean policy
old_val = mean_constraint.forward(s_obses).gather(1, torch.LongTensor(s_actions).view(-1,1).to(device)).squeeze()
# Compute loss
loss = loss_fn(target, old_val)
losses[random_agent] = loss.item()
# Optimize the model
optimizer.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(list(mean_constraint.parameters()), config_args.max_grad_norm)
optimizer.step()
else:
# Training for each agent
for agent in agents:
# Sample data from the dataset
s_obses, s_actions, s_next_obses, s_g1s, s_g2s, s_dones = dataset[agent].sample(config_args.batch_size)
with torch.no_grad():
# Get the action probability distribution from the latest learned value function
q_values_latest = latest_learned_constraint[agent].forward(s_obses).gather(1, torch.LongTensor(s_actions).view(-1,1).to(device)).squeeze()
# Get the action probability distribution from the last mean value function
q_values_prev_mean = previous_mean_constraint[agent].forward(s_obses).gather(1, torch.LongTensor(s_actions).view(-1,1).to(device)).squeeze()
# Compute the target
target = 1/round*(q_values_latest + (round - 1.0) * q_values_prev_mean)
# Get the action probability distribution from the previous state of the mean policy
old_val = mean_constraint[agent].forward(s_obses).gather(1, torch.LongTensor(s_actions).view(-1,1).to(device)).squeeze()
# Compute loss
loss = loss_fn(target, old_val)
losses[agent] = loss.item()
# Optimize the model
optimizer[agent].zero_grad()
loss.backward()