-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
test_utils.py
2098 lines (1857 loc) · 78.6 KB
/
test_utils.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
import argparse
from collections import Counter
import copy
import gymnasium as gym
from gymnasium.spaces import Box, Discrete, MultiDiscrete, MultiBinary
from gymnasium.spaces import Dict as GymDict
from gymnasium.spaces import Tuple as GymTuple
import inspect
import logging
import numpy as np
import os
import pprint
import random
import re
import sys
import time
import tree # pip install dm_tree
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
)
import yaml
import ray
from ray import air, tune
from ray.air.integrations.wandb import WandbLoggerCallback
from ray.rllib.common import SupportedFileType
from ray.rllib.env.wrappers.atari_wrappers import is_atari, wrap_deepmind
from ray.rllib.train import load_experiments_from_file
from ray.rllib.utils.annotations import OldAPIStack
from ray.rllib.utils.deprecation import Deprecated
from ray.rllib.utils.framework import try_import_jax, try_import_tf, try_import_torch
from ray.rllib.utils.metrics import (
DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY,
ENV_RUNNER_RESULTS,
EVALUATION_RESULTS,
NUM_ENV_STEPS_SAMPLED,
NUM_ENV_STEPS_SAMPLED_LIFETIME,
NUM_ENV_STEPS_TRAINED,
)
from ray.rllib.utils.nested_dict import NestedDict
from ray.rllib.utils.typing import ResultDict
from ray.rllib.utils.error import UnsupportedSpaceException
from ray.tune import CLIReporter, run_experiments
if TYPE_CHECKING:
from ray.rllib.algorithms import Algorithm, AlgorithmConfig
from ray.rllib.offline.dataset_reader import DatasetReader
jax, _ = try_import_jax()
tf1, tf, tfv = try_import_tf()
if tf1:
eager_mode = None
try:
from tensorflow.python.eager.context import eager_mode
except (ImportError, ModuleNotFoundError):
pass
torch, _ = try_import_torch()
logger = logging.getLogger(__name__)
def add_rllib_example_script_args(
parser: Optional[argparse.ArgumentParser] = None,
default_reward: float = 100.0,
default_iters: int = 200,
default_timesteps: int = 100000,
) -> argparse.ArgumentParser:
"""Adds RLlib-typical (and common) examples scripts command line args to a parser.
TODO (sven): This function should be used by most of our examples scripts, which
already mostly have this logic in them (but written out).
Args:
parser: The parser to add the arguments to. If None, create a new one.
default_reward: The default value for the --stop-reward option.
default_iters: The default value for the --stop-iters option.
default_timesteps: The default value for the --stop-timesteps option.
Returns:
The altered (or newly created) parser object.
"""
if parser is None:
parser = argparse.ArgumentParser()
# Algo and Algo config options.
parser.add_argument(
"--algo", type=str, default="PPO", help="The RLlib-registered algorithm to use."
)
parser.add_argument(
"--enable-new-api-stack",
action="store_true",
help="Whether to use the `enable_rl_module_and_learner` config setting.",
)
parser.add_argument(
"--framework",
choices=["tf", "tf2", "torch"],
default="torch",
help="The DL framework specifier.",
)
parser.add_argument(
"--num-env-runners",
type=int,
default=2,
help="The number of (remote) EnvRunners to use for the experiment.",
)
parser.add_argument(
"--num-agents",
type=int,
default=0,
help="If 0 (default), will run as single-agent. If > 0, will run as "
"multi-agent with the environment simply cloned n times and each agent acting "
"independently at every single timestep. The overall reward for this "
"experiment is then the sum over all individual agents' rewards.",
)
# tune.Tuner options.
parser.add_argument(
"--no-tune",
action="store_true",
help="Whether to NOT use tune.Tuner(), but rather a simple for-loop calling "
"`algo.train()` repeatedly until one of the stop criteria is met.",
)
parser.add_argument(
"--num-samples",
type=int,
default=1,
help="How many (tune.Tuner.fit()) experiments to execute - if possible in "
"parallel.",
)
parser.add_argument(
"--verbose",
type=int,
default=2,
help="The verbosity level for the `tune.Tuner()` running the experiment.",
)
parser.add_argument(
"--checkpoint-freq",
type=int,
default=0,
help=(
"The frequency (in training iterations) with which to create checkpoints. "
"Note that if --wandb-key is provided, all checkpoints will "
"automatically be uploaded to WandB."
),
)
parser.add_argument(
"--checkpoint-at-end",
action="store_true",
help=(
"Whether to create a checkpoint at the very end of the experiment. "
"Note that if --wandb-key is provided, all checkpoints will "
"automatically be uploaded to WandB."
),
)
# WandB logging options.
parser.add_argument(
"--wandb-key",
type=str,
default=None,
help="The WandB API key to use for uploading results.",
)
parser.add_argument(
"--wandb-project",
type=str,
default=None,
help="The WandB project name to use.",
)
parser.add_argument(
"--wandb-run-name",
type=str,
default=None,
help="The WandB run name to use.",
)
# Experiment stopping and testing criteria.
parser.add_argument(
"--stop-reward",
type=float,
default=default_reward,
help="Reward at which the script should stop training.",
)
parser.add_argument(
"--stop-iters",
type=int,
default=default_iters,
help="The number of iterations to train.",
)
parser.add_argument(
"--stop-timesteps",
type=int,
default=default_timesteps,
help="The number of (environment sampling) timesteps to train.",
)
parser.add_argument(
"--as-test",
action="store_true",
help="Whether this script should be run as a test. If set, --stop-reward must "
"be achieved within --stop-timesteps AND --stop-iters, otherwise this "
"script will throw an exception at the end.",
)
# Learner scaling options.
# Old API stack: config.num_gpus.
# New API stack: config.num_learner_workers (w/ num_gpus_per_learner_worker=1).
parser.add_argument("--num-gpus", type=int, default=0)
# Ray init options.
parser.add_argument("--num-cpus", type=int, default=0)
parser.add_argument(
"--local-mode",
action="store_true",
help="Init Ray in local mode for easier debugging.",
)
return parser
def check(x, y, decimals=5, atol=None, rtol=None, false=False):
"""
Checks two structures (dict, tuple, list,
np.array, float, int, etc..) for (almost) numeric identity.
All numbers in the two structures have to match up to `decimal` digits
after the floating point. Uses assertions.
Args:
x: The value to be compared (to the expectation: `y`). This
may be a Tensor.
y: The expected value to be compared to `x`. This must not
be a tf-Tensor, but may be a tf/torch-Tensor.
decimals: The number of digits after the floating point up to
which all numeric values have to match.
atol: Absolute tolerance of the difference between x and y
(overrides `decimals` if given).
rtol: Relative tolerance of the difference between x and y
(overrides `decimals` if given).
false: Whether to check that x and y are NOT the same.
"""
# A dict type.
if isinstance(x, (dict, NestedDict)):
assert isinstance(
y, (dict, NestedDict)
), "ERROR: If x is dict, y needs to be a dict as well!"
y_keys = set(x.keys())
for key, value in x.items():
assert key in y, f"ERROR: y does not have x's key='{key}'! y={y}"
check(value, y[key], decimals=decimals, atol=atol, rtol=rtol, false=false)
y_keys.remove(key)
assert not y_keys, "ERROR: y contains keys ({}) that are not in x! y={}".format(
list(y_keys), y
)
# A tuple type.
elif isinstance(x, (tuple, list)):
assert isinstance(
y, (tuple, list)
), "ERROR: If x is tuple/list, y needs to be a tuple/list as well!"
assert len(y) == len(
x
), "ERROR: y does not have the same length as x ({} vs {})!".format(
len(y), len(x)
)
for i, value in enumerate(x):
check(value, y[i], decimals=decimals, atol=atol, rtol=rtol, false=false)
# Boolean comparison.
elif isinstance(x, (np.bool_, bool)):
if false is True:
assert bool(x) is not bool(y), f"ERROR: x ({x}) is y ({y})!"
else:
assert bool(x) is bool(y), f"ERROR: x ({x}) is not y ({y})!"
# Nones or primitives.
elif x is None or y is None or isinstance(x, (str, int)):
if false is True:
assert x != y, f"ERROR: x ({x}) is the same as y ({y})!"
else:
assert x == y, f"ERROR: x ({x}) is not the same as y ({y})!"
# String/byte comparisons.
elif (
hasattr(x, "dtype") and (x.dtype == object or str(x.dtype).startswith("<U"))
) or isinstance(x, bytes):
try:
np.testing.assert_array_equal(x, y)
if false is True:
assert False, f"ERROR: x ({x}) is the same as y ({y})!"
except AssertionError as e:
if false is False:
raise e
# Everything else (assume numeric or tf/torch.Tensor).
else:
if tf1 is not None:
# y should never be a Tensor (y=expected value).
if isinstance(y, (tf1.Tensor, tf1.Variable)):
# In eager mode, numpyize tensors.
if tf.executing_eagerly():
y = y.numpy()
else:
raise ValueError(
"`y` (expected value) must not be a Tensor. "
"Use numpy.ndarray instead"
)
if isinstance(x, (tf1.Tensor, tf1.Variable)):
# In eager mode, numpyize tensors.
if tf1.executing_eagerly():
x = x.numpy()
# Otherwise, use a new tf-session.
else:
with tf1.Session() as sess:
x = sess.run(x)
return check(
x, y, decimals=decimals, atol=atol, rtol=rtol, false=false
)
if torch is not None:
if isinstance(x, torch.Tensor):
x = x.detach().cpu().numpy()
if isinstance(y, torch.Tensor):
y = y.detach().cpu().numpy()
# Using decimals.
if atol is None and rtol is None:
# Assert equality of both values.
try:
np.testing.assert_almost_equal(x, y, decimal=decimals)
# Both values are not equal.
except AssertionError as e:
# Raise error in normal case.
if false is False:
raise e
# Both values are equal.
else:
# If false is set -> raise error (not expected to be equal).
if false is True:
assert False, f"ERROR: x ({x}) is the same as y ({y})!"
# Using atol/rtol.
else:
# Provide defaults for either one of atol/rtol.
if atol is None:
atol = 0
if rtol is None:
rtol = 1e-7
try:
np.testing.assert_allclose(x, y, atol=atol, rtol=rtol)
except AssertionError as e:
if false is False:
raise e
else:
if false is True:
assert False, f"ERROR: x ({x}) is the same as y ({y})!"
def check_compute_single_action(
algorithm, include_state=False, include_prev_action_reward=False
):
"""Tests different combinations of args for algorithm.compute_single_action.
Args:
algorithm: The Algorithm object to test.
include_state: Whether to include the initial state of the Policy's
Model in the `compute_single_action` call.
include_prev_action_reward: Whether to include the prev-action and
-reward in the `compute_single_action` call.
Raises:
ValueError: If anything unexpected happens.
"""
# Have to import this here to avoid circular dependency.
from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID, SampleBatch
# Some Algorithms may not abide to the standard API.
pid = DEFAULT_POLICY_ID
try:
# Multi-agent: Pick any learnable policy (or DEFAULT_POLICY if it's the only
# one).
pid = next(iter(algorithm.workers.local_worker().get_policies_to_train()))
pol = algorithm.get_policy(pid)
except AttributeError:
pol = algorithm.policy
# Get the policy's model.
model = pol.model
action_space = pol.action_space
def _test(
what, method_to_test, obs_space, full_fetch, explore, timestep, unsquash, clip
):
call_kwargs = {}
if what is algorithm:
call_kwargs["full_fetch"] = full_fetch
call_kwargs["policy_id"] = pid
obs = obs_space.sample()
if isinstance(obs_space, Box):
obs = np.clip(obs, -1.0, 1.0)
state_in = None
if include_state:
state_in = model.get_initial_state()
if not state_in:
state_in = []
i = 0
while f"state_in_{i}" in model.view_requirements:
state_in.append(
model.view_requirements[f"state_in_{i}"].space.sample()
)
i += 1
action_in = action_space.sample() if include_prev_action_reward else None
reward_in = 1.0 if include_prev_action_reward else None
if method_to_test == "input_dict":
assert what is pol
input_dict = {SampleBatch.OBS: obs}
if include_prev_action_reward:
input_dict[SampleBatch.PREV_ACTIONS] = action_in
input_dict[SampleBatch.PREV_REWARDS] = reward_in
if state_in:
if what.config.get("enable_rl_module_and_learner", False):
input_dict["state_in"] = state_in
else:
for i, s in enumerate(state_in):
input_dict[f"state_in_{i}"] = s
input_dict_batched = SampleBatch(
tree.map_structure(lambda s: np.expand_dims(s, 0), input_dict)
)
action = pol.compute_actions_from_input_dict(
input_dict=input_dict_batched,
explore=explore,
timestep=timestep,
**call_kwargs,
)
# Unbatch everything to be able to compare against single
# action below.
# ARS and ES return action batches as lists.
if isinstance(action[0], list):
action = (np.array(action[0]), action[1], action[2])
action = tree.map_structure(lambda s: s[0], action)
try:
action2 = pol.compute_single_action(
input_dict=input_dict,
explore=explore,
timestep=timestep,
**call_kwargs,
)
# Make sure these are the same, unless we have exploration
# switched on (or noisy layers).
if not explore and not pol.config.get("noisy"):
check(action, action2)
except TypeError:
pass
else:
action = what.compute_single_action(
obs,
state_in,
prev_action=action_in,
prev_reward=reward_in,
explore=explore,
timestep=timestep,
unsquash_action=unsquash,
clip_action=clip,
**call_kwargs,
)
state_out = None
if state_in or full_fetch or what is pol:
action, state_out, _ = action
if state_out:
for si, so in zip(tree.flatten(state_in), tree.flatten(state_out)):
if tf.is_tensor(si):
# If si is a tensor of Dimensions, we need to convert it
# We expect this to be the case for TF RLModules who's initial
# states are Tf Tensors.
si_shape = si.shape.as_list()
else:
si_shape = list(si.shape)
check(si_shape, so.shape)
if unsquash is None:
unsquash = what.config["normalize_actions"]
if clip is None:
clip = what.config["clip_actions"]
# Test whether unsquash/clipping works on the Algorithm's
# compute_single_action method: Both flags should force the action
# to be within the space's bounds.
if method_to_test == "single" and what == algorithm:
if not action_space.contains(action) and (
clip or unsquash or not isinstance(action_space, Box)
):
raise ValueError(
f"Returned action ({action}) of algorithm/policy {what} "
f"not in Env's action_space {action_space}"
)
# We are operating in normalized space: Expect only smaller action
# values.
if (
isinstance(action_space, Box)
and not unsquash
and what.config.get("normalize_actions")
and np.any(np.abs(action) > 15.0)
):
raise ValueError(
f"Returned action ({action}) of algorithm/policy {what} "
"should be in normalized space, but seems too large/small "
"for that!"
)
# Loop through: Policy vs Algorithm; Different API methods to calculate
# actions; unsquash option; clip option; full fetch or not.
for what in [pol, algorithm]:
if what is algorithm:
# Get the obs-space from Workers.env (not Policy) due to possible
# pre-processor up front.
worker_set = getattr(algorithm, "workers", None)
assert worker_set
if not worker_set.local_worker():
obs_space = algorithm.get_policy(pid).observation_space
else:
obs_space = worker_set.local_worker().for_policy(
lambda p: p.observation_space, policy_id=pid
)
obs_space = getattr(obs_space, "original_space", obs_space)
else:
obs_space = pol.observation_space
for method_to_test in ["single"] + (["input_dict"] if what is pol else []):
for explore in [True, False]:
for full_fetch in [False, True] if what is algorithm else [False]:
timestep = random.randint(0, 100000)
for unsquash in [True, False, None]:
for clip in [False] if unsquash else [True, False, None]:
print("-" * 80)
print(f"what={what}")
print(f"method_to_test={method_to_test}")
print(f"explore={explore}")
print(f"full_fetch={full_fetch}")
print(f"unsquash={unsquash}")
print(f"clip={clip}")
_test(
what,
method_to_test,
obs_space,
full_fetch,
explore,
timestep,
unsquash,
clip,
)
def check_inference_w_connectors(policy, env_name, max_steps: int = 100):
"""Checks whether the given policy can infer actions from an env with connectors.
Args:
policy: The policy to check.
env_name: Name of the environment to check
max_steps: The maximum number of steps to run the environment for.
Raises:
ValueError: If the policy cannot infer actions from the environment.
"""
# Avoids circular import
from ray.rllib.utils.policy import local_policy_inference
env = gym.make(env_name)
# Potentially wrap the env like we do in RolloutWorker
if is_atari(env):
env = wrap_deepmind(
env,
dim=policy.config["model"]["dim"],
framestack=policy.config["model"].get("framestack"),
)
obs, info = env.reset()
reward, terminated, truncated = 0.0, False, False
ts = 0
while not terminated and not truncated and ts < max_steps:
action_out = local_policy_inference(
policy,
env_id=0,
agent_id=0,
obs=obs,
reward=reward,
terminated=terminated,
truncated=truncated,
info=info,
)
obs, reward, terminated, truncated, info = env.step(action_out[0][0])
ts += 1
def check_learning_achieved(
tune_results: "tune.ResultGrid",
min_value: float,
evaluation: Optional[bool] = None,
metric: str = f"{ENV_RUNNER_RESULTS}/episode_return_mean",
):
"""Throws an error if `min_reward` is not reached within tune_results.
Checks the last iteration found in tune_results for its
"episode_return_mean" value and compares it to `min_reward`.
Args:
tune_results: The tune.Tuner().fit() returned results object.
min_reward: The min reward that must be reached.
evaluation: If True, use `evaluation/sampler_results/[metric]`, if False, use
`sampler_results/[metric]`, if None, use evaluation sampler results if
available otherwise, use train sampler results.
Raises:
ValueError: If `min_reward` not reached.
"""
# Get maximum reward of all trials
# (check if at least one trial achieved some learning)
recorded_values = []
for _, row in tune_results.get_dataframe().iterrows():
if evaluation or (
evaluation is None and f"{EVALUATION_RESULTS}/{metric}" in row
):
recorded_values.append(row[f"{EVALUATION_RESULTS}/{metric}"])
else:
recorded_values.append(row[metric])
best_value = max(recorded_values)
if best_value < min_value:
raise ValueError(f"`{metric}` of {min_value} not reached!")
print(f"`{metric}` of {min_value} reached! ok")
def check_off_policyness(
results: ResultDict,
upper_limit: float,
lower_limit: float = 0.0,
) -> Optional[float]:
"""Verifies that the off-policy'ness of some update is within some range.
Off-policy'ness is defined as the average (across n workers) diff
between the number of gradient updates performed on the policy used
for sampling vs the number of gradient updates that have been performed
on the trained policy (usually the one on the local worker).
Uses the published DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY metric inside
a training results dict and compares to the given bounds.
Note: Only works with single-agent results thus far.
Args:
results: The training results dict.
upper_limit: The upper limit to for the off_policy_ness value.
lower_limit: The lower limit to for the off_policy_ness value.
Returns:
The off-policy'ness value (described above).
Raises:
AssertionError: If the value is out of bounds.
"""
# Have to import this here to avoid circular dependency.
from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID
from ray.rllib.utils.metrics.learner_info import LEARNER_INFO
# Assert that the off-policy'ness is within the given bounds.
learner_info = results["info"][LEARNER_INFO]
if DEFAULT_POLICY_ID not in learner_info:
return None
off_policy_ness = learner_info[DEFAULT_POLICY_ID][
DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY
]
# Roughly: Reaches up to 0.4 for 2 rollout workers and up to 0.2 for
# 1 rollout worker.
if not (lower_limit <= off_policy_ness <= upper_limit):
raise AssertionError(
f"`off_policy_ness` ({off_policy_ness}) is outside the given bounds "
f"({lower_limit} - {upper_limit})!"
)
return off_policy_ness
def check_train_results_new_api_stack(train_results: ResultDict) -> None:
"""Checks proper structure of a Algorithm.train() returned dict.
Args:
train_results: The train results dict to check.
Raises:
AssertionError: If `train_results` doesn't have the proper structure or
data in it.
"""
# Import these here to avoid circular dependencies.
from ray.rllib.core import DEFAULT_MODULE_ID
from ray.rllib.utils.metrics import (
ENV_RUNNER_RESULTS,
FAULT_TOLERANCE_STATS,
LEARNER_RESULTS,
NUM_AGENT_STEPS_SAMPLED_LIFETIME,
NUM_ENV_STEPS_SAMPLED_LIFETIME,
TIMERS,
)
# Assert that some keys are where we would expect them.
for key in [
ENV_RUNNER_RESULTS,
FAULT_TOLERANCE_STATS,
LEARNER_RESULTS,
NUM_AGENT_STEPS_SAMPLED_LIFETIME,
NUM_ENV_STEPS_SAMPLED_LIFETIME,
TIMERS,
"training_iteration",
"config",
]:
assert (
key in train_results
), f"'{key}' not found in `train_results` ({train_results})!"
# Make sure, `config` is an actual dict, not an AlgorithmConfig object.
assert isinstance(
train_results["config"], dict
), "`config` in results not a python dict!"
from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
is_multi_agent = (
AlgorithmConfig()
.update_from_dict({"policies": train_results["config"]["policies"]})
.is_multi_agent()
)
# Check in particular the "info" dict.
learner_results = train_results[LEARNER_RESULTS]
# Make sure we have a `DEFAULT_MODULE_ID key if we are not in a
# multi-agent setup.
if not is_multi_agent:
assert len(learner_results) == 0 or DEFAULT_MODULE_ID in learner_results, (
f"'{DEFAULT_MODULE_ID}' not found in "
f"train_results['{LEARNER_RESULTS}']!"
)
for module_id, module_metrics in learner_results.items():
# The ModuleID can be __all_modules__ in multi-agent case when the new learner
# stack is enabled.
if module_id == "__all_modules__":
continue
# On the new API stack, policy has no LEARNER_STATS_KEY under it anymore.
for key, value in module_metrics.items():
# Min- and max-stats should be single values.
if key.endswith("_min") or key.endswith("_max"):
assert np.isscalar(value), f"'key' value not a scalar ({value})!"
return train_results
@OldAPIStack
def check_train_results(train_results: ResultDict):
"""Checks proper structure of a Algorithm.train() returned dict.
Args:
train_results: The train results dict to check.
Raises:
AssertionError: If `train_results` doesn't have the proper structure or
data in it.
"""
# Import these here to avoid circular dependencies.
from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID
from ray.rllib.utils.metrics.learner_info import LEARNER_INFO, LEARNER_STATS_KEY
# Assert that some keys are where we would expect them.
for key in [
"agent_timesteps_total",
"config",
"custom_metrics",
"episode_len_mean",
"episode_reward_max",
"episode_reward_mean",
"episode_reward_min",
"hist_stats",
"info",
"iterations_since_restore",
"num_healthy_workers",
"perf",
"policy_reward_max",
"policy_reward_mean",
"policy_reward_min",
"sampler_perf",
"time_since_restore",
"time_this_iter_s",
"timesteps_total",
"timers",
"time_total_s",
"training_iteration",
]:
assert (
key in train_results
), f"'{key}' not found in `train_results` ({train_results})!"
# Make sure, `config` is an actual dict, not an AlgorithmConfig object.
assert isinstance(
train_results["config"], dict
), "`config` in results not a python dict!"
from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
is_multi_agent = (
AlgorithmConfig()
.update_from_dict({"policies": train_results["config"]["policies"]})
.is_multi_agent()
)
# Check in particular the "info" dict.
info = train_results["info"]
assert LEARNER_INFO in info, f"'learner' not in train_results['infos'] ({info})!"
assert (
"num_steps_trained" in info or NUM_ENV_STEPS_TRAINED in info
), f"'num_(env_)?steps_trained' not in train_results['infos'] ({info})!"
learner_info = info[LEARNER_INFO]
# Make sure we have a default_policy key if we are not in a
# multi-agent setup.
if not is_multi_agent:
# APEX algos sometimes have an empty learner info dict (no metrics
# collected yet).
assert len(learner_info) == 0 or DEFAULT_POLICY_ID in learner_info, (
f"'{DEFAULT_POLICY_ID}' not found in "
f"train_results['infos']['learner'] ({learner_info})!"
)
for pid, policy_stats in learner_info.items():
if pid == "batch_count":
continue
# the pid can be __all__ in multi-agent case when the new learner stack is
# enabled.
if pid == "__all__":
continue
# On the new API stack, policy has no LEARNER_STATS_KEY under it anymore.
if LEARNER_STATS_KEY in policy_stats:
learner_stats = policy_stats[LEARNER_STATS_KEY]
else:
learner_stats = policy_stats
for key, value in learner_stats.items():
# Min- and max-stats should be single values.
if key.startswith("min_") or key.startswith("max_"):
assert np.isscalar(value), f"'key' value not a scalar ({value})!"
return train_results
def framework_iterator(
config: Optional["AlgorithmConfig"] = None,
frameworks: Sequence[str] = ("tf2", "tf", "torch"),
session: bool = False,
time_iterations: Optional[dict] = None,
) -> Union[str, Tuple[str, Optional["tf1.Session"]]]:
"""An generator that allows for looping through n frameworks for testing.
Provides the correct config entries ("framework") as well
as the correct eager/non-eager contexts for tf/tf2.
Args:
config: An optional config dict or AlgorithmConfig object. This will be modified
(value for "framework" changed) depending on the iteration.
frameworks: A list/tuple of the frameworks to be tested.
Allowed are: "tf2", "tf", "torch", and None.
session: If True and only in the tf-case: Enter a tf.Session()
and yield that as second return value (otherwise yield (fw, None)).
Also sets a seed (42) on the session to make the test
deterministic.
time_iterations: If provided, will write to the given dict (by
framework key) the times in seconds that each (framework's)
iteration takes.
Yields:
If `session` is False: The current framework [tf2|tf|torch] used.
If `session` is True: A tuple consisting of the current framework
string and the tf1.Session (if fw="tf", otherwise None).
"""
config = config or {}
frameworks = [frameworks] if isinstance(frameworks, str) else list(frameworks)
for fw in frameworks:
# Skip tf if on new API stack.
if fw == "tf" and config.get("enable_rl_module_and_learner", False):
logger.warning("Skipping `framework=tf` (new API stack configured)!")
continue
# Skip if tf/tf2 and py >= 3.11.
elif fw in ["tf", "tf2"] and (
sys.version_info.major == 3 and sys.version_info.minor >= 9
):
logger.warning("Skipping `framework=tf/tf2` (python >= 3.9)!")
continue
# Skip non-installed frameworks.
if fw == "torch" and not torch:
logger.warning("framework_iterator skipping torch (not installed)!")
continue
if fw != "torch" and not tf:
logger.warning(
"framework_iterator skipping {} (tf not installed)!".format(fw)
)
continue
elif fw == "tf2" and tfv != 2:
logger.warning("framework_iterator skipping tf2.x (tf version is < 2.0)!")
continue
elif fw == "jax" and not jax:
logger.warning("framework_iterator skipping JAX (not installed)!")
continue
assert fw in ["tf2", "tf", "torch", "jax", None]
# Do we need a test session?
sess = None
if fw == "tf" and session is True:
sess = tf1.Session()
sess.__enter__()
tf1.set_random_seed(42)
if isinstance(config, dict):
config["framework"] = fw
else:
config.framework(fw)
eager_ctx = None
# Enable eager mode for tf2.
if fw == "tf2":
eager_ctx = eager_mode()
eager_ctx.__enter__()
assert tf1.executing_eagerly()
# Make sure, eager mode is off.
elif fw == "tf":
assert not tf1.executing_eagerly()
# Yield current framework + tf-session (if necessary).
print(f"framework={fw}")
time_started = time.time()
yield fw if session is False else (fw, sess)
if time_iterations is not None:
time_total = time.time() - time_started
time_iterations[fw] = time_total
print(f".. took {time_total}sec")
# Exit any context we may have entered.
if eager_ctx:
eager_ctx.__exit__(None, None, None)
elif sess:
sess.__exit__(None, None, None)
@Deprecated(new="run_learning_tests_from_yaml_or_py(config_files=...)", error=False)
def run_learning_tests_from_yaml(
yaml_files: List[str],
*,
framework: Optional[str] = None,
max_num_repeats: int = 2,
use_pass_criteria_as_stop: bool = True,
smoke_test: bool = False,
):
return run_learning_tests_from_yaml_or_py(
yaml_files,
framework=framework,
max_num_repeats=max_num_repeats,
use_pass_criteria_as_stop=use_pass_criteria_as_stop,
smoke_test=smoke_test,
)
def run_learning_tests_from_yaml_or_py(
config_files: List[str],
*,
framework: Optional[str] = None,
max_num_repeats: int = 2,
use_pass_criteria_as_stop: bool = True,
smoke_test: bool = False,
) -> Dict[str, Any]:
"""Runs the given experiments in config_files and returns results dict.
Args:
framework: The framework to use for running this test. If None,
run the test on all frameworks.
config_files: List of yaml or py config file names.
max_num_repeats: How many times should we repeat a failed
experiment?
use_pass_criteria_as_stop: Configure the Trial so that it stops
as soon as pass criterias are met.
smoke_test: Whether this is just a smoke-test. If True,
set time_total_s to 5min and don't early out due to rewards