Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add BinEinsum to suite-unit #1630

Merged
merged 9 commits into from
Jan 31, 2025
8 changes: 6 additions & 2 deletions core/src/ops/einsum/as_matmul.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,12 @@ fn einsum_rules(
let op = match ensure_mkn_axes(op, model, node).context("Figuring out m, k and n axes")? {
AxesOrPatch::Annotated(op) => op,
AxesOrPatch::Patch(p) => return Ok(Some(p)),
AxesOrPatch::NotAMatMul(axis) => {
bail!("{} is not a matmul because of axis {}", op.axes, axis.repr)
AxesOrPatch::NotAMatMul(axes) => {
bail!(
"{} is not a matmul because of axis {}",
op.axes,
axes.iter().map(|a| a.repr).join(", ")
)
}
};
let prefix: String = op
Expand Down
8 changes: 6 additions & 2 deletions core/src/ops/einsum/optimize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::ops::nn::{Reduce, Reducer};
pub enum AxesOrPatch<'a> {
Annotated(EinSumAnnotatedAsMatMul<'a>),
Patch(TypedModelPatch),
NotAMatMul(&'a Axis),
NotAMatMul(Vec<&'a Axis>),
}

pub struct EinSumAnnotatedAsMatMul<'a> {
Expand Down Expand Up @@ -69,6 +69,7 @@ pub(crate) fn optimize(
{
return Ok(None);
}

let annotated = match ensure_mkn_axes(op, model, node)? {
AxesOrPatch::Annotated(op) => op,
AxesOrPatch::Patch(p) => return Ok(Some(p)),
Expand Down Expand Up @@ -114,6 +115,7 @@ pub(crate) fn ensure_mkn_axes<'a>(
let Some(k_axis) = k_axis else {
return Ok(AxesOrPatch::Patch(inject_k_axis(op, model, node)?));
};

let m_axis = op
.axes
.iter_all_axes()
Expand All @@ -126,13 +128,15 @@ pub(crate) fn ensure_mkn_axes<'a>(
let Some(m_axis) = m_axis else {
return Ok(AxesOrPatch::Patch(inject_m_or_n_axis(op, model, node, false, &[k_axis])?));
};

let n_axis = op
.axes
.iter_all_axes()
.filter(|a| {
(a.inputs[0].len() == 0 || input_shapes[0][a.inputs[0][0]].is_one())
&& a.inputs[1].len() == 1
&& a.outputs[0].len() == 1
&& *a != m_axis
})
.max_by_key(|a| output_shape[a.outputs[0][0]].as_i64().unwrap_or(i64::MAX));
let Some(n_axis) = n_axis else {
Expand All @@ -152,7 +156,7 @@ pub(crate) fn ensure_mkn_axes<'a>(
axis.inputs[1].first().map(|pos| &input_shapes[1][*pos]).unwrap_or(&one) != &one;
let in_out = axis.outputs[0].first().map(|pos| &output_shape[*pos]).unwrap_or(&one) != &one;
if (in_left ^ in_right) && !in_out {
return Ok(AxesOrPatch::NotAMatMul(axis));
return Ok(AxesOrPatch::NotAMatMul(vec![axis]));
}
}
let m = input_shapes[0][m_axis.inputs[0][0]].clone();
Expand Down
Loading
Loading