-
Notifications
You must be signed in to change notification settings - Fork 229
/
preference_comparisons.py
1690 lines (1476 loc) · 70.4 KB
/
preference_comparisons.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
"""Learning reward models using preference comparisons.
Trains a reward model and optionally a policy based on preferences
between trajectory fragments.
"""
import abc
import math
import pickle
import re
from collections import defaultdict
from typing import (
Any,
Callable,
Dict,
List,
Mapping,
NamedTuple,
Optional,
Sequence,
Tuple,
Union,
cast,
)
import numpy as np
import torch as th
from scipy import special
from stable_baselines3.common import base_class, type_aliases, utils, vec_env
from torch import nn
from torch.utils import data as data_th
from tqdm.auto import tqdm
from imitation.algorithms import base
from imitation.data import rollout, types, wrappers
from imitation.data.types import (
AnyPath,
TrajectoryPair,
TrajectoryWithRew,
TrajectoryWithRewPair,
Transitions,
)
from imitation.policies import exploration_wrapper
from imitation.regularization import regularizers
from imitation.rewards import reward_function, reward_nets, reward_wrapper
from imitation.util import logger as imit_logger
from imitation.util import networks, util
class TrajectoryGenerator(abc.ABC):
"""Generator of trajectories with optional training logic."""
_logger: imit_logger.HierarchicalLogger
"""Object to log statistics and natural language messages to."""
def __init__(self, custom_logger: Optional[imit_logger.HierarchicalLogger] = None):
"""Builds TrajectoryGenerator.
Args:
custom_logger: Where to log to; if None (default), creates a new logger.
"""
self.logger = custom_logger or imit_logger.configure()
@abc.abstractmethod
def sample(self, steps: int) -> Sequence[TrajectoryWithRew]:
"""Sample a batch of trajectories.
Args:
steps: All trajectories taken together should
have at least this many steps.
Returns:
A list of sampled trajectories with rewards (which should
be the environment rewards, not ones from a reward model).
""" # noqa: DAR202
def train(self, steps: int, **kwargs):
"""Train an agent if the trajectory generator uses one.
By default, this method does nothing and doesn't need
to be overridden in subclasses that don't require training.
Args:
steps: number of environment steps to train for.
**kwargs: additional keyword arguments to pass on to
the training procedure.
"""
@property
def logger(self) -> imit_logger.HierarchicalLogger:
return self._logger
@logger.setter
def logger(self, value: imit_logger.HierarchicalLogger):
self._logger = value
class TrajectoryDataset(TrajectoryGenerator):
"""A fixed dataset of trajectories."""
def __init__(
self,
trajectories: Sequence[TrajectoryWithRew],
rng: np.random.Generator,
custom_logger: Optional[imit_logger.HierarchicalLogger] = None,
):
"""Creates a dataset loaded from `path`.
Args:
trajectories: the dataset of rollouts.
rng: RNG used for shuffling dataset.
custom_logger: Where to log to; if None (default), creates a new logger.
"""
super().__init__(custom_logger=custom_logger)
self._trajectories = trajectories
self.rng = rng
def sample(self, steps: int) -> Sequence[TrajectoryWithRew]:
# make a copy before shuffling
trajectories = list(self._trajectories)
self.rng.shuffle(trajectories)
return _get_trajectories(trajectories, steps)
class AgentTrainer(TrajectoryGenerator):
"""Wrapper for training an SB3 algorithm on an arbitrary reward function."""
def __init__(
self,
algorithm: base_class.BaseAlgorithm,
reward_fn: Union[reward_function.RewardFn, reward_nets.RewardNet],
venv: vec_env.VecEnv,
rng: np.random.Generator,
exploration_frac: float = 0.0,
switch_prob: float = 0.5,
random_prob: float = 0.5,
custom_logger: Optional[imit_logger.HierarchicalLogger] = None,
):
"""Initialize the agent trainer.
Args:
algorithm: the stable-baselines algorithm to use for training.
reward_fn: either a RewardFn or a RewardNet instance that will supply
the rewards used for training the agent.
venv: vectorized environment to train in.
rng: random number generator used for exploration and for sampling.
exploration_frac: fraction of the trajectories that will be generated
partially randomly rather than only by the agent when sampling.
switch_prob: the probability of switching the current policy at each
step for the exploratory samples.
random_prob: the probability of picking the random policy when switching
during exploration.
custom_logger: Where to log to; if None (default), creates a new logger.
"""
self.algorithm = algorithm
# NOTE: this has to come after setting self.algorithm because super().__init__
# will set self.logger, which also sets the logger for the algorithm
super().__init__(custom_logger)
if isinstance(reward_fn, reward_nets.RewardNet):
utils.check_for_correct_spaces(
venv,
reward_fn.observation_space,
reward_fn.action_space,
)
reward_fn = reward_fn.predict_processed
self.reward_fn = reward_fn
self.exploration_frac = exploration_frac
self.rng = rng
# The BufferingWrapper records all trajectories, so we can return
# them after training. This should come first (before the wrapper that
# changes the reward function), so that we return the original environment
# rewards.
# When applying BufferingWrapper and RewardVecEnvWrapper, we should use `venv`
# instead of `algorithm.get_env()` because SB3 may apply some wrappers to
# `algorithm`'s env under the hood. In particular, in image-based environments,
# SB3 may move the image-channel dimension in the observation space, making
# `algorithm.get_env()` not match with `reward_fn`.
self.buffering_wrapper = wrappers.BufferingWrapper(venv)
self.venv = self.reward_venv_wrapper = reward_wrapper.RewardVecEnvWrapper(
self.buffering_wrapper,
reward_fn=self.reward_fn,
)
self.log_callback = self.reward_venv_wrapper.make_log_callback()
self.algorithm.set_env(self.venv)
# Unlike with BufferingWrapper, we should use `algorithm.get_env()` instead
# of `venv` when interacting with `algorithm`.
algo_venv = self.algorithm.get_env()
assert algo_venv is not None
policy_callable = rollout._policy_to_callable(
self.algorithm,
algo_venv,
# By setting deterministic_policy to False, we ensure that the rollouts
# are collected from a deterministic policy only if self.algorithm is
# deterministic. If self.algorithm is stochastic, then policy_callable
# will also be stochastic.
deterministic_policy=False,
)
self.exploration_wrapper = exploration_wrapper.ExplorationWrapper(
policy_callable=policy_callable,
venv=algo_venv,
random_prob=random_prob,
switch_prob=switch_prob,
rng=self.rng,
)
def train(self, steps: int, **kwargs) -> None:
"""Train the agent using the reward function specified during instantiation.
Args:
steps: number of environment timesteps to train for
**kwargs: other keyword arguments to pass to BaseAlgorithm.train()
Raises:
RuntimeError: Transitions left in `self.buffering_wrapper`; call
`self.sample` first to clear them.
"""
n_transitions = self.buffering_wrapper.n_transitions
if n_transitions:
raise RuntimeError(
f"There are {n_transitions} transitions left in the buffer. "
"Call AgentTrainer.sample() first to clear them.",
)
self.algorithm.learn(
total_timesteps=steps,
reset_num_timesteps=False,
callback=self.log_callback,
**kwargs,
)
def sample(self, steps: int) -> Sequence[types.TrajectoryWithRew]:
agent_trajs, _ = self.buffering_wrapper.pop_finished_trajectories()
# We typically have more trajectories than are needed.
# In that case, we use the final trajectories because
# they are the ones with the most relevant version of
# the agent.
# The easiest way to do this will be to first invert the
# list and then later just take the first trajectories:
agent_trajs = agent_trajs[::-1]
avail_steps = sum(len(traj) for traj in agent_trajs)
exploration_steps = int(self.exploration_frac * steps)
if self.exploration_frac > 0 and exploration_steps == 0:
self.logger.warn(
"No exploration steps included: exploration_frac = "
f"{self.exploration_frac} > 0 but steps={steps} is too small.",
)
agent_steps = steps - exploration_steps
if avail_steps < agent_steps:
self.logger.log(
f"Requested {agent_steps} transitions but only {avail_steps} in buffer."
f" Sampling {agent_steps - avail_steps} additional transitions.",
)
sample_until = rollout.make_sample_until(
min_timesteps=agent_steps - avail_steps,
min_episodes=None,
)
# Important note: we don't want to use the trajectories returned
# here because 1) they might miss initial timesteps taken by the RL agent
# and 2) their rewards are the ones provided by the reward model!
# Instead, we collect the trajectories using the BufferingWrapper.
algo_venv = self.algorithm.get_env()
assert algo_venv is not None
rollout.generate_trajectories(
self.algorithm,
algo_venv,
sample_until=sample_until,
# By setting deterministic_policy to False, we ensure that the rollouts
# are collected from a deterministic policy only if self.algorithm is
# deterministic. If self.algorithm is stochastic, then policy_callable
# will also be stochastic.
deterministic_policy=False,
rng=self.rng,
)
additional_trajs, _ = self.buffering_wrapper.pop_finished_trajectories()
agent_trajs = list(agent_trajs) + list(additional_trajs)
agent_trajs = _get_trajectories(agent_trajs, agent_steps)
trajectories = list(agent_trajs)
if exploration_steps > 0:
self.logger.log(f"Sampling {exploration_steps} exploratory transitions.")
sample_until = rollout.make_sample_until(
min_timesteps=exploration_steps,
min_episodes=None,
)
algo_venv = self.algorithm.get_env()
assert algo_venv is not None
rollout.generate_trajectories(
policy=self.exploration_wrapper,
venv=algo_venv,
sample_until=sample_until,
# buffering_wrapper collects rollouts from a non-deterministic policy,
# so we do that here as well for consistency.
deterministic_policy=False,
rng=self.rng,
)
exploration_trajs, _ = self.buffering_wrapper.pop_finished_trajectories()
exploration_trajs = _get_trajectories(exploration_trajs, exploration_steps)
# We call _get_trajectories separately on agent_trajs and exploration_trajs
# and then just concatenate. This could mean we return slightly too many
# transitions, but it gets the proportion of exploratory and agent
# transitions roughly right.
trajectories.extend(list(exploration_trajs))
return trajectories
@property
def logger(self):
return super().logger
@logger.setter
def logger(self, value: imit_logger.HierarchicalLogger):
self._logger = value
self.algorithm.set_logger(self.logger)
def _get_trajectories(
trajectories: Sequence[TrajectoryWithRew],
steps: int,
) -> Sequence[TrajectoryWithRew]:
"""Get enough trajectories to have at least `steps` transitions in total."""
if steps == 0:
return []
available_steps = sum(len(traj) for traj in trajectories)
if available_steps < steps:
raise RuntimeError(
f"Asked for {steps} transitions but only {available_steps} available",
)
# We need the cumulative sum of trajectory lengths
# to determine how many trajectories to return:
steps_cumsum = np.cumsum([len(traj) for traj in trajectories])
# Now we find the first index that gives us enough
# total steps:
idx = int((steps_cumsum >= steps).argmax())
# we need to include the element at position idx
trajectories = trajectories[: idx + 1]
# sanity check
assert sum(len(traj) for traj in trajectories) >= steps
return trajectories
class PreferenceModel(nn.Module):
"""Class to convert two fragments' rewards into preference probability."""
def __init__(
self,
model: reward_nets.RewardNet,
noise_prob: float = 0.0,
discount_factor: float = 1.0,
threshold: float = 50,
):
"""Create Preference Prediction Model.
Args:
model: base model to compute reward.
noise_prob: assumed probability with which the preference
is uniformly random (used for the model of preference generation
that is used for the loss).
discount_factor: the model of preference generation uses a softmax
of returns as the probability that a fragment is preferred.
This is the discount factor used to calculate those returns.
Default is 1, i.e. undiscounted sums of rewards (which is what
the DRLHP paper uses).
threshold: the preference model used to compute the loss contains
a softmax of returns. To avoid overflows, we clip differences
in returns that are above this threshold. This threshold
is therefore in logspace. The default value of 50 means
that probabilities below 2e-22 are rounded up to 2e-22.
Raises:
ValueError: if `RewardEnsemble` is wrapped around a class
other than `AddSTDRewardWrapper`.
"""
super().__init__()
self.model = model
self.noise_prob = noise_prob
self.discount_factor = discount_factor
self.threshold = threshold
base_model = get_base_model(model)
self.ensemble_model = None
# if the base model is an ensemble model, then keep the base model as
# model to get rewards from all networks
if isinstance(base_model, reward_nets.RewardEnsemble):
# reward_model may include an AddSTDRewardWrapper for RL training; but we
# must train directly on the base model for reward model training.
is_base = model is base_model
is_std_wrapper = (
isinstance(model, reward_nets.AddSTDRewardWrapper)
and model.base is base_model
)
if not (is_base or is_std_wrapper):
raise ValueError(
"RewardEnsemble can only be wrapped"
f" by AddSTDRewardWrapper but found {type(model).__name__}.",
)
self.ensemble_model = base_model
self.member_pref_models = []
for member in self.ensemble_model.members:
member_pref_model = PreferenceModel(
cast(reward_nets.RewardNet, member), # nn.ModuleList is not generic
self.noise_prob,
self.discount_factor,
self.threshold,
)
self.member_pref_models.append(member_pref_model)
def forward(
self,
fragment_pairs: Sequence[TrajectoryPair],
) -> Tuple[th.Tensor, Optional[th.Tensor]]:
"""Computes the preference probability of the first fragment for all pairs.
Note: This function passes the gradient through for non-ensemble models.
For an ensemble model, this function should not be used for loss
calculation. It can be used in case where passing the gradient is not
required such as during active selection or inference time.
Therefore, the EnsembleTrainer passes each member network through this
function instead of passing the EnsembleNetwork object with the use of
`ensemble_member_index`.
Args:
fragment_pairs: batch of pair of fragments.
Returns:
A tuple with the first element as the preference probabilities for the
first fragment for all fragment pairs given by the network(s).
If the ground truth rewards are available, it also returns gt preference
probabilities in the second element of the tuple (else None).
Reward probability shape - (num_fragment_pairs, ) for non-ensemble reward
network and (num_fragment_pairs, num_networks) for an ensemble of networks.
"""
probs = th.empty(len(fragment_pairs), dtype=th.float32)
gt_reward_available = _trajectory_pair_includes_reward(fragment_pairs[0])
if gt_reward_available:
gt_probs = th.empty(len(fragment_pairs), dtype=th.float32)
for i, fragment in enumerate(fragment_pairs):
frag1, frag2 = fragment
trans1 = rollout.flatten_trajectories([frag1])
trans2 = rollout.flatten_trajectories([frag2])
rews1 = self.rewards(trans1)
rews2 = self.rewards(trans2)
probs[i] = self.probability(rews1, rews2)
if gt_reward_available:
frag1 = cast(TrajectoryWithRew, frag1)
frag2 = cast(TrajectoryWithRew, frag2)
gt_rews_1 = th.from_numpy(frag1.rews)
gt_rews_2 = th.from_numpy(frag2.rews)
gt_probs[i] = self.probability(gt_rews_1, gt_rews_2)
return probs, (gt_probs if gt_reward_available else None)
def rewards(self, transitions: Transitions) -> th.Tensor:
"""Computes the reward for all transitions.
Args:
transitions: batch of obs-act-obs-done for a fragment of a trajectory.
Returns:
The reward given by the network(s) for all the transitions.
Shape - (num_transitions, ) for Single reward network and
(num_transitions, num_networks) for ensemble of networks.
"""
state = transitions.obs
action = transitions.acts
next_state = transitions.next_obs
done = transitions.dones
if self.ensemble_model is not None:
rews_np = self.ensemble_model.predict_processed_all(
state,
action,
next_state,
done,
)
assert rews_np.shape == (len(state), self.ensemble_model.num_members)
rews = util.safe_to_tensor(rews_np).to(self.ensemble_model.device)
else:
preprocessed = self.model.preprocess(state, action, next_state, done)
rews = self.model(*preprocessed)
assert rews.shape == (len(state),)
return rews
def probability(self, rews1: th.Tensor, rews2: th.Tensor) -> th.Tensor:
"""Computes the Boltzmann rational probability that the first trajectory is best.
Args:
rews1: array/matrix of rewards for the first trajectory fragment.
matrix for ensemble models and array for non-ensemble models.
rews2: array/matrix of rewards for the second trajectory fragment.
matrix for ensemble models and array for non-ensemble models.
Returns:
The softmax of the difference between the (discounted) return of the
first and second trajectory.
Shape - (num_ensemble_members, ) for ensemble model and
() for non-ensemble model which is a torch scalar.
"""
# check rews has correct shape based on the model
expected_dims = 2 if self.ensemble_model is not None else 1
assert rews1.ndim == rews2.ndim == expected_dims
# First, we compute the difference of the returns of
# the two fragments. We have a special case for a discount
# factor of 1 to avoid unnecessary computation (especially
# since this is the default setting).
if self.discount_factor == 1:
returns_diff = (rews2 - rews1).sum(axis=0) # type: ignore[call-overload]
else:
discounts = self.discount_factor ** th.arange(len(rews1))
if self.ensemble_model is not None:
discounts = discounts.reshape(-1, 1)
returns_diff = (discounts * (rews2 - rews1)).sum(axis=0)
# Clip to avoid overflows (which in particular may occur
# in the backwards pass even if they do not in the forward pass).
returns_diff = th.clip(returns_diff, -self.threshold, self.threshold)
# We take the softmax of the returns. model_probability
# is the first dimension of that softmax, representing the
# probability that fragment 1 is preferred.
model_probability = 1 / (1 + returns_diff.exp())
probability = self.noise_prob * 0.5 + (1 - self.noise_prob) * model_probability
if self.ensemble_model is not None:
assert probability.shape == (self.model.num_members,)
else:
assert probability.shape == ()
return probability
class Fragmenter(abc.ABC):
"""Class for creating pairs of trajectory fragments from a set of trajectories."""
def __init__(self, custom_logger: Optional[imit_logger.HierarchicalLogger] = None):
"""Initialize the fragmenter.
Args:
custom_logger: Where to log to; if None (default), creates a new logger.
"""
self.logger = custom_logger or imit_logger.configure()
@abc.abstractmethod
def __call__(
self,
trajectories: Sequence[TrajectoryWithRew],
fragment_length: int,
num_pairs: int,
) -> Sequence[TrajectoryWithRewPair]:
"""Create fragment pairs out of a sequence of trajectories.
Args:
trajectories: collection of trajectories that will be split up into
fragments
fragment_length: the length of each sampled fragment
num_pairs: the number of fragment pairs to sample
Returns:
a sequence of fragment pairs
""" # noqa: DAR202
class RandomFragmenter(Fragmenter):
"""Sample fragments of trajectories uniformly at random with replacement.
Note that each fragment is part of a single episode and has a fixed
length. This leads to a bias: transitions at the beginning and at the
end of episodes are less likely to occur as part of fragments (this affects
the first and last fragment_length transitions).
An additional bias is that trajectories shorter than the desired fragment
length are never used.
"""
def __init__(
self,
rng: np.random.Generator,
warning_threshold: int = 10,
custom_logger: Optional[imit_logger.HierarchicalLogger] = None,
):
"""Initialize the fragmenter.
Args:
rng: the random number generator
warning_threshold: give a warning if the number of available
transitions is less than this many times the number of
required samples. Set to 0 to disable this warning.
custom_logger: Where to log to; if None (default), creates a new logger.
"""
super().__init__(custom_logger)
self.rng = rng
self.warning_threshold = warning_threshold
def __call__(
self,
trajectories: Sequence[TrajectoryWithRew],
fragment_length: int,
num_pairs: int,
) -> Sequence[TrajectoryWithRewPair]:
fragments: List[TrajectoryWithRew] = []
prev_num_trajectories = len(trajectories)
# filter out all trajectories that are too short
trajectories = [traj for traj in trajectories if len(traj) >= fragment_length]
if len(trajectories) == 0:
raise ValueError(
"No trajectories are long enough for the desired fragment length "
f"of {fragment_length}.",
)
num_discarded = prev_num_trajectories - len(trajectories)
if num_discarded:
self.logger.log(
f"Discarded {num_discarded} out of {prev_num_trajectories} "
"trajectories because they are shorter than the desired length "
f"of {fragment_length}.",
)
weights = [len(traj) for traj in trajectories]
# number of transitions that will be contained in the fragments
num_transitions = 2 * num_pairs * fragment_length
if sum(weights) < num_transitions:
self.logger.warn(
"Fewer transitions available than needed for desired number "
"of fragment pairs. Some transitions will appear multiple times.",
)
elif (
self.warning_threshold
and sum(weights) < self.warning_threshold * num_transitions
):
# If the number of available transitions is not much larger
# than the number of requires ones, we already give a warning.
# But only if self.warning_threshold is non-zero.
self.logger.warn(
f"Samples will contain {num_transitions} transitions in total "
f"and only {sum(weights)} are available. "
f"Because we sample with replacement, a significant number "
"of transitions are likely to appear multiple times.",
)
# we need two fragments for each comparison
for _ in range(2 * num_pairs):
traj = self.rng.choice(trajectories, p=np.array(weights) / sum(weights))
n = len(traj)
start = self.rng.integers(0, n - fragment_length, endpoint=True)
end = start + fragment_length
terminal = (end == n) and traj.terminal
fragment = TrajectoryWithRew(
obs=traj.obs[start : end + 1],
acts=traj.acts[start:end],
infos=traj.infos[start:end] if traj.infos is not None else None,
rews=traj.rews[start:end],
terminal=terminal,
)
fragments.append(fragment)
# fragments is currently a list of single fragments. We want to pair up
# fragments to get a list of (fragment1, fragment2) tuples. To do so,
# we create a single iterator of the list and zip it with itself:
iterator = iter(fragments)
return list(zip(iterator, iterator))
class ActiveSelectionFragmenter(Fragmenter):
"""Sample fragments of trajectories based on active selection.
Actively picks the fragment pairs with the highest uncertainty (variance)
of rewards/probabilties/predictions from ensemble model.
"""
def __init__(
self,
preference_model: PreferenceModel,
base_fragmenter: Fragmenter,
fragment_sample_factor: float,
uncertainty_on: str = "logits",
custom_logger: Optional[imit_logger.HierarchicalLogger] = None,
):
"""Initialize the active selection fragmenter.
Args:
preference_model: an ensemble model that predicts the
preference of the first fragment over the other.
base_fragmenter: fragmenter instance to get
fragment pairs from trajectories
fragment_sample_factor: the factor of the number of
fragment pairs to sample from the base_fragmenter
uncertainty_on: the variable to calculate the variance on.
Can be logit|probability|label.
custom_logger: Where to log to; if None (default), creates a new logger.
Raises:
ValueError: Preference model not wrapped over an ensemble of networks.
"""
super().__init__(custom_logger=custom_logger)
if preference_model.ensemble_model is None:
raise ValueError(
"PreferenceModel not wrapped over an ensemble of networks.",
)
self.preference_model = preference_model
self.base_fragmenter = base_fragmenter
self.fragment_sample_factor = fragment_sample_factor
self._uncertainty_on = uncertainty_on
if not (uncertainty_on in ["logit", "probability", "label"]):
self.raise_uncertainty_on_not_supported()
@property
def uncertainty_on(self) -> str:
return self._uncertainty_on
def raise_uncertainty_on_not_supported(self):
raise ValueError(
f"""{self.uncertainty_on} not supported.
`uncertainty_on` should be from `logit`, `probability`, or `label`""",
)
def __call__(
self,
trajectories: Sequence[TrajectoryWithRew],
fragment_length: int,
num_pairs: int,
) -> Sequence[TrajectoryWithRewPair]:
# sample a large number (self.fragment_sample_factor*num_pairs)
# of fragments from all the trajectories
fragments_to_sample = int(self.fragment_sample_factor * num_pairs)
fragment_pairs = self.base_fragmenter(
trajectories=trajectories,
fragment_length=fragment_length,
num_pairs=fragments_to_sample,
)
var_estimates = np.zeros(len(fragment_pairs))
for i, fragment in enumerate(fragment_pairs):
frag1, frag2 = fragment
trans1 = rollout.flatten_trajectories([frag1])
trans2 = rollout.flatten_trajectories([frag2])
with th.no_grad():
rews1 = self.preference_model.rewards(trans1)
rews2 = self.preference_model.rewards(trans2)
var_estimate = self.variance_estimate(rews1, rews2)
var_estimates[i] = var_estimate
fragment_idxs = np.argsort(var_estimates)[::-1] # sort in descending order
# return fragment pairs that have the highest uncertainty
return [fragment_pairs[idx] for idx in fragment_idxs[:num_pairs]]
def variance_estimate(self, rews1, rews2) -> float:
"""Gets the variance estimate from the rewards of a fragment pair.
Args:
rews1: rewards obtained by all the ensemble models for the first fragment.
Shape - (fragment_length, num_ensemble_members)
rews2: rewards obtained by all the ensemble models for the second fragment.
Shape - (fragment_length, num_ensemble_members)
Returns:
the variance estimate based on the `uncertainty_on` flag.
"""
if self.uncertainty_on == "logit":
returns1, returns2 = rews1.sum(0), rews2.sum(0)
var_estimate = (returns1 - returns2).var().item()
else: # uncertainty_on is probability or label
probs = self.preference_model.probability(rews1, rews2)
probs_np = probs.cpu().numpy()
assert probs_np.shape == (self.preference_model.model.num_members,)
if self.uncertainty_on == "probability":
var_estimate = probs_np.var()
elif self.uncertainty_on == "label": # uncertainty_on is label
preds = (probs_np > 0.5).astype(np.float32)
# probability estimate of Bernoulli random variable
prob_estimate = preds.mean()
# variance estimate of Bernoulli random variable
var_estimate = prob_estimate * (1 - prob_estimate)
else:
self.raise_uncertainty_on_not_supported()
return var_estimate
class PreferenceGatherer(abc.ABC):
"""Base class for gathering preference comparisons between trajectory fragments."""
def __init__(
self,
rng: Optional[np.random.Generator] = None,
custom_logger: Optional[imit_logger.HierarchicalLogger] = None,
):
"""Initializes the preference gatherer.
Args:
rng: random number generator, if applicable.
custom_logger: Where to log to; if None (default), creates a new logger.
"""
# The random seed isn't used here, but it's useful to have this
# as an argument nevertheless because that means we can always
# pass in a seed in training scripts (without worrying about whether
# the PreferenceGatherer we use needs one).
del rng
self.logger = custom_logger or imit_logger.configure()
@abc.abstractmethod
def __call__(self, fragment_pairs: Sequence[TrajectoryWithRewPair]) -> np.ndarray:
"""Gathers the probabilities that fragment 1 is preferred in `fragment_pairs`.
Args:
fragment_pairs: sequence of pairs of trajectory fragments
Returns:
A numpy array with shape (b, ), where b is the length of the input
(i.e. batch size). Each item in the array is the probability that
fragment 1 is preferred over fragment 2 for the corresponding
pair of fragments.
Note that for human feedback, these probabilities are simply 0 or 1
(or 0.5 in case of indifference), but synthetic models may yield other
probabilities.
""" # noqa: DAR202
class SyntheticGatherer(PreferenceGatherer):
"""Computes synthetic preferences using ground-truth environment rewards."""
def __init__(
self,
temperature: float = 1,
discount_factor: float = 1,
sample: bool = True,
rng: Optional[np.random.Generator] = None,
threshold: float = 50,
custom_logger: Optional[imit_logger.HierarchicalLogger] = None,
):
"""Initialize the synthetic preference gatherer.
Args:
temperature: the preferences are sampled from a softmax, this is
the temperature used for sampling. temperature=0 leads to deterministic
results (for equal rewards, 0.5 will be returned).
discount_factor: discount factor that is used to compute
how good a fragment is. Default is to use undiscounted
sums of rewards (as in the DRLHP paper).
sample: if True (default), the preferences are 0 or 1, sampled from
a Bernoulli distribution (or 0.5 in the case of ties with zero
temperature). If False, then the underlying Bernoulli probabilities
are returned instead.
rng: random number generator, only used if
``temperature > 0`` and ``sample=True``
threshold: preferences are sampled from a softmax of returns.
To avoid overflows, we clip differences in returns that are
above this threshold (after multiplying with temperature).
This threshold is therefore in logspace. The default value
of 50 means that probabilities below 2e-22 are rounded up to 2e-22.
custom_logger: Where to log to; if None (default), creates a new logger.
Raises:
ValueError: if `sample` is true and no random state is provided.
"""
super().__init__(custom_logger=custom_logger)
self.temperature = temperature
self.discount_factor = discount_factor
self.sample = sample
self.rng = rng
self.threshold = threshold
if self.sample and self.rng is None:
raise ValueError("If `sample` is True, then `rng` must be provided.")
def __call__(self, fragment_pairs: Sequence[TrajectoryWithRewPair]) -> np.ndarray:
"""Computes probability fragment 1 is preferred over fragment 2."""
returns1, returns2 = self._reward_sums(fragment_pairs)
if self.temperature == 0:
return (np.sign(returns1 - returns2) + 1) / 2
returns1 /= self.temperature
returns2 /= self.temperature
# clip the returns to avoid overflows in the softmax below
returns_diff = np.clip(returns2 - returns1, -self.threshold, self.threshold)
# Instead of computing exp(rews1) / (exp(rews1) + exp(rews2)) directly,
# we divide enumerator and denominator by exp(rews1) to prevent overflows:
model_probs = 1 / (1 + np.exp(returns_diff))
# Compute the mean binary entropy. This metric helps estimate
# how good we can expect the performance of the learned reward
# model to be at predicting preferences.
entropy = -(
special.xlogy(model_probs, model_probs)
+ special.xlogy(1 - model_probs, 1 - model_probs)
).mean()
self.logger.record("entropy", entropy)
if self.sample:
return self.rng.binomial(n=1, p=model_probs).astype(np.float32)
return model_probs
def _reward_sums(self, fragment_pairs) -> Tuple[np.ndarray, np.ndarray]:
rews1, rews2 = zip(
*[
(
rollout.discounted_sum(f1.rews, self.discount_factor),
rollout.discounted_sum(f2.rews, self.discount_factor),
)
for f1, f2 in fragment_pairs
],
)
return np.array(rews1, dtype=np.float32), np.array(rews2, dtype=np.float32)
class PreferenceDataset(th.utils.data.Dataset):
"""A PyTorch Dataset for preference comparisons.
Each item is a tuple consisting of two trajectory fragments
and a probability that fragment 1 is preferred over fragment 2.
This dataset is meant to be generated piece by piece during the
training process, which is why data can be added via the .push()
method.
"""
def __init__(self, max_size: Optional[int] = None):
"""Builds an empty PreferenceDataset.
Args:
max_size: Maximum number of preference comparisons to store in the dataset.
If None (default), the dataset can grow indefinitely. Otherwise, the
dataset acts as a FIFO queue, and the oldest comparisons are evicted
when `push()` is called and the dataset is at max capacity.
"""
self.fragments1: List[TrajectoryWithRew] = []
self.fragments2: List[TrajectoryWithRew] = []
self.max_size = max_size
self.preferences: np.ndarray = np.array([])
def push(self, fragments: Sequence[TrajectoryWithRewPair], preferences: np.ndarray):
"""Add more samples to the dataset.
Args:
fragments: list of pairs of trajectory fragments to add
preferences: corresponding preference probabilities (probability
that fragment 1 is preferred over fragment 2)
Raises:
ValueError: `preferences` shape does not match `fragments` or
has non-float32 dtype.
"""
fragments1, fragments2 = zip(*fragments)
if preferences.shape != (len(fragments),):
raise ValueError(
f"Unexpected preferences shape {preferences.shape}, "
f"expected {(len(fragments),)}",
)
if preferences.dtype != np.float32:
raise ValueError("preferences should have dtype float32")
self.fragments1.extend(fragments1)
self.fragments2.extend(fragments2)
self.preferences = np.concatenate((self.preferences, preferences))
# Evict old samples if the dataset is at max capacity
if self.max_size is not None:
extra = len(self.preferences) - self.max_size
if extra > 0:
self.fragments1 = self.fragments1[extra:]
self.fragments2 = self.fragments2[extra:]
self.preferences = self.preferences[extra:]
def __getitem__(self, i) -> Tuple[TrajectoryWithRewPair, float]:
return (self.fragments1[i], self.fragments2[i]), self.preferences[i]
def __len__(self) -> int:
assert len(self.fragments1) == len(self.fragments2) == len(self.preferences)
return len(self.fragments1)
def save(self, path: AnyPath) -> None:
with open(path, "wb") as file:
pickle.dump(self, file)
@staticmethod
def load(path: AnyPath) -> "PreferenceDataset":
with open(path, "rb") as file:
return pickle.load(file)
def preference_collate_fn(
batch: Sequence[Tuple[TrajectoryWithRewPair, float]],
) -> Tuple[Sequence[TrajectoryWithRewPair], np.ndarray]:
fragment_pairs, preferences = zip(*batch)
return list(fragment_pairs), np.array(preferences)
class LossAndMetrics(NamedTuple):
"""Loss and auxiliary metrics for reward network training."""
loss: th.Tensor
metrics: Mapping[str, th.Tensor]
class RewardLoss(nn.Module, abc.ABC):
"""A loss function over preferences."""
@abc.abstractmethod
def forward(
self,
fragment_pairs: Sequence[TrajectoryPair],
preferences: np.ndarray,
preference_model: PreferenceModel,