{"record":{"id":"1f0eba8b2d8b4eac","repo":"huggingface/candle","slug":"empty-last-dim-in-arg-sort","errorCode":null,"errorMessage":"empty last-dim in arg-sort","messagePattern":"empty last-dim in arg-sort","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"candle-core/src/sort.rs","lineNumber":275,"sourceCode":"        n *= 2\n    }\n    n\n}\n\nimpl Tensor {\n    /// Returns the indices that sort the tensor along the last dimension.\n    ///\n    /// If `asc` is `true`, sorting is in ascending order. Otherwise sorting is performed in\n    /// descending order. The sort is unstable so there is no guarantees on the final order when it\n    /// comes to ties.\n    pub fn arg_sort_last_dim(&self, asc: bool) -> Result<Tensor> {\n        if !self.is_contiguous() {\n            return Err(crate::Error::RequiresContiguous {\n                op: \"arg_sort_last_dim\",\n            });\n        }\n        let last_dim = match self.dims().last() {\n            None => crate::bail!(\"empty last-dim in arg-sort\"),\n            Some(last_dim) => *last_dim,\n        };\n        // No need for a backward pass for arg sort.\n        self.apply_op1_no_bwd(&ArgSort { asc, last_dim })\n    }\n\n    /// Sorts the tensor along the last dimension, returns the sorted tensor together with the\n    /// sorted indexes.\n    ///\n    /// If `asc` is `true`, sorting is in ascending order. Otherwise sorting is performed in\n    /// descending order. The sort is unstable so there is no guarantees on the final order when it\n    /// comes to ties.\n    pub fn sort_last_dim(&self, asc: bool) -> Result<(Tensor, Tensor)> {\n        if !self.is_contiguous() {\n            return Err(crate::Error::RequiresContiguous {\n                op: \"sort_last_dim\",\n            });\n        }","sourceCodeStart":257,"sourceCodeEnd":293,"githubUrl":"https://github.com/huggingface/candle/blob/d5fee525bfde3273eb7c9b75fd2bc4937be867ca/candle-core/src/sort.rs#L257-L293","documentation":"arg_sort_last_dim requires a non-empty tensor with a well-defined last dimension; if the tensor has zero dimensions (a rank-0 scalar) there is no last dim to sort along, so it bails. It also requires the tensor to be contiguous. Raised before dispatching the ArgSort op.","triggerScenarios":"Calling argsort/sort/topk on a rank-0 tensor created via Tensor::new(5f32, &dev) or tensor.get(0) on a 1-D tensor, leaving no remaining last dimension. Also triggered indirectly via topk on such a tensor.","commonSituations":"Indexing/squeezing a tensor down to a scalar in a loop and then trying to topk it; accidentally passing an unbatched scalar result into topk.","solutions":["Check t.rank() > 0 before sorting; add a batch dimension with t.unsqueeze(0) if needed.","Keep at least the dimension to sort along, e.g. avoid full squeeze/get-to-scalar before topk.","Ensure the tensor is contiguous (call .contiguous() if it came from a transpose/slice)."],"exampleFix":"// before\nlet (v, i) = scores.squeeze(0)?.topk(5)?; // rank-0 -> error\n// after\nlet (v, i) = scores.topk(5)?; // keep rank or unsqueeze\n","handlingStrategy":"validation","validationCode":"if t.rank() == 0 {\n    return Err(anyhow!(\"cannot arg-sort a rank-0 tensor\"));\n}\nif !t.is_contiguous() { let t = t.contiguous()?; }\nlet (v, i) = t.argsort_last_dim(asc)?;","typeGuard":null,"tryCatchPattern":"match t.argsort_last_dim(asc) {\n    Ok(s) => s,\n    Err(e) if e.to_string().contains(\"empty last-dim\") => t.unsqueeze(0)?.argsort_last_dim(asc)?,\n    Err(e) => return Err(e.into()),\n}","preventionTips":["Never call topk/argsort on tensors squeezed down to rank 0.","Track tensor rank through indexing/reshape chains in loops.","Call .contiguous() after transpose/slice before sorting."],"tags":["shape","argsort","empty-dim"],"backgroundTag":"invalid-tensor-shape","analyzedSha":"d5fee525bfde3273eb7c9b75fd2bc4937be867ca","analyzedAt":"2026-09-02T00:15:47.023Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T06:17:21.866Z"}