Skip to content

Commit 6f0c1eb

Browse files
authored
chore: dedup Sin/Cos Op::f via shared eval_trig helper (#186) (#251)
Sin and Cos had identical Op::f bodies apart from the nonlinearity called. Extract the shared modulo-4pi reduction into a pub(crate) eval_trig helper and have both ops delegate to it. Pure refactor; output is unchanged (verified by the existing sin/cos precision tests).
1 parent 3b0a82a commit 6f0c1eb

3 files changed

Lines changed: 19 additions & 8 deletions

File tree

atlas-onnx-tracer/src/ops/cos.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
use crate::{
2-
model::consts::FOUR_PI_APPROX,
3-
ops::{Cos, Op},
2+
ops::{Cos, Op, eval_trig},
43
tensor::{self, Tensor},
54
};
65

76
impl Op for Cos {
87
fn f(&self, inputs: Vec<&Tensor<i32>>) -> Tensor<i32> {
9-
let remainder = tensor::ops::nonlinearities::const_rem(inputs[0], FOUR_PI_APPROX);
10-
tensor::ops::nonlinearities::cos(&remainder, self.scale.into())
8+
eval_trig(inputs[0], self.scale, tensor::ops::nonlinearities::cos)
119
}
1210

1311
fn requires_shape_equality(&self) -> bool {

atlas-onnx-tracer/src/ops/mod.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,21 @@ pub trait Op {
180180
}
181181
}
182182

183+
/// Shared evaluation for the periodic trig operators ([`Sin`], [`Cos`]).
184+
///
185+
/// Both reduce the input modulo a `4π` approximation before applying their
186+
/// nonlinearity at the operator's scale, so the only thing that differs
187+
/// between them is the `nonlinearity` function itself.
188+
pub(crate) fn eval_trig(
189+
input: &Tensor<i32>,
190+
scale: F32,
191+
nonlinearity: fn(&Tensor<i32>, f64) -> Tensor<i32>,
192+
) -> Tensor<i32> {
193+
use crate::{model::consts::FOUR_PI_APPROX, tensor::ops::nonlinearities::const_rem};
194+
let remainder = const_rem(input, FOUR_PI_APPROX);
195+
nonlinearity(&remainder, scale.into())
196+
}
197+
183198
impl Op for Operator {
184199
fn f(&self, inputs: Vec<&Tensor<i32>>) -> Tensor<i32> {
185200
self.inner().f(inputs)

atlas-onnx-tracer/src/ops/sin.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
use crate::{
2-
model::consts::FOUR_PI_APPROX,
3-
ops::{Op, Sin},
2+
ops::{Op, Sin, eval_trig},
43
tensor::{self, Tensor},
54
};
65

76
impl Op for Sin {
87
fn f(&self, inputs: Vec<&Tensor<i32>>) -> Tensor<i32> {
9-
let remainder = tensor::ops::nonlinearities::const_rem(inputs[0], FOUR_PI_APPROX);
10-
tensor::ops::nonlinearities::sin(&remainder, self.scale.into())
8+
eval_trig(inputs[0], self.scale, tensor::ops::nonlinearities::sin)
119
}
1210

1311
fn requires_shape_equality(&self) -> bool {

0 commit comments

Comments
 (0)