Skip to main content

ruxla_env/
compiled.rs

1//! Environments compiled ahead of time to Rust: [`generate`] traces an
2//! environment's `reset` and `step` (with the automatic reset), optimizes the
3//! IR, and writes a Rust module whose functions work on fixed-size arrays; a
4//! build script includes the module, and `rustc` compiles it like handwritten
5//! code. The module implements
6//! [`CompiledEnv`].
7
8use std::fmt::Write;
9
10use ruxla_codegen::{Options, emit::elem_ty};
11use ruxla_core::random::Key;
12use ruxla_core::{Native, Trace, leaves, make_ir, random};
13use ruxla_ir::{AVal, Function, HostArray};
14
15use crate::{ActionSpace, ActionValue, Actions, Environment};
16
17/// One step of a compiled environment (the fields of [`crate::Step`]).
18#[derive(Clone, Debug, PartialEq)]
19pub struct CompiledStep<O, S> {
20    /// The next observation: after a reset if the episode ended.
21    pub obs: O,
22    /// The next state: a fresh one if the episode ended.
23    pub state: S,
24    /// The reward of the step.
25    pub reward: f32,
26    /// Whether the episode ended in a terminal state.
27    pub terminated: bool,
28    /// Whether the episode reached its time limit.
29    pub truncated: bool,
30    /// The observation reached by the step, before any reset.
31    pub final_observation: O,
32    /// 0 if the step reached a terminal state, 1 otherwise.
33    pub discount: f32,
34}
35
36/// The scalars of a step of [`CompiledEnv::step_in_place`].
37#[derive(Clone, Copy, Debug, PartialEq)]
38pub struct StepInfo {
39    /// The reward of the step.
40    pub reward: f32,
41    /// Whether the episode ended in a terminal state.
42    pub terminated: bool,
43    /// Whether the episode reached its time limit.
44    pub truncated: bool,
45    /// 0 if the step reached a terminal state, 1 otherwise.
46    pub discount: f32,
47}
48
49/// A computation on a compiled environment, called with the environment's
50/// type (by `ruxla_env_jax::visit` for an environment chosen by name).
51pub trait Visitor {
52    /// The result.
53    type Output;
54    /// Runs on the environment of `module` (a generated `Env`, a unit
55    /// struct that can be copied and kept, as `CompiledVecEnv::new` keeps
56    /// it).
57    fn visit<E: CompiledEnv + Clone + 'static>(&mut self, module: &str, env: &E) -> Self::Output;
58}
59
60/// An environment compiled by [`generate`]: `reset` and `step` (with the
61/// automatic reset of [`Environment::step`]) with the parameters fixed at
62/// generation, on states of fixed-size arrays. Keys are the two words of a
63/// JAX key (see [`key`] and [`split_key`]).
64pub trait CompiledEnv: Send + Sync {
65    /// The state: a tuple struct of the state's leaves.
66    type State: Clone + Send + Sync + std::fmt::Debug;
67    /// The observation: a tuple struct of the observation's leaves.
68    type Obs: Clone + Send + Sync + std::fmt::Debug;
69    /// An action: `i32` (discrete), `f32` (one element), or `[f32; N]`.
70    type Action: CompiledAction;
71
72    /// The environment's name ([`Environment::name`]).
73    fn name(&self) -> &'static str;
74    /// The actions ([`Environment::action_space`]).
75    fn action_space(&self) -> ActionSpace;
76    /// The number of discrete actions (0 for continuous actions).
77    fn num_actions(&self) -> usize {
78        self.action_space().num_actions()
79    }
80    /// The number of elements of an observation.
81    fn obs_len(&self) -> usize;
82    /// A new episode.
83    fn reset(&self, key: [u32; 2]) -> (Self::Obs, Self::State);
84    /// One step, with the automatic reset.
85    fn step(
86        &self,
87        key: [u32; 2],
88        state: &Self::State,
89        action: Self::Action,
90    ) -> CompiledStep<Self::Obs, Self::State>;
91    /// One step, with the automatic reset, in place: the state is updated
92    /// and the observation written to `obs` (without the final
93    /// observation, which [`CompiledEnv::step`] also gives).
94    fn step_in_place(
95        &self,
96        key: [u32; 2],
97        state: &mut Self::State,
98        action: Self::Action,
99        obs: &mut Self::Obs,
100    ) -> StepInfo;
101    /// [`CompiledEnv::step_in_place`] that also writes the observation
102    /// reached by the step, before any reset, to `final_obs`.
103    fn step_in_place_with_final(
104        &self,
105        key: [u32; 2],
106        state: &mut Self::State,
107        action: Self::Action,
108        obs: &mut Self::Obs,
109        final_obs: &mut Self::Obs,
110    ) -> StepInfo;
111    /// The shape of an observation (of its only leaf, or `[obs_len]` for
112    /// several leaves).
113    fn obs_shape(&self) -> Vec<usize>;
114    /// Writes the legal action mask of `state` (over the joint actions,
115    /// [`Environment::legal_action_mask`]) to `out` and returns `true`, or
116    /// returns `false` if the environment has none.
117    fn legal_action_mask(&self, state: &Self::State, out: &mut [bool]) -> bool {
118        let _ = (state, out);
119        false
120    }
121    /// Writes the observation's elements (converted to `f32`) to `out`.
122    fn obs_into(&self, obs: &Self::Obs, out: &mut [f32]);
123    /// The leaves of a state (those of the environment's state pytree).
124    fn state_leaves(&self, state: &Self::State) -> Vec<HostArray>;
125    /// The leaves of an observation.
126    fn obs_leaves(&self, obs: &Self::Obs) -> Vec<HostArray>;
127    /// A state from its leaves.
128    fn state_from_leaves(&self, leaves: &[HostArray]) -> Self::State;
129}
130
131/// An action of a compiled environment.
132pub trait CompiledAction: Copy + Send + Sync + std::fmt::Debug {
133    /// Action `i` of the fixed pseudo-random sequence of
134    /// [`ActionValue::pattern`].
135    fn pattern(space: &ActionSpace, i: u64) -> Self;
136    /// The action of environment `i` in a flat buffer.
137    fn from_flat(actions: Actions<'_>, i: usize) -> Self;
138    /// The joint action `index` ([`ActionValue::from_joint`]).
139    fn from_joint(space: &ActionSpace, index: usize) -> Self;
140}
141
142impl CompiledAction for i32 {
143    fn pattern(space: &ActionSpace, i: u64) -> Self {
144        match space {
145            ActionSpace::MultiDiscrete(nvec) => crate::pattern_discrete(i, nvec[0]),
146            _ => crate::pattern_discrete(i, space.num_actions()),
147        }
148    }
149    #[inline]
150    fn from_flat(actions: Actions<'_>, i: usize) -> Self {
151        match actions {
152            Actions::Discrete(a) | Actions::MultiDiscrete { data: a, .. } => a[i],
153            Actions::Continuous { .. } => panic!("discrete actions expected"),
154        }
155    }
156    fn from_joint(_: &ActionSpace, index: usize) -> Self {
157        index as i32
158    }
159}
160
161impl<const N: usize> CompiledAction for [i32; N] {
162    fn pattern(space: &ActionSpace, i: u64) -> Self {
163        let ActionSpace::MultiDiscrete(nvec) = space else {
164            panic!("multi-discrete actions expected");
165        };
166        std::array::from_fn(|k| crate::pattern_discrete(i.wrapping_add(k as u64 * 40_503), nvec[k]))
167    }
168    #[inline]
169    fn from_flat(actions: Actions<'_>, i: usize) -> Self {
170        match actions {
171            Actions::MultiDiscrete { data, .. } => {
172                data[i * N..(i + 1) * N].try_into().expect("N components")
173            }
174            _ => panic!("multi-discrete actions expected"),
175        }
176    }
177    fn from_joint(space: &ActionSpace, index: usize) -> Self {
178        let ActionSpace::MultiDiscrete(nvec) = space else {
179            panic!("multi-discrete actions expected");
180        };
181        let mut out = [0i32; N];
182        crate::unravel_joint(index, nvec, &mut out);
183        out
184    }
185}
186
187impl CompiledAction for f32 {
188    fn pattern(space: &ActionSpace, i: u64) -> Self {
189        let ActionSpace::Box { low, high, .. } = space else {
190            panic!("a box of actions expected");
191        };
192        crate::pattern_continuous(i, 0, low[0], high[0])
193    }
194    #[inline]
195    fn from_flat(actions: Actions<'_>, i: usize) -> Self {
196        match actions {
197            Actions::Continuous { data, .. } => data[i],
198            _ => panic!("continuous actions expected"),
199        }
200    }
201    fn from_joint(_: &ActionSpace, _: usize) -> Self {
202        panic!("continuous actions have no joint index")
203    }
204}
205
206impl<const N: usize> CompiledAction for [f32; N] {
207    fn pattern(space: &ActionSpace, i: u64) -> Self {
208        let ActionSpace::Box { low, high, .. } = space else {
209            panic!("a box of actions expected");
210        };
211        std::array::from_fn(|k| crate::pattern_continuous(i, k, low[k], high[k]))
212    }
213    #[inline]
214    fn from_flat(actions: Actions<'_>, i: usize) -> Self {
215        match actions {
216            Actions::Continuous { data, .. } => {
217                data[i * N..(i + 1) * N].try_into().expect("N elements")
218            }
219            _ => panic!("continuous actions expected"),
220        }
221    }
222    fn from_joint(_: &ActionSpace, _: usize) -> Self {
223        panic!("continuous actions have no joint index")
224    }
225}
226
227/// The key of `jax.random.key(seed)` (as [`random::key`]).
228pub fn key(seed: i64) -> [u32; 2] {
229    if i32::try_from(seed).is_ok() {
230        [0, seed as u32]
231    } else {
232        [(seed >> 32) as u32, seed as u32]
233    }
234}
235
236/// `jax.random.split(key)`, unpacked (as [`random::split2`]).
237///
238/// # Examples
239///
240/// ```
241/// use ruxla_core::{Native, random};
242/// use ruxla_env::compiled::{key, split_key};
243///
244/// let (a, b) = random::split2(&random::key::<Native>(3));
245/// let words = |k: &ruxla_core::Key<Native>| k.data().to_vec();
246/// let (c, d) = split_key(key(3));
247/// assert_eq!((words(&a), words(&b)), (c.to_vec(), d.to_vec()));
248/// ```
249#[inline]
250pub fn split_key(key: [u32; 2]) -> ([u32; 2], [u32; 2]) {
251    let (a0, b0) = ruxla_kernels::random::threefry2x32(key[0], key[1], 0, 0);
252    let (a1, b1) = ruxla_kernels::random::threefry2x32(key[0], key[1], 0, 1);
253    ([a0, b0], [a1, b1])
254}
255
256fn size(a: &AVal) -> usize {
257    a.shape.size()
258}
259
260fn rust_ty(a: &AVal) -> Result<String, ruxla_codegen::Error> {
261    let t = elem_ty(a.dtype)?;
262    Ok(if size(a) == 1 {
263        t.to_string()
264    } else {
265        format!("[{t}; {}]", size(a))
266    })
267}
268
269/// Generates the Rust module `module` of `env` compiled ahead of time with
270/// its default parameters: a unit struct `Env` that implements
271/// [`CompiledEnv`], with `State` and `Obs` structs. The code refers to the
272/// crates `ruxla_env`, `ruxla_codegen`, and `ruxla_ir`.
273///
274/// # Errors
275///
276/// Returns an error if the environment uses element types or operations
277/// that cannot be generated.
278pub fn generate<E: Environment>(
279    env: &E,
280    module: &str,
281    options: &Options,
282) -> Result<String, ruxla_codegen::Error> {
283    let params = env.default_params::<Native>();
284    let key0 = random::key::<Native>(0);
285    let (obs, state) = env.reset(key0.clone(), &params);
286    let space = env.action_space();
287    let action0 = <E::Action<Native> as ActionValue<Native>>::pattern(&space, 0);
288    let reset: Function = make_ir(
289        |k: Key<Trace>| env.reset(k, &env.default_params::<Trace>()),
290        &key0,
291    );
292    let step: Function = make_ir(
293        |(k, s, a): (Key<Trace>, E::State<Trace>, E::Action<Trace>)| {
294            let st = env.step(k, &s, a, &env.default_params::<Trace>());
295            (
296                st.obs,
297                st.state,
298                st.reward,
299                st.terminated,
300                st.truncated,
301                st.final_observation,
302                st.discount,
303            )
304        },
305        &(key0, state.clone(), action0),
306    );
307    let legal_action_mask = env.legal_action_mask(&state).map(|_| {
308        make_ir(
309            |s: E::State<Trace>| env.legal_action_mask(&s).expect("a legal action mask"),
310            &state,
311        )
312    });
313    let functions = EnvFunctions {
314        name: env.name().to_string(),
315        action_space: space,
316        num_obs: leaves(&obs).len(),
317        reset,
318        step,
319        legal_action_mask,
320    };
321    generate_from_functions(&functions, module, options)
322}
323
324/// The functions of an environment, from which [`generate_from_functions`]
325/// generates a [`CompiledEnv`]: traced from an [`Environment`] (as
326/// [`generate`] does) or imported from JAX (`ruxla-import`, [`crate::jax_env`]).
327/// The parameters are fixed (constants of the
328/// functions); keys are `u32[2]`, and states and observations are tuples of
329/// leaves.
330#[derive(Clone, Debug)]
331pub struct EnvFunctions {
332    /// The environment's name.
333    pub name: String,
334    /// The actions.
335    pub action_space: ActionSpace,
336    /// The number of leaves of an observation.
337    pub num_obs: usize,
338    /// `reset(key) -> (obs..., state...)`.
339    pub reset: Function,
340    /// The step with the automatic reset: `step(key, state..., action) ->
341    /// (obs..., state..., reward: f32, terminated: bool, truncated: bool,
342    /// final_obs..., discount: f32)`.
343    pub step: Function,
344    /// `legal_action_mask(state...) -> bool[n]` over the joint actions, if
345    /// the environment has one.
346    pub legal_action_mask: Option<Function>,
347}
348
349/// Generates the Rust module `module` of an environment given by its
350/// functions, as [`generate`] does for an [`Environment`].
351///
352/// # Errors
353///
354/// Returns an error if the functions do not have the form of
355/// [`EnvFunctions`], or use element types or operations that cannot be
356/// generated.
357pub fn generate_from_functions(
358    functions: &EnvFunctions,
359    module: &str,
360    options: &Options,
361) -> Result<String, ruxla_codegen::Error> {
362    let EnvFunctions {
363        name,
364        action_space: space,
365        num_obs: no,
366        reset: reset_ir,
367        step: step_ir,
368        legal_action_mask,
369    } = functions;
370    let no = *no;
371    let bad = |m: String| ruxla_codegen::Error(format!("{name}: {m}"));
372    let reset_out = reset_ir.out_avals();
373    if reset_out.len() < no {
374        return Err(bad(format!("reset gives {} outputs", reset_out.len())));
375    }
376    let obs_avals = reset_out[..no].to_vec();
377    let state_avals = reset_out[no..].to_vec();
378    let ns = state_avals.len();
379    let step_in = step_ir.in_avals();
380    if step_in.len() != ns + 2 || step_in[1..=ns] != state_avals[..] {
381        return Err(bad(String::from(
382            "step's inputs are not (key, state..., action)",
383        )));
384    }
385    let action_aval = step_in[ns + 1].clone();
386    let step_out = step_ir.out_avals();
387    if step_out.len() != 2 * no + ns + 4
388        || step_out[..no] != obs_avals[..]
389        || step_out[no..no + ns] != state_avals[..]
390    {
391        return Err(bad(String::from(
392            "step's outputs are not (obs..., state..., reward, terminated, truncated, final_obs..., discount)",
393        )));
394    }
395    let action_ty = rust_ty(&action_aval)?;
396    let action_arg = if size(&action_aval) == 1 {
397        "action"
398    } else {
399        "&action"
400    };
401    // The step in place: the state leaves are read and written back, the
402    // observation written out, and the final observation not computed.
403    let mut fast_ir = step_ir.clone();
404    fast_ir.outvars.drain(no + ns + 3..2 * no + ns + 3);
405    // The constant arrays of all the functions, defined once in the module.
406    let mut pool = ruxla_codegen::ConstPool::new();
407    // The legal action mask, if the environment has one.
408    let legal_fn = match legal_action_mask {
409        Some(f) => {
410            let n = f.out_avals().first().map_or(0, size);
411            let code = ruxla_codegen::compile_pooled(
412                "legal_ir",
413                f,
414                options,
415                &ruxla_codegen::Signature {
416                    inputs: Vec::new(),
417                    outputs: vec![ruxla_codegen::Output::Write],
418                },
419                &mut pool,
420            )?;
421            Some((n, code))
422        }
423        None => None,
424    };
425    let default = ruxla_codegen::Signature::default();
426    let reset_fn =
427        ruxla_codegen::compile_pooled("reset_ir", reset_ir, options, &default, &mut pool)?;
428    // `step` is the step in place with the final observation on a copy of the
429    // state (no function of its own: the generated code is a quarter smaller).
430    let ns0 = state_avals.len();
431    let mut inputs = vec![ruxla_codegen::Input::Default];
432    inputs.extend(std::iter::repeat_n(ruxla_codegen::Input::Mut, ns0));
433    let mut outputs = vec![ruxla_codegen::Output::Write; obs_avals.len()];
434    outputs.extend((0..ns0).map(|k| ruxla_codegen::Output::Into(1 + k)));
435    let fast_fn = ruxla_codegen::compile_pooled(
436        "step_in_place_ir",
437        &fast_ir,
438        options,
439        &ruxla_codegen::Signature {
440            inputs: inputs.clone(),
441            outputs: outputs.clone(),
442        },
443        &mut pool,
444    )?;
445    // The same with the final observation, written out too (`step_ir`'s
446    // outputs).
447    let mut final_outputs = outputs;
448    final_outputs.extend([ruxla_codegen::Output::Return; 3]);
449    final_outputs.extend(std::iter::repeat_n(
450        ruxla_codegen::Output::Write,
451        obs_avals.len(),
452    ));
453    final_outputs.push(ruxla_codegen::Output::Return);
454    let final_fn = ruxla_codegen::compile_pooled(
455        "step_in_place_final_ir",
456        step_ir,
457        options,
458        &ruxla_codegen::Signature {
459            inputs,
460            outputs: final_outputs,
461        },
462        &mut pool,
463    )?;
464
465    let obs_tys: Vec<String> = obs_avals.iter().map(rust_ty).collect::<Result<_, _>>()?;
466    let state_tys: Vec<String> = state_avals.iter().map(rust_ty).collect::<Result<_, _>>()?;
467    let obs_len: usize = obs_avals.iter().map(size).sum();
468    let arg = |k: usize, a: &AVal, owner: &str| {
469        if size(a) == 1 {
470            format!("{owner}.{k}")
471        } else {
472            format!("&{owner}.{k}")
473        }
474    };
475    let tuple = |r: &str, from: usize, n: usize| -> String {
476        (from..from + n)
477            .map(|i| format!("{r}.{i}"))
478            .collect::<Vec<_>>()
479            .join(", ")
480    };
481    let mut s = String::new();
482    let w = &mut s;
483    writeln!(
484        w,
485        "/// `{name}` compiled ahead of time by `ruxla_env::compiled::generate`."
486    )
487    .ok();
488    writeln!(w, "pub mod {module} {{").ok();
489    // `unused_comparisons`: `randint` with a runtime bound compares an `i32`
490    // with `i32::MAX`, as JAX does.
491    writeln!(
492        w,
493        "    #![allow(clippy::all, missing_docs, unused, unused_parens, unused_comparisons, \
494         unreachable_pub)]"
495    )
496    .ok();
497    writeln!(w, "    use ruxla_codegen::rt;").ok();
498    writeln!(
499        w,
500        "    use ruxla_env::compiled::{{CompiledEnv, CompiledStep}};"
501    )
502    .ok();
503    writeln!(w, "    use ruxla_ir::HostArray;").ok();
504    writeln!(w).ok();
505    writeln!(w, "    /// The environment.").ok();
506    writeln!(w, "    #[derive(Clone, Copy, Debug, Default)]").ok();
507    writeln!(w, "    pub struct Env;").ok();
508    writeln!(w, "    /// The state's leaves.").ok();
509    writeln!(w, "    #[derive(Clone, Copy, Debug, PartialEq)]").ok();
510    writeln!(
511        w,
512        "    pub struct State({});",
513        state_tys
514            .iter()
515            .map(|t| format!("pub {t}"))
516            .collect::<Vec<_>>()
517            .join(", ")
518    )
519    .ok();
520    writeln!(w, "    /// The observation's leaves.").ok();
521    writeln!(w, "    #[derive(Clone, Copy, Debug, PartialEq)]").ok();
522    writeln!(
523        w,
524        "    pub struct Obs({});",
525        obs_tys
526            .iter()
527            .map(|t| format!("pub {t}"))
528            .collect::<Vec<_>>()
529            .join(", ")
530    )
531    .ok();
532    writeln!(w).ok();
533    for line in pool
534        .code()
535        .lines()
536        .chain(reset_fn.lines())
537        .chain(fast_fn.lines())
538        .chain(final_fn.lines())
539        .chain(legal_fn.iter().flat_map(|(_, c)| c.lines()))
540    {
541        writeln!(w, "    {line}").ok();
542    }
543    writeln!(w).ok();
544    writeln!(w, "    impl CompiledEnv for Env {{").ok();
545    writeln!(w, "        type State = State;").ok();
546    writeln!(w, "        type Obs = Obs;").ok();
547    writeln!(w, "        fn name(&self) -> &'static str {{ {name:?} }}").ok();
548    writeln!(w, "        type Action = {action_ty};").ok();
549    let space_code = match &space {
550        ActionSpace::Discrete(n) => format!("ruxla_env::ActionSpace::Discrete({n})"),
551        ActionSpace::MultiDiscrete(nvec) => {
552            format!("ruxla_env::ActionSpace::MultiDiscrete(vec!{nvec:?})")
553        }
554        ActionSpace::Box { low, high, shape } => format!(
555            "ruxla_env::ActionSpace::Box {{ low: vec!{low:?}, high: vec!{high:?}, shape: vec!{shape:?} }}"
556        ),
557    };
558    writeln!(
559        w,
560        "        fn action_space(&self) -> ruxla_env::ActionSpace {{ {space_code} }}"
561    )
562    .ok();
563    writeln!(w, "        fn obs_len(&self) -> usize {{ {obs_len} }}").ok();
564    writeln!(w, "        #[inline]").ok();
565    writeln!(
566        w,
567        "        fn reset(&self, key: [u32; 2]) -> (Obs, State) {{"
568    )
569    .ok();
570    writeln!(w, "            let r = reset_ir(&key);").ok();
571    writeln!(
572        w,
573        "            (Obs({}), State({}))",
574        tuple("r", 0, no),
575        tuple("r", no, ns)
576    )
577    .ok();
578    writeln!(w, "        }}").ok();
579    writeln!(w, "        #[inline]").ok();
580    writeln!(w, "        fn step(&self, key: [u32; 2], state: &State, action: {action_ty}) -> CompiledStep<Obs, State> {{").ok();
581    let zeros = obs_avals
582        .iter()
583        .map(|a| {
584            if size(a) == 1 {
585                "Default::default()".to_string()
586            } else {
587                format!("[Default::default(); {}]", size(a))
588            }
589        })
590        .collect::<Vec<_>>()
591        .join(", ");
592    writeln!(w, "            let mut state = *state;").ok();
593    writeln!(w, "            let mut obs = Obs({zeros});").ok();
594    writeln!(w, "            let mut final_obs = Obs({zeros});").ok();
595    writeln!(w, "            let info = self.step_in_place_with_final(key, &mut state, action, &mut obs, &mut final_obs);").ok();
596    writeln!(w, "            CompiledStep {{ obs, state, reward: info.reward, terminated: info.terminated, truncated: info.truncated, final_observation: final_obs, discount: info.discount }}").ok();
597    writeln!(w, "        }}").ok();
598    writeln!(w, "        #[inline]").ok();
599    writeln!(w, "        fn step_in_place(&self, key: [u32; 2], state: &mut State, action: {action_ty}, obs: &mut Obs) -> ruxla_env::compiled::StepInfo {{").ok();
600    let mut fast_args = vec!["&key".to_string()];
601    fast_args.extend((0..ns).map(|k| format!("&mut state.{k}")));
602    fast_args.push(action_arg.into());
603    fast_args.extend((0..no).map(|k| format!("&mut obs.{k}")));
604    writeln!(
605        w,
606        "            let r = step_in_place_ir({});",
607        fast_args.join(", ")
608    )
609    .ok();
610    writeln!(w, "            ruxla_env::compiled::StepInfo {{ reward: r.0, terminated: r.1, truncated: r.2, discount: r.3 }}").ok();
611    writeln!(w, "        }}").ok();
612    writeln!(w, "        #[inline]").ok();
613    writeln!(w, "        fn step_in_place_with_final(&self, key: [u32; 2], state: &mut State, action: {action_ty}, obs: &mut Obs, final_obs: &mut Obs) -> ruxla_env::compiled::StepInfo {{").ok();
614    let mut final_args = vec!["&key".to_string()];
615    final_args.extend((0..ns).map(|k| format!("&mut state.{k}")));
616    final_args.push(action_arg.into());
617    final_args.extend((0..no).map(|k| format!("&mut obs.{k}")));
618    final_args.extend((0..no).map(|k| format!("&mut final_obs.{k}")));
619    writeln!(
620        w,
621        "            let r = step_in_place_final_ir({});",
622        final_args.join(", ")
623    )
624    .ok();
625    writeln!(w, "            ruxla_env::compiled::StepInfo {{ reward: r.0, terminated: r.1, truncated: r.2, discount: r.3 }}").ok();
626    writeln!(w, "        }}").ok();
627    let shape = match obs_avals.as_slice() {
628        [one] => format!("{:?}", one.shape.dims()),
629        _ => format!("[{obs_len}]"),
630    };
631    writeln!(
632        w,
633        "        fn obs_shape(&self) -> Vec<usize> {{ vec!{shape} }}"
634    )
635    .ok();
636    if let Some((n, _)) = &legal_fn {
637        let args: Vec<String> = state_avals
638            .iter()
639            .enumerate()
640            .map(|(k, a)| arg(k, a, "state"))
641            .collect();
642        writeln!(
643            w,
644            "        fn legal_action_mask(&self, state: &State, out: &mut [bool]) -> bool {{"
645        )
646        .ok();
647        if *n == 1 {
648            writeln!(w, "            let mut m = false;").ok();
649        } else {
650            writeln!(w, "            let mut m = [false; {n}];").ok();
651        }
652        writeln!(w, "            legal_ir({}, &mut m);", args.join(", ")).ok();
653        if *n == 1 {
654            writeln!(w, "            out[0] = m;").ok();
655        } else {
656            writeln!(w, "            out.copy_from_slice(&m);").ok();
657        }
658        writeln!(w, "            true").ok();
659        writeln!(w, "        }}").ok();
660    }
661    // Observations as f32.
662    writeln!(
663        w,
664        "        fn obs_into(&self, obs: &Obs, out: &mut [f32]) {{"
665    )
666    .ok();
667    let mut off = 0;
668    for (k, a) in obs_avals.iter().enumerate() {
669        let conv = |x: &str| match a.dtype {
670            ruxla_ir::DType::Bool => format!("({x} as u8 as f32)"),
671            ruxla_ir::DType::F16 | ruxla_ir::DType::BF16 => format!("{x}.to_f32()"),
672            _ => format!("({x} as f32)"),
673        };
674        if size(a) == 1 {
675            writeln!(w, "            out[{off}] = {};", conv(&format!("obs.{k}"))).ok();
676        } else {
677            writeln!(w, "            for (o, &x) in out[{off}..{}].iter_mut().zip(obs.{k}.iter()) {{ *o = {}; }}", off + size(a), conv("x")).ok();
678        }
679        off += size(a);
680    }
681    writeln!(w, "        }}").ok();
682    // Leaves.
683    let to_leaves = |avals: &[AVal], owner: &str| -> String {
684        avals
685            .iter()
686            .enumerate()
687            .map(|(k, a)| {
688                let dims = format!("{:?}", a.shape.dims());
689                if size(a) == 1 {
690                    format!("HostArray::from_vec(vec![{owner}.{k}], {dims}.to_vec())")
691                } else {
692                    format!("HostArray::from_vec({owner}.{k}.to_vec(), {dims}.to_vec())")
693                }
694            })
695            .collect::<Vec<_>>()
696            .join(", ")
697    };
698    writeln!(
699        w,
700        "        fn state_leaves(&self, state: &State) -> Vec<HostArray> {{ vec![{}] }}",
701        to_leaves(&state_avals, "state")
702    )
703    .ok();
704    writeln!(
705        w,
706        "        fn obs_leaves(&self, obs: &Obs) -> Vec<HostArray> {{ vec![{}] }}",
707        to_leaves(&obs_avals, "obs")
708    )
709    .ok();
710    let from_leaves: Vec<String> = state_avals
711        .iter()
712        .enumerate()
713        .map(|(k, a)| {
714            let t = elem_ty(a.dtype).unwrap_or("?");
715            if size(a) == 1 {
716                format!("rt::from_host_scalar::<{t}>(&leaves[{k}])")
717            } else {
718                format!("rt::from_host::<{t}, {}>(&leaves[{k}])", size(a))
719            }
720        })
721        .collect();
722    writeln!(
723        w,
724        "        fn state_from_leaves(&self, leaves: &[HostArray]) -> State {{ State({}) }}",
725        from_leaves.join(", ")
726    )
727    .ok();
728    writeln!(w, "    }}").ok();
729    writeln!(w, "}}").ok();
730    Ok(s)
731}