diff --git a/Project.toml b/Project.toml index 4cd8469a..c7ee341f 100644 --- a/Project.toml +++ b/Project.toml @@ -8,6 +8,7 @@ DiffResults = "163ba53b-c6d8-5494-b064-1a9d43ac40c5" DiffRules = "b552c78f-8df3-52c6-915a-8e097449b14b" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" NaNMath = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" +Preferences = "21216c6a-2e73-6563-6e65-726566657250" Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" SpecialFunctions = "276daf66-3868-5448-9aa4-cd146d93841b" @@ -20,6 +21,7 @@ DiffResults = "0.0.1, 0.0.2, 0.0.3, 0.0.4, 1.0.1" DiffRules = "1.2.1" DiffTests = "0.0.1, 0.1" NaNMath = "0.2.2, 0.3" +Preferences = "1" SpecialFunctions = "0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.10, 1.0" StaticArrays = "0.8.3, 0.9, 0.10, 0.11, 0.12, 1.0" julia = "1" diff --git a/docs/src/user/advanced.md b/docs/src/user/advanced.md index d12c3b9e..a304ff9e 100644 --- a/docs/src/user/advanced.md +++ b/docs/src/user/advanced.md @@ -138,8 +138,15 @@ decrease performance (~5%-10% on our benchmarks). In order to preserve performance in the majority of use cases, ForwardDiff disables this check by default. If your code is affected by this `NaN` behavior, you can enable -ForwardDiff's `NaN`-safe mode by setting the `NANSAFE_MODE_ENABLED` constant to `true` in -ForwardDiff's source. The constant is located in `src\prelude.jl`. +ForwardDiff's `NaN`-safe mode by using the +[Preferences.jl](https://github.com/JuliaPackaging/Preferences.jl) API to set +the `nansafe_mode` preference to true, for example via: + +```julia +julia> using ForwardDiff, Preferences + +julia> set_preferences!(ForwardDiff, "nansafe_mode" => true) +``` In the future, we plan on allowing users and downstream library authors to dynamically enable [NaN`-safe mode via the `AbstractConfig` diff --git a/src/ForwardDiff.jl b/src/ForwardDiff.jl index 51ce95a1..aacdbb8a 100644 --- a/src/ForwardDiff.jl +++ b/src/ForwardDiff.jl @@ -3,6 +3,9 @@ module ForwardDiff using DiffRules, DiffResults using DiffResults: DiffResult, MutableDiffResult, ImmutableDiffResult using StaticArrays +if VERSION >= v"1.6" + using Preferences +end using Random using LinearAlgebra diff --git a/src/prelude.jl b/src/prelude.jl index bfa72fd9..6c161537 100644 --- a/src/prelude.jl +++ b/src/prelude.jl @@ -1,4 +1,8 @@ -const NANSAFE_MODE_ENABLED = false +@static if VERSION >= v"1.6" + const NANSAFE_MODE_ENABLED = @load_preference("nansafe_mode", false) +else + const NANSAFE_MODE_ENABLED = false +end const AMBIGUOUS_TYPES = (AbstractFloat, Irrational, Integer, Rational, Real, RoundingMode)