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

Misc. bug: UMA detection incorrectly limits available memory on AMD APUs with large TTM allocations

Open AmesianX opened this issue 11 months ago • 5 comments

Name and Version

$ ./llama-server --version ggml_cuda_init: GGML_CUDA_FORCE_MMQ: no ggml_cuda_init: GGML_CUDA_FORCE_CUBLAS: no ggml_cuda_init: found 1 ROCm devices: Device 0: AMD Radeon Graphics, gfx1151 (0x1151), VMM: no, Wave Size: 32 version: 7464 (0a0bba05e) built with Clang 20.0.0 for Linux x86_64

Operating systems

Linux

Which llama.cpp modules do you know to be affected?

llama-server

Command line

./llama-server -m /home/user/Models/lmstudio-community/gpt-oss-120b-GGUF/gpt-oss-120b-MXFP4-00001-of-00002.gguf \
    -t 4 \
    -c 131072 \
    -n 8192 \
    --parallel 10 \
    --cont-batching \
    --jinja \
    --reasoning-format deepseek \
    --chat-template-kwargs '{"reasoning_effort": "low", "reasoning_format": "auto"}' \
    --n-gpu-layers 999 \
    --swa-full \
    --flash-attn on \
    -b 2048 \
    -ub 2048 \
    --no-mmap \
    --cache-type-k q8_0 \
    --cache-type-v q8_0 \
    --cache-ram 0 \
    --cache-reuse 256 \
    --defrag-thold 0.1 \
    --temp 1.0 \
    --top-p 1.0 \
    --top-k 0 \
    --min-p 0 \
    --host 0.0.0.0 \
    --port 8888 \
    --api-key "okokok"

Problem description & steps to reproduce

Summary

The UMA (Unified Memory Architecture) detection introduced in PR #17368 incorrectly identifies AMD APUs (such as Strix Halo) as UMA systems and limits the available GPU memory to system RAM's MemAvailable, ignoring the much larger TTM (Translation Table Manager) memory allocation that AMD APUs can utilize.

Environment

  • Hardware: AMD Strix Halo APU (gfx1151)
  • GPU Memory: 96GB TTM allocation via kernel boot parameters
  • System RAM: 32GB
  • OS: Ubuntu Linux with kernel 6.14.0
  • ROCm Version: 7.9.0
  • llama.cpp Version: Latest master (commit 0a0bba05e)

Kernel Boot Parameters

amdgpu.gttsize=98304 ttm.pages_limit=25000000 ttm.page_pool_size=12000000

Problem Description

After PR #17368 (DGX Spark: UMA support), the ggml_backend_cuda_device_get_memory() function checks prop.integrated > 0 to detect UMA systems. When detected as UMA, it reads available memory from /proc/meminfo instead of using cudaMemGetInfo().

The issue: AMD APUs report integrated = true, but they can utilize significantly more memory than system RAM through TTM. In my case:

  • System RAM available: ~27GB
  • Actual GPU memory available via TTM: 96GB

This causes the new llama_params_fit auto-fitting logic to incorrectly calculate that there isn't enough memory, resulting in:

  1. Context size being reduced from 131072 to 4096
  2. Model layers being offloaded to CPU unnecessarily
  3. Significant performance degradation

Logs

Before patch (incorrect behavior):

llama_params_fit_impl: projected to use 64909 MiB of device memory vs. 98304 MiB of free device memory
llama_params_fit_impl: cannot fulfill margin of 1024 MiB, need to reduce device memory by 37767 MiB
llama_params_fit_impl: context size reduced from 131072 to 4096
llama_params_fit_impl: ROCm0 (AMD Radeon Graphics): 36 layers (21 overflowing), 27049 MiB used

After patch (correct behavior):

llama_params_fit_impl: projected to use 64909 MiB of device memory vs. 98304 MiB of free device memory
llama_params_fit_impl: will leave 33092 >= 1024 MiB of free device memory, no changes needed

Root Cause

In ggml/src/ggml-cuda/ggml-cuda.cu, the ggml_backend_cuda_device_get_memory() function:

#if defined(__linux__)
    cudaDeviceProp prop;
    CUDA_CHECK(cudaGetDeviceProperties(&prop, ctx->device));

    bool uma_env = getenv("GGML_CUDA_ENABLE_UNIFIED_MEMORY") != nullptr;
    bool is_uma = prop.integrated > 0 || uma_env;  // <-- AMD APUs hit this

    if (is_uma) {
        // Uses /proc/meminfo which returns ~27GB instead of 96GB TTM
        if (ggml_backend_cuda_get_available_uma_memory(&available_memory_kb, &free_swap_kb) && available_memory_kb > 0) {
            *free = (size_t)available_memory_kb * 1024;
        }
    }
#endif

Proposed Fix

Skip the UMA memory detection for ROCm/HIP builds, as AMD APUs with TTM can report accurate memory via hipMemGetInfo():

-#if defined(__linux__)
+#if defined(__linux__) && !defined(GGML_USE_HIP)
     // Check if this is a UMA (Unified Memory Architecture) system
+    // Note: Skip this for ROCm/HIP - AMD APUs with large TTM allocations (e.g., Strix Halo)
+    // report integrated=true but can use much more memory via TTM than system RAM
     cudaDeviceProp prop;
     CUDA_CHECK(cudaGetDeviceProperties(&prop, ctx->device));
     ...
-#endif // defined(__linux__)
+#endif // defined(__linux__) && !defined(GGML_USE_HIP)

Alternative Solutions

  1. Environment variable override: Add an env var like GGML_CUDA_DISABLE_UMA_DETECTION to skip UMA detection
  2. TTM-aware detection for AMD: Check /sys/class/drm/card*/device/mem_info_vram_total or similar for AMD GPUs
  3. Compare reported vs actual: If cudaMemGetInfo returns significantly more than MemAvailable, prefer cudaMemGetInfo

Verification

With the proposed patch applied:

  • amd-smi shows 65GB+ GPU memory usage (correct)
  • Model loads with full 128K context
  • All 36 layers stay on GPU
  • No unnecessary CPU offloading

Related

  • PR #17368: DGX Spark: UMA support
  • PR #17537: cuda: fix UMA detection on discrete GPUs

System Information

$ amd-smi
+------------------------------------------------------------------------------+
| AMD-SMI 26.1.0      ROCm version: 7.9.0                                      |
|-------------------------------------+----------------------------------------|
| 0000:c5:00.0    AMD Radeon Graphics |                          65XXX/98304 MB |
+-------------------------------------+----------------------------------------+

$ amd-ttm
Current TTM pages limit: 25000000 pages (95.37 GB)
Total system memory: 30.99 GB

$ cat /proc/cmdline
... amdgpu.gttsize=98304 ttm.pages_limit=25000000 ...

First Bad Commit

No response

Relevant log output


AmesianX avatar Dec 18 '25 05:12 AmesianX

I think the use of /proc/meminfo :: MemAvailable is correct if you define GGML_CUDA_ENABLE_UNIFIED_MEMORY

If you use export GGML_CUDA_ENABLE_UNIFIED_MEMORY=ON ggml-hip backend did not use VRAM/TTM, the memory is allocated on system RAM.

so you have 2 case:

  • 1: use export GGML_CUDA_ENABLE_UNIFIED_MEMORY=ON in that case:
    • do not change TTM it is not use,
    • set VRAM as low as possible (512Mo...)
  • 2: if you do not use GGML_CUDA_ENABLE_UNIFIED_MEMORY env :
    • 2.1: with never kernel (can remember which one... >6.10/6.11 I think)
      • set VRAM as low as possible (512Mo...)
      • set GTT/TTM as you want. => in that case the memory available is VRAM+TTM.
    • 2.2: with older kernel
      • TTM/GTT is not use when gpu memory alloc.
      • Set VRAM as high as needed (96G for max)

So my advise in your case with 6.14 kernel, remove all you kernel param (This isn't even the correct way to do it for recent OS versions (Fedora 43 + systemd), for example.) set VRAM as low as possible, and run llama.cpp+romc like that:

GGML_CUDA_ENABLE_UNIFIED_MEMORY=ON ./llama-server [...]

good luck ;)

Djip007 avatar Jan 28 '26 01:01 Djip007

* 1: use `export GGML_CUDA_ENABLE_UNIFIED_MEMORY=ON` in that case:
  * do not change TTM it is not use,
  * set VRAM as low as possible (512Mo...)
* 2: if you do not use `GGML_CUDA_ENABLE_UNIFIED_MEMORY` env :
  * 2.1: with never kernel (can remember which one... >6.10/6.11 I think)
    * set VRAM as low as possible (512Mo...)
    * set GTT/TTM as you want.
      => in that case the memory available is VRAM+TTM.

Is there any performance difference between 1 and 2.1?

alex-mashin avatar Jul 07 '26 02:07 alex-mashin

Reproduced on a second Strix Halo (gfx1151) config — same root cause, adding a data point and a fix that I think is safer than disabling UMA for HIP entirely.

Config: Ryzen AI Max+ 395, 128 GB RAM, 96 GB dedicated VRAM carveout set in BIOS (not a kernel TTM param), so the OS sees ~30 GB RAM. ROCm 7.2.4. The 96 GB is real, allocatable VRAM — a direct hipMalloc of ~85 GB succeeds and an 85 GB model runs fully on the GPU once the reporting is corrected.

Concern with && !defined(GGML_USE_HIP): that disables the UMA path for all HIP builds, which would re-break genuinely shared-memory HIP APUs (small-carveout iGPUs) that this override was added for. It fixes dedicated-carveout APUs by removing the feature for the shared ones.

Alternative that handles both: take the max of the two values instead of overwriting — never lower the driver-reported VRAM below what hipMemGetInfo already returned:

if (ggml_backend_cuda_get_available_uma_memory(&available_memory_kb, &free_swap_kb) && available_memory_kb > 0) {
    const size_t uma_free = (size_t)available_memory_kb * 1024;
    if (uma_free > *free) {   // only raise to system RAM, never clobber real VRAM
        *free = uma_free;
    }
}
  • Dedicated carveout: hipMemGetInfo free (~95 GB) > system RAM (~27 GB) → keep ~95 GB.
  • True shared APU: hipMemGetInfo free (small heap) < system RAM → use system RAM (current behavior preserved).

Evidence (gfx1151, ROCm 7.2.4):

reported free 85 GB model placement
unpatched ~27 GB spills to CPU / OOM
max() patch ~95 GB fully on GPU, loads normally

Happy to open a PR with the one-liner if that direction sounds good.

boherlin avatar Jul 14 '26 16:07 boherlin

Hey whats up second gfx1151 box confirming boherlin's numbers, on current master.

Config: Ryzen AI Max+ 395 (Radeon 8060S), 128 GB unified LPDDR5X, 96 GB BIOS VRAM carveout — OS sees ~31 GB RAM, GTT 15.5 GB, no ttm/gttsize kernel params. Ubuntu 24.04, kernel 7.0.0-28-generic, ROCm 7.2.4, llama.cpp master 555881e built with -DGGML_HIP=ON -DAMDGPU_TARGETS=gfx1151.

Raw values:

source value
hipMemGetInfo free 98,148 MiB / total 98,304 MiB (prop.integrated = 1)
/proc/meminfo MemAvailable 29,382,252 kB (~28.7 GiB)

llama-cli --list-devices:

build env reported free / total (MiB)
master 555881e — 28,239 / 98,304
master 555881e GGML_CUDA_ENABLE_UNIFIED_MEMORY=1 28,220 / 98,304
+ max() patch from #18159 (comment) — 98,148 / 98,304
+ max() patch GGML_CUDA_ENABLE_UNIFIED_MEMORY=1 98,148 / 98,304

Notes:

  • Unpatched master reports MemAvailable instead of the ~96 GiB the driver says is free, so ~70 GiB of the carveout is invisible to llama_params_fit.
  • Setting GGML_CUDA_ENABLE_UNIFIED_MEMORY does not change the report, the UMA path is already active via prop.integrated, so the env-var workaround suggested earlier in the thread doesn't help the memory reporting.
  • The max() patch applies to current master with a one-line offset and restores the driver-reported value; behavior with the env var set is unchanged.
  • Happy to be a second test box if boherlin opens the PR.

ACNoonan avatar Jul 25 '26 04:07 ACNoonan

Thanks to the maintainers and to everyone who already reported here. I'm a curious user, not a ROCm or llama.cpp expert. This is a personal lab on a low-end laptop: not meant for production and not tested beyond this machine.

AI was used throughout: AI agents did the research (issues and other projects' code), wrote the test code, ran the tests on my machine, and drafted this text from my notes; I reviewed it and the numbers come from my machine. It was trial and error, I don't understand every cause, and I may be wrong. Please treat this as a lead, not a fix. Corrections are welcome.

The opposite case of this issue, on an APU with a small BIOS carveout.

This issue was about a large BIOS VRAM carveout, where MemAvailable underestimated the memory. The fix (PR #17368) keeps that adjustment out of HIP.

Mine is the opposite: small carveout (512 MiB) and a large GTT (10 GiB). Then hipMemGetInfo reports the free GTT — and the GTT is the same RAM every program uses. Measured here:

Moment hipMemGetInfo free MemAvailable (RAM the system can give)
Desktop almost idle 10.00 GiB 7.6 GiB
Another process loading 2.67 GiB 3.9 GiB
The run that froze the machine 10.00 GiB 5.3 GiB

In the last row the automatic fit (--fit) asked for about 9 GiB on the GPU with 5.3 GiB available. The kernel ran out of memory (OOM) and the driver spent 30 minutes in the svm_range_restore_work loop. Hard reboot.

What worked here (lab only, without touching ggml): before the fit, cap what the integrated GPU may use at MemAvailable − a reserve.

An idea for the general rule (tested only here): count the two memories separately —

free = vram_free + min(gtt_free, MemAvailable)

That gives about 95 GiB on the Strix Halo setups with a 96 GiB carveout (this issue's case) and about 0.5 + 5.3 GiB on my machine. The suggestion here of taking the larger of the two values fixes the first case but would keep the error in mine.

Strata does something similar on integrated GPUs: MemAvailable − 6 GiB (link below).

Main report with the measurements: https://github.com/ggml-org/llama.cpp/issues/19482#issuecomment-7012644238.

How I cap the integrated GPU before the fit
// cap = min(MemAvailable − reserve, fraction × total RAM)
// default reserve 512 MiB; default fraction 100 % (only the GTT limits)
fn cap(available: u64, reserve: u64, total: Option<u64>, fraction_pct: u64) -> u64 {
    let by_available = available.saturating_sub(reserve);
    match total {
        Some(t) => by_available.min(t / 100 * fraction_pct),
        None => by_available,
    }
}
// the margin passed to common_fit_params for the integrated GPU is: reported_free − cap
10-line program that shows hipMemGetInfo reporting the GTT

Build: hipcc --offload-arch=gfx1030 hip-props.hip -o hip-props

#include <hip/hip_runtime.h>
#include <cstdio>
int main(){int n=0; if(hipGetDeviceCount(&n)!=hipSuccess){printf("no device\n");return 1;}
for(int i=0;i<n;i++){hipDeviceProp_t p; hipGetDeviceProperties(&p,i); size_t f=0,t=0; hipSetDevice(i); hipMemGetInfo(&f,&t);
printf("dev %d: %s gcnArch=%s integrated=%d canMapHostMemory=%d managedMemory=%d pageableMemoryAccess=%d concurrentManagedAccess=%d totalGlobalMem=%.2f GiB hipMemGetInfo free=%.2f GiB total=%.2f GiB\n",
i,p.name,p.gcnArchName,p.integrated,p.canMapHostMemory,p.managedMemory,p.pageableMemoryAccess,p.concurrentManagedAccess,p.totalGlobalMem/1073741824.0,f/1073741824.0,t/1073741824.0);}
return 0;}

Output here: integrated=1, hipMemGetInfo free=10.00 GiB while MemAvailable was 7.6 GiB.

Links (what came from where)

  1. llama.cpp today (master, commit 2cbfc3c): the block that swaps free memory for MemAvailable, active only outside HIP (!defined(GGML_USE_HIP)) — ggml/src/ggml-cuda/ggml-cuda.cu, lines 6239–6259.
  2. This issue's fix: PR #17368.
  3. Strata (commit c775728): integrated-GPU free memory = MemAvailable − STRATA_UMA_HEADROOM_GIB (default 6) — src/core/expert_cache.cpp, lines 115–145.
Unit tests (23 passed, 2026-11-18)

Pure logic, no GPU: cargo test --release -j1 -p busca --no-default-features --features rocm --lib → 23 passed; 0 failed, run twice. The measurements in the tables are a different thing: real runs, one each.

Test What it checks
apu_budget_and_cap APU budget (carveout + GTT) vs discrete card, the iGPU cap, the false "available" peak right after another process exits, gfx override from the KFD gfx_target_version
gpu_ram_disk_split the GPU / fit / experts-in-RAM / CPU decision
ssd_manager_names tensor names blk.N.ffn_*_exps.weight and graph node ffn_moe_topk-N
ssd_manager_ceiling RAM ceiling for experts read from the mmap (70 % of available, minimum 512 MiB)
lru_respects_ceiling LRU over a real mmap gives back the oldest expert and never the layer in use
proc_reading, monitor_stops_on_drop the /proc reader (disk, CPU, RAM) and the monitor thread stopping
16 older tests log parsing, UTF-8, KV cache types

Behaviour test of the safety guard: with the swap limit set to 1 MiB the process exits with code 137, no segfault.

The tests behind the numbers in these comments (function names translated from Portuguese):

#[test]
fn apu_budget_and_cap() {
    const M: u64 = 1024 * 1024;
    // Radeon 610M: 512 MiB carveout + 10 GiB GTT -> 85 % of the sum
    assert_eq!(budget_from(512 * M, 10240 * M), (512 + 10240) * M / 100 * 85);
    // 12 GiB discrete card: only its VRAM counts
    assert_eq!(budget_from(12288 * M, 16000 * M), 12288 * M / 100 * 85);
    // gfx override read from the KFD gfx_target_version
    assert_eq!(gfx_override_for(100306), Some("10.3.0")); // gfx1036
    assert_eq!(gfx_override_for(100300), None);           // a real gfx1030
    assert_eq!(gfx_override_for(110003), None);           // RDNA3
    // 2026-11-18: 5 GiB available and a 3 GiB reserve leave 2 GiB for the iGPU
    assert_eq!(cap(5 * 1024 * M, 3072 * M, None, 35), 2048 * M);
    assert_eq!(cap(1024 * M, 3072 * M, None, 35), 0);
    // false peak right after another process exits: 9.6 GiB "available" on 14.4 GiB -> the fraction wins
    let total = 14746 * M;
    assert_eq!(cap(9830 * M, 3072 * M, Some(total), 35), total / 100 * 35);
}

#[test]
fn gpu_ram_disk_split() {
    const G: u64 = 1024 * 1024 * 1024;
    // auto: 11 GiB model, 8 GiB budget -> llama.cpp fit (GPU first, the rest in RAM)
    assert_eq!(decide("auto", true, 11 * G, Some(8 * G)), Fit);
    // auto: it fits -> all on the GPU
    assert_eq!(decide("auto", true, 2 * G, Some(8 * G)), Gpu);
    // auto with an unknown budget -> don't guess
    assert_eq!(decide("auto", true, 11 * G, None), Gpu);
    // no GPU, even when forced
    assert_eq!(decide("on", false, 11 * G, Some(8 * G)), Cpu);
    assert_eq!(decide("on", true, 1, Some(8 * G)), ExpertsInRam);
    assert_eq!(decide("off", true, 11 * G, Some(G)), Gpu);
}
Environment (full versions)
  • OS: Ubuntu 26.04 LTS, Linux kernel 7.0.0-43-generic (package linux-image-7.0.0-43-generic 7.0.0-43.43), amdgpu driver 3.64.0.
  • Firmware: linux-firmware-amd-graphics 20260319.git217ca6e4-0ubuntu3.1; DMUB 0x06001300; VBIOS 102-MENDOCINO-006.
  • Kernel parameter: ttm.pages_limit=2621440 (10 GiB GTT) — ttm.pages_limit in the kernel docs.
  • ROCm (Ubuntu packages): HIP 7.1.52801 (libamdhip64-7 7.1.0-0ubuntu2, hipcc 7.1.1+dfsg-0ubuntu1); libhsa-runtime64-1 7.1.0+dfsg-0ubuntu9; libhsakmt1 7.1.0+dfsg-0ubuntu9; librocblas5 7.1.0-1ubuntu4; libhipblas3 7.1.0-0ubuntu5; rocminfo 7.1.1-0ubuntu1.
  • Compilers: clang-21 1:21.1.8-6ubuntu1; Rust 1.97.1; CMake 4.2.3.
  • Hardware: ASUS Vivobook Go E1504FA (BIOS E1504FA.317); Ryzen 5 7520U; Radeon 610M 1002:1506 (gfx1036, 2 CUs, up to 1899 MHz); 2 × 8 GB LPDDR5-5500; clocks at power_dpm_force_performance_level=high.
  • llama.cpp used in the tests: the one bundled by the Rust crate llama-cpp-sys-2 0.1.161 (llama-cpp-rs, commit e7af607), which ships llama.cpp at commit d812350; HIP build for gfx1030, run with HSA_OVERRIDE_GFX_VERSION=10.3.0.
  • Model: gpt-oss-20b-MXFP4.gguf (12,109,566,624 bytes, sha256 27cd6c432c7672cb812a92f611cf3ba7bbc35928262bb1e1253ff4ee6ae35901).
  • Automated tests of my code: 23 passed (18/11/2026). They test the logic (memory limits, GPU/RAM decision, /proc parsing), without a GPU. The tables above are a different thing: real runs, one each.

programandosolucoes avatar Nov 19 '26 14:11 programandosolucoes