packages feed

hasktorch-CudaHashMap 0.1.0.0 → 0.1.1.0

raw patch · 7 files changed

+604/−50 lines, 7 files

Files

CHANGELOG.md view
@@ -3,3 +3,8 @@ ## 0.1.0.0 -- 2026-11-10  * First version. Released on an unsuspecting world.++## 0.1.1.0 -- 2026-11-24++* Add capacityCudaHashMap and auto-rehash insert variants+
README.md view
@@ -4,6 +4,85 @@  It supports high-throughput batch insertions and lookups directly on GPU-resident `Tensor`s without round-tripping through host (CPU) memory. +## Motivating Results++```bash+$ cabal bench+(snip)+Benchmarking Torch.CudaHashMap vs Data.HashMap.Strict (unordered-containers)+======================================================================================+Benchmark size: N = 10000 elements (Key: Int64, Value: Float / Index: Int64)+======================================================================================++[1] Batch Insert (Int64 -> Float)+  Data.HashMap.Strict (fromList)                  0.821 ms  (   12.18 Mops/s,   1.00x)+  CudaHashMap insertBatch (GPU tensor)            0.218 ms  (   45.84 Mops/s,   3.76x)+  CudaHashMap insertBatch (CPU -> GPU)            0.093 ms  (  107.50 Mops/s,   8.83x)++[2] Batch Lookup (Int64 -> Float, 50% hit / 50% miss)+  Data.HashMap.Strict (lookupDefault)             0.314 ms  (   31.82 Mops/s,   1.00x)+  CudaHashMap lookupBatch (dynamic_map, GPU)      0.007 ms  ( 1447.85 Mops/s,  45.50x)+  [finalizeCudaHashMap: 0.267 ms]+  CudaHashMap lookupBatch (static_map, GPU)       0.009 ms  ( 1092.68 Mops/s,  34.34x)+  CudaHashMap lookupBatch (static_map, CPU<->GPU)      0.054 ms  (  183.60 Mops/s,   5.77x)++[3] Key-to-Index Assignment (insertKeys) & Lookup (lookupIndices)+  Data.HashMap.Strict (key -> 0..K-1 insert)      0.936 ms  (   10.68 Mops/s,   1.00x)+  CudaHashMap insertKeys (GPU tensor)             0.302 ms  (   33.14 Mops/s,   3.10x)+  Data.HashMap.Strict (index lookup)              0.411 ms  (   24.33 Mops/s,   1.00x)+  CudaHashMap lookupIndices (static_map, GPU)      0.011 ms  (  936.21 Mops/s,  38.48x)++======================================================================================+Benchmark size: N = 100000 elements (Key: Int64, Value: Float / Index: Int64)+======================================================================================++[1] Batch Insert (Int64 -> Float)+  Data.HashMap.Strict (fromList)                  3.441 ms  (   29.06 Mops/s,   1.00x)+  CudaHashMap insertBatch (GPU tensor)            0.115 ms  (  868.33 Mops/s,  29.88x)+  CudaHashMap insertBatch (CPU -> GPU)            0.304 ms  (  328.95 Mops/s,  11.32x)++[2] Batch Lookup (Int64 -> Float, 50% hit / 50% miss)+  Data.HashMap.Strict (lookupDefault)             3.650 ms  (   27.40 Mops/s,   1.00x)+  CudaHashMap lookupBatch (dynamic_map, GPU)      0.014 ms  ( 7085.77 Mops/s, 258.60x)+  [finalizeCudaHashMap: 0.313 ms]+  CudaHashMap lookupBatch (static_map, GPU)       0.017 ms  ( 5914.50 Mops/s, 215.86x)+  CudaHashMap lookupBatch (static_map, CPU<->GPU)      0.386 ms  (  259.17 Mops/s,   9.46x)++[3] Key-to-Index Assignment (insertKeys) & Lookup (lookupIndices)+  Data.HashMap.Strict (key -> 0..K-1 insert)      6.311 ms  (   15.84 Mops/s,   1.00x)+  CudaHashMap insertKeys (GPU tensor)             0.460 ms  (  217.42 Mops/s,  13.72x)+  Data.HashMap.Strict (index lookup)              4.129 ms  (   24.22 Mops/s,   1.00x)+  CudaHashMap lookupIndices (static_map, GPU)      0.028 ms  ( 3592.65 Mops/s, 148.35x)++======================================================================================+Benchmark size: N = 1000000 elements (Key: Int64, Value: Float / Index: Int64)+======================================================================================++[1] Batch Insert (Int64 -> Float)+  Data.HashMap.Strict (fromList)                 31.486 ms  (   31.76 Mops/s,   1.00x)+  CudaHashMap insertBatch (GPU tensor)            0.364 ms  ( 2744.43 Mops/s,  86.41x)+  CudaHashMap insertBatch (CPU -> GPU)            1.740 ms  (  574.73 Mops/s,  18.10x)++[2] Batch Lookup (Int64 -> Float, 50% hit / 50% miss)+  Data.HashMap.Strict (lookupDefault)            45.611 ms  (   21.92 Mops/s,   1.00x)+  CudaHashMap lookupBatch (dynamic_map, GPU)      0.100 ms  (10010.48 Mops/s, 456.59x)+  [finalizeCudaHashMap: 1.327 ms]+  CudaHashMap lookupBatch (static_map, GPU)       0.101 ms  ( 9897.56 Mops/s, 451.44x)+  CudaHashMap lookupBatch (static_map, CPU<->GPU)      2.612 ms  (  382.84 Mops/s,  17.46x)++[3] Key-to-Index Assignment (insertKeys) & Lookup (lookupIndices)+  Data.HashMap.Strict (key -> 0..K-1 insert)     68.774 ms  (   14.54 Mops/s,   1.00x)+  CudaHashMap insertKeys (GPU tensor)             1.424 ms  (  702.45 Mops/s,  48.31x)+  Data.HashMap.Strict (index lookup)             36.981 ms  (   27.04 Mops/s,   1.00x)+  CudaHashMap lookupIndices (static_map, GPU)      0.120 ms  ( 8314.39 Mops/s, 307.47x)++Benchmark CudaHashMap-bench: FINISH+$ nvidia-smi |grep RTX+|   0  NVIDIA RTX A5000               Off |   00000000:01:00.0 Off |                  Off |+$ grep model\ name /proc/cpuinfo |uniq+model name      : 12th Gen Intel(R) Core(TM) i9-12900+```+ ## Features  - **Two-Stage Lifecycle (`dynamic_map` $\rightarrow$ `static_map`)**:@@ -169,12 +248,16 @@ | `newCudaHashMapOnDevice` | `Device -> Int -> IO CudaHashMap` | Create a new GPU hash map pinned to a specific CUDA `Device` (e.g. `Device CUDA 1`). | | `hashMapDevice` | `CudaHashMap -> IO Device` | Query the CUDA `Device` associated with the hash map. | | `sizeCudaHashMap` | `CudaHashMap -> IO Int` | Return the number of unique keys currently stored in the map. |+| `capacityCudaHashMap` | `CudaHashMap -> IO Int` | Return the current slot capacity of the map (`0` before the first insertion). | | `finalizeCudaHashMap` | `CudaHashMap -> IO ()` | Convert the internal `cuco::dynamic_map` into a single `cuco::static_map` for faster lookups. | | `insertBatch` | `CudaHashMap -> Tensor -> Tensor -> IO ()` | Insert or overwrite (`insert_or_assign`) key-value pairs (`Int32`, `Int64`, `Float`, `Double`). |+| `insertBatchWithRehash` | `CudaHashMap -> Double -> Tensor -> Tensor -> IO Bool` | Like `insertBatch`, but automatically rehashes a finalized `static_map` before insertion if the projected load factor exceeds the given threshold in `(0.0, 1.0]`. Returns `True` if rehashing occurred. | | `lookupBatch` | `CudaHashMap -> Tensor -> IO Tensor` | Look up values for a tensor of keys. Missing keys yield `-1` (`Int32`/`Int64`) or `NaN` (`Float`/`Double`). | | `insertKeys` | `CudaHashMap -> Tensor -> IO Tensor` | Assign 0-based sequential `Int64` indices to unseen keys and return the `Int64` index tensor for all input keys. |+| `insertKeysWithRehash` | `CudaHashMap -> Double -> Tensor -> IO (Tensor, Bool)` | Like `insertKeys`, but automatically rehashes a finalized `static_map` before insertion if the projected load factor exceeds the given threshold in `(0.0, 1.0]`. Returns `(indices, rehashed)`. | | `lookupIndices` | `CudaHashMap -> Tensor -> IO Tensor` | Look up 0-based `Int64` indices for input keys without inserting (`-1` for missing keys). | | `hashMapIndexPut` | `CudaHashMap -> Bool -> Tensor -> Tensor -> Tensor -> IO Tensor` | Map keys via `insertKeys` and update a table tensor using `indexPut`. |+| `hashMapIndexPutWithRehash` | `CudaHashMap -> Double -> Bool -> Tensor -> Tensor -> Tensor -> IO (Tensor, Bool)` | Like `hashMapIndexPut`, using `insertKeysWithRehash` to auto-rehash finalized `static_map`s when the load factor threshold is exceeded. Returns `(updatedTable, rehashed)`. | | `hashMapIndexSelect` | `CudaHashMap -> Int -> Tensor -> Tensor -> IO Tensor` | Map keys via `lookupIndices` and gather from a table tensor using `indexSelect`. |  ### Sentinel Value Conventions
cbits/cuco_wrapper.cu view
@@ -6,6 +6,7 @@ #include <dlfcn.h>  #include <thrust/copy.h>+#include <thrust/count.h> #include <thrust/device_vector.h> #include <thrust/execution_policy.h> #include <thrust/fill.h>@@ -19,6 +20,7 @@ #include <cuda/std/functional>  #include <algorithm>+#include <cmath> #include <cstdint> #include <cstring> #include <limits>@@ -140,9 +142,12 @@     virtual int key_dtype() const noexcept = 0;     virtual int val_dtype() const noexcept = 0;     virtual size_t size(cudaStream_t stream) const = 0;+    virtual size_t capacity() const noexcept = 0;     virtual void insert_batch(int num_elements, const void* d_keys, const void* d_values, cudaStream_t stream) = 0;+    virtual bool insert_batch_with_rehash(double load_factor_threshold, int num_elements, const void* d_keys, const void* d_values, cudaStream_t stream) = 0;     virtual void lookup_batch(int num_elements, const void* d_keys, void* d_values, cudaStream_t stream) const = 0;     virtual void insert_keys(int num_elements, const void* d_keys, int64_t* d_indices, cudaStream_t stream) = 0;+    virtual bool insert_keys_with_rehash(double load_factor_threshold, int num_elements, const void* d_keys, int64_t* d_indices, cudaStream_t stream) = 0;     virtual void lookup_indices(int num_elements, const void* d_keys, int64_t* d_indices, cudaStream_t stream) const = 0;     virtual void finalize(cudaStream_t stream) = 0; };@@ -158,6 +163,111 @@     V empty_val_;     std::variant<dynamic_map_t, static_map_t> map_storage_; +    static double sanitize_load_factor_threshold(double threshold) noexcept {+        if (std::isnan(threshold) || threshold <= 0.0) {+            return 1e-6;+        }+        if (threshold > 1.0) {+            return 1.0;+        }+        return threshold;+    }++    static size_t compute_rehash_capacity(size_t current_cap, size_t projected_size, double threshold) noexcept {+        double target_load = (threshold > 0.5) ? 0.5 : (threshold * 0.5);+        size_t needed_cap = static_cast<size_t>(std::ceil(static_cast<double>(projected_size) / target_load));+        size_t doubled_cap = (current_cap <= (std::numeric_limits<size_t>::max() / 2))+            ? (current_cap * 2)+            : std::numeric_limits<size_t>::max();+        return std::max<size_t>({doubled_cap, needed_cap, 1024});+    }++    bool maybe_rehash_static_map(size_t projected_size, double load_factor_threshold, cudaStream_t stream) {+        if (!std::holds_alternative<static_map_t>(map_storage_)) {+            return false;+        }+        double threshold = sanitize_load_factor_threshold(load_factor_threshold);+        auto& s_map = std::get<static_map_t>(map_storage_);+        size_t cap = static_cast<size_t>(s_map.capacity());+        if (cap == 0 ||+            projected_size > cap ||+            static_cast<double>(projected_size) > static_cast<double>(cap) * threshold)+        {+            size_t new_cap = compute_rehash_capacity(cap, projected_size, threshold);+            s_map.rehash(new_cap, cuda::stream_ref{stream});+            return true;+        }+        return false;+    }++    bool insert_keys_impl(+        bool check_rehash,+        double load_factor_threshold,+        int num_elements,+        const void* d_keys,+        int64_t* d_indices,+        cudaStream_t stream)+    {+        if (num_elements <= 0) return false;+        bool rehashed = false;++        if constexpr (std::is_same_v<V, int64_t>) {+            const K* keys = static_cast<const K*>(d_keys);+            auto exec = thrust::cuda::par.on(stream);++            // 1. Deduplicate keys within the input batch using sort + unique+            thrust::device_vector<K> unique_keys(num_elements);+            thrust::copy(exec, keys, keys + num_elements, unique_keys.begin());+            thrust::sort(exec, unique_keys.begin(), unique_keys.end());+            auto unique_end = thrust::unique(exec, unique_keys.begin(), unique_keys.end());+            size_t num_unique = static_cast<size_t>(unique_end - unique_keys.begin());++            // 2. Check in batch which unique keys are already present in the map+            thrust::device_vector<bool> is_contained(num_unique);+            std::visit([&](auto const& m) {+                m.contains_async(unique_keys.begin(), unique_end, is_contained.begin(), cuda::stream_ref{stream});+            }, map_storage_);++            // 3. Extract only the unregistered keys+            thrust::device_vector<K> new_keys(num_unique);+            auto new_keys_end = thrust::copy_if(+                exec,+                unique_keys.begin(),+                unique_end,+                is_contained.begin(),+                new_keys.begin(),+                cuda::std::logical_not<bool>{}+            );+            size_t num_new = static_cast<size_t>(new_keys_end - new_keys.begin());++            // 4. Rehash static_map if requested and projected load factor exceeds threshold+            bool need_size = (num_new > 0) || (check_rehash && std::holds_alternative<static_map_t>(map_storage_));+            size_t current_size = need_size ? size(stream) : 0;+            if (check_rehash) {+                rehashed = maybe_rehash_static_map(current_size + num_new, load_factor_threshold, stream);+            }++            // 5. Assign sequential Int64 indices in [base_idx, base_idx + num_new) to the new keys and insert them+            if (num_new > 0) {+                int64_t base_idx = static_cast<int64_t>(current_size);+                auto idx_begin = thrust::make_counting_iterator<int64_t>(base_idx);+                auto pairs_begin = make_cuco_pair_iterator<K, int64_t>(new_keys.begin(), idx_begin);+                auto pairs_end = pairs_begin + num_new;++                std::visit([&](auto& m) {+                    m.insert(pairs_begin, pairs_end, cuda::stream_ref{stream});+                }, map_storage_);+            }++            // 6. Write the 0-based indices corresponding to all original input keys into d_indices+            std::visit([&](auto const& m) {+                m.find_async(keys, keys + num_elements, d_indices, cuda::stream_ref{stream});+            }, map_storage_);+        }++        return rehashed;+    }+ public:     TypedCudaHashMap(int k_dtype, int v_dtype, size_t initial_capacity, cudaStream_t stream)         : key_dtype_(k_dtype),@@ -189,6 +299,12 @@         }     } +    size_t capacity() const noexcept override {+        return std::visit([](auto const& m) -> size_t {+            return static_cast<size_t>(m.capacity());+        }, map_storage_);+    }+     void insert_batch(int num_elements, const void* d_keys, const void* d_values, cudaStream_t stream) override {         if (num_elements <= 0) return; @@ -203,6 +319,61 @@         }, map_storage_);     } +    bool insert_batch_with_rehash(+        double load_factor_threshold,+        int num_elements,+        const void* d_keys,+        const void* d_values,+        cudaStream_t stream) override+    {+        if (num_elements <= 0) return false;++        bool rehashed = false;+        const K* keys = static_cast<const K*>(d_keys);+        const V* values = static_cast<const V*>(d_values);++        if (std::holds_alternative<static_map_t>(map_storage_)) {+            double threshold = sanitize_load_factor_threshold(load_factor_threshold);+            auto& s_map = std::get<static_map_t>(map_storage_);+            size_t current_size = s_map.size(cuda::stream_ref{stream});+            size_t cap = static_cast<size_t>(s_map.capacity());+            size_t worst_case_size = current_size + static_cast<size_t>(num_elements);++            // Fast path: if even the worst-case (all input keys unique and new) fits under threshold,+            // skip deduplication and containment checks.+            if (cap == 0 ||+                worst_case_size > cap ||+                static_cast<double>(worst_case_size) > static_cast<double>(cap) * threshold)+            {+                // Slow path: count exact number of genuinely new unique keys in the batch+                auto exec = thrust::cuda::par.on(stream);+                thrust::device_vector<K> unique_keys(num_elements);+                thrust::copy(exec, keys, keys + num_elements, unique_keys.begin());+                thrust::sort(exec, unique_keys.begin(), unique_keys.end());+                auto unique_end = thrust::unique(exec, unique_keys.begin(), unique_keys.end());+                size_t num_unique = static_cast<size_t>(unique_end - unique_keys.begin());++                thrust::device_vector<bool> is_contained(num_unique);+                s_map.contains_async(unique_keys.begin(), unique_end, is_contained.begin(), cuda::stream_ref{stream});++                size_t num_new = static_cast<size_t>(+                    thrust::count(exec, is_contained.begin(), is_contained.end(), false));++                rehashed = maybe_rehash_static_map(current_size + num_new, threshold, stream);+            }+        }++        auto pairs_begin = make_cuco_pair_iterator<K, V>(keys, values);+        auto pairs_end = pairs_begin + num_elements;++        // Overwrite with the new value if the key already exists (insert_or_assign)+        std::visit([&](auto& m) {+            m.insert_or_assign(pairs_begin, pairs_end, cuda::stream_ref{stream});+        }, map_storage_);++        return rehashed;+    }+     void lookup_batch(int num_elements, const void* d_keys, void* d_values, cudaStream_t stream) const override {         if (num_elements <= 0) return; @@ -215,54 +386,17 @@     }      void insert_keys(int num_elements, const void* d_keys, int64_t* d_indices, cudaStream_t stream) override {-        if (num_elements <= 0) return;--        if constexpr (std::is_same_v<V, int64_t>) {-            const K* keys = static_cast<const K*>(d_keys);-            auto exec = thrust::cuda::par.on(stream);--            // 1. Deduplicate keys within the input batch using sort + unique-            thrust::device_vector<K> unique_keys(num_elements);-            thrust::copy(exec, keys, keys + num_elements, unique_keys.begin());-            thrust::sort(exec, unique_keys.begin(), unique_keys.end());-            auto unique_end = thrust::unique(exec, unique_keys.begin(), unique_keys.end());-            size_t num_unique = static_cast<size_t>(unique_end - unique_keys.begin());--            // 2. Check in batch which unique keys are already present in the map-            thrust::device_vector<bool> is_contained(num_unique);-            std::visit([&](auto const& m) {-                m.contains_async(unique_keys.begin(), unique_end, is_contained.begin(), cuda::stream_ref{stream});-            }, map_storage_);--            // 3. Extract only the unregistered keys-            thrust::device_vector<K> new_keys(num_unique);-            auto new_keys_end = thrust::copy_if(-                exec,-                unique_keys.begin(),-                unique_end,-                is_contained.begin(),-                new_keys.begin(),-                cuda::std::logical_not<bool>{}-            );-            size_t num_new = static_cast<size_t>(new_keys_end - new_keys.begin());--            // 4. Assign sequential Int64 indices in [base_idx, base_idx + num_new) to the new keys and insert them-            if (num_new > 0) {-                int64_t base_idx = static_cast<int64_t>(size(stream));-                auto idx_begin = thrust::make_counting_iterator<int64_t>(base_idx);-                auto pairs_begin = make_cuco_pair_iterator<K, int64_t>(new_keys.begin(), idx_begin);-                auto pairs_end = pairs_begin + num_new;--                std::visit([&](auto& m) {-                    m.insert(pairs_begin, pairs_end, cuda::stream_ref{stream});-                }, map_storage_);-            }+        (void)insert_keys_impl(false, 1.0, num_elements, d_keys, d_indices, stream);+    } -            // 5. Write the 0-based indices corresponding to all original input keys into d_indices-            std::visit([&](auto const& m) {-                m.find_async(keys, keys + num_elements, d_indices, cuda::stream_ref{stream});-            }, map_storage_);-        }+    bool insert_keys_with_rehash(+        double load_factor_threshold,+        int num_elements,+        const void* d_keys,+        int64_t* d_indices,+        cudaStream_t stream) override+    {+        return insert_keys_impl(true, load_factor_threshold, num_elements, d_keys, d_indices, stream);     }      void lookup_indices(int num_elements, const void* d_keys, int64_t* d_indices, cudaStream_t stream) const override {@@ -407,6 +541,11 @@     return map_ptr->impl->size(stream); } +size_t custom_cuco_capacity(CudaHashMapOpaque* map_ptr) {+    if (!map_ptr || !map_ptr->impl) return 0;+    return map_ptr->impl->capacity();+}+ int custom_cuco_key_dtype(CudaHashMapOpaque* map_ptr) {     if (!map_ptr || !map_ptr->impl) return -1;     return map_ptr->impl->key_dtype();@@ -431,6 +570,21 @@     m->insert_keys(num_elements, d_keys, d_indices, stream); } +int custom_cuco_insert_keys_with_rehash(+    CudaHashMapOpaque* map_ptr,+    int key_dtype,+    double load_factor_threshold,+    int num_elements,+    const void* d_keys,+    int64_t* d_indices)+{+    if (!map_ptr || num_elements <= 0) return 0;+    ScopedCudaDevice guard(map_ptr->device_index);+    cudaStream_t stream = get_current_torch_cuda_stream(map_ptr->device_index);+    MapBase* m = map_ptr->ensure_initialized(key_dtype, CUCO_DTYPE_INT64, stream);+    return m->insert_keys_with_rehash(load_factor_threshold, num_elements, d_keys, d_indices, stream) ? 1 : 0;+}+ void custom_cuco_lookup_indices(     CudaHashMapOpaque* map_ptr,     int key_dtype,@@ -461,6 +615,22 @@     cudaStream_t stream = get_current_torch_cuda_stream(map_ptr->device_index);     MapBase* m = map_ptr->ensure_initialized(key_dtype, val_dtype, stream);     m->insert_batch(num_elements, d_keys, d_values, stream);+}++int custom_cuco_insert_batch_typed_with_rehash(+    CudaHashMapOpaque* map_ptr,+    int key_dtype,+    int val_dtype,+    double load_factor_threshold,+    int num_elements,+    const void* d_keys,+    const void* d_values)+{+    if (!map_ptr || num_elements <= 0) return 0;+    ScopedCudaDevice guard(map_ptr->device_index);+    cudaStream_t stream = get_current_torch_cuda_stream(map_ptr->device_index);+    MapBase* m = map_ptr->ensure_initialized(key_dtype, val_dtype, stream);+    return m->insert_batch_with_rehash(load_factor_threshold, num_elements, d_keys, d_values, stream) ? 1 : 0; }  void custom_cuco_lookup_batch_typed(
cbits/cuco_wrapper.h view
@@ -32,6 +32,9 @@ // Get the number of currently registered unique keys size_t custom_cuco_size(CudaHashMapOpaque* map_ptr); +// Get the current slot capacity of the map (0 when uninitialized)+size_t custom_cuco_capacity(CudaHashMapOpaque* map_ptr);+ // Get the key and value DTypes configured for the map (-1 when uninitialized) int custom_cuco_key_dtype(CudaHashMapOpaque* map_ptr); int custom_cuco_val_dtype(CudaHashMapOpaque* map_ptr);@@ -45,6 +48,18 @@     const void* d_keys,     int64_t* d_indices); +// Same as custom_cuco_insert_keys, but when finalized into a static_map, automatically+// rehashes to a larger capacity before insertion if the projected load factor (size / capacity)+// would exceed load_factor_threshold (in (0.0, 1.0]).+// Returns 1 if a rehash occurred, 0 otherwise.+int custom_cuco_insert_keys_with_rehash(+    CudaHashMapOpaque* map_ptr,+    int key_dtype,+    double load_factor_threshold,+    int num_elements,+    const void* d_keys,+    int64_t* d_indices);+ // Look up Int64 indices for keys without inserting new keys (unregistered keys get -1) void custom_cuco_lookup_indices(     CudaHashMapOpaque* map_ptr,@@ -58,6 +73,19 @@     CudaHashMapOpaque* map_ptr,     int key_dtype,     int val_dtype,+    int num_elements,+    const void* d_keys,+    const void* d_values);++// Same as custom_cuco_insert_batch_typed, but when finalized into a static_map, automatically+// rehashes to a larger capacity before insertion if the projected load factor (size / capacity)+// would exceed load_factor_threshold (in (0.0, 1.0]).+// Returns 1 if a rehash occurred, 0 otherwise.+int custom_cuco_insert_batch_typed_with_rehash(+    CudaHashMapOpaque* map_ptr,+    int key_dtype,+    int val_dtype,+    double load_factor_threshold,     int num_elements,     const void* d_keys,     const void* d_values);
hasktorch-CudaHashMap.cabal view
@@ -20,7 +20,7 @@ -- PVP summary:     +-+------- breaking API changes --                  | | +----- non-breaking API additions --                  | | | +--- code changes with no API change-version:            0.1.0.0+version:            0.1.1.0  -- A short (one-line) description of the package. synopsis:           HaskTorch interface to the GPU-parallel hashmap in cuCollections
src/Torch/CudaHashMap.hs view
@@ -11,19 +11,23 @@   , hashMapDevice   , finalizeCudaHashMap   , sizeCudaHashMap+  , capacityCudaHashMap     -- * Key-Value Batch Insert & Lookup (supports Int32, Int64, Float, Double)   , insertBatch+  , insertBatchWithRehash   , lookupBatch     -- * Index Conversion API for indexSelect / indexPut   , insertKeys+  , insertKeysWithRehash   , lookupIndices   , hashMapIndexPut+  , hashMapIndexPutWithRehash   , hashMapIndexSelect     -- * Low-Level Helper   , withDevicePointer   ) where -import Foreign.C.Types (CInt(..), CSize(..))+import Foreign.C.Types (CDouble(..), CInt(..), CSize(..)) import Foreign.ForeignPtr (ForeignPtr, newForeignPtr, withForeignPtr) import Foreign.Ptr (FunPtr, Ptr, castPtr) import Data.Int (Int64)@@ -77,6 +81,9 @@ foreign import ccall "custom_cuco_size"   c_size :: Ptr CudaHashMapOpaque -> IO CSize +foreign import ccall "custom_cuco_capacity"+  c_capacity :: Ptr CudaHashMapOpaque -> IO CSize+ foreign import ccall "custom_cuco_val_dtype"   c_val_dtype :: Ptr CudaHashMapOpaque -> IO CInt @@ -93,6 +100,16 @@     -> Ptr Int64     -> IO () +foreign import ccall "custom_cuco_insert_keys_with_rehash"+  c_insert_keys_with_rehash+    :: Ptr CudaHashMapOpaque+    -> CInt+    -> CDouble+    -> CInt+    -> Ptr ()+    -> Ptr Int64+    -> IO CInt+ foreign import ccall "custom_cuco_lookup_indices"   c_lookup_indices     :: Ptr CudaHashMapOpaque@@ -113,6 +130,17 @@     -> Ptr ()     -> IO () +foreign import ccall "custom_cuco_insert_batch_typed_with_rehash"+  c_insert_batch_typed_with_rehash+    :: Ptr CudaHashMapOpaque+    -> CInt+    -> CInt+    -> CDouble+    -> CInt+    -> Ptr ()+    -> Ptr ()+    -> IO CInt+ foreign import ccall "custom_cuco_lookup_batch_typed"   c_lookup_batch_typed     :: Ptr CudaHashMapOpaque@@ -212,6 +240,21 @@   withForeignPtr fptr $ \mapPtr ->     fromIntegral <$> c_size mapPtr +-- | Get the current slot capacity of the hash map (returns @0@ before the first insertion,+-- while the underlying GPU table is not yet allocated)+capacityCudaHashMap :: CudaHashMap -> IO Int+capacityCudaHashMap (CudaHashMap fptr) =+  withForeignPtr fptr $ \mapPtr ->+    fromIntegral <$> c_capacity mapPtr++-- | Validate that a load factor threshold is a finite value in @(0.0, 1.0]@.+validateLoadFactorThreshold :: String -> Double -> IO ()+validateLoadFactorThreshold funcName threshold+  | isNaN threshold || isInfinite threshold || threshold <= 0.0 || threshold > 1.0 =+      error $ "Torch.CudaHashMap." ++ funcName+           ++ ": load factor threshold must be in (0.0, 1.0], got " ++ show threshold+  | otherwise = return ()+ -- | Convert and freeze the internal dynamic_map into a single high-speed static_map once insertions have stabilized finalizeCudaHashMap :: CudaHashMap -> IO () finalizeCudaHashMap (CudaHashMap fptr) =@@ -237,6 +280,39 @@           withDevicePointer cudaValues $ \valPtr ->             c_insert_batch_typed mapPtr kDType vDType numElements keyPtr valPtr +-- | Batch-insert key and value tensors with automatic rehashing for finalized @static_map@s.+-- If the map has been finalized into a @static_map@ and inserting this batch would cause+-- the load factor (@size / capacity@) to exceed @loadFactorThreshold@ (in @(0.0, 1.0]@),+-- the @static_map@ is automatically rehashed to a larger capacity before insertion.+--+-- Returns @True@ if a rehash occurred, and @False@ otherwise (including while the map is+-- still a @dynamic_map@, which grows automatically via submaps without rehashing).+insertBatchWithRehash+  :: CudaHashMap+  -> Double  -- ^ loadFactorThreshold in (0.0, 1.0] (e.g. 0.75)+  -> Tensor  -- ^ keysTensor+  -> Tensor  -- ^ valuesTensor+  -> IO Bool -- ^ True if rehashing occurred, False otherwise+insertBatchWithRehash (CudaHashMap fptr) loadFactorThreshold keysTensor valuesTensor = do+  validateLoadFactorThreshold "insertBatchWithRehash" loadFactorThreshold+  withForeignPtr fptr $ \mapPtr -> do+    cudaKeys   <- ensureCudaOnMap mapPtr keysTensor+    cudaValues <- ensureCudaOnMap mapPtr valuesTensor+    let kDType  = toCucoDType (dtype cudaKeys)+        vDType  = toCucoDType (dtype cudaValues)+        numKeys = numel cudaKeys+        numVals = numel cudaValues+    if numKeys /= numVals+      then error $ "Torch.CudaHashMap.insertBatchWithRehash: key and value element counts do not match ("+                ++ show numKeys ++ " vs " ++ show numVals ++ ")"+      else do+        let numElements = fromIntegral numKeys+            cThreshold  = realToFrac loadFactorThreshold+        rehashed <- withDevicePointer cudaKeys $ \keyPtr ->+          withDevicePointer cudaValues $ \valPtr ->+            c_insert_batch_typed_with_rehash mapPtr kDType vDType cThreshold numElements keyPtr valPtr+        return (rehashed /= 0)+ -- | Batch-lookup a tensor of keys and return the corresponding tensor of values. -- Unregistered keys receive -1 for Int32 / Int64, or NaN for Float / Double. lookupBatch :: CudaHashMap -> Tensor -> IO Tensor@@ -271,6 +347,30 @@         c_insert_keys mapPtr kDType numElements keyPtr (castPtr idxPtr)     return indicesTensor +-- | Like 'insertKeys', but when the map has been finalized into a @static_map@, automatically+-- rehashes to a larger capacity before insertion if the projected load factor (@size / capacity@)+-- would exceed @loadFactorThreshold@ (in @(0.0, 1.0]@).+--+-- Returns @(indicesTensor, rehashed)@, where @rehashed@ is @True@ if rehashing occurred+-- and @False@ otherwise.+insertKeysWithRehash+  :: CudaHashMap+  -> Double            -- ^ loadFactorThreshold in (0.0, 1.0] (e.g. 0.75)+  -> Tensor            -- ^ keysTensor+  -> IO (Tensor, Bool) -- ^ (Int64 indicesTensor, True if rehashing occurred)+insertKeysWithRehash (CudaHashMap fptr) loadFactorThreshold keysTensor = do+  validateLoadFactorThreshold "insertKeysWithRehash" loadFactorThreshold+  withForeignPtr fptr $ \mapPtr -> do+    cudaKeys <- ensureCudaOnMap mapPtr keysTensor+    let kDType      = toCucoDType (dtype cudaKeys)+        numElements = fromIntegral (numel cudaKeys)+        cThreshold  = realToFrac loadFactorThreshold+    indicesTensor <- allocTensor (shape cudaKeys) DType.Int64 (device cudaKeys)+    rehashed <- withDevicePointer cudaKeys $ \keyPtr ->+      withDevicePointer indicesTensor $ \idxPtr ->+        c_insert_keys_with_rehash mapPtr kDType cThreshold numElements keyPtr (castPtr idxPtr)+    return (indicesTensor, rehashed /= 0)+ -- | Look up 0-based Int64 indices corresponding to a tensor of keys without registering new keys. -- Unregistered keys receive -1. lookupIndices :: CudaHashMap -> Tensor -> IO Tensor@@ -301,6 +401,27 @@     cudaTable  <- ensureCudaOnMap mapPtr tableTensor     let flatIndices = reshape [-1] indices     return $ indexPut accumulate [flatIndices] cudaValues cudaTable++-- | Like 'hashMapIndexPut', but uses 'insertKeysWithRehash' so finalized @static_map@s+-- automatically rehash when the projected load factor exceeds @loadFactorThreshold@.+--+-- Returns @(updatedTableTensor, rehashed)@.+hashMapIndexPutWithRehash+  :: CudaHashMap+  -> Double            -- ^ loadFactorThreshold in (0.0, 1.0] (e.g. 0.75)+  -> Bool              -- ^ accumulate (True to add, False to overwrite)+  -> Tensor            -- ^ keysTensor+  -> Tensor            -- ^ valuesTensor+  -> Tensor            -- ^ tableTensor (target tensor to write into)+  -> IO (Tensor, Bool) -- ^ (updated tableTensor, True if rehashing occurred)+hashMapIndexPutWithRehash hmap@(CudaHashMap fptr) loadFactorThreshold accumulate keysTensor valuesTensor tableTensor = do+  (indices, rehashed) <- insertKeysWithRehash hmap loadFactorThreshold keysTensor+  updatedTable <- withForeignPtr fptr $ \mapPtr -> do+    cudaValues <- ensureCudaOnMap mapPtr valuesTensor+    cudaTable  <- ensureCudaOnMap mapPtr tableTensor+    let flatIndices = reshape [-1] indices+    return $ indexPut accumulate [flatIndices] cudaValues cudaTable+  return (updatedTable, rehashed)  -- | Look up registered indices from a tensor of keys and extract elements -- from the specified dimension of tableTensor via indexSelect.
test/Main.hs view
@@ -1,11 +1,31 @@ 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, device, indexSelect, toDevice)+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 ==="@@ -18,6 +38,7 @@   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@@ -27,6 +48,12 @@   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@@ -40,3 +67,123 @@   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!"