Address remaining review requests

This commit is contained in:
eliets2 committed 2026-11-18 20:22:51 +02:00
1 parent d259e993c0
commit 85e8bf1191
3 files changed
+44 -21

No files matched your search

+15
View File
@@ -35,6 +35,7 @@ fn sources(op: &Op) -> (usize, Option<usize>) {
match op {
Op::Conv(c) => (c.src, c.src2),
Op::ConvT2(c) => (c.src, None),
Op::Add { src, src2 } => (*src, Some(*src2)),
Op::MaxPool2 { src } | Op::DepthToSpace2 { src } => (*src, None),
}
}
@@ -215,6 +216,7 @@ impl NetRunner {
&mut w.lower,
&mut w.product,
)?,
Op::Add { .. } => add(a, b.expect("Add needs two inputs"), shape.side, dest)?,
Op::MaxPool2 { .. } => pool(a, shape.side, dest)?,
Op::DepthToSpace2 { .. } => shuffle(a, shape.side, dest)?,
}
@@ -381,6 +383,19 @@ fn shuffle(a: &[f32], side: usize, dest: &mut [f32]) -> Result<()> {
}
Ok(())
}
fn add(a: &[f32], b: &[f32], side: usize, dest: &mut [f32]) -> Result<()> {
let pixels = side * side;
let channels = a.len() / pixels;
for c in 0..channels {
let a_plane = &a[c * pixels..(c + 1) * pixels];
let b_plane = &b[c * pixels..(c + 1) * pixels];
let d_plane = &mut dest[c * pixels..(c + 1) * pixels];
for (d, (&av, &bv)) in d_plane.iter_mut().zip(a_plane.iter().zip(b_plane)) {
*d = av + bv;
}
}
Ok(())
}
#[cfg(test)]
mod tests;
+19
View File
@@ -63,6 +63,11 @@ pub struct ConvT2 {
pub enum Op {
Conv(Conv),
ConvT2(ConvT2),
/// Elementwise addition of two same-shape tensors.
Add {
src: TensorId,
src2: TensorId,
},
/// 2 × 2 maximum, stride 2.
MaxPool2 {
src: TensorId,
@@ -146,6 +151,20 @@ impl Net {
check_weights(i, &c.weight, c.cin.checked_mul(c.cout).and_then(|n| n.checked_mul(4)), &c.bias, c.cout, c.leaky, &mut weights)?;
Shape { channels: c.cout, level: a.level - 1 }
}
Op::Add { src, src2 } => {
let a = shape_of(*src)?;
let b = shape_of(*src2)?;
if a.channels != b.channels || a.level != b.level {
return invalid(format!("layer {i}: add of tensors of different shapes"));
}
if a.channels == 0 {
return invalid(format!("layer {i}: add with zero channels"));
}
if a.channels > MAX_CHANNELS {
return invalid(format!("layer {i}: add with more than {} channels", MAX_CHANNELS));
}
Shape { channels: a.channels, level: a.level }
}
Op::MaxPool2 { src } => {
let a = shape_of(*src)?;
Shape { channels: a.channels, level: a.level + 1 }
+10 -21
View File
@@ -230,35 +230,18 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
let out = node.output.first().ok_or_else(|| NetError::Invalid("Add without an output".into()))?;
let (ca, la) = shapes.get(src).copied().ok_or_else(|| NetError::Invalid("Add reads a tensor with no shape".into()))?;
let (cb, lb) = shapes.get(src2).copied().ok_or_else(|| NetError::Invalid("Add reads a tensor with no shape".into()))?;
// same-shape addition as a 1x1 identity convolution over both sources (src2 channels follow src's):
// O(C^2) per pixel where elementwise addition is O(C). initializer broadcast is not a residual
// connection, reject it.
if ca != cb || la != lb {
return unsupported("Add of tensors of different shapes");
}
if ca == 0 {
return invalid("Add with zero channels");
}
if ca > 4096 {
if ca > MAX_CHANNELS {
return unsupported("Add with more than 4096 channels");
}
let nn = ca.checked_mul(ca).and_then(|n| n.checked_mul(2)).ok_or_else(|| NetError::Invalid("Add channel count overflows".into()))?;
weights_total = weights_total.saturating_add(nn).saturating_add(ca);
if weights_total > MAX_WEIGHTS {
return invalid("the network has too many weights");
}
let mut weight = vec![0.0f32; nn];
for c in 0..ca {
if let Some(w) = weight.get_mut(c * ca * 2 + c) {
*w = 1.0;
}
if let Some(w) = weight.get_mut(c * ca * 2 + ca + c) {
*w = 1.0;
}
}
ids.insert(out.clone(), this);
shapes.push((ca, la));
ops.push(Op::Conv(Conv { src, src2: Some(src2), cin: ca * 2, cout: ca, k: 1, weight, bias: vec![0.0; ca], leaky: None }));
ops.push(Op::Add { src, src2 });
}
"LeakyRelu" => {
let [a] = node.input.as_slice() else { return invalid("malformed LeakyRelu") };
@@ -598,8 +581,14 @@ mod tests {
model
}
let concat_model =
model(&[node("Concat", &["data", "data"], "joined", &[("axis", 1)]), node("Add", &["joined", "data"], "a1", &[])], 4, "a1");
let concat_model = model(
&[
node("Concat", &["data", "data"], "joined", &[("axis", 1)]),
node("Add", &["joined", "data"], "a1", &[]),
],
4,
"a1",
);
assert!(matches!(read_bytes(&concat_model), Err(NetError::Unsupported(_))));
let oversized_model = model(&[node("Add", &["data", "data"], "a1", &[])], 4097, "a1");