1use std::sync::Arc;
7
8use ruxla_ir::ad::{AdCx, Tangent, TransposeInput};
9use ruxla_ir::batching::{BatchCx, Batched};
10use ruxla_ir::lowering::{HloValue, LowerCx};
11use ruxla_ir::{AVal, Atom, Error, EvalCx, Function, HostArray, Params, Prim, Primitive, Result};
12
13use crate::ad::instantiate;
14use crate::batching::bdim_at_front;
15use crate::control::JIT;
16use crate::util::wrong_params;
17
18fn called<'a>(prim: &'static str, params: &'a Params) -> Result<&'a Arc<Function>> {
20 match params {
21 Params::CustomJvp { call, .. } | Params::CustomVjp { call, .. } => Ok(call),
22 Params::Checkpoint { body } => Ok(body),
23 _ => Err(wrong_params(prim)),
24 }
25}
26
27fn check_inputs(prim: &'static str, inputs: &[AVal], f: &Function) -> Result<()> {
28 if inputs != f.in_avals().as_slice() {
29 return Err(Error::type_error(
30 prim,
31 format!(
32 "the arguments do not match the function's inputs {:?}",
33 f.in_avals()
34 ),
35 ));
36 }
37 Ok(())
38}
39
40fn lower_call(
42 cx: &mut dyn LowerCx,
43 f: &Function,
44 hint: &str,
45 inputs: &[HloValue],
46 outputs: &[AVal],
47) -> Result<Vec<HloValue>> {
48 let symbol = cx.function(f, hint)?;
49 Ok(cx.op("func.call", inputs, &format!("callee = @{symbol}"), outputs))
50}
51
52fn batched_inputs(cx: &mut dyn BatchCx, inputs: &[Batched]) -> Result<Vec<Atom>> {
56 inputs.iter().map(|x| bdim_at_front(cx, x)).collect()
57}
58
59fn batch_all(cx: &mut dyn BatchCx, f: &Function) -> Result<Arc<Function>> {
61 let in_axes = vec![Some(0); f.invars.len()];
62 let force = vec![Some(true); f.outvars.len()];
63 Ok(Arc::new(cx.batch_function(f, &in_axes, &force)?.0))
64}
65
66fn all_batched(outs: Vec<Atom>) -> Vec<Batched> {
67 outs.into_iter()
68 .map(|atom| Batched {
69 atom,
70 bdim: Some(0),
71 })
72 .collect()
73}
74
75#[derive(Debug)]
77pub(crate) struct CustomJvpCall;
78pub static CUSTOM_JVP_CALL: Prim = Prim::new(&CustomJvpCall);
81
82impl Primitive for CustomJvpCall {
83 fn name(&self) -> &'static str {
84 "custom_jvp_call"
85 }
86 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
87 let Params::CustomJvp { call, jvp, .. } = params else {
88 return Err(wrong_params(self.name()));
89 };
90 check_inputs(self.name(), inputs, call)?;
91 let mut jvp_in = inputs.to_vec();
92 jvp_in.extend(inputs.iter().cloned());
93 jvp_in.drain(inputs.len()..inputs.len() + num_consts(params));
94 let mut jvp_out = call.out_avals();
95 jvp_out.extend(call.out_avals());
96 if jvp.in_avals() != jvp_in || jvp.out_avals() != jvp_out {
97 return Err(Error::type_error(
98 self.name(),
99 "the JVP function does not match the function",
100 ));
101 }
102 Ok(call.out_avals())
103 }
104 fn eval(
105 &self,
106 cx: &dyn EvalCx,
107 inputs: &[HostArray],
108 params: &Params,
109 ) -> Result<Vec<HostArray>> {
110 cx.eval_function(called(self.name(), params)?, inputs)
111 }
112 fn batch(
113 &'static self,
114 cx: &mut dyn BatchCx,
115 inputs: &[Batched],
116 params: &Params,
117 ) -> Result<Vec<Batched>> {
118 let Params::CustomJvp {
119 call,
120 jvp,
121 num_consts,
122 } = params
123 else {
124 return Err(wrong_params(self.name()));
125 };
126 let atoms = batched_inputs(cx, inputs)?;
127 let params = Params::CustomJvp {
128 call: batch_all(cx, call)?,
129 jvp: batch_all(cx, jvp)?,
130 num_consts: *num_consts,
131 };
132 Ok(all_batched(cx.bind(CUSTOM_JVP_CALL, &atoms, params)?))
133 }
134 fn lower(
135 &self,
136 cx: &mut dyn LowerCx,
137 inputs: &[HloValue],
138 params: &Params,
139 outputs: &[AVal],
140 ) -> Result<Vec<HloValue>> {
141 lower_call(
142 cx,
143 called(self.name(), params)?,
144 "custom_jvp_call",
145 inputs,
146 outputs,
147 )
148 }
149 fn jvp(
150 &'static self,
151 cx: &mut dyn AdCx,
152 primals: &[Atom],
153 tangents: &[Tangent],
154 params: &Params,
155 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
156 let Params::CustomJvp {
157 call,
158 jvp,
159 num_consts,
160 } = params
161 else {
162 return Err(wrong_params(self.name()));
163 };
164 if tangents[..*num_consts].iter().any(Option::is_some) {
165 return Err(Error::unsupported(
166 self.name(),
167 "differentiating a value that a custom_jvp function captured (pass it as an argument)",
168 ));
169 }
170 let mut args = primals.to_vec();
173 for (t, p) in tangents.iter().zip(primals).skip(*num_consts) {
174 args.push(instantiate(cx, t, &p.aval())?);
175 }
176 let mut outs = cx.bind(
177 JIT,
178 &args,
179 Params::Jit {
180 name: String::from("custom_jvp"),
181 body: jvp.clone(),
182 },
183 )?;
184 let touts = outs
185 .split_off(call.outvars.len())
186 .into_iter()
187 .map(Some)
188 .collect();
189 Ok((outs, touts))
190 }
191}
192
193fn num_consts(params: &Params) -> usize {
194 match params {
195 Params::CustomJvp { num_consts, .. } | Params::CustomVjp { num_consts, .. } => *num_consts,
196 _ => 0,
197 }
198}
199
200#[derive(Debug)]
202pub(crate) struct CustomVjpCall;
203pub static CUSTOM_VJP_CALL: Prim = Prim::new(&CustomVjpCall);
206
207impl Primitive for CustomVjpCall {
208 fn name(&self) -> &'static str {
209 "custom_vjp_call"
210 }
211 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
212 let Params::CustomVjp {
213 call,
214 fwd,
215 bwd,
216 num_consts,
217 } = params
218 else {
219 return Err(wrong_params(self.name()));
220 };
221 check_inputs(self.name(), inputs, call)?;
222 check_inputs(self.name(), inputs, fwd)?;
223 let outs = call.out_avals();
224 let fwd_out = fwd.out_avals();
225 if fwd_out.len() < outs.len() || fwd_out[..outs.len()] != outs[..] {
226 return Err(Error::type_error(
227 self.name(),
228 "the forward function does not return the outputs first",
229 ));
230 }
231 let mut bwd_in = fwd_out[outs.len()..].to_vec();
232 bwd_in.extend(outs.iter().cloned());
233 if bwd.in_avals() != bwd_in || bwd.out_avals() != inputs[*num_consts..] {
234 return Err(Error::type_error(
235 self.name(),
236 "the backward function does not match",
237 ));
238 }
239 Ok(outs)
240 }
241 fn eval(
242 &self,
243 cx: &dyn EvalCx,
244 inputs: &[HostArray],
245 params: &Params,
246 ) -> Result<Vec<HostArray>> {
247 cx.eval_function(called(self.name(), params)?, inputs)
248 }
249 fn batch(
250 &'static self,
251 cx: &mut dyn BatchCx,
252 inputs: &[Batched],
253 params: &Params,
254 ) -> Result<Vec<Batched>> {
255 let Params::CustomVjp {
256 call,
257 fwd,
258 bwd,
259 num_consts,
260 } = params
261 else {
262 return Err(wrong_params(self.name()));
263 };
264 let atoms = batched_inputs(cx, inputs)?;
265 let params = Params::CustomVjp {
266 call: batch_all(cx, call)?,
267 fwd: batch_all(cx, fwd)?,
268 bwd: batch_all(cx, bwd)?,
269 num_consts: *num_consts,
270 };
271 Ok(all_batched(cx.bind(CUSTOM_VJP_CALL, &atoms, params)?))
272 }
273 fn lower(
274 &self,
275 cx: &mut dyn LowerCx,
276 inputs: &[HloValue],
277 params: &Params,
278 outputs: &[AVal],
279 ) -> Result<Vec<HloValue>> {
280 lower_call(
281 cx,
282 called(self.name(), params)?,
283 "custom_vjp_call",
284 inputs,
285 outputs,
286 )
287 }
288 fn jvp(
292 &'static self,
293 cx: &mut dyn AdCx,
294 primals: &[Atom],
295 tangents: &[Tangent],
296 params: &Params,
297 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
298 let Params::CustomVjp {
299 call,
300 fwd,
301 bwd,
302 num_consts,
303 } = params
304 else {
305 return Err(wrong_params(self.name()));
306 };
307 if tangents[..*num_consts].iter().any(Option::is_some) {
308 return Err(Error::unsupported(
309 self.name(),
310 "differentiating a value that a custom_vjp function captured (pass it as an argument)",
311 ));
312 }
313 let mut outs = cx.bind(
314 JIT,
315 primals,
316 Params::Jit {
317 name: String::from("custom_vjp_fwd"),
318 body: fwd.clone(),
319 },
320 )?;
321 let res = outs.split_off(call.outvars.len());
322 let num_res = res.len();
323 let mut args = res;
324 for (t, p) in tangents.iter().zip(primals).skip(*num_consts) {
325 args.push(instantiate(cx, t, &p.aval())?);
326 }
327 let touts = cx
328 .bind(
329 CUSTOM_LIN,
330 &args,
331 Params::CustomLin {
332 bwd: bwd.clone(),
333 num_res,
334 },
335 )?
336 .into_iter()
337 .map(Some)
338 .collect();
339 Ok((outs, touts))
340 }
341}
342
343#[derive(Debug)]
345pub(crate) struct CustomLin;
346pub static CUSTOM_LIN: Prim = Prim::new(&CustomLin);
351
352impl Primitive for CustomLin {
353 fn name(&self) -> &'static str {
354 "custom_lin"
355 }
356 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
357 let Params::CustomLin { bwd, num_res } = params else {
358 return Err(wrong_params(self.name()));
359 };
360 let bwd_in = bwd.in_avals();
361 if inputs.len() < *num_res
362 || inputs[..*num_res] != bwd_in[..*num_res]
363 || inputs[*num_res..] != bwd.out_avals()[..]
364 {
365 return Err(Error::type_error(
366 self.name(),
367 "the inputs do not match the backward function",
368 ));
369 }
370 Ok(bwd_in[*num_res..].to_vec())
371 }
372 fn eval(&self, _: &dyn EvalCx, _: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
373 Err(Error::unsupported(
374 self.name(),
375 "forward-mode differentiation of a custom_vjp function",
376 ))
377 }
378 fn batch(
379 &'static self,
380 cx: &mut dyn BatchCx,
381 inputs: &[Batched],
382 params: &Params,
383 ) -> Result<Vec<Batched>> {
384 let Params::CustomLin { bwd, num_res } = params else {
385 return Err(wrong_params(self.name()));
386 };
387 let atoms = batched_inputs(cx, inputs)?;
388 let params = Params::CustomLin {
389 bwd: batch_all(cx, bwd)?,
390 num_res: *num_res,
391 };
392 Ok(all_batched(cx.bind(CUSTOM_LIN, &atoms, params)?))
393 }
394 fn lower(
395 &self,
396 _: &mut dyn LowerCx,
397 _: &[HloValue],
398 _: &Params,
399 _: &[AVal],
400 ) -> Result<Vec<HloValue>> {
401 Err(Error::unsupported(
402 self.name(),
403 "forward-mode differentiation of a custom_vjp function",
404 ))
405 }
406 fn transpose(
407 &'static self,
408 cx: &mut dyn AdCx,
409 cotangents: &[Tangent],
410 inputs: &[TransposeInput],
411 params: &Params,
412 ) -> Result<Vec<Tangent>> {
413 let Params::CustomLin { bwd, num_res } = params else {
414 return Err(wrong_params(self.name()));
415 };
416 if inputs[..*num_res].iter().any(TransposeInput::is_linear) {
417 return Err(Error::Malformed(String::from(
418 "custom_lin: a residual is linear",
419 )));
420 }
421 let mut args: Vec<Atom> = inputs[..*num_res]
422 .iter()
423 .map(|x| x.constant().clone())
424 .collect();
425 for (ct, a) in cotangents.iter().zip(bwd.in_avals()[*num_res..].iter()) {
426 args.push(instantiate(cx, ct, a)?);
427 }
428 let cts = cx.bind(
429 JIT,
430 &args,
431 Params::Jit {
432 name: String::from("custom_vjp_bwd"),
433 body: bwd.clone(),
434 },
435 )?;
436 let mut result = vec![None; *num_res];
437 result.extend(
438 cts.into_iter()
439 .zip(&inputs[*num_res..])
440 .map(|(c, x)| x.is_linear().then_some(c)),
441 );
442 Ok(result)
443 }
444}
445
446#[derive(Debug)]
448pub(crate) struct Checkpoint;
449pub static CHECKPOINT: Prim = Prim::new(&Checkpoint);
452
453impl Primitive for Checkpoint {
454 fn name(&self) -> &'static str {
455 "checkpoint"
456 }
457 fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
458 let body = called(self.name(), params)?;
459 check_inputs(self.name(), inputs, body)?;
460 Ok(body.out_avals())
461 }
462 fn eval(
463 &self,
464 cx: &dyn EvalCx,
465 inputs: &[HostArray],
466 params: &Params,
467 ) -> Result<Vec<HostArray>> {
468 cx.eval_function(called(self.name(), params)?, inputs)
469 }
470 fn batch(
471 &'static self,
472 cx: &mut dyn BatchCx,
473 inputs: &[Batched],
474 params: &Params,
475 ) -> Result<Vec<Batched>> {
476 let body = called(self.name(), params)?;
477 let in_axes: Vec<Option<usize>> = inputs.iter().map(|x| x.bdim).collect();
478 let force = vec![None; body.outvars.len()];
479 let (body, batched) = cx.batch_function(body, &in_axes, &force)?;
480 let atoms: Vec<Atom> = inputs.iter().map(|x| x.atom.clone()).collect();
481 let outs = cx.bind(
482 CHECKPOINT,
483 &atoms,
484 Params::Checkpoint {
485 body: Arc::new(body),
486 },
487 )?;
488 Ok(outs
489 .into_iter()
490 .zip(batched)
491 .map(|(atom, b)| Batched {
492 atom,
493 bdim: b.then_some(0),
494 })
495 .collect())
496 }
497 fn lower(
498 &self,
499 cx: &mut dyn LowerCx,
500 inputs: &[HloValue],
501 params: &Params,
502 outputs: &[AVal],
503 ) -> Result<Vec<HloValue>> {
504 lower_call(
505 cx,
506 called(self.name(), params)?,
507 "checkpoint",
508 inputs,
509 outputs,
510 )
511 }
512 fn jvp(
514 &'static self,
515 cx: &mut dyn AdCx,
516 primals: &[Atom],
517 tangents: &[Tangent],
518 params: &Params,
519 ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
520 let body = called(self.name(), params)?;
521 let nonzero: Vec<bool> = tangents.iter().map(Option::is_some).collect();
522 let n = body.outvars.len();
523 let (g, out_nz) = cx.jvp_function(body, &nonzero, &vec![false; n])?;
524 let mut args = primals.to_vec();
525 args.extend(tangents.iter().flatten().cloned());
526 let mut outs = cx.bind(CHECKPOINT, &args, Params::Checkpoint { body: Arc::new(g) })?;
527 let mut ts = outs.split_off(n).into_iter();
528 let touts = out_nz
529 .iter()
530 .map(|&nz| if nz { ts.next() } else { None })
531 .collect();
532 Ok((outs, touts))
533 }
534 fn transpose(
536 &'static self,
537 cx: &mut dyn AdCx,
538 cotangents: &[Tangent],
539 inputs: &[TransposeInput],
540 params: &Params,
541 ) -> Result<Vec<Tangent>> {
542 let body = called(self.name(), params)?;
543 if cotangents.iter().all(Option::is_none) {
544 return Ok(vec![None; inputs.len()]);
545 }
546 let linear: Vec<bool> = inputs.iter().map(TransposeInput::is_linear).collect();
547 let t = cx.transpose_function(body, &linear)?;
548 let mut args: Vec<Atom> = inputs
549 .iter()
550 .filter(|x| !x.is_linear())
551 .map(|x| x.constant().clone())
552 .collect();
553 for (ct, a) in cotangents.iter().zip(body.out_avals()) {
554 args.push(instantiate(cx, ct, &a)?);
555 }
556 let mut cts = cx
557 .bind(CHECKPOINT, &args, Params::Checkpoint { body: Arc::new(t) })?
558 .into_iter();
559 Ok(linear
560 .iter()
561 .map(|&l| if l { cts.next() } else { None })
562 .collect())
563 }
564}