burn_train/learner/rl/
strategy.rs1use std::sync::Arc;
2
3use burn_core::tensor::Device;
4
5use crate::{
6 Interrupter, LearnerSummaryConfig, OffPolicyConfig, RLCheckpointer, RLComponentsTypes, RLEvent,
7 RLEventProcessorType, RLResult,
8 metric::{processor::EventProcessorTraining, store::EventStoreClient},
9};
10
11pub struct RLComponents<RLC: RLComponentsTypes> {
13 pub label: Option<String>,
15 pub num_steps: usize,
17 pub checkpoint: Option<usize>,
19 pub checkpointer: Option<RLCheckpointer<RLC>>,
21 pub grad_accumulation: Option<usize>,
23 pub interrupter: Interrupter,
25 pub event_processor: RLEventProcessorType<RLC>,
27 pub event_store: Arc<EventStoreClient>,
29 pub summary: Option<LearnerSummaryConfig>,
31 pub inference_device: Device,
33}
34
35#[derive(Clone)]
37pub enum RLStrategies<RLC: RLComponentsTypes> {
38 OffPolicyStrategy(OffPolicyConfig),
40 Custom(CustomRLStrategy<RLC>),
42}
43
44pub type CustomRLStrategy<LC> = Arc<dyn RLStrategy<LC>>;
46
47pub trait RLStrategy<RLC: RLComponentsTypes> {
49 fn train(
51 &self,
52 mut learner_agent: RLC::LearningAgent,
53 mut training_components: RLComponents<RLC>,
54 env_init: RLC::EnvInit,
55 ) -> RLResult<RLC::Policy> {
56 let starting_epoch = training_components.checkpoint.unwrap_or(0) + 1;
57 let summary_config = training_components.summary.clone();
58 let interrupter = training_components.interrupter.clone();
59
60 interrupter.fail_on_error(training_components.event_processor.process_train(
62 RLEvent::Start {
63 total_items: training_components.num_steps,
64 label: training_components.label.clone(),
65 },
66 ));
67
68 let (policy, mut event_processor) = self.train_loop(
70 training_components,
71 &mut learner_agent,
72 starting_epoch,
73 env_init,
74 );
75
76 let summary = summary_config.and_then(|summary| summary.init().ok());
77
78 interrupter.fail_on_error(event_processor.process_train(RLEvent::End(summary)));
81
82 interrupter.fail_on_error(event_processor.flush());
86 let renderer = event_processor.renderer();
87
88 RLResult {
89 policy,
90 renderer,
91 interrupted: interrupter.interruption(),
92 error: interrupter.error(),
93 }
94 }
95
96 fn train_loop(
98 &self,
99 training_components: RLComponents<RLC>,
100 learner_agent: &mut RLC::LearningAgent,
101 starting_epoch: usize,
102 env_init: RLC::EnvInit,
103 ) -> (RLC::Policy, RLEventProcessorType<RLC>);
104}