Table of Contents


Model: qwen3:4b-instruct

A local model serves text through the llama.cpp completion endpoint, and every knob that shapes which token comes out next is exposed as a request parameter. This lab pokes at those knobs and observes the effect on the output distribution.

Objectives

By the end of this session you should be able to:

  1. Start a local LLM server with llama.cpp and query its completion endpoint over HTTP.
  2. Read the sampling configuration returned by the server and identify the parameters that shape next-token selection.
  3. Inspect the next-token distribution using log-probabilities and the top-k alternatives.
  4. Explain and demonstrate the three classic sampling controls — temperature, top_p (nucleus) and top_k — and predict how each reshapes the probability distribution.
  5. Measure inference latency and relate the sampling parameters to per-token timing.

Run

# curl
curl -LsSf https://llama.app/install.sh | sh
 
# powershell
irm https://llama.app/install.ps1 | iex
 
# start
llama serve -hf unsloth/Qwen3-4B-Instruct-2507-GGUF:Q5_K_M

Default parameters

A completion request without extra arguments runs with the full default configuration below. Do not memorise it — focus on the handful of parameters this lab varies:

The sampling pipeline, in order

logits → temperature (reshape) → top_k (cut to k tokens) → top_p / min_p / typical_p (cut the tail) → softmax → sample. The remaining parameters cover reproducibility (seed), repetition control (repeat_penalty, penalties), structured output (grammar) and streaming (stream).

ParameterValue
seed4294967295
temperature0.800000011920929
dynatemp_range0.0
dynatemp_exponent1.0
top_k40
top_p0.949999988079071
min_p0.05000000074505806
top_n_sigma-1.0
xtc_probability0.0
xtc_threshold0.10000000149011612
typical_p1.0
repeat_last_n64
repeat_penalty1.0
presence_penalty0.0
frequency_penalty0.0
dry_multiplier0.0
dry_base1.75
dry_allowed_length2
dry_penalty_last_n4096
dry_sequence_breakers['\n', ':', '"', '*']
mirostat0
mirostat_tau5.0
mirostat_eta0.10000000149011612
stop[]
max_tokens1
n_predict1
n_keep0
n_discard0
ignore_eosFalse
streamFalse
logit_bias[]
n_probs12
min_keep0
grammar''
grammar_lazyFalse
grammar_triggers[]
preserved_tokens[]
chat_format'Content-only'
reasoning_format'deepseek'
reasoning_in_contentFalse
thinking_forced_openFalse

Next-token probabilities

Ask the server for a single token (n_predict: 1) together with the top 12 alternatives (n_probs: 12). Each alternative comes as a log-probability, converted to a percentage with math.exp(logprob); the cumulative column shows how much probability mass the alternatives cover.

With temperature: 0.0 the server always picks the most likely token — greedy decoding — so Selected shows what the model considers the single best answer, independent of the sampling knobs below. The remaining 11 alternatives are exactly the candidates that top_k / top_p would keep or cut.

%pip install -q requests tqdm matplotlib ipykernel
import requests
import math
 
model = "unsloth/Qwen3-4B-Instruct-2507-GGUF:Q5_K_M"
prompt = "The sky color is? Output just the color name:"
url = 'http://localhost:8080/completion'
 
headers = {"Content-Type": "application/json"}
data = {"model": model, "prompt": prompt, 
    "n_predict": 1, "n_probs": 12, "temperature" : 0.0, "num_treads": 4}
 
result = requests.post(url, headers=headers, json=data)
if result.status_code != 200:
    print('error:', result.status_code)
else:
    response = result.json()
    acc = []
    print('Selected:', response['completion_probabilities'][0]['token'])
    print()
 
    print('--- Alternatives   %    TOTAL ---')
    for item in response['completion_probabilities'][0]['top_logprobs']:
        probability = math.exp(item['logprob']) * 100
        acc.append(probability)
        print(f'* {item["token"].strip():10} {probability:6.2f} % | {sum(acc):5.1f} %')

Temperature parameter effect

Temperature reshapes the distribution before any cutoff: each logit is divided by and passed through the softmax, . Lower values sharpen the distribution towards the most likely token, higher values flatten it and increase variety — at sampling degenerates into greedy decoding, at into a uniform draw. Sampling 100 times at the default temperature: 0.8 shows the empirical frequency of the selected color.

import requests
from matplotlib import pyplot as plt
from tqdm import tqdm
 
temperature = 0.8  # default 0.8
 
def get_next_word(temperature):
    
    url = 'http://localhost:8080/completion'
    headers = {"Content-Type": "application/json"}
    data = {"model": model, "prompt": prompt, 
        "n_predict": 1, "temperature":temperature, 'top_p': 0.99, 'min_p': 0.001 }
 
    result = requests.post(url, headers=headers, json=data)
    if result.status_code == 200:
        response = result.json()
    else:
        raise ValueError('Error getting data')
    
    return response['content']
 
 
predict_word = []
for n in tqdm(range(100)):
    predict_word.append(get_next_word(temperature).strip())
 
 
plt.figure(figsize=(10,4))
plt.hist(predict_word)
plt.title(f'Frequency distribution of next letter [temperature={temperature}]')
plt.xlabel('Selected color')
plt.ylabel('Freq [%]')
plt.show()

top_p effect

Nucleus sampling keeps only the most likely tokens whose cumulative probability reaches top_p, cutting the long tail of unlikely options. The cut is dynamic: a confident model keeps few tokens, an uncertain one keeps many — unlike top_k, which always keeps a fixed count. Here top_p: 0.95 discards the candidates that together hold the last 5% of the probability mass.

import requests
from matplotlib import pyplot as plt
from tqdm import tqdm
 
top_p = 0.95  # default 0.95
 
def get_next_word():
    url = 'http://localhost:8080/completion'
    headers = {"Content-Type": "application/json"}
    data = {"model": model, "prompt": prompt, 
        "n_predict": 1,  "top_p": top_p, 'min_p': 0.001}
 
    result = requests.post(url, headers=headers, json=data)
    if result.status_code == 200:
        response = result.json()
    else:
        raise ValueError('Error getting data')
    
    return response['content']
 
 
predict_word = []
for n in tqdm(range(100)):
    predict_word.append(get_next_word())
 
 
 
plt.hist(predict_word)
plt.title(f'Frequency distribution of next letter [top_p={top_p}]');

top_k effect

Top-k keeps only the k most likely tokens, whatever their absolute probabilities. With temperature: 2.0 the distribution is very flat, so many tokens carry similar probability — exactly the situation where top_k visibly limits how wild the sampler can get. Note the request also relaxes the other filters (top_p: 0.999, min_p: 0.001) so that top_k is the dominant control.

import requests
from matplotlib import pyplot as plt
from tqdm import tqdm
 
top_k = 40  # default 40
 
def get_next_word():
    url = 'http://localhost:8080/completion'
    headers = {"Content-Type": "application/json"}
    data = {"model": model, "prompt":prompt, 
        "n_predict": 1, "top_k": top_k, "top_p": 0.999, 'min_p': 0.001, 'temperature': 2.0 }
 
    result = requests.post(url, headers=headers, json=data)
    if result.status_code == 200:
        response = result.json()
    else:
        raise ValueError('Error getting data')
    
    return response['content']
 
 
predict_word = []
for n in tqdm(range(100)):
    predict_word.append(get_next_word())
 
 
plt.figure(figsize=(12,6))
plt.hist(predict_word)
plt.title(f'Frequency distribution of next letter [top_k={top_k}]');

top_k timings

Comparing prediction latency between two top_k settings, with the mean marked in red:

Expect a difference?

top_k only filters the candidate list before sampling — a cheap truncation, not extra matrix multiplications — so the per-token latency (predicted_per_token_ms) should stay essentially unchanged between the two settings. If the red mean lines differ noticeably, the variation comes from measurement noise and machine load, not from the sampler.

import requests
from matplotlib import pyplot as plt
from statistics import mean
from tqdm import tqdm
 
top_k1 = 2 
top_k2 = 8
 
def get_timings(top_k):
    url = 'http://localhost:8080/completion'
    headers = {"Content-Type": "application/json"}
    data = {"model": model, "prompt": prompt, 
        "n_predict": top_k, "top_k": top_k }
 
    result = requests.post(url, headers=headers, json=data)
    if result.status_code == 200:
        response = result.json()
    else:
        raise ValueError('Error getting data')
    
    return response['timings']['predicted_per_token_ms']
 
 
plt.figure(figsize=(16,6))
plt.subplot(121)
timings= []
for n in tqdm(range(100)):
    timings.append(get_timings(top_k=top_k1))
plt.hist(timings)
plt.title(f'Predict token timings [top_k={top_k1}] total={sum(timings):.1f}')
plt.xlabel('mSec')
plt.ylabel('Freq')
plt.axvline(mean(timings), color='red', linewidth=3)
 
plt.subplot(122)
timings= []
for n in tqdm(range(100)):
    timings.append(get_timings(top_k=top_k2))
plt.hist(timings)
plt.title(f'Predict token timings [top_k={top_k2}] total={sum(timings):.1f}')
plt.xlabel('mSec')
plt.ylabel('Freq')
plt.axvline(mean(timings), color='red', linewidth=3)
plt.tight_layout()
plt.show()