Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add module mapper book example #2621

Merged
merged 2 commits into from
Dec 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions burn-book/src/building-blocks/module.md
Original file line number Diff line number Diff line change
@@ -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<B: Backend> ModuleMapper<B> for Clamp {
fn map_float<const D: usize>(
&mut self,
_id: burn::module::ParamId,
tensor: burn::prelude::Tensor<B, D>,
) -> burn::prelude::Tensor<B, D> {
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.
2 changes: 1 addition & 1 deletion crates/burn-jit/src/backend.rs
Original file line number Diff line number Diff line change
@@ -113,7 +113,7 @@ impl<R: JitRuntime, F: FloatElement, I: IntElement, BT: BoolElement> ReprBackend
handle.handle
}

fn quantized_tensor(handles: TensorHandle<Self::Handle>) -> QuantizedTensor<Self> {
fn quantized_tensor(handle: TensorHandle<Self::Handle>) -> QuantizedTensor<Self> {
handle.handle
}