{"record":{"id":"cc6baf9d49a9bfb2","repo":"huggingface/candle","slug":"dimension-mismatch-in-permute-tensor-dims-cc6baf","errorCode":null,"errorMessage":"dimension mismatch in permute, tensor {:?}, dims: {:?}","messagePattern":"dimension mismatch in permute, tensor (.+?), dims: (.+?)","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"candle-core/src/tensor.rs","lineNumber":2329,"sourceCode":"\n    /// Returns a tensor with the same data as the input where the dimensions have been permuted.\n    /// dims must be a permutation, i.e. include each dimension index exactly once.\n    ///\n    /// ```rust\n    /// use candle_core::{Tensor, Device};\n    /// let tensor = Tensor::arange(0u32, 120u32, &Device::Cpu)?.reshape((2, 3, 4, 5))?;\n    /// assert_eq!(tensor.dims(), &[2, 3, 4, 5]);\n    /// let tensor = tensor.permute((2, 3, 1, 0))?;\n    /// assert_eq!(tensor.dims(), &[4, 5, 3, 2]);\n    /// # Ok::<(), candle_core::Error>(())\n    /// ```\n    pub fn permute<D: Dims>(&self, dims: D) -> Result<Tensor> {\n        let dims = dims.to_indexes(self.shape(), \"permute\")?;\n        // O(n^2) permutation check but these arrays are small.\n        let is_permutation =\n            dims.len() == self.rank() && (0..dims.len()).all(|i| dims.contains(&i));\n        if !is_permutation {\n            bail!(\n                \"dimension mismatch in permute, tensor {:?}, dims: {:?}\",\n                self.dims(),\n                dims\n            )\n        }\n        let op = BackpropOp::new1(self, |t| Op::Permute(t, dims.clone()));\n        let tensor_ = Tensor_ {\n            id: TensorId::new(),\n            storage: self.storage.clone(),\n            layout: self.layout.permute(&dims)?,\n            op,\n            is_variable: false,\n            dtype: self.dtype,\n            device: self.device.clone(),\n        };\n        Ok(Tensor(Arc::new(tensor_)))\n    }\n","sourceCodeStart":2311,"sourceCodeEnd":2347,"githubUrl":"https://github.com/huggingface/candle/blob/d5fee525bfde3273eb7c9b75fd2bc4937be867ca/candle-core/src/tensor.rs#L2311-L2347","documentation":"Tensor::permute reorders existing dimensions and therefore requires the supplied dims to be a valid permutation of 0..rank — same length as the rank, with every index 0..rank appearing exactly once. Anything else (repeated indices, out-of-range indices, wrong count) triggers this bail, which includes the tensor's dims and the offending dims for debugging.","triggerScenarios":"Calling t.permute(&[0, 2, 1]) on a tensor whose rank doesn't match the dims length; passing duplicate indices like [0,1,1]; using out-of-range indices like [0,3,2] on a rank-3 tensor; confusing permute (permutation of dims) with transpose (swap of two dims).","commonSituations":"Porting NumPy/PyTorch code with hardcoded permutations to a differently-shaped tensor; off-by-one dims in NHWC<->NCHW conversions; calling permute instead of transpose for a simple two-dim swap.","solutions":["Verify dims is a permutation of 0..t.rank(): same length, no duplicates, all indices < rank.","For a simple two-dimension swap, use t.transpose(d1, d2) instead of permute.","Print t.dims() and check your permutation against the actual rank.","For NHWC<->NCHW on 4-D tensors use the standard permutations: [0,3,1,2] and [0,2,3,1]."],"exampleFix":"// before\nlet out = img.permute(&[0, 2, 1])?; // img is rank 4 -> error\n// after\nlet out = img.permute(&[0, 2, 3, 1])?; // valid permutation of 0..4","handlingStrategy":"validation","validationCode":"let dims = [0usize, 2, 3, 1];\nlet r = t.rank();\nlet is_perm = dims.len() == r && (0..r).all(|i| dims.contains(&i));\nif !is_perm {\n    return Err(anyhow!(\"invalid permutation {:?} for rank {}\", dims, r));\n}\nlet out = t.permute(dims)?;","typeGuard":null,"tryCatchPattern":"match t.permute(dims) {\n    Ok(x) => x,\n    Err(e) if e.to_string().contains(\"dimension mismatch in permute\") => {\n        eprintln!(\"rank={}, attempted dims={:?}\", t.rank(), dims);\n        return Err(e.into());\n    }\n    Err(e) => return Err(e.into()),\n}","preventionTips":["Use transpose(d1, d2) for simple two-dim swaps instead of permute.","Derive permutations from rank instead of hardcoding literals.","Know the standard permutations: NHWC->NCHW is [0,3,1,2]; NCHW->NHWC is [0,2,3,1]."],"tags":["shape","permute","dimension"],"backgroundTag":"invalid-permutation","analyzedSha":"d5fee525bfde3273eb7c9b75fd2bc4937be867ca","analyzedAt":"2026-09-02T00:15:47.023Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T06:17:21.866Z"}