{"record":{"id":"2f4b4d6c60d5c1c5","repo":"huggingface/candle","slug":"norm-not-supported-for-integer-dtypes","errorCode":null,"errorMessage":"norm not supported for integer dtypes","messagePattern":"norm not supported for integer dtypes","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"candle-core/src/tensor.rs","lineNumber":1455,"sourceCode":"\n        (self * rhs).and_then(|ret| ret.sum_all())\n    }\n\n    /// Computes the **Frobenius norm** (L2 norm of all elements) of the tensor.\n    /// - Output is `sqrt(sum(x^2))`.\n    /// - Always returns a scalar (`[]` shape).\n    ///\n    /// # Example\n    /// ```rust\n    /// use candle_core::{Tensor, Device};\n    /// let t = Tensor::new(&[[3., 4.], [0., 0.]], &Device::Cpu)?;\n    /// let norm = t.norm()?;\n    /// assert_eq!(norm.to_scalar::<f64>()?, 5.);\n    /// # Ok::<(), candle_core::Error>(())\n    /// ```\n    pub fn norm(&self) -> Result<Self> {\n        if self.dtype().is_int() {\n            bail!(\"norm not supported for integer dtypes\");\n        }\n\n        self.sqr().and_then(|x| x.sum_all()).and_then(|x| x.sqrt())\n    }\n\n    /// Performs strict matrix-vector multiplication (`[m, n] * [n] = [m]`).\n    ///\n    /// - If `self` is a matrix (`[m, n]`) and `rhs` is a vector (`[n]`), returns a vector (`[m]`).\n    /// - **No broadcasting**: Panics if `self` is not 2D or if `rhs` is not 1D with matching size.\n    ///\n    /// # Example\n    /// ```rust\n    /// use candle_core::{Tensor, Device};\n    /// let mat = Tensor::new(&[[1., 2., 3.], [4., 5., 6.]], &Device::Cpu)?;\n    /// let vec = Tensor::new(&[1., 1., 1.], &Device::Cpu)?;\n    /// let res = mat.mv(&vec)?;\n    /// assert_eq!(res.to_vec1::<f64>()?, [6., 15.]);\n    /// # Ok::<(), candle_core::Error>(())","sourceCodeStart":1437,"sourceCodeEnd":1473,"githubUrl":"https://github.com/huggingface/candle/blob/d5fee525bfde3273eb7c9b75fd2bc4937be867ca/candle-core/src/tensor.rs#L1437-L1473","documentation":"Tensor::norm computes sqrt(sum(x^2)) which is only defined for float dtypes; integer tensors are rejected with this bail since the squared sum would overflow/lose meaning for int types. Cast to a float dtype to compute a norm.","triggerScenarios":"Calling tensor.norm() on a tensor with an integer dtype (U8, U32, I16, I32, I64) — e.g. after loading quantized/integer data or embedding indices.","commonSituations":"Computing norms of token-id tensors or uint8 image tensors without casting; generic utility code that assumes float input.","solutions":["Cast to float first: t.to_dtype(candle_core::DType::F32)?.norm()?.","If you truly need integer norms, compute manually with widening: t.to_dtype(F64) then sqr/sum/sqrt.","Add a dtype check (t.dtype().is_int()) in utility functions and cast defensively."],"exampleFix":"// before\nlet n = ids.norm()?; // ids: I64 -> error\n// after\nlet n = ids.to_dtype(DType::F32)?.norm()?;","handlingStrategy":"validation","validationCode":"let t = if t.dtype().is_int() {\n    t.to_dtype(candle_core::DType::F32)?\n} else { t };\nlet n = t.norm()?;","typeGuard":null,"tryCatchPattern":"match t.norm() {\n    Ok(n) => n,\n    Err(e) if e.to_string().contains(\"integer dtypes\") => t.to_dtype(DType::F32)?.norm()?,\n    Err(e) => return Err(e.into()),\n}","preventionTips":["Check dtype before math ops on tensors from integer sources (token ids, uint8 images).","Normalize inputs to F32 early in pipelines.","Document that utility functions expect float tensors."],"tags":["dtype","norm","integer"],"backgroundTag":"unsupported-dtype-for-op","analyzedSha":"d5fee525bfde3273eb7c9b75fd2bc4937be867ca","analyzedAt":"2026-09-02T00:15:47.023Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T06:17:21.866Z"}