Skip to main content

ruxla_prims/
conv.rs

1//! `conv_general_dilated`, following JAX's `lax.conv_general_dilated_p`.
2
3use ruxla_ir::Atom;
4use ruxla_ir::ad::{AdCx, Tangent, TransposeInput};
5use ruxla_ir::batching::{BatchCx, Batched};
6use ruxla_ir::lowering::{HloValue, LowerCx, i64_array};
7use ruxla_ir::{
8    AVal, ConvDims, DType, Error, EvalCx, HostArray, Params, Precision, Prim, Primitive, Result,
9    Shape, Value,
10};
11use ruxla_kernels::window::{self as w, ConvWindow};
12use ruxla_kernels::{Buffer, with_buffer};
13
14use crate::ad::{self as adh, add_tangents, convert};
15use crate::batching::{self, literal};
16use crate::structural::{BROADCAST_IN_DIM, RESHAPE, REV, TRANSPOSE};
17use crate::util::{arity, wrong_params};
18
19/// `conv_general_dilated`.
20#[derive(Debug)]
21pub(crate) struct ConvGeneralDilated;
22
23/// A convolution with strides, padding, input and kernel dilation, and
24/// feature and batch groups ([`Params::ConvGeneralDilated`]), as XLA's
25/// `Conv`.
26pub static CONV_GENERAL_DILATED: Prim = Prim::new(&ConvGeneralDilated);
27
28/// The parameters of `conv_general_dilated`, borrowed.
29#[derive(Clone, Copy)]
30pub(crate) struct Conv<'a> {
31    pub(crate) window_strides: &'a [usize],
32    pub(crate) padding: &'a [(i64, i64)],
33    pub(crate) lhs_dilation: &'a [usize],
34    pub(crate) rhs_dilation: &'a [usize],
35    pub(crate) dims: &'a ConvDims,
36    pub(crate) feature_group_count: usize,
37    pub(crate) batch_group_count: usize,
38    pub(crate) precision: Precision,
39    pub(crate) preferred_element_type: Option<DType>,
40}
41
42impl Conv<'_> {
43    fn from_params(params: &Params) -> Result<Conv<'_>> {
44        match params {
45            Params::ConvGeneralDilated {
46                window_strides,
47                padding,
48                lhs_dilation,
49                rhs_dilation,
50                dimension_numbers,
51                feature_group_count,
52                batch_group_count,
53                precision,
54                preferred_element_type,
55            } => Ok(Conv {
56                window_strides,
57                padding,
58                lhs_dilation,
59                rhs_dilation,
60                dims: dimension_numbers,
61                feature_group_count: *feature_group_count,
62                batch_group_count: *batch_group_count,
63                precision: *precision,
64                preferred_element_type: *preferred_element_type,
65            }),
66            _ => Err(wrong_params("conv_general_dilated")),
67        }
68    }
69
70    fn window(&self) -> ConvWindow<'_> {
71        ConvWindow {
72            strides: self.window_strides,
73            padding: self.padding,
74            lhs_dilation: self.lhs_dilation,
75            rhs_dilation: self.rhs_dilation,
76        }
77    }
78}
79
80/// Builds the parameters of `conv_general_dilated`.
81#[allow(clippy::too_many_arguments)]
82pub(crate) fn conv_params(
83    window_strides: Vec<usize>,
84    padding: Vec<(i64, i64)>,
85    lhs_dilation: Vec<usize>,
86    rhs_dilation: Vec<usize>,
87    dimension_numbers: ConvDims,
88    feature_group_count: usize,
89    batch_group_count: usize,
90    precision: Precision,
91    preferred_element_type: Option<DType>,
92) -> Params {
93    Params::ConvGeneralDilated {
94        window_strides,
95        padding,
96        lhs_dilation,
97        rhs_dilation,
98        dimension_numbers,
99        feature_group_count,
100        batch_group_count,
101        precision,
102        preferred_element_type,
103    }
104}
105
106fn is_permutation(spec: &[usize], rank: usize) -> bool {
107    let mut seen = vec![false; rank];
108    spec.len() == rank
109        && spec
110            .iter()
111            .all(|&d| d < rank && !std::mem::replace(&mut seen[d], true))
112}
113
114/// Checks the operands and parameters as JAX's shape and dtype rules do,
115/// and returns the result.
116fn conv_check(lhs: &AVal, rhs: &AVal, c: &Conv<'_>) -> Result<AVal> {
117    let name = "conv_general_dilated";
118    let err = |m: String| Err(Error::type_error(name, m));
119    if lhs.dtype != rhs.dtype || lhs.dtype == DType::Bool {
120        return err(format!("cannot convolve {lhs} with {rhs}"));
121    }
122    if let Some(to) = c.preferred_element_type {
123        let from = lhs.dtype;
124        let compatible = if from.is_int() {
125            to.is_int() || to.is_float()
126        } else {
127            to.is_float()
128        };
129        if !compatible || to.size_in_bytes() < from.size_in_bytes() {
130            return err(format!("cannot compute a convolution of {from} as {to}"));
131        }
132    }
133    let rank = lhs.shape.rank();
134    if rhs.shape.rank() != rank || rank < 2 {
135        return err(format!(
136            "lhs and rhs must have the same rank of at least 2, got {lhs} and {rhs}"
137        ));
138    }
139    let d = c.dims;
140    if !is_permutation(&d.lhs_spec, rank)
141        || !is_permutation(&d.rhs_spec, rank)
142        || !is_permutation(&d.out_spec, rank)
143    {
144        return err(format!("invalid dimension numbers {d:?} for rank {rank}"));
145    }
146    let n = rank - 2;
147    if c.window_strides.len() != n
148        || c.padding.len() != n
149        || c.lhs_dilation.len() != n
150        || c.rhs_dilation.len() != n
151    {
152        return err(format!(
153            "window_strides, padding, lhs_dilation, and rhs_dilation need {n} entries"
154        ));
155    }
156    if c.window_strides
157        .iter()
158        .chain(c.lhs_dilation)
159        .chain(c.rhs_dilation)
160        .any(|&s| s == 0)
161    {
162        return err(String::from("strides and dilations must be positive"));
163    }
164    let (fgc, bgc) = (c.feature_group_count, c.batch_group_count);
165    if fgc == 0 || bgc == 0 {
166        return err(String::from(
167            "feature_group_count and batch_group_count must be positive",
168        ));
169    }
170    let lhs_features = lhs.shape[d.lhs_spec[1]];
171    let rhs_in = rhs.shape[d.rhs_spec[1]];
172    let rhs_out = rhs.shape[d.rhs_spec[0]];
173    if !lhs_features.is_multiple_of(fgc) {
174        return err(format!(
175            "feature_group_count must divide lhs feature dimension size, but {fgc} does not divide {lhs_features}"
176        ));
177    }
178    if lhs_features / fgc != rhs_in {
179        return err(format!(
180            "lhs feature dimension size divided by feature_group_count must equal the rhs input feature dimension size, but {lhs_features} // {fgc} != {rhs_in}"
181        ));
182    }
183    if !rhs_out.is_multiple_of(fgc) {
184        return err(format!(
185            "rhs output feature dimension size must be a multiple of feature_group_count, but {rhs_out} is not a multiple of {fgc}"
186        ));
187    }
188    let lhs_batch = lhs.shape[d.lhs_spec[0]];
189    if bgc > 1 && !lhs_batch.is_multiple_of(bgc) {
190        return err(format!(
191            "batch_group_count must divide lhs batch dimension size, but {bgc} does not divide {lhs_batch}"
192        ));
193    }
194    if !rhs_out.is_multiple_of(bgc) {
195        return err(format!(
196            "rhs output feature dimension size must be a multiple of batch_group_count, but {rhs_out} is not a multiple of {bgc}"
197        ));
198    }
199    if bgc > 1 && fgc > 1 {
200        return err(format!(
201            "at most one of batch_group_count and feature_group_count may be > 1, got batch_group_count={bgc} and feature_group_count={fgc}"
202        ));
203    }
204    for k in 0..n {
205        let dilated = w::dilate_dim(lhs.shape[d.lhs_spec[2 + k]], c.lhs_dilation[k]) as i64;
206        let (lo, hi) = c.padding[k];
207        if dilated + lo + hi < 0 {
208            return err(format!(
209                "negative padding {:?} is larger than the size of the dimension",
210                c.padding[k]
211            ));
212        }
213    }
214    let shape = w::conv_shape(&lhs.shape, &rhs.shape, &c.window(), d, bgc);
215    Ok(AVal::new(
216        shape,
217        c.preferred_element_type.unwrap_or(lhs.dtype),
218    ))
219}
220
221/// Formats `(low, high)` pairs as a `tensor<Nx2xi64>` attribute.
222pub(crate) fn padding_attr(padding: &[(i64, i64)]) -> String {
223    if padding.is_empty() {
224        return String::from("dense<> : tensor<0x2xi64>");
225    }
226    let rows: Vec<String> = padding
227        .iter()
228        .map(|(lo, hi)| format!("[{lo}, {hi}]"))
229        .collect();
230    format!(
231        "dense<[{}]> : tensor<{}x2xi64>",
232        rows.join(", "),
233        padding.len()
234    )
235}
236
237/// Applies a primitive with one output, in a batching or a differentiation
238/// context.
239pub(crate) trait Emit {
240    /// Applies `prim`.
241    fn emit(&mut self, prim: Prim, inputs: &[Atom], params: Params) -> Result<Atom>;
242}
243
244impl Emit for dyn BatchCx + '_ {
245    fn emit(&mut self, prim: Prim, inputs: &[Atom], params: Params) -> Result<Atom> {
246        batching::bind1(self, prim, inputs, params)
247    }
248}
249
250impl Emit for dyn AdCx + '_ {
251    fn emit(&mut self, prim: Prim, inputs: &[Atom], params: Params) -> Result<Atom> {
252        adh::bind1(self, prim, inputs, params)
253    }
254}
255
256/// JAX's `lax.reshape(x, new_sizes, dimensions)`: a transpose by
257/// `dimensions` (unless it is the identity), then a reshape (unless the
258/// shape is the same).
259fn reshape<C: Emit + ?Sized>(
260    cx: &mut C,
261    x: &Atom,
262    new_sizes: Vec<usize>,
263    dimensions: &[usize],
264) -> Result<Atom> {
265    let mut x = x.clone();
266    if dimensions.iter().enumerate().any(|(i, &d)| i != d) {
267        x = cx.emit(
268            TRANSPOSE,
269            &[x],
270            Params::Transpose {
271                permutation: dimensions.to_vec(),
272            },
273        )?;
274    }
275    if x.aval().shape.dims() == new_sizes.as_slice() {
276        return Ok(x);
277    }
278    cx.emit(
279        RESHAPE,
280        &[x],
281        Params::Reshape {
282            new_sizes: new_sizes.into(),
283        },
284    )
285}
286
287/// JAX's `_reshape_axis_into`: merges dimension `src` into dimension `dst`
288/// (numbered after `src` is removed) as its major part.
289pub(crate) fn reshape_axis_into<C: Emit + ?Sized>(
290    cx: &mut C,
291    src: usize,
292    dst: usize,
293    x: &Atom,
294) -> Result<Atom> {
295    let shape = x.aval().shape;
296    let rank = shape.rank();
297    let mut perm: Vec<usize> = (0..rank).filter(|&i| i != src).collect();
298    perm.insert(dst, src);
299    let mut new_shape: Vec<usize> = shape
300        .iter()
301        .enumerate()
302        .filter(|&(i, _)| i != src)
303        .map(|(_, &d)| d)
304        .collect();
305    new_shape[dst] *= shape[src];
306    reshape(cx, x, new_shape, &perm)
307}
308
309/// JAX's `_reshape_axis_out_of`: splits dimension `src` into `size1` and
310/// the rest.
311pub(crate) fn reshape_axis_out_of<C: Emit + ?Sized>(
312    cx: &mut C,
313    src: usize,
314    size1: usize,
315    x: &Atom,
316) -> Result<Atom> {
317    let mut shape = x.aval().shape.dims().to_vec();
318    let size2 = shape[src] / size1;
319    shape.splice(src..=src, [size1, size2]);
320    let rank = x.aval().shape.rank();
321    let identity: Vec<usize> = (0..rank).collect();
322    reshape(cx, x, shape, &identity)
323}
324
325fn dilate_shape(shape: &[usize], dilation: &[usize]) -> Vec<usize> {
326    shape
327        .iter()
328        .zip(dilation)
329        .map(|(&d, &k)| w::dilate_dim(d, k))
330        .collect()
331}
332
333fn take(shape: &[usize], dims: &[usize]) -> Vec<usize> {
334    dims.iter().map(|&d| shape[d]).collect()
335}
336
337/// JAX's `_conv_general_vjp_lhs_padding`.
338pub(crate) fn vjp_lhs_padding(
339    in_shape: &[usize],
340    window_dimensions: &[usize],
341    window_strides: &[usize],
342    out_shape: &[usize],
343    padding: &[(i64, i64)],
344    lhs_dilation: &[usize],
345    rhs_dilation: &[usize],
346) -> Vec<(i64, i64)> {
347    let lhs_dilated = dilate_shape(in_shape, lhs_dilation);
348    let rhs_dilated = dilate_shape(window_dimensions, rhs_dilation);
349    let out_dilated = dilate_shape(out_shape, window_strides);
350    (0..in_shape.len())
351        .map(|i| {
352            let before = rhs_dilated[i] as i64 - padding[i].0 - 1;
353            let after =
354                lhs_dilated[i] as i64 + rhs_dilated[i] as i64 - 1 - out_dilated[i] as i64 - before;
355            (before, after)
356        })
357        .collect()
358}
359
360/// JAX's `_conv_general_vjp_rhs_padding`.
361fn vjp_rhs_padding(
362    in_shape: &[usize],
363    window_dimensions: &[usize],
364    window_strides: &[usize],
365    out_shape: &[usize],
366    padding: &[(i64, i64)],
367    lhs_dilation: &[usize],
368    rhs_dilation: &[usize],
369) -> Vec<(i64, i64)> {
370    let lhs_dilated = dilate_shape(in_shape, lhs_dilation);
371    let rhs_dilated = dilate_shape(window_dimensions, rhs_dilation);
372    let out_dilated = dilate_shape(out_shape, window_strides);
373    (0..in_shape.len())
374        .map(|i| {
375            let lo = padding[i].0;
376            let from_lhs = out_dilated[i] as i64 - lhs_dilated[i] as i64;
377            let from_rhs = rhs_dilated[i] as i64 - lo - 1;
378            (lo, from_lhs + from_rhs)
379        })
380        .collect()
381}
382
383/// `(spec[1], spec[0], spec[2..])`.
384fn spec_transpose(spec: &[usize]) -> Vec<usize> {
385    let mut s = spec.to_vec();
386    s.swap(0, 1);
387    s
388}
389
390impl Primitive for ConvGeneralDilated {
391    fn name(&self) -> &'static str {
392        "conv_general_dilated"
393    }
394
395    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
396        arity(self.name(), inputs, 2)?;
397        let c = Conv::from_params(params)?;
398        Ok(vec![conv_check(&inputs[0], &inputs[1], &c)?])
399    }
400
401    fn eval(
402        &self,
403        _: &dyn EvalCx,
404        inputs: &[HostArray],
405        params: &Params,
406    ) -> Result<Vec<HostArray>> {
407        let c = Conv::from_params(params)?;
408        let out = conv_check(&inputs[0].aval(), &inputs[1].aval(), &c)?;
409        // The operands are converted to the result type, then convolved.
410        let (l, r) = (inputs[0].convert(out.dtype), inputs[1].convert(out.dtype));
411        let b = with_buffer!(l.buffer(), |a| Buffer::from_vec(w::conv_general_dilated(
412            a,
413            l.shape(),
414            r.as_slice().expect("same types"),
415            r.shape(),
416            &c.window(),
417            c.dims,
418            c.feature_group_count,
419            c.batch_group_count,
420        )));
421        Ok(vec![HostArray::from_buffer(b, out.shape)])
422    }
423
424    /// JAX's `_conv_general_dilated_batch_rule`.
425    fn batch(
426        &'static self,
427        cx: &mut dyn BatchCx,
428        inputs: &[Batched],
429        params: &Params,
430    ) -> Result<Vec<Batched>> {
431        let c = Conv::from_params(params)?;
432        let (lhs, rhs) = (&inputs[0], &inputs[1]);
433        let (lhs_spec, rhs_spec, out_spec) = (&c.dims.lhs_spec, &c.dims.rhs_spec, &c.dims.out_spec);
434        let with_groups = |fgc: usize, bgc: usize| {
435            conv_params(
436                c.window_strides.to_vec(),
437                c.padding.to_vec(),
438                c.lhs_dilation.to_vec(),
439                c.rhs_dilation.to_vec(),
440                c.dims.clone(),
441                fgc,
442                bgc,
443                c.precision,
444                c.preferred_element_type,
445            )
446        };
447        let size = cx.axis_size();
448        // Reshaping a batch of size 0 into a batch or feature dimension does
449        // not work: the result is an empty array.
450        if size == 0 {
451            let out = conv_check(&lhs.example_aval(), &rhs.example_aval(), &c)?;
452            let mut shape = vec![0];
453            shape.extend(out.shape.iter());
454            let zero = literal(out.dtype, Value::Int(0));
455            let full = batching::bind1(
456                cx,
457                BROADCAST_IN_DIM,
458                &[zero],
459                Params::BroadcastInDim {
460                    shape: Shape::from(shape),
461                    broadcast_dimensions: Vec::new(),
462                },
463            )?;
464            return Ok(vec![Batched::mapped(full, 0)]);
465        }
466        let (fgc, bgc) = (c.feature_group_count, c.batch_group_count);
467        let cx: &mut dyn BatchCx = cx;
468        match (lhs.bdim, rhs.bdim) {
469            (Some(lb), Some(rb)) => {
470                let (new_lhs, params) = if bgc > 1 {
471                    (
472                        reshape_axis_into(cx, lb, lhs_spec[0], &lhs.atom)?,
473                        with_groups(fgc, bgc * size),
474                    )
475                } else {
476                    (
477                        reshape_axis_into(cx, lb, lhs_spec[1], &lhs.atom)?,
478                        with_groups(fgc * size, bgc),
479                    )
480                };
481                let new_rhs = reshape_axis_into(cx, rb, rhs_spec[0], &rhs.atom)?;
482                let out = cx.emit(CONV_GENERAL_DILATED, &[new_lhs, new_rhs], params)?;
483                let out = reshape_axis_out_of(cx, out_spec[1], size, &out)?;
484                Ok(vec![Batched::mapped(out, out_spec[1])])
485            }
486            (Some(lb), None) => {
487                let new_lhs = if bgc == 1 {
488                    reshape_axis_into(cx, lb, lhs_spec[0], &lhs.atom)?
489                } else {
490                    let x = reshape_axis_out_of(
491                        cx,
492                        lhs_spec[0] + usize::from(lb <= lhs_spec[0]),
493                        bgc,
494                        &lhs.atom,
495                    )?;
496                    let x = reshape_axis_into(
497                        cx,
498                        lb + usize::from(lhs_spec[0] < lb),
499                        lhs_spec[0] + 1,
500                        &x,
501                    )?;
502                    reshape_axis_into(cx, lhs_spec[0], lhs_spec[0], &x)?
503                };
504                let out = cx.emit(
505                    CONV_GENERAL_DILATED,
506                    &[new_lhs, rhs.atom.clone()],
507                    with_groups(fgc, bgc),
508                )?;
509                let out = reshape_axis_out_of(cx, out_spec[0], size, &out)?;
510                Ok(vec![Batched::mapped(out, out_spec[0])])
511            }
512            (None, Some(rb)) => {
513                if fgc == 1 && bgc == 1 {
514                    let new_rhs = reshape_axis_into(cx, rb, rhs_spec[0], &rhs.atom)?;
515                    let out = cx.emit(
516                        CONV_GENERAL_DILATED,
517                        &[lhs.atom.clone(), new_rhs],
518                        with_groups(fgc, bgc),
519                    )?;
520                    let out = reshape_axis_out_of(cx, out_spec[1], size, &out)?;
521                    return Ok(vec![Batched::mapped(out, out_spec[1])]);
522                }
523                // Groups must stay outermost: they are factored out of the
524                // output features, the batch is merged into the rest, and
525                // the groups are put back (likewise in the result).
526                let groups = if fgc > 1 { fgc } else { bgc };
527                let r = reshape_axis_out_of(
528                    cx,
529                    rhs_spec[0] + usize::from(rb <= rhs_spec[0]),
530                    groups,
531                    &rhs.atom,
532                )?;
533                let r =
534                    reshape_axis_into(cx, rb + usize::from(rhs_spec[0] < rb), rhs_spec[0] + 1, &r)?;
535                let r = reshape_axis_into(cx, rhs_spec[0], rhs_spec[0], &r)?;
536                let out = cx.emit(
537                    CONV_GENERAL_DILATED,
538                    &[lhs.atom.clone(), r],
539                    with_groups(fgc, bgc),
540                )?;
541                let out = reshape_axis_out_of(cx, out_spec[1], groups, &out)?;
542                let out = reshape_axis_out_of(cx, out_spec[1] + 1, size, &out)?;
543                let out = reshape_axis_into(cx, out_spec[1], out_spec[1] + 1, &out)?;
544                Ok(vec![Batched::mapped(out, out_spec[1])])
545            }
546            (None, None) => Err(Error::Malformed(String::from(
547                "the batching rule of conv_general_dilated was called without batched operands",
548            ))),
549        }
550    }
551
552    fn lower(
553        &self,
554        cx: &mut dyn LowerCx,
555        inputs: &[HloValue],
556        params: &Params,
557        outputs: &[AVal],
558    ) -> Result<Vec<HloValue>> {
559        let c = Conv::from_params(params)?;
560        let d = c.dims;
561        let rank = d.lhs_spec.len();
562        // `[b, 0, 1, f]`: the role of each dimension of an operand.
563        let layout = |spec: &[usize], first: &str, second: &str| {
564            let mut names = vec![String::new(); rank];
565            names[spec[0]] = first.to_string();
566            names[spec[1]] = second.to_string();
567            for (k, &s) in spec[2..].iter().enumerate() {
568                names[s] = k.to_string();
569            }
570            format!("[{}]", names.join(", "))
571        };
572        let precision = match c.precision {
573            Precision::Default => "DEFAULT",
574            Precision::High => "HIGH",
575            Precision::Highest => "HIGHEST",
576        };
577        let n = rank - 2;
578        let reversal = if n == 0 {
579            String::from("array<i1>")
580        } else {
581            format!("array<i1: {}>", vec!["false"; n].join(", "))
582        };
583        let attrs = format!(
584            "batch_group_count = {} : i64, dimension_numbers = #stablehlo.conv<{}x{}->{}>, \
585             feature_group_count = {} : i64, lhs_dilation = {}, padding = {}, \
586             precision_config = [#stablehlo<precision {precision}>, #stablehlo<precision {precision}>], \
587             rhs_dilation = {}, window_reversal = {reversal}, window_strides = {}",
588            c.batch_group_count,
589            layout(&d.lhs_spec, "b", "f"),
590            layout(&d.rhs_spec, "o", "i"),
591            layout(&d.out_spec, "b", "f"),
592            c.feature_group_count,
593            i64_array(c.lhs_dilation),
594            padding_attr(c.padding),
595            i64_array(c.rhs_dilation),
596            i64_array(c.window_strides),
597        );
598        Ok(vec![cx.op1(
599            "stablehlo.convolution",
600            inputs,
601            &attrs,
602            &outputs[0],
603        )])
604    }
605
606    /// JAX's `ad.defbilinear`: `conv(tl, r) + conv(l, tr)`.
607    fn jvp(
608        &'static self,
609        cx: &mut dyn AdCx,
610        primals: &[Atom],
611        tangents: &[Tangent],
612        params: &Params,
613    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
614        let ans = adh::bind1(cx, CONV_GENERAL_DILATED, primals, params.clone())?;
615        let a = tangents[0]
616            .as_ref()
617            .map(|t| {
618                adh::bind1(
619                    cx,
620                    CONV_GENERAL_DILATED,
621                    &[t.clone(), primals[1].clone()],
622                    params.clone(),
623                )
624            })
625            .transpose()?;
626        let b = tangents[1]
627            .as_ref()
628            .map(|t| {
629                adh::bind1(
630                    cx,
631                    CONV_GENERAL_DILATED,
632                    &[primals[0].clone(), t.clone()],
633                    params.clone(),
634                )
635            })
636            .transpose()?;
637        Ok((vec![ans], vec![add_tangents(cx, a, b)?]))
638    }
639
640    /// JAX's `_conv_general_dilated_transpose_lhs` and
641    /// `_conv_general_dilated_transpose_rhs`.
642    fn transpose(
643        &'static self,
644        cx: &mut dyn AdCx,
645        cotangents: &[Tangent],
646        inputs: &[TransposeInput],
647        params: &Params,
648    ) -> Result<Vec<Tangent>> {
649        let c = Conv::from_params(params)?;
650        let Some(g) = &cotangents[0] else {
651            return Ok(vec![None, None]);
652        };
653        match (inputs[0].is_linear(), inputs[1].is_linear()) {
654            (true, false) => {
655                let lhs = transpose_lhs(cx, g, &inputs[0].aval(), inputs[1].constant(), &c)?;
656                Ok(vec![Some(lhs), None])
657            }
658            (false, true) => {
659                let rhs = transpose_rhs(cx, g, inputs[0].constant(), &inputs[1].aval(), &c)?;
660                Ok(vec![None, rhs])
661            }
662            _ => Err(Error::unsupported(
663                "conv_general_dilated",
664                "a convolution of two linear values is not linear",
665            )),
666        }
667    }
668}
669
670fn transpose_lhs(
671    cx: &mut dyn AdCx,
672    g: &Atom,
673    lhs: &AVal,
674    rhs: &Atom,
675    c: &Conv<'_>,
676) -> Result<Atom> {
677    let d = c.dims;
678    let rhs_shape = rhs.aval().shape;
679    let (lhs_sdims, rhs_sdims, out_sdims) = (&d.lhs_spec[2..], &d.rhs_spec[2..], &d.out_spec[2..]);
680    let t_rhs_spec = spec_transpose(&d.rhs_spec);
681    let mut fgc = c.feature_group_count;
682    let bgc = c.batch_group_count;
683    let mut rhs = rhs.clone();
684    if fgc > 1 {
685        rhs = reshape_axis_out_of(cx, d.rhs_spec[0], fgc, &rhs)?;
686        rhs = reshape_axis_into(cx, d.rhs_spec[0], d.rhs_spec[1], &rhs)?;
687    } else if bgc > 1 {
688        rhs = reshape_axis_out_of(cx, d.rhs_spec[0], bgc, &rhs)?;
689        rhs = reshape_axis_into(cx, d.rhs_spec[0], d.rhs_spec[1], &rhs)?;
690        fgc = bgc;
691    }
692    let dims = ConvDims {
693        lhs_spec: d.out_spec.clone(),
694        rhs_spec: t_rhs_spec,
695        out_spec: d.lhs_spec.clone(),
696    };
697    let padding = vjp_lhs_padding(
698        &take(&lhs.shape, lhs_sdims),
699        &take(&rhs_shape, rhs_sdims),
700        c.window_strides,
701        &take(&g.aval().shape, out_sdims),
702        c.padding,
703        c.lhs_dilation,
704        c.rhs_dilation,
705    );
706    let revd = adh::bind1(
707        cx,
708        REV,
709        &[rhs],
710        Params::Rev {
711            dimensions: rhs_sdims.to_vec(),
712        },
713    )?;
714    let revd = convert(cx, &revd, g.aval().dtype)?;
715    let out = adh::bind1(
716        cx,
717        CONV_GENERAL_DILATED,
718        &[g.clone(), revd],
719        conv_params(
720            c.lhs_dilation.to_vec(),
721            padding,
722            c.window_strides.to_vec(),
723            c.rhs_dilation.to_vec(),
724            dims,
725            fgc,
726            1,
727            c.precision,
728            c.preferred_element_type,
729        ),
730    )?;
731    let mut out = convert(cx, &out, lhs.dtype)?;
732    if bgc > 1 {
733        out = reshape_axis_out_of(cx, d.lhs_spec[1], bgc, &out)?;
734        out = reshape_axis_into(cx, d.lhs_spec[1], d.lhs_spec[0], &out)?;
735    }
736    Ok(out)
737}
738
739fn transpose_rhs(
740    cx: &mut dyn AdCx,
741    g: &Atom,
742    lhs: &Atom,
743    rhs: &AVal,
744    c: &Conv<'_>,
745) -> Result<Tangent> {
746    let g_aval = g.aval();
747    if g_aval.shape.size() == 0 {
748        // Avoids convolutions whose kernel has spatial size 0.
749        return Ok(None);
750    }
751    let d = c.dims;
752    let lhs_shape = lhs.aval().shape;
753    let (lhs_sdims, rhs_sdims, out_sdims) = (&d.lhs_spec[2..], &d.rhs_spec[2..], &d.out_spec[2..]);
754    let (mut fgc, mut bgc) = (c.feature_group_count, c.batch_group_count);
755    if bgc > 1 {
756        fgc = bgc;
757        bgc = 1;
758    } else if fgc > 1 {
759        bgc = fgc;
760        fgc = 1;
761    }
762    let dims = ConvDims {
763        lhs_spec: spec_transpose(&d.lhs_spec),
764        rhs_spec: spec_transpose(&d.out_spec),
765        out_spec: spec_transpose(&d.rhs_spec),
766    };
767    let padding = vjp_rhs_padding(
768        &take(&lhs_shape, lhs_sdims),
769        &take(&rhs.shape, rhs_sdims),
770        c.window_strides,
771        &take(&g_aval.shape, out_sdims),
772        c.padding,
773        c.lhs_dilation,
774        c.rhs_dilation,
775    );
776    let lhs = convert(cx, lhs, g_aval.dtype)?;
777    let out = adh::bind1(
778        cx,
779        CONV_GENERAL_DILATED,
780        &[lhs, g.clone()],
781        conv_params(
782            c.rhs_dilation.to_vec(),
783            padding,
784            c.lhs_dilation.to_vec(),
785            c.window_strides.to_vec(),
786            dims,
787            fgc,
788            bgc,
789            c.precision,
790            c.preferred_element_type,
791        ),
792    )?;
793    Ok(Some(convert(cx, &out, rhs.dtype)?))
794}