Struct LpLoss
pub struct LpLoss {
pub p: f64,
}Expand description
Computes the Lp Loss between predictions and targets.
This loss function computes the element-wise p-th power of absolute errors, then reduces them via mean or sum.
§Mathematical Definition
For predictions ŷ and targets y, the element-wise loss is:
Lᵢ = |ŷᵢ - yᵢ|ᵖWith mean reduction (default), the final loss is:
L = (1/n) × Σᵢ |ŷᵢ - yᵢ|ᵖ§Notes
- This implementation computes
|error|^p, not the Lp norm(Σ|error|^p)^(1/p). - The
p = 1case uses an optimizedabs()operation. - The
p = 2case uses an optimized computationerror * errorinstead ofpowf.
§Example
use burn_nn::loss::{LpLossConfig, Reduction};
use burn::tensor::Tensor;
// Create L2 loss
let l2_loss = LpLossConfig::l2();
let predictions: Tensor<2> = /* model output */;
let targets: Tensor<2> = /* ground truth */;
// Compute loss with mean reduction (MSE)
let mse = l2_loss.forward(predictions.clone(), targets.clone(), Reduction::Mean);
// Compute loss with sum reduction (SSE)
let sse = l2_loss.forward(predictions.clone(), targets.clone(), Reduction::Sum);
// Compute loss with no reduction
let unreduced_l2_loss = l2_loss.forward_no_reduction(predictions, targets);Fields§
§p: f64The order of the norm (e.g., 1 for L1, 2 for L2).
Equivalently, the exponent p for computing |error|^p.
Implementations§
§impl LpLoss
impl LpLoss
pub fn forward<const D: usize>(
&self,
predictions: Tensor<D>,
targets: Tensor<D>,
reduction: Reduction,
) -> Tensor<1>
pub fn forward<const D: usize>( &self, predictions: Tensor<D>, targets: Tensor<D>, reduction: Reduction, ) -> Tensor<1>
Computes the element-wise loss |error|^p with reduction.
§Arguments
predictions- The model’s predicted values.targets- The ground truth target values.reduction- Specifies how to reduce the element-wise losses:Reduction::MeanorReduction::Auto: Returns the mean of all element-wise losses.Reduction::Sum: Returns the sum of all element-wise losses.
§Returns
A scalar tensor containing the reduced loss value.
§Shapes
- predictions:
[...dims]- Any shape - targets:
[...dims]- Must match predictions shape - output:
[1]- Scalar loss value
pub fn forward_no_reduction<const D: usize>(
&self,
predictions: Tensor<D>,
targets: Tensor<D>,
) -> Tensor<D>
pub fn forward_no_reduction<const D: usize>( &self, predictions: Tensor<D>, targets: Tensor<D>, ) -> Tensor<D>
Computes the element-wise loss |error|^p without reduction.
§Arguments
predictions- The model’s predicted values.targets- The ground truth target values.
§Returns
A tensor of the same shape as the inputs, containing |prediction - target|^p
for each element.
§Shapes
- predictions:
[...dims]- Any shape - targets:
[...dims]- Must match predictions shape - output:
[...dims]- Same shape as inputs
pub fn forward_reduce_dims<const D: usize>(
&self,
predictions: Tensor<D>,
targets: Tensor<D>,
dims: &[impl AsIndex],
) -> Tensor<D>
pub fn forward_reduce_dims<const D: usize>( &self, predictions: Tensor<D>, targets: Tensor<D>, dims: &[impl AsIndex], ) -> Tensor<D>
Computes the element-wise loss |error|^p with reduction over specified dimensions.
Calculates element-wise |predictions - targets|^p, then takes the mean
over the specified dimensions. Useful for per-sample or per-channel losses (e.g., when
working with images).
Dimensions can be provided in any order.
§Arguments
predictions- The model’s predicted values.targets- The ground truth target values.dims- Dimensions to reduce over. Negative dimensions are supported and count from the end.
§Returns
A tensor with the specified dimensions reduced to size 1.
§Example
// Image tensor: [batch, C, H, W]
let l2_loss = LpLossConfig::l2();
// Per-image MSE for PSNR: reduce over C, H, W → [batch, 1, 1, 1]
let mse_per_image = l2_loss.forward_reduce_dims(predictions, targets, &[1, 2, 3]);Trait Implementations§
§impl Module for LpLoss
impl Module for LpLoss
§fn visit<V>(&self, _visitor: &mut V)where
V: ModuleVisitor,
fn visit<V>(&self, _visitor: &mut V)where
V: ModuleVisitor,
§fn map<M>(self, _mapper: &mut M) -> LpLosswhere
M: ModuleMapper,
fn map<M>(self, _mapper: &mut M) -> LpLosswhere
M: ModuleMapper,
§fn to_device(self, _: &Device) -> LpLoss
fn to_device(self, _: &Device) -> LpLoss
§fn fork(self, _: &Device) -> LpLoss
fn fork(self, _: &Device) -> LpLoss
§fn collect_devices(&self, devices: Vec<Device>) -> Vec<Device>
fn collect_devices(&self, devices: Vec<Device>) -> Vec<Device>
§fn materialize(self) -> LpLoss
fn materialize(self) -> LpLoss
§fn valid(&self) -> LpLoss
fn valid(&self) -> LpLoss
§fn train(self) -> LpLoss
fn train(self) -> LpLoss
§fn devices(&self) -> Vec<Device>
fn devices(&self) -> Vec<Device>
§fn set_require_grad(self, require_grad: bool) -> Self
fn set_require_grad(self, require_grad: bool) -> Self
§fn set_require_grad_group(self, group: ParamGroup, require_grad: bool) -> Self
fn set_require_grad_group(self, group: ParamGroup, require_grad: bool) -> Self
§fn no_grad(self) -> Self
fn no_grad(self) -> Self
§fn freeze_group(self, group: ParamGroup) -> Self
fn freeze_group(self, group: ParamGroup) -> Self
§fn unfreeze_group(self, group: ParamGroup) -> Self
fn unfreeze_group(self, group: ParamGroup) -> Self
§fn num_params(&self) -> usize
fn num_params(&self) -> usize
§fn quantize_weights(self, quantizer: &mut Quantizer) -> Self
fn quantize_weights(self, quantizer: &mut Quantizer) -> Self
§fn quantize_weights_group(
self,
quantizer: &mut Quantizer,
group: ParamGroup,
) -> Self
fn quantize_weights_group( self, quantizer: &mut Quantizer, group: ParamGroup, ) -> Self
§fn apply_reparameterization<R>(self, reparameterizer: R) -> Selfwhere
Self: Sized,
R: Reparameterizer,
fn apply_reparameterization<R>(self, reparameterizer: R) -> Selfwhere
Self: Sized,
R: Reparameterizer,
Reparameterizer. Read more§fn apply_lora(self, lora: Lora) -> Selfwhere
Self: Sized,
fn apply_lora(self, lora: Lora) -> Selfwhere
Self: Sized,
§fn apply_qlora(self, qlora: QLora) -> Selfwhere
Self: Sized,
fn apply_qlora(self, qlora: QLora) -> Selfwhere
Self: Sized,
§fn into_record(self) -> ModuleRecordwhere
Self: Sized,
fn into_record(self) -> ModuleRecordwhere
Self: Sized,
ModuleRecord. Read more§fn into_record_group(self, group: ParamGroup) -> ModuleRecordwhere
Self: Sized,
fn into_record_group(self, group: ParamGroup) -> ModuleRecordwhere
Self: Sized,
§fn try_load_record(self, record: ModuleRecord) -> Result<Self, RecordError>where
Self: Sized,
fn try_load_record(self, record: ModuleRecord) -> Result<Self, RecordError>where
Self: Sized,
ModuleRecord to this module, returning the loaded
module. Read more§fn load_record(self, record: ModuleRecord) -> Selfwhere
Self: Sized,
fn load_record(self, record: ModuleRecord) -> Selfwhere
Self: Sized,
ModuleRecord to this module, consuming and returning
it. Read more§fn save_file<P>(self, path: P) -> Result<(), RecordError>
fn save_file<P>(self, path: P) -> Result<(), RecordError>
§fn load_file<P>(self, path: P) -> Self
fn load_file<P>(self, path: P) -> Self
§fn try_load_file<P>(self, path: P) -> Result<Self, RecordError>
fn try_load_file<P>(self, path: P) -> Result<Self, RecordError>
§impl ModuleDisplay for LpLoss
impl ModuleDisplay for LpLoss
§fn format(&self, passed_settings: DisplaySettings) -> String
fn format(&self, passed_settings: DisplaySettings) -> String
§fn custom_settings(&self) -> Option<DisplaySettings>
fn custom_settings(&self) -> Option<DisplaySettings>
Auto Trait Implementations§
impl Freeze for LpLoss
impl RefUnwindSafe for LpLoss
impl Send for LpLoss
impl Sync for LpLoss
impl Unpin for LpLoss
impl UnsafeUnpin for LpLoss
impl UnwindSafe for LpLoss
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<K, Q> Comparable<Q> for K
impl<K, Q> Comparable<Q> for K
§impl<K, Q> Equivalent<Q> for K
impl<K, Q> Equivalent<Q> for K
§fn equivalent(&self, key: &Q) -> bool
fn equivalent(&self, key: &Q) -> bool
key and return true if they are equal.impl<T> ErasedDestructor for Twhere
T: 'static,
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more§impl<T> Pointable for T
impl<T> Pointable for T
§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
§impl<T> ToCompactString for Twhere
T: Display,
impl<T> ToCompactString for Twhere
T: Display,
§fn try_to_compact_string(&self) -> Result<CompactString, ToCompactStringError>
fn try_to_compact_string(&self) -> Result<CompactString, ToCompactStringError>
ToCompactString::to_compact_string()] Read more§fn to_compact_string(&self) -> CompactString
fn to_compact_string(&self) -> CompactString
CompactString]. Read more