quant.cpp icon indicating copy to clipboard operation
quant.cpp copied to clipboard

Memory leak: 108MB dequant_tensor_fp32 buffer not freed by quant_free_model()

Open unamedkr opened this issue 7 months ago • 1 comments

Description

quant_free_model() does not free the dequant_tensor_fp32 buffer allocated during GGUF loading, causing a 108 MB memory leak per model load/unload cycle.

Steps to Reproduce

cc -O2 -o minimal examples/embed_minimal.c -lm -lpthread
leaks --atExit -- ./minimal ~/.cache/quantcpp/smollm2-135m-instruct-q8_0.gguf "test"

Actual Behavior

leaks Report Version: 4.0
Process:         minimal [PID]
Leaks:           62
Total leaked:    108.3 MB

  108 MB: dequant_tensor_fp32 (largest single leak)
  ~30 per-layer allocations from tq_load_gguf also leaked

Expected Behavior

Zero leaks after quant_free_model() + quant_free_ctx().

Impact

  • Severity: P0 — Showstopper for embedded/long-running applications
  • Each model load/unload leaks 108+ MB (scales with model size)
  • Server processes accumulate leaked memory over time
  • iOS/Android apps will be killed by OS memory pressure

Root Cause

The dequant_tensor_fp32 buffer is allocated during Q4 weight conversion in tq_load_gguf but not tracked for cleanup in quant_free_model(). Additionally, ~30 per-layer weight allocations are not freed.

Suggested Fix

  1. Track dequant_tensor_fp32 pointer in the model struct
  2. Free it in quant_free_model() / tq_free_model()
  3. Iterate and free per-layer allocations in the cleanup path
  4. Add a leaks --atExit check to CI

Environment

  • quant.cpp: latest main (49c6605)
  • Model: SmolLM2-135M (Q8_0, 138 MB)
  • OS: macOS 15 (Apple M3)
  • Tool: leaks --atExit (Xcode Instruments)

Reported by ClawTeam Claw-3 (Embedder persona)

unamedkr avatar Apr 12 '26 02:04 unamedkr

Fixed: tq_free_model() now frees all per-layer dequantized norm buffers and model-level embedding/norm buffers allocated by dequant_tensor_fp32() in the GGUF load path. SafeTensor path (where these point into _converted_data) is not affected — the free is gated on model->gguf_ctx != NULL.

unamedkr avatar Apr 12 '26 03:04 unamedkr