relearn 0.3.1

A Reinforcement Learning library
Documentation
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
//! Utilities for calculating step history features.
use crate::envs::Successor;
use crate::simulation::PartialStep;
use crate::spaces::{FeatureSpace, ReprSpace, Space};
use crate::torch::packed::{PackedSeqIter, PackedStructure, PackedTensor};
use crate::torch::ExclusiveTensor;
use crate::utils::sequence::Sequence;
use ndarray::Axis;
use once_cell::unsync::OnceCell;
use std::cmp::Reverse;
use tch::{Device, Tensor};

/// View features of a (mini-)batch of collected history.
///
/// Floating-point tensors are `f32`.
pub trait HistoryFeatures {
    /// Packed observation features. A 2D `f32` tensor.
    fn observation_features(&self) -> &PackedTensor;

    /// Packed extended observation features. Includes interrupted successor observations.
    ///
    /// # Returns
    /// * `extended_observations` - A 2D `f32` tensor. Rows are the features of `step.observation`
    ///     for each step in an episode followed by the features of `step.next` on the last step of
    ///     the episode if it is `Step::Interrupt` or zeros otherwise.
    /// * `is_invalid` - A 1D boolean tensor with length equal to the number of rows of
    ///     `extended_observations`. Is `true` where the corresponding row of
    ///     `extended_observations` is invalid (non-interrupted end-of-episode).
    fn extended_observation_features(&self) -> (&PackedTensor, &PackedTensor);

    /// Packed action values.
    ///
    /// A tensor of any type and shape, apart from the first dimension along which actions are
    /// packed. Appropriate for passing to [`ParameterizedDistributionSpace`] methods.
    ///
    /// [`ParameterizedDistributionSpace`]: crate::spaces::ParameterizedDistributionSpace
    fn actions(&self) -> &PackedTensor;

    /// Packed rewards. A 1D f32 tensor.
    fn rewards(&self) -> &PackedTensor;

    /// Device on which tensors will be placed.
    fn device(&self) -> Device;
}

/// Packed history features with lazy evaluation and caching.
#[derive(Debug)]
pub struct LazyHistoryFeatures<'a, OS: Space + ?Sized, AS: Space + ?Sized, E> {
    /// Episodes sorted in monotonic decreasing order of length
    episodes: Vec<E>,
    observation_space: &'a OS,
    action_space: &'a AS,
    device: Device,

    /// Structure representing sequences that are 1 longer than each episode
    extended_structure: PackedStructure,

    cached_observation_features: OnceCell<PackedTensor>,
    cached_extended_observation_features: OnceCell<(PackedTensor, PackedTensor)>,
    cached_actions: OnceCell<PackedTensor>,
    cached_rewards: OnceCell<PackedTensor>,
}

impl<'a, OS, AS, E> LazyHistoryFeatures<'a, OS, AS, E>
where
    OS: Space + ?Sized,
    AS: Space + ?Sized,
    E: Sequence,
{
    pub fn new<I>(
        episodes: I,
        observation_space: &'a OS,
        action_space: &'a AS,
        device: Device,
    ) -> Self
    where
        I: IntoIterator<Item = E>,
    {
        let mut episodes: Vec<_> = episodes.into_iter().collect();
        episodes.sort_unstable_by_key(|ep| Reverse(ep.len()));

        let extended_structure =
            PackedStructure::from_sorted_sequence_lengths(episodes.iter().map(|ep| ep.len() + 1))
                .unwrap();

        Self {
            episodes,
            observation_space,
            action_space,
            device,
            extended_structure,
            cached_observation_features: OnceCell::new(),
            cached_extended_observation_features: OnceCell::new(),
            cached_actions: OnceCell::new(),
            cached_rewards: OnceCell::new(),
        }
    }

    pub fn num_steps(&self) -> usize {
        self.extended_structure.len() - self.episodes.len()
    }

    pub fn num_episodes(&self) -> usize {
        self.episodes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.episodes.is_empty()
    }

    /// Regular non-extended structure
    fn structure(&self) -> PackedStructure {
        self.extended_structure.clone().trim(1)
    }
}

impl<'a, OS, AS, E> HistoryFeatures for LazyHistoryFeatures<'a, OS, AS, E>
where
    OS: FeatureSpace + ?Sized,
    AS: ReprSpace<Tensor> + ?Sized,
    // Like &'a [PartialStep<O, A>]
    E: Sequence<Item = &'a PartialStep<OS::Element, AS::Element>>
        + IntoIterator<Item = &'a PartialStep<OS::Element, AS::Element>>
        + Copy,
    E::IntoIter: DoubleEndedIterator,
{
    fn observation_features(&self) -> &PackedTensor {
        self.cached_observation_features.get_or_init(|| {
            let tensor = self
                .observation_space
                .batch_features::<_, Tensor>(
                    PackedSeqIter::from_sorted(&self.episodes).map(|step| &step.observation),
                )
                .to(self.device);
            PackedTensor::from_parts(tensor, self.structure())
        })
    }

    fn extended_observation_features(&self) -> (&PackedTensor, &PackedTensor) {
        let (extended_observations, is_invalid) =
            self.cached_extended_observation_features.get_or_init(|| {
                let observations = PackedSeqIter::from_sorted(
                    self.episodes
                        .iter()
                        .copied()
                        .map(ExtendedEpisodeObservations::from),
                );
                let num_observations = observations.len();
                let num_features = self.observation_space.num_features();

                let mut extended_observations =
                    ExclusiveTensor::<f32, _>::zeros((num_observations, num_features));
                let mut is_invalid = ExclusiveTensor::<bool, _>::zeros(num_observations);
                {
                    let mut extended_observations = extended_observations.array_view_mut();
                    let mut is_invalid = is_invalid.array_view_mut();
                    for (i, obs) in observations.enumerate() {
                        if let Some(obs) = obs {
                            self.observation_space.features_out(
                                obs,
                                extended_observations
                                    .index_axis_mut(Axis(0), i)
                                    .as_slice_mut()
                                    .unwrap(),
                                true,
                            );
                        } else {
                            is_invalid[i] = true;
                        }
                    }
                }

                let packed_extended_observations = PackedTensor::from_parts(
                    extended_observations.into_tensor().to(self.device),
                    self.extended_structure.clone(),
                );
                let packed_is_invalid = PackedTensor::from_parts(
                    is_invalid.into_tensor().to(self.device),
                    self.extended_structure.clone(),
                );

                (packed_extended_observations, packed_is_invalid)
            });
        (extended_observations, is_invalid)
    }

    fn actions(&self) -> &PackedTensor {
        self.cached_actions.get_or_init(|| {
            let tensor = self
                .action_space
                .batch_repr(PackedSeqIter::from_sorted(&self.episodes).map(|step| &step.action))
                .to(self.device);
            PackedTensor::from_parts(tensor, self.structure())
        })
    }

    #[allow(clippy::cast_possible_truncation)]
    fn rewards(&self) -> &PackedTensor {
        self.cached_rewards.get_or_init(|| {
            let tensor = Tensor::of_slice(
                &PackedSeqIter::from_sorted(&self.episodes)
                    .map(|step| f64::from(step.feedback) as f32)
                    .collect::<Vec<_>>(),
            )
            .to(self.device);
            PackedTensor::from_parts(tensor, self.structure())
        })
    }

    fn device(&self) -> Device {
        self.device
    }
}

/// View an episode as a `Sequence` of observations: one per step followed by the final successor.
///
/// All items are `Some` except possibly the final successor observation, which is `None` for
/// `Successor::Terminate` or empty episodes.
struct ExtendedEpisodeObservations<E> {
    episode: E,
}

impl<E> From<E> for ExtendedEpisodeObservations<E> {
    fn from(episode: E) -> Self {
        Self { episode }
    }
}

impl<'a, E, O, A> Sequence for ExtendedEpisodeObservations<E>
where
    E: Sequence<Item = &'a PartialStep<O, A>>,
    O: 'a,
    A: 'a,
{
    type Item = Option<&'a O>;
    fn len(&self) -> usize {
        // Each step plus the final successor.
        self.episode.len() + 1
    }
    fn is_empty(&self) -> bool {
        false
    }
    fn get(&self, idx: usize) -> Option<Self::Item> {
        match self.episode.get(idx) {
            // Within episode
            Some(step) => Some(Some(&step.observation)),
            // One past the end of an empty episode
            None if idx == 0 => Some(None),
            // One past the end of a non-empty episode
            None if idx == self.episode.len() => {
                // Return step.next if the episode was interrupted, otherwise None
                match &self.episode.get(idx - 1).unwrap().next {
                    Successor::Interrupt(obs) => Some(Some(obs)),
                    _ => Some(None),
                }
            }
            // More than one past the end of the episode
            _ => None,
        }
    }
}

#[cfg(test)]
#[allow(clippy::needless_pass_by_value)]
pub(crate) mod tests {
    use super::*;
    use crate::envs::Successor::{Continue, Interrupt, Terminate};
    use crate::feedback::Reward;
    use crate::spaces::{BooleanSpace, IndexSpace};
    use rstest::{fixture, rstest};

    pub struct StoredHistory<OS: Space, AS: Space> {
        episodes: Vec<Vec<PartialStep<OS::Element, AS::Element>>>,
        observation_space: OS,
        action_space: AS,
        device: Device,
    }

    impl<OS: Space, AS: Space> StoredHistory<OS, AS> {
        #[allow(clippy::type_complexity)]
        pub fn features(
            &self,
        ) -> LazyHistoryFeatures<OS, AS, &[PartialStep<OS::Element, AS::Element>]> {
            LazyHistoryFeatures::new(
                self.episodes.iter().map(AsRef::as_ref),
                &self.observation_space,
                &self.action_space,
                self.device,
            )
        }
    }

    #[fixture]
    pub fn history() -> StoredHistory<BooleanSpace, IndexSpace> {
        let episodes = vec![
            vec![
                PartialStep::new(true, 0, Reward(1.0), Continue(())),
                PartialStep::new(true, 1, Reward(1.0), Continue(())),
                PartialStep::new(true, 2, Reward(1.0), Continue(())),
                PartialStep::new(true, 3, Reward(1.0), Continue(())),
            ],
            vec![
                PartialStep::new(false, 10, Reward(-1.0), Continue(())),
                PartialStep::new(false, 11, Reward(-1.0), Continue(())),
                PartialStep::new(false, 12, Reward(0.0), Continue(())),
                PartialStep::new(false, 13, Reward(0.0), Continue(())),
                PartialStep::new(false, 14, Reward(1.0), Continue(())),
                PartialStep::new(false, 15, Reward(1.0), Terminate),
            ],
            vec![
                PartialStep::new(false, 20, Reward(2.0), Continue(())),
                PartialStep::new(true, 21, Reward(2.0), Continue(())),
                PartialStep::new(false, 22, Reward(2.0), Interrupt(true)),
            ],
            vec![PartialStep::new(true, 30, Reward(3.0), Terminate)],
        ];

        // Packing order (by action)
        // [10, 0, 20, 30,
        //  11, 1, 21,
        //  12, 2, 22,
        //  13, 3,
        //  14,
        //  15]

        StoredHistory {
            episodes,
            observation_space: BooleanSpace::new(),
            action_space: IndexSpace::new(31),
            device: Device::Cpu,
        }
    }

    #[rstest]
    fn num_steps(history: StoredHistory<BooleanSpace, IndexSpace>) {
        assert_eq!(history.features().num_steps(), 14);
    }

    #[rstest]
    fn num_episodes(history: StoredHistory<BooleanSpace, IndexSpace>) {
        assert_eq!(history.features().num_episodes(), 4);
    }

    #[rstest]
    fn is_empty(history: StoredHistory<BooleanSpace, IndexSpace>) {
        assert!(!history.features().is_empty());
    }

    #[rstest]
    fn device(history: StoredHistory<BooleanSpace, IndexSpace>) {
        assert_eq!(history.features().device(), Device::Cpu);
    }

    #[rstest]
    fn observation_features(history: StoredHistory<BooleanSpace, IndexSpace>) {
        let features = history.features();
        let actual = features.observation_features();
        let expected = &Tensor::of_slice(&[
            0.0, 1.0, 0.0, 1.0, //
            0.0, 1.0, 1.0, //
            0.0, 1.0, 0.0, //
            0.0, 1.0, //
            0.0, //
            0.0f32,
        ])
        .unsqueeze(-1);
        assert_eq!(actual.tensor(), expected);
    }

    #[rstest]
    fn actions(history: StoredHistory<BooleanSpace, IndexSpace>) {
        let features = history.features();
        let actual = features.actions();
        let expected = &Tensor::of_slice(&[
            10, 0, 20, 30, //
            11, 1, 21, //
            12, 2, 22, //
            13, 3,  //
            14, //
            15i64,
        ]);
        assert_eq!(actual.tensor(), expected);
    }

    #[rstest]
    fn actions_batch_sizes_tensor(history: StoredHistory<BooleanSpace, IndexSpace>) {
        assert_eq!(
            history.features().actions().batch_sizes_tensor(),
            Tensor::of_slice(&[4, 3, 3, 2, 1, 1])
        );
    }

    #[rstest]
    fn rewards(history: StoredHistory<BooleanSpace, IndexSpace>) {
        let features = history.features();
        let actual = features.rewards();
        let expected = &Tensor::of_slice(&[
            -1.0, 1.0, 2.0, 3.0, //
            -1.0, 1.0, 2.0, //
            0.0, 1.0, 2.0, //
            0.0, 1.0, //
            1.0, //
            1.0f32,
        ]);
        assert_eq!(actual.tensor(), expected);
    }
}