| 1 |
// Copyright (c) 2023 ISRG |
| 2 |
// SPDX-License-Identifier: MPL-2.0 |
| 3 |
// |
| 4 |
// This file contains code covered by the following copyright and permission notice |
| 5 |
// and has been modified by ISRG and collaborators. |
| 6 |
// |
| 7 |
// Copyright (c) 2022 President and Fellows of Harvard College |
| 8 |
// |
| 9 |
// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 10 |
// of this software and associated documentation files (the "Software"), to deal |
| 11 |
// in the Software without restriction, including without limitation the rights |
| 12 |
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 13 |
// copies of the Software, and to permit persons to whom the Software is |
| 14 |
// furnished to do so, subject to the following conditions: |
| 15 |
// |
| 16 |
// The above copyright notice and this permission notice shall be included in all |
| 17 |
// copies or substantial portions of the Software. |
| 18 |
// |
| 19 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 20 |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 21 |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 22 |
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 23 |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 24 |
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 25 |
// SOFTWARE. |
| 26 |
// |
| 27 |
// This file incorporates work covered by the following copyright and |
| 28 |
// permission notice: |
| 29 |
// |
| 30 |
// Copyright 2020 Thomas Steinke |
| 31 |
// |
| 32 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 33 |
// you may not use this file except in compliance with the License. |
| 34 |
// You may obtain a copy of the License at |
| 35 |
// |
| 36 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 37 |
// |
| 38 |
// Unless required by applicable law or agreed to in writing, software |
| 39 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 40 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 41 |
// See the License for the specific language governing permissions and |
| 42 |
// limitations under the License. |
| 43 |
|
| 44 |
// The following code is adapted from the opendp implementation to reduce dependencies: |
| 45 |
// https://github.com/opendp/opendp/blob/main/rust/src/traits/samplers/cks20 |
| 46 |
|
| 47 |
//! Implementation of a sampler from the Discrete Gaussian Distribution. |
| 48 |
//! |
| 49 |
//! Follows |
| 50 |
//! Clément Canonne, Gautam Kamath, Thomas Steinke. The Discrete Gaussian for Differential Privacy. 2020. |
| 51 |
//! <https://arxiv.org/pdf/2004.00010.pdf> |
| 52 |
|
| 53 |
use num_bigint::{BigInt, BigUint, UniformBigUint}; |
| 54 |
use num_integer::Integer; |
| 55 |
use num_iter::range_inclusive; |
| 56 |
use num_rational::Ratio; |
| 57 |
use num_traits::{One, Zero}; |
| 58 |
use rand::{distributions::uniform::UniformSampler, distributions::Distribution, Rng}; |
| 59 |
use serde::{Deserialize, Serialize}; |
| 60 |
|
| 61 |
use super::{ |
| 62 |
DifferentialPrivacyBudget, DifferentialPrivacyDistribution, DifferentialPrivacyStrategy, |
| 63 |
DpError, ZCdpBudget, |
| 64 |
}; |
| 65 |
|
| 66 |
/// Sample from the Bernoulli(gamma) distribution, where $gamma /leq 1$. |
| 67 |
/// |
| 68 |
/// `sample_bernoulli(gamma, rng)` returns numbers distributed as $Bernoulli(gamma)$. |
| 69 |
/// using the given random number generator for base randomness. The procedure is as described |
| 70 |
/// on page 30 of [[CKS20]]. |
| 71 |
/// |
| 72 |
/// [CKS20]: https://arxiv.org/pdf/2004.00010.pdf |
| 73 |
fn sample_bernoulli<R: Rng + ?Sized>(gamma: &Ratio<BigUint>, rng: &mut R) -> bool { |
| 74 |
let d = gamma.denom(); |
| 75 |
assert!(!d.is_zero()); |
| 76 |
assert!(gamma <= &Ratio::<BigUint>::one()); |
| 77 |
|
| 78 |
// sample uniform biguint in {1,...,d} |
| 79 |
// uses the implementation of rand::Uniform for num_bigint::BigUint |
| 80 |
let s = UniformBigUint::sample_single_inclusive(BigUint::one(), d, rng); |
| 81 |
|
| 82 |
s <= *gamma.numer() |
| 83 |
} |
| 84 |
|
| 85 |
/// Sample from the Bernoulli(exp(-gamma)) distribution where `gamma` is in `[0,1]`. |
| 86 |
/// |
| 87 |
/// `sample_bernoulli_exp1(gamma, rng)` returns numbers distributed as $Bernoulli(exp(-gamma))$, |
| 88 |
/// using the given random number generator for base randomness. Follows Algorithm 1 of [[CKS20]], |
| 89 |
/// splitting the branches into two non-recursive functions. This is the `gamma in [0,1]` branch. |
| 90 |
/// |
| 91 |
/// [CKS20]: https://arxiv.org/pdf/2004.00010.pdf |
| 92 |
fn sample_bernoulli_exp1<R: Rng + ?Sized>(gamma: &Ratio<BigUint>, rng: &mut R) -> bool { |
| 93 |
assert!(!gamma.denom().is_zero()); |
| 94 |
assert!(gamma <= &Ratio::<BigUint>::one()); |
| 95 |
|
| 96 |
let mut k = BigUint::one(); |
| 97 |
loop { |
| 98 |
if sample_bernoulli(&(gamma / k.clone()), rng) { |
| 99 |
k += 1u8; |
| 100 |
} else { |
| 101 |
return k.is_odd(); |
| 102 |
} |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
/// Sample from the Bernoulli(exp(-gamma)) distribution. |
| 107 |
/// |
| 108 |
/// `sample_bernoulli_exp(gamma, rng)` returns numbers distributed as $Bernoulli(exp(-gamma))$, |
| 109 |
/// using the given random number generator for base randomness. Follows Algorithm 1 of [[CKS20]], |
| 110 |
/// splitting the branches into two non-recursive functions. This is the `gamma > 1` branch. |
| 111 |
/// |
| 112 |
/// [CKS20]: https://arxiv.org/pdf/2004.00010.pdf |
| 113 |
fn sample_bernoulli_exp<R: Rng + ?Sized>(gamma: &Ratio<BigUint>, rng: &mut R) -> bool { |
| 114 |
assert!(!gamma.denom().is_zero()); |
| 115 |
for _ in range_inclusive(BigUint::one(), gamma.floor().to_integer()) { |
| 116 |
if !sample_bernoulli_exp1(&Ratio::<BigUint>::one(), rng) { |
| 117 |
return false; |
| 118 |
} |
| 119 |
} |
| 120 |
sample_bernoulli_exp1(&(gamma - gamma.floor()), rng) |
| 121 |
} |
| 122 |
|
| 123 |
/// Sample from the geometric distribution with parameter 1 - exp(-gamma). |
| 124 |
/// |
| 125 |
/// `sample_geometric_exp(gamma, rng)` returns numbers distributed according to |
| 126 |
/// $Geometric(1 - exp(-gamma))$, using the given random number generator for base randomness. |
| 127 |
/// The code follows all but the last three lines of Algorithm 2 in [[CKS20]]. |
| 128 |
/// |
| 129 |
/// [CKS20]: https://arxiv.org/pdf/2004.00010.pdf |
| 130 |
fn sample_geometric_exp<R: Rng + ?Sized>(gamma: &Ratio<BigUint>, rng: &mut R) -> BigUint { |
| 131 |
let (s, t) = (gamma.numer(), gamma.denom()); |
| 132 |
assert!(!t.is_zero()); |
| 133 |
if gamma.is_zero() { |
| 134 |
return BigUint::zero(); |
| 135 |
} |
| 136 |
|
| 137 |
// sampler for uniform biguint in {0...t-1} |
| 138 |
// uses the implementation of rand::Uniform for num_bigint::BigUint |
| 139 |
let usampler = UniformBigUint::new(BigUint::zero(), t); |
| 140 |
let mut u = usampler.sample(rng); |
| 141 |
|
| 142 |
while !sample_bernoulli_exp1(&Ratio::<BigUint>::new(u.clone(), t.clone()), rng) { |
| 143 |
u = usampler.sample(rng); |
| 144 |
} |
| 145 |
|
| 146 |
let mut v = BigUint::zero(); |
| 147 |
loop { |
| 148 |
if sample_bernoulli_exp1(&Ratio::<BigUint>::one(), rng) { |
| 149 |
v += 1u8; |
| 150 |
} else { |
| 151 |
break; |
| 152 |
} |
| 153 |
} |
| 154 |
|
| 155 |
// we do integer division, so the following term equals floor((u + t*v)/s) |
| 156 |
(u + t * v) / s |
| 157 |
} |
| 158 |
|
| 159 |
/// Sample from the discrete Laplace distribution. |
| 160 |
/// |
| 161 |
/// `sample_discrete_laplace(scale, rng)` returns numbers distributed according to |
| 162 |
/// $\mathcal{L}_\mathbb{Z}(0, scale)$, using the given random number generator for base randomness. |
| 163 |
/// This follows Algorithm 2 of [[CKS20]], using a subfunction for geometric sampling. |
| 164 |
/// |
| 165 |
/// [CKS20]: https://arxiv.org/pdf/2004.00010.pdf |
| 166 |
fn sample_discrete_laplace<R: Rng + ?Sized>(scale: &Ratio<BigUint>, rng: &mut R) -> BigInt { |
| 167 |
let (s, t) = (scale.numer(), scale.denom()); |
| 168 |
assert!(!t.is_zero()); |
| 169 |
if s.is_zero() { |
| 170 |
return BigInt::zero(); |
| 171 |
} |
| 172 |
|
| 173 |
loop { |
| 174 |
let negative = sample_bernoulli(&Ratio::<BigUint>::new(BigUint::one(), 2u8.into()), rng); |
| 175 |
let y: BigInt = sample_geometric_exp(&scale.recip(), rng).into(); |
| 176 |
if negative && y.is_zero() { |
| 177 |
continue; |
| 178 |
} else { |
| 179 |
return if negative { -y } else { y }; |
| 180 |
} |
| 181 |
} |
| 182 |
} |
| 183 |
|
| 184 |
/// Sample from the discrete Gaussian distribution. |
| 185 |
/// |
| 186 |
/// `sample_discrete_gaussian(sigma, rng)` returns `BigInt` numbers distributed as |
| 187 |
/// $\mathcal{N}_\mathbb{Z}(0, sigma^2)$, using the given random number generator for base |
| 188 |
/// randomness. Follows Algorithm 3 from [[CKS20]]. |
| 189 |
/// |
| 190 |
/// [CKS20]: https://arxiv.org/pdf/2004.00010.pdf |
| 191 |
fn sample_discrete_gaussian<R: Rng + ?Sized>(sigma: &Ratio<BigUint>, rng: &mut R) -> BigInt { |
| 192 |
assert!(!sigma.denom().is_zero()); |
| 193 |
if sigma.is_zero() { |
| 194 |
return 0.into(); |
| 195 |
} |
| 196 |
let t = sigma.floor() + BigUint::one(); |
| 197 |
|
| 198 |
// no need to compute these parts of the probability term every iteration |
| 199 |
let summand = sigma.pow(2) / t.clone(); |
| 200 |
// compute probability of accepting the laplace sample y |
| 201 |
let prob = |term: Ratio<BigUint>| term.pow(2) * (sigma.pow(2) * BigUint::from(2u8)).recip(); |
| 202 |
|
| 203 |
loop { |
| 204 |
let y = sample_discrete_laplace(&t, rng); |
| 205 |
|
| 206 |
// absolute value without type conversion |
| 207 |
let y_abs: Ratio<BigUint> = BigUint::new(y.to_u32_digits().1).into(); |
| 208 |
|
| 209 |
// unsigned subtraction-followed-by-square |
| 210 |
let prob: Ratio<BigUint> = if y_abs < summand { |
| 211 |
prob(summand.clone() - y_abs) |
| 212 |
} else { |
| 213 |
prob(y_abs - summand.clone()) |
| 214 |
}; |
| 215 |
|
| 216 |
if sample_bernoulli_exp(&prob, rng) { |
| 217 |
return y; |
| 218 |
} |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
/// Samples `BigInt` numbers according to the discrete Gaussian distribution with mean zero. |
| 223 |
/// The distribution is defined over the integers, represented by arbitrary-precision integers. |
| 224 |
/// The sampling procedure follows [[CKS20]]. |
| 225 |
/// |
| 226 |
/// [CKS20]: https://arxiv.org/pdf/2004.00010.pdf |
| 227 |
#[derive(Clone, Debug)] |
| 228 |
pub struct DiscreteGaussian { |
| 229 |
/// The standard deviation of the distribution. |
| 230 |
std: Ratio<BigUint>, |
| 231 |
} |
| 232 |
|
| 233 |
impl DiscreteGaussian { |
| 234 |
/// Create a new sampler from the Discrete Gaussian Distribution with the given |
| 235 |
/// standard deviation and mean zero. Errors if the input has denominator zero. |
| 236 |
pub fn new(std: Ratio<BigUint>) -> Result<DiscreteGaussian, DpError> { |
| 237 |
if std.denom().is_zero() { |
| 238 |
return Err(DpError::ZeroDenominator); |
| 239 |
} |
| 240 |
Ok(DiscreteGaussian { std }) |
| 241 |
} |
| 242 |
} |
| 243 |
|
| 244 |
impl Distribution<BigInt> for DiscreteGaussian { |
| 245 |
fn sample<R>(&self, rng: &mut R) -> BigInt |
| 246 |
where |
| 247 |
R: Rng + ?Sized, |
| 248 |
{ |
| 249 |
sample_discrete_gaussian(&self.std, rng) |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
impl DifferentialPrivacyDistribution for DiscreteGaussian {} |
| 254 |
|
| 255 |
/// A DP strategy using the discrete gaussian distribution. |
| 256 |
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Ord, PartialOrd)] |
| 257 |
pub struct DiscreteGaussianDpStrategy<B> |
| 258 |
where |
| 259 |
B: DifferentialPrivacyBudget, |
| 260 |
{ |
| 261 |
budget: B, |
| 262 |
} |
| 263 |
|
| 264 |
/// A DP strategy using the discrete gaussian distribution providing zero-concentrated DP. |
| 265 |
pub type ZCdpDiscreteGaussian = DiscreteGaussianDpStrategy<ZCdpBudget>; |
| 266 |
|
| 267 |
impl DifferentialPrivacyStrategy for DiscreteGaussianDpStrategy<ZCdpBudget> { |
| 268 |
type Budget = ZCdpBudget; |
| 269 |
type Distribution = DiscreteGaussian; |
| 270 |
type Sensitivity = Ratio<BigUint>; |
| 271 |
|
| 272 |
fn from_budget(budget: ZCdpBudget) -> DiscreteGaussianDpStrategy<ZCdpBudget> { |
| 273 |
DiscreteGaussianDpStrategy { budget } |
| 274 |
} |
| 275 |
|
| 276 |
/// Create a new sampler from the Discrete Gaussian Distribution with a standard |
| 277 |
/// deviation calibrated to provide `1/2 epsilon^2` zero-concentrated differential |
| 278 |
/// privacy when added to the result of an integer-valued function with sensitivity |
| 279 |
/// `sensitivity`, following Theorem 4 from [[CKS20]] |
| 280 |
/// |
| 281 |
/// [CKS20]: https://arxiv.org/pdf/2004.00010.pdf |
| 282 |
fn create_distribution( |
| 283 |
&self, |
| 284 |
sensitivity: Ratio<BigUint>, |
| 285 |
) -> Result<DiscreteGaussian, DpError> { |
| 286 |
DiscreteGaussian::new(sensitivity / self.budget.epsilon.clone()) |
| 287 |
} |
| 288 |
} |
| 289 |
|
| 290 |
#[cfg(test)] |
| 291 |
mod tests { |
| 292 |
|
| 293 |
use super::*; |
| 294 |
use crate::dp::Rational; |
| 295 |
use crate::vdaf::xof::SeedStreamTurboShake128; |
| 296 |
|
| 297 |
use num_bigint::{BigUint, Sign, ToBigInt, ToBigUint}; |
| 298 |
use num_traits::{One, Signed, ToPrimitive}; |
| 299 |
use rand::{distributions::Distribution, SeedableRng}; |
| 300 |
use statrs::distribution::{ChiSquared, ContinuousCDF, Normal}; |
| 301 |
use std::collections::HashMap; |
| 302 |
|
| 303 |
#[test] |
| 304 |
fn test_discrete_gaussian() { |
| 305 |
let sampler = |
| 306 |
DiscreteGaussian::new(Ratio::<BigUint>::from_integer(BigUint::from(5u8))).unwrap(); |
| 307 |
|
| 308 |
// check samples are consistent |
| 309 |
let mut rng = SeedStreamTurboShake128::from_seed([0u8; 16]); |
| 310 |
let samples: Vec<i8> = (0..10) |
| 311 |
.map(|_| i8::try_from(sampler.sample(&mut rng)).unwrap()) |
| 312 |
.collect(); |
| 313 |
let samples1: Vec<i8> = (0..10) |
| 314 |
.map(|_| i8::try_from(sampler.sample(&mut rng)).unwrap()) |
| 315 |
.collect(); |
| 316 |
assert_eq!(samples, vec![0, -3, -2, 3, 2, -1, -5, 4, -7, -5]); |
| 317 |
assert_eq!(samples1, vec![2, 7, -8, -3, 1, -3, -3, 6, -3, -1]); |
| 318 |
} |
| 319 |
|
| 320 |
#[test] |
| 321 |
/// Make sure that the distribution created by `create_distribution` |
| 322 |
/// of `ZCdpDicreteGaussian` is the same one as manually creating one |
| 323 |
/// by using the constructor of `DiscreteGaussian` directly. |
| 324 |
fn test_zcdp_discrete_gaussian() { |
| 325 |
// sample from a manually created distribution |
| 326 |
let sampler1 = |
| 327 |
DiscreteGaussian::new(Ratio::<BigUint>::from_integer(BigUint::from(4u8))).unwrap(); |
| 328 |
let mut rng = SeedStreamTurboShake128::from_seed([0u8; 16]); |
| 329 |
let samples1: Vec<i8> = (0..10) |
| 330 |
.map(|_| i8::try_from(sampler1.sample(&mut rng)).unwrap()) |
| 331 |
.collect(); |
| 332 |
|
| 333 |
// sample from the distribution created by the `zcdp` strategy |
| 334 |
let zcdp = ZCdpDiscreteGaussian { |
| 335 |
budget: ZCdpBudget::new(Rational::try_from(0.25).unwrap()), |
| 336 |
}; |
| 337 |
let sampler2 = zcdp |
| 338 |
.create_distribution(Ratio::<BigUint>::from_integer(1u8.into())) |
| 339 |
.unwrap(); |
| 340 |
let mut rng2 = SeedStreamTurboShake128::from_seed([0u8; 16]); |
| 341 |
let samples2: Vec<i8> = (0..10) |
| 342 |
.map(|_| i8::try_from(sampler2.sample(&mut rng2)).unwrap()) |
| 343 |
.collect(); |
| 344 |
|
| 345 |
assert_eq!(samples2, samples1); |
| 346 |
} |
| 347 |
|
| 348 |
pub fn test_mean<FS: FnMut() -> BigInt>( |
| 349 |
mut sampler: FS, |
| 350 |
hyp_mean: f64, |
| 351 |
hyp_var: f64, |
| 352 |
alpha: f64, |
| 353 |
n: u32, |
| 354 |
) -> bool { |
| 355 |
// we test if the mean from our sampler is within the given error margin assuimng its |
| 356 |
// normally distributed with mean hyp_mean and variance sqrt(hyp_var/n) |
| 357 |
// this assumption is from the central limit theorem |
| 358 |
|
| 359 |
// inverse cdf (quantile function) is F s.t. P[X<=F(p)]=p for X ~ N(0,1) |
| 360 |
// (i.e. X from the standard normal distribution) |
| 361 |
let probit = |p| Normal::new(0.0, 1.0).unwrap().inverse_cdf(p); |
| 362 |
|
| 363 |
// x such that the probability of a N(0,1) variable attaining |
| 364 |
// a value outside of (-x, x) is alpha |
| 365 |
let z_stat = probit(alpha / 2.).abs(); |
| 366 |
|
| 367 |
// confidence interval for the mean |
| 368 |
let abs_p_tol = Ratio::<BigInt>::from_float(z_stat * (hyp_var / n as f64).sqrt()).unwrap(); |
| 369 |
|
| 370 |
// take n samples from the distribution, compute empirical mean |
| 371 |
let emp_mean = Ratio::<BigInt>::new((0..n).map(|_| sampler()).sum::<BigInt>(), n.into()); |
| 372 |
|
| 373 |
(emp_mean - Ratio::<BigInt>::from_float(hyp_mean).unwrap()).abs() < abs_p_tol |
| 374 |
} |
| 375 |
|
| 376 |
fn histogram( |
| 377 |
d: &Vec<BigInt>, |
| 378 |
bin_bounds: &[Option<(BigInt, BigInt)>], |
| 379 |
smallest: BigInt, |
| 380 |
largest: BigInt, |
| 381 |
) -> HashMap<Option<(BigInt, BigInt)>, u64> { |
| 382 |
// a binned histogram of the samples in `d` |
| 383 |
// used for chi_square test |
| 384 |
|
| 385 |
fn insert<T>(hist: &mut HashMap<T, u64>, key: &T, val: u64) |
| 386 |
where |
| 387 |
T: Eq + std::hash::Hash + Clone, |
| 388 |
{ |
| 389 |
*hist.entry(key.clone()).or_default() += val; |
| 390 |
} |
| 391 |
|
| 392 |
// regular histogram |
| 393 |
let mut hist = HashMap::<BigInt, u64>::new(); |
| 394 |
//binned histogram |
| 395 |
let mut bin_hist = HashMap::<Option<(BigInt, BigInt)>, u64>::new(); |
| 396 |
|
| 397 |
for val in d { |
| 398 |
// throw outliers with bound bins |
| 399 |
if val < &smallest || val > &largest { |
| 400 |
insert(&mut bin_hist, &None, 1); |
| 401 |
} else { |
| 402 |
insert(&mut hist, val, 1); |
| 403 |
} |
| 404 |
} |
| 405 |
// sort values into their bins |
| 406 |
for (a, b) in bin_bounds.iter().flatten() { |
| 407 |
for i in range_inclusive(a.clone(), b.clone()) { |
| 408 |
if let Some(count) = hist.get(&i) { |
| 409 |
insert(&mut bin_hist, &Some((a.clone(), b.clone())), *count); |
| 410 |
} |
| 411 |
} |
| 412 |
} |
| 413 |
bin_hist |
| 414 |
} |
| 415 |
|
| 416 |
fn discrete_gauss_cdf_approx( |
| 417 |
sigma: &BigUint, |
| 418 |
bin_bounds: &[Option<(BigInt, BigInt)>], |
| 419 |
) -> HashMap<Option<(BigInt, BigInt)>, f64> { |
| 420 |
// approximate bin probabilties from theoretical distribution |
| 421 |
// formula is eq. (1) on page 3 of [[CKS20]] |
| 422 |
// |
| 423 |
// [CKS20]: https://arxiv.org/pdf/2004.00010.pdf |
| 424 |
let sigma = BigInt::from_biguint(Sign::Plus, sigma.clone()); |
| 425 |
let exp_sum = |lower: &BigInt, upper: &BigInt| { |
| 426 |
range_inclusive(lower.clone(), upper.clone()) |
| 427 |
.map(|x: BigInt| { |
| 428 |
f64::exp( |
| 429 |
Ratio::<BigInt>::new(-(x.pow(2)), 2 * sigma.pow(2)) |
| 430 |
.to_f64() |
| 431 |
.unwrap(), |
| 432 |
) |
| 433 |
}) |
| 434 |
.sum::<f64>() |
| 435 |
}; |
| 436 |
// denominator is approximate up to 10 times the variance |
| 437 |
// outside of that probabilities should be very small |
| 438 |
// so the error will be negligible for the test |
| 439 |
let denom = exp_sum(&(-10i8 * sigma.pow(2)), &(10i8 * sigma.pow(2))); |
| 440 |
|
| 441 |
// compute probabilities for each bin |
| 442 |
let mut cdf = HashMap::new(); |
| 443 |
let mut p_outside = 1.0; // probability of not landing inside bin boundaries |
| 444 |
for (a, b) in bin_bounds.iter().flatten() { |
| 445 |
let entry = exp_sum(a, b) / denom; |
| 446 |
assert!(!entry.is_zero() && entry.is_finite()); |
| 447 |
cdf.insert(Some((a.clone(), b.clone())), entry); |
| 448 |
p_outside -= entry; |
| 449 |
} |
| 450 |
cdf.insert(None, p_outside); |
| 451 |
cdf |
| 452 |
} |
| 453 |
|
| 454 |
fn chi_square(sigma: &BigUint, n_bins: usize, alpha: f64) -> bool { |
| 455 |
// perform pearsons chi-squared test on the discrete gaussian sampler |
| 456 |
|
| 457 |
let sigma_signed = BigInt::from_biguint(Sign::Plus, sigma.clone()); |
| 458 |
|
| 459 |
// cut off at 3 times the std. and collect all outliers in a seperate bin |
| 460 |
let global_bound = 3u8 * sigma_signed; |
| 461 |
|
| 462 |
// bounds of bins |
| 463 |
let lower_bounds = range_inclusive(-global_bound.clone(), global_bound.clone()).step_by( |
| 464 |
((2u8 * global_bound.clone()) / BigInt::from(n_bins)) |
| 465 |
.try_into() |
| 466 |
.unwrap(), |
| 467 |
); |
| 468 |
let mut bin_bounds: Vec<Option<(BigInt, BigInt)>> = std::iter::zip( |
| 469 |
lower_bounds.clone().take(n_bins), |
| 470 |
lower_bounds.map(|x: BigInt| x - 1u8).skip(1), |
| 471 |
) |
| 472 |
.map(Some) |
| 473 |
.collect(); |
| 474 |
bin_bounds.push(None); // bin for outliers |
| 475 |
|
| 476 |
// approximate bin probabilities |
| 477 |
let cdf = discrete_gauss_cdf_approx(sigma, &bin_bounds); |
| 478 |
|
| 479 |
// chi2 stat wants at least 5 expected entries per bin |
| 480 |
// so we choose n_samples in a way that gives us that |
| 481 |
let n_samples = cdf |
| 482 |
.values() |
| 483 |
.map(|val| f64::ceil(5.0 / *val) as u32) |
| 484 |
.max() |
| 485 |
.unwrap(); |
| 486 |
|
| 487 |
// collect that number of samples |
| 488 |
let mut rng = SeedStreamTurboShake128::from_seed([0u8; 16]); |
| 489 |
let samples: Vec<BigInt> = (1..n_samples) |
| 490 |
.map(|_| { |
| 491 |
sample_discrete_gaussian(&Ratio::<BigUint>::from_integer(sigma.clone()), &mut rng) |
| 492 |
}) |
| 493 |
.collect(); |
| 494 |
|
| 495 |
// make a histogram from the samples |
| 496 |
let hist = histogram(&samples, &bin_bounds, -global_bound.clone(), global_bound); |
| 497 |
|
| 498 |
// compute pearsons chi-squared test statistic |
| 499 |
let stat: f64 = bin_bounds |
| 500 |
.iter() |
| 501 |
.map(|key| { |
| 502 |
let expected = cdf.get(&(key.clone())).unwrap() * n_samples as f64; |
| 503 |
if let Some(val) = hist.get(&(key.clone())) { |
| 504 |
(*val as f64 - expected).powf(2.) / expected |
| 505 |
} else { |
| 506 |
0.0 |
| 507 |
} |
| 508 |
}) |
| 509 |
.sum::<f64>(); |
| 510 |
|
| 511 |
let chi2 = ChiSquared::new((cdf.len() - 1) as f64).unwrap(); |
| 512 |
// the probability of observing X >= stat for X ~ chi-squared |
| 513 |
// (the "p-value") |
| 514 |
let p = 1.0 - chi2.cdf(stat); |
| 515 |
|
| 516 |
p > alpha |
| 517 |
} |
| 518 |
|
| 519 |
#[test] |
| 520 |
fn empirical_test_gauss() { |
| 521 |
[100, 2000, 20000].iter().for_each(|p| { |
| 522 |
let mut rng = SeedStreamTurboShake128::from_seed([0u8; 16]); |
| 523 |
let sampler = || { |
| 524 |
sample_discrete_gaussian( |
| 525 |
&Ratio::<BigUint>::from_integer((*p).to_biguint().unwrap()), |
| 526 |
&mut rng, |
| 527 |
) |
| 528 |
}; |
| 529 |
let mean = 0.0; |
| 530 |
let var = (p * p) as f64; |
| 531 |
assert!( |
| 532 |
test_mean(sampler, mean, var, 0.00001, 1000), |
| 533 |
"Empirical evaluation of discrete Gaussian({:?}) sampler mean failed.", |
| 534 |
p |
| 535 |
); |
| 536 |
}); |
| 537 |
// we only do chi square for std 100 because it's expensive |
| 538 |
assert!(chi_square(&(100u8.to_biguint().unwrap()), 10, 0.05)); |
| 539 |
} |
| 540 |
|
| 541 |
#[test] |
| 542 |
fn empirical_test_bernoulli_mean() { |
| 543 |
[2u8, 5u8, 7u8, 9u8].iter().for_each(|p| { |
| 544 |
let mut rng = SeedStreamTurboShake128::from_seed([0u8; 16]); |
| 545 |
let sampler = || { |
| 546 |
if sample_bernoulli( |
| 547 |
&Ratio::<BigUint>::new(BigUint::one(), (*p).into()), |
| 548 |
&mut rng, |
| 549 |
) { |
| 550 |
BigInt::one() |
| 551 |
} else { |
| 552 |
BigInt::zero() |
| 553 |
} |
| 554 |
}; |
| 555 |
let mean = 1. / (*p as f64); |
| 556 |
let var = mean * (1. - mean); |
| 557 |
assert!( |
| 558 |
test_mean(sampler, mean, var, 0.00001, 1000), |
| 559 |
"Empirical evaluation of the Bernoulli(1/{:?}) distribution mean failed", |
| 560 |
p |
| 561 |
); |
| 562 |
}) |
| 563 |
} |
| 564 |
|
| 565 |
#[test] |
| 566 |
fn empirical_test_geometric_mean() { |
| 567 |
[2u8, 5u8, 7u8, 9u8].iter().for_each(|p| { |
| 568 |
let mut rng = SeedStreamTurboShake128::from_seed([0u8; 16]); |
| 569 |
let sampler = || { |
| 570 |
sample_geometric_exp( |
| 571 |
&Ratio::<BigUint>::new(BigUint::one(), (*p).into()), |
| 572 |
&mut rng, |
| 573 |
) |
| 574 |
.to_bigint() |
| 575 |
.unwrap() |
| 576 |
}; |
| 577 |
let p_prob = 1. - f64::exp(-(1. / *p as f64)); |
| 578 |
let mean = (1. - p_prob) / p_prob; |
| 579 |
let var = (1. - p_prob) / p_prob.powi(2); |
| 580 |
assert!( |
| 581 |
test_mean(sampler, mean, var, 0.0001, 1000), |
| 582 |
"Empirical evaluation of the Geometric(1-exp(-1/{:?})) distribution mean failed", |
| 583 |
p |
| 584 |
); |
| 585 |
}) |
| 586 |
} |
| 587 |
|
| 588 |
#[test] |
| 589 |
fn empirical_test_laplace_mean() { |
| 590 |
[2u8, 5u8, 7u8, 9u8].iter().for_each(|p| { |
| 591 |
let mut rng = SeedStreamTurboShake128::from_seed([0u8; 16]); |
| 592 |
let sampler = || { |
| 593 |
sample_discrete_laplace( |
| 594 |
&Ratio::<BigUint>::new(BigUint::one(), (*p).into()), |
| 595 |
&mut rng, |
| 596 |
) |
| 597 |
}; |
| 598 |
let mean = 0.0; |
| 599 |
let var = (1. / *p as f64).powi(2); |
| 600 |
assert!( |
| 601 |
test_mean(sampler, mean, var, 0.0001, 1000), |
| 602 |
"Empirical evaluation of the Laplace(0,1/{:?}) distribution mean failed", |
| 603 |
p |
| 604 |
); |
| 605 |
}) |
| 606 |
} |
| 607 |
} |