From 8a89293bf3ee02fe7216705ed3b7370506489e4a Mon Sep 17 00:00:00 2001 From: Guillaume Lagrange Date: Mon, 16 Dec 2024 11:44:14 -0500 Subject: [PATCH] Add module mapper book example (#2621) * Add module mapper example * Fix handles typo --- burn-book/src/building-blocks/module.md | 31 +++++++++++++++++++++++++ crates/burn-jit/src/backend.rs | 2 +- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/burn-book/src/building-blocks/module.md b/burn-book/src/building-blocks/module.md index 128a99a7b6..6404552471 100644 --- a/burn-book/src/building-blocks/module.md +++ b/burn-book/src/building-blocks/module.md @@ -112,6 +112,37 @@ Note that the trait doesn't require all methods to be implemented as they are al perform no operation. If you're only interested in float tensors (like the majority of use cases), then you can simply implement `map_float` or `visit_float`. +For example, the `ModuleMapper` trait could be implemented to clamp all parameters into the range +`[min, max]`. + +```rust, ignore +/// Clamp parameters into the range `[min, max]`. +pub struct Clamp { + /// Lower-bound of the range. + pub min: f32, + /// Upper-bound of the range. + pub max: f32, +} + +// Clamp all floating-point parameter tensors between `[min, max]`. +impl ModuleMapper for Clamp { + fn map_float( + &mut self, + _id: burn::module::ParamId, + tensor: burn::prelude::Tensor, + ) -> burn::prelude::Tensor { + tensor.clamp(self.min, self.max) + } +} + +// Clamp module mapper into the range `[-0.5, 0.5]` +let mut clamp = Clamp { + min: -0.5, + max: 0.5, +}; +let model = model.map(&mut clamp); +``` + ## Module Display Burn provides a simple way to display the structure of a module and its configuration at a glance. diff --git a/crates/burn-jit/src/backend.rs b/crates/burn-jit/src/backend.rs index 2d1b64ebce..3f5637e412 100644 --- a/crates/burn-jit/src/backend.rs +++ b/crates/burn-jit/src/backend.rs @@ -113,7 +113,7 @@ impl ReprBackend handle.handle } - fn quantized_tensor(handles: TensorHandle) -> QuantizedTensor { + fn quantized_tensor(handle: TensorHandle) -> QuantizedTensor { handle.handle }