Skip to content
This repository was archived by the owner on Apr 28, 2025. It is now read-only.

Commit 58b9652

Browse files
committed
Streamline the way that test iteration count is determined
Currently, tests use a handful of constants to determine how many iterations to perform: `NTESTS`, `AROUND`, and `MAX_CHECK_POINTS`. This configuration is not very straightforward to adjust and needs to be repeated everywhere it is used. Replace this with new functions in the `run_cfg` module that determine iteration counts in a more reusable and documented way. This only updates `edge_cases` and `domain_logspace`, `random` is refactored in a later commit.
1 parent 1b555ca commit 58b9652

File tree

5 files changed

+208
-57
lines changed

5 files changed

+208
-57
lines changed

crates/libm-test/src/gen/domain_logspace.rs

Lines changed: 8 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6,41 +6,26 @@ use libm::support::{IntTy, MinInt};
66

77
use crate::domain::HasDomain;
88
use crate::op::OpITy;
9+
use crate::run_cfg::{GeneratorKind, iteration_count};
910
use crate::{CheckCtx, MathOp, logspace};
1011

11-
/// Number of tests to run.
12-
// FIXME(ntests): replace this with a more logical algorithm
13-
const NTESTS: usize = {
14-
if cfg!(optimizations_enabled) {
15-
if crate::emulated()
16-
|| !cfg!(target_pointer_width = "64")
17-
|| cfg!(all(target_arch = "x86_64", target_vendor = "apple"))
18-
{
19-
// Tests are pretty slow on non-64-bit targets, x86 MacOS, and targets that run
20-
// in QEMU.
21-
100_000
22-
} else {
23-
5_000_000
24-
}
25-
} else {
26-
// Without optimizations just run a quick check
27-
800
28-
}
29-
};
30-
3112
/// Create a range of logarithmically spaced inputs within a function's domain.
3213
///
3314
/// This allows us to get reasonably thorough coverage without wasting time on values that are
3415
/// NaN or out of range. Random tests will still cover values that are excluded here.
35-
pub fn get_test_cases<Op>(_ctx: &CheckCtx) -> impl Iterator<Item = (Op::FTy,)>
16+
pub fn get_test_cases<Op>(ctx: &CheckCtx) -> impl Iterator<Item = (Op::FTy,)>
3617
where
3718
Op: MathOp + HasDomain<Op::FTy>,
38-
IntTy<Op::FTy>: TryFrom<usize>,
19+
IntTy<Op::FTy>: TryFrom<u64>,
3920
RangeInclusive<IntTy<Op::FTy>>: Iterator,
4021
{
4122
let domain = Op::DOMAIN;
23+
let ntests = iteration_count(ctx, GeneratorKind::Domain, 0);
24+
25+
// We generate logspaced inputs within a specific range, excluding values that are out of
26+
// range in order to make iterations useful (random tests still cover the full range).
4227
let start = domain.range_start();
4328
let end = domain.range_end();
44-
let steps = OpITy::<Op>::try_from(NTESTS).unwrap_or(OpITy::<Op>::MAX);
29+
let steps = OpITy::<Op>::try_from(ntests).unwrap_or(OpITy::<Op>::MAX);
4530
logspace(start, end, steps).map(|v| (v,))
4631
}

crates/libm-test/src/gen/edge_cases.rs

Lines changed: 25 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,11 @@
33
use libm::support::Float;
44

55
use crate::domain::HasDomain;
6+
use crate::run_cfg::{check_near_count, check_point_count};
67
use crate::{CheckCtx, FloatExt, MathOp};
78

8-
/// Number of values near an interesting point to check.
9-
// FIXME(ntests): replace this with a more logical algorithm
10-
const AROUND: usize = 100;
11-
12-
/// Functions have infinite asymptotes, limit how many we check.
13-
// FIXME(ntests): replace this with a more logical algorithm
14-
const MAX_CHECK_POINTS: usize = 10;
15-
169
/// Create a list of values around interesting points (infinities, zeroes, NaNs).
17-
pub fn get_test_cases<Op, F>(_ctx: &CheckCtx) -> impl Iterator<Item = (F,)>
10+
pub fn get_test_cases<Op, F>(ctx: &CheckCtx) -> impl Iterator<Item = (F,)>
1811
where
1912
Op: MathOp<FTy = F> + HasDomain<F>,
2013
F: Float,
@@ -25,23 +18,26 @@ where
2518
let domain_start = domain.range_start();
2619
let domain_end = domain.range_end();
2720

21+
let check_points = check_point_count(ctx);
22+
let near_points = check_near_count(ctx);
23+
2824
// Check near some notable constants
29-
count_up(F::ONE, values);
30-
count_up(F::ZERO, values);
31-
count_up(F::NEG_ONE, values);
32-
count_down(F::ONE, values);
33-
count_down(F::ZERO, values);
34-
count_down(F::NEG_ONE, values);
25+
count_up(F::ONE, near_points, values);
26+
count_up(F::ZERO, near_points, values);
27+
count_up(F::NEG_ONE, near_points, values);
28+
count_down(F::ONE, near_points, values);
29+
count_down(F::ZERO, near_points, values);
30+
count_down(F::NEG_ONE, near_points, values);
3531
values.push(F::NEG_ZERO);
3632

3733
// Check values near the extremes
38-
count_up(F::NEG_INFINITY, values);
39-
count_down(F::INFINITY, values);
40-
count_down(domain_end, values);
41-
count_up(domain_start, values);
42-
count_down(domain_start, values);
43-
count_up(domain_end, values);
44-
count_down(domain_end, values);
34+
count_up(F::NEG_INFINITY, near_points, values);
35+
count_down(F::INFINITY, near_points, values);
36+
count_down(domain_end, near_points, values);
37+
count_up(domain_start, near_points, values);
38+
count_down(domain_start, near_points, values);
39+
count_up(domain_end, near_points, values);
40+
count_down(domain_end, near_points, values);
4541

4642
// Check some special values that aren't included in the above ranges
4743
values.push(F::NAN);
@@ -50,9 +46,9 @@ where
5046
// Check around asymptotes
5147
if let Some(f) = domain.check_points {
5248
let iter = f();
53-
for x in iter.take(MAX_CHECK_POINTS) {
54-
count_up(x, values);
55-
count_down(x, values);
49+
for x in iter.take(check_points) {
50+
count_up(x, near_points, values);
51+
count_down(x, near_points, values);
5652
}
5753
}
5854

@@ -65,11 +61,11 @@ where
6561

6662
/// Add `AROUND` values starting at and including `x` and counting up. Uses the smallest possible
6763
/// increments (1 ULP).
68-
fn count_up<F: Float>(mut x: F, values: &mut Vec<F>) {
64+
fn count_up<F: Float>(mut x: F, points: u64, values: &mut Vec<F>) {
6965
assert!(!x.is_nan());
7066

7167
let mut count = 0;
72-
while x < F::INFINITY && count < AROUND {
68+
while x < F::INFINITY && count < points {
7369
values.push(x);
7470
x = x.next_up();
7571
count += 1;
@@ -78,11 +74,11 @@ fn count_up<F: Float>(mut x: F, values: &mut Vec<F>) {
7874

7975
/// Add `AROUND` values starting at and including `x` and counting down. Uses the smallest possible
8076
/// increments (1 ULP).
81-
fn count_down<F: Float>(mut x: F, values: &mut Vec<F>) {
77+
fn count_down<F: Float>(mut x: F, points: u64, values: &mut Vec<F>) {
8278
assert!(!x.is_nan());
8379

8480
let mut count = 0;
85-
while x > F::NEG_INFINITY && count < AROUND {
81+
while x > F::NEG_INFINITY && count < points {
8682
values.push(x);
8783
x = x.next_down();
8884
count += 1;

crates/libm-test/src/gen/random.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use crate::{BaseName, CheckCtx, GenerateInput};
1212
const SEED: [u8; 32] = *b"3.141592653589793238462643383279";
1313

1414
/// Number of tests to run.
15+
// FIXME(ntests): clean this up when possible
1516
const NTESTS: usize = {
1617
if cfg!(optimizations_enabled) {
1718
if crate::emulated()

crates/libm-test/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ pub use libm::support::{Float, Int, IntTy, MinInt};
2525
pub use num::{FloatExt, logspace};
2626
pub use op::{BaseName, FloatTy, Identifier, MathOp, OpCFn, OpFTy, OpRustFn, OpRustRet, Ty};
2727
pub use precision::{MaybeOverride, SpecialCase, default_ulp};
28-
pub use run_cfg::{CheckBasis, CheckCtx};
28+
pub use run_cfg::{CheckBasis, CheckCtx, EXTENSIVE_ENV, GeneratorKind};
2929
pub use test_traits::{CheckOutput, GenerateInput, Hex, TupleCall};
3030

3131
/// Result type for tests is usually from `anyhow`. Most times there is no success value to

crates/libm-test/src/run_cfg.rs

Lines changed: 173 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
//! Configuration for how tests get run.
22
3-
#![allow(unused)]
4-
5-
use std::collections::BTreeMap;
63
use std::env;
74
use std::sync::LazyLock;
85

9-
use crate::{BaseName, FloatTy, Identifier, op};
6+
use crate::{BaseName, FloatTy, Identifier, test_log};
107

8+
/// The environment variable indicating which extensive tests should be run.
119
pub const EXTENSIVE_ENV: &str = "LIBM_EXTENSIVE_TESTS";
1210

1311
/// Context passed to [`CheckOutput`].
@@ -49,3 +47,174 @@ pub enum CheckBasis {
4947
/// Check against infinite precision (MPFR).
5048
Mpfr,
5149
}
50+
51+
/// The different kinds of generators that provide test input.
52+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53+
pub enum GeneratorKind {
54+
Domain,
55+
Random,
56+
}
57+
58+
/// A list of all functions that should get extensive tests.
59+
///
60+
/// This also supports the special test name `all` to run all tests, as well as `all_f16`,
61+
/// `all_f32`, `all_f64`, and `all_f128` to run all tests for a specific float type.
62+
static EXTENSIVE: LazyLock<Vec<Identifier>> = LazyLock::new(|| {
63+
let var = env::var(EXTENSIVE_ENV).unwrap_or_default();
64+
let list = var.split(",").filter(|s| !s.is_empty()).collect::<Vec<_>>();
65+
let mut ret = Vec::new();
66+
67+
let append_ty_ops = |ret: &mut Vec<_>, fty: FloatTy| {
68+
let iter = Identifier::ALL.iter().filter(move |id| id.math_op().float_ty == fty).copied();
69+
ret.extend(iter);
70+
};
71+
72+
for item in list {
73+
match item {
74+
"all" => ret = Identifier::ALL.to_owned(),
75+
"all_f16" => append_ty_ops(&mut ret, FloatTy::F16),
76+
"all_f32" => append_ty_ops(&mut ret, FloatTy::F32),
77+
"all_f64" => append_ty_ops(&mut ret, FloatTy::F64),
78+
"all_f128" => append_ty_ops(&mut ret, FloatTy::F128),
79+
s => {
80+
let id = Identifier::from_str(s)
81+
.unwrap_or_else(|| panic!("unrecognized test name `{s}`"));
82+
ret.push(id);
83+
}
84+
}
85+
}
86+
87+
ret
88+
});
89+
90+
/// Information about the function to be tested.
91+
#[derive(Debug)]
92+
struct TestEnv {
93+
/// Tests should be reduced because the platform is slow. E.g. 32-bit or emulated.
94+
slow_platform: bool,
95+
/// The float cannot be tested exhaustively, `f64` or `f128`.
96+
large_float_ty: bool,
97+
/// Env indicates that an extensive test should be run.
98+
should_run_extensive: bool,
99+
/// Multiprecision tests will be run.
100+
mp_tests_enabled: bool,
101+
/// The number of inputs to the function.
102+
input_count: usize,
103+
}
104+
105+
impl TestEnv {
106+
fn from_env(ctx: &CheckCtx) -> Self {
107+
let id = ctx.fn_ident;
108+
let op = id.math_op();
109+
110+
let will_run_mp = cfg!(feature = "test-multiprecision");
111+
112+
// Tests are pretty slow on non-64-bit targets, x86 MacOS, and targets that run in QEMU. Start
113+
// with a reduced number on these platforms.
114+
let slow_on_ci = crate::emulated()
115+
|| usize::BITS < 64
116+
|| cfg!(all(target_arch = "x86_64", target_vendor = "apple"));
117+
let slow_platform = slow_on_ci && crate::ci();
118+
119+
let large_float_ty = match op.float_ty {
120+
FloatTy::F16 | FloatTy::F32 => false,
121+
FloatTy::F64 | FloatTy::F128 => true,
122+
};
123+
124+
let will_run_extensive = EXTENSIVE.contains(&id);
125+
126+
let input_count = op.rust_sig.args.len();
127+
128+
Self {
129+
slow_platform,
130+
large_float_ty,
131+
should_run_extensive: will_run_extensive,
132+
mp_tests_enabled: will_run_mp,
133+
input_count,
134+
}
135+
}
136+
}
137+
138+
/// The number of iterations to run for a given test.
139+
pub fn iteration_count(ctx: &CheckCtx, gen_kind: GeneratorKind, argnum: usize) -> u64 {
140+
let t_env = TestEnv::from_env(ctx);
141+
142+
// Ideally run 5M tests
143+
let mut domain_iter_count: u64 = 4_000_000;
144+
145+
// Start with a reduced number of tests on slow platforms.
146+
if t_env.slow_platform {
147+
domain_iter_count = 100_000;
148+
}
149+
150+
// Larger float types get more iterations.
151+
if t_env.large_float_ty {
152+
domain_iter_count *= 4;
153+
}
154+
155+
// Functions with more arguments get more iterations.
156+
let arg_multiplier = 1 << (t_env.input_count - 1);
157+
domain_iter_count *= arg_multiplier;
158+
159+
// If we will be running tests against MPFR, we don't need to test as much against musl.
160+
// However, there are some platforms where we have to test against musl since MPFR can't be
161+
// built.
162+
if t_env.mp_tests_enabled && ctx.basis == CheckBasis::Musl {
163+
domain_iter_count /= 100;
164+
}
165+
166+
// Run fewer random tests than domain tests.
167+
let random_iter_count = domain_iter_count / 100;
168+
169+
let mut total_iterations = match gen_kind {
170+
GeneratorKind::Domain => domain_iter_count,
171+
GeneratorKind::Random => random_iter_count,
172+
};
173+
174+
if cfg!(optimizations_enabled) {
175+
// Always run at least 10,000 tests.
176+
total_iterations = total_iterations.max(10_000);
177+
} else {
178+
// Without optimizations, just run a quick check regardless of other parameters.
179+
total_iterations = 800;
180+
}
181+
182+
// Adjust for the number of inputs
183+
let ntests = match t_env.input_count {
184+
1 => total_iterations,
185+
2 => (total_iterations as f64).sqrt().ceil() as u64,
186+
3 => (total_iterations as f64).cbrt().ceil() as u64,
187+
_ => panic!("test has more than three arguments"),
188+
};
189+
let total = ntests.pow(t_env.input_count.try_into().unwrap());
190+
191+
test_log(&format!(
192+
"{gen_kind:?} {basis:?} {fn_ident} arg {arg}/{args}: {ntests} iterations \
193+
({total} total)",
194+
basis = ctx.basis,
195+
fn_ident = ctx.fn_ident,
196+
arg = argnum + 1,
197+
args = t_env.input_count,
198+
));
199+
200+
ntests
201+
}
202+
203+
/// For domain tests, limit how many asymptotes or specified check points we test.
204+
pub fn check_point_count(ctx: &CheckCtx) -> usize {
205+
let t_env = TestEnv::from_env(ctx);
206+
if t_env.slow_platform || !cfg!(optimizations_enabled) { 4 } else { 10 }
207+
}
208+
209+
/// When validating points of interest (e.g. asymptotes, inflection points, extremes), also check
210+
/// this many surrounding values.
211+
pub fn check_near_count(_ctx: &CheckCtx) -> u64 {
212+
if cfg!(optimizations_enabled) { 100 } else { 10 }
213+
}
214+
215+
/// Check whether extensive actions should be run or skipped.
216+
#[expect(dead_code, reason = "extensive tests have not yet been added")]
217+
pub fn skip_extensive_test(ctx: &CheckCtx) -> bool {
218+
let t_env = TestEnv::from_env(ctx);
219+
!t_env.should_run_extensive
220+
}

0 commit comments

Comments
 (0)