{"record":{"id":"2a5b05a31f2770d3","repo":"huggingface/candle","slug":"unsqueeze-maximum-size-for-tensor-at-dimension-d","errorCode":null,"errorMessage":"unsqueeze: maximum size for tensor at dimension {dim} is {max_len} but size is {size}","messagePattern":"unsqueeze: maximum size for tensor at dimension (.+?) is (.+?) but size is (.+?)","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"candle-core/src/tensor.rs","lineNumber":2980,"sourceCode":"        Ok(result)\n    }\n\n    /// Returns a view of which contains all slices of size `size` from self tensor in the dimension\n    /// `dim` and stepped by `step`.\n    pub fn unfold<D: Dim>(&self, dim: D, size: usize, step: usize) -> Result<Self> {\n        // https://github.com/pytorch/pytorch/blob/75b0720a97ac5d82e8a7a1a6ae7c5f7a87d7183d/aten/src/ATen/native/TensorShape.cpp#L3785-L3804\n        let mut sizes = self.dims().to_vec();\n        let mut strides = self.stride().to_vec();\n\n        let dim = dim.to_index(self.shape(), \"unfold\")?;\n\n        let max_len = if self.dims().is_empty() {\n            1\n        } else {\n            sizes[dim]\n        };\n        if size > max_len {\n            bail!(\n                \"unsqueeze: maximum size for tensor at dimension {dim} is {max_len} but size is {size}\"\n            )\n        }\n        sizes.push(size);\n        strides.push(if self.dims().is_empty() {\n            1\n        } else {\n            strides[dim]\n        });\n\n        if !self.dims().is_empty() {\n            sizes[dim] = ((sizes[dim] as f32 - size as f32) / step as f32 + 1.) as usize;\n            strides[dim] *= step;\n        }\n\n        let tensor_ = Tensor_ {\n            id: TensorId::new(),\n            storage: self.storage.clone(),","sourceCodeStart":2962,"sourceCodeEnd":2998,"githubUrl":"https://github.com/huggingface/candle/blob/d5fee525bfde3273eb7c9b75fd2bc4937be867ca/candle-core/src/tensor.rs#L2962-L2998","documentation":"This is thrown by the unsqueeze-related size validation (the code building sizes/strides for a view with a new dimension). The requested size for the new dimension exceeds the maximum allowed at that position (1 for a scalar/empty tensor, otherwise the existing size at that dim), so the operation cannot be expressed as a view and it bails. Typically this comes from Tensor::broadcast UNSQUEEZE-style expansion (e.g. broadcast_in / expand paths) where a size of N is requested for a dim that has size 1 or doesn't exist.","triggerScenarios":"Calling broadcast/unsqueeze-style ops requesting dim size > allowed max, e.g. t.broadcast_as a shape with dim size 4 where the tensor has size 1 or rank 0 with size requested > 1.","commonSituations":"Broadcasting tensors whose shapes aren't broadcast-compatible (e.g. (3,) to (4,)); expanding a scalar to size >1 via the wrong API; config-driven target shapes inconsistent with the input.","solutions":["Verify the target dim size is 1 or equals the tensor's existing size at that dim before broadcasting","Use the documented broadcast APIs (broadcast_as / broadcast_in) which handle unsqueezing, instead of low-level size construction","Reshape the source tensor so the requested dim aligns with an existing size"],"exampleFix":"// before\n// t: [3], requesting dim size 4 -> bails\nlet b = t.broadcast_as((4, 3))?; // adjust so requested sizes are compatible\n// after\nlet b = t.broadcast_as((3, 3))?; // or reshape t first","handlingStrategy":"validation","validationCode":"fn broadcast_ok(from: &[usize], to: &[usize]) -> bool {\n    from.iter().rev().zip(to.iter().rev()).all(|(f, t)| *f == 1 || f == t)\n}\nassert!(broadcast_ok(&t.dims(), &target_shape));","typeGuard":null,"tryCatchPattern":"let out = t.broadcast_as(target_shape)\n    .or_else(|_| {\n        // align shapes manually before broadcasting\n        t.reshape(aligned_shape)?.broadcast_as(target_shape)\n    })?;","preventionTips":["Check broadcast compatibility (dims equal or 1) before expanding","Use broadcast_as/broadcast_in rather than hand-built size/stride views","Log both shapes on mismatch to catch config-driven target-shape bugs"],"tags":["rust","candle","unsqueeze","broadcast","shape"],"backgroundTag":"broadcast-shape-mismatch","analyzedSha":"d5fee525bfde3273eb7c9b75fd2bc4937be867ca","analyzedAt":"2026-09-02T00:15:47.023Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T06:17:21.866Z"}