packages feed

lazyppl-singlesite-0.2.0: src/LazyPPL/SingleSite/Hooks.hs

{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}

-- | Explicit completion and proposal hooks for single-site inference.
--
-- Evaluation must be referentially stable on its supplied Tree and return a
-- finite, forceable result. A suspended callback is resumed before a transition
-- can commit. Hidden mutable core values are not made replay-safe by this API.
-- An exception while forcing a completed result is a terminal
-- 'InvalidCompletedResult', since forcing that same result again cannot retry
-- the evaluator.
--
-- With independent ideal prior draws, reproducible evaluation, and matching
-- site draws and masses, the local and fixed-probability refresh kernels
-- preserve the target distribution. The implementation uses finite 52-bit
-- midpoint acceptance labels and rounded logarithms, so exact machine-level
-- invariance does not follow from that ideal-randomness argument.
--
-- Site discovery inspects evaluated 'Tree' constructors, boxed 'Double'
-- labels and evaluated list cells; unevaluated labels and children are not
-- sites. It follows blackholes and indirections. Other heap representations
-- are not covered. A 'Double' label is decoded from its machine words with
-- @castWord64ToDouble@ on a 64-bit platform; the decoder is tested on Linux
-- x86_64.
--
-- A module compiled with both @-fno-cse@ and @-fno-full-laziness@ can be
-- miscompiled by GHC (see GHC issue #27886); add @-fno-float-in@ to such a
-- module. The tests also pass for a client built with plain @-O2@. Tested on
-- Linux x86_64 with GHC 9.6.7, 9.12.4 and 9.14.1 and lazyppl 1.1.0.1.
module LazyPPL.SingleSite.Hooks
  ( Site, Completion (..), TreeFactory, Evaluator, SiteSelector
  , SiteLaw, mkSiteLaw, mkSiteLawUnchecked, siteMass, uniformSites
  , Kernel, mkKernel, pureEvaluator
  , Snapshot, snapshotResult, snapshotSites
  , Chain, chainSnapshot, chainSources, chainTransitions
  , KernelError (..), ProposalKind (..), Decision (..), TransitionRecord (..)
  , InitialResult (..), PendingInitial, initialise, resumeInitial
  , TransitionResult (..), PendingTransition, transition, resumeTransition
  , acceptanceLog, accepts
  ) where

import Control.DeepSeq (NFData, force)
import Control.Exception
  ( SomeException, SomeAsyncException, displayException, evaluate
  , fromException, tryJust )
import Control.Monad.Trans.Writer (runWriterT)
import Control.Monad.Trans.Cont (ContT (..))
import Data.IORef (newIORef, readIORef)
import qualified Data.Map.Strict as Map
import qualified Data.Map.Lazy as Substitution
import Data.Monoid (Product (..))
import Data.Ratio (denominator, numerator)
import LazyPPL (Meas (..), Tree, randomTree, runProb)
import LazyPPL.Internal.Sampler (randomLabel)
import LazyPPL.SingleSite.Internal
  ( Site, PTree, LocalStep (..), localStepWith
  , getSites, mutateNodes, trunc )
import Numeric.Log (Log, ln)
import System.Random (RandomGen, split, uniformR)

-- | A callback may suspend with an explicit continuation on the same request
-- and source. Calling the continuation is an explicit retry, never a rejection.
-- A permanent failure has no continuation and leaves the chain unchanged.
data Completion e a
  = Complete a
  | Suspend e (IO (Completion e a))
  | Failed e

-- Each call must allocate a fresh heap for the same logical source. An
-- evaluator returns the exact successful heap, never one retained from a
-- failed pass. This is needed for completed used-site discovery.
type TreeFactory = IO Tree
type Evaluator e a = TreeFactory
  -> IO (Completion e (Tree, (a, Product (Log Double))))

-- | The selector is a deterministic function of the completed snapshot.
-- Its IO may complete immutable oracle requests; it must not draw unrecorded
-- auxiliary randomness or turn a backend failure into a different law.
-- A returned 'Failed' is permanent. A thrown synchronous exception suspends
-- the attempt; each explicit resume calls the selector again, so callers must
-- stop resuming a deterministic failure instead of retrying it indefinitely.
type SiteSelector e a = Snapshot a -> IO (Completion (KernelError e) SiteLaw)

-- The ordinary constructor derives the sampler from the assessed masses.
data SiteLaw = SiteLaw
  (forall g. RandomGen g => g -> (Site, g))
  (Map.Map Site Rational)

mkSiteLaw :: [(Site, Rational)] -> Either String SiteLaw
mkSiteLaw entries = mkSiteLawUnchecked draw entries
  where
    common = foldr lcm 1 (map (denominator . snd) entries)
    weighted = [(site, numerator (mass * fromInteger common)) | (site, mass) <- entries]
    draw generator =
      let (ticket, next) = uniformR (1, common) generator
          pick _ [] = error "mkSiteLaw: validated masses do not cover the draw"
          pick n ((site, weight):rest)
            | n <= weight = site
            | otherwise = pick (n - weight) rest
      in (pick ticket weighted, next)

-- State-dependent guides may supply an externally derived sampler. Its author
-- must ensure that sampler and supplied masses describe the same law.
mkSiteLawUnchecked :: (forall g. RandomGen g => g -> (Site, g))
                   -> [(Site, Rational)] -> Either String SiteLaw
mkSiteLawUnchecked draw entries
  | null entries = Left "empty site law"
  | length sites /= Map.size masses = Left "duplicate site"
  | any (any (< 0)) sites = Left "negative site coordinate"
  | any ((< 0) . snd) entries = Left "negative site mass"
  | sum (map snd entries) /= 1 = Left "site masses do not sum to one"
  | any losesLog entries = Left "positive site mass is lost by binary64 logarithm conversion"
  | otherwise = Right (SiteLaw draw masses)
  where
    sites = map fst entries
    masses = Map.fromList entries
    losesLog (_, mass)
      | mass == 0 = False
      | otherwise = let value = log (fromRational mass :: Double)
                    in isNaN value || isInfinite value

siteMass :: SiteLaw -> Site -> Rational
siteMass (SiteLaw _ masses) site = Map.findWithDefault 0 site masses

-- | Reuse the existing maintained discrete selector, with its assessed mass.
uniformSites :: SiteSelector e a
uniformSites snapshot =
  let sites = snapshotSites snapshot
      mass = 1 / fromIntegral (length sites)
  in case mkSiteLaw [(site, mass) | site <- sites] of
       Right law -> pure (Complete law)
       Left message -> pure (Failed (InvalidSiteLaw message))

data Kernel e a = Kernel
  { evaluator :: Evaluator e a
  , selector :: SiteSelector e a
  , refreshProbability :: Rational
  }

-- | The fixed refresh probability is independent of the current state.
-- A positive value provides a whole-prior-tree proposal, including currently
-- hidden branches. It does not prove posterior connectivity or finite runtime.
mkKernel :: Rational -> Evaluator e a -> SiteSelector e a
         -> Either String (Kernel e a)
mkKernel probability evaluateTree selectSite
  | probability < 0 || probability > 1 = Left "refresh probability outside [0,1]"
  | otherwise = Right (Kernel evaluateTree selectSite probability)

pureEvaluator :: Meas a -> Evaluator e a
pureEvaluator (Meas model) fresh = do
  tree <- fresh
  pure (Complete (tree, runProb (runWriterT model) tree))

-- Keep the actual evaluated tree and value/weight pair, not an extensional
-- reconstruction. Rejection returns this same Snapshot object.
data Snapshot a = Snapshot Tree (a, Product (Log Double)) PTree [Site]

snapshotResult :: Snapshot a -> (a, Product (Log Double))
snapshotResult (Snapshot _ result _ _) = result

-- A selector sees only the completed result and its revealed site paths; it
-- cannot use this interface to demand additional labels from the latent Tree.
snapshotSites :: Snapshot a -> [Site]
snapshotSites (Snapshot _ _ _ sites) = sites

data Chain g a = Chain
  { chainSnapshot :: Snapshot a
  , chainTreeSeed :: g
  , chainSubstitution :: Map.Map Site (g, Double)
  , chainProposalSeed :: !g
  , chainTransitions :: !Int
  }

-- | Source identity for finite reproducibility records. Sites are root-to-leaf.
-- This is not serialization of arbitrary suspended callbacks or model values.
chainSources :: Chain g a -> (g, g, [(Site, Double)])
chainSources chain =
  (chainTreeSeed chain, chainProposalSeed chain,
   [(site, value) | (site, (_, value)) <- Map.toAscList (chainSubstitution chain)])

-- Rebuild using the established randomTree/mutateNodes implementation. Read
-- the recipe inside each invocation through an IO allocation boundary rather
-- than supplying a closed pure Tree expression. Mutation recipes regenerate the
-- same label; they do not insert a previously forced Double into the new heap.
-- This is compiler-qualified by the optimized missed-request/demand controls,
-- not a language-level theorem that a pure wrapper guarantees fresh objects.
materialiseTree :: RandomGen g => g -> Map.Map Site (g, Double) -> TreeFactory
materialiseTree seed edits = do
  source <- newIORef (seed, edits)
  (freshSeed, freshEdits) <- readIORef source
  let substitutions = Substitution.map (\(generator, _) -> fst (randomLabel generator)) freshEdits
  evaluate (mutateNodes (randomTree freshSeed) substitutions)
{-# NOINLINE materialiseTree #-}

data KernelError e
  = CallbackInterrupted e
  | CallbackFailed e
  | InvalidCompletedResult String
  | InvalidCompletedWeight Double
  | InvalidSiteLaw String
  | InvalidSelection Site
  | SynchronousFailure String
  deriving (Eq, Show)

data ProposalKind = ResampleSite Site | RefreshAll | NoActiveSite
  deriving (Eq, Show)

data Decision = Accepted | Rejected | Stayed
  deriving (Eq, Show)

-- | Site masses include state-dependent selection. The fixed branch-mixture
-- probability cancels for each reversible component. A fresh uniform label
-- and a whole-prior-tree refresh each cancel against their prior source law.
data TransitionRecord = TransitionRecord
  { transitionIndex :: Int
  , proposalKind :: ProposalKind
  , decision :: Decision
  , forwardSiteMass :: Maybe Rational
  , reverseSiteMass :: Maybe Rational
  , acceptanceUniform :: Maybe Double
  , logAcceptance :: Maybe Rational
  , previousLogWeight :: Double
  , candidateLogWeight :: Maybe Double
  } deriving (Eq, Show)

data InitialResult e g a
  = Initialised (Chain g a)
  | InitialInterrupted (KernelError e) (PendingInitial e g a)
  | InitialFailed (KernelError e)

newtype PendingInitial e g a =
  PendingInitial (IO (InitialResult e g a))

resumeInitial :: PendingInitial e g a -> IO (InitialResult e g a)
resumeInitial (PendingInitial action) = action

data TransitionResult e g a
  = Transitioned (Chain g a) TransitionRecord
  | TransitionInterrupted (KernelError e) (Chain g a) (PendingTransition e g a)
  | TransitionFailed (KernelError e) (Chain g a)

newtype PendingTransition e g a =
  PendingTransition (IO (TransitionResult e g a))

resumeTransition :: PendingTransition e g a -> IO (TransitionResult e g a)
resumeTransition (PendingTransition action) = action

bindCompletion :: IO (Completion e a)
               -> (a -> IO (Completion e b)) -> IO (Completion e b)
bindCompletion action next = do
  result <- action
  case result of
    Complete value -> next value
    Suspend err resume -> pure (Suspend err (bindCompletion resume next))
    Failed err -> pure (Failed err)

-- Use the maintained continuation transformer to instantiate the shared
-- generic local step. Suspension closes over the continuation of that same
-- step; it does not restart selection or consume another random label.
awaitCompletion :: IO (Completion e a) -> ContT (Completion e r) IO a
awaitCompletion action = ContT (bindCompletion action)

mapCallback :: IO (Completion e a) -> IO (Completion (KernelError e) a)
mapCallback action = protect (do
  result <- action
  case result of
    Complete value -> evaluate value >> pure result
    _ -> pure result) `bindCompletion` mapResult
  where
    mapResult (Complete value) = pure (Complete value)
    mapResult (Failed err) = pure (Failed (CallbackFailed err))
    mapResult (Suspend err resume) =
      pure (Suspend (CallbackInterrupted err) (mapCallback resume))

-- Catch synchronous execution/forcing failures only. Cancellation propagates;
-- it never becomes a zero-weight state or a silently rejected proposal.
protect :: IO a -> IO (Completion (KernelError e) a)
protect action = do
  result <- tryJust synchronous action
  case result of
    Right value -> pure (Complete value)
    Left err -> pure (Suspend (SynchronousFailure (displayException err)) (protect action))

synchronous :: SomeException -> Maybe SomeException
synchronous err = case fromException err :: Maybe SomeAsyncException of
  Just _ -> Nothing
  Nothing -> Just err

invalid :: KernelError e -> IO (Completion (KernelError e) a)
invalid err = pure (Failed err)

completeSnapshot :: NFData a => (Tree, (a, Product (Log Double)))
                 -> IO (Completion (KernelError e) (Snapshot a))
completeSnapshot (tree, result) = do
  outcome <- tryJust synchronous (evaluate (force result))
  case outcome of
    Left err -> invalid (InvalidCompletedResult (displayException err))
    Right forced ->
      let weight = ln (getProduct (snd forced))
      in if isNaN weight || (isInfinite weight && weight > 0)
           then invalid (InvalidCompletedWeight weight)
           else protect (do
             partial <- trunc tree
             sites <- evaluate (force (map reverse (getSites partial)))
             pure (Snapshot tree forced partial sites))

evaluateSnapshot :: NFData a => Kernel e a -> TreeFactory
                 -> IO (Completion (KernelError e) (Snapshot a))
evaluateSnapshot kernel fresh =
  mapCallback (evaluator kernel fresh) `bindCompletion` completeSnapshot

initialise :: (RandomGen g, NFData a) => Kernel e a -> g
           -> IO (InitialResult e g a)
initialise kernel source =
  let (treeSeed, proposalSeed) = split source
      finish action = do
        result <- action
        case result of
          Complete snapshot ->
            pure (Initialised (Chain snapshot treeSeed Substitution.empty proposalSeed 0))
          Suspend err resume ->
            pure (InitialInterrupted err (PendingInitial (finish resume)))
          Failed err -> pure (InitialFailed err)
  in finish (evaluateSnapshot kernel (materialiseTree treeSeed Substitution.empty))

snapshotWeight :: Snapshot a -> Double
snapshotWeight = ln . getProduct . snd . snapshotResult

-- | Log of min(1, w'/w * q_reverse/q_forward), represented as an exact rational
-- combination of the supplied finite binary64 logarithms. Nothing is zero
-- acceptance. This avoids overflowing intermediate log differences.
-- The site masses are full marginal probabilities, not selected-component
-- probabilities or normalized importance weights from another inference run.
acceptanceLog :: Double -> Double -> Rational -> Rational -> Maybe Rational
acceptanceLog old new forward reverse
  | forward <= 0 || reverse <= 0 = Nothing
  | isNaN old || isNaN new = Nothing
  | isInfinite new && new < 0 = Nothing
  | isInfinite old && old < 0 = Just 0
  | isInfinite old || isInfinite new = Nothing
  | otherwise = Just (min 0
      (toRational new - toRational old
       + toRational (log (fromRational reverse :: Double))
       - toRational (log (fromRational forward :: Double))))

-- | The core supplies open 52-bit midpoint labels. The comparison is strict,
-- like the original mh1 acceptance convention; no zero label can accept a
-- zero-mass candidate. A fixed seed is execution evidence, not a continuous-
-- randomness stationarity theorem.
accepts :: Double -> Maybe Rational -> Bool
accepts uniformLabel threshold
  | isNaN uniformLabel || uniformLabel <= 0 || uniformLabel >= 1 = False
  | otherwise = maybe False (toRational (log uniformLabel) <) threshold

checkedSelection :: Snapshot a -> SiteLaw
                 -> IO (Completion (KernelError e) SiteLaw)
checkedSelection snapshot law@(SiteLaw _ masses) =
  protect (evaluate (force (Map.toAscList masses))) `bindCompletion` \entries ->
    if any (\(site, mass) -> mass > 0 && site `notElem` snapshotSites snapshot) entries
      then invalid (InvalidSiteLaw "positive selection mass outside active sites")
      else pure (Complete law)

selectLaw :: Kernel e a -> Snapshot a
          -> IO (Completion (KernelError e) SiteLaw)
selectLaw kernel snapshot =
  protectSelector (selector kernel snapshot) `bindCompletion` checkedSelection snapshot

protectSelector :: IO (Completion (KernelError e) a)
                -> IO (Completion (KernelError e) a)
protectSelector action = protect (do
  result <- action
  case result of
    Complete value -> evaluate value >> pure result
    _ -> pure result) `bindCompletion` \result -> case result of
  Complete value -> pure (Complete value)
  Failed err -> pure (Failed err)
  Suspend err resume -> pure (Suspend err (protectSelector resume))

transition :: (RandomGen g, NFData a) => Kernel e a -> Chain g a
           -> IO (TransitionResult e g a)
transition kernel original = finish attempt
  where
    old = chainSnapshot original
    oldWeight = snapshotWeight old
    count = chainTransitions original + 1
    (proposalSource, nextSource) = split (chainProposalSeed original)
    probability = refreshProbability kernel

    finish action = do
      result <- action
      case result of
        Complete (chain, record) -> pure (Transitioned chain record)
        Failed err -> pure (TransitionFailed err original)
        Suspend err resume -> pure
          (TransitionInterrupted err original (PendingTransition (finish resume)))

    -- Only a completed decision commits the proposal generator. The original
    -- chain and the exact suspended attempt remain available on interruption.
    advance snapshot seed substitutions = Chain snapshot seed substitutions nextSource count
    retained = advance old (chainTreeSeed original) (chainSubstitution original)

    record kind verdict forward reverse label threshold proposed =
      TransitionRecord count kind verdict forward reverse label threshold oldWeight proposed

    attempt
      | probability == 0 = local proposalSource
      | probability == 1 = refresh proposalSource
      | otherwise =
          let (ticket, rest) = uniformR (1, denominator probability) proposalSource
          in if ticket <= numerator probability then refresh rest else local rest

    refresh source =
      let (treeSeed, acceptanceSource) = split source
      in protect (evaluate (fst (randomLabel acceptanceSource))) `bindCompletion` \label ->
         evaluateSnapshot kernel (materialiseTree treeSeed Substitution.empty) `bindCompletion` \candidate ->
           let newWeight = snapshotWeight candidate
               threshold = acceptanceLog oldWeight newWeight 1 1
               accepted = accepts label threshold
               next = if accepted then advance candidate treeSeed Substitution.empty else retained
               verdict = if accepted then Accepted else Rejected
           in pure (Complete (next,
                record RefreshAll verdict Nothing Nothing (Just label) threshold (Just newWeight)))

    local source = runContT
      (localStepWith (if null (snapshotSites old) then Nothing else Just choose)
        evaluateCandidate decide source)
      commit
      where
        choose generator = do
          law@(SiteLaw draw _) <- awaitCompletion (selectLaw kernel old)
          let (siteSource, labelSource) = split generator
          site <- awaitCompletion (protect (evaluate (forceSite labelSource (fst (draw siteSource)))))
          if site `notElem` snapshotSites old || siteMass law site <= 0
            then awaitCompletion (invalid (InvalidSelection site))
            else pure (site, labelSource, law)
        evaluateCandidate site labelSource newLabel = do
          let substitutions = Substitution.insert site (labelSource, newLabel)
                (chainSubstitution original)
          candidate <- awaitCompletion (evaluateSnapshot kernel
            (materialiseTree (chainTreeSeed original) substitutions))
          pure (substitutions, candidate)
        decide site law label (_, candidate) = do
          reverse <- if site `notElem` snapshotSites candidate then pure 0 else do
            reverseLaw <- awaitCompletion (selectLaw kernel candidate)
            pure (siteMass reverseLaw site)
          let forward = siteMass law site
              newWeight = snapshotWeight candidate
              threshold = acceptanceLog oldWeight newWeight forward reverse
          pure (forward, reverse, threshold, newWeight, accepts label threshold)
        commit NoLocalSite = pure (Complete
          (retained, record NoActiveSite Stayed Nothing Nothing Nothing Nothing Nothing))
        commit (LocalStep site _ label (substitutions, candidate)
                (forward, reverse, threshold, newWeight, accepted)) =
          let next = if accepted
                then advance candidate (chainTreeSeed original) substitutions
                else retained
              verdict = if accepted then Accepted else Rejected
          in pure (Complete (next,
            record (ResampleSite site) verdict (Just forward) (Just reverse)
              (Just label) threshold (Just newWeight)))

    -- RandomGen need not have NFData. Force both labels the local step will
    -- use while the draw is protected, as well as the complete chosen site.
    forceSite labelSource site =
      let (replacement, next) = randomLabel labelSource
          (acceptance, _) = randomLabel next
      in force site `seq` replacement `seq` acceptance `seq` site