rusttorch-data 0.3.0

Typed datasets, samplers, batching, and loading for RustTorch
Documentation
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
use std::{
    cell::RefCell,
    convert::Infallible,
    fmt,
    sync::{
        Arc, Condvar, Mutex,
        atomic::{AtomicBool, Ordering},
    },
    time::{Duration, Instant},
};

use crossbeam_channel::{Receiver, Sender, bounded};
use rusttorch_core::{Result, RustTorchError};

/// Version of RustTorch's deterministic worker-seed derivation.
pub const WORKER_SEED_DERIVATION_VERSION: u32 = 1;

// Predicate transitions always acquire `wait_lock` first, then `deadline` or
// `signal_sender`, and notify while `wait_lock` is still held. Readers that
// need both locks use the same `wait_lock -> deadline` order. This is the one
// lock order for lifecycle state and prevents a notification between a
// predicate check and the condition-variable park.
struct CancellationState {
    cancelled: AtomicBool,
    wait_lock: Mutex<()>,
    deadline: Mutex<Option<Instant>>,
    wake: Condvar,
    signal: Receiver<()>,
    signal_sender: Mutex<Option<Sender<()>>>,
    #[cfg(test)]
    require_wait_lock_for_transition: AtomicBool,
}

impl CancellationState {
    fn new(deadline: Option<Instant>) -> Arc<Self> {
        let (signal_sender, signal) = bounded(0);
        Arc::new(Self {
            cancelled: AtomicBool::new(false),
            wait_lock: Mutex::new(()),
            deadline: Mutex::new(deadline),
            wake: Condvar::new(),
            signal,
            signal_sender: Mutex::new(Some(signal_sender)),
            #[cfg(test)]
            require_wait_lock_for_transition: AtomicBool::new(false),
        })
    }

    #[cfg(test)]
    fn assert_transition_holds_wait_lock(&self) {
        if self.require_wait_lock_for_transition.load(Ordering::SeqCst) {
            assert!(
                self.wait_lock.try_lock().is_err(),
                "predicate transition did not hold the waiter mutex"
            );
        }
    }
}

/// Cloneable cooperative cancellation notification.
///
/// Cancellation is sticky. Waiting uses a condition variable and queue waits
/// use the same token's disconnection signal, so neither path polls.
#[derive(Clone)]
pub struct CancellationToken {
    state: Arc<CancellationState>,
}

impl fmt::Debug for CancellationToken {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CancellationToken")
            .field("cancelled", &self.is_cancelled())
            .finish_non_exhaustive()
    }
}

impl Default for CancellationToken {
    fn default() -> Self {
        Self::new()
    }
}

impl CancellationToken {
    /// Creates a live token with no deadline.
    pub fn new() -> Self {
        Self {
            state: CancellationState::new(None),
        }
    }

    /// Requests cooperative cancellation and wakes every waiter.
    pub fn cancel(&self) {
        let _wait_guard = self.state.wait_lock.lock().unwrap();
        #[cfg(test)]
        self.state.assert_transition_holds_wait_lock();
        if !self.state.cancelled.swap(true, Ordering::AcqRel) {
            self.state.signal_sender.lock().unwrap().take();
            self.state.wake.notify_all();
        }
    }

    /// Returns whether cancellation has been requested.
    pub fn is_cancelled(&self) -> bool {
        self.state.cancelled.load(Ordering::Acquire)
    }

    /// Blocks until cancellation is requested.
    pub fn wait_cancelled(&self) {
        let mut guard = self.state.wait_lock.lock().unwrap();
        while !self.is_cancelled() {
            guard = self.state.wake.wait(guard).unwrap();
        }
    }

    /// Waits up to `timeout`, returning `true` when cancellation won.
    pub fn wait_cancelled_timeout(&self, timeout: Duration) -> bool {
        if self.is_cancelled() {
            return true;
        }
        let guard = self.state.wait_lock.lock().unwrap();
        let _ = self
            .state
            .wake
            .wait_timeout_while(guard, timeout, |_| !self.is_cancelled())
            .unwrap();
        self.is_cancelled()
    }

    pub(crate) fn signal(&self) -> &Receiver<()> {
        &self.state.signal
    }

    pub(crate) fn paired_deadline(&self) -> Deadline {
        Deadline {
            state: Arc::clone(&self.state),
        }
    }

    pub(crate) fn wait_cancelled_or_deadline(&self, deadline: &Deadline) -> WaitOutcome {
        let mut guard = self.state.wait_lock.lock().unwrap();
        loop {
            if self.is_cancelled() {
                return WaitOutcome::Cancelled;
            }
            match deadline.remaining() {
                Some(remaining) if remaining.is_zero() => return WaitOutcome::DeadlineExpired,
                Some(remaining) => {
                    let (next, _) = self.state.wake.wait_timeout(guard, remaining).unwrap();
                    guard = next;
                }
                None => guard = self.state.wake.wait(guard).unwrap(),
            }
        }
    }
}

/// Cloneable monotonic deadline visible to cooperative worker code.
///
/// Loader-owned deadlines are armed for each blocking `Iterator::next` call
/// and disarmed afterwards. [`Deadline::none`] never expires.
#[derive(Clone)]
pub struct Deadline {
    state: Arc<CancellationState>,
}

impl fmt::Debug for Deadline {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Deadline")
            .field("remaining", &self.remaining())
            .finish_non_exhaustive()
    }
}

impl Default for Deadline {
    fn default() -> Self {
        Self::none()
    }
}

impl Deadline {
    /// Creates an unarmed deadline.
    pub fn none() -> Self {
        Self {
            state: CancellationState::new(None),
        }
    }

    /// Creates a deadline expiring after `timeout`.
    ///
    /// A duration outside the platform's monotonic [`Instant`] range fails
    /// closed as an already-expired deadline; it never becomes unarmed.
    pub fn after(timeout: Duration) -> Self {
        let now = Instant::now();
        Self {
            state: CancellationState::new(Some(now.checked_add(timeout).unwrap_or(now))),
        }
    }

    /// Returns whether the armed deadline has expired.
    pub fn is_expired(&self) -> bool {
        self.remaining()
            .is_some_and(|remaining| remaining.is_zero())
    }

    /// Returns the remaining duration, or `None` when unarmed.
    pub fn remaining(&self) -> Option<Duration> {
        self.state
            .deadline
            .lock()
            .unwrap()
            .map(|deadline| deadline.saturating_duration_since(Instant::now()))
    }

    pub(crate) fn arm(&self, timeout: Duration) {
        let _wait_guard = self.state.wait_lock.lock().unwrap();
        #[cfg(test)]
        self.state.assert_transition_holds_wait_lock();
        let now = Instant::now();
        *self.state.deadline.lock().unwrap() = Some(now.checked_add(timeout).unwrap_or(now));
        self.state.wake.notify_all();
    }

    pub(crate) fn disarm(&self) {
        let _wait_guard = self.state.wait_lock.lock().unwrap();
        #[cfg(test)]
        self.state.assert_transition_holds_wait_lock();
        *self.state.deadline.lock().unwrap() = None;
        self.state.wake.notify_all();
    }

    pub(crate) fn can_represent(timeout: Duration) -> bool {
        Instant::now().checked_add(timeout).is_some()
    }
}

/// Outcome of waiting for cooperative cancellation or a deadline.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WaitOutcome {
    /// Cancellation was requested.
    Cancelled,
    /// The monotonic deadline expired.
    DeadlineExpired,
}

/// Error returned by [`WorkerContext::check`] after cancellation or expiry.
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[error("loader work was cancelled or its deadline expired")]
pub struct LoaderCancelled;

/// Stable information visible while a loader worker callback is active.
///
/// Use `id` and `num_workers` to divide source records, and `seed` to initialize
/// worker-local randomness. The dataset remains owned by the typed loader.
///
/// ```
/// use rusttorch_data::WorkerInfo;
/// let info = WorkerInfo::new(1, 3, 42, 0)?;
/// let records: Vec<_> = (info.id..10).step_by(info.num_workers).collect();
/// assert_eq!(records, [1, 4, 7]);
/// # Ok::<(), rusttorch_core::RustTorchError>(())
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WorkerInfo {
    /// Zero-based worker identifier.
    pub id: usize,
    /// Total workers in the pool.
    pub num_workers: usize,
    /// Worker-local initialization seed.
    pub seed: u64,
    /// Distributed rank configured on the loader.
    pub rank: usize,
}

impl WorkerInfo {
    /// Creates validated worker information from an explicit seed.
    ///
    /// # Errors
    ///
    /// Returns [`RustTorchError::InvalidConfiguration`] when `num_workers` is
    /// zero or `id` is outside the worker pool.
    pub fn new(id: usize, num_workers: usize, seed: u64, rank: usize) -> Result<Self> {
        validate_worker(id, num_workers)?;
        Ok(Self {
            id,
            num_workers,
            seed,
            rank,
        })
    }

    /// Creates validated worker information using version-1 seed derivation.
    ///
    /// Worker seeds are consecutive by identifier for one loader seed, rank,
    /// and iterator generation. This RustTorch sequence does not claim
    /// PyTorch generator or Philox identity.
    ///
    /// # Errors
    ///
    /// Returns [`RustTorchError::InvalidConfiguration`] when the worker
    /// identity is outside the configured pool.
    pub fn from_loader_seed(
        id: usize,
        num_workers: usize,
        loader_seed: u64,
        rank: usize,
        iterator_generation: u64,
    ) -> Result<Self> {
        Self::new(
            id,
            num_workers,
            derive_worker_seed(loader_seed, rank, iterator_generation, id),
            rank,
        )
    }
}

/// Cancellation and deadline state passed to worker lifecycle callbacks.
///
/// For persistent pools this context belongs to the pool lifetime: its token
/// is cancelled only when the owner shuts the pool down. Dataset fetches and
/// task transforms receive a separate, fresh context for each iterator
/// generation.
///
/// ```
/// use std::time::Duration;
/// use rusttorch_data::{
///     CancellationToken, Deadline, LoaderCancelled, WaitOutcome,
///     WorkerContext, WorkerInfo,
/// };
///
/// let cancellation = CancellationToken::new();
/// let context = WorkerContext::new(
///     WorkerInfo::new(0, 1, 7, 0)?,
///     cancellation.clone(),
///     Deadline::none(),
/// );
/// assert!(context.check().is_ok());
/// let cancel = std::thread::spawn(move || cancellation.cancel());
/// assert_eq!(context.wait_cancelled_or_deadline(), WaitOutcome::Cancelled);
/// cancel.join().unwrap();
/// let _: LoaderCancelled = context.check().unwrap_err();
///
/// let expired = WorkerContext::new(
///     WorkerInfo::new(0, 1, 7, 0)?,
///     CancellationToken::new(),
///     Deadline::after(Duration::ZERO),
/// );
/// assert_eq!(
///     expired.wait_cancelled_or_deadline(),
///     WaitOutcome::DeadlineExpired,
/// );
/// # Ok::<(), rusttorch_core::RustTorchError>(())
/// ```
#[derive(Clone, Debug)]
pub struct WorkerContext {
    /// Stable worker identity and initialization seed.
    pub info: WorkerInfo,
    /// Cooperative cancellation token.
    pub cancellation: CancellationToken,
    /// Dynamic monotonic deadline.
    pub deadline: Deadline,
}

impl WorkerContext {
    /// Creates a context from explicit worker information and controls.
    pub fn new(info: WorkerInfo, cancellation: CancellationToken, deadline: Deadline) -> Self {
        Self {
            info,
            cancellation,
            deadline,
        }
    }

    /// Returns an error when cancelled or expired.
    pub fn check(&self) -> std::result::Result<(), LoaderCancelled> {
        if self.cancellation.is_cancelled() || self.deadline.is_expired() {
            Err(LoaderCancelled)
        } else {
            Ok(())
        }
    }

    /// Blocks until cancellation or deadline expiry.
    pub fn wait_cancelled_or_deadline(&self) -> WaitOutcome {
        self.cancellation.wait_cancelled_or_deadline(&self.deadline)
    }
}

/// Initializes one worker after its context becomes active.
///
/// The default serial loader imposes no thread-safety bound; positive worker
/// execution requires a shared `Send + Sync` initializer.
pub trait WorkerInit {
    /// Initialization failure.
    type Error;

    /// Initializes `worker` once for its worker lifecycle.
    fn initialize(&self, worker: &WorkerContext) -> std::result::Result<(), Self::Error>;
}

/// Adapts a fallible closure into a [`WorkerInit`].
#[derive(Clone, Copy, Debug)]
pub struct FnWorkerInit<F> {
    initialize: F,
}

impl<F> FnWorkerInit<F> {
    /// Creates a closure-backed worker initializer.
    pub fn new(initialize: F) -> Self {
        Self { initialize }
    }
}

impl<E, F> WorkerInit for FnWorkerInit<F>
where
    F: Fn(&WorkerContext) -> std::result::Result<(), E>,
{
    type Error = E;

    fn initialize(&self, worker: &WorkerContext) -> std::result::Result<(), Self::Error> {
        (self.initialize)(worker)
    }
}

/// Default worker initializer that performs no work.
#[derive(Clone, Copy, Debug, Default)]
pub struct NoWorkerInit;

impl WorkerInit for NoWorkerInit {
    type Error = Infallible;

    fn initialize(&self, _worker: &WorkerContext) -> std::result::Result<(), Self::Error> {
        Ok(())
    }
}

thread_local! {
    static WORKER_INFO: RefCell<Option<WorkerInfo>> = const { RefCell::new(None) };
}

/// Returns worker information for the active callback, if any.
///
/// ```
/// use rusttorch_data::get_worker_info;
///
/// assert_eq!(get_worker_info(), None);
/// ```
pub fn get_worker_info() -> Option<WorkerInfo> {
    WORKER_INFO.with(|current| *current.borrow())
}

/// Runs a callback in a simulated worker scope.
///
/// This hook supports worker-contract tests and the bounded worker engine. Its
/// RAII guard restores nested context during normal return and unwinding.
#[doc(hidden)]
pub fn with_worker_info<T>(worker: WorkerInfo, callback: impl FnOnce() -> T) -> T {
    struct Restore(Option<WorkerInfo>);

    impl Drop for Restore {
        fn drop(&mut self) {
            WORKER_INFO.with(|current| *current.borrow_mut() = self.0);
        }
    }

    let previous = WORKER_INFO.with(|current| current.borrow_mut().replace(worker));
    let _restore = Restore(previous);
    callback()
}

fn validate_worker(id: usize, num_workers: usize) -> Result<()> {
    if num_workers == 0 {
        return Err(invalid_configuration(
            "num_workers",
            "must be greater than zero",
        ));
    }
    if id >= num_workers {
        return Err(invalid_configuration(
            "worker_id",
            "must be less than num_workers",
        ));
    }
    Ok(())
}

fn splitmix64(mut value: u64) -> u64 {
    value = value.wrapping_add(0x9e37_79b9_7f4a_7c15);
    value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
    value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
    value ^ (value >> 31)
}

fn derive_worker_seed(
    loader_seed: u64,
    rank: usize,
    iterator_generation: u64,
    worker_id: usize,
) -> u64 {
    let rank_domain = (rank as u64).wrapping_mul(0xd1b5_4a32_d192_ed03);
    let iterator_domain = iterator_generation.wrapping_mul(0xa076_1d64_78bd_642f);
    splitmix64(loader_seed ^ rank_domain ^ iterator_domain).wrapping_add(worker_id as u64)
}

fn invalid_configuration(field: &'static str, reason: impl Into<String>) -> RustTorchError {
    RustTorchError::InvalidConfiguration {
        field,
        reason: reason.into(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cancellation_transition_holds_the_waiter_mutex() {
        let cancellation = CancellationToken::new();
        cancellation
            .state
            .require_wait_lock_for_transition
            .store(true, Ordering::SeqCst);

        cancellation.cancel();
        assert!(cancellation.is_cancelled());
    }

    #[test]
    fn deadline_transitions_hold_the_waiter_mutex() {
        let cancellation = CancellationToken::new();
        let deadline = cancellation.paired_deadline();
        cancellation
            .state
            .require_wait_lock_for_transition
            .store(true, Ordering::SeqCst);

        deadline.arm(Duration::from_secs(1));
        deadline.disarm();
        assert_eq!(deadline.remaining(), None);
    }
}