Add Resize to onnx ops (#2946)

* added resize to candle-onnx, not currently working

* changed unreachable to bail, and bailed when both scales and sizes are set

* cleanup and added other unused options for this op

* cleanup

* fixed image loading to make output work

* cleanup and removed unused variables

* removed path path creation code, and changed unwrap to ?
This commit is contained in:
Kyle Birnbaum
2025-05-09 22:05:03 -07:00
committed by GitHub
parent 3d05f5cf3d
commit 36508a2c93
2 changed files with 118 additions and 13 deletions

View File

@ -1960,6 +1960,76 @@ fn simple_eval_(
let output = input.sign()?;
values.insert(node.output[0].clone(), output);
}
"Resize" => {
let input = get(&node.input[0])?;
if input.rank() != 4 {
bail!("Unsupported rank for nearest resize: {}", input.rank());
}
let scales = if node.input.len() > 2 && !node.input[2].is_empty() {
Some(get(&node.input[2])?)
} else {
None
};
let sizes = if node.input.len() > 3 && !node.input[3].is_empty() {
Some(get(&node.input[3])?)
} else {
None
};
let output_dims = match (scales, sizes) {
(Some(_), Some(_)) => {
bail!("Scales and sizes cannot both be set for Resize operation")
}
(Some(scales_tensor), None) => {
let scale_values = scales_tensor.to_vec1::<f32>()?;
input
.dims()
.iter()
.enumerate()
.map(|(i, &d)| (d as f32 * scale_values[i]) as usize)
.collect::<Vec<_>>()
}
(None, Some(sizes_tensor)) => sizes_tensor
.to_vec1::<i64>()?
.iter()
.map(|&d| d as usize)
.collect::<Vec<_>>(),
(None, None) => bail!("Either scales or sizes should be present"),
};
let coordinate_transformation_mode =
get_attr_opt::<str>(node, "coordinate_transformation_mode")?
.unwrap_or("half_pixel");
// Interpolation mode: nearest, linear, or cubic.
let mode = get_attr_opt::<str>(node, "mode")?.unwrap_or("nearest");
// How to determine the "nearest" pixel in nearest interpolation mode.
let nearest_mode =
get_attr_opt::<str>(node, "nearest_mode")?.unwrap_or("round_prefer_floor");
if mode != "nearest" {
bail!("Unsupported resize mode: {}", mode);
}
if nearest_mode != "floor" {
bail!("Unsupported nearest_mode for resize: {}", nearest_mode);
}
if coordinate_transformation_mode != "asymmetric" {
bail!(
"Unsupported coordinate_transformation_mode for resize: {}",
coordinate_transformation_mode
);
}
let h = output_dims[2];
let w = output_dims[3];
let output = input.upsample_nearest2d(h, w)?;
values.insert(node.output[0].clone(), output);
}
op_type => bail!("unsupported op_type {op_type} for op {node:?}"),
}
}