rusting_brain 5.0.0

A Rust deep-learning library for training and running transformer language models, dense and mixture-of-experts, on CPU or CUDA.
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
//! Backend-agnostic accelerator training.
//!
//! `cuda_training` and `metal_training` are two implementations of the same
//! contract: a persistent session that owns device buffers, trains one epoch at
//! a time, and can hand back a host checkpoint. This module is the part of that
//! contract that does not depend on either API, so it compiles on every
//! platform and in every feature combination. Applications should drive
//! training through [`TrainingSession`] and read [`AcceleratorDoctorReport`]
//! rather than reaching for a vendor module directly.

use crate::{CudaTrainingCheckpoint, Dataset, Network, NetworkError, TrainConfig, TrainingBackend};
use std::time::Duration;

pub(crate) const MIB: usize = 1024 * 1024;

/// Measurements for the lifetime of a persistent accelerator training session.
#[derive(Clone, Debug, Default)]
pub struct AcceleratorStats {
    /// Bytes owned by device allocations at the high-water mark (driver overhead excluded).
    pub peak_allocated_bytes: usize,
    pub setup_time: Duration,
    pub training_time: Duration,
    pub checkpoint_time: Duration,
    pub epochs: usize,
    pub batches: usize,
    pub host_to_device_bytes: usize,
    pub device_to_host_bytes: usize,
    pub dataset_resident: bool,
}

/// What a device offers, gathered before a campaign commits to it.
#[derive(Clone, Debug)]
pub struct AcceleratorDoctorReport {
    /// `"cuda"` or `"metal"`.
    pub backend: &'static str,
    pub device: usize,
    pub name: String,
    /// CUDA compute capability, or the Metal GPU family.
    pub revision: String,
    pub total_memory_mib: usize,
    pub free_memory_mib: Option<usize>,
    pub requested_budget_mib: usize,
    pub allocation_test: bool,
    /// cuBLAS on CUDA; the bundled tiled GEMM kernels on Metal.
    pub gemm_available: bool,
    pub kernel_available: bool,
}

/// Probes the device behind `backend`, or `Ok(None)` for [`TrainingBackend::Cpu`].
///
/// Fails rather than degrading: a backend that was not compiled in reports the
/// missing feature instead of quietly answering for the CPU.
pub fn accelerator_doctor(
    backend: TrainingBackend,
) -> Result<Option<AcceleratorDoctorReport>, NetworkError> {
    match backend {
        TrainingBackend::Cpu => Ok(None),
        TrainingBackend::Cuda {
            device,
            memory_budget_mib,
        } => {
            #[cfg(feature = "cuda")]
            {
                let r = crate::cuda_training::cuda_doctor(device, memory_budget_mib)?;
                Ok(Some(AcceleratorDoctorReport {
                    backend: "cuda",
                    device: r.device,
                    name: r.name,
                    revision: r.compute_capability,
                    total_memory_mib: r.total_memory_mib,
                    free_memory_mib: r.free_memory_mib,
                    requested_budget_mib: r.requested_budget_mib,
                    allocation_test: r.allocation_test,
                    gemm_available: r.cublas_available,
                    kernel_available: r.kernel_available,
                }))
            }
            #[cfg(not(feature = "cuda"))]
            {
                let _ = (device, memory_budget_mib);
                Err(NetworkError::CudaFeatureDisabled)
            }
        }
        TrainingBackend::Metal {
            device,
            memory_budget_mib,
        } => {
            #[cfg(all(feature = "metal", target_os = "macos"))]
            {
                Ok(Some(crate::metal_training::metal_doctor(
                    device,
                    memory_budget_mib,
                )?))
            }
            #[cfg(not(all(feature = "metal", target_os = "macos")))]
            {
                let _ = (device, memory_budget_mib);
                Err(NetworkError::MetalFeatureDisabled)
            }
        }
    }
}

/// Conservative tensor allocation estimate (MiB, rounded up). This is public so
/// applications can reject an unsuitable configuration before touching a device.
pub fn estimate_tensor_memory_mib(
    network: &Network,
    batch_size: usize,
) -> Result<usize, NetworkError> {
    let overflow = || NetworkError::Accelerator("tensor size overflow".into());
    if batch_size == 0 {
        return Err(NetworkError::Accelerator(
            "batch size must be non-zero".into(),
        ));
    }
    let mut floats = batch_size
        .checked_mul(network.input_size())
        .ok_or_else(overflow)?;
    for l in network.layers() {
        let p = l.weights.data.len() + l.biases.data.len();
        // parameter, gradient, and both Adam moments (also allocated for SGD,
        // so the estimate is a stable upper bound for either optimizer)
        floats = floats
            .checked_add(p.checked_mul(4).ok_or_else(overflow)?)
            .ok_or_else(overflow)?;
        let a = batch_size
            .checked_mul(l.weights.rows)
            .ok_or_else(overflow)?;
        // activation and delta
        floats = floats
            .checked_add(a.checked_mul(2).ok_or_else(overflow)?)
            .ok_or_else(overflow)?;
    }
    // the epoch loss accumulator
    floats = floats.checked_add(1).ok_or_else(overflow)?;
    Ok(floats.checked_mul(4).ok_or_else(overflow)?.div_ceil(MIB))
}

/// A persistent device session, whichever backend is behind it.
///
/// Epoch-at-a-time training exists because a campaign checkpoints and
/// early-stops after every epoch. Calling `fit_with_backend` once per epoch
/// would rebuild the device context, the compiled kernels, and every buffer
/// each time; a session keeps all of that, and the training set, resident.
pub enum TrainingSession {
    #[cfg(feature = "cuda")]
    Cuda(crate::cuda_training::CudaTrainingSession),
    #[cfg(all(feature = "metal", target_os = "macos"))]
    Metal(crate::metal_training::MetalTrainingSession),
}

impl TrainingSession {
    /// Opens a session for `backend`, or `Ok(None)` when the request is
    /// [`TrainingBackend::Cpu`] and the caller should use [`Network::fit`].
    pub fn new(
        network: &Network,
        dataset: &Dataset,
        config: TrainConfig,
        backend: TrainingBackend,
    ) -> Result<Option<Self>, NetworkError> {
        match backend {
            TrainingBackend::Cpu => Ok(None),
            TrainingBackend::Cuda {
                device,
                memory_budget_mib,
            } => {
                #[cfg(feature = "cuda")]
                {
                    Ok(Some(Self::Cuda(
                        crate::cuda_training::CudaTrainingSession::new(
                            network,
                            dataset,
                            config,
                            device,
                            memory_budget_mib,
                        )?,
                    )))
                }
                #[cfg(not(feature = "cuda"))]
                {
                    let _ = (network, dataset, config, device, memory_budget_mib);
                    Err(NetworkError::CudaFeatureDisabled)
                }
            }
            TrainingBackend::Metal {
                device,
                memory_budget_mib,
            } => {
                #[cfg(all(feature = "metal", target_os = "macos"))]
                {
                    Ok(Some(Self::Metal(
                        crate::metal_training::MetalTrainingSession::new(
                            network,
                            dataset,
                            config,
                            device,
                            memory_budget_mib,
                        )?,
                    )))
                }
                #[cfg(not(all(feature = "metal", target_os = "macos")))]
                {
                    let _ = (network, dataset, config, device, memory_budget_mib);
                    Err(NetworkError::MetalFeatureDisabled)
                }
            }
        }
    }

    /// Resumes a session from a host checkpoint, replaying the shuffle so the
    /// resumed run sees the same batches it would have seen without the crash.
    pub fn from_checkpoint(
        checkpoint: CudaTrainingCheckpoint,
        dataset: &Dataset,
        config: TrainConfig,
        backend: TrainingBackend,
    ) -> Result<Option<Self>, NetworkError> {
        match backend {
            TrainingBackend::Cpu => Ok(None),
            TrainingBackend::Cuda {
                device,
                memory_budget_mib,
            } => {
                #[cfg(feature = "cuda")]
                {
                    Ok(Some(Self::Cuda(
                        crate::cuda_training::CudaTrainingSession::from_checkpoint(
                            checkpoint,
                            dataset,
                            config,
                            device,
                            memory_budget_mib,
                        )?,
                    )))
                }
                #[cfg(not(feature = "cuda"))]
                {
                    let _ = (checkpoint, dataset, config, device, memory_budget_mib);
                    Err(NetworkError::CudaFeatureDisabled)
                }
            }
            TrainingBackend::Metal {
                device,
                memory_budget_mib,
            } => {
                #[cfg(all(feature = "metal", target_os = "macos"))]
                {
                    Ok(Some(Self::Metal(
                        crate::metal_training::MetalTrainingSession::from_checkpoint(
                            checkpoint,
                            dataset,
                            config,
                            device,
                            memory_budget_mib,
                        )?,
                    )))
                }
                #[cfg(not(all(feature = "metal", target_os = "macos")))]
                {
                    let _ = (checkpoint, dataset, config, device, memory_budget_mib);
                    Err(NetworkError::MetalFeatureDisabled)
                }
            }
        }
    }

    pub fn train_epoch(&mut self) -> Result<f32, NetworkError> {
        match self {
            #[cfg(feature = "cuda")]
            Self::Cuda(session) => session.train_epoch(),
            #[cfg(all(feature = "metal", target_os = "macos"))]
            Self::Metal(session) => session.train_epoch(),
            #[allow(unreachable_patterns)]
            _ => Err(NetworkError::Accelerator(
                "no accelerator backend is compiled in".into(),
            )),
        }
    }

    pub fn checkpoint(&mut self) -> Result<CudaTrainingCheckpoint, NetworkError> {
        match self {
            #[cfg(feature = "cuda")]
            Self::Cuda(session) => session.checkpoint(),
            #[cfg(all(feature = "metal", target_os = "macos"))]
            Self::Metal(session) => session.checkpoint(),
            #[allow(unreachable_patterns)]
            _ => Err(NetworkError::Accelerator(
                "no accelerator backend is compiled in".into(),
            )),
        }
    }

    /// Copies device state back into `network`, so host-side validation and
    /// campaign checkpoints see the weights this epoch produced.
    pub fn synchronize_network(&mut self, network: &mut Network) -> Result<(), NetworkError> {
        network.restore_cuda_checkpoint(self.checkpoint()?)
    }

    pub fn stats(&self) -> &AcceleratorStats {
        match self {
            #[cfg(feature = "cuda")]
            Self::Cuda(session) => session.stats(),
            #[cfg(all(feature = "metal", target_os = "macos"))]
            Self::Metal(session) => session.stats(),
            #[allow(unreachable_patterns)]
            _ => unreachable!("TrainingSession has no variant without a backend feature"),
        }
    }

    pub fn epoch(&self) -> usize {
        match self {
            #[cfg(feature = "cuda")]
            Self::Cuda(session) => session.epoch(),
            #[cfg(all(feature = "metal", target_os = "macos"))]
            Self::Metal(session) => session.epoch(),
            #[allow(unreachable_patterns)]
            _ => 0,
        }
    }

    /// True only for backends with a device-side validation path (CUDA
    /// today). Callers should keep using the host `evaluate_loss`
    /// round-trip on any backend this returns `false` for, Metal included:
    /// it has no `prepare_validation`/`validate_epoch` implementation.
    pub fn supports_device_validation(&self) -> bool {
        match self {
            #[cfg(feature = "cuda")]
            Self::Cuda(_) => true,
            #[allow(unreachable_patterns)]
            _ => false,
        }
    }

    /// Uploads `dataset` once so `validate_epoch` can score it on-device.
    /// Only call when `supports_device_validation()` is true. Returns
    /// `Ok(false)` (not an error) when it would not fit the device budget
    /// alongside what training already uses; the caller should fall back to
    /// host-side validation for the whole session in that case.
    #[cfg_attr(not(feature = "cuda"), allow(unused_variables))]
    pub fn prepare_validation(
        &mut self,
        dataset: &Dataset,
        budget_mib: usize,
    ) -> Result<bool, NetworkError> {
        match self {
            #[cfg(feature = "cuda")]
            Self::Cuda(session) => session.prepare_validation(dataset, budget_mib),
            #[allow(unreachable_patterns)]
            _ => Err(NetworkError::Accelerator(
                "device-side validation is not implemented for this backend".into(),
            )),
        }
    }

    /// Device-side validation loss over the set uploaded by
    /// `prepare_validation`, using the weights currently resident on the
    /// device. No host copy of the model is needed to compute it.
    pub fn validate_epoch(&mut self) -> Result<f32, NetworkError> {
        match self {
            #[cfg(feature = "cuda")]
            Self::Cuda(session) => session.validate_epoch(),
            #[allow(unreachable_patterns)]
            _ => Err(NetworkError::Accelerator(
                "device-side validation is not implemented for this backend".into(),
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Activation, Optimizer};

    fn tiny() -> Network {
        Network::builder()
            .input_size(2)
            .dense(3, Activation::Relu)
            .dense(1, Activation::Linear)
            .optimizer(Optimizer::sgd(0.1))
            .build()
    }

    #[test]
    fn cpu_backend_has_no_session_and_no_doctor_report() {
        let network = tiny();
        let data = Dataset::new(vec![vec![0.0, 0.0]], vec![vec![0.0]]);
        let config = TrainConfig {
            epochs: 1,
            batch_size: 1,
            shuffle: false,
            seed: Some(1),
        };
        assert!(
            TrainingSession::new(&network, &data, config, TrainingBackend::Cpu)
                .unwrap()
                .is_none()
        );
        assert!(accelerator_doctor(TrainingBackend::Cpu).unwrap().is_none());
    }

    #[test]
    fn memory_estimate_is_nonzero_and_rejects_a_zero_batch() {
        assert!(estimate_tensor_memory_mib(&tiny(), 4).unwrap() >= 1);
        assert!(estimate_tensor_memory_mib(&tiny(), 0).is_err());
    }

    #[test]
    fn metal_is_rejected_when_it_is_not_compiled_in() {
        let backend = TrainingBackend::Metal {
            device: 0,
            memory_budget_mib: 1024,
        };
        assert_eq!(backend.name(), "metal");
        assert!(backend.is_accelerated());
        #[cfg(not(all(feature = "metal", target_os = "macos")))]
        assert!(matches!(
            accelerator_doctor(backend),
            Err(NetworkError::MetalFeatureDisabled)
        ));
    }
}