modurl 0.1.0

Modular reinforcement learning algorithms and utilities built on Candle
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
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
use std::num::NonZeroUsize;

use candle_core::Tensor;
use candle_nn::Module;

use crate::distributions::{DifferentiableExpectation, Distribution, ExpectationTerms};

pub trait ProbabilisticPolicy {
    type Error;
    /// Samples actions shaped `[batch_size, ...action_shape]` from states
    /// shaped `[batch_size, ...state_shape]`.
    fn sample(&self, state: &Tensor) -> Result<Tensor, Self::Error>;
    /// Returns modal actions shaped `[batch_size, ...action_shape]` for states
    /// shaped `[batch_size, ...state_shape]`.
    fn mode(&self, state: &Tensor) -> Result<Tensor, Self::Error>;
    /// Evaluates `action` shaped `[batch_size, ...action_shape]` for `state`
    /// shaped `[batch_size, ...state_shape]`.
    ///
    /// Returns log probability and entropy tensors shaped `[batch_size]`.
    fn log_prob_and_entropy(
        &self,
        state: &Tensor,
        action: &Tensor,
    ) -> Result<(Tensor, Tensor), Self::Error>;
}

/// Policy extension used by algorithms that optimize an exact or
/// reparameterized action expectation (notably SAC).
pub trait ExpectationPolicy: ProbabilisticPolicy {
    /// Builds expectation terms for `state` shaped
    /// `[batch_size, ...state_shape]`.
    fn expectation(
        &self,
        state: &Tensor,
        samples: NonZeroUsize,
    ) -> Result<ExpectationTerms, Self::Error>;

    /// Returns the default target entropy for `state` shaped
    /// `[batch_size, ...state_shape]`.
    fn default_target_entropy(&self, state: &Tensor) -> Result<f64, Self::Error>;
}

pub struct ProbabilisticPolicyModel<D>
where
    D: Distribution,
{
    module: Box<dyn Module>,
    distribution: D,
}

impl<D> ProbabilisticPolicyModel<D>
where
    D: Distribution + Default,
    <D as Distribution>::Error: std::fmt::Debug,
{
    pub fn new(module: impl Module + 'static) -> Self {
        Self {
            module: Box::new(module),
            distribution: D::default(),
        }
    }
}

impl<D> ProbabilisticPolicyModel<D>
where
    D: Distribution,
    <D as Distribution>::Error: std::fmt::Debug,
{
    /// Creates a policy with an explicitly configured distribution operator.
    pub fn with_distribution(module: impl Module + 'static, distribution: D) -> Self {
        Self {
            module: Box::new(module),
            distribution,
        }
    }

    pub fn distribution(&self) -> &D {
        &self.distribution
    }

    /// Maps `state` `[batch, ...state_shape]` to distribution parameters
    /// `[batch, ...parameter_shape]`.
    fn outputs(&self, state: &Tensor) -> candle_core::Result<Tensor> {
        self.module.forward(state)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ProbabilisticPolicyModelError<DE>
where
    DE: std::fmt::Debug,
{
    #[error("policy module failed: {0}")]
    ModuleError(#[source] candle_core::Error),
    #[error("policy distribution failed: {0}")]
    DistError(#[source] DE),
}

impl<DE> From<candle_core::Error> for ProbabilisticPolicyModelError<DE>
where
    DE: std::fmt::Debug,
{
    fn from(error: candle_core::Error) -> Self {
        ProbabilisticPolicyModelError::ModuleError(error)
    }
}

impl<D> ProbabilisticPolicy for ProbabilisticPolicyModel<D>
where
    D: Distribution,
    <D as Distribution>::Error: std::fmt::Debug,
{
    type Error = ProbabilisticPolicyModelError<<D as Distribution>::Error>;

    /// Maps states `[batch, ...state_shape]` to sampled actions
    /// `[batch, ...action_shape]`.
    fn sample(&self, state: &Tensor) -> Result<Tensor, Self::Error> {
        let outputs = self.outputs(state)?;
        self.distribution
            .sample(&outputs)
            .map_err(ProbabilisticPolicyModelError::DistError)
    }

    /// Maps states `[batch, ...state_shape]` to modal actions
    /// `[batch, ...action_shape]`.
    fn mode(&self, state: &Tensor) -> Result<Tensor, Self::Error> {
        let outputs = self.outputs(state)?;
        self.distribution
            .mode(&outputs)
            .map_err(ProbabilisticPolicyModelError::DistError)
    }

    /// Evaluates actions `[batch, ...action_shape]` for states
    /// `[batch, ...state_shape]`, returning two `[batch]` tensors.
    fn log_prob_and_entropy(
        &self,
        state: &Tensor,
        action: &Tensor,
    ) -> Result<(Tensor, Tensor), Self::Error> {
        let outputs = self.outputs(state)?;
        let dist_eval = self
            .distribution
            .dist_eval(&outputs, action)
            .map_err(ProbabilisticPolicyModelError::DistError)?;

        let log_prob = dist_eval.log_prob().clone();
        let entropy = dist_eval.entropy().clone();
        Ok((log_prob, entropy))
    }
}

impl<D> ExpectationPolicy for ProbabilisticPolicyModel<D>
where
    D: DifferentiableExpectation,
    <D as Distribution>::Error: std::fmt::Debug,
{
    /// Builds candidates `[batch, candidates, ...action_shape]` for states
    /// `[batch, ...state_shape]`.
    fn expectation(
        &self,
        state: &Tensor,
        samples: NonZeroUsize,
    ) -> Result<ExpectationTerms, Self::Error> {
        let outputs = self.outputs(state)?;
        self.distribution
            .expectation(&outputs, samples)
            .map_err(ProbabilisticPolicyModelError::DistError)
    }

    /// Computes target entropy for states `[batch, ...state_shape]`.
    fn default_target_entropy(&self, state: &Tensor) -> Result<f64, Self::Error> {
        let outputs = self.outputs(state)?.detach();
        self.distribution
            .default_target_entropy(&outputs)
            .map_err(ProbabilisticPolicyModelError::DistError)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{distributions::GaussianDistribution, models::MLP};
    use candle_core::{DType, Device, Tensor};
    use candle_nn::{Activation, VarBuilder, VarMap};

    fn create_test_policy(
        input_size: usize,
        action_size: usize,
        hidden_sizes: Vec<usize>,
    ) -> Result<ProbabilisticPolicyModel<GaussianDistribution>, candle_core::Error> {
        let device = Device::Cpu;
        let varmap = VarMap::new();
        let vb = VarBuilder::from_varmap(&varmap, DType::F64, &device);

        // Output size is double action_size for mean and std
        let mlp = MLP::builder()
            .input_size(input_size)
            .output_size(action_size * 2)
            .vb(vb)
            .hidden_layer_sizes(hidden_sizes)
            .activation(Activation::Relu)
            .build()?;

        Ok(ProbabilisticPolicyModel::new(mlp))
    }

    #[test]
    fn configured_distribution_is_stored_by_the_policy() {
        use crate::distributions::{TanhTransform, TransformedDistribution};

        let device = Device::Cpu;
        let varmap = VarMap::new();
        let mlp = MLP::builder()
            .input_size(2)
            .output_size(2)
            .vb(VarBuilder::from_varmap(&varmap, DType::F32, &device))
            .hidden_layer_sizes(vec![4])
            .build()
            .unwrap();
        let policy = ProbabilisticPolicyModel::with_distribution(
            mlp,
            TransformedDistribution::new(GaussianDistribution::default(), TanhTransform),
        );
        let actions = policy
            .sample(&Tensor::zeros((3, 2), DType::F32, &device).unwrap())
            .unwrap();
        assert_eq!(actions.dims(), &[3, 1]);
        assert!(
            actions
                .abs()
                .unwrap()
                .max_all()
                .unwrap()
                .to_scalar::<f32>()
                .unwrap()
                <= 1.0
        );
    }

    fn create_test_state(
        batch_size: usize,
        state_dim: usize,
    ) -> Result<Tensor, candle_core::Error> {
        Tensor::randn(0.0, 1.0, (batch_size, state_dim), &Device::Cpu)
    }

    #[test]
    fn test_policy_creation() {
        let policy = create_test_policy(4, 2, vec![32, 32]);
        assert!(policy.is_ok(), "Failed to create probabilistic policy");
    }

    #[test]
    fn test_sample_action_shape() {
        let policy = create_test_policy(4, 2, vec![32, 32]).unwrap();
        let state = create_test_state(1, 4).unwrap();

        let action = policy.sample(&state).unwrap();

        // Action should have shape [batch_size, action_dim]
        assert_eq!(action.dims(), &[1, 2]);
    }

    #[test]
    fn test_sample_batch_consistency() {
        let policy = create_test_policy(4, 2, vec![32, 32]).unwrap();
        let batch_sizes = vec![1, 5, 10];

        for batch_size in batch_sizes {
            let state = create_test_state(batch_size, 4).unwrap();
            let action = policy.sample(&state).unwrap();

            assert_eq!(
                action.dims(),
                &[batch_size, 2],
                "Action shape incorrect for batch size {}",
                batch_size
            );
        }
    }

    #[test]
    fn test_log_prob_and_entropy_shape() {
        let policy = create_test_policy(4, 2, vec![32, 32]).unwrap();
        let batch_size = 5;
        let state = create_test_state(batch_size, 4).unwrap();
        let action = create_test_state(batch_size, 2).unwrap();

        let (log_prob, entropy) = policy.log_prob_and_entropy(&state, &action).unwrap();

        // Both should have shape [batch_size]
        assert_eq!(log_prob.dims(), &[batch_size]);
        assert_eq!(entropy.dims(), &[batch_size]);
    }

    #[test]
    fn test_entropy_is_positive() {
        let policy = create_test_policy(4, 2, vec![32, 32]).unwrap();
        let state = create_test_state(1, 4).unwrap();
        let action = create_test_state(1, 2).unwrap();

        let (_, entropy) = policy.log_prob_and_entropy(&state, &action).unwrap();
        let entropy_val = entropy.to_vec1::<f64>().unwrap()[0];

        // Entropy should generally be positive for continuous distributions
        assert!(
            entropy_val.is_finite(),
            "Entropy is not finite: {}",
            entropy_val
        );
        assert!(
            entropy_val > -100.0,
            "Entropy is not reasonable: {}",
            entropy_val
        );
        assert!(entropy_val < 100.0, "Entropy is too large: {}", entropy_val);
    }

    #[test]
    fn test_log_prob_is_finite() {
        let policy = create_test_policy(4, 2, vec![32, 32]).unwrap();
        let state = create_test_state(3, 4).unwrap();
        let action = create_test_state(3, 2).unwrap();

        let (log_prob, _) = policy.log_prob_and_entropy(&state, &action).unwrap();
        let log_prob_vals = log_prob.to_vec1::<f64>().unwrap();

        for (i, val) in log_prob_vals.iter().enumerate() {
            assert!(
                val.is_finite(),
                "Log probability {} is not finite: {}",
                i,
                val
            );
        }
    }

    #[test]
    fn test_deterministic_with_same_state() {
        let policy = create_test_policy(4, 2, vec![32, 32]).unwrap();
        let state = Tensor::zeros((1, 4), candle_core::DType::F64, &Device::Cpu).unwrap();
        let action = Tensor::zeros((1, 2), candle_core::DType::F64, &Device::Cpu).unwrap();

        // Multiple calls with same input should give same log_prob and entropy
        let (log_prob1, entropy1) = policy.log_prob_and_entropy(&state, &action).unwrap();
        let (log_prob2, entropy2) = policy.log_prob_and_entropy(&state, &action).unwrap();

        let log_prob1_val = log_prob1.to_vec1::<f64>().unwrap()[0];
        let log_prob2_val = log_prob2.to_vec1::<f64>().unwrap()[0];
        let entropy1_val = entropy1.to_vec1::<f64>().unwrap()[0];
        let entropy2_val = entropy2.to_vec1::<f64>().unwrap()[0];

        assert!(
            (log_prob1_val - log_prob2_val).abs() < 1e-6,
            "Log probabilities should be deterministic"
        );
        assert!(
            (entropy1_val - entropy2_val).abs() < 1e-6,
            "Entropies should be deterministic"
        );
    }

    #[test]
    fn test_different_action_sizes() {
        let action_sizes = vec![1, 2, 4, 8];

        for action_size in action_sizes {
            let policy = create_test_policy(4, action_size, vec![32, 32]).unwrap();
            let state = create_test_state(1, 4).unwrap();
            let action = policy.sample(&state).unwrap();

            assert_eq!(
                action.dims(),
                &[1, action_size],
                "Action size incorrect for action_size {}",
                action_size
            );
        }
    }

    #[test]
    fn configured_gaussian_policy_preserves_multidimensional_actions() {
        let device = Device::Cpu;
        let varmap = VarMap::new();
        let actor = MLP::builder()
            .input_size(4)
            .output_size(12)
            .vb(VarBuilder::from_varmap(&varmap, DType::F64, &device))
            .hidden_layer_sizes(vec![8])
            .build()
            .unwrap();
        let policy = ProbabilisticPolicyModel::with_distribution(
            actor,
            GaussianDistribution::new(vec![2, 3]).unwrap(),
        );
        let states = create_test_state(5, 4).unwrap();
        let actions = policy.sample(&states).unwrap();
        assert_eq!(actions.dims(), &[5, 2, 3]);

        let (log_probabilities, entropies) =
            policy.log_prob_and_entropy(&states, &actions).unwrap();
        assert_eq!(log_probabilities.dims(), &[5]);
        assert_eq!(entropies.dims(), &[5]);

        let terms = policy
            .expectation(&states, NonZeroUsize::new(2).unwrap())
            .unwrap();
        assert_eq!(terms.actions().dims(), &[5, 2, 2, 3]);
        assert_eq!(terms.log_probabilities().dims(), &[5, 2]);
    }

    #[test]
    fn test_log_prob_and_entropy_are_finite_for_default_network() {
        let policy = create_test_policy(4, 2, vec![32, 32]).unwrap();
        let state = create_test_state(1, 4).unwrap();
        let action = create_test_state(1, 2).unwrap();

        let (log_prob, entropy) = policy.log_prob_and_entropy(&state, &action).unwrap();
        assert!(log_prob.to_vec1::<f64>().unwrap()[0].is_finite());
        assert!(entropy.to_vec1::<f64>().unwrap()[0].is_finite());
    }

    #[test]
    fn test_gradient_flow() {
        // Test that the policy can be used in a gradient computation context
        let device = Device::Cpu;
        let varmap = VarMap::new();
        let vb = VarBuilder::from_varmap(&varmap, DType::F64, &device);

        let mlp = MLP::builder()
            .input_size(4)
            .output_size(4)
            .vb(vb)
            .hidden_layer_sizes(vec![16])
            .activation(Activation::Relu)
            .build()
            .unwrap();

        let policy: ProbabilisticPolicyModel<GaussianDistribution> =
            ProbabilisticPolicyModel::new(mlp);
        let state = create_test_state(2, 4).unwrap();

        // Sample action
        let action = policy.sample(&state).unwrap();

        // Compute log probability
        let (log_prob, entropy) = policy.log_prob_and_entropy(&state, &action).unwrap();

        // This should work without errors - just verify no panic occurs
        let _ = (log_prob.mean(0).unwrap(), entropy.mean(0).unwrap());
    }

    #[test]
    fn fuzz_log_prob_and_entropy() {
        const FUZZ_ITERATIONS: usize = 30;

        for i in 0..FUZZ_ITERATIONS {
            let state_dim = 2 + (i % 8); // 2-9
            let action_dim = 1 + (i % 5); // 1-5
            let batch_size = 1 + (i % 15); // 1-15

            let policy = create_test_policy(state_dim, action_dim, vec![32, 32]).unwrap();
            let state = create_test_state(batch_size, state_dim).unwrap();
            let action = create_test_state(batch_size, action_dim).unwrap();

            let (log_prob, entropy) = policy.log_prob_and_entropy(&state, &action).unwrap();

            // Verify shapes
            assert_eq!(
                log_prob.dims(),
                &[batch_size],
                "Iteration {}: Log prob shape incorrect",
                i
            );
            assert_eq!(
                entropy.dims(),
                &[batch_size],
                "Iteration {}: Entropy shape incorrect",
                i
            );

            // Verify values are finite and reasonable
            let log_prob_vals = log_prob.to_vec1::<f64>().unwrap();
            let entropy_vals = entropy.to_vec1::<f64>().unwrap();

            for (j, val) in log_prob_vals.iter().enumerate() {
                assert!(
                    val.is_finite(),
                    "Iteration {}, sample {}: Log prob is not finite: {}",
                    i,
                    j,
                    val
                );
            }

            for (j, val) in entropy_vals.iter().enumerate() {
                assert!(
                    val.is_finite(),
                    "Iteration {}, sample {}: Entropy is not finite: {}",
                    i,
                    j,
                    val
                );
                assert!(
                    *val > -100.0,
                    "Iteration {}, sample {}: Entropy too negative: {}",
                    i,
                    j,
                    val
                );
            }
        }
    }

    #[test]
    fn fuzz_different_architectures() {
        const FUZZ_ITERATIONS: usize = 25;

        for i in 0..FUZZ_ITERATIONS {
            let state_dim = 2 + (i % 6); // 2-7
            let action_dim = 1 + (i % 4); // 1-4

            // Vary architecture
            let hidden_layers = match i % 4 {
                0 => vec![16],
                1 => vec![32, 16],
                2 => vec![64, 32, 16],
                _ => vec![128, 64],
            };

            let policy = create_test_policy(state_dim, action_dim, hidden_layers).unwrap();
            let state = create_test_state(5, state_dim).unwrap();

            // Test sampling
            let action = policy.sample(&state).unwrap();
            assert_eq!(
                action.dims(),
                &[5, action_dim],
                "Iteration {}: Sampling failed",
                i
            );

            // Test log prob computation
            let result = policy.log_prob_and_entropy(&state, &action);
            assert!(
                result.is_ok(),
                "Iteration {}: Log prob computation failed: {:?}",
                i,
                result.err()
            );
        }
    }

    #[test]
    fn fuzz_numerical_stability() {
        const FUZZ_ITERATIONS: usize = 40;

        for i in 0..FUZZ_ITERATIONS {
            let policy = create_test_policy(4, 2, vec![32, 32]).unwrap();

            // Create states with varying magnitudes to test numerical stability
            let scale = match i % 4 {
                0 => 0.01,
                1 => 1.0,
                2 => 5.0,
                _ => 10.0,
            };

            let mut state = create_test_state(3, 4).unwrap();
            state = (state * scale).unwrap();

            let mut action = create_test_state(3, 2).unwrap();
            action = (action * (scale * 0.1)).unwrap();

            // This should not crash or produce NaN/Inf values
            let result = policy.log_prob_and_entropy(&state, &action);
            assert!(
                result.is_ok(),
                "Iteration {} (scale={}): Computation failed: {:?}",
                i,
                scale,
                result.err()
            );

            if let Ok((log_prob, entropy)) = result {
                let log_prob_vals = log_prob.to_vec1::<f64>().unwrap();
                let entropy_vals = entropy.to_vec1::<f64>().unwrap();

                for val in log_prob_vals {
                    assert!(
                        val.is_finite(),
                        "Iteration {} (scale={}): Log prob not finite: {}",
                        i,
                        scale,
                        val
                    );
                }

                for val in entropy_vals {
                    assert!(
                        val.is_finite(),
                        "Iteration {} (scale={}): Entropy not finite: {}",
                        i,
                        scale,
                        val
                    );
                }
            }
        }
    }

    #[test]
    fn fuzz_batch_size_stress_test() {
        const FUZZ_ITERATIONS: usize = 20;

        for i in 0..FUZZ_ITERATIONS {
            // Test with various batch sizes including edge cases
            let batch_size = match i % 6 {
                0 => 1,
                1 => 2,
                2 => 5,
                3 => 10,
                4 => 50,
                _ => 100,
            };

            let policy = create_test_policy(4, 2, vec![32, 32]).unwrap();
            let state = create_test_state(batch_size, 4).unwrap();

            // Test sampling with large batches
            let action = policy.sample(&state).unwrap();
            assert_eq!(
                action.dims(),
                &[batch_size, 2],
                "Iteration {}: Batch size {} failed",
                i,
                batch_size
            );

            // Test log prob computation
            let (log_prob, entropy) = policy.log_prob_and_entropy(&state, &action).unwrap();

            assert_eq!(
                log_prob.dims(),
                &[batch_size],
                "Iteration {}: Log prob batch size incorrect",
                i
            );
            assert_eq!(
                entropy.dims(),
                &[batch_size],
                "Iteration {}: Entropy batch size incorrect",
                i
            );

            // Verify all values are finite
            let log_prob_vals = log_prob.to_vec1::<f64>().unwrap();
            let entropy_vals = entropy.to_vec1::<f64>().unwrap();

            assert!(
                log_prob_vals.iter().all(|v| v.is_finite()),
                "Iteration {}: Some log prob values not finite",
                i
            );
            assert!(
                entropy_vals.iter().all(|v| v.is_finite()),
                "Iteration {}: Some entropy values not finite",
                i
            );
        }
    }
}