1use crate::tensor::{DeviceTensor, DeviceTensorExt, IntoDevice};
2use derive_new::new;
3use tract_core::internal::*;
4
5pub type DispatchResizeAxisFn = fn(
8 input: &DeviceTensor,
9 axis: usize,
10 indices: &DeviceTensor,
11 weights: &DeviceTensor,
12 window: usize,
13 output: &DeviceTensor,
14) -> TractResult<()>;
15
16#[derive(Clone, new)]
22pub struct GpuResize {
23 pub axes: TVec<usize>,
24 pub windows: TVec<usize>,
25 pub plans: TVec<(Arc<Tensor>, Arc<Tensor>)>,
26 pub output_shape: TVec<usize>,
27 pub backend_name: &'static str,
28 pub dispatch: DispatchResizeAxisFn,
29}
30
31impl std::fmt::Debug for GpuResize {
32 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
33 write!(f, "{}Resize", self.backend_name)
34 }
35}
36
37impl PartialEq for GpuResize {
38 fn eq(&self, other: &Self) -> bool {
39 self.backend_name == other.backend_name
40 && self.axes == other.axes
41 && self.windows == other.windows
42 && self.output_shape == other.output_shape
43 }
44}
45impl Eq for GpuResize {}
46
47impl std::hash::Hash for GpuResize {
48 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
49 self.backend_name.hash(state);
50 self.axes.hash(state);
51 self.windows.hash(state);
52 self.output_shape.hash(state);
53 }
54}
55
56impl Op for GpuResize {
57 fn name(&self) -> StaticName {
58 format!("{}Resize", self.backend_name).into()
59 }
60 fn info(&self) -> TractResult<Vec<String>> {
61 Ok(vec![format!("axes={:?} windows={:?}", self.axes, self.windows)])
62 }
63 op_as_typed_op!();
64}
65
66impl EvalOp for GpuResize {
67 op_out_of_plan!();
68
69 fn eval(&self, ctx: &EvalContext, inputs: TVec<TValue>) -> TractResult<TVec<TValue>> {
70 let data = inputs[0].to_device_tensor()?;
71 let dt = data.datum_type();
72 let mut shape: TVec<usize> = data.shape().into();
73 let mut current = data.clone();
74 for (step, (&axis, &window)) in self.axes.iter().zip(&self.windows).enumerate() {
75 let (indices, weights) = &self.plans[step];
76 let indices = indices.as_ref().clone().into_device()?;
77 let weights = weights.as_ref().clone().into_device()?;
78 shape[axis] = self.output_shape[axis];
79 let last = step + 1 == self.axes.len();
80 let output = if last {
81 crate::turn_handler::make_tensor_for_node(ctx, dt, &shape)?
82 } else {
83 DeviceTensor::uninitialized_dt(dt, &shape)?
84 };
85 (self.dispatch)(¤t, axis, &indices, &weights, window, &output)?;
86 current = output;
87 }
88 Ok(tvec!(current.into_tensor().into_tvalue()))
89 }
90}
91
92impl TypedOp for GpuResize {
93 fn output_facts(&self, inputs: &[&TypedFact]) -> TractResult<TVec<TypedFact>> {
94 crate::utils::facts_to_device_facts(inputs, |facts| {
95 ensure!(facts.len() == 1);
96 let shape: TVec<TDim> = self.output_shape.iter().map(|d| d.to_dim()).collect();
97 Ok(tvec!(facts[0].datum_type.fact(&shape)))
98 })
99 .with_context(|| format!("Error while computing facts for {:?}", self.name()))
100 }
101 as_op!();
102}