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

Reoptim change axes #1593

Merged
merged 4 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions core/src/ops/scan/decluttered.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashSet;

use crate::ops::einsum::EinSum;
use crate::ops::konst::Const;
use crate::optim::OptimizerSession;
Expand Down Expand Up @@ -592,12 +594,14 @@ impl Scan {
) -> TractResult<Option<AxisChangeConsequence>> {
self.body.check_consistency()?;
let locked_outlets = self.body_locked_outlets(node_input_facts)?;
let mut explored: HashSet<AxisChange> = Default::default();
let (body_patch, body_changed_wires) = if let Some(changes) =
crate::optim::change_axes::change_axes(
&self.body,
&change,
if locked_interface { &locked_outlets } else { &[] },
&self.body_bounds()?,
&mut explored
)? {
changes
} else {
Expand Down
76 changes: 58 additions & 18 deletions core/src/optim/change_axes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::internal::*;
use crate::model::*;
use crate::ops::dummy::Dummy;
use crate::ops::einsum::EinSum;
use crate::ops::konst::Const;
use std::collections::hash_map::Entry;
use std::collections::HashSet;
use std::fmt::Debug;
Expand All @@ -30,6 +31,7 @@ impl TypedPass for ChangeAxes {
_session: &mut OptimizerSession,
model: &TypedModel,
) -> TractResult<Option<TypedModelPatch>> {
let mut explored: HashSet<AxisChange> = Default::default();
let mut interfaces = model.output_outlets()?.to_vec();
interfaces.extend(model.input_outlets()?.iter());
for node in &model.nodes[self.1..] {
Expand All @@ -40,10 +42,10 @@ impl TypedPass for ChangeAxes {
let outlet = suggestion.0.as_outlet(node);
let change = AxisChange { outlet, op: suggestion.1 };
if self.0.insert(change.clone()) {
if let Some((patch, _)) = change_axes(model, &change, &interfaces, &[])
.with_context(|| {
format!("Making patch for {:?} from {}", change, node)
})?
if let Some((patch, _)) =
change_axes(model, &change, &interfaces, &[], &mut explored).with_context(
|| format!("Making patch for {:?} from {}", change, node),
)?
{
self.1 = node.id;
return Ok(Some(patch));
Expand All @@ -56,10 +58,11 @@ impl TypedPass for ChangeAxes {
let change =
AxisChange { outlet: OutletId::new(node.id, slot), op: AxisOp::Rm(ix) };
if self.0.insert(change.clone()) {
if let Some((patch, _)) = change_axes(model, &change, &interfaces, &[])
.with_context(|| {
format!("Making patch for {:?} from {}", change, node)
})?
if let Some((patch, _)) =
change_axes(model, &change, &interfaces, &[], &mut explored)
.with_context(|| {
format!("Making patch for {:?} from {}", change, node)
})?
{
self.1 = node.id;
return Ok(Some(patch));
Expand All @@ -79,7 +82,16 @@ pub fn change_axes(
change: &AxisChange,
locked: &[OutletId],
bounds: &[TVec<OutletId>],
explored: &mut HashSet<AxisChange>,
) -> TractResult<Option<(TypedModelPatch, TVec<(InOut, AxisOp)>)>> {
if explored.contains(change) {
debug!(" Not considering change because deja vu {:?}", change);
return Ok(None);
}
if model.node(change.outlet.node).op_as::<Const>().is_some_and(|c| c.0.volume() == 1) {
debug!(" Not considering change from const {:?}", change);
return Ok(None);
}
debug!(" Considering change {:?}", change);
let mut todo_changes = vec![(change.clone(), None)];
let mut changed_wires: HashMap<TVec<OutletId>, AxisOp> = HashMap::new();
Expand All @@ -88,14 +100,18 @@ pub fn change_axes(
};
changed_wires.insert(bound_outlets(change.outlet), change.op.clone());
let mut changed_ops: HashMap<usize, Box<dyn TypedOp>> = HashMap::new();
while let Some((c, emitter)) = todo_changes.pop() {
let outlet_group = bound_outlets(c.outlet);
let mut rewired_scalar_input: HashMap<InletId, (OutletId, AxisOp)> = Default::default();
while let Some((change, emitter)) = todo_changes.pop() {
if !explored.insert(change.clone()) {
return Ok(None);
}
let outlet_group = bound_outlets(change.outlet);
for &outlet in &outlet_group {
if locked.contains(&outlet) {
debug!(" Change {:?} blocked by locked interface {:?}", change, outlet);
return Ok(None);
}
let mut interfaces = vec![(outlet.node, InOut::Out(outlet.slot))];
let mut interfaces: Vec<(usize, InOut)> = vec![(outlet.node, InOut::Out(outlet.slot))];
for inlet in model.outlet_successors(outlet) {
interfaces.push((inlet.node, InOut::In(inlet.slot)));
}
Expand All @@ -104,6 +120,7 @@ pub fn change_axes(
continue;
}
let node = model.node(node_id);
// if this is a revisit...
let op = if let Some(op) = changed_ops.get(&node_id) {
trace!(" Change {:?} revisiting {}", change, model.node(node_id));
if op.is::<EinSum>() {
Expand All @@ -117,20 +134,33 @@ pub fn change_axes(
&node.op
};
let more = op
.change_axes(model, node, io, &c.op)
.change_axes(model, node, io, &change.op)
.with_context(|| format!("Propagating {change:?} to node {node}"))?;
if more.is_none() {
debug!(" Propagation of {:?} blocked by {}", change, node);
return Ok(None);
}
let AxisChangeConsequence { substitute_op, wire_changes } = more.unwrap();
trace!(" Change {:?} enters {} from {:?}", c.op, node, io);
trace!(" Change {:?} enters {} from {:?}", change.op, node, io);
trace!(" propagates as {:?}", wire_changes);
if let Some(op) = substitute_op {
trace!(" replace op by {:?}", op);
changed_ops.insert(node.id, op);
}
for (wire, op) in wire_changes.into_iter() {
let outlet = wire.as_outlet(node);
// stop upstram propagation to a scalar constant: we will clone it and alter it
// at patch generation time
if let InOut::In(inlet) = wire {
if model
.node(outlet.node)
.op_as::<Const>()
.is_some_and(|k| k.0.volume() == 1)
{
rewired_scalar_input.insert(InletId::new(node.id, inlet), (outlet, op));
continue;
}
}
let outlet_group = bound_outlets(wire.as_outlet(node));
match changed_wires.entry(outlet_group.clone()) {
Entry::Vacant(entry) => {
Expand Down Expand Up @@ -180,11 +210,21 @@ pub fn change_axes(
let node = model.node(node_id);
if nodes_to_replace.contains(&node_id) {
let mut inputs = tvec!();
for orig in &node.inputs {
let tgt = replaced_wires
.entry(*orig)
.or_insert_with(|| patch.tap_model(model, *orig).unwrap());
inputs.push(*tgt);
for (slot, orig) in node.inputs.iter().enumerate() {
let tgt = if let Some((outlet, alteration)) =
rewired_scalar_input.get(&InletId::new(node_id, slot))
{
let const_node = model.node(outlet.node);
let mut value = const_node.op_as::<Const>().unwrap().0.clone().into_tensor();
alteration.change_tensor(&mut value, false)?;
let name = model.unique_name(&const_node.name);
patch.add_const(name, value)?
} else {
*replaced_wires
.entry(*orig)
.or_insert_with(|| patch.tap_model(model, *orig).unwrap())
};
inputs.push(tgt);
}
let op: Box<dyn TypedOp> =
changed_ops.get(&node_id).cloned().unwrap_or_else(|| node.op.clone());
Expand Down
6 changes: 3 additions & 3 deletions harness/pre-optimized-graphes/hey_snips_v4_model17/expected
Original file line number Diff line number Diff line change
Expand Up @@ -548,11 +548,11 @@ graph network(input_node) -> (i"wavenet_2/post_proc_2-1x1_conv-conv1d/convolutio
i"wavenet_2/dilation_layer_23-dilation_rate_8-1x1_conv_skip-conv1d/convolution/Conv2D.filters_as_co_ci" = variable<scalar>(label = "wavenet_2/dilation_layer_23-dilation_rate_8-1x1_conv_skip-conv1d/convolution/Conv2D.filters_as_co_ci", shape = [32, 64]);
i"wavenet_2/dilation_layer_23-dilation_rate_8-1x1_conv_skip-conv1d/convolution/Conv2D" = matmul(i"wavenet_2/mul_23", i"wavenet_2/dilation_layer_23-dilation_rate_8-1x1_conv_skip-conv1d/convolution/Conv2D.filters_as_co_ci", transposeA = false, transposeB = true);
i"wavenet_2/AddN.22" = add(i"wavenet_2/AddN.21", i"wavenet_2/dilation_layer_23-dilation_rate_8-1x1_conv_skip-conv1d/convolution/Conv2D");
i"wavenet_2/Relu.low.cst" = [[0.0]];
i"wavenet_2/Relu.low" = max(i"wavenet_2/AddN.22", i"wavenet_2/Relu.low.cst");
i"wavenet_2/Relu.low.cst.1.1.1" = [[0.0]];
i"wavenet_2/Relu.low" = max(i"wavenet_2/AddN.22", i"wavenet_2/Relu.low.cst.1.1.1");
i"wavenet_2/post_proc_1-1x1_conv-conv1d/convolution/Conv2D.filters_as_co_ci" = variable<scalar>(label = "wavenet_2/post_proc_1-1x1_conv-conv1d/convolution/Conv2D.filters_as_co_ci", shape = [32, 32]);
i"wavenet_2/post_proc_1-1x1_conv-conv1d/convolution/Conv2D" = matmul(i"wavenet_2/Relu.low", i"wavenet_2/post_proc_1-1x1_conv-conv1d/convolution/Conv2D.filters_as_co_ci", transposeA = false, transposeB = true);
i"wavenet_2/post_proc_1-1x1_conv-conv1d/Relu.low" = max(i"wavenet_2/post_proc_1-1x1_conv-conv1d/convolution/Conv2D", i"wavenet_2/Relu.low.cst");
i"wavenet_2/post_proc_1-1x1_conv-conv1d/Relu.low" = max(i"wavenet_2/post_proc_1-1x1_conv-conv1d/convolution/Conv2D", i"wavenet_2/Relu.low.cst.1.1.1");
i"wavenet_2/post_proc_2-1x1_conv-conv1d/convolution/Conv2D.filters_as_co_ci" = variable<scalar>(label = "wavenet_2/post_proc_2-1x1_conv-conv1d/convolution/Conv2D.filters_as_co_ci", shape = [2, 32]);
i"wavenet_2/post_proc_2-1x1_conv-conv1d/convolution/Conv2D" = matmul(i"wavenet_2/post_proc_1-1x1_conv-conv1d/Relu.low", i"wavenet_2/post_proc_2-1x1_conv-conv1d/convolution/Conv2D.filters_as_co_ci", transposeA = false, transposeB = true);
}
Loading
Loading