use crate::{OpAttrs, OpTag};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnresolvedAttr {
pub op: OpTag,
pub field: &'static str,
}
impl core::fmt::Display for UnresolvedAttr {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"cannot serialize {:?}: required attr `{}` is unset (the canonical wire has no absent state, so there is no value to emit)",
self.op, self.field
)
}
}
impl std::error::Error for UnresolvedAttr {}
fn put_u32(b: &mut Vec<u8>, x: u32) {
b.extend_from_slice(&x.to_le_bytes());
}
fn put_u64(b: &mut Vec<u8>, x: u64) {
b.extend_from_slice(&x.to_le_bytes());
}
fn put_i64(b: &mut Vec<u8>, x: i64) {
b.extend_from_slice(&x.to_le_bytes());
}
fn put_f64(b: &mut Vec<u8>, x: f64) {
b.extend_from_slice(&x.to_le_bytes());
}
fn put_str(b: &mut Vec<u8>, s: &str) {
put_u32(b, s.len() as u32);
b.extend_from_slice(s.as_bytes());
}
fn put_i64_list(b: &mut Vec<u8>, xs: &[i64]) {
put_u32(b, xs.len() as u32);
for &x in xs {
put_i64(b, x);
}
}
fn put_u32_list(b: &mut Vec<u8>, xs: &[u32]) {
put_u32(b, xs.len() as u32);
for &x in xs {
put_u32(b, x);
}
}
fn put_f64_list(b: &mut Vec<u8>, xs: &[f64]) {
put_u32(b, xs.len() as u32);
for &x in xs {
put_f64(b, x);
}
}
fn put_u8_list(b: &mut Vec<u8>, xs: &[u8]) {
put_u32(b, xs.len() as u32);
b.extend_from_slice(xs);
}
impl OpAttrs {
pub fn to_canonical_bytes(&self, op: OpTag) -> Result<Vec<u8>, UnresolvedAttr> {
let body = self.canonical_body(op)?;
let mut out = (body.len() as u32).to_le_bytes().to_vec();
out.extend_from_slice(&body);
Ok(out)
}
fn canonical_body(&self, op: OpTag) -> Result<Vec<u8>, UnresolvedAttr> {
if let Some(leaf) = self.leaf_body(op)? {
return Ok(leaf);
}
if let Some(b) = self.list_body(op) {
return Ok(b);
}
self.declining_body(op)
}
fn declining_body(&self, op: OpTag) -> Result<Vec<u8>, UnresolvedAttr> {
use OpTag as T;
let req = |v: Option<i64>, field| v.ok_or(UnresolvedAttr { op, field });
let req_u64 = |v: Option<u64>, field| v.ok_or(UnresolvedAttr { op, field });
let mut body: Vec<u8> = Vec::new();
match op {
T::Slice => {
put_u32(&mut body, req(self.axis, "axis")? as u32);
put_u64(&mut body, req_u64(self.slice_start, "slice_start")?);
put_u64(&mut body, req_u64(self.slice_len, "slice_len")?);
}
T::Concat
| T::Flip
| T::Triu
| T::Tril
| T::IndexSelect
| T::Gather
| T::IndexAdd
| T::ScatterAdd => {
put_i64(&mut body, req(self.axis, "axis")?);
}
T::Roll => {
put_i64(&mut body, req(self.axis, "axis")?);
put_i64(&mut body, req(self.roll_shift, "roll_shift")?);
}
T::SumDim | T::MaxDim | T::MeanDim | T::CumSum => {
put_i64(&mut body, req(self.axis, "axis")?);
body.push(self.keepdim.unwrap_or(false) as u8);
}
T::Cast => put_str(
&mut body,
self.cast_dtype.as_deref().ok_or(UnresolvedAttr {
op,
field: "cast_dtype",
})?,
),
T::Pad => {
put_u32(&mut body, self.pad_amounts.len() as u32);
for &(before, after) in &self.pad_amounts {
put_u64(&mut body, before);
put_u64(&mut body, after);
}
body.push(self.pad_mode.ok_or(UnresolvedAttr {
op,
field: "pad_mode",
})?);
put_f64(&mut body, self.pad_value.unwrap_or(0.0));
}
T::MaskedFill => {
put_f64_list(&mut body, &self.scalars);
put_str(
&mut body,
self.cast_dtype.as_deref().ok_or(UnresolvedAttr {
op,
field: "cast_dtype",
})?,
);
}
other if Self::has_empty_canonical_body(other) => {}
other => {
return Err(UnresolvedAttr {
op: other,
field: "<tag has no declared canonical schema>",
});
}
}
Ok(body)
}
fn list_body(&self, op: OpTag) -> Option<Vec<u8>> {
use OpTag as T;
let mut body: Vec<u8> = Vec::new();
match op {
T::Reshape | T::BroadcastTo | T::ReduceSumTo | T::ReduceMaxTo | T::Iota => {
put_i64_list(&mut body, &self.target_shape);
}
T::Permute | T::Transpose => {
let perm: Vec<u32> = self.perm.iter().map(|&p| p as u32).collect();
put_u32_list(&mut body, &perm);
}
T::Unsqueeze | T::Squeeze => {
let dims: Vec<u32> = self.dims.iter().map(|&d| d as u32).collect();
put_u32_list(&mut body, &dims);
}
T::AddScalar | T::MulScalar | T::Clamp | T::PowI => {
put_f64_list(&mut body, &self.scalars);
}
T::MatMul if !self.lhs_roles.is_empty() || !self.rhs_roles.is_empty() => {
put_u8_list(&mut body, &self.lhs_roles);
put_u8_list(&mut body, &self.rhs_roles);
}
T::MatMul => {}
_ => return None,
}
Some(body)
}
fn leaf_body(&self, op: OpTag) -> Result<Option<Vec<u8>>, UnresolvedAttr> {
use OpTag as T;
let mut body: Vec<u8> = Vec::new();
match op {
T::Const => put_u64(
&mut body,
self.const_bits.ok_or(UnresolvedAttr {
op,
field: "const_bits",
})?,
),
T::RuntimeScalar => put_u32(
&mut body,
self.slot_index.ok_or(UnresolvedAttr {
op,
field: "slot_index",
})?,
),
T::ReducedCount => put_i64(
&mut body,
self.axis.ok_or(UnresolvedAttr { op, field: "axis" })?,
),
T::ScanPlaceholder => {
body.push(self.scan_role.ok_or(UnresolvedAttr {
op,
field: "scan_role",
})?);
put_u32(
&mut body,
self.scan_index.ok_or(UnresolvedAttr {
op,
field: "scan_index",
})?,
);
}
_ => return Ok(None),
}
Ok(Some(body))
}
fn has_empty_canonical_body(op: OpTag) -> bool {
use OpTag as T;
match op {
T::Add
| T::Sub
| T::Mul
| T::Div
| T::Maximum
| T::Minimum
| T::Pow
| T::Rem
| T::Neg
| T::Abs
| T::Sqr
| T::Sqrt
| T::Rsqrt
| T::Recip
| T::Exp
| T::Log
| T::Sin
| T::Cos
| T::Tanh
| T::Sigmoid
| T::Silu
| T::GeluTanh
| T::Gelu
| T::Relu
| T::Erf
| T::Step
| T::Floor
| T::Ceil
| T::Round
| T::Sign
| T::Equal
| T::Ne
| T::Lt
| T::Le
| T::Gt
| T::Ge
| T::Where
| T::SumAll
| T::MaxAll
| T::MinAll
| T::MeanAll
| T::LogSoftmaxLastDim
| T::Scan
| T::View
| T::Fused => true,
T::AddScalar
| T::MulScalar
| T::PowI
| T::Clamp
| T::MaskedFill
| T::SumDim
| T::MaxDim
| T::MeanDim
| T::ReduceSumTo
| T::ReduceMaxTo
| T::CumSum
| T::MatMul
| T::Transpose
| T::Permute
| T::Reshape
| T::BroadcastTo
| T::Unsqueeze
| T::Squeeze
| T::Cast
| T::Slice
| T::Concat
| T::Flip
| T::Roll
| T::Pad
| T::Triu
| T::Tril
| T::IndexSelect
| T::Gather
| T::IndexAdd
| T::ScatterAdd
| T::Iota
| T::Const
| T::RuntimeScalar
| T::ReducedCount
| T::ScanPlaceholder => false,
}
}
}