r/LocalLLaMA • • Sep 03 '26 Heartwarming

Tutorial | Guide My RULE of Thumb of choosing a models

Post image
1.1k Upvotes

This is mostly for setting up for expectation, since personally without LLM i could take 3 days (15 hours of active programming) to debug or implement a feature, but with Qwen 27B (even before Qwen 3.8) it take 4 hours.

And yes 0.5 tok/s is human, not accounting of deletion and pausing, that's also the reason i am fine leaving overnight code base wide analysis or fin tech and deep research.

r/LocalLLaMA • • Aug 26 '26

Tutorial | Guide How to Fine-Tune an LLM: An End-to-End Guide

Thumbnail
towardsdatascience.com
90 Upvotes

I ended up fine tuning a mistral 7b to outperform our costly foundational model and saved $300k. I previously thought that fine tuning was pointless (it's definitely not) and that all these problems could be solved with RAG (they can't).

The truth is, a LoRA/QLoRA adapter is extremely useful for many cases, and can dramatically outperform RAG with aggressive system prompts.

With this guide, I want to help people understand the reasonableness of QLoRA on a consumer grade GPU (you might even be able to fine-tune on a colab t4).

It also includes a deep dive on the mathematics behind LoRA/QLoRA as well.

Let me know if I can help you out with your fine tuning pipeline. It certainly works!

r/LocalLLaMA • • Jun 22 '26

Tutorial | Guide Same model, same prompt, 4 different agents

Thumbnail
gallery
91 Upvotes

Setup: one self-hosted Qwen3.6-27B (Q4) on llama.cpp, identical prompt, identical hardware. The only variable is the agent scaffolding. Agents tested: pi, opencode, hermes, qwen code.

Task: a single-file 2D canvas solar system with scripted orbits and gravity that acts only on user-launched comets.

The exact prompt (note the explicit "build incrementally, your context window is small" instruction):

Build a 2D solar system simulation as a self-contained HTML file using <canvas> and vanilla JavaScript (no external libraries).
Scene
- The Sun is fixed at the center of the canvas.
- Several planets orbit the Sun on stable circular/elliptical paths. Planets and the Sun do NOT gravitationally affect each other — their orbits are fixed/scripted, not physically simulated against one another.
- Pure 2D, top-down view. Make the canvas resize to the window.
Gravity model
- The Sun and every planet each have a gravitational mass proportional to their visual radius (bigger body = stronger gravity), matching real-world relative sizes as closely as reasonable.
- This gravity only acts on comets (see below). It does NOT act on the planets or the Sun.
Comets
- The user can launch a comet by clicking and dragging on the canvas: drag direction and length set the comet's initial velocity vector (release to launch).
- Comets ARE affected by the combined gravity of the Sun and all planets (sum of forces), so they curve and can slingshot.
- Each comet draws a fading trail behind it.
- Remove comets when they fly far off-screen.
Controls
- A slider (range input) that scales the gravity strength of ALL bodies up and down proportionally in real time.
Constraints (important — your context window is small):
- Do NOT write one huge file in a single shot. Build it incrementally in small pieces.
- Keep the code compact and readable. Avoid unnecessary comments and verbosity.
- After finishing, tell me the filename so I can open it in a browser.

Results: all 4 produced a working sim, but the code quality differs a lot:

opencode, my pick. Cleanest architecture, mass ∝ radius exactly as asked, and the only one doing sub-stepped integration (×4 per frame) → by far the most stable comet trajectories and slingshots. Reads like a human wrote it. Minor bug: planet-gravity mixes absolute/center-relative coords, but the Sun dominates so you barely notice.

pi, most correct. Coordinate-consistent, distance softening to avoid singularities, removes comets that hit the Sun, planet labels, and the only one with touch support. Less flashy, most robust.

hermes, flashiest, but physically wrong. Only one with real elliptical orbits + a nice drag-vector arrow. But it computes planet gravity on comets at a different time step than it renders the planets, so comets pull toward where the planets aren't. Looks best, simulates worst.

qwen code, most minimal. Shortest, runs, but crude: huge launch-velocity multiplier flings comets off instantly, no softening, no stars.

Takeaway: with a fixed local model, the agent's scaffolding visibly changes the output (integration strategy, coordinate hygiene, edge-case handling). The prettiest demo (hermes) was the buggiest; the plain-looking one (pi) was the most correct; opencode hit the best balance of clean code + stable physics. Curious whether others get the same ranking on their own local setups.

r/LocalLLaMA • • Mar 08 '26 Popcorn

Tutorial | Guide (Llama.cpp) In case people are struggling with prompt processing on larger models like Qwen 27B, here's what helped me out

86 Upvotes

TLDR: I put the --ubatch-size to my GPU's L3 cache is (in MB).

EDIT: This seems to occur only on Qwen 3.5 27B, 35B and 9B on my setup. Also tried Ministral and Devstral, and they didn't have the same quirk happen, allowing me higher ubatch values with no issues

I was playing around with that value, and I had a hard time finding what exactly it did, or rather, I couldn't really understand it from most of the sources, and asking AI chats for help yielded very mixed results.

My GPU is 9070xt, and when I put it to --ubatch-size 64 (as the GPU has 64MB of L3 cache) my prompt processing jumped in speed where it was actually usable for Claude code invocation.

I understand there might well be some resources detailing and explaining this on the web, or in the docs. I am however doing this out of joy of "tweaking gauges" so to speak, and I'm mostly asking Gemini or ChatGPT for back and forth information on what I should change and what that setting does. I just randomly changed these values until I heard the "coil whine" sound on my gpu, and it was actually blazing fast once I dropped it from higher values to 64.

The default value seems to be 512, which explains calling it without --ubatch-size set yielded poor results for me

EDIT: For the sake of having a more complete set of circumstances;

I am on windows 11, using rocm backend through llama.cpp-rocm with the latest (26.2.2) AMD drivers.

Here's the output:

llama-bench -m "I:\Models\unsloth\Qwen3.5-27B-GGUF\Qwen3.5-27B-Q3_K_S.gguf" -ngl 99 -b 8192 -ub 4,8,64,128 -t 12 -fa 1 -ctk q8_0 -ctv q8_0 -p 512 -n 128 HIP Library Path: C:\WINDOWS\SYSTEM32\amdhip64_7.dll ggml_cuda_init: found 1 ROCm devices: Device 0: AMD Radeon RX 9070 XT, gfx1201 (0x1201), VMM: no, Wave Size: 32

modelsizeparamsbackendnglthreadsn_batchn_ubatchtype_ktype_vfatestt/s
qwen35 27B Q3_K - Small11.44 GiB26.90 BROCm991281924q8_0q8_01pp51259.50 ± 0.22
qwen35 27B Q3_K - Small11.44 GiB26.90 BROCm991281924q8_0q8_01tg12826.84 ± 0.03
qwen35 27B Q3_K - Small11.44 GiB26.90 BROCm991281928q8_0q8_01pp51283.25 ± 0.07
qwen35 27B Q3_K - Small11.44 GiB26.90 BROCm991281928q8_0q8_01tg12826.78 ± 0.01
qwen35 27B Q3_K - Small11.44 GiB26.90 BROCm9912819264q8_0q8_01pp512582.39 ± 0.59
qwen35 27B Q3_K - Small11.44 GiB26.90 BROCm9912819264q8_0q8_01tg12826.80 ± 0.01
qwen35 27B Q3_K - Small11.44 GiB26.90 BROCm99128192128q8_0q8_01pp51214.68 ± 0.16
qwen35 27B Q3_K - Small11.44 GiB26.90 BROCm99128192128q8_0q8_01tg12827.09 ± 0.13

EDIT 2, a day after:

Did some more testing. Rocm vs Vulkan llama.cpp behavior on the same Unsloth Qwen3.5 27B Q3_K_S variant. On ROCm, when ubatch goes over 64, the prompt processing slows down to a snails pace, and I noticed that GPU compute buffers on task manager are barely active, at around 6-10%

VRAM is still not at full capacity at that time, nor is CPU or RAM usage any higher due to this.

[Vulkan llama.cpp]
| model                          |       size |     params | backend    | ngl | threads | n_ubatch | type_k | type_v | fa |            test |                  t/s |
| ------------------------------ | ---------: | ---------: | ---------- | --: | ------: | -------: | -----: | -----: | -: | --------------: | -------------------: |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | Vulkan     |  99 |      12 |       32 |   q8_0 |   q8_0 |  1 |          pp4096 |        271.42 ± 0.65 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | Vulkan     |  99 |      12 |       32 |   q8_0 |   q8_0 |  1 |           tg128 |         33.46 ± 0.02 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | Vulkan     |  99 |      12 |       64 |   q8_0 |   q8_0 |  1 |          pp4096 |        447.42 ± 0.29 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | Vulkan     |  99 |      12 |       64 |   q8_0 |   q8_0 |  1 |           tg128 |         33.44 ± 0.02 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | Vulkan     |  99 |      12 |      256 |   q8_0 |   q8_0 |  1 |          pp4096 |        587.76 ± 0.55 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | Vulkan     |  99 |      12 |      256 |   q8_0 |   q8_0 |  1 |           tg128 |         33.43 ± 0.01 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | Vulkan     |  99 |      12 |      512 |   q8_0 |   q8_0 |  1 |          pp4096 |        597.25 ± 0.45 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | Vulkan     |  99 |      12 |      512 |   q8_0 |   q8_0 |  1 |           tg128 |         33.41 ± 0.02 |


[ROCm llama.cpp]


| model                          |       size |     params | backend    | ngl | threads | n_ubatch | type_k | type_v | fa |            test |                  t/s |
| ------------------------------ | ---------: | ---------: | ---------- | --: | ------: | -------: | -----: | -----: | -: | --------------: | -------------------: |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | ROCm       |  99 |      12 |      256 |   q4_0 |   q4_0 |  1 |           pp512 |         14.35 ± 0.36 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | ROCm       |  99 |      12 |      256 |   q4_0 |   q4_0 |  1 |           tg128 |         27.14 ± 0.11 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | ROCm       |  99 |      12 |      256 |   q8_0 |   q8_0 |  1 |           pp512 |         15.36 ± 0.40 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | ROCm       |  99 |      12 |      256 |   q8_0 |   q8_0 |  1 |           tg128 |         27.35 ± 0.07 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | ROCm       |  99 |      12 |      512 |   q8_0 |   q8_0 |  1 |           pp512 |         14.68 ± 0.22 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | ROCm       |  99 |      12 |      512 |   q8_0 |   q8_0 |  1 |           tg128 |         27.16 ± 0.11 |


| model                          |       size |     params | backend    | ngl | threads | n_ubatch | type_k | type_v | fa |            test |                  t/s |
| ------------------------------ | ---------: | ---------: | ---------- | --: | ------: | -------: | -----: | -----: | -: | --------------: | -------------------: |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | ROCm       |  99 |      12 |       32 |   q8_0 |   q8_0 |  1 |          pp2048 |        354.72 ± 5.39 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | ROCm       |  99 |      12 |       32 |   q8_0 |   q8_0 |  1 |           tg128 |         26.95 ± 0.03 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | ROCm       |  99 |      12 |       64 |   q8_0 |   q8_0 |  1 |          pp2048 |        581.98 ± 0.31 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | ROCm       |  99 |      12 |       64 |   q8_0 |   q8_0 |  1 |           tg128 |         26.90 ± 0.01 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | ROCm       |  99 |      12 |       72 |   q8_0 |   q8_0 |  1 |          pp2048 |          8.47 ± 0.04 |
| qwen35 27B Q3_K - Small        |  11.44 GiB |    26.90 B | ROCm       |  99 |      12 |       72 |   q8_0 |   q8_0 |  1 |           tg128 |         27.24 ± 0.12 |

Well, this has been fun.

I'll just go use Vulkan like a normal person

r/LocalLLaMA • • Aug 17 '26 Bravo Heartwarming

Tutorial | Guide After pushing 1M+ tokens through Qwen 3.8 27B, here is my optimal llama.cpp config for 16GB VRAM (73k Context, Agentic Coding)

Thumbnail
gallery
1.0k Upvotes

Dando seguimiento a mi post anterior sobre cómo tengo montado mi servidor de presupuesto (Intel N100 + RTX 5060 Ti 16GB), varios me preguntaron por una mirada más profunda a mi configuración real de inferencia y al desempeño agentic en el mundo real.

Como muchos de ustedes, estaba refrescando la página esperando descargar Qwen 3.8 27B apenas salió. Después de pasar todo el fin de semana estresándolo con flujos de trabajo de codificación agentic, logré correr un proyecto completo y grande casi todo de forma autónoma (más de 1M de tokens procesados en total, solo 3 prompts).

Aquí va un resumen rápido de la configuración base antes de meternos en los detalles del config y del workflow.

Specs y parámetros rápidos

  • Modelo: Qwen3.8-27B-UD-Q3_K_XL.gguf
  • Hardware: RTX 5060 Ti (16GB VRAM) + Intel N100 (4C/4T, 16GB RAM)
  • Ventana de contexto: 73,728 (73k de contexto) corriendo tranqui en 16GB de VRAM.
  • Cuantización de KV Cache: q4_1 para el contexto principal
  • Decodificación especulativa: MTP nativa activada (spec-type = draft-mtp, n-max = 2)
  • Sampling: temp = 0.65, top_p = 0.95, top_k = 20, min_p = 0.05

El experimento: armar una API completa con 3 prompts

En vez de correr benchmarks sintéticos, metí esta configuración por una cadena real de ingeniería de software: construyendo una REST API no oficial y un servidor MCP para un foro vBulletin heredado.

  1. Prompt 1 (Arquitectura del sitio y análisis): Pedí al modelo que mapee el sitio objetivo. Generó una especificación en Markdown impecable de ~1,500 líneas que cubría análisis estructural, nodos HTML rescatables, payloads JSON esperados, selección de stack, lógica de paginación, autenticación de sesión y endpoints de búsqueda—mucho más a fondo de lo que yo habría escrito a mano.
  2. Prompt 2 (Arquitectura de desarrollo): Usando la spec como única fuente de verdad, diseñó un plan de implementación modular de NestJS dividido en 9 fases de ejecución:
  • Fase 1: Estructura inicial del proyecto
  • Fase 2: Modelos de dominio
  • Fase 3: Scraping core (HTTP + limitación de tasa + reintentos)
  • Fase 4: Parsers de HTML (cheerio)
  • Fase 5: Capa de caché
  • Fase 6: Servicios de aplicación + REST API
  • Fase 7: Autenticación (sesiones con cookies)
  • Fase 8: Servidor MCP (entrega principal)
  • Fase 9: Fortalecimiento, documentación y entrega
  1. Prompt 3 (Ejecución autónoma agentic): La prueba de verdad. Le pedí a OpenCode (usando Qwen 3.8 27B) que actuara estrictamente como orquestador, creando sub-agentes para cada fase de tareas. Corrió de forma autónoma por ~2 horas. Cuando se acercaron los límites de contexto, OpenCode resumió su estado y siguió construyendo. Escribió tests unitarios, aplicó linting y entregó código 100% funcional—solo necesitando un arreglo automatizado menor cuando le di un payload de HTML crudo con un caso extremo.

El archivo de configuración llama.cpp

Aquí está mi archivo exacto de configuración de enrutador --models-preset . Fíjate cómo fit = off se usa en el perfil de 27B junto con ctx-size = 73728 (73k) y q4_1 para cuantizar la KV cache, con el objetivo de maximizar la asignación de VRAM mientras se mantiene el rendimiento nativo de MTP.

# ==============================================================================
# LLAMA.CPP — CONFIGURACIÓN DE INFERENCIA (modo router / --models-preset)
# ==============================================================================
#
# Objetivo de hardware:
#   GPU: 16 GB VRAM (RTX 5060 Ti)
#   CPU: Intel N100, 4C/4T (Debian Headless)

# ------------------------------------------------------------------------------
# GLOBAL / LÍNEA BASE
# ------------------------------------------------------------------------------
[*]

# --- HILOS DE CPU -----------------------------------------------------------
# Reserva 1 core para SO/servicios durante el decode.
# Usa los 4 threads durante ráfagas de prefill del prompt.
threads             = 3
threads-batch       = 4

# --- SERVIDOR / CONCURRENCIA ---------------------------------------------------
# Un solo slot; desactivado continuous batching para máximo rendimiento por usuario.
parallel            = 1
cont-batching       = 0

# --- GPU / AJUSTE DE VRAM ---------------------------------------------------------
flash-attn          = on
fit                 = on

# Holgura de seguridad para el límite físico de VRAM (MiB).
# Ponlo bajo (128) porque el sistema es headless (100% VRAM disponible para inferencia).
# NOTA: Si usas caches KV draft de MTP, ojo con la asignación doble de VRAM. 
# Sube a 128-256 si te topas con OOMs.
fit-target          = 128

# --- CONTEXTO & CACHÉ ------------------------------------------------------
ctx-size            = 65536
context-shift       = 1

# Desactiva checkpoints de contexto (evita problemas de reprocesamiento en arquitecturas híbridas)
ctx-checkpoints     = 0

# RAM Prompt Cache (2 GiB)
cache-ram           = 2048

# --- KV CACHE GLOBAL --------------------------------------------------------
cache-type-k        = q5_1
cache-type-v        = q5_1

# --- PREFILL / BATCHING -----------------------------------------------------
batch-size          = 2048
ubatch-size         = 1024

# --- SAMPLING POR DEFECTO (Códigos / Precisión) ----------------------------------
temp                = 0.5
top-p               = 0.95
top-k               = 20
min-p               = 0.05
repeat-penalty      = 1.0

# ------------------------------------------------------------------------------
# QWEN 3.8 27B — PERFIL DE RAZONAMIENTO & CODIFICACIÓN PESADA
# ------------------------------------------------------------------------------
[qwen3.8-27b]
model               = /opt/llama-infrastructure/models/Qwen3.8-27B-UD-Q3_K_XL.gguf

# Desactiva "fit" para evitar que capas se carguen en la CPU por un error de cálculo automático
fit                 = off
ctx-size            = 73728
context-shift       = 1

# MTP nativa del modelo (Decodificación especulativa)
spec-type           = ngram-mod,draft-mtp
spec-draft-n-max    = 2

# Cuantización de KV (q4_1 nos permite meter contexto de 73k en 16GB de VRAM)
cache-type-k        = q4_1
cache-type-v        = q4_1

# Parámetros de presupuesto de pensamiento / razonamiento
chat-template-kwargs = {"preserve_thinking": true, "reasoning_effort":"medium"}
reasoning-budget    = 5000

# Batches más chicos para evitar picos de VRAM durante prefills masivos
batch-size          = 1024
ubatch-size         = 512

# Ajustes oficiales / recomendados del sampler de cuantización
temp                = 0.65
top-p               = 0.95
top-k               = 15
min-p               = 0.05

r/LocalLLaMA • • Aug 29 '25

Tutorial | Guide Qwen3-coder is mind blowing on local hardware (tutorial linked)

1.1k Upvotes

Hello hello!

I'm honestly blown away by how far local models have gotten in the past 1-2 months. Six months ago, local models were completely useless in Cline, which tbf is pretty heavyweight in terms of context and tool-calling demands. And then a few months ago I found one of the qwen models to actually be somewhat usable, but not for any real coding.

However, qwen3-coder-30B is really impressive. 256k context and is actually able to complete tool calls and diff edits reliably in Cline. I'm using the 4-bit quantized version on my 36GB RAM Mac.

My machine does turn into a bit of a jet engine after a while, but the performance is genuinely useful. My setup is LM Studio + Qwen3 Coder 30B + Cline (VS Code extension). There are some critical config details that can break it (like disabling KV cache quantization in LM Studio), but once dialed in, it just works.

This feels like the first time local models have crossed the threshold from "interesting experiment" to "actually useful coding tool." I wrote a full technical walkthrough and setup guide: https://cline.bot/blog/local-models

r/LocalLLaMA • • Aug 05 '26

Tutorial | Guide I took a local OCR model's accuracy from 60% to 99%

0 Upvotes

I built a local OCR pipeline a few days ago, and it turned into a surprisingly interesting experiment—taking accuracy from around 60% to 99%.

I wrote a short blog about what worked, what failed, and the breakthrough that finally made the difference.

Thought some of you might enjoy it.

Link in the comments