File size: 5,444 Bytes
2109241 36fe364 2109241 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | //! 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<Option<i32>> = 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<RuntimeGuard, RuntimeError> {
acquire_from(&OPERATION)
}
/// Claim a named runtime lock; injection keeps lock-law tests process-independent.
fn acquire_from(operation: &'static Mutex<()>) -> Result<RuntimeGuard, RuntimeError> {
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)
));
}
}
|