Solution:
Root Cause: Excessive Context Allocation (num_ctx) Overhead
Processing massive prompt context windows (e.g., 32k or 128k tokens) requires significant compute resources during the initial prompt evaluation phase (KV cache creation). High default context allocations force CPU memory paging before generation starts.
Step-by-Step Fix:
1.Restrict Context Window in Custom Modelfile:
Create a text file named Modelfile containing: dockerfile
FROM llama3:8b
PARAMETER num_ctx 4096
Build the optimized model variant: ollama create llama3-4k -f ./Modelfile2.Adjust Runtime Parameters in API Requests:
When sending requests via API, explicitly declare num_ctx in the options block: json
{
"model": "llama3",
"options": {
"num_ctx": 4096,
"num_thread": 8
}
}
3.Set CPU Thread Limits for System Hardware:
Set num_thread to match your CPU's physical core count (not logical hyperthreads) to avoid CPU thread thrashing. Further setup details can be found in the Ollama Official Documentation.