Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Fix Local AI Agents Using Too Much Memory or Running Slowly

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Local AI agents—like those running on Ollama, LM Studio, or custom Python scripts—can grind your machine to a halt when they consume excessive memory or respond sluggishly. This guide walks you through practical, step-by-step methods to diagnose and fix performance issues, covering model selection, system settings, and code-level optimizations. You'll learn how to identify the bottleneck, reduce memory footprint, and speed up inference without sacrificing output quality.

What You'll Need

  • Access to the terminal or command prompt on your machine
  • Administrator or sudo privileges (for changing system settings)
  • Basic familiarity with your AI agent's configuration files (e.g., Ollama's Modelfile, LM Studio's settings, or Python environment)
  • A monitoring tool like Task Manager (Windows), Activity Monitor (macOS), or htop (Linux)

Step-by-Step

  1. Identify the bottleneck. Open your system monitor and run a few typical prompts. Watch whether CPU, GPU, or RAM spikes to 100%. If RAM is constantly maxed out, the issue is memory. If CPU/GPU is pegged but RAM is fine, it's a speed problem. Note the model name and size you're using.
  2. Check current memory usage. In the terminal, run ps aux --sort=-%mem | head -20 (Linux/macOS) or use Task Manager's Details tab (Windows) to see which processes are consuming the most memory. This tells you if it's the model runtime, your agent script, or something else.
  3. Reduce model size or use a quantized version. If you're using a 13B or 70B parameter model, switch to a smaller one (7B or 3B) or use a quantized version (e.g., Q4_K_M instead of F16). Quantization reduces memory usage by 4-5x with minimal quality loss. For Ollama, you can specify a quantized model like llama3.2:1b-q4_K_M. In LM Studio, download a GGUF file with a lower quantization.
  4. Limit context window. A longer context window (e.g., 8192 tokens) uses more memory. Reduce it to 2048 or 4096 if your tasks don't need long conversations. In Ollama, set num_ctx in the Modelfile or via the API. In LM Studio, adjust the context length in the model settings.
  5. Adjust GPU offloading. If you have a GPU, make sure as many layers as possible are offloaded to it (this speeds up inference). In Ollama, set num_gpu to the number of layers you want to offload, or use OLLAMA_NUM_GPU environment variable. In LM Studio, use the "GPU Offload" slider. If you don't have a GPU, skip this step.
  6. Optimize your agent's code. If you're running a custom Python agent, look for memory leaks. Use gc.collect() after large operations, avoid holding onto large data structures, and stream responses instead of loading them all into memory. For example, use response.iter_content() instead of response.content when making HTTP calls.
  7. Set a memory limit (optional). On Linux, you can use ulimit -v 4096 to limit virtual memory to 4GB for a process. This forces the agent to stay within bounds, but may cause crashes if it's not enough. On Windows, you can use Job Objects, but it's more complex.
  8. Update your software. Ensure you're running the latest version of your AI runtime (Ollama, llama.cpp, etc.). Performance improvements and memory fixes are frequently released. Check the official GitHub or website for updates.
  9. Restart the agent periodically. Long-running agents can accumulate memory fragmentation. A simple restart every few hours can free up memory and improve responsiveness.

Common Mistakes

  • Using a model that's too large for your hardware. A 70B model on a 16GB RAM machine will always be slow and memory-heavy. Match the model to your hardware.
  • Ignoring the context window. Even a small model can eat 8GB of RAM if you set the context to 32k. Always reduce context to what you actually need.
  • Not using quantization. Many users load F16 models when Q4 would work fine. Quantization is the single biggest memory saver.
  • Forgetting to close resources. In Python, not closing file handles or database connections can cause memory leaks. Use with statements.
  • Running multiple agents simultaneously. Each instance loads its own copy of the model. Run one at a time or use a shared model server.

Tips

  • Use a model server. Instead of loading the model in each script, run a single server (like Ollama or LM Studio's server mode) and have your agent connect via API. This shares the model across requests, saving memory.
  • Monitor with a dedicated tool. Use nvidia-smi for GPU memory, and free -h for RAM. Set up alerts if memory crosses a threshold.
  • Experiment with batch size. If you're doing batch inference, a smaller batch size reduces memory but may be slower. Find the sweet spot.
  • Use flash attention. If your runtime supports it (e.g., llama.cpp with -fa), enable it. It reduces memory usage for long sequences.
  • Consider a smaller embedding model. If your agent uses embeddings, switch to a tiny model like all-MiniLM-L6-v2 instead of a large one.

Troubleshooting

  • If the agent still runs slowly after reducing model size: Check if the CPU is throttling due to heat. Clean your fans and ensure proper ventilation. Also, close other heavy applications (browsers, games) that compete for resources.
  • If you get out-of-memory errors: Lower the context window further, use an even smaller quantization (Q2_K), or increase your system's swap space (but note this will slow things down).
  • If the agent crashes after setting a memory limit: The limit is too low. Increase it gradually until stable.
  • If GPU offloading doesn't seem to help: Verify that your GPU is actually being used (check nvidia-smi during inference). Some GPUs don't support certain operations, forcing fallback to CPU.
  • If the problem is intermittent: Look for memory leaks in your code. Use Python's tracemalloc to track allocations and identify where memory grows.

Frequently Asked Questions

Why does my AI agent use so much memory even with a small model?

Even small models (7B) need ~4-6GB in FP16. The context window, batch size, and any additional data (like embeddings) also contribute. Check your context length and reduce it.

Is it better to use CPU or GPU for local AI?

GPU is faster for inference, but uses more power. CPU is more memory-efficient per GB, but slower. If you have a GPU with enough VRAM, use it. Otherwise, CPU with quantization is fine.

Can I run multiple AI agents at once?

Yes, but each loads its own model into memory. If you have 16GB RAM, running two 7B models (each ~4GB) is possible, but you'll be tight. Use a single server to share the model.

How do I know which quantization to choose?

Q4_K_M is a good balance of quality and size. Q8 is higher quality but uses more memory. Q2 is smallest but noticeably worse. Start with Q4_K_M and adjust based on your quality needs.

Will reducing the context window affect my agent's performance?

Only if your tasks require long conversations or large documents. If you're doing simple Q&A, 2048 tokens is usually enough. Test with your actual use case.

What's the best way to monitor memory usage in real-time?

On Linux/macOS, use htop and press F6 to sort by memory. On Windows, use Task Manager's Performance tab. For GPU, use nvidia-smi with a refresh rate.