Skip to main content

ruxla_pjrt/
compile_options.rs

1//! Compile options, serialized as `xla.CompileOptionsProto`.
2
3/// Options for [`Client::compile_with_options`](crate::Client::compile_with_options).
4///
5/// Programs are always compiled for one replica and one partition, without a
6/// fixed device.
7///
8/// XLA's debug options cannot be overridden one by one: if the proto carries
9/// any `debug_options`, XLA replaces all of the plugin's defaults with it, and
10/// unset fields become zero (which, for example, makes the CPU compiler fail
11/// with `parallel_codegen_split_count (0)`). Behavior that would need a debug
12/// option is therefore handled in the lowering instead (see
13/// `ruxla_ir::lowering::Target`).
14#[derive(Clone, Debug, Default, PartialEq, Eq)]
15#[non_exhaustive]
16pub struct CompileOptions {}
17
18impl CompileOptions {
19    /// Creates options with the plugin's defaults.
20    pub fn new() -> Self {
21        Self::default()
22    }
23
24    /// Serializes the options as `xla.CompileOptionsProto`.
25    pub(crate) fn encode(&self) -> Vec<u8> {
26        // xla.ExecutableBuildOptionsProto
27        let mut build = Vec::new();
28        write_varint_field(&mut build, 1, -1i64 as u64); // device_ordinal
29        write_varint_field(&mut build, 4, 1); // num_replicas
30        write_varint_field(&mut build, 5, 1); // num_partitions
31        // xla.CompileOptionsProto
32        let mut out = Vec::new();
33        write_bytes_field(&mut out, 3, &build); // executable_build_options
34        out
35    }
36}
37
38fn write_varint(out: &mut Vec<u8>, mut value: u64) {
39    loop {
40        let byte = (value & 0x7f) as u8;
41        value >>= 7;
42        if value == 0 {
43            out.push(byte);
44            return;
45        }
46        out.push(byte | 0x80);
47    }
48}
49
50fn write_varint_field(out: &mut Vec<u8>, field: u32, value: u64) {
51    write_varint(out, u64::from(field) << 3);
52    write_varint(out, value);
53}
54
55fn write_bytes_field(out: &mut Vec<u8>, field: u32, bytes: &[u8]) {
56    write_varint(out, (u64::from(field) << 3) | 2);
57    write_varint(out, bytes.len() as u64);
58    out.extend_from_slice(bytes);
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn default_options_match_the_hand_encoded_proto() {
67        // executable_build_options { device_ordinal: -1 num_replicas: 1 num_partitions: 1 }
68        let expected = [
69            0x1a, 0x0f, 0x08, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x20,
70            0x01, 0x28, 0x01,
71        ];
72        assert_eq!(CompileOptions::new().encode(), expected);
73    }
74}