ciphercore_base/ops/pwl/
approx_sigmoid.rs1use crate::custom_ops::CustomOperationBody;
3use crate::data_types::{Type, INT64};
4use crate::errors::Result;
5use crate::graphs::{Context, Graph};
6
7use serde::{Deserialize, Serialize};
8
9use super::approx_pointwise::{create_approximation, PWLConfig};
10
11#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Hash)]
39pub struct ApproxSigmoid {
40 pub precision: u64,
42}
43
44#[typetag::serde]
45impl CustomOperationBody for ApproxSigmoid {
46 fn instantiate(&self, context: Context, arguments_types: Vec<Type>) -> Result<Graph> {
47 if arguments_types.len() != 1 {
48 return Err(runtime_error!(
49 "Invalid number of arguments for ApproxSigmoid"
50 ));
51 }
52 let t = arguments_types[0].clone();
53 if !t.is_scalar() && !t.is_array() {
54 return Err(runtime_error!(
55 "Argument in ApproxSigmoid must be a scalar or an array"
56 ));
57 }
58 let sc = t.get_scalar_type();
59 if sc != INT64 {
60 return Err(runtime_error!(
61 "Argument in ApproxSigmoid must consist of INT64's"
62 ));
63 }
64 if self.precision > 30 || self.precision == 0 {
65 return Err(runtime_error!("`precision` should be in range [1, 30]."));
66 }
67
68 let g = context.create_graph()?;
69 let arg = g.input(t)?;
70 let result = create_approximation(
79 arg,
80 |x| 1.0 / (1.0 + (-x).exp()),
81 -10.0,
82 10.0,
83 self.precision,
84 PWLConfig {
85 log_buckets: 5,
86 flatten_left: true,
87 flatten_right: true,
88 },
89 )?;
90 result.set_as_output()?;
91 g.finalize()?;
92 Ok(g)
93 }
94
95 fn get_name(&self) -> String {
96 format!("ApproxSigmoid(scaling_factor=2**{})", self.precision)
97 }
98}
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103
104 use crate::custom_ops::run_instantiation_pass;
105 use crate::custom_ops::CustomOperation;
106 use crate::data_types::array_type;
107 use crate::data_types::scalar_type;
108 use crate::data_values::Value;
109 use crate::evaluators::random_evaluate;
110 use crate::graphs::util::simple_context;
111
112 fn scalar_helper(arg: i64, precision: u64) -> Result<i64> {
113 let c = simple_context(|g| {
114 let i = g.input(scalar_type(INT64))?;
115 g.custom_op(CustomOperation::new(ApproxSigmoid { precision }), vec![i])
116 })?;
117 let mapped_c = run_instantiation_pass(c)?;
118 let result = random_evaluate(
119 mapped_c.get_context().get_main_graph()?,
120 vec![Value::from_scalar(arg, INT64)?],
121 )?;
122 let res = result.to_i64(INT64)?;
123 Ok(res)
124 }
125
126 fn array_helper(arg: Vec<i64>) -> Result<Vec<i64>> {
127 let array_t = array_type(vec![arg.len() as u64], INT64);
128 let c = simple_context(|g| {
129 let i = g.input(array_t.clone())?;
130 g.custom_op(
131 CustomOperation::new(ApproxSigmoid { precision: 10 }),
132 vec![i],
133 )
134 })?;
135 let mapped_c = run_instantiation_pass(c)?;
136 let result = random_evaluate(
137 mapped_c.get_context().get_main_graph()?,
138 vec![Value::from_flattened_array(&arg, INT64)?],
139 )?;
140 result.to_flattened_array_i64(array_t)
141 }
142
143 fn sigmoid(x: f32) -> f32 {
144 1.0 / (1.0 + (-x).exp())
145 }
146
147 #[test]
148 fn test_approx_sigmoid_scalar() {
149 for i in (-5000..5000).step_by(1000) {
150 let expected = (sigmoid((i as f32) / 1024.0) * 1024.0) as i64;
151 let actual = scalar_helper(i, 10).unwrap();
152 let absolute_error = ((expected - actual).abs() as f64) / 1024.0;
153 assert!(absolute_error <= 0.01);
154 }
155 }
156
157 #[test]
158 fn test_approx_sigmoid_array() {
159 let arr: Vec<i64> = (-5000..5000).step_by(100).collect();
160 let res = array_helper(arr.clone()).unwrap();
161 for i in 0..arr.len() {
162 let expected = (sigmoid((arr[i] as f32) / 1024.0) * 1024.0) as i64;
163 let actual = res[i];
164 let absolute_error = ((expected - actual).abs() as f64) / 1024.0;
165 assert!(absolute_error <= 0.01);
166 }
167 }
168}