packages feed

hasktorch-CudaHashMap-0.1.1.0: test/Main.hs

module Main (main) where

import Control.Exception (SomeException, try)
import Control.Monad (unless)
import Data.Int (Int32, Int64)
import Torch.Device (Device(..), DeviceType(..))
import Torch.Functional (indexPut)
import Torch.Tensor (asTensor, asValue, device, indexSelect, toDevice)
import Torch.TensorFactories (zeros')
import Torch.CudaHashMap

assertEq :: (Eq a, Show a) => String -> a -> a -> IO ()
assertEq msg expected actual =
  unless (expected == actual) $
    error $ "Assertion failed (" ++ msg ++ "): expected " ++ show expected ++ ", got " ++ show actual

assertTrue :: String -> Bool -> IO ()
assertTrue msg cond =
  unless cond $
    error $ "Assertion failed: " ++ msg

assertThrows :: String -> IO a -> IO ()
assertThrows msg action = do
  res <- (try (action >> return ()) :: IO (Either SomeException ()))
  case res of
    Left _  -> return ()
    Right _ -> error $ "Assertion failed (" ++ msg ++ "): expected an exception, but succeeded"

main :: IO ()
main = do
  putStrLn "=== Test 1: Int32 Key -> Int32 Value ==="
  m1 <- newCudaHashMap
  let k1 = asTensor ([1, 2, 3] :: [Int32])
      v1 = asTensor ([10, 20, 30] :: [Int32])
      v1_overwrite = asTensor ([100, 200, 300] :: [Int32])
  insertBatch m1 k1 v1
  insertBatch m1 k1 v1_overwrite
  finalizeCudaHashMap m1
  res1 <- lookupBatch m1 (asTensor ([3, 1, 99] :: [Int32]))
  print res1
  assertEq "Test 1 values" ([300, 100, -1] :: [Int32]) (asValue (toDevice (Device CPU 0) res1))

  putStrLn "=== Test 2: Int64 Key -> Float Value ==="
  m2 <- newCudaHashMap
  let k2 = asTensor ([100, 200, 300] :: [Int64])
      v2 = asTensor ([1.25, 2.5, 3.75] :: [Float])
  insertBatch m2 k2 v2
  finalizeCudaHashMap m2
  res2 <- lookupBatch m2 (asTensor ([200, 100, 999] :: [Int64]))
  print res2
  case (asValue (toDevice (Device CPU 0) res2) :: [Float]) of
    [r2a, r2b, r2c] -> do
      assertEq "Test 2 key 200" 2.5 r2a
      assertEq "Test 2 key 100" 1.25 r2b
      assertTrue "Test 2 missing key is NaN" (isNaN r2c)
    xs -> error $ "Assertion failed (Test 2 length): got " ++ show xs

  putStrLn "=== Test 3: Key -> Index (Int64) for indexPut / indexSelect ==="
  m3 <- newCudaHashMap
  let table0 = zeros' [10]
      batchKeys1 = asTensor ([500, 600, 500, 700] :: [Int64])
      batchVals1 = asTensor ([5.0, 6.0, 5.5, 7.0] :: [Float])
  idx1 <- insertKeys m3 batchKeys1
  let dev    = device idx1
      table1 = indexPut False [idx1] (toDevice dev batchVals1) (toDevice dev table0)
  finalizeCudaHashMap m3
  qIdx <- lookupIndices m3 (asTensor ([700, 500, 600] :: [Int64]))
  let out = indexSelect 0 qIdx table1
  print out

  putStrLn "=== Test 4: capacityCudaHashMap & insertBatchWithRehash ==="
  m4 <- newCudaHashMap
  capInit <- capacityCudaHashMap m4
  assertEq "uninitialized capacity is 0" 0 capInit

  -- Insert while still dynamic_map -> should not trigger static_map rehash
  let initKeys = [1 .. 100] :: [Int64]
      initVals = map (* 10) initKeys :: [Int64]
  rehashedDyn <- insertBatchWithRehash m4 0.75 (asTensor initKeys) (asTensor initVals)
  assertEq "dynamic_map insertBatchWithRehash returns False" False rehashedDyn
  capDyn <- capacityCudaHashMap m4
  assertTrue ("dynamic_map capacity >= 100000, got " ++ show capDyn) (capDyn >= 100000)

  -- Compact into static_map (actual_size = 100 -> optimal_capacity = 1024)
  finalizeCudaHashMap m4
  capStatic0 <- capacityCudaHashMap m4
  assertTrue ("finalized capacity >= 1024 and < 100000, got " ++ show capStatic0)
             (capStatic0 >= 1024 && capStatic0 < 100000)

  -- Insert 500 more keys -> total 600 <= capStatic0 * 0.75 -> no rehash
  let batchAKeys = [101 .. 600] :: [Int64]
      batchAVals = map (* 10) batchAKeys :: [Int64]
  rehashedA <- insertBatchWithRehash m4 0.75 (asTensor batchAKeys) (asTensor batchAVals)
  assertEq "batch under threshold does not rehash" False rehashedA
  capStaticA <- capacityCudaHashMap m4
  assertEq "capacity unchanged when under threshold" capStatic0 capStaticA

  -- Overwrite all 600 existing keys (worst-case 600 + 600 = 1200 > capStatic0 * 0.75,
  -- but actual new keys = 0) -> should NOT rehash!
  let overwriteKeys = [1 .. 600] :: [Int64]
      overwriteVals = map (* 20) overwriteKeys :: [Int64]
  rehashedOverwrite <- insertBatchWithRehash m4 0.75 (asTensor overwriteKeys) (asTensor overwriteVals)
  assertEq "overwriting existing keys does not trigger false rehash" False rehashedOverwrite
  capAfterOverwrite <- capacityCudaHashMap m4
  assertEq "capacity unchanged after overwrite" capStatic0 capAfterOverwrite

  -- Insert 300 brand new keys -> total 900 > capStatic0 * 0.75 -> MUST rehash!
  let batchBKeys = [601 .. 900] :: [Int64]
      batchBVals = map (* 20) batchBKeys :: [Int64]
  rehashedB <- insertBatchWithRehash m4 0.75 (asTensor batchBKeys) (asTensor batchBVals)
  assertEq "exceeding threshold triggers rehash" True rehashedB
  capStaticB <- capacityCudaHashMap m4
  sizeB <- sizeCudaHashMap m4
  assertEq "size after rehash is 900" 900 sizeB
  assertTrue ("capacity grew after rehash: " ++ show capStatic0 ++ " -> " ++ show capStaticB)
             (capStaticB > capStatic0)
  assertTrue "load factor after rehash <= 0.75"
             (fromIntegral sizeB <= fromIntegral capStaticB * (0.75 :: Double))

  -- Verify all 900 keys (overwritten old keys + new keys) are intact
  let all900 = [1 .. 900] :: [Int64]
  res900 <- lookupBatch m4 (asTensor all900)
  assertEq "all 900 values preserved after rehash"
           (map (* 20) all900)
           (asValue (toDevice (Device CPU 0) res900) :: [Int64])

  -- Huge single batch that jumps well past 2 * capStaticB -> MUST rehash to fit
  let hugeKeys = [901 .. 6000] :: [Int64]
      hugeVals = map (* 20) hugeKeys :: [Int64]
  rehashedHuge <- insertBatchWithRehash m4 0.75 (asTensor hugeKeys) (asTensor hugeVals)
  assertEq "huge batch triggers rehash" True rehashedHuge
  capHuge <- capacityCudaHashMap m4
  sizeHuge <- sizeCudaHashMap m4
  assertEq "size after huge batch is 6000" 6000 sizeHuge
  assertTrue "load factor after huge batch <= 0.75"
             (fromIntegral sizeHuge <= fromIntegral capHuge * (0.75 :: Double))
  resHugeSample <- lookupBatch m4 (asTensor ([1, 600, 900, 901, 6000, 99999] :: [Int64]))
  assertEq "sample lookup after huge rehash"
           ([20, 12000, 18000, 18020, 120000, -1] :: [Int64])
           (asValue (toDevice (Device CPU 0) resHugeSample))

  putStrLn "=== Test 5: insertKeysWithRehash & hashMapIndexPutWithRehash ==="
  m5 <- newCudaHashMap
  let k5Init = [1 .. 50] :: [Int64]
  idx5Init <- insertKeys m5 (asTensor k5Init)
  let initIndices = asValue (toDevice (Device CPU 0) idx5Init) :: [Int64]
  finalizeCudaHashMap m5
  cap5_0 <- capacityCudaHashMap m5

  -- Add 200 keys with strict threshold 0.2 -> 250 > cap5_0 * 0.2 (~204.8) -> MUST rehash!
  let k5More = [51 .. 250] :: [Int64]
  (idx5More, rehashed5) <- insertKeysWithRehash m5 0.2 (asTensor k5More)
  assertEq "insertKeysWithRehash triggers rehash at low threshold 0.2" True rehashed5
  cap5_1 <- capacityCudaHashMap m5
  size5_1 <- sizeCudaHashMap m5
  assertEq "size after insertKeysWithRehash is 250" 250 size5_1
  assertTrue ("capacity grew for low threshold 0.2: " ++ show cap5_0 ++ " -> " ++ show cap5_1)
             (cap5_1 > cap5_0)
  assertTrue "load factor <= 0.2 after rehash"
             (fromIntegral size5_1 <= fromIntegral cap5_1 * (0.2 :: Double))

  -- Verify old keys kept their exact original indices and new keys got [50 .. 249]
  q5Init <- lookupIndices m5 (asTensor k5Init)
  assertEq "original key indices unchanged after rehash"
           initIndices
           (asValue (toDevice (Device CPU 0) q5Init) :: [Int64])
  let moreIndices = asValue (toDevice (Device CPU 0) idx5More) :: [Int64]
  assertEq "new keys got sequential indices [50..249]" ([50 .. 249] :: [Int64]) moreIndices

  -- Test hashMapIndexPutWithRehash
  let table5 = zeros' [2000]
      k5Put  = [251 .. 1000] :: [Int64]
      v5Put  = map fromIntegral k5Put :: [Float]
  (table5Updated, rehashedPut) <- hashMapIndexPutWithRehash m5 0.2 False (asTensor k5Put) (asTensor v5Put) table5
  assertEq "hashMapIndexPutWithRehash triggers rehash" True rehashedPut
  size5_2 <- sizeCudaHashMap m5
  assertEq "size after hashMapIndexPutWithRehash is 1000" 1000 size5_2
  sel5 <- hashMapIndexSelect m5 0 (asTensor ([251, 500, 1000] :: [Int64])) table5Updated
  assertEq "hashMapIndexSelect after hashMapIndexPutWithRehash"
           ([251.0, 500.0, 1000.0] :: [Float])
           (asValue (toDevice (Device CPU 0) sel5))

  putStrLn "=== Test 6: Invalid threshold validation ==="
  assertThrows "threshold 0.0" (insertBatchWithRehash m4 0.0 (asTensor ([1] :: [Int64])) (asTensor ([1] :: [Int64])))
  assertThrows "threshold -0.1" (insertKeysWithRehash m5 (-0.1) (asTensor ([1] :: [Int64])))
  assertThrows "threshold 1.5" (insertBatchWithRehash m4 1.5 (asTensor ([1] :: [Int64])) (asTensor ([1] :: [Int64])))
  assertThrows "threshold NaN" (insertKeysWithRehash m5 (0.0 / 0.0) (asTensor ([1] :: [Int64])))

  putStrLn "All tests passed!"