Skip to main content

ruda_model/module/
base.rs

1use super::{Param, ParamId, Quantizer};
2use crate::{
3    record::Record,
4    tensor::backend::{AutodiffBackend, Backend},
5};
6use alloc::{string::String, vec::Vec};
7pub use ruda_model_macros::Module;
8use ruda_tensor::api::{Bool, Int, Tensor, ops::Device};
9
10/// Type alias to `Vec<B::Device>` which supports `no_std` environments, but automatically using
11/// the `alloc` crate.
12pub type Devices<B> = Vec<Device<B>>;
13
14// At the moment, our plan is to continue experimenting with the macro internally and monitor its development.
15// We may consider making it public in the future.
16macro_rules! module {
17    (map=$module:ident, ops=$item:expr) => {{
18        struct Mapper;
19        impl<B: Backend> ModuleMapper<B> for Mapper {
20            fn map_float<const D: usize>(
21                &mut self,
22                param: Param<Tensor<B, D>>,
23            ) -> Param<Tensor<B, D>> {
24                let func = $item;
25                func(param)
26            }
27
28            fn map_int<const D: usize>(
29                &mut self,
30                param: Param<Tensor<B, D, Int>>,
31            ) -> Param<Tensor<B, D, Int>> {
32                param
33            }
34
35            fn map_bool<const D: usize>(
36                &mut self,
37                param: Param<Tensor<B, D, Bool>>,
38            ) -> Param<Tensor<B, D, Bool>> {
39                param
40            }
41        }
42        let mut mapper = Mapper;
43        $module.map(&mut mapper)
44    }};
45    (visit_float=$module:ident, ops=$item:expr, state=$state_ty:ty, init=$init:expr) => {{
46        struct Visitor<'a, B: Backend> {
47            state: &'a mut $state_ty,
48            backend: core::marker::PhantomData<B>,
49        }
50        impl<'a, B: Backend> ModuleVisitor<B> for Visitor<'a, B> {
51            fn visit_float<const D: usize>(&mut self, param: &Param<Tensor<B, D>>) {
52                let func = $item;
53                func(&param.val(), &mut self.state)
54            }
55        }
56        #[allow(clippy::redundant_closure_call)]
57        let mut state = $init();
58        let mut visitor = Visitor {
59            state: &mut state,
60            backend: core::marker::PhantomData,
61        };
62        $module.visit(&mut visitor);
63        state
64    }};
65}
66
67/// Trait for all neural network modules.
68///
69/// Modules should be created using the [derive](ruda_model_macros::Module) attribute.
70/// This will make your module trainable, savable and loadable via
71/// `state` and `load`.
72///
73/// # Example
74///
75/// A module should have a [backend](crate::tensor::backend::Backend) defined as a generic
76/// parameter B. This will be used by the [derive](ruda_model_macros::Module) attribute to generate the code
77/// necessary to optimize and train the module on any backend.
78///
79/// ```rust, ignore
80/// use ruda_model::module::Module;
81/// use ruda_nn::Linear;
82/// use ruda_tensor::api::{Tensor, backend::Backend};
83///
84/// #[derive(Module, Debug)]
85/// struct MyModule<B: Backend> {
86///   my_param: Linear<B>,
87///   my_other_field: usize,
88/// }
89/// ```
90pub trait Module<B: Backend>: Clone + Send + core::fmt::Debug {
91    /// Type to save and load the module.
92    type Record: Record<B>;
93
94    /// Return all the devices found in the underneath module tree added to the given vector
95    /// without duplicates.
96    fn collect_devices(&self, devices: Devices<B>) -> Devices<B>;
97
98    /// Return all the devices found in the underneath module tree without duplicates.
99    fn devices(&self) -> Devices<B> {
100        self.collect_devices(Devices::<B>::new())
101    }
102
103    /// Fork the module and all of its sub-modules to the given device.
104    ///
105    /// # Notes
106    ///
107    /// This is similar to [to_device](Module::to_device), but it ensures the output module on the
108    /// new device will have its own autodiff graph.
109    fn fork(self, device: &B::Device) -> Self;
110
111    /// Move the module and all of its sub-modules to the given device.
112    ///
113    /// # Warnings
114    ///
115    /// The operation supports autodiff and it will be registered when activated. However, this may
116    /// not be what you want. The output model will be an intermediary model, meaning that you
117    /// can't optimize it with gradient descent. If you want to optimize the output network on the
118    /// target device, use [fork](Module::fork) instead.
119    fn to_device(self, device: &B::Device) -> Self;
120
121    /// Each tensor in the module tree will not require grad.
122    ///
123    /// # Warnings
124    ///
125    /// This should not be used for inference, use [valid](AutodiffModule::valid) when using
126    /// AD modules. This is mostly useful when performing partial finetuning, which is updating only
127    /// a small fraction of the parameters instead of finetuning all of them.
128    fn no_grad(self) -> Self {
129        module!(
130            map = self,
131            ops = |param: Param<Tensor<B, D>>| param.set_require_grad(false)
132        )
133    }
134
135    /// Move the module and all of its sub-modules to the autodiff backend.
136    ///
137    /// # Notes
138    ///
139    /// * Only plain modules (not already on an autodiff backend) can be moved.
140    /// * Calling `train()` on a module that is already on an autodiff backend
141    ///   will result in a type error, because the module's inner backend does not match.
142    fn train<AB>(self) -> <Self as HasAutodiffModule<AB>>::TrainModule
143    where
144        AB: AutodiffBackend<InnerBackend = B>,
145        Self: HasAutodiffModule<AB>,
146    {
147        <Self as HasAutodiffModule<AB>>::TrainModule::from_inner(self)
148    }
149
150    /// Get the number of parameters the module has, including all of its sub-modules.
151    fn num_params(&self) -> usize {
152        module!(
153            visit_float = self,
154            ops = |tensor: &Tensor<B, D>, state: &mut usize| {
155                *state += tensor.shape().num_elements();
156            },
157            state = usize,
158            init = || 0
159        )
160    }
161    /// Visit each tensor parameter in the module with a [visitor](ModuleVisitor).
162    fn visit<Visitor: ModuleVisitor<B>>(&self, visitor: &mut Visitor);
163
164    /// Map each tensor parameter in the module with a [mapper](ModuleMapper).
165    fn map<Mapper: ModuleMapper<B>>(self, mapper: &mut Mapper) -> Self;
166
167    /// Load the module state from a record.
168    fn load_record(self, record: Self::Record) -> Self;
169
170    /// Convert the module into a record containing the state.
171    fn into_record(self) -> Self::Record;
172
173    #[cfg(feature = "std")]
174    /// Save the module to a file using the provided [file recorder](crate::record::FileRecorder).
175    ///
176    /// List of supported file recorders:
177    ///
178    /// * [default](crate::record::DefaultFileRecorder)
179    /// * [bincode](crate::record::BinFileRecorder)
180    /// * [bincode compressed with gzip](crate::record::BinGzFileRecorder)
181    /// * [json pretty](crate::record::PrettyJsonFileRecorder)
182    /// * [json compressed with gzip](crate::record::JsonGzFileRecorder)
183    /// * [named mpk](crate::record::NamedMpkFileRecorder)
184    /// * [named mpk compressed with gzip](crate::record::NamedMpkGzFileRecorder)
185    ///
186    /// ## Notes
187    ///
188    /// The file extension is automatically added depending on the file recorder provided, you
189    /// don't have to specify it.
190    fn save_file<FR, PB>(
191        self,
192        file_path: PB,
193        recorder: &FR,
194    ) -> Result<(), crate::record::RecorderError>
195    where
196        FR: crate::record::FileRecorder<B>,
197        PB: Into<std::path::PathBuf>,
198    {
199        let record = Self::into_record(self);
200        recorder.record(record, file_path.into())
201    }
202
203    #[cfg(feature = "std")]
204    /// Load the module from a file using the provided [file recorder](crate::record::FileRecorder).
205    ///
206    /// The recorder should be the same as the one used to save the module, see
207    /// [save_file](Self::save_file).
208    ///
209    /// ## Notes
210    ///
211    /// The file extension is automatically added depending on the file recorder provided, you
212    /// don't have to specify it.
213    fn load_file<FR, PB>(
214        self,
215        file_path: PB,
216        recorder: &FR,
217        device: &B::Device,
218    ) -> Result<Self, crate::record::RecorderError>
219    where
220        FR: crate::record::FileRecorder<B>,
221        PB: Into<std::path::PathBuf>,
222    {
223        let record = recorder.load(file_path.into(), device)?;
224
225        Ok(self.load_record(record))
226    }
227
228    /// Quantize the weights of the module.
229    fn quantize_weights(self, quantizer: &mut Quantizer) -> Self {
230        self.map(quantizer)
231    }
232}
233
234/// Module visitor trait for traversing and inspecting module parameters.
235pub trait ModuleVisitor<B: Backend> {
236    /// Visit a float parameter in the module.
237    ///
238    /// # Parameters
239    /// - `param`: The float parameter to visit
240    #[allow(unused_variables)]
241    fn visit_float<const D: usize>(&mut self, param: &Param<Tensor<B, D>>) {}
242
243    /// Visit an int parameter in the module.
244    ///
245    /// # Parameters
246    /// - `param`: The integer parameter to visit
247    #[allow(unused_variables)]
248    fn visit_int<const D: usize>(&mut self, param: &Param<Tensor<B, D, Int>>) {}
249
250    /// Visit a bool parameter in the module.
251    ///
252    /// # Parameters
253    /// - `param`: The boolean parameter to visit
254    #[allow(unused_variables)]
255    fn visit_bool<const D: usize>(&mut self, param: &Param<Tensor<B, D, Bool>>) {}
256
257    /// Called when entering a submodule.
258    ///
259    /// # Parameters
260    /// - `name`: The name of the submodule being entered
261    /// - `container_type`: The type of the container with format:
262    ///   - For user-defined structs: "Struct:TypeName" (e.g., "Struct:Linear")
263    ///   - For user-defined enums: "Enum:TypeName" (e.g., "Enum:MyEnum")
264    ///   - For Vec containers: "Vec" (name is the index)
265    ///   - For Tuple containers: "Tuple" (name is the index)
266    ///   - For Array containers: "Array" (name is the index)
267    ///
268    /// Note: Option containers do not call enter_module/exit_module to preserve
269    /// the field name in the path (e.g., "bias" instead of "bias.Some")
270    #[allow(unused_variables)]
271    fn enter_module(&mut self, name: &str, container_type: &str) {}
272
273    /// Called when exiting a submodule.
274    ///
275    /// # Parameters
276    /// - `name`: The name of the submodule being exited
277    /// - `container_type`: The type of the container with format:
278    ///   - For user-defined structs: "Struct:TypeName" (e.g., "Struct:Linear")
279    ///   - For user-defined enums: "Enum:TypeName" (e.g., "Enum:MyEnum")
280    ///   - For Vec containers: "Vec" (name is the index)
281    ///   - For Tuple containers: "Tuple" (name is the index)
282    ///   - For Array containers: "Array" (name is the index)
283    ///
284    /// Note: Option containers do not call enter_module/exit_module to preserve
285    /// the field name in the path (e.g., "bias" instead of "bias.Some")
286    #[allow(unused_variables)]
287    fn exit_module(&mut self, name: &str, container_type: &str) {}
288
289    /// Visit a float tensor with its full module path.
290    ///
291    /// # Parameters
292    /// - `path`: The path components to the tensor as a slice (e.g., &["encoder", "layer1", "weight"]).
293    ///   Each element represents a module name in the hierarchy, with the final element
294    ///   being the parameter name. This allows efficient reuse of the path stack.
295    /// - `id`: The unique identifier of the parameter
296    /// - `tensor`: The float tensor to visit
297    #[allow(unused_variables)]
298    fn visit_float_with_path<const D: usize>(
299        &mut self,
300        path: &[String],
301        id: ParamId,
302        tensor: &Tensor<B, D>,
303    ) {
304    }
305
306    /// Visit an int tensor with its full module path.
307    ///
308    /// # Parameters
309    /// - `path`: The path components to the tensor as a slice (e.g., &["encoder", "layer1", "weight"]).
310    ///   Each element represents a module name in the hierarchy, with the final element
311    ///   being the parameter name. This allows efficient reuse of the path stack.
312    /// - `id`: The unique identifier of the parameter
313    /// - `tensor`: The integer tensor to visit
314    #[allow(unused_variables)]
315    fn visit_int_with_path<const D: usize>(
316        &mut self,
317        path: &[String],
318        id: ParamId,
319        tensor: &Tensor<B, D, Int>,
320    ) {
321    }
322
323    /// Visit a bool tensor with its full module path.
324    ///
325    /// # Parameters
326    /// - `path`: The path components to the tensor as a slice (e.g., &["encoder", "layer1", "weight"]).
327    ///   Each element represents a module name in the hierarchy, with the final element
328    ///   being the parameter name. This allows efficient reuse of the path stack.
329    /// - `id`: The unique identifier of the parameter
330    /// - `tensor`: The boolean tensor to visit
331    #[allow(unused_variables)]
332    fn visit_bool_with_path<const D: usize>(
333        &mut self,
334        path: &[String],
335        id: ParamId,
336        tensor: &Tensor<B, D, Bool>,
337    ) {
338    }
339}
340
341/// Module mapper trait for transforming module parameters.
342pub trait ModuleMapper<B: Backend> {
343    /// Called when entering a submodule.
344    ///
345    /// # Parameters
346    /// - `name`: The name of the submodule being entered
347    /// - `container_type`: The type of the container with format:
348    ///   - For user-defined structs: "Struct:TypeName" (e.g., "Struct:Linear")
349    ///   - For user-defined enums: "Enum:TypeName" (e.g., "Enum:MyEnum")
350    ///   - For Vec containers: "Vec" (name is the index)
351    ///   - For Tuple containers: "Tuple" (name is the index)
352    ///   - For Array containers: "Array" (name is the index)
353    ///
354    /// Note: Option containers do not call enter_module/exit_module to preserve
355    /// the field name in the path (e.g., "bias" instead of "bias.Some")
356    #[allow(unused_variables)]
357    fn enter_module(&mut self, name: &str, container_type: &str) {}
358
359    /// Called when exiting a submodule.
360    ///
361    /// # Parameters
362    /// - `name`: The name of the submodule being exited
363    /// - `container_type`: The type of the container with format:
364    ///   - For user-defined structs: "Struct:TypeName" (e.g., "Struct:Linear")
365    ///   - For user-defined enums: "Enum:TypeName" (e.g., "Enum:MyEnum")
366    ///   - For Vec containers: "Vec" (name is the index)
367    ///   - For Tuple containers: "Tuple" (name is the index)
368    ///   - For Array containers: "Array" (name is the index)
369    ///
370    /// Note: Option containers do not call enter_module/exit_module to preserve
371    /// the field name in the path (e.g., "bias" instead of "bias.Some")
372    #[allow(unused_variables)]
373    fn exit_module(&mut self, name: &str, container_type: &str) {}
374
375    /// Map a float parameter in the module.
376    ///
377    /// # Parameters
378    /// - `param`: The float parameter to transform
379    ///
380    /// # Returns
381    /// The transformed parameter
382    #[allow(unused_variables)]
383    fn map_float<const D: usize>(&mut self, param: Param<Tensor<B, D>>) -> Param<Tensor<B, D>> {
384        let (id, tensor, mapper) = param.consume();
385        Param::from_mapped_value(id, tensor, mapper)
386    }
387
388    /// Map an int parameter in the module.
389    ///
390    /// # Parameters
391    /// - `param`: The integer parameter to transform
392    ///
393    /// # Returns
394    /// The transformed parameter
395    #[allow(unused_variables)]
396    fn map_int<const D: usize>(
397        &mut self,
398        param: Param<Tensor<B, D, Int>>,
399    ) -> Param<Tensor<B, D, Int>> {
400        let (id, tensor, mapper) = param.consume();
401        Param::from_mapped_value(id, tensor, mapper)
402    }
403
404    /// Map a bool parameter in the module.
405    ///
406    /// # Parameters
407    /// - `param`: The boolean parameter to transform
408    ///
409    /// # Returns
410    /// The transformed parameter
411    #[allow(unused_variables)]
412    fn map_bool<const D: usize>(
413        &mut self,
414        param: Param<Tensor<B, D, Bool>>,
415    ) -> Param<Tensor<B, D, Bool>> {
416        let (id, tensor, mapper) = param.consume();
417        Param::from_mapped_value(id, tensor, mapper)
418    }
419}
420
421/// Module with auto-differentiation backend.
422pub trait AutodiffModule<B: AutodiffBackend>: Module<B> + Send + core::fmt::Debug {
423    /// Inner module without auto-differentiation.
424    type InnerModule: Module<B::InnerBackend>;
425
426    /// Returns the same module, but on the inner backend without auto-differentiation.
427    fn valid(&self) -> Self::InnerModule;
428
429    /// Wraps an inner module back into an auto-diff module.
430    fn from_inner(module: Self::InnerModule) -> Self;
431}
432
433/// Helper trait to associate a module with its autodiff version.
434pub trait HasAutodiffModule<B: AutodiffBackend> {
435    /// The module with auto-differentiation.
436    type TrainModule: AutodiffModule<B, InnerModule = Self>;
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442
443    use crate::TestAutodiffBackend;
444    use crate::test_utils::SimpleLinear;
445
446    #[test]
447    fn test_module_val_train_stateful() {
448        let device = Default::default();
449        let module = SimpleLinear::<TestAutodiffBackend>::new(4, 4, &device);
450
451        assert!(module.weight.is_require_grad());
452        assert!(module.weight.require_grad);
453
454        let module = module.valid();
455        assert!(!module.weight.is_require_grad());
456        assert!(module.weight.require_grad); // stateful
457
458        // Without `HasAutodiffModule`, we would need to specify the module type as well, which would be annoying
459        // let module: SimpleLinear<TestAutodiffBackend> = module.train();
460        let module = module.train::<TestAutodiffBackend>();
461        assert!(module.weight.is_require_grad());
462        assert!(module.weight.require_grad); // stateful
463
464        let module = module.no_grad();
465        assert!(!module.weight.is_require_grad());
466        assert!(!module.weight.require_grad); // stateful
467
468        let module = module.valid();
469        assert!(!module.weight.is_require_grad()); // always
470        assert!(!module.weight.require_grad); // stateful
471
472        let module = module.train::<TestAutodiffBackend>();
473        assert!(!module.weight.is_require_grad());
474        assert!(!module.weight.require_grad); // stateful
475    }
476}