//! Coordination for LibTorch's process-wide random state and CPU worker pool. //! //! Training holds the runtime guard from initialization through publication. //! Model loading holds it while constructing temporary randomized parameters. //! Inference on an already loaded model uses neither seed mutation nor dropout //! and can proceed concurrently. Acquisition never waits for another operation. use std::sync::{Mutex, MutexGuard, TryLockError}; use thiserror::Error; /// Single ownership of operations that initialize or consume training RNG state. static OPERATION: Mutex<()> = Mutex::new(()); /// The CPU pool is configured once and remains fixed for this process lifetime. static THREADS: Mutex> = Mutex::new(None); /// Recoverable process-runtime coordination failures. #[derive(Debug, Error)] pub enum RuntimeError { /// Another operation holds the RNG-changing runtime capability. #[error("another training or model-loading operation is active; retry when it completes")] Busy, /// A dependency panic invalidated the runtime's initialization invariant. #[error("the native runtime is unavailable after a failed operation; restart the process")] Poisoned, /// The thread count cannot be passed to LibTorch. #[error("native thread count must be a positive signed 32-bit integer")] InvalidThreads, /// The shared CPU pool was already established with a different size. #[error( "LibTorch already uses {configured} threads; restart the process to request {requested}" )] ThreadCountChanged { /// Thread count selected by the first successful configuration. configured: i32, /// Conflicting thread count requested by this operation. requested: i32, }, } /// Exclusive capability to mutate LibTorch's process-wide training RNG state. /// /// Keep this guard alive for the complete training operation, or for model /// construction/loading. Its destructor releases the capability without joining /// any worker. The guard intentionally cannot be copied or moved across threads. pub struct RuntimeGuard { /// Standard mutex guard proves sole ownership and releases it on drop. _guard: MutexGuard<'static, ()>, } /// Try to claim the runtime capability, returning Busy without blocking. pub fn try_acquire() -> Result { acquire_from(&OPERATION) } /// Claim a named runtime lock; injection keeps lock-law tests process-independent. fn acquire_from(operation: &'static Mutex<()>) -> Result { match operation.try_lock() { Ok(guard) => Ok(RuntimeGuard { _guard: guard }), Err(TryLockError::WouldBlock) => Err(RuntimeError::Busy), Err(TryLockError::Poisoned(_)) => Err(RuntimeError::Poisoned), } } /// Configure LibTorch's global thread count once; reject later changes. /// /// Call before constructing any model. Repeat calls with the same count are /// harmless, including while cached inference or training is running. pub fn configure_threads(requested: i32) -> Result<(), RuntimeError> { if requested <= 0 { return Err(RuntimeError::InvalidThreads); } let mut configured = match THREADS.try_lock() { Ok(guard) => guard, Err(TryLockError::WouldBlock) => return Err(RuntimeError::Busy), Err(TryLockError::Poisoned(_)) => return Err(RuntimeError::Poisoned), }; match *configured { Some(previous) if previous != requested => Err(RuntimeError::ThreadCountChanged { configured: previous, requested, }), Some(_) => Ok(()), None => { tch::set_num_threads(requested); *configured = Some(requested); Ok(()) } } } /// Serialize library tests that construct models or consume global LibTorch RNG. /// /// This separate test-only mutex allows an entire test to retain isolation while /// production training independently acquires its nonblocking runtime guard. /// Recovering this mutex after an assertion panic avoids hiding the first test /// failure; the production runtime's own poisoning behavior remains unchanged. #[cfg(test)] pub(crate) fn test_serial_guard() -> MutexGuard<'static, ()> { /// Test scheduling must not race tensor seeds or runtime-capability checks. static TEST_EXECUTION: Mutex<()> = Mutex::new(()); match TEST_EXECUTION.lock() { Ok(guard) => guard, Err(poisoned) => poisoned.into_inner(), } } #[cfg(test)] mod tests { use super::*; /// Competing capabilities fail immediately and dropping the guard restores access. #[test] fn exclusive_runtime_guard_is_nonblocking_and_reusable() -> Result<(), RuntimeError> { static TEST_OPERATION: Mutex<()> = Mutex::new(()); let guard = acquire_from(&TEST_OPERATION)?; assert!(matches!( acquire_from(&TEST_OPERATION), Err(RuntimeError::Busy) )); drop(guard); let _next = acquire_from(&TEST_OPERATION)?; Ok(()) } /// Invalid pool sizes fail before touching process-wide state. #[test] fn nonpositive_threads_are_rejected() { assert!(matches!( configure_threads(0), Err(RuntimeError::InvalidThreads) )); assert!(matches!( configure_threads(-1), Err(RuntimeError::InvalidThreads) )); } }