{"record":{"id":"d83ad9f979bca00f","repo":"huggingface/candle","slug":"input-and-target-must-have-the-same-shape-got-inp","errorCode":null,"errorMessage":"input and target must have the same shape, got inp: {:?}, target: {:?}","messagePattern":"input and target must have the same shape, got inp: (.+?), target: (.+?)","errorType":"exception","errorClass":"candle::Error","httpStatus":null,"severity":"error","filePath":"candle-nn/src/loss.rs","lineNumber":91,"sourceCode":"    Ok(loss)\n}\n\n/// HuberLoss\n///\n/// A robust loss function that combines `MAE` and `MSE` losses:\n///\n/// - When the absolute element-wise error is less than `delta`, it uses a squared term (MSE loss).\n/// - When the absolute element-wise error is greater than or equal to `delta`, it uses a linear term (MAE loss scaled by `delta`).\n/// # Formula\n///\n/// HuberLoss =\n/// ```tex\n/// 0.5(x_n - y_n)^2, & |x_n - y_n| < delta\n/// delta(|x_n - y_n| - 0.5delta), & |x_n - y_n| >= delta\n/// ```\npub fn huber(inp: &Tensor, target: &Tensor, delta: f64) -> Result<Tensor> {\n    if inp.dims() != target.dims() {\n        candle::bail!(\n            \"input and target must have the same shape, got inp: {:?}, target: {:?}\",\n            inp.dims(),\n            target.dims()\n        );\n    }\n    let diff = (inp - target)?;\n    let abs_diff = diff.abs()?;\n    let mask = abs_diff.le(delta)?;\n    let squared_loss = ((&diff * &diff)? * 0.5)?;\n    let linear_loss = ((abs_diff * delta)? - 0.5 * delta.powi(2))?;\n    let loss = mask.where_cond(&squared_loss, &linear_loss)?;\n    loss.mean_all()\n}\n","sourceCodeStart":73,"sourceCodeEnd":105,"githubUrl":"https://github.com/huggingface/candle/blob/d5fee525bfde3273eb7c9b75fd2bc4937be867ca/candle-nn/src/loss.rs#L73-L105","documentation":"candle_nn::loss::huber computes the element-wise Huber loss between inp and target, which requires both tensors to have identical shapes so elementwise subtraction and comparisons are well defined. This bail fires when inp.dims() != target.dims(), reporting both shapes.","triggerScenarios":"Calling huber(&inp, &target, delta) with mismatched shapes — e.g. predictions [B] vs targets [B,1], predictions of a different sequence length, or broadcast-shaped targets that NumPy/PyTorch would silently broadcast but candle rejects.","commonSituations":"Regression targets squeezed/unsqueezed inconsistently between pipelines; targets stored with an extra singleton dim; predictions from a head with different output size than labels; mixing per-step and per-sequence reductions.","solutions":["Reshape the target to match inp exactly: e.g. target.reshape_like(&inp)? or squeeze the trailing singleton dim.","Alternatively reshape predictions: out.squeeze(1)? (or unsqueeze) so both are [B].","Check dataset collation so targets and model outputs share the same shape convention; fix at the source rather than reshaping at the loss.","Assert inp.dims() == target.dims() with a clear log right after the forward pass to catch drift early."],"exampleFix":"// before\nlet loss = huber(&pred, &target, 1.0)?; // pred [B], target [B,1]\n// after\nlet target = target.squeeze(1)?;\nlet loss = huber(&pred, &target, 1.0)?;","handlingStrategy":"validation","validationCode":"if inp.dims() != target.dims() {\n    return Err(anyhow!(\"huber shape mismatch: {:?} vs {:?}\", inp.dims(), target.dims()));\n}","typeGuard":null,"tryCatchPattern":"let target = if target.dims() != pred.dims() {\n    target.reshape_like(&pred)?\n} else { target };\nlet loss = huber(&pred, &target, delta)?;","preventionTips":["Standardize prediction and target shape conventions ([B] vs [B,1]) at dataset level","Use reshape_like or squeeze immediately after the forward pass, not inside the loss","Compare pred.dims() == target.dims() in a debug assert each step","Check the regression head's output size matches the label dimensionality"],"tags":["loss","shape","regression","rust"],"backgroundTag":"shape-mismatch","analyzedSha":"d5fee525bfde3273eb7c9b75fd2bc4937be867ca","analyzedAt":"2026-09-02T00:15:47.023Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T06:17:21.866Z"}