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
//! Utilities for calculating step history features.
use crate::spaces::{BatchFeatureSpace, ReprSpace, Space};
use crate::utils::packed::{self, PackedBatchSizes, PackingIndices};
use crate::Step;
use lazycell::LazyCell;
use std::ops::Range;
use tch::{Device, Tensor};

/// View packed history features
pub trait PackedHistoryFeaturesView {
    /// Discount factor for calculating returns.
    fn discount_factor(&self) -> f64;

    /// Episode index ranges sorted in decreasing order of episode length.
    fn episode_ranges(&self) -> &[Range<usize>];

    /// Batch sizes in the packing.
    ///
    /// Note: Batch sizes are always >= 0 but the [tch] API uses i64.
    fn batch_sizes(&self) -> &[i64];

    /// Batch sizes in the packing. A 1D i64 tensor.
    fn batch_sizes_tensor(&self) -> &Tensor;

    /// Packed observation features. A 2D f64 tensor.
    fn observation_features(&self) -> &Tensor;

    /// 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) -> &Tensor;

    /// Packed returns (discounted reward-to-go). A 1D f32 tensor.
    fn returns(&self) -> &Tensor;

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

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

/// Packed history features with lazy evaluation and caching.
#[derive(Debug)]
pub struct LazyPackedHistoryFeatures<'a, OS: Space, AS: Space> {
    steps: &'a [Step<OS::Element, AS::Element>],
    episode_ranges: Vec<Range<usize>>,
    observation_space: &'a OS,
    action_space: &'a AS,
    discount_factor: f64,
    device: Device,

    cached_batch_sizes: LazyCell<Vec<i64>>,
    cached_batch_sizes_tensor: LazyCell<Tensor>,
    cached_observation_features: LazyCell<Tensor>,
    cached_actions: LazyCell<Tensor>,
    cached_returns: LazyCell<Tensor>,
    cached_rewards: LazyCell<Tensor>,
}

impl<'a, OS: Space, AS: Space> LazyPackedHistoryFeatures<'a, OS, AS> {
    pub fn new<I>(
        steps: &'a [Step<OS::Element, AS::Element>],
        episode_ranges: I,
        observation_space: &'a OS,
        action_space: &'a AS,
        discount_factor: f64,
        device: Device,
    ) -> Self
    where
        I: IntoIterator<Item = Range<usize>>,
    {
        let episode_ranges = sorted_episode_ranges(episode_ranges);
        Self {
            steps,
            episode_ranges,
            observation_space,
            action_space,
            discount_factor,
            device,
            cached_batch_sizes: LazyCell::new(),
            cached_batch_sizes_tensor: LazyCell::new(),
            cached_observation_features: LazyCell::new(),
            cached_actions: LazyCell::new(),
            cached_returns: LazyCell::new(),
            cached_rewards: LazyCell::new(),
        }
    }

    /// Finalize this into a structure of the current values in cache.
    pub fn finalize(self) -> PackedHistoryFeatures {
        PackedHistoryFeatures {
            discount_factor: self.discount_factor,
            episode_ranges: self.episode_ranges,
            batch_sizes: self.cached_batch_sizes.into_inner(),
            batch_sizes_tensor: self.cached_batch_sizes_tensor.into_inner(),
            observation_features: self.cached_observation_features.into_inner(),
            actions: self.cached_actions.into_inner(),
            returns: self.cached_returns.into_inner(),
            rewards: self.cached_rewards.into_inner(),
            device: self.device,
        }
    }
}

impl<'a, OS, AS> PackedHistoryFeaturesView for LazyPackedHistoryFeatures<'a, OS, AS>
where
    OS: BatchFeatureSpace<Tensor>,
    AS: ReprSpace<Tensor>,
{
    fn discount_factor(&self) -> f64 {
        self.discount_factor
    }

    fn episode_ranges(&self) -> &[Range<usize>] {
        &self.episode_ranges
    }

    fn batch_sizes(&self) -> &[i64] {
        self.cached_batch_sizes.borrow_with(|| {
            packing_batch_sizes(&self.episode_ranges)
                .map(|x| x as i64)
                .collect()
        })
    }

    fn batch_sizes_tensor(&self) -> &Tensor {
        // Must stay on the CPU
        self.cached_batch_sizes_tensor
            .borrow_with(|| Tensor::of_slice(self.batch_sizes()))
    }

    fn observation_features(&self) -> &Tensor {
        self.cached_observation_features.borrow_with(|| {
            packed_observation_features(
                self.steps,
                &self.episode_ranges,
                self.observation_space,
                self.device,
            )
        })
    }

    fn actions(&self) -> &Tensor {
        self.cached_actions.borrow_with(|| {
            packed_actions(
                self.steps,
                &self.episode_ranges,
                self.action_space,
                self.device,
            )
        })
    }

    fn returns(&self) -> &Tensor {
        self.cached_returns.borrow_with(|| {
            packed_returns(
                self.rewards(),
                self.batch_sizes(),
                self.discount_factor,
                self.device,
            )
        })
    }

    fn rewards(&self) -> &Tensor {
        self.cached_rewards
            .borrow_with(|| packed_rewards(self.steps, &self.episode_ranges, self.device))
    }

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

/// Packed history features.
///
/// # Panics
/// The [`PackedHistoryFeaturesView`] this provides will panic
/// if the requested features is not available.
#[derive(Debug, PartialEq)]
pub struct PackedHistoryFeatures {
    pub discount_factor: f64,
    pub episode_ranges: Vec<Range<usize>>,
    pub batch_sizes: Option<Vec<i64>>,
    pub batch_sizes_tensor: Option<Tensor>,
    pub observation_features: Option<Tensor>,
    pub actions: Option<Tensor>,
    pub returns: Option<Tensor>,
    pub rewards: Option<Tensor>,
    pub device: Device,
}

impl PackedHistoryFeaturesView for PackedHistoryFeatures {
    fn discount_factor(&self) -> f64 {
        self.discount_factor
    }

    fn episode_ranges(&self) -> &[Range<usize>] {
        &self.episode_ranges
    }

    fn batch_sizes(&self) -> &[i64] {
        self.batch_sizes
            .as_ref()
            .expect("batch_sizes has not been evaluated")
    }

    fn batch_sizes_tensor(&self) -> &Tensor {
        self.batch_sizes_tensor
            .as_ref()
            .expect("batch_sizes has not been evaluated")
    }

    fn observation_features(&self) -> &Tensor {
        self.observation_features
            .as_ref()
            .expect("observation_features has not been evaluated")
    }

    fn actions(&self) -> &Tensor {
        self.actions
            .as_ref()
            .expect("actions has not been evaluated")
    }

    fn returns(&self) -> &Tensor {
        self.returns
            .as_ref()
            .expect("returns has not been evaluated")
    }

    /// Packed rewards. A 1D f32 tensor.
    fn rewards(&self) -> &Tensor {
        self.rewards
            .as_ref()
            .expect("rewards has not been evaluated")
    }

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

/// Episode index ranges sorted in decreasing order of episode length.
///
/// Episodes must be packed in decreasing order of length.
pub fn sorted_episode_ranges<I>(ranges: I) -> Vec<Range<usize>>
where
    I: IntoIterator<Item = Range<usize>>,
{
    let mut episode_ranges: Vec<_> = ranges.into_iter().collect();
    episode_ranges.sort_by(|a, b| a.len().cmp(&b.len()).reverse());
    episode_ranges
}

/// Iterator over batch sizes in the packing
pub fn packing_batch_sizes(episode_ranges: &[Range<usize>]) -> PackedBatchSizes<Range<usize>> {
    PackedBatchSizes::from_sorted_ranges(episode_ranges)
}

/// Packed observation features. A 2D f32 tensor.
pub fn packed_observation_features<OS, A>(
    steps: &[Step<OS::Element, A>],
    episode_ranges: &[Range<usize>],
    observation_space: &OS,
    device: Device,
) -> Tensor
where
    OS: BatchFeatureSpace<Tensor>,
{
    let _no_grad = tch::no_grad_guard();
    observation_space
        .batch_features(PackingIndices::from_sorted(episode_ranges).map(|i| &steps[i].observation))
        .to(device)
}

pub fn packed_actions<O, AS>(
    steps: &[Step<O, AS::Element>],
    episode_ranges: &[Range<usize>],
    action_space: &AS,
    device: Device,
) -> Tensor
where
    AS: ReprSpace<Tensor>,
{
    let _no_grad = tch::no_grad_guard();
    action_space
        .batch_repr(PackingIndices::from_sorted(episode_ranges).map(|i| &steps[i].action))
        .to(device)
}

/// Packed step rewards. A 1D f32 tensor.
pub fn packed_rewards<S, A>(
    steps: &[Step<S, A>],
    episode_ranges: &[Range<usize>],
    device: Device,
) -> Tensor {
    let _no_grad = tch::no_grad_guard();
    #[allow(clippy::cast_possible_truncation)]
    Tensor::of_slice(
        &PackingIndices::from_sorted(episode_ranges)
            .map(|i| steps[i].reward as f32)
            .collect::<Vec<_>>(),
    )
    .to(device)
}

/// Packed step returns (discounted rewards-to-go). A 1D f32 tensor.
pub fn packed_returns(
    rewards: &Tensor,
    batch_sizes: &[i64],
    discount_factor: f64,
    device: Device,
) -> Tensor {
    let _no_grad = tch::no_grad_guard();
    packed::packed_tensor_discounted_cumsum_from_end(rewards, batch_sizes, discount_factor)
        .to(device)
}

/// Convert an iterator over steps into packed actions.
///
/// The by-value iterator is necessary because actions are not necessarily copy-able.
pub fn into_packed_actions<I, S, A>(steps: I, episode_ranges: &[Range<usize>]) -> Vec<A>
where
    I: IntoIterator<Item = Step<S, A>>,
{
    // Put into Option so that we can take the action when packing.
    let mut some_actions: Vec<_> = steps.into_iter().map(|step| Some(step.action)).collect();
    PackingIndices::from_sorted(episode_ranges)
        .map(|i| some_actions[i].take().unwrap())
        .collect()
}