Skip to main content

ruxla_ir/
serialize.rs

1//! A binary serialization of functions.
2//!
3//! The format starts with the magic bytes `RXIR` and a format version.
4//! Variables are numbered in order of first appearance, so functions that
5//! differ only in variable ids serialize to the same bytes (usable as cache
6//! keys); they get fresh ids when read back. Primitives are stored by name
7//! and resolved with a lookup function (normally `ruxla_prims::by_name`).
8//!
9//! # Examples
10//!
11//! ```
12//! use ruxla_ir::{AVal, DType, Function, Var, serialize};
13//!
14//! let x = Var::new(AVal::new([2], DType::F32));
15//! let f = Function { invars: vec![x.clone()], outvars: vec![x.into()], ..Function::default() };
16//! let g = serialize::from_bytes(&serialize::to_bytes(&f), &|_| None).unwrap();
17//! assert_eq!(g.to_string(), f.to_string());
18//! ```
19
20use std::collections::HashMap;
21use std::sync::Arc;
22
23use ruxla_kernels::DType;
24use ruxla_kernels::array::{DotDims, GatherDims, GatherScatterMode, ScatterDims};
25use ruxla_kernels::fft::FftType;
26use ruxla_kernels::window::ConvDims;
27
28use crate::error::{Error, Result};
29use crate::function::{
30    Atom, EighImplementation, Eqn, Function, Literal, Params, Precision, RoundingMethod,
31    SelectPrim, SvdAlgorithm, Var,
32};
33use crate::host::HostArray;
34use crate::primitive::Prim;
35use crate::shape::{AVal, Shape};
36
37const MAGIC: &[u8; 4] = b"RXIR";
38
39/// The version of the format written by [`to_bytes`].
40pub const FORMAT_VERSION: u32 = 1;
41
42/// Serializes a function.
43pub fn to_bytes(f: &Function) -> Vec<u8> {
44    let mut w = Writer::default();
45    w.buf.extend_from_slice(MAGIC);
46    w.u32(FORMAT_VERSION);
47    w.function(f);
48    w.buf
49}
50
51/// Reads a function written by [`to_bytes`], resolving primitives by name.
52///
53/// # Errors
54///
55/// Returns [`Error::Malformed`] if the bytes are not a function of this
56/// format version, or name an unknown primitive.
57pub fn from_bytes(bytes: &[u8], lookup: &dyn Fn(&str) -> Option<Prim>) -> Result<Function> {
58    let mut r = Reader {
59        bytes,
60        pos: 0,
61        vars: HashMap::new(),
62        lookup,
63    };
64    if r.take(4)? != MAGIC {
65        return Err(Error::Malformed(String::from(
66            "not a serialized ruxla function",
67        )));
68    }
69    let version = r.u32()?;
70    if version != FORMAT_VERSION {
71        return Err(Error::Malformed(format!(
72            "format version {version}; this build reads version {FORMAT_VERSION}"
73        )));
74    }
75    let f = r.function()?;
76    if r.pos != bytes.len() {
77        return Err(Error::Malformed(String::from("trailing bytes")));
78    }
79    Ok(f)
80}
81
82#[derive(Default)]
83struct Writer {
84    buf: Vec<u8>,
85    vars: HashMap<u64, u64>,
86}
87
88impl Writer {
89    fn u8(&mut self, v: u8) {
90        self.buf.push(v);
91    }
92    fn u32(&mut self, v: u32) {
93        self.buf.extend_from_slice(&v.to_le_bytes());
94    }
95    fn u64(&mut self, v: u64) {
96        self.buf.extend_from_slice(&v.to_le_bytes());
97    }
98    fn i64(&mut self, v: i64) {
99        self.buf.extend_from_slice(&v.to_le_bytes());
100    }
101    fn usize(&mut self, v: usize) {
102        self.u64(v as u64);
103    }
104    fn bool(&mut self, v: bool) {
105        self.u8(u8::from(v));
106    }
107    fn usizes(&mut self, v: &[usize]) {
108        self.usize(v.len());
109        v.iter().for_each(|&x| self.usize(x));
110    }
111    fn pairs(&mut self, v: &[(i64, i64)]) {
112        self.usize(v.len());
113        for &(lo, hi) in v {
114            self.i64(lo);
115            self.i64(hi);
116        }
117    }
118    fn precision(&mut self, p: Precision) {
119        self.u8(match p {
120            Precision::Default => 0,
121            Precision::High => 1,
122            Precision::Highest => 2,
123        });
124    }
125    fn opt_dtype(&mut self, d: Option<DType>) {
126        match d {
127            None => self.u8(0),
128            Some(d) => {
129                self.u8(1);
130                self.dtype(d);
131            }
132        }
133    }
134    fn select_prim(&mut self, p: SelectPrim) {
135        self.u8(match p {
136            SelectPrim::Ge => 0,
137            SelectPrim::Le => 1,
138        });
139    }
140    fn str(&mut self, s: &str) {
141        self.usize(s.len());
142        self.buf.extend_from_slice(s.as_bytes());
143    }
144    fn dtype(&mut self, d: DType) {
145        self.str(d.name());
146    }
147    fn aval(&mut self, a: &AVal) {
148        self.dtype(a.dtype);
149        self.usizes(&a.shape);
150    }
151    fn var(&mut self, v: &Var) {
152        let next = self.vars.len() as u64;
153        let i = *self.vars.entry(v.id()).or_insert(next);
154        self.u64(i);
155        self.aval(v.aval());
156    }
157    fn host(&mut self, h: &HostArray) {
158        self.aval(&h.aval());
159        // Elements in little-endian order.
160        let size = h.dtype().size_in_bytes();
161        let mut bytes = h.to_bytes();
162        if cfg!(target_endian = "big") {
163            bytes.chunks_exact_mut(size).for_each(<[u8]>::reverse);
164        }
165        self.usize(bytes.len());
166        self.buf.extend_from_slice(&bytes);
167    }
168    fn atom(&mut self, a: &Atom) {
169        match a {
170            Atom::Var(v) => {
171                self.u8(0);
172                self.var(v);
173            }
174            Atom::Lit(l) => {
175                self.u8(1);
176                self.host(l.value());
177            }
178        }
179    }
180    fn function(&mut self, f: &Function) {
181        self.usize(f.constvars.len());
182        for (v, h) in &f.constvars {
183            self.var(v);
184            self.host(h);
185        }
186        self.usize(f.invars.len());
187        f.invars.iter().for_each(|v| self.var(v));
188        self.usize(f.eqns.len());
189        for e in &f.eqns {
190            self.str(e.prim.name());
191            self.usize(e.inputs.len());
192            e.inputs.iter().for_each(|a| self.atom(a));
193            self.params(&e.params);
194            self.usize(e.outputs.len());
195            e.outputs.iter().for_each(|v| self.var(v));
196        }
197        self.usize(f.outvars.len());
198        f.outvars.iter().for_each(|a| self.atom(a));
199    }
200    fn mode(&mut self, m: GatherScatterMode) {
201        self.u8(match m {
202            GatherScatterMode::Clip => 0,
203            GatherScatterMode::FillOrDrop => 1,
204            GatherScatterMode::PromiseInBounds => 2,
205        });
206    }
207    fn params(&mut self, p: &Params) {
208        match p {
209            Params::None => self.u8(0),
210            Params::Convert { new_dtype } => {
211                self.u8(1);
212                self.dtype(*new_dtype);
213            }
214            Params::Round { method } => {
215                self.u8(2);
216                self.bool(*method == RoundingMethod::ToNearestEven);
217            }
218            Params::IntegerPow { y } => {
219                self.u8(3);
220                self.i64(i64::from(*y));
221            }
222            Params::BroadcastInDim {
223                shape,
224                broadcast_dimensions,
225            } => {
226                self.u8(4);
227                self.usizes(shape);
228                self.usizes(broadcast_dimensions);
229            }
230            Params::Reshape { new_sizes } => {
231                self.u8(5);
232                self.usizes(new_sizes);
233            }
234            Params::Transpose { permutation } => {
235                self.u8(6);
236                self.usizes(permutation);
237            }
238            Params::Reduce { axes } => {
239                self.u8(7);
240                self.usizes(axes);
241            }
242            Params::ArgMinMax { axis, index_dtype } => {
243                self.u8(8);
244                self.usize(*axis);
245                self.dtype(*index_dtype);
246            }
247            Params::DotGeneral {
248                dimension_numbers: d,
249                precision,
250                preferred_element_type,
251            } => {
252                self.u8(9);
253                for v in [
254                    &d.lhs_contracting,
255                    &d.rhs_contracting,
256                    &d.lhs_batch,
257                    &d.rhs_batch,
258                ] {
259                    self.usizes(v);
260                }
261                self.u8(match precision {
262                    Precision::Default => 0,
263                    Precision::High => 1,
264                    Precision::Highest => 2,
265                });
266                match preferred_element_type {
267                    None => self.u8(0),
268                    Some(d) => {
269                        self.u8(1);
270                        self.dtype(*d);
271                    }
272                }
273            }
274            Params::Iota {
275                dtype,
276                shape,
277                dimension,
278            } => {
279                self.u8(10);
280                self.dtype(*dtype);
281                self.usizes(shape);
282                self.usize(*dimension);
283            }
284            Params::Slice {
285                start_indices,
286                limit_indices,
287                strides,
288            } => {
289                self.u8(11);
290                self.usizes(start_indices);
291                self.usizes(limit_indices);
292                self.usizes(strides);
293            }
294            Params::DynamicSlice { slice_sizes } => {
295                self.u8(12);
296                self.usizes(slice_sizes);
297            }
298            Params::Concatenate { dimension } => {
299                self.u8(13);
300                self.usize(*dimension);
301            }
302            Params::Pad { padding_config } => {
303                self.u8(14);
304                self.usize(padding_config.len());
305                for &(lo, hi, int) in padding_config {
306                    self.i64(lo);
307                    self.i64(hi);
308                    self.usize(int);
309                }
310            }
311            Params::Rev { dimensions } => {
312                self.u8(15);
313                self.usizes(dimensions);
314            }
315            Params::Sort {
316                dimension,
317                is_stable,
318                num_keys,
319            } => {
320                self.u8(23);
321                self.usize(*dimension);
322                self.bool(*is_stable);
323                self.usize(*num_keys);
324            }
325            Params::Cumulative { axis, reverse } => {
326                self.u8(40);
327                self.usize(*axis);
328                self.bool(*reverse);
329            }
330            Params::Fft {
331                fft_type,
332                fft_lengths,
333            } => {
334                self.u8(80);
335                self.u8(fft_type.index());
336                self.usizes(fft_lengths);
337            }
338            Params::TopK { k, axis, is_stable } => {
339                self.u8(41);
340                self.usize(*k);
341                self.usize(*axis);
342                self.bool(*is_stable);
343            }
344            Params::ConvGeneralDilated {
345                window_strides,
346                padding,
347                lhs_dilation,
348                rhs_dilation,
349                dimension_numbers: d,
350                feature_group_count,
351                batch_group_count,
352                precision,
353                preferred_element_type,
354            } => {
355                self.u8(50);
356                self.usizes(window_strides);
357                self.pairs(padding);
358                self.usizes(lhs_dilation);
359                self.usizes(rhs_dilation);
360                self.usizes(&d.lhs_spec);
361                self.usizes(&d.rhs_spec);
362                self.usizes(&d.out_spec);
363                self.usize(*feature_group_count);
364                self.usize(*batch_group_count);
365                self.precision(*precision);
366                self.opt_dtype(*preferred_element_type);
367            }
368            Params::ReduceWindow {
369                window_dimensions,
370                window_strides,
371                padding,
372                base_dilation,
373                window_dilation,
374            } => {
375                self.u8(51);
376                self.usizes(window_dimensions);
377                self.usizes(window_strides);
378                self.pairs(padding);
379                self.usizes(base_dilation);
380                self.usizes(window_dilation);
381            }
382            Params::SelectAndScatterAdd {
383                select_prim,
384                window_dimensions,
385                window_strides,
386                padding,
387            } => {
388                self.u8(52);
389                self.select_prim(*select_prim);
390                self.usizes(window_dimensions);
391                self.usizes(window_strides);
392                self.pairs(padding);
393            }
394            Params::SelectAndGatherAdd {
395                select_prim,
396                window_dimensions,
397                window_strides,
398                padding,
399                base_dilation,
400                window_dilation,
401            } => {
402                self.u8(53);
403                self.select_prim(*select_prim);
404                self.usizes(window_dimensions);
405                self.usizes(window_strides);
406                self.pairs(padding);
407                self.usizes(base_dilation);
408                self.usizes(window_dilation);
409            }
410            Params::TriangularSolve {
411                left_side,
412                lower,
413                transpose_a,
414                conjugate_a,
415                unit_diagonal,
416            } => {
417                self.u8(70);
418                self.bool(*left_side);
419                self.bool(*lower);
420                self.bool(*transpose_a);
421                self.bool(*conjugate_a);
422                self.bool(*unit_diagonal);
423            }
424            Params::LuPivotsToPermutation { permutation_size } => {
425                self.u8(71);
426                self.usize(*permutation_size);
427            }
428            Params::Qr {
429                full_matrices,
430                pivoting,
431            } => {
432                self.u8(72);
433                self.bool(*full_matrices);
434                self.bool(*pivoting);
435            }
436            Params::Eigh {
437                lower,
438                sort_eigenvalues,
439                subset_by_index,
440                algorithm,
441            } => {
442                // Tag 73 is the format without a subset or an algorithm, 82
443                // with a subset, 84 with an algorithm (and a subset flag).
444                let tag = match (subset_by_index, algorithm) {
445                    (None, None) => 73,
446                    (Some(_), None) => 82,
447                    (_, Some(_)) => 84,
448                };
449                self.u8(tag);
450                self.bool(*lower);
451                self.bool(*sort_eigenvalues);
452                if tag == 84 {
453                    self.bool(subset_by_index.is_some());
454                }
455                if let Some((start, end)) = subset_by_index {
456                    self.usize(*start);
457                    self.usize(*end);
458                }
459                if let Some(a) = algorithm {
460                    self.u8(*a as u8);
461                }
462            }
463            Params::Schur {
464                compute_schur_vectors,
465            } => {
466                self.u8(76);
467                self.bool(*compute_schur_vectors);
468            }
469            Params::Ormqr { left, transpose } => {
470                self.u8(77);
471                self.bool(*left);
472                self.bool(*transpose);
473            }
474            Params::SymmetricProduct { alpha, beta } => {
475                self.u8(81);
476                self.u64(alpha.to_bits());
477                self.u64(beta.to_bits());
478            }
479            // A Rust function cannot be written: the tag makes reading fail
480            // with a clear message.
481            Params::HostCallback { callback, .. } => {
482                self.u8(86);
483                self.usize(callback.name().len());
484                for b in callback.name().bytes() {
485                    self.u8(b);
486                }
487            }
488            Params::Tridiagonal { lower } => {
489                self.u8(79);
490                self.bool(*lower);
491            }
492            Params::TridiagonalSolve { perturb_singular } => {
493                self.u8(78);
494                self.bool(*perturb_singular);
495            }
496            Params::Eig {
497                compute_left_eigenvectors,
498                compute_right_eigenvectors,
499                enable_eigvec_derivs,
500            } => {
501                self.u8(75);
502                self.bool(*compute_left_eigenvectors);
503                self.bool(*compute_right_eigenvectors);
504                self.bool(*enable_eigvec_derivs);
505            }
506            Params::Svd {
507                full_matrices,
508                compute_uv,
509                subset_by_index,
510                algorithm,
511            } => {
512                // Tag 74 is the format without a subset or an algorithm, 83
513                // with a subset, 85 with an algorithm (and a subset flag).
514                let tag = match (subset_by_index, algorithm) {
515                    (None, None) => 74,
516                    (Some(_), None) => 83,
517                    (_, Some(_)) => 85,
518                };
519                self.u8(tag);
520                self.bool(*full_matrices);
521                self.bool(*compute_uv);
522                if tag == 85 {
523                    self.bool(subset_by_index.is_some());
524                }
525                if let Some((start, end)) = subset_by_index {
526                    self.usize(*start);
527                    self.usize(*end);
528                }
529                if let Some(a) = algorithm {
530                    self.u8(*a as u8);
531                }
532            }
533            Params::Gather {
534                dimension_numbers: d,
535                slice_sizes,
536                mode,
537                indices_are_sorted,
538                unique_indices,
539            } => {
540                self.u8(16);
541                for v in [
542                    &d.offset_dims,
543                    &d.collapsed_slice_dims,
544                    &d.start_index_map,
545                    &d.operand_batching_dims,
546                    &d.start_indices_batching_dims,
547                    slice_sizes,
548                ] {
549                    self.usizes(v);
550                }
551                self.mode(*mode);
552                self.bool(*indices_are_sorted);
553                self.bool(*unique_indices);
554            }
555            Params::Scatter {
556                dimension_numbers: d,
557                mode,
558                indices_are_sorted,
559                unique_indices,
560            } => {
561                self.u8(17);
562                for v in [
563                    &d.update_window_dims,
564                    &d.inserted_window_dims,
565                    &d.scatter_dims_to_operand_dims,
566                    &d.operand_batching_dims,
567                    &d.scatter_indices_batching_dims,
568                ] {
569                    self.usizes(v);
570                }
571                self.mode(*mode);
572                self.bool(*indices_are_sorted);
573                self.bool(*unique_indices);
574            }
575            Params::Cond { branches } => {
576                self.u8(18);
577                self.usize(branches.len());
578                branches.iter().for_each(|b| self.function(b));
579            }
580            Params::While {
581                cond,
582                body,
583                cond_nconsts,
584                body_nconsts,
585            } => {
586                self.u8(19);
587                self.function(cond);
588                self.function(body);
589                self.usize(*cond_nconsts);
590                self.usize(*body_nconsts);
591            }
592            Params::Scan {
593                body,
594                length,
595                reverse,
596                num_consts,
597                num_carry,
598            } => {
599                self.u8(20);
600                self.function(body);
601                self.usize(*length);
602                self.bool(*reverse);
603                self.usize(*num_consts);
604                self.usize(*num_carry);
605            }
606            Params::CustomJvp {
607                call,
608                jvp,
609                num_consts,
610            } => {
611                self.u8(30);
612                self.function(call);
613                self.function(jvp);
614                self.usize(*num_consts);
615            }
616            Params::CustomVjp {
617                call,
618                fwd,
619                bwd,
620                num_consts,
621            } => {
622                self.u8(31);
623                self.function(call);
624                self.function(fwd);
625                self.function(bwd);
626                self.usize(*num_consts);
627            }
628            Params::CustomLin { bwd, num_res } => {
629                self.u8(32);
630                self.function(bwd);
631                self.usize(*num_res);
632            }
633            Params::Checkpoint { body } => {
634                self.u8(33);
635                self.function(body);
636            }
637            Params::Jit { name, body } => {
638                self.u8(21);
639                self.str(name);
640                self.function(body);
641            }
642            Params::Extern {
643                name,
644                module,
645                inputs,
646                outputs,
647            } => {
648                self.u8(22);
649                self.str(name);
650                self.str(module);
651                self.usize(inputs.len());
652                inputs.iter().for_each(|a| self.aval(a));
653                self.usize(outputs.len());
654                outputs.iter().for_each(|a| self.aval(a));
655            }
656        }
657    }
658}
659
660struct Reader<'a> {
661    bytes: &'a [u8],
662    pos: usize,
663    vars: HashMap<u64, Var>,
664    lookup: &'a dyn Fn(&str) -> Option<Prim>,
665}
666
667impl Reader<'_> {
668    fn take(&mut self, n: usize) -> Result<&[u8]> {
669        let end = self.pos.checked_add(n).filter(|&e| e <= self.bytes.len());
670        let end = end.ok_or_else(|| Error::Malformed(String::from("unexpected end of input")))?;
671        let s = &self.bytes[self.pos..end];
672        self.pos = end;
673        Ok(s)
674    }
675    fn u8(&mut self) -> Result<u8> {
676        Ok(self.take(1)?[0])
677    }
678    fn u32(&mut self) -> Result<u32> {
679        Ok(u32::from_le_bytes(
680            self.take(4)?.try_into().expect("4 bytes"),
681        ))
682    }
683    fn u64(&mut self) -> Result<u64> {
684        Ok(u64::from_le_bytes(
685            self.take(8)?.try_into().expect("8 bytes"),
686        ))
687    }
688    fn i64(&mut self) -> Result<i64> {
689        Ok(i64::from_le_bytes(
690            self.take(8)?.try_into().expect("8 bytes"),
691        ))
692    }
693    fn usize(&mut self) -> Result<usize> {
694        usize::try_from(self.u64()?)
695            .map_err(|_| Error::Malformed(String::from("size out of range")))
696    }
697    /// Reads a length, which cannot exceed the remaining bytes.
698    fn len(&mut self) -> Result<usize> {
699        let n = self.usize()?;
700        if n > self.bytes.len() - self.pos {
701            return Err(Error::Malformed(String::from("length exceeds the input")));
702        }
703        Ok(n)
704    }
705    fn pairs(&mut self) -> Result<Vec<(i64, i64)>> {
706        let n = self.len()?;
707        (0..n).map(|_| Ok((self.i64()?, self.i64()?))).collect()
708    }
709    fn precision(&mut self) -> Result<Precision> {
710        Ok(match self.u8()? {
711            0 => Precision::Default,
712            1 => Precision::High,
713            2 => Precision::Highest,
714            p => return Err(Error::Malformed(format!("invalid precision {p}"))),
715        })
716    }
717    fn opt_dtype(&mut self) -> Result<Option<DType>> {
718        Ok(if self.bool()? {
719            Some(self.dtype()?)
720        } else {
721            None
722        })
723    }
724    fn select_prim(&mut self) -> Result<SelectPrim> {
725        Ok(match self.u8()? {
726            0 => SelectPrim::Ge,
727            1 => SelectPrim::Le,
728            p => return Err(Error::Malformed(format!("invalid select_prim {p}"))),
729        })
730    }
731    fn bool(&mut self) -> Result<bool> {
732        match self.u8()? {
733            0 => Ok(false),
734            1 => Ok(true),
735            b => Err(Error::Malformed(format!("invalid bool {b}"))),
736        }
737    }
738    fn usizes(&mut self) -> Result<Vec<usize>> {
739        let n = self.len()?;
740        (0..n).map(|_| self.usize()).collect()
741    }
742    fn str(&mut self) -> Result<String> {
743        let n = self.len()?;
744        String::from_utf8(self.take(n)?.to_vec())
745            .map_err(|_| Error::Malformed(String::from("invalid UTF-8")))
746    }
747    fn dtype(&mut self) -> Result<DType> {
748        let s = self.str()?;
749        DType::from_name(&s).ok_or_else(|| Error::Malformed(format!("unknown element type {s}")))
750    }
751    fn shape(&mut self) -> Result<Shape> {
752        let s = Shape::from(self.usizes()?);
753        // Arrays of this shape could not exist.
754        let fits = s
755            .checked_size()
756            .and_then(|n| n.checked_mul(16))
757            .is_some_and(|b| isize::try_from(b).is_ok());
758        if !fits {
759            return Err(Error::Malformed(format!("shape [{s}] is too large")));
760        }
761        Ok(s)
762    }
763    fn aval(&mut self) -> Result<AVal> {
764        let dtype = self.dtype()?;
765        Ok(AVal {
766            dtype,
767            shape: self.shape()?,
768        })
769    }
770    fn var(&mut self) -> Result<Var> {
771        let id = self.u64()?;
772        let aval = self.aval()?;
773        Ok(self
774            .vars
775            .entry(id)
776            .or_insert_with(|| Var::new(aval))
777            .clone())
778    }
779    fn host(&mut self) -> Result<HostArray> {
780        let aval = self.aval()?;
781        let n = self.len()?;
782        let mut bytes = self.take(n)?.to_vec();
783        if cfg!(target_endian = "big") {
784            bytes
785                .chunks_exact_mut(aval.dtype.size_in_bytes())
786                .for_each(<[u8]>::reverse);
787        }
788        HostArray::from_bytes(&bytes, aval.shape, aval.dtype)
789    }
790    fn atom(&mut self) -> Result<Atom> {
791        match self.u8()? {
792            0 => Ok(Atom::Var(self.var()?)),
793            1 => {
794                let h = self.host()?;
795                if h.shape().rank() != 0 {
796                    return Err(Error::Malformed(String::from("literals must be scalars")));
797                }
798                Ok(Atom::Lit(Literal::new(h)))
799            }
800            t => Err(Error::Malformed(format!("invalid atom tag {t}"))),
801        }
802    }
803    fn function(&mut self) -> Result<Function> {
804        let n = self.len()?;
805        let constvars = (0..n)
806            .map(|_| Ok((self.var()?, self.host()?)))
807            .collect::<Result<_>>()?;
808        let n = self.len()?;
809        let invars = (0..n).map(|_| self.var()).collect::<Result<_>>()?;
810        let n = self.len()?;
811        let mut eqns = Vec::with_capacity(n);
812        for _ in 0..n {
813            let name = self.str()?;
814            let prim = (self.lookup)(&name)
815                .ok_or_else(|| Error::Malformed(format!("unknown primitive {name}")))?;
816            let k = self.len()?;
817            let inputs = (0..k).map(|_| self.atom()).collect::<Result<_>>()?;
818            let params = self.params()?;
819            let k = self.len()?;
820            let outputs = (0..k).map(|_| self.var()).collect::<Result<_>>()?;
821            eqns.push(Eqn {
822                prim,
823                inputs,
824                params,
825                outputs,
826                loc: None,
827            });
828        }
829        let n = self.len()?;
830        let outvars = (0..n).map(|_| self.atom()).collect::<Result<_>>()?;
831        Ok(Function {
832            constvars,
833            invars,
834            eqns,
835            outvars,
836        })
837    }
838    fn mode(&mut self) -> Result<GatherScatterMode> {
839        Ok(match self.u8()? {
840            0 => GatherScatterMode::Clip,
841            1 => GatherScatterMode::FillOrDrop,
842            2 => GatherScatterMode::PromiseInBounds,
843            m => return Err(Error::Malformed(format!("invalid mode {m}"))),
844        })
845    }
846    fn params(&mut self) -> Result<Params> {
847        let tag = self.u8()?;
848        Ok(match tag {
849            0 => Params::None,
850            1 => Params::Convert {
851                new_dtype: self.dtype()?,
852            },
853            2 => Params::Round {
854                method: if self.bool()? {
855                    RoundingMethod::ToNearestEven
856                } else {
857                    RoundingMethod::AwayFromZero
858                },
859            },
860            3 => Params::IntegerPow {
861                y: i32::try_from(self.i64()?)
862                    .map_err(|_| Error::Malformed(String::from("exponent out of range")))?,
863            },
864            4 => Params::BroadcastInDim {
865                shape: self.shape()?,
866                broadcast_dimensions: self.usizes()?,
867            },
868            5 => Params::Reshape {
869                new_sizes: self.shape()?,
870            },
871            6 => Params::Transpose {
872                permutation: self.usizes()?,
873            },
874            7 => Params::Reduce {
875                axes: self.usizes()?,
876            },
877            8 => Params::ArgMinMax {
878                axis: self.usize()?,
879                index_dtype: self.dtype()?,
880            },
881            9 => {
882                let d = DotDims {
883                    lhs_contracting: self.usizes()?,
884                    rhs_contracting: self.usizes()?,
885                    lhs_batch: self.usizes()?,
886                    rhs_batch: self.usizes()?,
887                };
888                let precision = match self.u8()? {
889                    0 => Precision::Default,
890                    1 => Precision::High,
891                    2 => Precision::Highest,
892                    p => return Err(Error::Malformed(format!("invalid precision {p}"))),
893                };
894                let preferred_element_type = if self.bool()? {
895                    Some(self.dtype()?)
896                } else {
897                    None
898                };
899                Params::DotGeneral {
900                    dimension_numbers: d,
901                    precision,
902                    preferred_element_type,
903                }
904            }
905            10 => Params::Iota {
906                dtype: self.dtype()?,
907                shape: self.shape()?,
908                dimension: self.usize()?,
909            },
910            11 => Params::Slice {
911                start_indices: self.usizes()?,
912                limit_indices: self.usizes()?,
913                strides: self.usizes()?,
914            },
915            12 => Params::DynamicSlice {
916                slice_sizes: self.usizes()?,
917            },
918            13 => Params::Concatenate {
919                dimension: self.usize()?,
920            },
921            14 => {
922                let n = self.len()?;
923                let padding_config = (0..n)
924                    .map(|_| Ok((self.i64()?, self.i64()?, self.usize()?)))
925                    .collect::<Result<_>>()?;
926                Params::Pad { padding_config }
927            }
928            15 => Params::Rev {
929                dimensions: self.usizes()?,
930            },
931            16 => Params::Gather {
932                dimension_numbers: GatherDims {
933                    offset_dims: self.usizes()?,
934                    collapsed_slice_dims: self.usizes()?,
935                    start_index_map: self.usizes()?,
936                    operand_batching_dims: self.usizes()?,
937                    start_indices_batching_dims: self.usizes()?,
938                },
939                slice_sizes: self.usizes()?,
940                mode: self.mode()?,
941                indices_are_sorted: self.bool()?,
942                unique_indices: self.bool()?,
943            },
944            17 => Params::Scatter {
945                dimension_numbers: ScatterDims {
946                    update_window_dims: self.usizes()?,
947                    inserted_window_dims: self.usizes()?,
948                    scatter_dims_to_operand_dims: self.usizes()?,
949                    operand_batching_dims: self.usizes()?,
950                    scatter_indices_batching_dims: self.usizes()?,
951                },
952                mode: self.mode()?,
953                indices_are_sorted: self.bool()?,
954                unique_indices: self.bool()?,
955            },
956            18 => {
957                let n = self.len()?;
958                let branches = (0..n)
959                    .map(|_| self.function().map(Arc::new))
960                    .collect::<Result<_>>()?;
961                Params::Cond { branches }
962            }
963            19 => Params::While {
964                cond: Arc::new(self.function()?),
965                body: Arc::new(self.function()?),
966                cond_nconsts: self.usize()?,
967                body_nconsts: self.usize()?,
968            },
969            20 => Params::Scan {
970                body: Arc::new(self.function()?),
971                length: self.usize()?,
972                reverse: self.bool()?,
973                num_consts: self.usize()?,
974                num_carry: self.usize()?,
975            },
976            21 => Params::Jit {
977                name: self.str()?,
978                body: Arc::new(self.function()?),
979            },
980            22 => {
981                let name = self.str()?;
982                let module: Arc<str> = self.str()?.into();
983                let n = self.usize()?;
984                let inputs = (0..n).map(|_| self.aval()).collect::<Result<Vec<_>>>()?;
985                let n = self.usize()?;
986                let outputs = (0..n).map(|_| self.aval()).collect::<Result<Vec<_>>>()?;
987                Params::Extern {
988                    name,
989                    module,
990                    inputs,
991                    outputs,
992                }
993            }
994            23 => Params::Sort {
995                dimension: self.usize()?,
996                is_stable: self.bool()?,
997                num_keys: self.usize()?,
998            },
999            40 => Params::Cumulative {
1000                axis: self.usize()?,
1001                reverse: self.bool()?,
1002            },
1003            80 => {
1004                let t = self.u8()?;
1005                Params::Fft {
1006                    fft_type: FftType::from_index(t)
1007                        .ok_or_else(|| Error::Malformed(format!("invalid FFT type {t}")))?,
1008                    fft_lengths: self.usizes()?,
1009                }
1010            }
1011            41 => Params::TopK {
1012                k: self.usize()?,
1013                axis: self.usize()?,
1014                is_stable: self.bool()?,
1015            },
1016            50 => Params::ConvGeneralDilated {
1017                window_strides: self.usizes()?,
1018                padding: self.pairs()?,
1019                lhs_dilation: self.usizes()?,
1020                rhs_dilation: self.usizes()?,
1021                dimension_numbers: ConvDims {
1022                    lhs_spec: self.usizes()?,
1023                    rhs_spec: self.usizes()?,
1024                    out_spec: self.usizes()?,
1025                },
1026                feature_group_count: self.usize()?,
1027                batch_group_count: self.usize()?,
1028                precision: self.precision()?,
1029                preferred_element_type: self.opt_dtype()?,
1030            },
1031            51 => Params::ReduceWindow {
1032                window_dimensions: self.usizes()?,
1033                window_strides: self.usizes()?,
1034                padding: self.pairs()?,
1035                base_dilation: self.usizes()?,
1036                window_dilation: self.usizes()?,
1037            },
1038            52 => Params::SelectAndScatterAdd {
1039                select_prim: self.select_prim()?,
1040                window_dimensions: self.usizes()?,
1041                window_strides: self.usizes()?,
1042                padding: self.pairs()?,
1043            },
1044            53 => Params::SelectAndGatherAdd {
1045                select_prim: self.select_prim()?,
1046                window_dimensions: self.usizes()?,
1047                window_strides: self.usizes()?,
1048                padding: self.pairs()?,
1049                base_dilation: self.usizes()?,
1050                window_dilation: self.usizes()?,
1051            },
1052            70 => Params::TriangularSolve {
1053                left_side: self.bool()?,
1054                lower: self.bool()?,
1055                transpose_a: self.bool()?,
1056                conjugate_a: self.bool()?,
1057                unit_diagonal: self.bool()?,
1058            },
1059            71 => Params::LuPivotsToPermutation {
1060                permutation_size: self.usize()?,
1061            },
1062            72 => Params::Qr {
1063                full_matrices: self.bool()?,
1064                pivoting: self.bool()?,
1065            },
1066            73 | 82 | 84 => {
1067                let lower = self.bool()?;
1068                let sort_eigenvalues = self.bool()?;
1069                let has_subset = tag == 82 || (tag == 84 && self.bool()?);
1070                let subset_by_index = if has_subset {
1071                    Some((self.usize()?, self.usize()?))
1072                } else {
1073                    None
1074                };
1075                let algorithm = if tag == 84 {
1076                    Some(match self.u8()? {
1077                        0 => EighImplementation::Qr,
1078                        1 => EighImplementation::Jacobi,
1079                        2 => EighImplementation::Qdwh,
1080                        _ => return Err(Error::Malformed(String::from("eigh algorithm"))),
1081                    })
1082                } else {
1083                    None
1084                };
1085                Params::Eigh {
1086                    lower,
1087                    sort_eigenvalues,
1088                    subset_by_index,
1089                    algorithm,
1090                }
1091            }
1092            76 => Params::Schur {
1093                compute_schur_vectors: self.bool()?,
1094            },
1095            77 => Params::Ormqr {
1096                left: self.bool()?,
1097                transpose: self.bool()?,
1098            },
1099            81 => Params::SymmetricProduct {
1100                alpha: f64::from_bits(self.u64()?),
1101                beta: f64::from_bits(self.u64()?),
1102            },
1103            86 => {
1104                let len = self.usize()?;
1105                let name: Vec<u8> = (0..len).map(|_| self.u8()).collect::<Result<_>>()?;
1106                return Err(Error::Malformed(format!(
1107                    "the host callback `{}` cannot be read back (Rust functions are not serialized)",
1108                    String::from_utf8_lossy(&name)
1109                )));
1110            }
1111            79 => Params::Tridiagonal {
1112                lower: self.bool()?,
1113            },
1114            78 => Params::TridiagonalSolve {
1115                perturb_singular: self.bool()?,
1116            },
1117            75 => Params::Eig {
1118                compute_left_eigenvectors: self.bool()?,
1119                compute_right_eigenvectors: self.bool()?,
1120                enable_eigvec_derivs: self.bool()?,
1121            },
1122            74 | 83 | 85 => {
1123                let full_matrices = self.bool()?;
1124                let compute_uv = self.bool()?;
1125                let has_subset = tag == 83 || (tag == 85 && self.bool()?);
1126                let subset_by_index = if has_subset {
1127                    Some((self.usize()?, self.usize()?))
1128                } else {
1129                    None
1130                };
1131                let algorithm = if tag == 85 {
1132                    Some(match self.u8()? {
1133                        0 => SvdAlgorithm::Default,
1134                        1 => SvdAlgorithm::Qr,
1135                        2 => SvdAlgorithm::Jacobi,
1136                        3 => SvdAlgorithm::Polar,
1137                        4 => SvdAlgorithm::DivideAndConquer,
1138                        _ => return Err(Error::Malformed(String::from("svd algorithm"))),
1139                    })
1140                } else {
1141                    None
1142                };
1143                Params::Svd {
1144                    full_matrices,
1145                    compute_uv,
1146                    subset_by_index,
1147                    algorithm,
1148                }
1149            }
1150            30 => Params::CustomJvp {
1151                call: Arc::new(self.function()?),
1152                jvp: Arc::new(self.function()?),
1153                num_consts: self.usize()?,
1154            },
1155            31 => Params::CustomVjp {
1156                call: Arc::new(self.function()?),
1157                fwd: Arc::new(self.function()?),
1158                bwd: Arc::new(self.function()?),
1159                num_consts: self.usize()?,
1160            },
1161            32 => Params::CustomLin {
1162                bwd: Arc::new(self.function()?),
1163                num_res: self.usize()?,
1164            },
1165            33 => Params::Checkpoint {
1166                body: Arc::new(self.function()?),
1167            },
1168            t => return Err(Error::Malformed(format!("invalid parameter tag {t}"))),
1169        })
1170    }
1171}
1172
1173#[cfg(test)]
1174mod tests {
1175    use super::*;
1176
1177    #[test]
1178    fn window_parameters_round_trip() {
1179        let all = [
1180            Params::ConvGeneralDilated {
1181                window_strides: vec![2, 1],
1182                padding: vec![(1, -1), (0, 2)],
1183                lhs_dilation: vec![1, 2],
1184                rhs_dilation: vec![2, 1],
1185                dimension_numbers: ConvDims {
1186                    lhs_spec: vec![0, 3, 1, 2],
1187                    rhs_spec: vec![3, 2, 0, 1],
1188                    out_spec: vec![0, 3, 1, 2],
1189                },
1190                feature_group_count: 2,
1191                batch_group_count: 1,
1192                precision: Precision::Highest,
1193                preferred_element_type: Some(DType::F32),
1194            },
1195            Params::ReduceWindow {
1196                window_dimensions: vec![1, 2],
1197                window_strides: vec![1, 2],
1198                padding: vec![(0, 0), (0, 1)],
1199                base_dilation: vec![1, 1],
1200                window_dilation: vec![2, 1],
1201            },
1202            Params::SelectAndScatterAdd {
1203                select_prim: SelectPrim::Ge,
1204                window_dimensions: vec![2],
1205                window_strides: vec![2],
1206                padding: vec![(1, 0)],
1207            },
1208            Params::SelectAndGatherAdd {
1209                select_prim: SelectPrim::Le,
1210                window_dimensions: vec![2],
1211                window_strides: vec![1],
1212                padding: vec![(0, 0)],
1213                base_dilation: vec![2],
1214                window_dilation: vec![1],
1215            },
1216            Params::Fft {
1217                fft_type: FftType::Irfft,
1218                fft_lengths: vec![4, 6],
1219            },
1220        ];
1221        for p in all {
1222            let mut w = Writer::default();
1223            w.params(&p);
1224            let mut r = Reader {
1225                bytes: &w.buf,
1226                pos: 0,
1227                vars: HashMap::new(),
1228                lookup: &|_| None,
1229            };
1230            assert_eq!(r.params().unwrap(), p);
1231            assert_eq!(r.pos, w.buf.len());
1232        }
1233    }
1234
1235    #[test]
1236    fn rejects_bad_input() {
1237        assert!(from_bytes(b"nope", &|_| None).is_err());
1238        let mut bytes = to_bytes(&Function::default());
1239        bytes.push(0);
1240        assert!(from_bytes(&bytes, &|_| None).is_err());
1241    }
1242
1243    #[test]
1244    fn rejects_shapes_that_overflow() {
1245        let x = Var::new(AVal::new([1 << 33, 1 << 33, 0], DType::F32));
1246        let f = Function {
1247            invars: vec![x.clone()],
1248            outvars: vec![x.into()],
1249            ..Function::default()
1250        };
1251        assert!(from_bytes(&to_bytes(&f), &|_| None).is_err());
1252    }
1253
1254    #[test]
1255    fn equal_functions_give_equal_bytes() {
1256        let make = || {
1257            let x = Var::new(AVal::new([2], DType::I32));
1258            let c = Var::new(AVal::new([2], DType::I32));
1259            Function {
1260                constvars: vec![(c.clone(), HostArray::from_vec(vec![1, 2], [2]))],
1261                invars: vec![x],
1262                outvars: vec![
1263                    Atom::Var(c),
1264                    Atom::Lit(Literal::new(HostArray::scalar(1.5f32))),
1265                ],
1266                ..Function::default()
1267            }
1268        };
1269        assert_eq!(to_bytes(&make()), to_bytes(&make()));
1270        let g = from_bytes(&to_bytes(&make()), &|_| None).unwrap();
1271        assert_eq!(g.to_string(), make().to_string());
1272    }
1273}