huggingface/candle · error

slice-assign: the range for dim {i} ({start_included}..{end_

Error message

slice-assign: the range for dim {i} ({start_included}..{end_excluded}) does not match the size of src {}

What it means

After validating the range for each dim, slice_assign requires the region width (end_excluded - start_included) to equal src's size along that dim, since the whole src tensor is written into the region (padded with zeros around it). A mismatch means src cannot fit the region, so it bails reporting the range and src's dim size.

Source

Thrown at candle-core/src/tensor.rs:2906

                std::ops::Bound::Included(v) => *v,
                std::ops::Bound::Excluded(v) => *v + 1,
            };
            let end_excluded = match range.end_bound() {
                std::ops::Bound::Unbounded => self_dims[i],
                std::ops::Bound::Included(v) => *v + 1,
                std::ops::Bound::Excluded(v) => *v,
            };
            if end_excluded <= start_included {
                bail!("slice-assign: empty range for dim {i}, {start_included} {end_excluded}")
            }
            if self_dims[i] < end_excluded {
                bail!(
                    "slice-assign: upper bound is out of range for dim {i}, {end_excluded} {}",
                    self_dims[i]
                )
            }
            if end_excluded - start_included != src_dims[i] {
                bail!(
                    "slice-assign: the range for dim {i} ({start_included}..{end_excluded}) does not match the size of src {}", src_dims[i]
                )
            }
            src = src.pad_with_zeros(i, start_included, self_dims[i] - end_excluded)?;
            mask = mask.pad_with_zeros(i, start_included, self_dims[i] - end_excluded)?
        }
        mask.where_cond(/* on_true= */ &src, /* on_false= */ self)
    }

    /// Returns log(sum(exp(tensor), dim)).
    pub fn log_sum_exp<D: Dims>(&self, sum_dims: D) -> Result<Self> {
        let sum_dims = sum_dims.to_indexes(self.shape(), "log-sum-exp")?;
        if sum_dims.is_empty() {
            return Ok(self.clone());
        }
        let max = sum_dims[1..]
            .iter()
            .try_fold(self.max_keepdim(sum_dims[0])?, |max, &dim| {

View on GitHub (pinned to d5fee525bf)

Solutions

  1. Reshape/narrow src so each src_dims[i] equals end_excluded - start_included
  2. Adjust the ranges so their widths match src's dims exactly
  3. Pad or truncate src with pad_with_zeros/narrow before the call

Example fix

// before
// region 0..5 (width 5), src.dim(0) = 3
t.slice_assign(&[0..5, 0..4], &src)?;
// after
let src = src.pad_with_zeros(0, 0, 2)?; // now dim0 = 5
t.slice_assign(&[0..5, 0..4], &src)?;
Defensive patterns

Strategy: validation

Validate before calling

let region: Vec<usize> = ranges.iter().zip(t.dims()).map(|(r, d)| r.end.min(d) - r.start).collect();
assert_eq!(region, src.dims(), "src must match region sizes");

Try / catch

let src = match pad_or_narrow_to(&src, &region_sizes) {
    Ok(s) => s,
    Err(e) => { log::error!("src shape {} vs region {:?}", src.dims(), region_sizes); return Err(e); }
};

Prevention

When it happens

Trigger: tensor.slice_assign(&[0..5, 0..4], &src) where src.dim(0) == 3, i.e. src dims don't match the region sizes dim-by-dim.

Common situations: Assigning a differently-shaped patch into a larger tensor without matching region size; shape drift after preprocessing; forgetting that each dim's range width must equal the corresponding src dim.

Understand the failure class

Background: Tensor shape mismatch errors ("must have shape", "expected shape ... got ..."): when tensor dimensions disagree with what an op or layer was told to expect — this error's family across 6 libraries.

Related errors


AI-assisted analysis of huggingface/candle@d5fee525bf (2026-09-02). Data as JSON: /api/errors/b343c1299408ce3c. Report an issue: GitHub.