{"record":{"id":"ef418b81bb6505bd","repo":"huggingface/candle","slug":"one-hot-index-value-value-exceeds-depth-depth","errorCode":null,"errorMessage":"one_hot: index value {value} exceeds depth {depth}","messagePattern":"one_hot: index value (.+?) exceeds depth (.+?)","errorType":"exception","errorClass":"candle::Error","httpStatus":null,"severity":"error","filePath":"candle-nn/src/encoding.rs","lineNumber":142,"sourceCode":"    value: I,\n    offset: usize,\n    depth: usize,\n    v: &mut [D],\n    on_value: D,\n) -> Result<()> {\n    let value = value.into();\n    // Skip for an entire row of off_values\n    if value == -1 {\n        return Ok(());\n    }\n    if value < -1 {\n        bail!(\n            \"one_hot: invalid negative index value {value}, expected a positive index value or -1\"\n        );\n    }\n    let value = value as usize;\n    if value >= depth {\n        bail!(\"one_hot: index value {value} exceeds depth {depth}\")\n    }\n    let idx = offset + value;\n    if idx >= v.len() {\n        bail!(\"one_hot: index out of bounds {idx}, len {}\", v.len());\n    }\n    v[idx] = on_value;\n    Ok(())\n}\n","sourceCodeStart":124,"sourceCodeEnd":151,"githubUrl":"https://github.com/huggingface/candle/blob/d5fee525bfde3273eb7c9b75fd2bc4937be867ca/candle-nn/src/encoding.rs#L124-L151","documentation":"candle-nn's one_hot helper writes a marker value into a flat vector at `offset + value`. Before writing, it validates that the class index is non-negative and strictly less than `depth` (the number of one-hot slots per entry). This bail fires when the supplied class index is >= depth, i.e. the index does not fit in the requested one-hot width.","triggerScenarios":"Calling candle_nn::encoding::one_hot with an index tensor containing a value equal to or greater than the `depth` argument (e.g. one_hot(labels, depth=10) where a label is 10 or 255). The check is `value >= depth` after the value is cast to usize.","commonSituations":"Num-class mismatch: labels tensor created for a 1000-class dataset but model/one-hot built with depth=100; padding label values (e.g. 255 mask) accidentally included in the label tensor; off-by-one where classes are 1-indexed so max label == depth; vocab-size shrink after model version change.","solutions":["Increase the `depth` argument of one_hot to be strictly greater than every index in the tensor (e.g. depth = num_classes including any padding label).","Filter or remap out-of-range labels (padding/ignore values like 255 or -1-for-background) before calling one_hot.","Verify label max: compute labels.max_all()? (or min/max on CPU) and assert it is < depth before encoding.","Check for 1-indexed labels from an external dataset; convert to 0-indexed by subtracting 1 if appropriate."],"exampleFix":"// before: labels contain class 255 (padding), depth = num_classes\nlet onehot = one_hot(&labels, num_classes)?; // panics/errors for 255\n// after: clamp/filter padding labels first\nlet valid = labels.lt(num_classes as u32)?;\nlet labels = labels.masked_fill(&valid logical_not, 0u32)?;\nlet onehot = one_hot(&labels, num_classes)?;","handlingStrategy":"validation","validationCode":"let max_idx = labels.min_max()?.1.to_scalar::<u32>()?;\nif max_idx as usize >= depth {\n    return Err(anyhow!(\"label index {max_idx} exceeds one_hot depth {depth}\"));\n}","typeGuard":"fn indices_fit(labels: &Tensor, depth: usize) -> candle::Result<bool> {\n    Ok(labels.min_max()?.1.to_scalar::<u32>()? as usize < depth)\n}","tryCatchPattern":"match one_hot(&labels, depth) {\n    Ok(t) => t,\n    Err(e) if e.to_string().contains(\"exceeds depth\") => {\n        // remap padding labels and retry\n        one_hot(&labels.clamp(0u32, (depth as u32) - 1)?, depth)?\n    }\n    Err(e) => return Err(e.into()),\n}","preventionTips":["Keep a single NUM_CLASSES constant used for both label generation and one_hot depth","Filter padding/ignore label values (255, -1) before encoding","Unit-test one_hot with min/max label values from your dataset","Prefer using labels.max() in a debug assert before encoding"],"tags":["tensor","encoding","validation","rust"],"backgroundTag":"index-out-of-range","analyzedSha":"d5fee525bfde3273eb7c9b75fd2bc4937be867ca","analyzedAt":"2026-09-02T00:15:47.023Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T06:17:21.866Z"}