-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathrational-new-div.rs
353 lines (321 loc) · 11.3 KB
/
rational-new-div.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*!
Here is an example of how to implement a domain for Ruler to infer rewrites.
This shows the domain of rationals with a different
semantics for division by zero (see `Section 6.3` in the paper).
To implement a new domain, you need to
- define the operators in the language with `define_language`,
- implement `eval` which is the interpreter for your domain,
- implement `init_synth` to add the variables and important constants to the initial egraph,
- implement `make_layer` to enumerate terms in the egraph,
- implement `is_valid` for checking the validity of the rules in your domain.
!*/
use egg::*;
use ruler::*;
use num::bigint::{BigInt, RandBigInt, ToBigInt};
use num::{rational::Ratio, Signed, ToPrimitive, Zero};
use rand::Rng;
use rand_pcg::Pcg64;
use z3::ast::Ast;
use z3::*;
/// define `Constant` for rationals
pub type Constant = Ratio<BigInt>;
define_language! {
/// Define the operators for the domain.
pub enum Math {
"+" = Add([Id; 2]),
"-" = Sub([Id; 2]),
"*" = Mul([Id; 2]),
"/" = Div([Id; 2]),
"~" = Neg(Id),
"fabs" = Abs(Id),
"pow" = Pow([Id; 2]),
"recip" = Reciprocal(Id),
Num(Constant),
Var(egg::Symbol),
}
}
/// Return a non-zero constant.
fn mk_constant(n: &BigInt, d: &BigInt) -> Option<Constant> {
if d.is_zero() {
None
} else {
Some(Ratio::new(n.clone(), d.clone()))
}
}
impl SynthLanguage for Math {
type Constant = Constant;
fn eval<'a, F>(&'a self, cvec_len: usize, mut v: F) -> CVec<Self>
where
F: FnMut(&'a Id) -> &'a CVec<Self>,
{
match self {
Math::Neg(a) => map!(v, a => Some(-a)),
Math::Add([a, b]) => map!(v, a, b => Some(a + b)),
Math::Sub([a, b]) => map!(v, a, b => Some(a - b)),
Math::Mul([a, b]) => map!(v, a, b => Some(a * b)),
Math::Num(n) => vec![Some(n.clone()); cvec_len],
Math::Var(_) => vec![],
Math::Div([a, b]) => map!(v, a, b => {
if b.is_zero() {
Some(Ratio::new(BigInt::from(0), BigInt::from(1)))
} else{
Some(a / b)
}
}),
Math::Abs(a) => map!(v, a => Some(a.abs())),
Math::Pow([a, b]) => map!(v, a, b => {
match b.to_i32() {
Some(b_int) => {
if a.is_zero() && b_int < 0 {
None
} else {
Some(a.pow(b_int))
}
}
None => None
}
}),
Math::Reciprocal(a) => map!(v, a => {
if a.is_zero() {
None
} else {
Some(a.recip())
}
}),
}
}
fn to_var(&self) -> Option<egg::Symbol> {
if let Math::Var(sym) = self {
Some(*sym)
} else {
None
}
}
fn mk_var(sym: egg::Symbol) -> Self {
Math::Var(sym)
}
fn to_constant(&self) -> Option<&Self::Constant> {
if let Math::Num(n) = self {
Some(n)
} else {
None
}
}
fn mk_constant(c: Self::Constant) -> Self {
Math::Num(c)
}
fn init_synth(synth: &mut Synthesizer<Self>) {
// this is for adding to the egraph, not used for cvec.
let constants: Vec<Constant> = ["1", "0", "-1"]
.iter()
.map(|s| s.parse().unwrap())
.collect();
let mut consts: Vec<Option<Constant>> = vec![];
for i in 0..synth.params.important_cvec_offsets {
consts.push(mk_constant(
&i.to_bigint().unwrap(),
&(1.to_bigint().unwrap()),
));
consts.push(mk_constant(
&(-i.to_bigint().unwrap()),
&(1.to_bigint().unwrap()),
));
}
consts.sort();
consts.dedup();
let mut consts = self_product(&consts, synth.params.variables);
// add the necessary random values, if any
for row in consts.iter_mut() {
let n_samples = synth.params.n_samples;
let svals: Vec<Constant> = sampler(&mut synth.rng, 8, 6, n_samples);
let mut vals: Vec<Option<Constant>> = vec![];
for v in svals {
vals.push(Some(v));
}
// let vals: Vec<Option<Constant>> = (0..n_samples)
// .map(|_| mk_constant(&synth.rng.gen_bigint(32), &gen_denom(&mut synth.rng, 32)))
// .collect();
row.extend(vals);
}
let mut egraph = EGraph::new(SynthAnalysis {
cvec_len: consts[0].len(),
constant_fold: if synth.params.no_constant_fold {
ConstantFoldMethod::NoFold
} else {
ConstantFoldMethod::CvecMatching
},
rule_lifting: false,
});
for (i, item) in consts.iter().enumerate().take(synth.params.variables) {
let var = egg::Symbol::from(letter(i));
let id = egraph.add(Math::Var(var));
egraph[id].data.cvec = item.clone();
}
for n in &constants {
egraph.add(Math::Num(n.clone()));
}
synth.egraph = egraph;
}
fn make_layer(synth: &Synthesizer<Self>, _iter: usize) -> Vec<Self> {
let mut to_add = vec![];
for i in synth.ids() {
for j in synth.ids() {
if synth.egraph[i].data.exact && synth.egraph[j].data.exact {
continue;
}
to_add.push(Math::Add([i, j]));
to_add.push(Math::Sub([i, j]));
to_add.push(Math::Mul([i, j]));
to_add.push(Math::Div([i, j]));
// to_add.push(Math::Pow([i, j]));
}
if synth.egraph[i].data.exact {
continue;
}
to_add.push(Math::Abs(i));
to_add.push(Math::Neg(i));
// to_add.push(Math::Reciprocal(i));
}
log::info!("Made a layer of {} enodes", to_add.len());
to_add
}
fn validate(
synth: &mut Synthesizer<Self>,
lhs: &egg::Pattern<Self>,
rhs: &egg::Pattern<Self>,
) -> ValidationResult {
if synth.params.use_smt {
let mut cfg = z3::Config::new();
cfg.set_timeout_msec(1000);
let ctx = z3::Context::new(&cfg);
let solver = z3::Solver::new(&ctx);
let (lexpr, _) = egg_to_z3(&ctx, Self::instantiate(lhs).as_ref());
let (rexpr, _) = egg_to_z3(&ctx, Self::instantiate(rhs).as_ref());
solver.assert(&lexpr._eq(&rexpr).not());
match solver.check() {
SatResult::Unsat => ValidationResult::Invalid,
SatResult::Sat => {
// println!("z3 validation: failed for {} => {}", lhs, rhs);
ValidationResult::Valid
}
SatResult::Unknown => {
// println!("z3 validation: unknown for {} => {}", lhs, rhs);
synth.smt_unknown += 1;
ValidationResult::Unknown
}
}
} else {
let n = synth.params.num_fuzz;
let mut env = HashMap::default();
for var in lhs.vars() {
env.insert(var, vec![]);
}
for var in rhs.vars() {
env.insert(var, vec![]);
}
for cvec in env.values_mut() {
cvec.reserve(n);
for s in sampler(&mut synth.rng, 8, 6, n) {
cvec.push(Some(s));
}
// for _ in 0..n {
// let numer = synth.rng.gen_bigint(32);
// let denom = gen_denom(&mut synth.rng, 32);
// cvec.push(Some(Ratio::new(numer, denom)));
// }
}
let lvec = Self::eval_pattern(lhs, &env, n);
let rvec = Self::eval_pattern(rhs, &env, n);
ValidationResult::from(lvec == rvec)
}
}
}
/// Return a randomply sampled BigInt that is not 0
// randomly sample so that they are not 0
// Ratio::new will panic if the denom is 0
pub fn gen_pos(rng: &mut Pcg64, bits: u64) -> BigInt {
let mut res: BigInt;
loop {
res = rng.gen_bigint(bits);
if res != 0.to_bigint().unwrap() {
break;
}
}
res
}
/// A sampler that generates both big and small rationals.
pub fn sampler(rng: &mut Pcg64, b1: u64, b2: u64, num_samples: usize) -> Vec<Ratio<BigInt>> {
let mut ret = vec![];
for _ in 0..num_samples {
let big = gen_pos(rng, b1);
let small = gen_pos(rng, b2);
let flip = rng.gen::<bool>();
if flip {
ret.push(Ratio::new(big, small));
} else {
ret.push(Ratio::new(small, big))
}
}
ret
}
/// Convert expressions to Z3's syntax for using SMT based rule verification.
#[allow(unused_mut, mutable_borrow_reservation_conflict)] // please remove if changing this
fn egg_to_z3<'a>(
ctx: &'a z3::Context,
expr: &[Math],
) -> (z3::ast::Real<'a>, Vec<z3::ast::Bool<'a>>) {
let mut buf: Vec<z3::ast::Real> = vec![];
let mut assumes: Vec<z3::ast::Bool> = vec![];
let zero = z3::ast::Real::from_real(ctx, 0, 1);
for node in expr.as_ref().iter() {
match node {
Math::Var(v) => buf.push(z3::ast::Real::new_const(ctx, v.to_string())),
Math::Num(c) => buf.push(z3::ast::Real::from_real(
ctx,
(c.numer()).to_i32().unwrap(),
(c.denom()).to_i32().unwrap(),
// to_i32(c.numer()),
// to_i32(c.denom()),
)),
Math::Add([a, b]) => buf.push(z3::ast::Real::add(
ctx,
&[&buf[usize::from(*a)], &buf[usize::from(*b)]],
)),
Math::Sub([a, b]) => buf.push(z3::ast::Real::sub(
ctx,
&[&buf[usize::from(*a)], &buf[usize::from(*b)]],
)),
Math::Mul([a, b]) => buf.push(z3::ast::Real::mul(
ctx,
&[&buf[usize::from(*a)], &buf[usize::from(*b)]],
)),
Math::Div([a, b]) => {
let denom = &buf[usize::from(*b)];
let lez = z3::ast::Real::le(denom, &zero);
let gez = z3::ast::Real::ge(denom, &zero);
let denom_zero = z3::ast::Bool::and(ctx, &[&lez, &gez]);
let numer = &buf[usize::from(*a)].clone();
buf.push(z3::ast::Bool::ite(
&denom_zero,
&zero,
&z3::ast::Real::div(numer, denom),
));
}
Math::Neg(a) => buf.push(z3::ast::Real::unary_minus(&buf[usize::from(*a)])),
Math::Abs(a) => {
let inner = &buf[usize::from(*a)].clone();
buf.push(z3::ast::Bool::ite(
&z3::ast::Real::le(inner, &zero),
&z3::ast::Real::unary_minus(inner),
inner,
));
}
_ => unimplemented!(),
}
}
(buf.pop().unwrap(), assumes)
}
/// Entry point.
fn main() {
Math::main()
}