Repository navigation
Expand file tree
/
Copy pathdd_ppo.py
More file actions
1351 lines (1221 loc) · 63.2 KB
/
Copy pathdd_ppo.py
File metadata and controls
1351 lines (1221 loc) · 63.2 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
'''
Self-contained PPO training algorithm. Adapted from CleanRL https://github.com/vwxyzjn/cleanrl
'''
import argparse
import os
import random
import time
import pathlib
import re
import gc
import datetime
import math
from collections import deque
import torch
from torch import nn
import torch.nn.functional as F
from torch import optim
from tensorboardX import SummaryWriter
from tqdm import tqdm
import gymnasium as gym
from gymnasium.envs.registration import register
import numpy as np
import wandb
import jsonpickle
import jsonpickle.ext.numpy as jsonpickle_numpy
from pytictoc import TicToc
import zmq
from model import PPOPolicy
from rl_config import GlobalConfig
from birds_eye_view.bev_observation import image_to_class_labels
import rl_utils as rl_u
jsonpickle_numpy.register_handlers()
jsonpickle.set_encoder_options('json', sort_keys=True, indent=4)
torch.set_num_threads(1)
def strtobool(v):
return str(v).lower() in ('yes', 'y', 'true', 't', '1', 'True')
def none_or_str(value):
if value == 'None':
return None
return value
def save(model, optimizer, config, folder, model_file, optimizer_file):
model_file = os.path.join(folder, model_file)
torch.save(model.module.state_dict(), model_file)
if optimizer is not None:
optimizer_file = os.path.join(folder, optimizer_file)
torch.save(optimizer.state_dict(), optimizer_file)
json_config = jsonpickle.encode(config)
with open(os.path.join(folder, 'config.json'), 'wt', encoding='utf-8') as f2:
f2.write(json_config)
def parse_args(config):
# fmt: off
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('--rdzv_addr', default='localhost', type=str, help='Master address for the TCP store.')
parser.add_argument('--exp_name', type=str, default=config.exp_name, help='the name of this experiment')
parser.add_argument('--gym_id', type=str, default=config.gym_id, help='the id of the gym environment')
parser.add_argument('--tcp_store_port', type=int, required=True, help='port for the key value store')
parser.add_argument('--learning_rate',
type=float,
default=config.learning_rate,
help='the learning rate of the optimizer')
parser.add_argument('--seed', type=int, default=config.seed, help='seed of the experiment')
parser.add_argument('--total_timesteps',
type=int,
default=config.total_timesteps,
help='total timesteps of the experiments')
parser.add_argument('--torch_deterministic',
type=lambda x: bool(strtobool(x)),
default=config.torch_deterministic,
nargs='?',
const=True,
help='if toggled, `torch.backends.cudnn.deterministic=False`')
parser.add_argument('--allow_tf32',
type=lambda x: bool(strtobool(x)),
default=config.allow_tf32,
nargs='?',
const=True,
help='whether to use tensor cores, lower numeric precision but faster speed')
parser.add_argument('--benchmark',
type=lambda x: bool(strtobool(x)),
default=config.benchmark,
nargs='?',
const=True,
help='Whether to benchmark different algorithms on hardware to find the fastest')
parser.add_argument('--matmul_precision',
type=str,
default=config.matmul_precision,
help=' Options highest=float32, high=tf32, medium=bfloat16')
parser.add_argument('--cuda',
type=lambda x: bool(strtobool(x)),
default=config.cuda,
nargs='?',
const=True,
help='if toggled, cuda will be enabled by default')
parser.add_argument('--track',
type=lambda x: bool(strtobool(x)),
default=config.track,
nargs='?',
const=True,
help='if toggled, this experiment will be tracked with Weights and Biases')
parser.add_argument('--wandb_project_name',
type=str,
default=config.wandb_project_name,
help='the wandb project name')
parser.add_argument('--wandb_entity',
type=str,
default=config.wandb_entity,
help='the entity (team) of wandb project')
parser.add_argument('--capture_video',
type=lambda x: bool(strtobool(x)),
default=config.capture_video,
nargs='?',
const=True,
help='whether to capture videos of the agent performances (check out `videos` folder)')
# Algorithm specific arguments
parser.add_argument('--total_batch_size',
type=int,
default=config.total_batch_size,
help='the total amount of data collected at every step across all environments')
parser.add_argument('--total_minibatch_size',
type=int,
default=config.total_minibatch_size,
help='the total minibatch sized used for training (across all environments)')
parser.add_argument('--lr_schedule',
default=config.lr_schedule,
type=str,
help='Which lr schedule to use. Options: (linear, kl, none, step, cosine, cosine_restart)')
parser.add_argument('--gae',
type=lambda x: bool(strtobool(x)),
default=config.gae,
nargs='?',
const=True,
help='Use GAE for advantage computation')
parser.add_argument('--gamma', type=float, default=config.gamma, help='the discount factor gamma')
parser.add_argument('--gae_lambda',
type=float,
default=config.gae_lambda,
help='the lambda for the general advantage estimation')
parser.add_argument('--update_epochs',
type=int,
default=config.update_epochs,
help='the K epochs to update the policy')
parser.add_argument('--norm_adv',
type=lambda x: bool(strtobool(x)),
default=config.norm_adv,
nargs='?',
const=True,
help='Toggles advantages normalization')
parser.add_argument('--clip_coef', type=float, default=config.clip_coef, help='the surrogate clipping coefficient')
parser.add_argument('--clip_vloss',
type=lambda x: bool(strtobool(x)),
default=config.clip_vloss,
nargs='?',
const=True,
help='Toggles whether or not to use a clipped loss for the value function, as per the paper.')
parser.add_argument('--ent_coef', type=float, default=config.ent_coef, help='coefficient of the entropy')
parser.add_argument('--vf_coef', type=float, default=config.vf_coef, help='coefficient of the value function')
parser.add_argument('--max_grad_norm',
type=float,
default=config.max_grad_norm,
help='the maximum norm for the gradient clipping')
parser.add_argument('--target_kl', type=float, default=config.target_kl, help='the target KL divergence threshold')
parser.add_argument('--visualize',
type=lambda x: bool(strtobool(x)),
default=config.visualize,
nargs='?',
const=True,
help='if toggled, Game will render on screen')
parser.add_argument('--logdir', type=str, default=config.logdir, help='The directory to log the data into.')
parser.add_argument('--load_file',
type=none_or_str,
nargs='?',
default=config.load_file,
help='model weights for initialization')
parser.add_argument('--ports',
nargs='+',
default=config.ports,
type=int,
help='Ports of the carla_gym wrapper to connect to.'
'It requires to submit a port for every envs'
'#ports == --nproc_per_node')
parser.add_argument('--gpu_ids',
nargs='+',
default=config.gpu_ids,
type=int,
help='Which GPUs to train on. Index 0 indicates GPU for rank 0 etc.')
parser.add_argument('--num_envs_per_proc',
type=int,
default=config.num_envs_per_proc,
help='Number of environments per process. Only considered for dd_ppo.py')
parser.add_argument('--compile_model',
type=lambda x: bool(strtobool(x)),
default=config.compile_model,
nargs='?',
const=True,
help='whether to compile the model with torch.compile.')
parser.add_argument('--expl_coef', type=float, default=config.expl_coef, help='coefficient of the exploration')
parser.add_argument('--adam_eps', type=float, default=config.adam_eps, help='eps parameter of adam optimizer')
parser.add_argument('--cpu_collect',
type=lambda x: bool(strtobool(x)),
default=config.cpu_collect,
nargs='?',
const=True,
help='If true than the agent will be run on the cpu during data collection. Can be faster.')
parser.add_argument('--use_exploration_suggest',
type=lambda x: bool(strtobool(x)),
default=config.use_exploration_suggest,
nargs='?',
const=True,
help='Whether to use the exploration loss from roach.')
parser.add_argument('--use_speed_limit_as_max_speed',
type=lambda x: bool(strtobool(x)),
default=config.use_speed_limit_as_max_speed,
nargs='?',
const=True,
help='If true rr_maximum_speed will be overwritten to the current speed limit affecting the ego '
'vehicle.')
parser.add_argument('--beta_min_a_b_value',
type=float,
default=config.beta_min_a_b_value,
help='Nugget that gets added to the softplus output of the network.'
'Aims to prevent degenerate distributions with the Beta.')
parser.add_argument('--use_rpo',
type=lambda x: bool(strtobool(x)),
default=config.use_rpo,
nargs='?',
const=True,
help='Whether to use robust policy optimization (add noise to mean during training)')
parser.add_argument('--rpo_alpha',
type=float,
default=config.rpo_alpha,
help='Noise added during training is of uniform shape [-rpo_alpha, rpo_alpha]')
parser.add_argument('--use_new_bev_obs',
type=lambda x: bool(strtobool(x)),
default=config.use_new_bev_obs,
nargs='?',
const=True,
help='Whether to use the new bev observation or the old roach one.')
parser.add_argument('--obs_num_channels',
type=int,
default=config.obs_num_channels,
help='Number of channels is the BEV image.')
parser.add_argument('--map_folder',
type=str,
default=config.map_folder,
help='The map folder to use with the new representation. Needs to align with pixels_per_meter')
parser.add_argument('--pixels_per_meter',
type=float,
default=config.pixels_per_meter,
help='Pixels per meter in the new BEV image.')
parser.add_argument('--route_width',
type=int,
default=config.route_width,
help='Width of the rendered route in pixel. Only affects new obs.')
parser.add_argument('--reward_type',
type=str,
default=config.reward_type,
help='Reward function to be used during training. Options: roach, simple_reward')
parser.add_argument('--consider_tl',
type=lambda x: bool(strtobool(x)),
default=config.consider_tl,
nargs='?',
const=True,
help='If set to false traffic light infractions are turned off. Used in simple reward')
parser.add_argument('--eval_time', type=float, default=config.eval_time, help='Time until the model times out.')
parser.add_argument('--terminal_reward',
type=float,
default=config.terminal_reward,
help='Time until the model times out.')
parser.add_argument('--normalize_rewards',
type=lambda x: bool(strtobool(x)),
default=config.normalize_rewards,
nargs='?',
const=True,
help=' Whether to use gymnasiums reward normalization.')
parser.add_argument('--speeding_infraction',
type=lambda x: bool(strtobool(x)),
default=config.speeding_infraction,
nargs='?',
const=True,
help='Whether to terminate the route if the agent drives too fast. Only simple reward.')
parser.add_argument('--min_thresh_lat_dist',
type=float,
default=config.min_thresh_lat_dist,
help='Time until the model times out.')
parser.add_argument('--num_route_points_rendered',
type=int,
default=config.num_route_points_rendered,
help='Number of route points rendered into the BEV seg observation.')
parser.add_argument('--use_green_wave',
type=lambda x: bool(strtobool(x)),
default=config.use_green_wave,
nargs='?',
const=True,
help='If True in some routes all TL that the agent encounters are set to green.')
parser.add_argument('--image_encoder',
type=str,
default=config.image_encoder,
help='Which image cnn encoder to use. Either roach, roach_ln, or timm model name')
parser.add_argument('--use_comfort_infraction',
type=lambda x: bool(strtobool(x)),
default=config.use_comfort_infraction,
nargs='?',
const=True,
help='Whether to apply a soft penalty if comfort limits are exceeded.')
parser.add_argument('--use_layer_norm',
type=lambda x: bool(strtobool(x)),
default=config.use_layer_norm,
nargs='?',
const=True,
help='Whether to use LayerNorm before ReLU in MLPs.')
parser.add_argument('--use_vehicle_close_penalty',
type=lambda x: bool(strtobool(x)),
default=config.use_vehicle_close_penalty,
nargs='?',
const=True,
help='Whether to use a penalty for being too close to the front vehicle.')
parser.add_argument('--render_green_tl',
type=lambda x: bool(strtobool(x)),
default=config.render_green_tl,
nargs='?',
const=True,
help='Whether to render green traffic lights into the observation.')
parser.add_argument('--distribution',
type=str,
default=config.distribution,
help='Distribution used for the action space. Options beta, normal, beta_uni_mix')
parser.add_argument('--weight_decay',
type=float,
default=config.weight_decay,
help='Weight decay applied to optimizer. AdamW is used when > 0.0')
parser.add_argument('--use_dd_ppo_preempt',
type=lambda x: bool(strtobool(x)),
default=config.use_dd_ppo_preempt,
nargs='?',
const=True,
help='Whether to use the dd-ppo preemption technique to early stop stragglers.')
parser.add_argument('--use_termination_hint',
type=lambda x: bool(strtobool(x)),
default=config.use_termination_hint,
nargs='?',
const=True,
help='Whether to give a penalty depending on vehicle speed when crashing or running red light.')
parser.add_argument('--use_perc_progress',
type=lambda x: bool(strtobool(x)),
default=config.use_perc_progress,
nargs='?',
const=True,
help='Whether to multiply RC reward by percentage away from lane center.')
parser.add_argument('--use_min_speed_infraction',
type=lambda x: bool(strtobool(x)),
default=config.use_min_speed_infraction,
nargs='?',
const=True,
help='Whether to penalize the agent for driving slower than other agents on avg.')
parser.add_argument('--use_leave_route_done',
type=lambda x: bool(strtobool(x)),
default=config.use_leave_route_done,
nargs='?',
const=True,
help='Whether to terminate the route when leaving the precomputed path.')
parser.add_argument('--use_temperature',
type=lambda x: bool(strtobool(x)),
default=config.use_temperature,
nargs='?',
const=True,
help='Whether to scale the output distribution values with a predicted temperature.')
parser.add_argument('--obs_num_measurements',
type=int,
default=config.obs_num_measurements,
help='Number of scalar measurements in observation.')
parser.add_argument('--use_extra_control_inputs',
type=lambda x: bool(strtobool(x)),
default=config.use_extra_control_inputs,
nargs='?',
const=True,
help='Whether to use extra control inputs such as integral of past steering.')
parser.add_argument('--condition_outside_junction',
type=lambda x: bool(strtobool(x)),
default=config.condition_outside_junction,
nargs='?',
const=True,
help=' Whether to render the route outside junctions.')
parser.add_argument('--use_layer_norm_policy_head',
type=lambda x: bool(strtobool(x)),
default=config.use_layer_norm_policy_head,
nargs='?',
const=True,
help='Applicable if use_layer_norm=True, whether to also apply layernorm to the policy head.'
'Can be useful to remove to allow the policy to predict large values (for a, b of Beta).')
parser.add_argument('--use_hl_gauss_value_loss',
type=lambda x: bool(strtobool(x)),
default=config.use_hl_gauss_value_loss,
nargs='?',
const=True,
help='Whether to use the histogram loss gauss to train the value head via classification '
'(instead of regression + L2)')
parser.add_argument('--use_outside_route_lanes',
type=lambda x: bool(strtobool(x)),
default=config.use_outside_route_lanes,
nargs='?',
const=True,
help='Whether to terminate the route when invading opposing lanes or sidewalks.')
parser.add_argument('--use_max_change_penalty',
type=lambda x: bool(strtobool(x)),
default=config.use_max_change_penalty,
nargs='?',
const=True,
help='Whether to apply a soft penalty when the action changes too fast.')
parser.add_argument('--use_lstm',
type=lambda x: bool(strtobool(x)),
default=config.use_lstm,
nargs='?',
const=True,
help=' Whether to use an LSTM after the feature encoder.')
parser.add_argument('--terminal_hint',
type=float,
default=config.terminal_hint,
help='Reward at the end of the episode when colliding, the number will be subtracted.')
parser.add_argument('--penalize_yellow_light',
type=lambda x: bool(strtobool(x)),
default=config.penalize_yellow_light,
nargs='?',
const=True,
help='Whether to penalize running a yellow light.')
parser.add_argument('--use_target_point',
type=lambda x: bool(strtobool(x)),
default=config.use_target_point,
nargs='?',
const=True,
help='Whether to input a target point in the measurements.')
parser.add_argument('--use_value_measurements',
type=lambda x: bool(strtobool(x)),
default=config.use_value_measurements,
nargs='?',
const=True,
help='Whether to use value measurements (otherwise all are set to 0)')
parser.add_argument('--bev_semantics_width',
type=int,
default=config.bev_semantics_width,
help='Numer of pixels the bev_semantics is wide')
parser.add_argument('--bev_semantics_height',
type=int,
default=config.bev_semantics_height,
help='Numer of pixels the bev_semantics is high')
parser.add_argument('--pixels_ev_to_bottom',
type=int,
default=config.pixels_ev_to_bottom,
help='Numer of pixels from the vehicle to the bottom.')
parser.add_argument('--use_history',
type=lambda x: bool(strtobool(x)),
default=config.use_history,
nargs='?',
const=True,
help='Whether to use historic vehicle and pedestrian observations in BEV obs')
parser.add_argument('--use_off_road_term',
type=lambda x: bool(strtobool(x)),
default=config.use_off_road_term,
nargs='?',
const=True,
help='Whether to terminate when the agent drives off the drivable area')
parser.add_argument('--off_road_term_perc',
type=float,
default=config.off_road_term_perc,
help='Percentage of agent overlap with off-road, that triggers the termination')
parser.add_argument('--beta_1', type=float, default=config.beta_1, help='Beta 1 parameter of adam')
parser.add_argument('--beta_2', type=float, default=config.beta_2, help='Beta 2 parameter of adam')
parser.add_argument('--render_speed_lines',
type=lambda x: bool(strtobool(x)),
default=config.render_speed_lines,
nargs='?',
const=True,
help='Whether to render the speed lines for moving objects')
parser.add_argument('--use_new_stop_sign_detector',
type=lambda x: bool(strtobool(x)),
default=config.use_new_stop_sign_detector,
nargs='?',
const=True,
help='Whether to use a different stop sign detector that prevents the policy from cheating by '
'changing lanes.')
parser.add_argument('--use_positional_encoding',
type=lambda x: bool(strtobool(x)),
default=config.use_positional_encoding,
nargs='?',
const=True,
help='Whether to add positional encoding to the image')
parser.add_argument('--use_ttc',
type=lambda x: bool(strtobool(x)),
default=config.use_ttc,
nargs='?',
const=True,
help='Whether to use TTC in the reward.')
parser.add_argument('--num_value_measurements',
type=int,
default=config.num_value_measurements,
help='Number of measurements exclusive to the value head.')
parser.add_argument('--render_yellow_time',
type=lambda x: bool(strtobool(x)),
default=config.render_yellow_time,
nargs='?',
const=True,
help='Whether to indicate the remaining time to red in yellow light rendering.')
parser.add_argument('--use_single_reward',
type=lambda x: bool(strtobool(x)),
default=config.use_single_reward,
nargs='?',
const=True,
help='Whether to only use RC als reward source in simple reward')
parser.add_argument('--use_rl_termination_hint',
type=lambda x: bool(strtobool(x)),
default=config.use_rl_termination_hint,
nargs='?',
const=True,
help='Whether to include rl infraction for termination hints')
parser.add_argument('--render_shoulder',
type=lambda x: bool(strtobool(x)),
default=config.render_shoulder,
nargs='?',
const=True,
help='Whether to render shoulder lanes as roads.')
parser.add_argument('--use_shoulder_channel',
type=lambda x: bool(strtobool(x)),
default=config.use_shoulder_channel,
nargs='?',
const=True,
help='Whether to use an extra channel for shoulder lanes.')
parser.add_argument('--lane_distance_violation_threshold',
type=float,
default=config.lane_distance_violation_threshold,
help='Grace distance in m at which no lane perc penalty is applied')
parser.add_argument('--lane_dist_penalty_softener',
type=float,
default=config.lane_dist_penalty_softener,
help='If smaller than 1 reduces lane distance penalty')
parser.add_argument('--comfort_penalty_factor',
type=float,
default=config.comfort_penalty_factor,
help='Max comfort penalty if all comfort metrics are violated.')
parser.add_argument('--use_survival_reward',
type=lambda x: bool(strtobool(x)),
default=config.use_survival_reward,
nargs='?',
const=True,
help='Whether to add a constant reward every frame')
args, unknown = parser.parse_known_args()
print('Unkown Arguments', unknown)
# fmt: on
return args
def make_env(gym_id, args, run_name, port, config):
def thunk():
if args.visualize:
render_mode = 'human' # Only works well with num envs 1 right now
else:
render_mode = 'rgb_array'
env = gym.make(gym_id, port=port, config=config, render_mode=render_mode)
env = gym.wrappers.RecordEpisodeStatistics(env)
if args.capture_video:
env = gym.wrappers.RecordVideo(env, f'videos/{run_name}')
env = gym.wrappers.ClipAction(env)
if config.normalize_rewards:
env = gym.wrappers.NormalizeReward(env, gamma=config.gamma)
env = gym.wrappers.TransformReward(env, lambda reward: np.clip(reward, -10, 10))
return env
return thunk
def main():
register(
id='CARLAEnv-v0',
entry_point='env_gym:CARLAEnv',
max_episode_steps=None,
)
config = GlobalConfig()
args = parse_args(config)
# Torchrun initialization
# Use torchrun for starting because it has proper error handling. Local rank will be set automatically
rank = int(os.environ['RANK']) # Rank across all processes
local_rank = int(os.environ['LOCAL_RANK']) # Rank on Node
world_size = int(os.environ['WORLD_SIZE']) # Number of processes
print(f'RANK, LOCAL_RANK and WORLD_SIZE in environ: {rank}/{local_rank}/{world_size}')
local_batch_size = args.total_batch_size // world_size
local_bs_per_env = local_batch_size // args.num_envs_per_proc
local_minibatch_size = args.total_minibatch_size // world_size
num_minibatches = local_batch_size // local_minibatch_size
run_name = f'{args.gym_id}__{args.exp_name}__{args.seed}'
if rank == 0:
exp_folder = os.path.join(args.logdir, f'{args.exp_name}')
wandb_folder = os.path.join(exp_folder, 'wandb')
pathlib.Path(exp_folder).mkdir(parents=True, exist_ok=True)
pathlib.Path(wandb_folder).mkdir(parents=True, exist_ok=True)
if args.track:
wandb.init(
project=args.wandb_project_name,
entity=args.wandb_entity,
sync_tensorboard=True,
config=vars(args),
name=run_name,
monitor_gym=False,
allow_val_change=True,
save_code=False,
mode='online',
resume='auto',
dir=wandb_folder,
settings=wandb.Settings(_disable_stats=True, _disable_meta=True,
start_method='fork') # Can get large if we log all the cpu cores.
)
writer = SummaryWriter(exp_folder)
writer.add_text(
'hyperparameters',
'|param|value|\n|-|-|\n%s' % ('\n'.join([f'|{key}|{value}|' for key, value in vars(args).items()])),
)
# TRY NOT TO MODIFY: seeding
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
print('Is cuda available?:', torch.cuda.is_available())
# Load the config before overwriting values with current arguments
if args.load_file is not None:
load_folder = pathlib.Path(args.load_file).parent.resolve()
with open(os.path.join(load_folder, 'config.json'), 'rt', encoding='utf-8') as f:
json_config = f.read()
# 4 ms, might need to move outside the agent.
loaded_config = jsonpickle.decode(json_config)
# Overwrite all properties that were set in the saved config.
config.__dict__.update(loaded_config.__dict__)
# Configure config. Converts all arguments into config attributes
config.initialize(**vars(args))
if config.use_dd_ppo_preempt:
# Gloo is used for the parallelization strategy where multiple processes with 1 env run on 1 GPU because NCCL
# does not support this use case currently.
num_rollouts_done_store = torch.distributed.TCPStore(args.rdzv_addr, args.tcp_store_port, world_size, rank == 0)
torch.distributed.init_process_group(backend='gloo' if
(args.cpu_collect or args.num_envs_per_proc == 1) else 'nccl',
store=num_rollouts_done_store,
world_size=world_size,
rank=rank,
timeout=datetime.timedelta(minutes=45))
num_rollouts_done_store.set('num_done', '0')
print(f'Rank:{rank}, TCP_Store_Port: {args.tcp_store_port}')
else:
torch.distributed.init_process_group(backend='gloo' if
(args.cpu_collect or args.num_envs_per_proc == 1) else 'nccl',
init_method='env://',
world_size=world_size,
rank=rank,
timeout=datetime.timedelta(minutes=45))
device_id = args.gpu_ids[rank]
print(device_id)
if device_id < 0:
print('ERROR! Device id must be positive.')
device = torch.device(f'cuda:{args.gpu_ids[rank]}') if torch.cuda.is_available() and args.cuda else torch.device(
'cpu')
if torch.cuda.is_available() and args.cuda:
torch.cuda.device(device)
torch.backends.cudnn.deterministic = args.torch_deterministic
torch.backends.cuda.matmul.allow_tf32 = args.allow_tf32
torch.backends.cudnn.benchmark = args.benchmark
torch.backends.cudnn.allow_tf32 = args.allow_tf32
torch.set_float32_matmul_precision(args.matmul_precision)
if rank == 0:
json_config = jsonpickle.encode(config)
with open(os.path.join(exp_folder, 'config.json'), 'w', encoding='utf-8') as f2:
f2.write(json_config)
# NOTE: need to update the config with the argparse arguments before creating the gym environment because the gym env
# will make a copy of the config and send it to the carla leaderboard process.
# Sends the updated config to the different environments.
context = zmq.Context()
socket_list = [] # So that the garbage collector doesn't clean up sockets before we are done.
for i in range(args.num_envs_per_proc):
socket_list.append(context.socket(zmq.PAIR))
current_folder = pathlib.Path(__file__).parent.resolve()
comm_folder = os.path.join(current_folder, 'comm_files')
pathlib.Path(comm_folder).mkdir(parents=True, exist_ok=True)
communication_file = os.path.join(comm_folder, str(args.ports[args.num_envs_per_proc * local_rank + i]))
socket_list[i].bind(f'ipc://{communication_file}.conf_lock')
json_config = jsonpickle.encode(config)
socket_list[i].send_string(json_config)
_ = socket_list[i].recv_string()
socket_list[i].close()
context.term()
del socket_list
print(f'Rank {rank}, sent CONFIG files')
if args.num_envs_per_proc > 1:
env = gym.vector.AsyncVectorEnv([
make_env(args.gym_id, args, run_name, args.ports[args.num_envs_per_proc * local_rank + i], config)
for i in range(args.num_envs_per_proc)
])
else:
# We don't want to spawn subprocesses for a single environment, so we use Sync==Sequential Vector env.
env = gym.vector.SyncVectorEnv(
[make_env(args.gym_id, args, run_name, args.ports[args.num_envs_per_proc * local_rank + i], config)])
assert isinstance(env.single_action_space, gym.spaces.Box), 'only continuous action space is supported'
agent = PPOPolicy(env.single_observation_space, env.single_action_space, config=config).to(device)
if config.compile_model:
agent = torch.compile(agent)
start_step = 0
if args.load_file is not None:
load_file_name = os.path.basename(args.load_file)
algo_step = re.findall(r'\d+', load_file_name)
if len(algo_step) > 0:
start_step = int(algo_step[0]) + 1 # That step was already finished.
print('Start training from step:', start_step)
agent.load_state_dict(torch.load(args.load_file, map_location=device), strict=True)
print(f'Rank {rank}, START DistributedDataParallel')
agent = torch.nn.parallel.DistributedDataParallel(agent,
device_ids=None,
output_device=None,
broadcast_buffers=False,
find_unused_parameters=False)
print(f'Rank:{rank}, Created DistributedDataParallel')
# If we are resuming training use last learning rate from config.
# If we start a fresh training set the current learning rate according to arguments.
if args.load_file is None:
config.current_learning_rate = args.learning_rate
if rank == 0:
model_parameters = filter(lambda p: p.requires_grad, agent.parameters())
num_params = sum(np.prod(p.size()) for p in model_parameters)
print('Total trainable parameters: ', num_params)
if config.weight_decay > 0.0:
optimizer = optim.AdamW(agent.parameters(),
lr=config.current_learning_rate,
eps=config.adam_eps,
weight_decay=config.weight_decay,
betas=(config.beta_1, config.beta_2))
else:
optimizer = optim.Adam(agent.parameters(),
lr=config.current_learning_rate,
eps=config.adam_eps,
betas=(config.beta_1, config.beta_2))
print(f'Rank:{rank}, Created Optimizer')
# Load optimizer
if args.load_file is not None:
optimizer.load_state_dict(torch.load(args.load_file.replace('model_', 'optimizer_'), map_location=device))
print(f'Rank:{rank}, Load model')
if rank == 0:
writer.add_scalar('charts/restart', 1, config.global_step) # Log that a restart happened
if config.cpu_collect:
device = 'cpu'
# ALGO Logic: Storage setup
obs = {
'bev_semantics':
torch.zeros(
(local_bs_per_env, args.num_envs_per_proc) + env.single_observation_space.spaces['bev_semantics'].shape,
device=device,
dtype=torch.uint8),
'measurements':
torch.zeros(
(local_bs_per_env, args.num_envs_per_proc) + env.single_observation_space.spaces['measurements'].shape,
device=device),
'value_measurements':
torch.zeros((local_bs_per_env, args.num_envs_per_proc) +
env.single_observation_space.spaces['value_measurements'].shape,
device=device),
}
actions = torch.zeros((local_bs_per_env, args.num_envs_per_proc) + env.single_action_space.shape, device=device)
old_mus = torch.zeros((local_bs_per_env, args.num_envs_per_proc) + env.single_action_space.shape, device=device)
old_sigmas = torch.zeros((local_bs_per_env, args.num_envs_per_proc) + env.single_action_space.shape, device=device)
logprobs = torch.zeros((local_bs_per_env, args.num_envs_per_proc), device=device)
rewards = torch.zeros((local_bs_per_env, args.num_envs_per_proc), device=device)
dones = torch.zeros((local_bs_per_env, args.num_envs_per_proc), device=device)
values = torch.zeros((local_bs_per_env, args.num_envs_per_proc), device=device)
exp_n_steps = np.zeros((local_bs_per_env, args.num_envs_per_proc), dtype=np.int32)
exp_suggest = np.zeros((local_bs_per_env, args.num_envs_per_proc), dtype=np.int32)
# TRY NOT TO MODIFY: start the game
reset_obs = env.reset(seed=[args.seed + rank * args.num_envs_per_proc + i for i in range(args.num_envs_per_proc)])
next_obs = {
'bev_semantics': torch.tensor(reset_obs[0]['bev_semantics'], device=device, dtype=torch.uint8),
'measurements': torch.tensor(reset_obs[0]['measurements'], device=device, dtype=torch.float32),
'value_measurements': torch.tensor(reset_obs[0]['value_measurements'], device=device, dtype=torch.float32)
}
next_done = torch.zeros(args.num_envs_per_proc, device=device)
next_lstm_state = (
torch.zeros(config.num_lstm_layers, args.num_envs_per_proc, config.features_dim, device=device),
torch.zeros(config.num_lstm_layers, args.num_envs_per_proc, config.features_dim, device=device),
)
num_updates = args.total_timesteps // args.total_batch_size
local_processed_samples = 0
start_time = time.time()
# TODO This doesn't affect our agent, but it should probably be eval for data collection and train for training
agent.train()
if rank == 0:
avg_returns = deque(maxlen=100)
# from matplotlib import pyplot as plt
# pyplots = []
# fig = plt.figure(figsize=(config.obs_num_channels + 1, config.obs_num_channels + 1))
# for i in range(1, config.obs_num_channels + 1):
# fig.add_subplot(4, 4, i)
# pyplots.append(plt.imshow(np.zeros((192, 192)), cmap='gray', vmin=0, vmax=255))
# plt.show(block=False)
if config.use_hl_gauss_value_loss:
hl_gauss_bins = rl_u.hl_gaus_bins(config.hl_gauss_vmin, config.hl_gauss_vmax, config.hl_gauss_bucket_size, device)
print(f'Rank:{rank}, Created obs', flush=True)
for update in tqdm(range(start_step, num_updates), disable=rank != 0):
if config.cpu_collect:
device = 'cpu'
agent.to(device)
# Free all data from last interation.
gc.collect()
with torch.no_grad():
torch.cuda.empty_cache()
if config.use_dd_ppo_preempt:
num_rollouts_done_store.set('num_done', '0')
# Buffers we use to store returns and aggregate them later to rank 0 for logging.
total_returns = torch.zeros(world_size, device=device, dtype=torch.float32, requires_grad=False)
total_lengths = torch.zeros(world_size, device=device, dtype=torch.float32, requires_grad=False)
num_total_returns = torch.zeros(world_size, device=device, dtype=torch.int32, requires_grad=False)
if config.use_lstm:
initial_lstm_state = (next_lstm_state[0].clone(), next_lstm_state[1].clone())
# Annealing the rate if instructed to do so.
if config.lr_schedule == 'linear':
frac = 1.0 - (update - 1.0) / num_updates
config.current_learning_rate = frac * config.learning_rate
elif config.lr_schedule == 'step':
frac = update / num_updates
lr_multiplier = 1.0
for change_percentage in config.lr_schedule_step_perc:
if frac > change_percentage:
lr_multiplier *= config.lr_schedule_step_factor
config.current_learning_rate = lr_multiplier * config.learning_rate
elif config.lr_schedule == 'cosine':
frac = update / num_updates
config.current_learning_rate = 0.5 * config.learning_rate * (1 + math.cos(frac * math.pi))
elif config.lr_schedule == 'cosine_restart':
frac = update / (num_updates + 1) # + 1 so it doesn't become 100 %
for idx, frac_restart in enumerate(config.lr_schedule_cosine_restarts):
if frac >= frac_restart:
current_idx = idx
base_frac = config.lr_schedule_cosine_restarts[current_idx]
length_current_interval = (config.lr_schedule_cosine_restarts[current_idx + 1] -
config.lr_schedule_cosine_restarts[current_idx])
frac_current_iter = (frac - base_frac) / length_current_interval
config.current_learning_rate = 0.5 * config.learning_rate * (1 + math.cos(frac_current_iter * math.pi))
for param_group in optimizer.param_groups:
param_group['lr'] = config.current_learning_rate
t0 = TicToc() # Data collect
t1 = TicToc() # Forward pass
t2 = TicToc() # Env step
t3 = TicToc() # Pre-processing
t4 = TicToc() # Train inter
t5 = TicToc() # Logging
t0.tic()
inference_times = []
env_times = []
for step in range(0, local_bs_per_env):
config.global_step += 1 * world_size * args.num_envs_per_proc
local_processed_samples += 1 * world_size * args.num_envs_per_proc
obs['bev_semantics'][step] = next_obs['bev_semantics']
obs['measurements'][step] = next_obs['measurements']
obs['value_measurements'][step] = next_obs['value_measurements']
dones[step] = next_done
# ALGO LOGIC: action logic
with torch.no_grad():
t1.tic()
action, logprob, _, value, _, mu, sigma, _, _, _, next_lstm_state = agent.forward(next_obs,
lstm_state=next_lstm_state,
done=next_done)
if config.use_hl_gauss_value_loss:
value_pdf = F.softmax(value, dim=1)
value = torch.sum(value_pdf * hl_gauss_bins.unsqueeze(0), dim=1)
inference_times.append(t1.tocvalue())
values[step] = value.flatten()
actions[step] = action
logprobs[step] = logprob
old_mus[step] = mu
old_sigmas[step] = sigma
# TRY NOT TO MODIFY: execute the game and log data.
t2.tic()
next_obs, reward, termination, truncation, info = env.step(action.cpu().numpy())
env_times.append(t2.tocvalue())
# for i in range(config.obs_num_channels):
# pyplots[i].set_data(next_obs['bev_semantics'][0, i])
# plt.pause(0.0001)
done = np.logical_or(termination, truncation) # Not treated separately in original PPO
rewards[step] = torch.tensor(reward, device=device, dtype=torch.float32)
next_done = torch.tensor(done, device=device, dtype=torch.float32)
next_obs = {
'bev_semantics': torch.tensor(next_obs['bev_semantics'], device=device, dtype=torch.uint8),
'measurements': torch.tensor(next_obs['measurements'], device=device, dtype=torch.float32),
'value_measurements': torch.tensor(next_obs['value_measurements'], device=device, dtype=torch.float32)
}
if 'final_info' in info.keys():
for idx, single_info in enumerate(info['final_info']):
if single_info is not None:
if config.use_exploration_suggest:
# Exploration loss
exp_n_steps[step, idx] = single_info['n_steps']
exp_suggest[step, idx] = single_info['suggest']
# Sum up total returns and how often the env was reset during this iteration.
if 'episode' in single_info.keys():
print(f'rank: {rank}, config.global_step={config.global_step}, '
f'episodic_return={single_info["episode"]["r"]}')
total_returns[rank] += single_info['episode']['r'].item()
total_lengths[rank] += single_info['episode']['l'].item()
num_total_returns[rank] += 1
if config.use_dd_ppo_preempt:
num_done = int(num_rollouts_done_store.get('num_done'))
min_steps = int(config.dd_ppo_min_perc * local_bs_per_env)
if (num_done / world_size) > config.dd_ppo_preempt_threshold and step > min_steps:
print(f'Rank:{rank}, Preempt at step: {step}, Num done: {num_done}')
break # End data collection early the other workers are finished.
t0.toc(msg=f'Rank:{rank}, Data collection.')
print(f'Rank:{rank}, Avg forward time {sum(inference_times)}')
print(f'Rank:{rank}, Avg env time {sum(env_times)}')
t3.tic()
if config.use_dd_ppo_preempt:
num_rollouts_done_store.add('num_done', 1)
# In case of a dd-ppo preempt this can be smaller than local batch size
num_collected_steps = step + 1
# bootstrap value if not done
with torch.no_grad():
if config.use_hl_gauss_value_loss:
next_value = agent.module.get_value(next_obs, next_lstm_state, next_done)
value_pdf = F.softmax(next_value, dim=1)
next_value = torch.sum(value_pdf * hl_gauss_bins.unsqueeze(0), dim=1)
else:
next_value = agent.module.get_value(next_obs, next_lstm_state, next_done).squeeze(1)
if args.gae:
advantages = torch.zeros_like(rewards, device=device)
lastgaelam = 0.0
for t in reversed(range(num_collected_steps)):
if t == local_bs_per_env - 1:
nextnonterminal = 1.0 - next_done
nextvalues = next_value