{"record":{"id":"0e3208597dd0bb42","repo":"huggingface/candle","slug":"dimension-index-dim-is-too-large-for-tensor-rank","errorCode":null,"errorMessage":"dimension index {dim} is too large for tensor rank {rank}","messagePattern":"dimension index (.+?) is too large for tensor rank (.+?)","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"candle-pyo3/src/lib.rs","lineNumber":191,"sourceCode":"        let index = index as usize;\n        if dim <= index {\n            ::candle::bail!(\"index {index} is too large for tensor dimension {dim}\")\n        }\n        Ok(index)\n    } else {\n        if (dim as i64) < -index {\n            ::candle::bail!(\"index {index} is too low for tensor dimension {dim}\")\n        }\n        Ok((dim as i64 + index) as usize)\n    }\n}\n\nfn actual_dim(t: &Tensor, dim: i64) -> ::candle::Result<usize> {\n    let rank = t.rank();\n    if 0 <= dim {\n        let dim = dim as usize;\n        if rank <= dim {\n            ::candle::bail!(\"dimension index {dim} is too large for tensor rank {rank}\")\n        }\n        Ok(dim)\n    } else {\n        if (rank as i64) < -dim {\n            ::candle::bail!(\"dimension index {dim} is too low for tensor rank {rank}\")\n        }\n        Ok((rank as i64 + dim) as usize)\n    }\n}\n\n// TODO: Something similar to this should probably be a part of candle core.\ntrait MapDType {\n    type Output;\n    fn f<T: PyWithDType>(&self, t: &Tensor) -> PyResult<Self::Output>;\n\n    fn map(&self, t: &Tensor) -> PyResult<Self::Output> {\n        match t.dtype() {\n            DType::U8 => self.f::<u8>(t),","sourceCodeStart":173,"sourceCodeEnd":209,"githubUrl":"https://github.com/huggingface/candle/blob/d5fee525bfde3273eb7c9b75fd2bc4937be867ca/candle-pyo3/src/lib.rs#L173-L209","documentation":"Thrown by candle-pyo3's `actual_dim` when a non-negative dimension index passed to operations like index_select, gather, squeeze, narrow, argmax_keepdim or argmin_keepdim is >= the tensor's rank. It validates that the dim refers to an existing axis before delegating to the candle core op.","triggerScenarios":"Calling any of the bound ops with dim = rank or higher, e.g. squeeze(3) on a rank-3 tensor, or narrow(4, ...) on a 4-D tensor (valid dims 0-3).","commonSituations":"Hard-coded dim values written for a different model architecture, forgetting batch/channel axes, or tensors that lost a dimension after a squeeze/reshape earlier in the pipeline.","solutions":["Print t.rank() (or len(t.shape)) and verify dim < rank","Use negative dims (-1 for the last axis), which actual_dim supports","Fix the hard-coded dim constant to match the actual tensor rank"],"exampleFix":"// before\nt.squeeze(3)  # rank-3 tensor, valid dims 0..2\n// after\nassert 3 < t.rank()\nt.squeeze(-1)  # operate on last axis regardless of rank","handlingStrategy":"validation","validationCode":"let rank = t.rank();\nif dim < 0 || dim as usize >= rank { panic!(\"dim {} invalid for rank {}\", dim, rank); }","typeGuard":"fn is_valid_dim(rank: usize, dim: i64) -> bool {\n    (-(rank as i64)..(rank as i64)).contains(&dim)\n}","tryCatchPattern":"match t.squeeze(dim) {\n    Ok(v) => v,\n    Err(e) if e.to_string().contains(\"too large\") => return Err(e),\n    Err(e) => return Err(e),\n}","preventionTips":["Derive dims from t.rank()/t.dims() instead of hard-coding","Use negative dims (-1) for axis-relative operations","Assert tensor rank after every reshape/squeeze in the pipeline"],"tags":["rust","pyo3","tensor","dimension-out-of-range"],"backgroundTag":"tensor-dimension-out-of-range","analyzedSha":"d5fee525bfde3273eb7c9b75fd2bc4937be867ca","analyzedAt":"2026-09-02T00:15:47.023Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T06:17:21.866Z"}