Skip to main content

ruxla_env/
vec_env.rs

1//! `VecEnv`: many native environments stepped in parallel.
2
3use ruxla_core::random::{self, Key};
4use ruxla_core::{Array, Backend, Element, Native, leaves};
5
6use crate::compiled::{CompiledEnv, split_key};
7use crate::pool::Pool;
8use crate::{ActionValue, Actions, Environment};
9
10/// The fewest environments in one chunk of a parallel step: a step takes a
11/// fraction of a microsecond, so smaller chunks would cost more to hand out
12/// than to run.
13const MIN_ENVS_PER_CHUNK: usize = 8;
14
15/// A raw pointer that may be shared between the threads of a step, which
16/// access disjoint ranges of the buffer it points to.
17#[derive(Clone, Copy)]
18struct SharedPtr<T>(*mut T);
19
20// SAFETY: the threads of a step only access disjoint ranges (one chunk
21// each), and the step waits for all of them before the buffer is used again.
22unsafe impl<T: Send> Send for SharedPtr<T> {}
23// SAFETY: as above.
24unsafe impl<T: Send> Sync for SharedPtr<T> {}
25
26impl<T> SharedPtr<T> {
27    /// The elements `range` of the buffer.
28    ///
29    /// # Safety
30    ///
31    /// The range must be in bounds, and no other thread may access it while
32    /// the slice lives.
33    #[allow(clippy::mut_from_ref)] // disjoint ranges per thread, see above
34    unsafe fn slice(&self, range: std::ops::Range<usize>) -> &mut [T] {
35        // SAFETY: guaranteed by the caller.
36        unsafe { std::slice::from_raw_parts_mut(self.0.add(range.start), range.len()) }
37    }
38}
39
40/// The result of [`VecEnv::step`]: one entry per environment.
41#[derive(Clone, Debug)]
42pub struct VecStep<O> {
43    /// The next observations (after a reset where an episode ended).
44    pub obs: Vec<O>,
45    /// The rewards.
46    pub reward: Vec<f32>,
47    /// Whether each episode ended in a terminal state.
48    pub terminated: Vec<bool>,
49    /// Whether each episode reached its time limit.
50    pub truncated: Vec<bool>,
51    /// The observations reached by the step, before any reset (the same as
52    /// `obs` where the episode goes on).
53    pub final_obs: Vec<O>,
54}
55
56/// A native observation that can be copied into a flat `f32` buffer, for
57/// [`VecEnv::step_into`] (which the NumPy arrays of the Python package use).
58pub trait FlatObs {
59    /// The shape of the observation.
60    fn shape(&self) -> Vec<usize>;
61
62    /// Writes the elements, converted to `f32`, in row-major order.
63    ///
64    /// # Panics
65    ///
66    /// Panics if `out` does not have one element per element of the
67    /// observation.
68    fn write_f32(&self, out: &mut [f32]);
69}
70
71impl<T: Element> FlatObs for Array<Native, T> {
72    fn shape(&self) -> Vec<usize> {
73        self.native().shape().dims().to_vec()
74    }
75
76    #[inline]
77    fn write_f32(&self, out: &mut [f32]) {
78        let data = self.native().data();
79        assert_eq!(
80            out.len(),
81            data.len(),
82            "an observation buffer of the wrong size"
83        );
84        for (o, x) in out.iter_mut().zip(data) {
85            *o = Native::cast::<T, f32>(*x);
86        }
87    }
88}
89
90impl<T: Element> FlatObs for ruxla_core::Scalar<Native, T> {
91    fn shape(&self) -> Vec<usize> {
92        Vec::new()
93    }
94
95    #[inline]
96    fn write_f32(&self, out: &mut [f32]) {
97        assert_eq!(out.len(), 1, "an observation buffer of the wrong size");
98        out[0] = Native::cast::<T, f32>(self.value());
99    }
100}
101
102/// Implements [`FlatObs`] for an observation struct of several fields (for
103/// `Native`): the fields, in the order given, flattened one after another,
104/// with the shape `[total size]`.
105///
106/// # Examples
107///
108/// ```
109/// use ruxla_core::{Array, Backend, I32, Native, Tree};
110/// use ruxla_env::FlatObs;
111///
112/// #[derive(Clone, Tree)]
113/// struct Obs<B: Backend> {
114///     grid: Array<B, f32>,
115///     steps: I32<B>,
116/// }
117/// ruxla_env::flat_obs!(Obs { grid, steps });
118///
119/// let obs = Obs::<Native> { grid: Array::from_slice(&[1.0, 2.0], [2]), steps: I32::new(7) };
120/// let mut out = [0.0; 3];
121/// obs.write_f32(&mut out);
122/// assert_eq!((obs.shape(), out), (vec![3], [1.0, 2.0, 7.0]));
123/// ```
124#[macro_export]
125macro_rules! flat_obs {
126    ($ty:ident { $($field:ident),+ $(,)? }) => {
127        impl $crate::FlatObs for $ty<::ruxla_core::Native> {
128            fn shape(&self) -> ::std::vec::Vec<usize> {
129                let mut n = 0usize;
130                $(n += $crate::FlatObs::shape(&self.$field).iter().product::<usize>();)+
131                ::std::vec![n]
132            }
133
134            fn write_f32(&self, out: &mut [f32]) {
135                let mut at = 0usize;
136                $(
137                    let len: usize = $crate::FlatObs::shape(&self.$field).iter().product();
138                    $crate::FlatObs::write_f32(&self.$field, &mut out[at..at + len]);
139                    at += len;
140                )+
141                assert_eq!(at, out.len(), "an observation buffer of the wrong size");
142            }
143        }
144    };
145}
146
147/// Buffers that [`VecEnv::step_into`] writes the results of a step to, one
148/// entry per environment; `obs` and `final_obs` hold the flat observations
149/// ([`FlatObs`]) environment after environment.
150#[derive(Debug)]
151pub struct StepBuffers<'a> {
152    /// The next observations (after a reset where an episode ended).
153    pub obs: &'a mut [f32],
154    /// The rewards.
155    pub reward: &'a mut [f32],
156    /// Whether each episode ended in a terminal state.
157    pub terminated: &'a mut [bool],
158    /// Whether each episode reached its time limit.
159    pub truncated: &'a mut [bool],
160    /// The observations reached by the step, before any reset.
161    pub final_obs: &'a mut [f32],
162}
163
164/// The results of one environment's step, as `VecEnv::step_with` hands them
165/// to its sink.
166struct EnvStep<'a, O> {
167    obs: &'a O,
168    final_obs: &'a O,
169    reward: f32,
170    terminated: bool,
171    truncated: bool,
172}
173
174/// A batch of native environments, stepped in parallel and reset
175/// automatically ([`Environment::step`]).
176///
177/// The environments are split into chunks run by a pool of worker threads
178/// (one per available core by default), which wait for the next step by
179/// spinning briefly, so that a step costs little more than its computation.
180///
181/// Each environment has its own key, split at every step as PureJaxRL does
182/// (`key, step_key = split(key)`).
183///
184/// # Examples
185///
186/// ```
187/// use ruxla_env::{CartPole, VecEnv};
188///
189/// let mut envs = VecEnv::new(CartPole, 8, 0);
190/// let step = envs.step(&[1; 8]);
191/// assert_eq!(step.reward, [1.0; 8]);
192/// assert_eq!(envs.obs_f32().len(), 8 * 4);
193/// ```
194#[derive(Debug)]
195pub struct VecEnv<E: Environment> {
196    env: E,
197    params: E::Params<Native>,
198    keys: Vec<Key<Native>>,
199    states: Vec<E::State<Native>>,
200    /// The results of the last step (or the reset observations), written in
201    /// place by the parallel tasks.
202    last: VecStep<E::Obs<Native>>,
203    pool: Pool,
204}
205
206impl<E> VecEnv<E>
207where
208    E: Environment,
209    E::State<Native>: Send + Sync,
210    E::Params<Native>: Sync,
211    E::Obs<Native>: Send + Sync,
212{
213    /// Creates `num_envs` environments with the default parameters and
214    /// resets them; environment `i` starts from the key
215    /// `fold_in(key(seed), i)`, which it splits into its key and the key of
216    /// the reset.
217    pub fn new(env: E, num_envs: usize, seed: i64) -> Self {
218        let params = env.default_params::<Native>();
219        Self::with_params(env, params, num_envs, seed)
220    }
221
222    /// Creates environments with the given parameters (see [`VecEnv::new`]).
223    pub fn with_params(env: E, params: E::Params<Native>, num_envs: usize, seed: i64) -> Self {
224        let threads = default_threads(num_envs);
225        let mut envs = Self {
226            env,
227            params,
228            keys: Vec::new(),
229            states: Vec::new(),
230            last: VecStep {
231                obs: Vec::new(),
232                reward: Vec::new(),
233                terminated: Vec::new(),
234                truncated: Vec::new(),
235                final_obs: Vec::new(),
236            },
237            pool: Pool::new(threads - 1),
238        };
239        envs.keys = Self::seed_keys(num_envs, seed);
240        envs.reset_from_keys();
241        envs
242    }
243
244    /// The keys `fold_in(key(seed), i)`.
245    fn seed_keys(num_envs: usize, seed: i64) -> Vec<Key<Native>> {
246        let root = random::key::<Native>(seed);
247        (0..num_envs)
248            .map(|i| random::fold_in(&root, i as u32))
249            .collect()
250    }
251
252    /// Starts new episodes in every environment.
253    ///
254    /// With a seed, the environments start over as in [`VecEnv::new`] with
255    /// that seed. Without one, each environment splits its current key
256    /// (`key, reset_key = split(key)`) and resets with the second half, so
257    /// that the new episodes depend on the steps taken before.
258    ///
259    /// # Examples
260    ///
261    /// ```
262    /// use ruxla_env::{CartPole, VecEnv};
263    ///
264    /// let mut envs = VecEnv::new(CartPole, 4, 7);
265    /// let start = envs.obs_f32();
266    /// envs.step(&[0; 4]);
267    /// envs.reset(Some(7));
268    /// assert_eq!(envs.obs_f32(), start);
269    /// ```
270    pub fn reset(&mut self, seed: Option<i64>) {
271        if let Some(seed) = seed {
272            self.keys = Self::seed_keys(self.num_envs(), seed);
273        }
274        self.reset_from_keys();
275    }
276
277    /// Splits every key and resets each environment with the second half.
278    fn reset_from_keys(&mut self) {
279        let n = self.keys.len();
280        self.states.clear();
281        self.last.obs.clear();
282        self.last.final_obs.clear();
283        for key in &mut self.keys {
284            let (next, reset_key) = random::split2(key);
285            *key = next;
286            let (obs, state) = self.env.reset(reset_key, &self.params);
287            self.states.push(state);
288            self.last.final_obs.push(obs.clone());
289            self.last.obs.push(obs);
290        }
291        self.last.reward = vec![0.0; n];
292        self.last.terminated = vec![false; n];
293        self.last.truncated = vec![false; n];
294    }
295
296    /// The number of environments.
297    pub fn num_envs(&self) -> usize {
298        self.states.len()
299    }
300
301    /// The environment.
302    pub fn env(&self) -> &E {
303        &self.env
304    }
305
306    /// The current states.
307    pub fn states(&self) -> &[E::State<Native>] {
308        &self.states
309    }
310
311    /// The current observations.
312    pub fn obs(&self) -> &[E::Obs<Native>] {
313        &self.last.obs
314    }
315
316    /// The current observations as one contiguous buffer: the leaves of each
317    /// observation converted to `f32`, environment after environment.
318    pub fn obs_f32(&self) -> Vec<f32> {
319        let mut out = Vec::new();
320        for o in &self.last.obs {
321            for l in leaves(o) {
322                out.extend(
323                    l.convert(ruxla_core::DType::F32)
324                        .as_slice::<f32>()
325                        .expect("converted to f32"),
326                );
327            }
328        }
329        out
330    }
331
332    /// The shape of one observation (that of the first environment), or
333    /// `None` if there are no environments.
334    pub fn obs_shape(&self) -> Option<Vec<usize>>
335    where
336        E::Obs<Native>: FlatObs,
337    {
338        self.last.obs.first().map(FlatObs::shape)
339    }
340
341    /// The number of elements of one observation in the flat buffers of
342    /// [`VecEnv::step_into`] and [`VecEnv::obs_into`].
343    pub fn obs_len(&self) -> usize
344    where
345        E::Obs<Native>: FlatObs,
346    {
347        self.obs_shape().map_or(0, |s| s.iter().product())
348    }
349
350    /// Writes the current observations to a flat buffer, environment after
351    /// environment.
352    ///
353    /// # Panics
354    ///
355    /// Panics if the buffer does not have [`VecEnv::obs_len`] elements per
356    /// environment.
357    pub fn obs_into(&self, out: &mut [f32])
358    where
359        E::Obs<Native>: FlatObs,
360    {
361        let len = self.obs_len();
362        assert_eq!(
363            out.len(),
364            self.num_envs() * len,
365            "an observation buffer of the wrong size"
366        );
367        for (i, o) in self.last.obs.iter().enumerate() {
368            o.write_f32(&mut out[i * len..(i + 1) * len]);
369        }
370    }
371
372    /// Uses `threads` threads (the caller included) for the steps.
373    ///
374    /// # Panics
375    ///
376    /// Panics if `threads` is zero.
377    pub fn set_num_threads(&mut self, threads: usize) {
378        assert!(threads > 0, "a VecEnv needs at least one thread");
379        self.pool = Pool::new(threads - 1);
380    }
381
382    /// Writes the legal action mask of every environment
383    /// ([`Environment::legal_action_mask`], flattened, environment after
384    /// environment) to `out` and returns `true`, or returns `false` if the
385    /// environment has none.
386    ///
387    /// # Panics
388    ///
389    /// Panics if `out` has the wrong size.
390    pub fn legal_action_masks_into(&self, out: &mut [bool]) -> bool {
391        let joint = self.env.action_space().mask_len();
392        assert_eq!(
393            out.len(),
394            self.num_envs() * joint,
395            "a mask buffer of the wrong size"
396        );
397        for (i, s) in self.states.iter().enumerate() {
398            let Some(m) = self.env.legal_action_mask(s) else {
399                return false;
400            };
401            out[i * joint..(i + 1) * joint].copy_from_slice(&m.to_vec());
402        }
403        true
404    }
405
406    /// The number of threads that step the environments.
407    pub fn num_threads(&self) -> usize {
408        self.pool.num_threads()
409    }
410
411    /// Steps every environment with its action, in parallel, resetting the
412    /// episodes that end, and returns the results (kept until the next
413    /// step).
414    ///
415    /// # Panics
416    ///
417    /// Panics if the number of actions differs from the number of
418    /// environments.
419    pub fn step(&mut self, actions: &[i32]) -> &VecStep<E::Obs<Native>> {
420        self.step_actions(Actions::Discrete(actions))
421    }
422
423    /// [`VecEnv::step`] with actions of any kind (continuous actions as
424    /// a flat buffer).
425    ///
426    /// # Panics
427    ///
428    /// Panics if the number or kind of actions is wrong.
429    pub fn step_actions(&mut self, actions: Actions<'_>) -> &VecStep<E::Obs<Native>> {
430        self.step_with(actions, |_, _| {});
431        &self.last
432    }
433
434    /// Like [`VecEnv::step`], and also writes the results to flat buffers
435    /// from the threads that step the environments, so that the copy runs in
436    /// parallel too.
437    ///
438    /// # Panics
439    ///
440    /// Panics if the number of actions differs from the number of
441    /// environments, or a buffer has the wrong size.
442    ///
443    /// # Examples
444    ///
445    /// ```
446    /// use ruxla_env::{CartPole, StepBuffers, VecEnv};
447    ///
448    /// let mut envs = VecEnv::new(CartPole, 2, 0);
449    /// let (mut obs, mut final_obs) = ([0.0; 8], [0.0; 8]);
450    /// let (mut reward, mut terminated, mut truncated) = ([0.0; 2], [false; 2], [false; 2]);
451    /// envs.step_into(
452    ///     &[0, 1],
453    ///     StepBuffers {
454    ///         obs: &mut obs,
455    ///         reward: &mut reward,
456    ///         terminated: &mut terminated,
457    ///         truncated: &mut truncated,
458    ///         final_obs: &mut final_obs,
459    ///     },
460    /// );
461    /// assert_eq!(reward, [1.0; 2]);
462    /// assert_eq!(obs.to_vec(), envs.obs_f32());
463    /// ```
464    pub fn step_into(&mut self, actions: &[i32], out: StepBuffers<'_>)
465    where
466        E::Obs<Native>: FlatObs,
467    {
468        self.step_into_actions(Actions::Discrete(actions), out);
469    }
470
471    /// [`VecEnv::step_into`] with actions of any kind.
472    ///
473    /// # Panics
474    ///
475    /// Panics if the number or kind of actions is wrong, or a buffer has the
476    /// wrong size.
477    pub fn step_into_actions(&mut self, actions: Actions<'_>, out: StepBuffers<'_>)
478    where
479        E::Obs<Native>: FlatObs,
480    {
481        let n = self.num_envs();
482        let len = self.obs_len();
483        assert_eq!(
484            out.obs.len(),
485            n * len,
486            "an observation buffer of the wrong size"
487        );
488        assert_eq!(
489            out.final_obs.len(),
490            n * len,
491            "an observation buffer of the wrong size"
492        );
493        assert_eq!(out.reward.len(), n, "a reward buffer of the wrong size");
494        assert_eq!(
495            out.terminated.len(),
496            n,
497            "a termination buffer of the wrong size"
498        );
499        assert_eq!(
500            out.truncated.len(),
501            n,
502            "a truncation buffer of the wrong size"
503        );
504        let obs = SharedPtr(out.obs.as_mut_ptr());
505        let final_obs = SharedPtr(out.final_obs.as_mut_ptr());
506        let reward = SharedPtr(out.reward.as_mut_ptr());
507        let terminated = SharedPtr(out.terminated.as_mut_ptr());
508        let truncated = SharedPtr(out.truncated.as_mut_ptr());
509        self.step_with(actions, |i, st| {
510            // SAFETY: entry `i < n` of each buffer (in bounds by the checks
511            // above) is written only by the thread that stepped environment
512            // `i`, and the buffers are borrowed mutably for the whole step.
513            unsafe {
514                st.obs.write_f32(obs.slice(i * len..(i + 1) * len));
515                st.final_obs
516                    .write_f32(final_obs.slice(i * len..(i + 1) * len));
517                reward.slice(i..i + 1)[0] = st.reward;
518                terminated.slice(i..i + 1)[0] = st.terminated;
519                truncated.slice(i..i + 1)[0] = st.truncated;
520            }
521        });
522    }
523
524    /// Steps every environment in parallel, storing the results in
525    /// `self.last`; `sink(i, results)` runs on the thread that stepped
526    /// environment `i`, right after its step.
527    fn step_with<F>(&mut self, actions: Actions<'_>, sink: F)
528    where
529        F: Fn(usize, EnvStep<'_, E::Obs<Native>>) + Sync,
530    {
531        let n = self.num_envs();
532        assert_eq!(actions.len(), n, "one action per environment");
533        let chunks = self
534            .pool
535            .num_threads()
536            .min(n.div_ceil(MIN_ENVS_PER_CHUNK))
537            .max(1);
538        let per_chunk = n.div_ceil(chunks);
539        let (env, params) = (&self.env, &self.params);
540        let keys = SharedPtr(self.keys.as_mut_ptr());
541        let states = SharedPtr(self.states.as_mut_ptr());
542        let obs = SharedPtr(self.last.obs.as_mut_ptr());
543        let final_obs = SharedPtr(self.last.final_obs.as_mut_ptr());
544        let reward = SharedPtr(self.last.reward.as_mut_ptr());
545        let terminated = SharedPtr(self.last.terminated.as_mut_ptr());
546        let truncated = SharedPtr(self.last.truncated.as_mut_ptr());
547        let sink = &sink;
548        self.pool.run(chunks, &|c| {
549            let range = c * per_chunk..((c + 1) * per_chunk).min(n);
550            // SAFETY: the chunks are disjoint ranges of the buffers, which
551            // have `n` elements and are not otherwise accessed during the
552            // run; `Pool::run` returns after every chunk is done.
553            let (keys, states, obs, final_obs, reward, terminated, truncated) = unsafe {
554                (
555                    keys.slice(range.clone()),
556                    states.slice(range.clone()),
557                    obs.slice(range.clone()),
558                    final_obs.slice(range.clone()),
559                    reward.slice(range.clone()),
560                    terminated.slice(range.clone()),
561                    truncated.slice(range.clone()),
562                )
563            };
564            for i in 0..range.len() {
565                let a =
566                    <E::Action<Native> as ActionValue<Native>>::from_flat(actions, range.start + i);
567                let (next, step_key) = random::split2(&keys[i]);
568                keys[i] = next;
569                let st = env.step(step_key, &states[i], a, params);
570                states[i] = st.state;
571                obs[i] = st.obs;
572                final_obs[i] = st.final_observation;
573                reward[i] = st.reward.value();
574                terminated[i] = st.terminated.value();
575                truncated[i] = st.truncated.value();
576                sink(
577                    range.start + i,
578                    EnvStep {
579                        obs: &obs[i],
580                        final_obs: &final_obs[i],
581                        reward: reward[i],
582                        terminated: terminated[i],
583                        truncated: truncated[i],
584                    },
585                );
586            }
587        });
588    }
589}
590
591/// A batch of environments compiled ahead of time ([`CompiledEnv`]),
592/// stepped in parallel and reset automatically, like [`VecEnv`] (the same
593/// keys, so the same trajectories as a `VecEnv` of the environment).
594///
595/// # Examples
596///
597/// ```
598/// use ruxla_env::compiled::{CompiledEnv, StepInfo};
599/// use ruxla_env::{CompiledVecEnv, StepBuffers};
600///
601/// # fn run<C: CompiledEnv>(env: C) {
602/// let mut envs = CompiledVecEnv::new(env, 8, 0);
603/// let len = envs.obs_len();
604/// let (mut obs, mut final_obs) = (vec![0.0; 8 * len], vec![0.0; 8 * len]);
605/// let (mut reward, mut terminated, mut truncated) = ([0.0; 8], [false; 8], [false; 8]);
606/// envs.step_into(
607///     &[0; 8],
608///     StepBuffers {
609///         obs: &mut obs,
610///         reward: &mut reward,
611///         terminated: &mut terminated,
612///         truncated: &mut truncated,
613///         final_obs: &mut final_obs,
614///     },
615/// );
616/// # }
617/// ```
618#[derive(Debug)]
619pub struct CompiledVecEnv<C: CompiledEnv> {
620    env: C,
621    keys: Vec<[u32; 2]>,
622    states: Vec<C::State>,
623    obs: Vec<C::Obs>,
624    pool: Pool,
625}
626
627impl<C: CompiledEnv> CompiledVecEnv<C>
628where
629    C::State: Send,
630    C::Obs: Send,
631{
632    /// Creates `num_envs` environments and resets them, with the keys of
633    /// [`VecEnv::new`].
634    pub fn new(env: C, num_envs: usize, seed: i64) -> Self {
635        let mut envs = Self {
636            env,
637            keys: Vec::new(),
638            states: Vec::new(),
639            obs: Vec::new(),
640            pool: Pool::new(default_threads(num_envs) - 1),
641        };
642        envs.keys = Self::seed_keys(num_envs, seed);
643        envs.reset_from_keys();
644        envs
645    }
646
647    /// The keys `fold_in(key(seed), i)`.
648    fn seed_keys(num_envs: usize, seed: i64) -> Vec<[u32; 2]> {
649        let root = random::key::<Native>(seed);
650        (0..num_envs)
651            .map(|i| {
652                let k = random::fold_in(&root, i as u32).data().to_vec();
653                [k[0], k[1]]
654            })
655            .collect()
656    }
657
658    /// Starts new episodes in every environment (see [`VecEnv::reset`]).
659    pub fn reset(&mut self, seed: Option<i64>) {
660        if let Some(seed) = seed {
661            self.keys = Self::seed_keys(self.num_envs(), seed);
662        }
663        self.reset_from_keys();
664    }
665
666    fn reset_from_keys(&mut self) {
667        self.states.clear();
668        self.obs.clear();
669        for key in &mut self.keys {
670            let (next, reset_key) = split_key(*key);
671            *key = next;
672            let (obs, state) = self.env.reset(reset_key);
673            self.states.push(state);
674            self.obs.push(obs);
675        }
676    }
677
678    /// The number of environments.
679    pub fn num_envs(&self) -> usize {
680        self.states.len()
681    }
682
683    /// The environment.
684    pub fn env(&self) -> &C {
685        &self.env
686    }
687
688    /// The current states.
689    pub fn states(&self) -> &[C::State] {
690        &self.states
691    }
692
693    /// The number of elements of one observation.
694    pub fn obs_len(&self) -> usize {
695        self.env.obs_len()
696    }
697
698    /// Writes the current observations to a flat buffer, environment after
699    /// environment.
700    ///
701    /// # Panics
702    ///
703    /// Panics if the buffer does not have [`CompiledVecEnv::obs_len`]
704    /// elements per environment.
705    pub fn obs_into(&self, out: &mut [f32]) {
706        let len = self.obs_len();
707        assert_eq!(
708            out.len(),
709            self.num_envs() * len,
710            "an observation buffer of the wrong size"
711        );
712        for (i, o) in self.obs.iter().enumerate() {
713            self.env.obs_into(o, &mut out[i * len..(i + 1) * len]);
714        }
715    }
716
717    /// Uses `threads` threads (the caller included) for the steps.
718    ///
719    /// # Panics
720    ///
721    /// Panics if `threads` is zero.
722    pub fn set_num_threads(&mut self, threads: usize) {
723        assert!(threads > 0, "a VecEnv needs at least one thread");
724        self.pool = Pool::new(threads - 1);
725    }
726
727    /// Writes the legal action mask of every environment to `out` (see
728    /// [`VecEnv::legal_action_masks_into`]).
729    ///
730    /// # Panics
731    ///
732    /// Panics if `out` has the wrong size.
733    pub fn legal_action_masks_into(&self, out: &mut [bool]) -> bool {
734        let joint = self.env.action_space().mask_len();
735        assert_eq!(
736            out.len(),
737            self.num_envs() * joint,
738            "a mask buffer of the wrong size"
739        );
740        for (i, s) in self.states.iter().enumerate() {
741            if !self
742                .env
743                .legal_action_mask(s, &mut out[i * joint..(i + 1) * joint])
744            {
745                return false;
746            }
747        }
748        true
749    }
750
751    /// The number of threads that step the environments.
752    pub fn num_threads(&self) -> usize {
753        self.pool.num_threads()
754    }
755
756    /// Steps every environment with its action, in parallel, resetting the
757    /// episodes that end, and writes the results to flat buffers (see
758    /// [`VecEnv::step_into`]).
759    ///
760    /// # Panics
761    ///
762    /// Panics if the number of actions differs from the number of
763    /// environments, or a buffer has the wrong size.
764    pub fn step_into(&mut self, actions: &[i32], out: StepBuffers<'_>) {
765        self.step_into_actions(Actions::Discrete(actions), out);
766    }
767
768    /// [`CompiledVecEnv::step_into_actions`] without the final observations:
769    /// the step is the one without them ([`CompiledEnv::step_in_place`]), so
770    /// the generated code does not compute the observation reached before a
771    /// reset, and only the next observations are converted to `obs`.
772    ///
773    /// # Panics
774    ///
775    /// Panics if the number or kind of actions is wrong, or a buffer has the
776    /// wrong size.
777    pub fn step_into_without_final(
778        &mut self,
779        actions: Actions<'_>,
780        obs_out: &mut [f32],
781        reward: &mut [f32],
782        terminated: &mut [bool],
783        truncated: &mut [bool],
784    ) {
785        let n = self.num_envs();
786        let len = self.obs_len();
787        assert_eq!(actions.len(), n, "one action per environment");
788        assert_eq!(
789            obs_out.len(),
790            n * len,
791            "an observation buffer of the wrong size"
792        );
793        assert!(
794            reward.len() == n && terminated.len() == n && truncated.len() == n,
795            "a reward or end buffer of the wrong size"
796        );
797        let chunks = self
798            .pool
799            .num_threads()
800            .min(n.div_ceil(MIN_ENVS_PER_CHUNK))
801            .max(1);
802        let per_chunk = n.div_ceil(chunks);
803        let env = &self.env;
804        let keys = SharedPtr(self.keys.as_mut_ptr());
805        let states = SharedPtr(self.states.as_mut_ptr());
806        let obs = SharedPtr(self.obs.as_mut_ptr());
807        let obs_out = SharedPtr(obs_out.as_mut_ptr());
808        let reward = SharedPtr(reward.as_mut_ptr());
809        let terminated = SharedPtr(terminated.as_mut_ptr());
810        let truncated = SharedPtr(truncated.as_mut_ptr());
811        self.pool.run(chunks, &|c| {
812            let range = c * per_chunk..((c + 1) * per_chunk).min(n);
813            // SAFETY: the chunks are disjoint ranges of the buffers (of `n`
814            // environments, checked above), not otherwise accessed during the
815            // run; `Pool::run` returns after every chunk is done.
816            let (keys, states, obs, obs_out, reward, terminated, truncated) = unsafe {
817                (
818                    keys.slice(range.clone()),
819                    states.slice(range.clone()),
820                    obs.slice(range.clone()),
821                    obs_out.slice(range.start * len..range.end * len),
822                    reward.slice(range.clone()),
823                    terminated.slice(range.clone()),
824                    truncated.slice(range.clone()),
825                )
826            };
827            for i in 0..range.len() {
828                let a = <C::Action as crate::compiled::CompiledAction>::from_flat(
829                    actions,
830                    range.start + i,
831                );
832                let (next, step_key) = split_key(keys[i]);
833                keys[i] = next;
834                let info = env.step_in_place(step_key, &mut states[i], a, &mut obs[i]);
835                env.obs_into(&obs[i], &mut obs_out[i * len..(i + 1) * len]);
836                reward[i] = info.reward;
837                terminated[i] = info.terminated;
838                truncated[i] = info.truncated;
839            }
840        });
841    }
842
843    /// [`CompiledVecEnv::step_into`] with actions of any kind.
844    ///
845    /// # Panics
846    ///
847    /// Panics if the number or kind of actions is wrong, or a buffer has the
848    /// wrong size.
849    pub fn step_into_actions(&mut self, actions: Actions<'_>, out: StepBuffers<'_>) {
850        let n = self.num_envs();
851        let len = self.obs_len();
852        assert_eq!(actions.len(), n, "one action per environment");
853        assert_eq!(
854            out.obs.len(),
855            n * len,
856            "an observation buffer of the wrong size"
857        );
858        assert_eq!(
859            out.final_obs.len(),
860            n * len,
861            "an observation buffer of the wrong size"
862        );
863        assert_eq!(out.reward.len(), n, "a reward buffer of the wrong size");
864        assert_eq!(
865            out.terminated.len(),
866            n,
867            "a termination buffer of the wrong size"
868        );
869        assert_eq!(
870            out.truncated.len(),
871            n,
872            "a truncation buffer of the wrong size"
873        );
874        let chunks = self
875            .pool
876            .num_threads()
877            .min(n.div_ceil(MIN_ENVS_PER_CHUNK))
878            .max(1);
879        let per_chunk = n.div_ceil(chunks);
880        let env = &self.env;
881        let keys = SharedPtr(self.keys.as_mut_ptr());
882        let states = SharedPtr(self.states.as_mut_ptr());
883        let obs = SharedPtr(self.obs.as_mut_ptr());
884        let obs_out = SharedPtr(out.obs.as_mut_ptr());
885        let final_out = SharedPtr(out.final_obs.as_mut_ptr());
886        let reward = SharedPtr(out.reward.as_mut_ptr());
887        let terminated = SharedPtr(out.terminated.as_mut_ptr());
888        let truncated = SharedPtr(out.truncated.as_mut_ptr());
889        self.pool.run(chunks, &|c| {
890            let range = c * per_chunk..((c + 1) * per_chunk).min(n);
891            // SAFETY: the chunks are disjoint ranges of the buffers (of `n`
892            // environments, checked above), not otherwise accessed during the
893            // run; `Pool::run` returns after every chunk is done.
894            let (keys, states, obs, reward, terminated, truncated) = unsafe {
895                (
896                    keys.slice(range.clone()),
897                    states.slice(range.clone()),
898                    obs.slice(range.clone()),
899                    reward.slice(range.clone()),
900                    terminated.slice(range.clone()),
901                    truncated.slice(range.clone()),
902                )
903            };
904            // SAFETY: as above, the observation rows of this chunk.
905            let (obs_out, final_out) = unsafe {
906                (
907                    obs_out.slice(range.start * len..range.end * len),
908                    final_out.slice(range.start * len..range.end * len),
909                )
910            };
911            let mut final_obs = obs.first().cloned();
912            for i in 0..range.len() {
913                let a = <C::Action as crate::compiled::CompiledAction>::from_flat(
914                    actions,
915                    range.start + i,
916                );
917                let (next, step_key) = split_key(keys[i]);
918                keys[i] = next;
919                let f = final_obs.as_mut().expect("a non-empty chunk");
920                let info =
921                    env.step_in_place_with_final(step_key, &mut states[i], a, &mut obs[i], f);
922                env.obs_into(&obs[i], &mut obs_out[i * len..(i + 1) * len]);
923                env.obs_into(f, &mut final_out[i * len..(i + 1) * len]);
924                reward[i] = info.reward;
925                terminated[i] = info.terminated;
926                truncated[i] = info.truncated;
927            }
928        });
929    }
930}
931
932/// The default number of threads for `num_envs` environments: one per
933/// physical core (a second thread on a core shares its execution units and
934/// slows the spinning workers), and at most one per 32 environments, below
935/// which the work of a step does not pay for waking a thread.
936fn default_threads(num_envs: usize) -> usize {
937    let logical = std::thread::available_parallelism().map_or(1, |n| n.get());
938    let cores = physical_cores().unwrap_or(logical).clamp(1, logical);
939    cores.min(num_envs.div_ceil(32)).max(1)
940}
941
942/// The number of physical cores, if known: on Linux, the distinct
943/// `(physical id, core id)` pairs of `/proc/cpuinfo` (x86-64) or, where it has
944/// none (AArch64), the distinct sibling sets of
945/// `/sys/devices/system/cpu/cpu*/topology`; on macOS, the performance cores
946/// (`hw.perflevel0.physicalcpu`, or `hw.physicalcpu` on Intel), since the
947/// workers take equal chunks and an efficiency core would hold up the step.
948fn physical_cores() -> Option<usize> {
949    #[cfg(target_os = "linux")]
950    {
951        linux_cpuinfo_cores().or_else(linux_sysfs_cores)
952    }
953    #[cfg(target_os = "macos")]
954    {
955        macos_sysctl("hw.perflevel0.physicalcpu").or_else(|| macos_sysctl("hw.physicalcpu"))
956    }
957    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
958    {
959        None
960    }
961}
962
963/// The distinct `(physical id, core id)` pairs of `/proc/cpuinfo`.
964#[cfg(target_os = "linux")]
965fn linux_cpuinfo_cores() -> Option<usize> {
966    let info = std::fs::read_to_string("/proc/cpuinfo").ok()?;
967    let mut cores = std::collections::HashSet::new();
968    let mut physical = None;
969    for line in info.lines() {
970        let mut parts = line.splitn(2, ':');
971        let (key, value) = (parts.next()?.trim(), parts.next().map(str::trim));
972        match key {
973            "physical id" => physical = value.map(String::from),
974            "core id" => {
975                cores.insert((physical.clone(), value.map(String::from)));
976            }
977            _ => {}
978        }
979    }
980    (!cores.is_empty()).then_some(cores.len())
981}
982
983/// The distinct sets of hardware threads that share a core, from the
984/// topology of every CPU in sysfs.
985#[cfg(target_os = "linux")]
986fn linux_sysfs_cores() -> Option<usize> {
987    let mut cores = std::collections::HashSet::new();
988    for entry in std::fs::read_dir("/sys/devices/system/cpu").ok()? {
989        let path = entry.ok()?.path();
990        let is_cpu = path
991            .file_name()
992            .and_then(|n| n.to_str())
993            .and_then(|n| n.strip_prefix("cpu"))
994            .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()));
995        if !is_cpu {
996            continue;
997        }
998        let topology = path.join("topology");
999        let siblings = std::fs::read_to_string(topology.join("core_cpus_list"))
1000            .or_else(|_| std::fs::read_to_string(topology.join("thread_siblings_list")));
1001        if let Ok(siblings) = siblings {
1002            cores.insert(siblings.trim().to_string());
1003        }
1004    }
1005    (!cores.is_empty()).then_some(cores.len())
1006}
1007
1008/// An integer of `sysctlbyname`.
1009#[cfg(target_os = "macos")]
1010fn macos_sysctl(name: &str) -> Option<usize> {
1011    use std::ffi::{CString, c_char, c_int, c_void};
1012    unsafe extern "C" {
1013        // libSystem, linked into every macOS program.
1014        fn sysctlbyname(
1015            name: *const c_char,
1016            oldp: *mut c_void,
1017            oldlenp: *mut usize,
1018            newp: *mut c_void,
1019            newlen: usize,
1020        ) -> c_int;
1021    }
1022    let name = CString::new(name).ok()?;
1023    let mut value: i32 = 0;
1024    let mut len = std::mem::size_of::<i32>();
1025    // SAFETY: `name` is a NUL-terminated string, `value` is writable for
1026    // `len` bytes (sysctl writes at most `len` and updates it), and no new
1027    // value is set.
1028    let rc = unsafe {
1029        sysctlbyname(
1030            name.as_ptr(),
1031            (&raw mut value).cast(),
1032            &mut len,
1033            std::ptr::null_mut(),
1034            0,
1035        )
1036    };
1037    (rc == 0 && len == std::mem::size_of::<i32>() && value > 0).then_some(value as usize)
1038}
1039
1040#[cfg(test)]
1041mod tests {
1042    use super::*;
1043
1044    #[test]
1045    fn default_threads_follow_the_cores_and_the_environments() {
1046        let logical = std::thread::available_parallelism().map_or(1, |n| n.get());
1047        assert_eq!(default_threads(1), 1);
1048        assert_eq!(default_threads(32), 1);
1049        assert!(default_threads(64) <= 2);
1050        let many = default_threads(1 << 20);
1051        assert!(many >= 1 && many <= logical);
1052        if let Some(cores) = physical_cores() {
1053            assert_eq!(many, cores.min(logical));
1054        }
1055    }
1056
1057    #[test]
1058    #[cfg(target_os = "linux")]
1059    fn the_sysfs_topology_agrees_with_cpuinfo() {
1060        // Where both are known (x86-64), they count the same cores.
1061        if let (Some(a), Some(b)) = (linux_cpuinfo_cores(), linux_sysfs_cores()) {
1062            assert_eq!(a, b);
1063        }
1064    }
1065}