Skip to main content

ruxla_env/
lib.rs

1//! Reinforcement learning environments with gymnax's API, which run as native
2//! code and export to JAX.
3//!
4//! An environment implements [`Environment`] with code generic over the
5//! backend: [`Environment::reset`] and [`Environment::step_env`] are pure
6//! functions of a key, a state, an action, and parameters, and
7//! [`Environment::step`] adds gymnax's automatic reset. The same code runs
8//! natively (`B = Native`, also in parallel with [`VecEnv`]), with XLA
9//! through [`jit`](ruxla_core::jit), compiled ahead of time to Rust
10//! ([`compiled`]), and inside JAX programs after [`export`]ing it for the
11//! Python package `ruxla`. Environments written in JAX can be imported
12//! ([`jax_env`]) and compiled ahead of time too.
13//!
14//! The crate contains a few reference environments, which match the
15//! originals bit for bit (or to rounding, for the floating-point physics)
16//! and serve as examples: [`CartPole`], [`Acrobot`], and [`Pendulum`]
17//! (gymnax's `CartPole-v1`, `Acrobot-v1`, and `Pendulum-v1`), [`Breakout`]
18//! (gymnax's `Breakout-MinAtar`), and [`TicTacToe`] (Pgx's `tic_tac_toe`).
19//!
20//! # Examples
21//!
22//! ```
23//! use ruxla_core::{I32, Native, random};
24//! use ruxla_env::{CartPole, Environment};
25//!
26//! let env = CartPole;
27//! let params = env.default_params::<Native>();
28//! let (obs, state) = env.reset(random::key(0), &params);
29//! let step = env.step(random::key(1), &state, I32::new(1), &params);
30//! assert_eq!(obs.shape().to_vec(), [4]);
31//! assert_eq!(step.reward.value(), 1.0);
32//! ```
33
34mod acrobot;
35mod action;
36mod breakout;
37mod cartpole;
38pub mod compiled;
39pub mod dylib;
40pub mod jax_env;
41mod package;
42mod pendulum;
43mod pool;
44pub mod testing;
45mod tic_tac_toe;
46mod vec_env;
47
48use ruxla_core::random::{self, Key};
49use ruxla_core::{Array, Backend, Bool, F32, Native, Trace, Tree, TreeDef, lax, select_tree};
50
51pub use acrobot::{Acrobot, AcrobotParams, AcrobotState};
52pub use action::{
53    ActionSpace, ActionValue, Actions, MAX_MASK_ACTIONS, choose_legal, pattern_continuous,
54    pattern_discrete, unravel_joint,
55};
56pub use breakout::{Breakout, BreakoutParams, BreakoutState};
57pub use cartpole::{CartPole, CartPoleParams, CartPoleState};
58pub use package::{ExportError, PackageWriter, SCHEMA_VERSION, export};
59pub use pendulum::{Pendulum, PendulumParams, PendulumState};
60pub use tic_tac_toe::{TicTacToe, TicTacToeState};
61pub use vec_env::{CompiledVecEnv, FlatObs, StepBuffers, VecEnv, VecStep};
62
63/// A reinforcement learning environment with gymnax's API.
64///
65/// The methods are generic over the backend and must be pure functions of
66/// their arguments. Actions are discrete (`I32`) or continuous
67/// (`Array<B, f32>`), as [`Environment::action_space`] says.
68///
69/// The bounds on the associated types say that a state on one backend
70/// becomes the same structure on the other (`State<Native>` and
71/// `State<Trace>`), which `#[derive(Tree)]` gives.
72pub trait Environment: Send + Sync + 'static {
73    /// The state of an episode.
74    type State<B: Backend>: Tree<B, On<Native> = Self::State<Native>, On<Trace> = Self::State<Trace>>;
75    /// The parameters of the environment.
76    type Params<B: Backend>: Tree<B, On<Native> = Self::Params<Native>, On<Trace> = Self::Params<Trace>>;
77    /// An observation.
78    type Obs<B: Backend>: Tree<B, On<Native> = Self::Obs<Native>, On<Trace> = Self::Obs<Trace>>;
79    /// An action: `I32<B>` for discrete actions, `Array<B, f32>` for
80    /// continuous ones.
81    type Action<B: Backend>: Tree<B, On<Native> = Self::Action<Native>, On<Trace> = Self::Action<Trace>>
82        + ActionValue<B>
83        + Clone;
84
85    /// The name, such as `"CartPole-v1"`.
86    fn name(&self) -> &str;
87
88    /// The actions (gymnax's `action_space`).
89    fn action_space(&self) -> ActionSpace;
90
91    /// The number of discrete actions (0 for continuous actions).
92    fn num_actions(&self) -> usize {
93        self.action_space().num_actions()
94    }
95
96    /// The default parameters.
97    fn default_params<B: Backend>(&self) -> Self::Params<B>;
98
99    /// Starts an episode (gymnax's `reset_env`).
100    fn reset<B: Backend>(
101        &self,
102        key: Key<B>,
103        params: &Self::Params<B>,
104    ) -> (Self::Obs<B>, Self::State<B>);
105
106    /// Advances an episode by one step, without resetting.
107    fn step_env<B: Backend>(
108        &self,
109        key: Key<B>,
110        state: &Self::State<B>,
111        action: Self::Action<B>,
112        params: &Self::Params<B>,
113    ) -> Transition<B, Self::State<B>, Self::Obs<B>>;
114
115    /// Whether `step_env` uses its key (the default). An environment whose
116    /// steps are deterministic returns `false`, so that `step` natively
117    /// splits the key only when the episode ends and the reset needs it;
118    /// the results are the same (`testing::check_backends` compares the
119    /// native results with the traced ones, which always split).
120    fn step_env_uses_key(&self) -> bool {
121        true
122    }
123
124    /// Whether the episode reached its time limit.
125    fn is_truncated<B: Backend>(&self, state: &Self::State<B>, params: &Self::Params<B>)
126    -> Bool<B>;
127
128    /// The legal actions in `state`, for environments that have them (board
129    /// games, Jumanji): a mask over the joint actions (shape `[n]`, or
130    /// `nvec` for multi-discrete actions); `None` (the default) if every
131    /// action is legal. Tests and benchmarks take legal actions with
132    /// [`choose_legal`]. Environments with more joint actions than
133    /// [`MAX_MASK_ACTIONS`] have no mask ([`ActionSpace::mask_len`] is 0).
134    fn legal_action_mask<B: Backend>(&self, state: &Self::State<B>) -> Option<Array<B, bool>> {
135        let _ = state;
136        None
137    }
138
139    /// Advances an episode by one step and starts a new one if it ended, as
140    /// gymnax's `Environment.step` does: the key is split in two, both
141    /// `step_env` and `reset` are computed, and the reset state and
142    /// observation are selected where the episode ended. Natively, the reset
143    /// is computed only when the episode ends ([`lax::select_with`]), with
144    /// the same results.
145    fn step<B: Backend>(
146        &self,
147        key: Key<B>,
148        state: &Self::State<B>,
149        action: Self::Action<B>,
150        params: &Self::Params<B>,
151    ) -> Step<B, Self::State<B>, Self::Obs<B>> {
152        let lazy = B::FAST_PATHS && !self.step_env_uses_key();
153        let (key_step, key_reset) = if lazy {
154            // The key is split below if the reset needs it; `step_env`
155            // ignores the key it gets.
156            (key.clone(), None)
157        } else {
158            let (a, b) = random::split2(&key);
159            (a, Some(b))
160        };
161        let t = self.step_env(key_step, state, action, params);
162        let truncated = self.is_truncated(&t.state, params);
163        let done = t.terminated | truncated;
164        // gymnax's `discount`: `select(terminated, 0.0, 1.0)`.
165        let discount = lax::select(t.terminated, F32::new(0.0), F32::new(1.0));
166        let (obs, state) = match B::branch_value(done) {
167            // Natively, the reset is computed only when the episode ends,
168            // and otherwise the state of the step is moved, not copied.
169            Some(true) => {
170                let key_reset = key_reset.unwrap_or_else(|| random::split2(&key).1);
171                self.reset(key_reset, params)
172            }
173            Some(false) => (t.obs.clone(), t.state),
174            None => {
175                let key_reset = key_reset.unwrap_or_else(|| random::split2(&key).1);
176                let (obs_reset, state_reset) = self.reset(key_reset, params);
177                (
178                    select_tree(done, &obs_reset, &t.obs),
179                    select_tree(done, &state_reset, &t.state),
180                )
181            }
182        };
183        Step {
184            obs,
185            state,
186            reward: t.reward,
187            terminated: t.terminated,
188            truncated,
189            final_observation: t.obs,
190            discount,
191        }
192    }
193}
194
195/// The result of [`Environment::step_env`].
196#[derive(Clone, Debug)]
197pub struct Transition<B: Backend, S, O> {
198    /// The observation after the step.
199    pub obs: O,
200    /// The state after the step.
201    pub state: S,
202    /// The reward of the step.
203    pub reward: F32<B>,
204    /// Whether the episode ended in a terminal state.
205    pub terminated: Bool<B>,
206}
207
208/// The result of [`Environment::step`], with automatic reset (gymnax's
209/// `(obs, state, reward, terminated, truncated, info)`).
210#[derive(Clone, Debug)]
211pub struct Step<B: Backend, S, O> {
212    /// The next observation: after a reset if the episode ended.
213    pub obs: O,
214    /// The next state: a fresh one if the episode ended.
215    pub state: S,
216    /// The reward of the step.
217    pub reward: F32<B>,
218    /// Whether the episode ended in a terminal state.
219    pub terminated: Bool<B>,
220    /// Whether the episode reached its time limit.
221    pub truncated: Bool<B>,
222    /// The observation reached by the step, before any reset.
223    pub final_observation: O,
224    /// 0 if the step reached a terminal state, 1 otherwise.
225    pub discount: F32<B>,
226}
227
228/// The arguments of [`Environment::step`] as one pytree: `(key, state,
229/// action, params)`.
230pub type StepInput<B, E> = (
231    Key<B>,
232    <E as Environment>::State<B>,
233    <E as Environment>::Action<B>,
234    <E as Environment>::Params<B>,
235);
236
237/// The [`Step`] of an environment.
238pub type StepOf<B, E> = Step<B, <E as Environment>::State<B>, <E as Environment>::Obs<B>>;
239
240impl<B: Backend, S: Tree<B>, O: Tree<B>> Tree<B> for Step<B, S, O> {
241    type On<C: Backend> = Step<C, S::On<C>, O::On<C>>;
242
243    fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
244        self.obs.flatten(leaves);
245        self.state.flatten(leaves);
246        self.reward.flatten(leaves);
247        self.terminated.flatten(leaves);
248        self.truncated.flatten(leaves);
249        self.final_observation.flatten(leaves);
250        self.discount.flatten(leaves);
251    }
252
253    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
254        Step {
255            obs: self.obs.unflatten_like(leaves),
256            state: self.state.unflatten_like(leaves),
257            reward: self.reward.unflatten_like(leaves),
258            terminated: self.terminated.unflatten_like(leaves),
259            truncated: self.truncated.unflatten_like(leaves),
260            final_observation: self.final_observation.unflatten_like(leaves),
261            discount: self.discount.unflatten_like(leaves),
262        }
263    }
264
265    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Self::On<C> {
266        Step {
267            obs: self.obs.rebuild::<C>(leaves),
268            state: self.state.rebuild::<C>(leaves),
269            reward: self.reward.rebuild::<C>(leaves),
270            terminated: self.terminated.rebuild::<C>(leaves),
271            truncated: self.truncated.rebuild::<C>(leaves),
272            final_observation: self.final_observation.rebuild::<C>(leaves),
273            discount: self.discount.rebuild::<C>(leaves),
274        }
275    }
276
277    fn def(&self) -> TreeDef {
278        TreeDef::Struct {
279            name: String::from("Step"),
280            fields: [
281                "obs",
282                "state",
283                "reward",
284                "terminated",
285                "truncated",
286                "final_observation",
287                "discount",
288            ]
289            .map(String::from)
290            .to_vec(),
291            children: vec![
292                self.obs.def(),
293                self.state.def(),
294                self.reward.def(),
295                self.terminated.def(),
296                self.truncated.def(),
297                self.final_observation.def(),
298                self.discount.def(),
299            ],
300        }
301    }
302
303    fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self {
304        Step {
305            obs: O::select(pred, &on_true.obs, &on_false.obs),
306            state: S::select(pred, &on_true.state, &on_false.state),
307            reward: Tree::select(pred, &on_true.reward, &on_false.reward),
308            terminated: Tree::select(pred, &on_true.terminated, &on_false.terminated),
309            truncated: Tree::select(pred, &on_true.truncated, &on_false.truncated),
310            final_observation: O::select(
311                pred,
312                &on_true.final_observation,
313                &on_false.final_observation,
314            ),
315            discount: Tree::select(pred, &on_true.discount, &on_false.discount),
316        }
317    }
318}