packages feed

hsmt-0.1.0.0: test/HSMT/FloatSpec.hs

-- | Floating point: the reference semantics against the IEEE arithmetic of
-- GHC, and the bit-blasted circuits against the reference semantics.
module HSMT.FloatSpec (tests) where

import qualified Data.Text as T
import GHC.Float (castDoubleToWord64, castFloatToWord32, castWord32ToFloat, castWord64ToDouble)
import Test.QuickCheck
import Test.QuickCheck.Monadic (monadicIO, run)
import qualified Test.QuickCheck.Monadic as QC
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck (testProperty)

import HSMT.Core.Eval
import HSMT.Core.Expr
import HSMT.Core.Float
import HSMT.Core.Op
import HSMT.Core.Sort
import HSMT.Core.Value
import HSMT.Gen.Expr (fpLiteral)
import HSMT.SMT.Engine

tests :: TestTree
tests =
  testGroup
    "Floating point"
    [ testGroup
        "reference semantics against GHC (round to nearest even)"
        [ testProperty "Float32" prop_float
        , testProperty "Float64" prop_double
        ]
    , testCase "special values" $ do
        let one = encode 8 24 (Finite False 1)
            two = encode 8 24 (Finite False 2)
            nan = canonicalNaN 8 24
            inf = encode 8 24 (Inf False)
        fpAdd RNE 8 24 one one @?= two
        fpDiv RNE 8 24 one (encode 8 24 (Zero True)) @?= encode 8 24 (Inf True)
        fpMul RNE 8 24 inf (encode 8 24 (Zero False)) @?= nan
        fpAdd RTN 8 24 one (fpNeg 8 24 one) @?= encode 8 24 (Zero True)
        fpAdd RNE 8 24 one (fpNeg 8 24 one) @?= encode 8 24 (Zero False)
        fpSqrt RNE 8 24 (encode 8 24 (Zero True)) @?= encode 8 24 (Zero True)
        fpMin 8 24 (encode 8 24 (Zero True)) (encode 8 24 (Zero False)) @?= Nothing
        fpToInteger RTZ 8 24 (0, 15) (encode 8 24 (Finite False 15.75)) @?= Just 15
        fpToInteger RNE 8 24 (0, 15) (encode 8 24 (Finite False 15.75)) @?= Nothing
        fpRem RNE 8 24 (encode 8 24 (Finite False 5)) (encode 8 24 (Finite False 2)) @?= one
        fpRem RNE 8 24 (encode 8 24 (Finite False 7)) (encode 8 24 (Finite False 2)) @?= encode 8 24 (Finite True 1)
    , testGroup
        "circuits agree with the reference semantics"
        [ testProperty "small formats" (prop_circuits [(3, 3), (3, 4), (4, 3), (2, 5), (5, 4)])
        , testProperty "Float16" (withMaxSuccess 200 (prop_circuits [(5, 11)]))
        , testProperty "Float32" (withMaxSuccess 40 (prop_circuits [(8, 24)]))
        ]
    , testCase "solving" $ do
        -- x + 1 = x has only infinite and huge solutions in Float16.
        r1 <- solve [App Eq [App FPAdd [rne, x16, one16], x16], App Not [App FPIsInfinite [x16]]]
        r1 @?= "sat"
        r2 <- solve [App Eq [App FPAdd [rne, x16, one16], x16], App FPLt [App FPAbs [x16], big16]]
        r2 @?= "unsat"
        -- NaN is not fp.eq to itself but is = to itself.
        r3 <- solve [App FPIsNaN [x16], App FPEq [x16, x16]]
        r3 @?= "unsat"
        r4 <- solve [App FPIsNaN [x16], App Not [App Eq [x16, x16]]]
        r4 @?= "unsat"
        -- fp.min of zeros of different signs may be either zero.
        let pz = constant (FPConst 5 11 0)
            nz = constant (FPConst 5 11 (2 ^ (15 :: Int)))
        r5 <- solve [App Eq [App FPMin [pz, nz], pz]]
        r6 <- solve [App Eq [App FPMin [pz, nz], nz]]
        r7 <- solve [App Not [App Eq [App FPMin [pz, nz], App FPMin [pz, nz]]]]
        (r5, r6, r7) @?= ("sat", "sat", "unsat")
    ]
  where
    rne = constant (RMConst RNE)
    x16 = constant (Uninterpreted (Symbol "x" [] (FPSort 5 11)))
    one16 = constant (FPConst 5 11 (encode 5 11 (Finite False 1)))
    big16 = constant (FPConst 5 11 (encode 5 11 (Finite False 2048)))

solve :: [Expr] -> IO String
solve as =
  solveAssertions True as >>= \case
    ESat _ -> pure "sat"
    EUnsat _ -> pure "unsat"
    EUnknown why -> pure ("unknown: " <> show why)

-------------------------------------------------------------------------------
-- Against GHC

-- | Patterns of special values, extremes and random bits.
genBits :: Int -> Int -> Gen Integer
genBits = fpLiteral

prop_float :: Property
prop_float = forAll ((,,) <$> elements ops <*> genBits 8 24 <*> genBits 8 24) $ \(name, a, b) ->
  let fa = castWord32ToFloat (fromInteger a)
      fb = castWord32ToFloat (fromInteger b)
      bitsOf :: Float -> Integer
      bitsOf = canonicalize 8 24 . toInteger . castFloatToWord32
      (mine, ghc) = case name of
        "add" -> (fpAdd RNE 8 24 a b, bitsOf (fa + fb))
        "sub" -> (fpSub RNE 8 24 a b, bitsOf (fa - fb))
        "mul" -> (fpMul RNE 8 24 a b, bitsOf (fa * fb))
        "div" -> (fpDiv RNE 8 24 a b, bitsOf (fa / fb))
        _ -> (fpSqrt RNE 8 24 a, bitsOf (sqrt fa))
   in counterexample (show (name, fa, fb, mine, ghc)) (mine === ghc)
  where
    ops = ["add", "sub", "mul", "div", "sqrt"] :: [String]

prop_double :: Property
prop_double = forAll ((,,) <$> elements ops <*> genBits 11 53 <*> genBits 11 53) $ \(name, a, b) ->
  let fa = castWord64ToDouble (fromInteger a)
      fb = castWord64ToDouble (fromInteger b)
      bitsOf :: Double -> Integer
      bitsOf = canonicalize 11 53 . toInteger . castDoubleToWord64
      (mine, ghc) = case name of
        "add" -> (fpAdd RNE 11 53 a b, bitsOf (fa + fb))
        "sub" -> (fpSub RNE 11 53 a b, bitsOf (fa - fb))
        "mul" -> (fpMul RNE 11 53 a b, bitsOf (fa * fb))
        "div" -> (fpDiv RNE 11 53 a b, bitsOf (fa / fb))
        _ -> (fpSqrt RNE 11 53 a, bitsOf (sqrt fa))
   in counterexample (show (name, fa, fb, mine, ghc)) (mine === ghc)
  where
    ops = ["add", "sub", "mul", "div", "sqrt"] :: [String]

-------------------------------------------------------------------------------
-- Circuits

-- | For random operands, the circuit of each operator must give exactly
-- the value of the reference semantics (or, where SMT-LIB leaves the
-- result unspecified, accept it). The operands are variables fixed by
-- equalities, so the circuits are not constant-folded.
prop_circuits :: [(Int, Int)] -> Property
prop_circuits formats = forAll gen $ \(op, fmt, rm, vals) -> monadicIO $ do
  let (eb, sb) = fmt
      fpVar n = constant (Uninterpreted (Symbol n [] (FPSort eb sb)))
      names = ["a", "b", "c"]
      args = [fpVar n | n <- take (length vals) names]
      fixes = [App Eq [a, constant (FPConst eb sb v)] | (a, v) <- zip args vals]
      rmArg = [constant (RMConst rm) | needsRM op]
      term = App op (rmArg <> args)
      concrete = App op (rmArg <> [constant (FPConst eb sb v) | v <- vals])
      expected = either (error . show) id (evalExpr emptyInterpretation concrete)
      specified = not (unspecified op fmt rm vals)
      valueTerm = case expected of
        VFP e s v -> constant (FPConst e s v)
        VBV w v -> constant (BVConst w v)
        VBool b -> constant (BoolConst b)
        other -> error (show other)
  agrees <- run (solve (fixes <> [App Eq [term, valueTerm]]))
  differs <- run (solve (fixes <> [App Not [App Eq [term, valueTerm]]]))
  QC.monitor (counterexample (show (op, fmt, rm, vals, expected, agrees, differs)))
  QC.monitor (label (T.unpack (opName op)))
  QC.assert (if specified then agrees == "sat" && differs == "unsat" else agrees == "sat" || differs == "sat")
  where
    gen = do
      fmt@(eb, sb) <- elements formats
      (op, arity) <- elements operators
      rm <- elements allRoundingModes
      vals <- vectorOf arity (fpLiteral eb sb)
      pure (op, fmt, rm, vals)
    operators =
      [(o, 2) | o <- [FPAdd, FPSub, FPMul, FPDiv, FPRem, FPMin, FPMax, FPLeq, FPLt, FPEq]]
        <> [(FPFma, 3)]
        <> [ (o, 1)
           | o <-
               [ FPSqrt, FPRoundToIntegral, FPAbs, FPNeg, FPIsNormal, FPIsSubnormal, FPIsZero
               , FPIsInfinite, FPIsNaN, FPIsNegative, FPIsPositive
               , ToFP 3 5, ToFP 6 7, FPToUBV 4, FPToSBV 5
               ]
           ]
    needsRM = \case
      o | o `elem` [FPAdd, FPSub, FPMul, FPDiv, FPFma, FPSqrt, FPRoundToIntegral] -> True
      ToFP _ _ -> True
      FPToUBV _ -> True
      FPToSBV _ -> True
      _ -> False
    unspecified op (eb, sb) rm vals = case (op, vals) of
      (FPMin, [x, y]) -> fpMin eb sb x y == Nothing
      (FPMax, [x, y]) -> fpMax eb sb x y == Nothing
      (FPToUBV w, [x]) -> fpToInteger rm eb sb (0, 2 ^ w - 1) x == Nothing
      (FPToSBV w, [x]) -> fpToInteger rm eb sb (negate (2 ^ (w - 1)), 2 ^ (w - 1) - 1) x == Nothing
      _ -> False