From 76eb6272d0896a16c82c466f04c41d8c9762d843 Mon Sep 17 00:00:00 2001 From: Alexey Gerasev Date: Fri, 29 Mar 2024 08:31:47 +0700 Subject: [PATCH] Fix `StandardGpuResources` memory leak --- src/gpu.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/gpu.rs b/src/gpu.rs index 159cded..7e3cce1 100644 --- a/src/gpu.rs +++ b/src/gpu.rs @@ -110,6 +110,14 @@ impl StandardGpuResources { } } +impl Drop for StandardGpuResources { + fn drop(&mut self) { + unsafe { + faiss_StandardGpuResources_free(self.inner); + } + } +} + impl GpuResourcesProvider for StandardGpuResources { fn inner_ptr(&self) -> *mut FaissGpuResourcesProvider { self.inner as *mut _ @@ -169,4 +177,20 @@ mod tests { fn smoke_detector() { StandardGpuResources::new().unwrap(); } + + // The test marked as ignored because it takes a significant amount of time. + #[ignore] + #[test] + fn resources_leak() { + use crate::{index_factory, MetricType}; + + // Try to allocate gpu resources multiple times in a loop. + // If resources are not properly deallocated this will cause out-of-memory error. + for _ in 0..50 { + let res = StandardGpuResources::new().unwrap(); + // We need to create an index because `StandardGpuResources` constructor does not allocate actual resources. + let index = index_factory(32, "Flat", MetricType::InnerProduct).unwrap(); + let _gpu_index = index.into_gpu(&res, 0).unwrap(); + } + } }