Skip to main content

torsh_data/dataloader/
workers.rs

1//! Worker pool functionality for multi-process data loading
2//!
3//! This module provides worker pool implementations for parallel data loading,
4//! including both standard and persistent worker pools.
5
6use crate::{collate::Collate, dataset::Dataset, sampler::BatchSampler};
7use std::collections::HashMap;
8use std::sync::mpsc;
9use std::sync::{Arc, Mutex};
10use std::thread;
11use torsh_core::error::Result;
12
13/// Worker task containing indices to process
14#[derive(Debug, Clone)]
15struct WorkerTask {
16    task_id: usize,
17    indices: Vec<usize>,
18}
19
20/// Worker result containing processed batch
21#[derive(Debug)]
22pub struct WorkerResult<T> {
23    pub task_id: usize,
24    pub result: Result<T>,
25}
26
27/// Handle to a worker thread
28struct WorkerHandle<T> {
29    _thread: thread::JoinHandle<()>,
30    _phantom: std::marker::PhantomData<T>,
31}
32
33/// Worker process manager for multi-process data loading
34///
35/// This struct manages a pool of worker threads that process batches in parallel,
36/// allowing for efficient utilization of multiple CPU cores during data loading.
37///
38/// # Type Parameters
39///
40/// * `D` - Dataset type implementing the Dataset trait
41/// * `C` - Collate function type implementing the Collate trait
42///
43/// # Examples
44///
45/// ```rust,ignore
46/// use std::sync::Arc;
47/// use torsh_data::dataloader::workers::WorkerPool;
48/// use torsh_data::dataset::TensorDataset;
49/// use torsh_data::collate::DefaultCollate;
50///
51/// let dataset = Arc::new(TensorDataset::new(vec![1, 2, 3, 4, 5]));
52/// let collate_fn = Arc::new(DefaultCollate);
53/// let worker_pool = WorkerPool::new(dataset, collate_fn, 4);
54///
55/// // Submit tasks and collect results
56/// worker_pool.submit_task(0, vec![0, 1]).unwrap();
57/// let result = worker_pool.get_result().unwrap();
58/// ```
59pub struct WorkerPool<D, C>
60where
61    D: Dataset + Clone + Send + Sync + 'static,
62    C: Collate<D::Item> + Clone + Send + Sync + 'static,
63    D::Item: Send + 'static,
64    C::Output: Send + 'static,
65{
66    #[allow(dead_code)]
67    dataset: Arc<D>,
68    #[allow(dead_code)]
69    collate_fn: Arc<C>,
70    num_workers: usize,
71    #[allow(dead_code)]
72    workers: Vec<WorkerHandle<C::Output>>,
73    task_sender: mpsc::Sender<WorkerTask>,
74    result_receiver: mpsc::Receiver<WorkerResult<C::Output>>,
75}
76
77impl<D, C> WorkerPool<D, C>
78where
79    D: Dataset + Clone + Send + Sync + 'static,
80    C: Collate<D::Item> + Clone + Send + Sync + 'static,
81    D::Item: Send + 'static,
82    C::Output: Send + 'static,
83{
84    /// Create a new worker pool
85    ///
86    /// # Arguments
87    ///
88    /// * `dataset` - The dataset to process
89    /// * `collate_fn` - The collation function to apply to batches
90    /// * `num_workers` - Number of worker threads to spawn
91    ///
92    /// # Returns
93    ///
94    /// A new WorkerPool ready to process tasks
95    pub fn new(dataset: Arc<D>, collate_fn: Arc<C>, num_workers: usize) -> Self {
96        let (task_sender, task_receiver) = mpsc::channel::<WorkerTask>();
97        let (result_sender, result_receiver) = mpsc::channel::<WorkerResult<C::Output>>();
98
99        let task_receiver = Arc::new(Mutex::new(task_receiver));
100        let mut workers = Vec::with_capacity(num_workers);
101
102        // Spawn worker threads
103        for worker_id in 0..num_workers {
104            let dataset_clone = Arc::clone(&dataset);
105            let collate_fn_clone = Arc::clone(&collate_fn);
106            let task_receiver_clone = Arc::clone(&task_receiver);
107            let result_sender_clone = result_sender.clone();
108
109            let worker_thread = thread::spawn(move || {
110                Self::worker_loop(
111                    worker_id,
112                    dataset_clone,
113                    collate_fn_clone,
114                    task_receiver_clone,
115                    result_sender_clone,
116                );
117            });
118
119            workers.push(WorkerHandle {
120                _thread: worker_thread,
121                _phantom: std::marker::PhantomData,
122            });
123        }
124
125        Self {
126            dataset,
127            collate_fn,
128            num_workers,
129            workers,
130            task_sender,
131            result_receiver,
132        }
133    }
134
135    /// Worker thread loop
136    ///
137    /// This is the main loop that each worker thread runs to process tasks.
138    #[allow(clippy::too_many_arguments)]
139    fn worker_loop(
140        _worker_id: usize,
141        dataset: Arc<D>,
142        collate_fn: Arc<C>,
143        task_receiver: Arc<Mutex<mpsc::Receiver<WorkerTask>>>,
144        result_sender: mpsc::Sender<WorkerResult<C::Output>>,
145    ) {
146        loop {
147            // Try to receive a task
148            let task = {
149                let receiver = match task_receiver.lock() {
150                    Ok(receiver) => receiver,
151                    Err(_) => {
152                        // Mutex is poisoned, worker should exit
153                        break;
154                    }
155                };
156                receiver.recv()
157            };
158
159            match task {
160                Ok(WorkerTask { task_id, indices }) => {
161                    // Process the batch
162                    let batch_result = Self::process_batch(&*dataset, &*collate_fn, indices);
163
164                    let result = WorkerResult {
165                        task_id,
166                        result: batch_result,
167                    };
168
169                    // Send result back
170                    if result_sender.send(result).is_err() {
171                        // Main thread is no longer listening, exit
172                        break;
173                    }
174                }
175                Err(_) => {
176                    // Main thread closed the channel, exit
177                    break;
178                }
179            }
180        }
181    }
182
183    /// Process a batch of indices
184    ///
185    /// # Arguments
186    ///
187    /// * `dataset` - The dataset to load from
188    /// * `collate_fn` - The collation function to apply
189    /// * `indices` - The indices of samples to load
190    ///
191    /// # Returns
192    ///
193    /// The collated batch result
194    fn process_batch(dataset: &D, collate_fn: &C, indices: Vec<usize>) -> Result<C::Output> {
195        let mut samples = Vec::with_capacity(indices.len());
196
197        for idx in indices {
198            match dataset.get(idx) {
199                Ok(sample) => samples.push(sample),
200                Err(e) => return Err(e),
201            }
202        }
203
204        collate_fn.collate(samples)
205    }
206
207    /// Submit a task to the worker pool
208    ///
209    /// # Arguments
210    ///
211    /// * `task_id` - Unique identifier for the task
212    /// * `indices` - Indices of samples to process
213    ///
214    /// # Returns
215    ///
216    /// Result indicating success or failure of task submission
217    pub fn submit_task(&self, task_id: usize, indices: Vec<usize>) -> Result<()> {
218        let task = WorkerTask { task_id, indices };
219
220        self.task_sender.send(task).map_err(|_| {
221            torsh_core::error::TorshError::RuntimeError(
222                "Failed to send task to worker pool".to_string(),
223            )
224        })?;
225
226        Ok(())
227    }
228
229    /// Get a result from the worker pool
230    ///
231    /// This method blocks until a result is available from any worker.
232    ///
233    /// # Returns
234    ///
235    /// The next available worker result
236    pub fn get_result(&self) -> Result<WorkerResult<C::Output>> {
237        self.result_receiver.recv().map_err(|_| {
238            torsh_core::error::TorshError::RuntimeError(
239                "Failed to receive result from worker pool".to_string(),
240            )
241        })
242    }
243
244    /// Try to get a result without blocking
245    ///
246    /// # Returns
247    ///
248    /// Some(result) if a result is available, None otherwise
249    pub fn try_get_result(&self) -> Option<WorkerResult<C::Output>> {
250        self.result_receiver.try_recv().ok()
251    }
252
253    /// Get the number of workers
254    ///
255    /// # Returns
256    ///
257    /// The number of worker threads in the pool
258    pub fn num_workers(&self) -> usize {
259        self.num_workers
260    }
261}
262
263/// Multi-process DataLoader iterator
264///
265/// This iterator coordinates with a WorkerPool to process batches in parallel,
266/// maintaining a pipeline of pending tasks to maximize throughput.
267///
268/// # Type Parameters
269///
270/// * `D` - Dataset type
271/// * `S` - Sampler type
272/// * `C` - Collate function type
273pub struct MultiProcessIterator<'a, D, S, C>
274where
275    D: Dataset + Clone + Send + Sync + 'static,
276    S: BatchSampler,
277    C: Collate<D::Item> + Clone + Send + Sync + 'static,
278    D::Item: Send + 'static,
279    C::Output: Send + 'static,
280{
281    sampler_iter: S::Iter,
282    worker_pool: &'a WorkerPool<D, C>,
283    pending_tasks: HashMap<usize, Vec<usize>>,
284    /// Completed results that arrived out of order, keyed by task_id, waiting
285    /// for `next_expected_id` to catch up so they can be emitted in
286    /// submission order.
287    result_buffer: HashMap<usize, Result<C::Output>>,
288    next_task_id: usize,
289    /// task_id of the next batch that must be returned from `next()`.
290    next_expected_id: usize,
291    max_pending: usize,
292}
293
294impl<'a, D, S, C> MultiProcessIterator<'a, D, S, C>
295where
296    D: Dataset + Clone + Send + Sync + 'static,
297    S: BatchSampler,
298    C: Collate<D::Item> + Clone + Send + Sync + 'static,
299    D::Item: Send + 'static,
300    C::Output: Send + 'static,
301{
302    /// Create a new multi-process iterator
303    ///
304    /// # Arguments
305    ///
306    /// * `sampler_iter` - Iterator over batch indices
307    /// * `worker_pool` - Worker pool to use for processing
308    ///
309    /// # Returns
310    ///
311    /// A new MultiProcessIterator
312    pub fn new(sampler_iter: S::Iter, worker_pool: &'a WorkerPool<D, C>) -> Self {
313        let max_pending = worker_pool.num_workers() * 2; // Buffer 2x the number of workers
314
315        Self {
316            sampler_iter,
317            worker_pool,
318            pending_tasks: HashMap::new(),
319            result_buffer: HashMap::new(),
320            next_task_id: 0,
321            next_expected_id: 0,
322            max_pending,
323        }
324    }
325
326    /// Create a new multi-process iterator with custom buffer size
327    ///
328    /// # Arguments
329    ///
330    /// * `sampler_iter` - Iterator over batch indices
331    /// * `worker_pool` - Worker pool to use for processing
332    /// * `max_pending` - Maximum number of pending tasks
333    ///
334    /// # Returns
335    ///
336    /// A new MultiProcessIterator with custom buffering
337    pub fn with_buffer_size(
338        sampler_iter: S::Iter,
339        worker_pool: &'a WorkerPool<D, C>,
340        max_pending: usize,
341    ) -> Self {
342        Self {
343            sampler_iter,
344            worker_pool,
345            pending_tasks: HashMap::new(),
346            result_buffer: HashMap::new(),
347            next_task_id: 0,
348            next_expected_id: 0,
349            max_pending,
350        }
351    }
352
353    /// Submit tasks to keep the pipeline full.
354    ///
355    /// The outstanding work (tasks still in flight, plus results already
356    /// completed but not yet emitted because an earlier task hasn't finished)
357    /// is capped at `max_pending`, so a slow worker applies backpressure
358    /// instead of letting `result_buffer` grow without bound.
359    fn submit_tasks(&mut self) {
360        while self.pending_tasks.len() + self.result_buffer.len() < self.max_pending {
361            if let Some(indices) = self.sampler_iter.next() {
362                let task_id = self.next_task_id;
363                self.next_task_id += 1;
364
365                if self
366                    .worker_pool
367                    .submit_task(task_id, indices.clone())
368                    .is_ok()
369                {
370                    self.pending_tasks.insert(task_id, indices);
371                } else {
372                    break;
373                }
374            } else {
375                break;
376            }
377        }
378    }
379
380    /// Get the number of pending tasks
381    pub fn pending_count(&self) -> usize {
382        self.pending_tasks.len()
383    }
384
385    /// Check if there are any pending tasks
386    pub fn has_pending_tasks(&self) -> bool {
387        !self.pending_tasks.is_empty()
388    }
389}
390
391impl<D, S, C> Iterator for MultiProcessIterator<'_, D, S, C>
392where
393    D: Dataset + Clone + Send + Sync + 'static,
394    S: BatchSampler,
395    S::Iter: Iterator<Item = Vec<usize>>,
396    C: Collate<D::Item> + Clone + Send + Sync + 'static,
397    D::Item: Send + 'static,
398    C::Output: Send + 'static,
399{
400    type Item = Result<C::Output>;
401
402    fn next(&mut self) -> Option<Self::Item> {
403        // Reorder buffer: workers can finish tasks out of order (thread
404        // scheduling), but callers need batches back in sampler/submission
405        // order for reproducibility, matching PyTorch's DataLoader. Drain
406        // worker results into `result_buffer` until the one this call must
407        // return (`next_expected_id`) is present, then emit it.
408        loop {
409            if let Some(result) = self.result_buffer.remove(&self.next_expected_id) {
410                self.next_expected_id += 1;
411                return Some(result);
412            }
413
414            // Submit new tasks to keep the pipeline full.
415            self.submit_tasks();
416
417            // Nothing in flight and nothing buffered: the sampler is exhausted.
418            if self.pending_tasks.is_empty() && self.result_buffer.is_empty() {
419                return None;
420            }
421
422            // Wait for the next completion, which may be out of order.
423            match self.worker_pool.get_result() {
424                Ok(WorkerResult { task_id, result }) => {
425                    self.pending_tasks.remove(&task_id);
426                    self.result_buffer.insert(task_id, result);
427                }
428                Err(e) => return Some(Err(e)),
429            }
430        }
431    }
432}
433
434/// Messages for persistent workers
435#[derive(Debug)]
436enum PersistentWorkerMessage {
437    Task(WorkerTask),
438    Shutdown,
439}
440
441/// Handle to a persistent worker
442struct PersistentWorkerHandle {
443    _thread: thread::JoinHandle<()>,
444}
445
446/// Persistent worker pool that keeps workers alive across epochs
447///
448/// Unlike the regular WorkerPool, this implementation keeps worker threads alive
449/// between epochs, reducing the overhead of thread creation and destruction.
450/// This is particularly useful for training scenarios with multiple epochs.
451///
452/// # Examples
453///
454/// ```rust,ignore
455/// use std::sync::Arc;
456/// use torsh_data::dataloader::workers::PersistentWorkerPool;
457/// use torsh_data::dataset::TensorDataset;
458/// use torsh_data::collate::DefaultCollate;
459///
460/// let dataset = Arc::new(TensorDataset::new(vec![1, 2, 3, 4, 5]));
461/// let collate_fn = Arc::new(DefaultCollate);
462/// let worker_pool = PersistentWorkerPool::new(dataset, collate_fn, 4);
463///
464/// // Use across multiple epochs
465/// for epoch in 0..10 {
466///     worker_pool.reset_for_epoch().unwrap();
467///     // Submit tasks for this epoch
468/// }
469///
470/// // Shutdown when done
471/// worker_pool.shutdown().unwrap();
472/// ```
473pub struct PersistentWorkerPool<D, C>
474where
475    D: Dataset + Clone + Send + Sync + 'static,
476    C: Collate<D::Item> + Clone + Send + Sync + 'static,
477    D::Item: Send + 'static,
478    C::Output: Send + 'static,
479{
480    #[allow(dead_code)]
481    dataset: Arc<D>,
482    #[allow(dead_code)]
483    collate_fn: Arc<C>,
484    num_workers: usize,
485    #[allow(dead_code)]
486    workers: Vec<PersistentWorkerHandle>,
487    task_sender: mpsc::Sender<PersistentWorkerMessage>,
488    result_receiver: mpsc::Receiver<WorkerResult<C::Output>>,
489    is_shutdown: Arc<std::sync::atomic::AtomicBool>,
490}
491
492impl<D, C> PersistentWorkerPool<D, C>
493where
494    D: Dataset + Clone + Send + Sync + 'static,
495    C: Collate<D::Item> + Clone + Send + Sync + 'static,
496    D::Item: Send + 'static,
497    C::Output: Send + 'static,
498{
499    /// Create a new persistent worker pool
500    ///
501    /// # Arguments
502    ///
503    /// * `dataset` - The dataset to process
504    /// * `collate_fn` - The collation function to apply to batches
505    /// * `num_workers` - Number of worker threads to spawn
506    ///
507    /// # Returns
508    ///
509    /// A new PersistentWorkerPool ready to process tasks
510    pub fn new(dataset: Arc<D>, collate_fn: Arc<C>, num_workers: usize) -> Self {
511        let (task_sender, task_receiver) = mpsc::channel::<PersistentWorkerMessage>();
512        let (result_sender, result_receiver) = mpsc::channel::<WorkerResult<C::Output>>();
513
514        let task_receiver = Arc::new(Mutex::new(task_receiver));
515        let is_shutdown = Arc::new(std::sync::atomic::AtomicBool::new(false));
516        let mut workers = Vec::with_capacity(num_workers);
517
518        // Spawn persistent worker threads
519        for worker_id in 0..num_workers {
520            let dataset_clone = Arc::clone(&dataset);
521            let collate_fn_clone = Arc::clone(&collate_fn);
522            let task_receiver_clone = Arc::clone(&task_receiver);
523            let result_sender_clone = result_sender.clone();
524            let is_shutdown_clone = Arc::clone(&is_shutdown);
525
526            let worker_thread = thread::spawn(move || {
527                Self::persistent_worker_loop(
528                    worker_id,
529                    dataset_clone,
530                    collate_fn_clone,
531                    task_receiver_clone,
532                    result_sender_clone,
533                    is_shutdown_clone,
534                );
535            });
536
537            workers.push(PersistentWorkerHandle {
538                _thread: worker_thread,
539            });
540        }
541
542        Self {
543            dataset,
544            collate_fn,
545            num_workers,
546            workers,
547            task_sender,
548            result_receiver,
549            is_shutdown,
550        }
551    }
552
553    /// Persistent worker thread loop that stays alive
554    ///
555    /// This loop includes timeout-based shutdown checking to ensure workers
556    /// can be cleanly terminated even if no tasks are pending.
557    #[allow(clippy::too_many_arguments)]
558    fn persistent_worker_loop(
559        _worker_id: usize,
560        dataset: Arc<D>,
561        collate_fn: Arc<C>,
562        task_receiver: Arc<Mutex<mpsc::Receiver<PersistentWorkerMessage>>>,
563        result_sender: mpsc::Sender<WorkerResult<C::Output>>,
564        is_shutdown: Arc<std::sync::atomic::AtomicBool>,
565    ) {
566        loop {
567            // Check for shutdown signal
568            if is_shutdown.load(std::sync::atomic::Ordering::Relaxed) {
569                break;
570            }
571
572            // Try to receive a message with timeout to allow periodic shutdown checks
573            let message = {
574                let receiver = match task_receiver.lock() {
575                    Ok(receiver) => receiver,
576                    Err(_) => {
577                        // Mutex is poisoned, worker should exit
578                        break;
579                    }
580                };
581                receiver.recv_timeout(std::time::Duration::from_millis(100))
582            };
583
584            match message {
585                Ok(PersistentWorkerMessage::Task(WorkerTask { task_id, indices })) => {
586                    // Process the batch
587                    let batch_result = Self::process_batch(&*dataset, &*collate_fn, indices);
588
589                    let result = WorkerResult {
590                        task_id,
591                        result: batch_result,
592                    };
593
594                    // Send result back
595                    if result_sender.send(result).is_err() {
596                        // Main thread is no longer listening, exit
597                        break;
598                    }
599                }
600                Ok(PersistentWorkerMessage::Shutdown) => {
601                    // Explicit shutdown request
602                    break;
603                }
604                Err(mpsc::RecvTimeoutError::Timeout) => {
605                    // Timeout occurred, continue the loop to check for shutdown
606                    continue;
607                }
608                Err(mpsc::RecvTimeoutError::Disconnected) => {
609                    // Main thread closed the channel, exit
610                    break;
611                }
612            }
613        }
614    }
615
616    /// Process a batch of indices (same as WorkerPool)
617    fn process_batch(dataset: &D, collate_fn: &C, indices: Vec<usize>) -> Result<C::Output> {
618        let mut samples = Vec::with_capacity(indices.len());
619
620        for idx in indices {
621            match dataset.get(idx) {
622                Ok(sample) => samples.push(sample),
623                Err(e) => return Err(e),
624            }
625        }
626
627        collate_fn.collate(samples)
628    }
629
630    /// Submit a task to the persistent worker pool
631    ///
632    /// # Arguments
633    ///
634    /// * `task_id` - Unique identifier for the task
635    /// * `indices` - Indices of samples to process
636    ///
637    /// # Returns
638    ///
639    /// Result indicating success or failure of task submission
640    pub fn submit_task(&self, task_id: usize, indices: Vec<usize>) -> Result<()> {
641        let message = PersistentWorkerMessage::Task(WorkerTask { task_id, indices });
642
643        self.task_sender.send(message).map_err(|_| {
644            torsh_core::error::TorshError::RuntimeError(
645                "Failed to send task to persistent worker pool".to_string(),
646            )
647        })?;
648
649        Ok(())
650    }
651
652    /// Get a result from the persistent worker pool
653    ///
654    /// This method blocks until a result is available from any worker.
655    ///
656    /// # Returns
657    ///
658    /// The next available worker result
659    pub fn get_result(&self) -> Result<WorkerResult<C::Output>> {
660        self.result_receiver.recv().map_err(|_| {
661            torsh_core::error::TorshError::RuntimeError(
662                "Failed to receive result from persistent worker pool".to_string(),
663            )
664        })
665    }
666
667    /// Get a result with timeout
668    ///
669    /// # Arguments
670    ///
671    /// * `timeout` - Maximum time to wait for a result
672    ///
673    /// # Returns
674    ///
675    /// The next available worker result or a timeout error
676    pub fn get_result_timeout(
677        &self,
678        timeout: std::time::Duration,
679    ) -> Result<WorkerResult<C::Output>> {
680        self.result_receiver
681            .recv_timeout(timeout)
682            .map_err(|e| match e {
683                mpsc::RecvTimeoutError::Timeout => torsh_core::error::TorshError::RuntimeError(
684                    "Timeout waiting for result from persistent worker pool".to_string(),
685                ),
686                mpsc::RecvTimeoutError::Disconnected => {
687                    torsh_core::error::TorshError::RuntimeError(
688                        "Persistent worker pool disconnected".to_string(),
689                    )
690                }
691            })
692    }
693
694    /// Try to get a result without blocking
695    ///
696    /// # Returns
697    ///
698    /// Some(result) if a result is available, None otherwise
699    pub fn try_get_result(&self) -> Option<WorkerResult<C::Output>> {
700        self.result_receiver.try_recv().ok()
701    }
702
703    /// Get the number of workers
704    ///
705    /// # Returns
706    ///
707    /// The number of worker threads in the pool
708    pub fn num_workers(&self) -> usize {
709        self.num_workers
710    }
711
712    /// Check if the pool is shutdown
713    ///
714    /// # Returns
715    ///
716    /// True if the pool has been shutdown, false otherwise
717    pub fn is_shutdown(&self) -> bool {
718        self.is_shutdown.load(std::sync::atomic::Ordering::Relaxed)
719    }
720
721    /// Shutdown the persistent worker pool
722    ///
723    /// This method gracefully shuts down all worker threads and should be called
724    /// when the pool is no longer needed.
725    ///
726    /// # Returns
727    ///
728    /// Result indicating success or failure of shutdown operation
729    pub fn shutdown(&self) -> Result<()> {
730        // Set shutdown flag
731        self.is_shutdown
732            .store(true, std::sync::atomic::Ordering::Relaxed);
733
734        // Send shutdown messages to all workers
735        for _ in 0..self.num_workers {
736            if self
737                .task_sender
738                .send(PersistentWorkerMessage::Shutdown)
739                .is_err()
740            {
741                // Channel is closed, workers are already shutdown
742                break;
743            }
744        }
745
746        Ok(())
747    }
748
749    /// Reset the pool for a new epoch (clears any pending tasks)
750    ///
751    /// This method can be called between epochs to reset the pool state.
752    /// In the current implementation, this is a placeholder for future
753    /// epoch-specific optimizations.
754    ///
755    /// # Returns
756    ///
757    /// Result indicating success or failure of reset operation
758    pub fn reset_for_epoch(&self) -> Result<()> {
759        // For a full implementation, you might want to:
760        // 1. Clear any pending tasks
761        // 2. Reset worker state
762        // 3. Optionally restart workers if needed
763
764        // For now, this is a placeholder
765        Ok(())
766    }
767}
768
769impl<D, C> Drop for PersistentWorkerPool<D, C>
770where
771    D: Dataset + Clone + Send + Sync + 'static,
772    C: Collate<D::Item> + Clone + Send + Sync + 'static,
773    D::Item: Send + 'static,
774    C::Output: Send + 'static,
775{
776    fn drop(&mut self) {
777        // Ensure workers are shutdown when pool is dropped
778        let _ = self.shutdown();
779    }
780}
781
782/// Configuration for worker pools
783#[derive(Debug, Clone)]
784pub struct WorkerConfig {
785    /// Number of worker threads
786    pub num_workers: usize,
787    /// Maximum number of pending tasks for multi-process iterator
788    pub max_pending_tasks: Option<usize>,
789    /// Whether to use persistent workers
790    pub persistent: bool,
791}
792
793impl Default for WorkerConfig {
794    fn default() -> Self {
795        Self {
796            num_workers: std::thread::available_parallelism()
797                .map(|n| n.get())
798                .unwrap_or(1),
799            max_pending_tasks: None,
800            persistent: false,
801        }
802    }
803}
804
805impl WorkerConfig {
806    /// Create a new worker configuration
807    pub fn new() -> Self {
808        Self::default()
809    }
810
811    /// Set the number of workers
812    pub fn num_workers(mut self, num_workers: usize) -> Self {
813        self.num_workers = num_workers;
814        self
815    }
816
817    /// Set the maximum number of pending tasks
818    pub fn max_pending_tasks(mut self, max_pending: usize) -> Self {
819        self.max_pending_tasks = Some(max_pending);
820        self
821    }
822
823    /// Enable persistent workers
824    pub fn persistent(mut self, persistent: bool) -> Self {
825        self.persistent = persistent;
826        self
827    }
828}
829
830/// Utility functions for worker management
831pub mod utils {
832    use super::*;
833
834    /// Determine optimal number of workers based on system capabilities
835    ///
836    /// # Arguments
837    ///
838    /// * `cpu_intensive` - Whether the workload is CPU-intensive
839    ///
840    /// # Returns
841    ///
842    /// Recommended number of worker threads
843    pub fn optimal_worker_count(cpu_intensive: bool) -> usize {
844        let cpu_count = std::thread::available_parallelism()
845            .map(|n| n.get())
846            .unwrap_or(1);
847
848        if cpu_intensive {
849            // For CPU-intensive tasks, use fewer workers to avoid over-subscription
850            (cpu_count * 3 / 4).max(1)
851        } else {
852            // For I/O-bound tasks, can use more workers
853            cpu_count * 2
854        }
855    }
856
857    /// Create a worker configuration optimized for training
858    ///
859    /// # Returns
860    ///
861    /// A WorkerConfig optimized for training workloads
862    pub fn training_config() -> WorkerConfig {
863        WorkerConfig::new()
864            .num_workers(optimal_worker_count(false))
865            .persistent(true)
866            .max_pending_tasks(optimal_worker_count(false) * 3)
867    }
868
869    /// Create a worker configuration optimized for inference
870    ///
871    /// # Returns
872    ///
873    /// A WorkerConfig optimized for inference workloads
874    pub fn inference_config() -> WorkerConfig {
875        WorkerConfig::new()
876            .num_workers(optimal_worker_count(true))
877            .persistent(false)
878            .max_pending_tasks(optimal_worker_count(true) * 2)
879    }
880}
881
882#[cfg(test)]
883mod tests {
884    use super::*;
885    use crate::{collate::DefaultCollate, dataset::TensorDataset};
886
887    #[test]
888    fn test_worker_pool_creation() {
889        use torsh_core::device::DeviceType;
890        use torsh_tensor::Tensor;
891
892        let tensor = Tensor::from_data(vec![1.0f32, 2.0, 3.0, 4.0, 5.0], vec![5], DeviceType::Cpu)
893            .expect("Tensor should succeed");
894        let dataset = Arc::new(TensorDataset::from_tensor(tensor));
895        let collate_fn = Arc::new(DefaultCollate);
896        let worker_pool = WorkerPool::new(dataset, collate_fn, 2);
897
898        assert_eq!(worker_pool.num_workers(), 2);
899    }
900
901    #[test]
902    fn test_worker_pool_task_submission() {
903        use torsh_core::device::DeviceType;
904        use torsh_tensor::Tensor;
905
906        let tensor = Tensor::from_data(vec![1.0f32, 2.0, 3.0, 4.0, 5.0], vec![5], DeviceType::Cpu)
907            .expect("Tensor should succeed");
908        let dataset = Arc::new(TensorDataset::from_tensor(tensor));
909        let collate_fn = Arc::new(DefaultCollate);
910        let worker_pool = WorkerPool::new(dataset, collate_fn, 2);
911
912        assert!(worker_pool.submit_task(0, vec![0, 1]).is_ok());
913    }
914
915    #[test]
916    fn test_persistent_worker_pool_creation() {
917        use torsh_core::device::DeviceType;
918        use torsh_tensor::Tensor;
919
920        let tensor = Tensor::from_data(vec![1.0f32, 2.0, 3.0, 4.0, 5.0], vec![5], DeviceType::Cpu)
921            .expect("Tensor should succeed");
922        let dataset = Arc::new(TensorDataset::from_tensor(tensor));
923        let collate_fn = Arc::new(DefaultCollate);
924        let worker_pool = PersistentWorkerPool::new(dataset, collate_fn, 2);
925
926        assert_eq!(worker_pool.num_workers(), 2);
927        assert!(!worker_pool.is_shutdown());
928    }
929
930    #[test]
931    fn test_persistent_worker_pool_shutdown() {
932        use torsh_core::device::DeviceType;
933        use torsh_tensor::Tensor;
934
935        let tensor = Tensor::from_data(vec![1.0f32, 2.0, 3.0, 4.0, 5.0], vec![5], DeviceType::Cpu)
936            .expect("Tensor should succeed");
937        let dataset = Arc::new(TensorDataset::from_tensor(tensor));
938        let collate_fn = Arc::new(DefaultCollate);
939        let worker_pool = PersistentWorkerPool::new(dataset, collate_fn, 2);
940
941        assert!(worker_pool.shutdown().is_ok());
942        assert!(worker_pool.is_shutdown());
943    }
944
945    #[test]
946    fn test_worker_config() {
947        let config = WorkerConfig::new()
948            .num_workers(4)
949            .max_pending_tasks(8)
950            .persistent(true);
951
952        assert_eq!(config.num_workers, 4);
953        assert_eq!(config.max_pending_tasks, Some(8));
954        assert!(config.persistent);
955    }
956
957    #[test]
958    fn test_optimal_worker_count() {
959        let cpu_intensive_count = utils::optimal_worker_count(true);
960        let io_bound_count = utils::optimal_worker_count(false);
961
962        assert!(cpu_intensive_count > 0);
963        assert!(io_bound_count > 0);
964        assert!(io_bound_count >= cpu_intensive_count);
965    }
966
967    #[test]
968    fn test_training_config() {
969        let config = utils::training_config();
970
971        assert!(config.num_workers > 0);
972        assert!(config.persistent);
973        assert!(config.max_pending_tasks.is_some());
974    }
975
976    #[test]
977    fn test_inference_config() {
978        let config = utils::inference_config();
979
980        assert!(config.num_workers > 0);
981        assert!(!config.persistent);
982        assert!(config.max_pending_tasks.is_some());
983    }
984}