Skip to content

Fix ggml_tensor_extra_gpu memory leak - #2146

Closed
eugen-ajechiloae-clearml wants to merge 1 commit into
ggml-org:masterfrom
eugen-ajechiloae-clearml:master
Closed

eugen-ajechiloae-clearml wants to merge 1 commit into
ggml-org:masterfrom
eugen-ajechiloae-clearml:master

Conversation

@eugen-ajechiloae-clearml

@eugen-ajechiloae-clearml eugen-ajechiloae-clearml commented Jul 8, 2023 •

Copy link
Copy Markdown

Fixes #2145. Allocate the extra member of ggml_tensor statically

Allocate the `extra` member of `ggml_tensor` statically

@JohannesGaessler JohannesGaessler left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be fine with me but ggml changes will need to be approved by @ggerganov.

@mqy

mqy commented Jul 8, 2023

Copy link
Copy Markdown
Contributor

#2099 uses extra

@ggerganov

Copy link
Copy Markdown
Member

Not a good change - the CUDA implementation should clean-up the allocated memory

@ggerganov ggerganov closed this Jul 9, 2023
@eugen-ajechiloae-clearml

Copy link
Copy Markdown
Author

Hi @ggerganov ! Is there any reason why you allocate the memory dynamically? Cleaning up the memory seems very difficult . Looks like the same memory region is used by multiple instances of ggml_tensor, also tracking every pointer allocated is not easy to me at least.
I think that creating a new member in ggml_tensor with type ggml_tensor_extra_cpu would make memory management a lot easier, and I really don't think it adds significant overhead. We could also leave the extra pointer untouched, such that #2099 is unaffected.
What do you think?

@ggerganov

Copy link
Copy Markdown
Member

The goal is to keep ggml_tensor general-purpose. Adding CUDA specific members is not desired since it incentivises doing the same for the other backends and this does not scale well.

tracking every pointer allocated is not easy to me at least.

Is it really so difficult. I guess we could pre-allocate a single large enough buffer in ggml_init_cublas() and then emplace each ggml_tensor_extra_gpu inside it. Keep a counter and increase it for each new struct. Reset the counter at the start of each eval. Finally free the buffer upon exit.

If it is indeed too difficult we can think of some alternative approaches, but the main requirement is to not couple ggml_tensor with GPU-specific things

@bullno1

bullno1 commented Jul 11, 2023 •

Copy link
Copy Markdown
Contributor

AFAIK, there are two types of ggml_tensor_extra_gpu, those bound to model/context and those bound to the temporary context in llama_eval_internal. Only the latter get leaked. The former are freed in the destructor.

Since the lifecycle of them is tied to ctx0, they should also be freed at the same time as ctx0.
Their lifecycle should be tracked separately from the model/context bound ones.

All temp allocations are made in ggml_cuda_assign_buffers so it can be tracked right there.
I think it's better to make offload contextful:

typedef void (*offload_func_t)(void * offload_ctx, struct ggml_tensor * tensor);

int llama_eval_internal(...) {
    ctx0 = ggml_init(...);

    #ifdef GGML_USE_CUBLAS
    void * offload_ctx = ggml_cuda_init_offload_ctx(...);
    #endif

    // Now the offload_func will have to be called like this
    offload_func(offload_ctx, tensor);

    #ifdef GGML_USE_CUBLAS
    ggml_cuda_free_offload_ctx(offload_ctx);
    #endif

    ggml_free(ctx0);
}

It's a bit more verbose but we correctly track the life cycle of those temp allocations.
A free list or bump allocator can be used.

ggml_cuda_assign_buffers will have to take a context pointer and look different from the rest of the family like: ggml_cuda_assign_buffers_no_scratch or ggml_cuda_assign_buffers_force_inplace but it is used in a very different manner anw.

The offload_ctx can be dropped too but allocations would have to be linked to some global/TLS state.
The it would just be: ggml_cuda_offload_begin() and ggml_cuda_offload_end().

@eugen-ajechiloae-clearml

Copy link
Copy Markdown
Author

Memory management seems a bit too complicated for me in this case, so I just wanted to let you know that I will not open another PR for this issue. Thank you guys for your input!

bong-water-water-bong pushed a commit to 1bit-MONSTER/llama.cpp that referenced this pull request Nov 12, 2026
…own rule (engine ggml-org#2146)

The registry skips a registration when a pattern is a substring of its name. The two
supports_op claims that must decline with their only registration checked the other
way round: they looked for the full name ("hip.top_k_f32", "common.argsort_rows_f32")
inside the variable. So =top_k removed the matcher but kept the claim, and on
Flash-Next at 18.8k the request failed with "unsupported HRX node 1: TOP_K" (the
sparse-attention indexer's 2051-of-2560 selection) instead of running TOP_K on the CPU.

dispatch_name_disabled() is now the one rule; the registry and both claims call it.
Compiled against the bench build's commands; the claim path has not been run on a
device yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bong-water-water-bong pushed a commit to 1bit-MONSTER/llama.cpp that referenced this pull request Nov 12, 2026
…un (engine ggml-org#2146)

Two defects, measured on gfx1151 by running the kernel directly through HIP, 50 runs
per shape:

1. A race in the selection levels. After the level's last barrier every lane reads
   bucket_found / take_found, but lane 0 resets both at the start of the next level
   without a barrier in between, so a slow lane could publish a wrong threshold_key.
   At 2560 -> 2051 x 512 rows the old kernel returned rows that are not a top-k
   (1-12 per 50 runs) and, with distinct inputs, a different index set in 2-3 of 49.
   One __syncthreads() after the reads: 0 invalid rows, set stable.

2. The emit took a slot per element with atomicAdd, so the order differed every run
   (49 of 49), and in the group equal to the rank-k key whichever lanes came first
   took the remaining slots, so with ties the set differed every run too. Each lane
   now counts its two groups, an exclusive scan over lanes gives fixed offsets, and a
   second pass writes in visit order. Order and set: 0 of 49 differ on every shape
   (2560/2051, 4096/2048, 128/8, a 2561 unaligned pitch, one 200,000 row, k == cols);
   with distinct inputs the set equals a CPU reference.

The sparse-attention indexer on Flash-Next picks 2051 of 2560 KV rows with this
kernel, and identical greedy 18.8k requests gave 4 replies in 4 with the GPU to
itself.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bong-water-water-bong pushed a commit to 1bit-MONSTER/llama.cpp that referenced this pull request Nov 12, 2026
…input (engine ggml-org#2146)

Seven cases (the Flash-Next indexer's 2560 -> 2051, heavy ties, 4096 -> 2048, a
router-like 128 -> 8, an odd pitch, k == cols), 12 runs each: every row a valid
top-k, bitwise-identical output across runs, and with distinct inputs the CPU's set.
Skips without HRX0.

Before (bench build of 962507f, the old kernel): FAIL, rc 1, 4 of 7 cases with
11 of 11 runs differing from run 1. After: owed on a build of this branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bong-water-water-bong added a commit to 1bit-MONSTER/llama.cpp that referenced this pull request Nov 12, 2026
…un (engine ggml-org#2146) (#328)

* hrx: hip_top_k_f32 returns the same indices in the same order every run (engine ggml-org#2146)

Two defects, measured on gfx1151 by running the kernel directly through HIP, 50 runs
per shape:

1. A race in the selection levels. After the level's last barrier every lane reads
   bucket_found / take_found, but lane 0 resets both at the start of the next level
   without a barrier in between, so a slow lane could publish a wrong threshold_key.
   At 2560 -> 2051 x 512 rows the old kernel returned rows that are not a top-k
   (1-12 per 50 runs) and, with distinct inputs, a different index set in 2-3 of 49.
   One __syncthreads() after the reads: 0 invalid rows, set stable.

2. The emit took a slot per element with atomicAdd, so the order differed every run
   (49 of 49), and in the group equal to the rank-k key whichever lanes came first
   took the remaining slots, so with ties the set differed every run too. Each lane
   now counts its two groups, an exclusive scan over lanes gives fixed offsets, and a
   second pass writes in visit order. Order and set: 0 of 49 differ on every shape
   (2560/2051, 4096/2048, 128/8, a 2561 unaligned pitch, one 200,000 row, k == cols);
   with distinct inputs the set equals a CPU reference.

The sparse-attention indexer on Flash-Next picks 2051 of 2560 KV rows with this
kernel, and identical greedy 18.8k requests gave 4 replies in 4 with the GPU to
itself.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* tests: test-hrx-top-k-repeat, TOP_K on HRX is a pure function of its input (engine ggml-org#2146)

Seven cases (the Flash-Next indexer's 2560 -> 2051, heavy ties, 4096 -> 2048, a
router-like 128 -> 8, an odd pitch, k == cols), 12 runs each: every row a valid
top-k, bitwise-identical output across runs, and with distinct inputs the CPU's set.
Skips without HRX0.

Before (bench build of 962507f, the old kernel): FAIL, rc 1, 4 of 7 cases with
11 of 11 runs differing from run 1. After: owed on a build of this branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: bong-water-water-bong <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
bong-water-water-bong pushed a commit to 1bit-MONSTER/llama.cpp that referenced this pull request Nov 12, 2026
…the CPU with the CPU's result (engine ggml-org#2146)

The same seven cases as test-hrx-top-k-repeat, run with GGML_HRX_DISABLE_DISPATCH=top_k
through a scheduler with HRX first and the CPU second. Each case requires that HRX does
not claim the node, that the scheduler places it on the CPU, and that the indices equal
the CPU backend's, entry for entry. Review on #331: nothing else takes this path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bong-water-water-bong added a commit to 1bit-MONSTER/llama.cpp that referenced this pull request Nov 12, 2026
… CPU instead of failing the graph (engine ggml-org#2146) (#331)

* hrx: the TOP_K and ARGSORT claims follow GGML_HRX_DISABLE_DISPATCH's own rule (engine ggml-org#2146)

The registry skips a registration when a pattern is a substring of its name. The two
supports_op claims that must decline with their only registration checked the other
way round: they looked for the full name ("hip.top_k_f32", "common.argsort_rows_f32")
inside the variable. So =top_k removed the matcher but kept the claim, and on
Flash-Next at 18.8k the request failed with "unsupported HRX node 1: TOP_K" (the
sparse-attention indexer's selection) instead of running TOP_K on the CPU.

dispatch_name_disabled() is now the one rule; the registry and both claims call it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* tests: test-hrx-top-k-declined, the switched-off TOP_K falls back to the CPU with the CPU's result (engine ggml-org#2146)

The same seven cases as test-hrx-top-k-repeat, run with GGML_HRX_DISABLE_DISPATCH=top_k
through a scheduler with HRX first and the CPU second. Each case requires that HRX does
not claim the node, that the scheduler places it on the CPU, and that the indices equal
the CPU backend's, entry for entry. Review on #331: nothing else takes this path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: bong-water-water-bong <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[User] ggml_tensor->extra(s) are not freed at the end of llama_eval, causing a memory leak

5 participants