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    /// Convert floating parameter storage while preserving IDs, shared parameters
122    /// and frozen/trainable settings. Converted trainable parameters are new leaves;
123    /// gradients through the conversion itself are not retained.
124    fn to_dtype(self, dtype: ruda_tensor::FloatDType) -> Self {
125        self.map(&mut super::precision::DtypeMapper::new(dtype))
126    }
127
128    /// Each tensor in the module tree will not require grad.
129    ///
130    /// # Warnings
131    ///
132    /// This should not be used for inference, use [valid](AutodiffModule::valid) when using
133    /// AD modules. This is mostly useful when performing partial finetuning, which is updating only
134    /// a small fraction of the parameters instead of finetuning all of them.
135    fn no_grad(self) -> Self {
136        module!(
137            map = self,
138            ops = |param: Param<Tensor<B, D>>| param.set_require_grad(false)
139        )
140    }
141
142    /// Move the module and all of its sub-modules to the autodiff backend.
143    ///
144    /// # Notes
145    ///
146    /// * Only plain modules (not already on an autodiff backend) can be moved.
147    /// * Calling `train()` on a module that is already on an autodiff backend
148    ///   will result in a type error, because the module's inner backend does not match.
149    fn train<AB>(self) -> <Self as HasAutodiffModule<AB>>::TrainModule
150    where
151        AB: AutodiffBackend<InnerBackend = B>,
152        Self: HasAutodiffModule<AB>,
153    {
154        <Self as HasAutodiffModule<AB>>::TrainModule::from_inner(self)
155    }
156
157    /// Get the number of parameters the module has, including all of its sub-modules.
158    fn num_params(&self) -> usize {
159        module!(
160            visit_float = self,
161            ops = |tensor: &Tensor<B, D>, state: &mut usize| {
162                *state += tensor.shape().num_elements();
163            },
164            state = usize,
165            init = || 0
166        )
167    }
168    /// Visit each tensor parameter in the module with a [visitor](ModuleVisitor).
169    fn visit<Visitor: ModuleVisitor<B>>(&self, visitor: &mut Visitor);
170
171    /// Map each tensor parameter in the module with a [mapper](ModuleMapper).
172    fn map<Mapper: ModuleMapper<B>>(self, mapper: &mut Mapper) -> Self;
173
174    /// Load the module state from a record.
175    fn load_record(self, record: Self::Record) -> Self;
176
177    /// Convert the module into a record containing the state.
178    fn into_record(self) -> Self::Record;
179
180    #[cfg(feature = "std")]
181    /// Save the module to a file using the provided [file recorder](crate::record::FileRecorder).
182    ///
183    /// List of supported file recorders:
184    ///
185    /// * [default](crate::record::DefaultFileRecorder)
186    /// * [bincode](crate::record::BinFileRecorder)
187    /// * [bincode compressed with gzip](crate::record::BinGzFileRecorder)
188    /// * [json pretty](crate::record::PrettyJsonFileRecorder)
189    /// * [json compressed with gzip](crate::record::JsonGzFileRecorder)
190    /// * [named mpk](crate::record::NamedMpkFileRecorder)
191    /// * [named mpk compressed with gzip](crate::record::NamedMpkGzFileRecorder)
192    ///
193    /// ## Notes
194    ///
195    /// The file extension is automatically added depending on the file recorder provided, you
196    /// don't have to specify it.
197    fn save_file<FR, PB>(
198        self,
199        file_path: PB,
200        recorder: &FR,
201    ) -> Result<(), crate::record::RecorderError>
202    where
203        FR: crate::record::FileRecorder<B>,
204        PB: Into<std::path::PathBuf>,
205    {
206        let record = Self::into_record(self);
207        recorder.record(record, file_path.into())
208    }
209
210    #[cfg(feature = "std")]
211    /// Load the module from a file using the provided [file recorder](crate::record::FileRecorder).
212    ///
213    /// The recorder should be the same as the one used to save the module, see
214    /// [save_file](Self::save_file).
215    ///
216    /// ## Notes
217    ///
218    /// The file extension is automatically added depending on the file recorder provided, you
219    /// don't have to specify it.
220    fn load_file<FR, PB>(
221        self,
222        file_path: PB,
223        recorder: &FR,
224        device: &B::Device,
225    ) -> Result<Self, crate::record::RecorderError>
226    where
227        FR: crate::record::FileRecorder<B>,
228        PB: Into<std::path::PathBuf>,
229    {
230        let record = recorder.load(file_path.into(), device)?;
231
232        Ok(self.load_record(record))
233    }
234
235    /// Quantize the weights of the module.
236    fn quantize_weights(self, quantizer: &mut Quantizer) -> Self {
237        self.map(quantizer)
238    }
239}
240
241/// Module visitor trait for traversing and inspecting module parameters.
242pub trait ModuleVisitor<B: Backend> {
243    /// Visit a float parameter in the module.
244    ///
245    /// # Parameters
246    /// - `param`: The float parameter to visit
247    #[allow(unused_variables)]
248    fn visit_float<const D: usize>(&mut self, param: &Param<Tensor<B, D>>) {}
249
250    /// Visit an int parameter in the module.
251    ///
252    /// # Parameters
253    /// - `param`: The integer parameter to visit
254    #[allow(unused_variables)]
255    fn visit_int<const D: usize>(&mut self, param: &Param<Tensor<B, D, Int>>) {}
256
257    /// Visit a bool parameter in the module.
258    ///
259    /// # Parameters
260    /// - `param`: The boolean parameter to visit
261    #[allow(unused_variables)]
262    fn visit_bool<const D: usize>(&mut self, param: &Param<Tensor<B, D, Bool>>) {}
263
264    /// Called when entering a submodule.
265    ///
266    /// # Parameters
267    /// - `name`: The name of the submodule being entered
268    /// - `container_type`: The type of the container with format:
269    ///   - For user-defined structs: "Struct:TypeName" (e.g., "Struct:Linear")
270    ///   - For user-defined enums: "Enum:TypeName" (e.g., "Enum:MyEnum")
271    ///   - For Vec containers: "Vec" (name is the index)
272    ///   - For Tuple containers: "Tuple" (name is the index)
273    ///   - For Array containers: "Array" (name is the index)
274    ///
275    /// Note: Option containers do not call enter_module/exit_module to preserve
276    /// the field name in the path (e.g., "bias" instead of "bias.Some")
277    #[allow(unused_variables)]
278    fn enter_module(&mut self, name: &str, container_type: &str) {}
279
280    /// Called when exiting a submodule.
281    ///
282    /// # Parameters
283    /// - `name`: The name of the submodule being exited
284    /// - `container_type`: The type of the container with format:
285    ///   - For user-defined structs: "Struct:TypeName" (e.g., "Struct:Linear")
286    ///   - For user-defined enums: "Enum:TypeName" (e.g., "Enum:MyEnum")
287    ///   - For Vec containers: "Vec" (name is the index)
288    ///   - For Tuple containers: "Tuple" (name is the index)
289    ///   - For Array containers: "Array" (name is the index)
290    ///
291    /// Note: Option containers do not call enter_module/exit_module to preserve
292    /// the field name in the path (e.g., "bias" instead of "bias.Some")
293    #[allow(unused_variables)]
294    fn exit_module(&mut self, name: &str, container_type: &str) {}
295
296    /// Visit a float tensor with its full module path.
297    ///
298    /// # Parameters
299    /// - `path`: The path components to the tensor as a slice (e.g., &["encoder", "layer1", "weight"]).
300    ///   Each element represents a module name in the hierarchy, with the final element
301    ///   being the parameter name. This allows efficient reuse of the path stack.
302    /// - `id`: The unique identifier of the parameter
303    /// - `tensor`: The float tensor to visit
304    #[allow(unused_variables)]
305    fn visit_float_with_path<const D: usize>(
306        &mut self,
307        path: &[String],
308        id: ParamId,
309        tensor: &Tensor<B, D>,
310    ) {
311    }
312
313    /// Visit an int tensor with its full module path.
314    ///
315    /// # Parameters
316    /// - `path`: The path components to the tensor as a slice (e.g., &["encoder", "layer1", "weight"]).
317    ///   Each element represents a module name in the hierarchy, with the final element
318    ///   being the parameter name. This allows efficient reuse of the path stack.
319    /// - `id`: The unique identifier of the parameter
320    /// - `tensor`: The integer tensor to visit
321    #[allow(unused_variables)]
322    fn visit_int_with_path<const D: usize>(
323        &mut self,
324        path: &[String],
325        id: ParamId,
326        tensor: &Tensor<B, D, Int>,
327    ) {
328    }
329
330    /// Visit a bool tensor with its full module path.
331    ///
332    /// # Parameters
333    /// - `path`: The path components to the tensor as a slice (e.g., &["encoder", "layer1", "weight"]).
334    ///   Each element represents a module name in the hierarchy, with the final element
335    ///   being the parameter name. This allows efficient reuse of the path stack.
336    /// - `id`: The unique identifier of the parameter
337    /// - `tensor`: The boolean tensor to visit
338    #[allow(unused_variables)]
339    fn visit_bool_with_path<const D: usize>(
340        &mut self,
341        path: &[String],
342        id: ParamId,
343        tensor: &Tensor<B, D, Bool>,
344    ) {
345    }
346}
347
348/// Module mapper trait for transforming module parameters.
349pub trait ModuleMapper<B: Backend> {
350    /// Called when entering a submodule.
351    ///
352    /// # Parameters
353    /// - `name`: The name of the submodule being entered
354    /// - `container_type`: The type of the container with format:
355    ///   - For user-defined structs: "Struct:TypeName" (e.g., "Struct:Linear")
356    ///   - For user-defined enums: "Enum:TypeName" (e.g., "Enum:MyEnum")
357    ///   - For Vec containers: "Vec" (name is the index)
358    ///   - For Tuple containers: "Tuple" (name is the index)
359    ///   - For Array containers: "Array" (name is the index)
360    ///
361    /// Note: Option containers do not call enter_module/exit_module to preserve
362    /// the field name in the path (e.g., "bias" instead of "bias.Some")
363    #[allow(unused_variables)]
364    fn enter_module(&mut self, name: &str, container_type: &str) {}
365
366    /// Called when exiting a submodule.
367    ///
368    /// # Parameters
369    /// - `name`: The name of the submodule being exited
370    /// - `container_type`: The type of the container with format:
371    ///   - For user-defined structs: "Struct:TypeName" (e.g., "Struct:Linear")
372    ///   - For user-defined enums: "Enum:TypeName" (e.g., "Enum:MyEnum")
373    ///   - For Vec containers: "Vec" (name is the index)
374    ///   - For Tuple containers: "Tuple" (name is the index)
375    ///   - For Array containers: "Array" (name is the index)
376    ///
377    /// Note: Option containers do not call enter_module/exit_module to preserve
378    /// the field name in the path (e.g., "bias" instead of "bias.Some")
379    #[allow(unused_variables)]
380    fn exit_module(&mut self, name: &str, container_type: &str) {}
381
382    /// Map a float parameter in the module.
383    ///
384    /// # Parameters
385    /// - `param`: The float parameter to transform
386    ///
387    /// # Returns
388    /// The transformed parameter
389    #[allow(unused_variables)]
390    fn map_float<const D: usize>(&mut self, param: Param<Tensor<B, D>>) -> Param<Tensor<B, D>> {
391        let (id, tensor, mapper) = param.consume();
392        Param::from_mapped_value(id, tensor, mapper)
393    }
394
395    /// Map an int parameter in the module.
396    ///
397    /// # Parameters
398    /// - `param`: The integer parameter to transform
399    ///
400    /// # Returns
401    /// The transformed parameter
402    #[allow(unused_variables)]
403    fn map_int<const D: usize>(
404        &mut self,
405        param: Param<Tensor<B, D, Int>>,
406    ) -> Param<Tensor<B, D, Int>> {
407        let (id, tensor, mapper) = param.consume();
408        Param::from_mapped_value(id, tensor, mapper)
409    }
410
411    /// Map a bool parameter in the module.
412    ///
413    /// # Parameters
414    /// - `param`: The boolean parameter to transform
415    ///
416    /// # Returns
417    /// The transformed parameter
418    #[allow(unused_variables)]
419    fn map_bool<const D: usize>(
420        &mut self,
421        param: Param<Tensor<B, D, Bool>>,
422    ) -> Param<Tensor<B, D, Bool>> {
423        let (id, tensor, mapper) = param.consume();
424        Param::from_mapped_value(id, tensor, mapper)
425    }
426}
427
428/// Module with auto-differentiation backend.
429pub trait AutodiffModule<B: AutodiffBackend>: Module<B> + Send + core::fmt::Debug {
430    /// Inner module without auto-differentiation.
431    type InnerModule: Module<B::InnerBackend>;
432
433    /// Returns the same module, but on the inner backend without auto-differentiation.
434    fn valid(&self) -> Self::InnerModule;
435
436    /// Wraps an inner module back into an auto-diff module.
437    fn from_inner(module: Self::InnerModule) -> Self;
438}
439
440/// Helper trait to associate a module with its autodiff version.
441pub trait HasAutodiffModule<B: AutodiffBackend> {
442    /// The module with auto-differentiation.
443    type TrainModule: AutodiffModule<B, InnerModule = Self>;
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449
450    use crate::TestAutodiffBackend;
451    use crate::test_utils::SimpleLinear;
452
453    #[test]
454    fn test_module_val_train_stateful() {
455        let device = Default::default();
456        let module = SimpleLinear::<TestAutodiffBackend>::new(4, 4, &device);
457
458        assert!(module.weight.is_require_grad());
459        assert!(module.weight.require_grad);
460
461        let module = module.valid();
462        assert!(!module.weight.is_require_grad());
463        assert!(module.weight.require_grad); // stateful
464
465        // Without `HasAutodiffModule`, we would need to specify the module type as well, which would be annoying
466        // let module: SimpleLinear<TestAutodiffBackend> = module.train();
467        let module = module.train::<TestAutodiffBackend>();
468        assert!(module.weight.is_require_grad());
469        assert!(module.weight.require_grad); // stateful
470
471        let module = module.no_grad();
472        assert!(!module.weight.is_require_grad());
473        assert!(!module.weight.require_grad); // stateful
474
475        let module = module.valid();
476        assert!(!module.weight.is_require_grad()); // always
477        assert!(!module.weight.require_grad); // stateful
478
479        let module = module.train::<TestAutodiffBackend>();
480        assert!(!module.weight.is_require_grad());
481        assert!(!module.weight.require_grad); // stateful
482    }
483}